Imported from ../lua-3.0.tar.gz.
[lua.git] / src / lua.stx
blob3a1bf62c7f96799e9c9ee286e641715a2abd2599
1 %{
3 char *rcs_luastx = "$Id: lua.stx,v 3.47 1997/06/19 17:46:12 roberto Exp $";
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #include "luadebug.h"
10 #include "luamem.h"
11 #include "lex.h"
12 #include "opcode.h"
13 #include "hash.h"
14 #include "inout.h"
15 #include "tree.h"
16 #include "table.h"
17 #include "lua.h"
18 #include "func.h"
20 /* to avoid warnings generated by yacc */
21 int yyparse (void);
22 #define malloc luaI_malloc
23 #define realloc luaI_realloc
24 #define free luaI_free
26 #ifndef LISTING
27 #define LISTING 0
28 #endif
30 #ifndef CODE_BLOCK
31 #define CODE_BLOCK 256
32 #endif
33 static int   maxcode;
34 static int   maxmain;
35 static int   maxcurr;
36 static Byte  *funcCode = NULL;
37 static Byte **initcode;
38 static Byte  *basepc;
39 static int   maincode;
40 static int   pc;
43 #define MAXVAR 32
44 static Long    varbuffer[MAXVAR];    /* variables in an assignment list;
45                                 it's long to store negative Word values */
46 static int     nvarbuffer=0;         /* number of variables at a list */
48 #define MAXLOCALS 32
49 static TaggedString *localvar[MAXLOCALS];  /* store local variable names */
50 static int     nlocalvar=0;          /* number of local variables */
52 #define MAXFIELDS FIELDS_PER_FLUSH*2
54 int lua_debug = 0;
56 /* Internal functions */
58 static void yyerror (char *s)
60   luaI_syntaxerror(s);
63 static void check_space (int i)
65   if (pc+i>maxcurr-1)  /* 1 byte free to code HALT of main code */
66     maxcurr = growvector(&basepc, maxcurr, Byte, codeEM, MAX_INT);
69 static void code_byte (Byte c)
71  check_space(1);
72  basepc[pc++] = c;
75 static void code_word (Word n)
77   check_space(sizeof(Word));
78   memcpy(basepc+pc, &n, sizeof(Word));
79   pc += sizeof(Word);
82 static void code_float (real n)
84   check_space(sizeof(real));
85   memcpy(basepc+pc, &n, sizeof(real));
86   pc += sizeof(real);
89 static void code_code (TFunc *tf)
91   check_space(sizeof(TFunc *));
92   memcpy(basepc+pc, &tf, sizeof(TFunc *));
93   pc += sizeof(TFunc *);
96 static void code_word_at (Byte *p, int n)
98   Word w = n;
99   if (w != n)
100     yyerror("block too big");
101   memcpy(p, &w, sizeof(Word));
104 static void flush_record (int n)
106   if (n == 0) return;
107   code_byte(STOREMAP);
108   code_byte(n);
111 static void flush_list (int m, int n)
113   if (n == 0) return;
114   if (m == 0)
115     code_byte(STORELIST0); 
116   else
117   if (m < 255)
118   {
119     code_byte(STORELIST);
120     code_byte(m);
121   }
122   else
123    yyerror ("list constructor too long");
124   code_byte(n);
127 static void store_localvar (TaggedString *name, int n)
129  if (nlocalvar+n < MAXLOCALS)
130   localvar[nlocalvar+n] = name;
131  else
132   yyerror ("too many local variables");
133  if (lua_debug)
134    luaI_registerlocalvar(name, lua_linenumber);
137 static void add_localvar (TaggedString *name)
139   store_localvar(name, 0);
140   nlocalvar++;
143 static void add_varbuffer (Long var)
145  if (nvarbuffer < MAXVAR)
146   varbuffer[nvarbuffer++] = var;
147  else
148   yyerror ("variable buffer overflow");
151 static void code_string (Word w)
153   code_byte(PUSHSTRING);
154   code_word(w);
157 static void code_constant (TaggedString *s)
159   code_string(luaI_findconstant(s));
162 static void code_number (float f)
164   Word i;
165   if (f >= 0 && f <= (float)MAX_WORD && (float)(i=(Word)f) == f) {
166    /* f has an (short) integer value */
167    if (i <= 2) code_byte(PUSH0 + i);
168    else if (i <= 255)
169    {
170     code_byte(PUSHBYTE);
171     code_byte(i);
172    }
173    else
174    {
175     code_byte(PUSHWORD);
176     code_word(i);
177    }
178   }
179   else
180   {
181    code_byte(PUSHFLOAT);
182    code_float(f);
183   }
187 ** Search a local name and if find return its index. If do not find return -1
189 static int lua_localname (TaggedString *n)
191  int i;
192  for (i=nlocalvar-1; i >= 0; i--)
193   if (n == localvar[i]) return i;       /* local var */
194  return -1;                     /* global var */
198 ** Push a variable given a number. If number is positive, push global variable
199 ** indexed by (number -1). If negative, push local indexed by ABS(number)-1.
200 ** Otherwise, if zero, push indexed variable (record).
202 static void lua_pushvar (Long number)
204  if (number > 0)        /* global var */
206   code_byte(PUSHGLOBAL);
207   code_word(number-1);
209  else if (number < 0)   /* local var */
211   number = (-number) - 1;
212   if (number < 10) code_byte(PUSHLOCAL0 + number);
213   else
214   {
215    code_byte(PUSHLOCAL);
216    code_byte(number);
217   }
219  else
221   code_byte(PUSHINDEXED);
225 static void lua_codeadjust (int n)
227  if (n+nlocalvar == 0)
228    code_byte(ADJUST0);
229  else
231    code_byte(ADJUST);
232    code_byte(n+nlocalvar);
236 static void change2main (void)
238   /* (re)store main values */
239   pc=maincode; basepc=*initcode; maxcurr=maxmain;
240   nlocalvar=0;
243 static void savemain (void)
245   /* save main values */
246   maincode=pc; *initcode=basepc; maxmain=maxcurr;
249 static void init_func (void)
251   if (funcCode == NULL) /* first function */
252   {
253    funcCode = newvector(CODE_BLOCK, Byte);
254    maxcode = CODE_BLOCK;
255   }
256   savemain();  /* save main values */
257   /* set func values */
258   pc=0; basepc=funcCode; maxcurr=maxcode; 
259   nlocalvar = 0;
260   luaI_codedebugline(lua_linenumber);
263 static void codereturn (void)
265   if (nlocalvar == 0)
266     code_byte(RETCODE0);
267   else
268   {
269     code_byte(RETCODE);
270     code_byte(nlocalvar);
271   }
274 void luaI_codedebugline (int line)
276   static int lastline = 0;
277   if (lua_debug && line != lastline)
278   {
279     code_byte(SETLINE);
280     code_word(line);
281     lastline = line;
282   }
285 static int adjust_functioncall (Long exp, int i)
287   if (exp <= 0)
288     return -exp; /* exp is -list length */
289   else
290   {
291     int temp = basepc[exp];
292     basepc[exp] = i;
293     return temp+i;
294   }
297 static void adjust_mult_assign (int vars, Long exps, int temps)
299   if (exps > 0)
300   { /* must correct function call */
301     int diff = vars - basepc[exps];
302     if (diff >= 0)
303       adjust_functioncall(exps, diff);
304     else
305     {
306       adjust_functioncall(exps, 0);
307       lua_codeadjust(temps);
308     }
309   }
310   else if (vars != -exps)
311     lua_codeadjust(temps);
314 static int close_parlist (int dots)
316   if (!dots)
317     lua_codeadjust(0);
318   else
319   {
320     code_byte(VARARGS);
321     code_byte(nlocalvar);
322     add_localvar(luaI_createfixedstring("arg"));
323   }
324   return lua_linenumber;
327 static void storesinglevar (Long v)
329  if (v > 0)             /* global var */
331    code_byte(STOREGLOBAL);
332    code_word(v-1);
334  else if (v < 0)      /* local var */
336    int number = (-v) - 1;
337    if (number < 10) code_byte(STORELOCAL0 + number);
338    else
339    {
340      code_byte(STORELOCAL);
341      code_byte(number);
342    }
344  else 
345    code_byte(STOREINDEXED0);
348 static void lua_codestore (int i)
350  if (varbuffer[i] != 0)  /* global or local var */
351   storesinglevar(varbuffer[i]);
352  else                             /* indexed var */
354   int j;
355   int upper=0;          /* number of indexed variables upper */
356   int param;            /* number of itens until indexed expression */
357   for (j=i+1; j <nvarbuffer; j++)
358    if (varbuffer[j] == 0) upper++;
359   param = upper*2 + i;
360   if (param == 0)
361    code_byte(STOREINDEXED0);
362   else
363   {
364    code_byte(STOREINDEXED);
365    code_byte(param);
366   }
370 static void codeIf (Long thenAdd, Long elseAdd)
372   Long elseinit = elseAdd+sizeof(Word)+1;
373   if (pc == elseinit)           /* no else */
374   {
375     pc -= sizeof(Word)+1;
376     elseinit = pc;
377   }
378   else
379   {
380     basepc[elseAdd] = JMP;
381     code_word_at(basepc+elseAdd+1, pc-elseinit);
382   }
383   basepc[thenAdd] = IFFJMP;
384   code_word_at(basepc+thenAdd+1,elseinit-(thenAdd+sizeof(Word)+1));
389 ** Parse LUA code.
391 void lua_parse (TFunc *tf)
393  initcode = &(tf->code);
394  *initcode = newvector(CODE_BLOCK, Byte);
395  maincode = 0; 
396  maxmain = CODE_BLOCK;
397  change2main();
398  if (yyparse ()) lua_error("parse error");
399  savemain();
400  (*initcode)[maincode++] = RETCODE0;
401  tf->size = maincode;
402 #if LISTING
403 { static void PrintCode (Byte *c, Byte *end);
404  PrintCode(*initcode,*initcode+maincode); }
405 #endif
412 %union 
414  int   vInt;
415  float vFloat;
416  char *pChar;
417  Word  vWord;
418  Long  vLong;
419  TFunc *pFunc;
420  TaggedString *pTStr;
423 %start chunk
425 %token WRONGTOKEN
426 %token NIL
427 %token IF THEN ELSE ELSEIF WHILE DO REPEAT UNTIL END
428 %token RETURN
429 %token LOCAL
430 %token FUNCTION
431 %token DOTS
432 %token <vFloat> NUMBER
433 %token <vWord>  STRING
434 %token <pTStr>  NAME 
436 %type <vLong> PrepJump
437 %type <vLong> exprlist, exprlist1  /* if > 0, points to function return
438         counter (which has list length); if <= 0, -list lenght */
439 %type <vLong> functioncall, expr  /* if != 0, points to function return
440                                          counter */
441 %type <vInt>  varlist1, funcParams, funcvalue
442 %type <vInt>  fieldlist, localdeclist, decinit
443 %type <vInt>  ffieldlist, ffieldlist1, semicolonpart
444 %type <vInt>  lfieldlist, lfieldlist1
445 %type <vInt>  parlist, parlist1, par
446 %type <vLong> var, singlevar, funcname
447 %type <pFunc> body
449 %left AND OR
450 %left EQ NE '>' '<' LE GE
451 %left CONC
452 %left '+' '-'
453 %left '*' '/'
454 %left UNARY NOT
455 %right '^'
458 %% /* beginning of rules section */
460 chunk   : chunklist ret ;
462 chunklist : /* empty */
463           | chunklist stat sc
464           | chunklist function
465           ;
467 function     : FUNCTION funcname body    
468                { 
469                 code_byte(PUSHFUNCTION);
470                 code_code($3);
471                 storesinglevar($2);
472                }
473                ;
475 funcname        : var { $$ =$1; init_func(); }
476                 | varexp ':' NAME
477         {
478           code_constant($3);
479           $$ = 0;  /* indexed variable */
480           init_func();
481           add_localvar(luaI_createfixedstring("self"));
482         }
483                 ;
485 body :  '(' parlist ')' block END
486         {
487           codereturn();
488           $$ = new(TFunc);
489           luaI_initTFunc($$);
490           $$->size = pc;
491           $$->code = newvector(pc, Byte);
492           $$->lineDefined = $2;
493           memcpy($$->code, basepc, pc*sizeof(Byte));
494           if (lua_debug)
495             luaI_closelocalvars($$);
496           /* save func values */
497           funcCode = basepc; maxcode=maxcurr;
498 #if LISTING
499                 PrintCode(funcCode,funcCode+pc);
500 #endif
501           change2main();  /* change back to main code */
502         }
503                 ;
505 statlist : /* empty */
506          | statlist stat sc
507          ;
509 sc       : /* empty */ | ';' ;
511 stat   : IF expr1 THEN PrepJump block PrepJump elsepart END
512         { codeIf($4, $6); }
514        | WHILE {$<vLong>$=pc;} expr1 DO PrepJump block PrepJump END
515        {
516         basepc[$5] = IFFJMP;
517         code_word_at(basepc+$5+1, pc - ($5 + sizeof(Word)+1));
518         basepc[$7] = UPJMP;
519         code_word_at(basepc+$7+1, pc - ($<vLong>2));
520        }
521      
522        | REPEAT {$<vLong>$=pc;} block UNTIL expr1 PrepJump
523        {
524         basepc[$6] = IFFUPJMP;
525         code_word_at(basepc+$6+1, pc - ($<vLong>2));
526        }
528        | varlist1 '=' exprlist1
529        {
530         {
531          int i;
532          adjust_mult_assign(nvarbuffer, $3, $1 * 2 + nvarbuffer);
533          for (i=nvarbuffer-1; i>=0; i--)
534           lua_codestore (i);
535          if ($1 > 1 || ($1 == 1 && varbuffer[0] != 0))
536           lua_codeadjust (0);
537         }
538        } 
539        | functioncall {;}
540        | LOCAL localdeclist decinit
541         { nlocalvar += $2;
542           adjust_mult_assign($2, $3, 0);
543         }
544        ;
546 elsepart : /* empty */
547          | ELSE block
548          | ELSEIF expr1 THEN PrepJump block PrepJump elsepart
549         { codeIf($4, $6); }
550          ;
551      
552 block    : {$<vInt>$ = nlocalvar;} statlist ret 
553          {
554           if (nlocalvar != $<vInt>1)
555           {
556            if (lua_debug)
557              for (; nlocalvar > $<vInt>1; nlocalvar--)
558                luaI_unregisterlocalvar(lua_linenumber);
559            else
560              nlocalvar = $<vInt>1;
561            lua_codeadjust (0);
562           }
563          }
564          ;
566 ret     : /* empty */
567         | RETURN exprlist sc
568           {
569            adjust_functioncall($2, MULT_RET);
570            codereturn();
571           }
572         ;
574 PrepJump : /* empty */
575          { 
576           $$ = pc;
577           code_byte(0);         /* open space */
578           code_word (0);
579          }
580          ;
581            
582 expr1    : expr { adjust_functioncall($1, 1); }
583          ;
584                                 
585 expr :  '(' expr ')'  { $$ = $2; }
586      |  expr1 EQ  expr1 { code_byte(EQOP);   $$ = 0; }
587      |  expr1 '<' expr1 { code_byte(LTOP);   $$ = 0; }
588      |  expr1 '>' expr1 { code_byte(GTOP);   $$ = 0; }
589      |  expr1 NE  expr1 { code_byte(EQOP); code_byte(NOTOP); $$ = 0; }
590      |  expr1 LE  expr1 { code_byte(LEOP);   $$ = 0; }
591      |  expr1 GE  expr1 { code_byte(GEOP);   $$ = 0; }
592      |  expr1 '+' expr1 { code_byte(ADDOP);  $$ = 0; }
593      |  expr1 '-' expr1 { code_byte(SUBOP);  $$ = 0; }
594      |  expr1 '*' expr1 { code_byte(MULTOP); $$ = 0; }
595      |  expr1 '/' expr1 { code_byte(DIVOP);  $$ = 0; }
596      |  expr1 '^' expr1 { code_byte(POWOP);  $$ = 0; }
597      |  expr1 CONC expr1 { code_byte(CONCOP);  $$ = 0; }
598      |  '-' expr1 %prec UNARY   { code_byte(MINUSOP); $$ = 0;}
599      | table { $$ = 0; }
600      |  varexp          { $$ = 0;}
601      |  NUMBER          { code_number($1); $$ = 0; }
602      |  STRING
603      {
604        code_string($1);
605        $$ = 0;
606      }
607      |  NIL             {code_byte(PUSHNIL); $$ = 0; }
608      |  functioncall    { $$ = $1; }
609      |  NOT expr1       { code_byte(NOTOP);  $$ = 0;}
610      |  expr1 AND PrepJump {code_byte(POP); } expr1
611      { 
612       basepc[$3] = ONFJMP;
613       code_word_at(basepc+$3+1, pc - ($3 + sizeof(Word)+1));
614       $$ = 0;
615      }
616      |  expr1 OR PrepJump {code_byte(POP); } expr1      
617      { 
618       basepc[$3] = ONTJMP;
619       code_word_at(basepc+$3+1, pc - ($3 + sizeof(Word)+1));
620       $$ = 0;
621      }
622      ;
624 table :
625      {
626       code_byte(CREATEARRAY);
627       $<vLong>$ = pc; code_word(0);
628      }
629       '{' fieldlist '}'
630      {
631       code_word_at(basepc+$<vLong>1, $3);
632      }
633          ;
635 functioncall : funcvalue funcParams
636         {
637           code_byte(CALLFUNC);
638           code_byte($1+$2);
639           $$ = pc;
640           code_byte(0);  /* may be modified by other rules */
641         }
642              ;
644 funcvalue    : varexp { $$ = 0; }
645              | varexp ':' NAME 
646              { 
647                code_byte(PUSHSELF); 
648                code_word(luaI_findconstant($3));
649                $$ = 1;
650              }
651              ;
653 funcParams :    '(' exprlist ')'
654         { $$ = adjust_functioncall($2, 1); }
655         |       table  { $$ = 1; }
656         ;
658 exprlist  :     /* empty */             { $$ = 0; }
659           |     exprlist1               { $$ = $1; }
660           ;
661                 
662 exprlist1 :  expr       { if ($1 != 0) $$ = $1; else $$ = -1; }
663           |  exprlist1 ',' { $<vLong>$ = adjust_functioncall($1, 1); } expr 
664         {
665           if ($4 == 0) $$ = -($<vLong>3 + 1);  /* -length */
666           else
667           {
668             adjust_functioncall($4, $<vLong>3);
669             $$ = $4;
670           }
671         }
672           ;
674 parlist  :      /* empty */ { $$ = close_parlist(0); }
675           |     parlist1    { $$ = close_parlist($1); }
676           ;
677                 
678 parlist1 :      par               { $$ = $1; }
679           |     parlist1 ',' par
680         {
681           if ($1)
682             lua_error("invalid parameter list");
683           $$ = $3;
684         }
685           ;
687 par : NAME      { add_localvar($1); $$ = 0; }
688     | DOTS      { $$ = 1; }
689     ;
690                 
691 fieldlist  : lfieldlist
692              { flush_list($1/FIELDS_PER_FLUSH, $1%FIELDS_PER_FLUSH); }
693              semicolonpart
694              { $$ = $1+$3; }
695            | ffieldlist1 lastcomma
696              { $$ = $1; flush_record($1%FIELDS_PER_FLUSH); }
697            ;
699 semicolonpart : /* empty */
700                 { $$ = 0; }
701               | ';' ffieldlist
702                 { $$ = $2; flush_record($2%FIELDS_PER_FLUSH); }
703               ;
705 lastcomma  : /* empty */ 
706            | ','
707            ;
709 ffieldlist  : /* empty */ { $$ = 0; }
710             | ffieldlist1 lastcomma { $$ = $1; }
711             ;   
713 ffieldlist1 : ffield                    {$$=1;}
714            | ffieldlist1 ',' ffield     
715                 {
716                   $$=$1+1;
717                   if ($$%FIELDS_PER_FLUSH == 0) flush_record(FIELDS_PER_FLUSH);
718                 }
719            ; 
721 ffield      : ffieldkey '=' expr1
722            ;
724 ffieldkey   : '[' expr1 ']'
725             | NAME { code_constant($1); }
726             ;
728 lfieldlist  : /* empty */ { $$ = 0; }
729             | lfieldlist1 lastcomma { $$ = $1; }
730             ;
732 lfieldlist1 : expr1  {$$=1;}
733             | lfieldlist1 ',' expr1
734                 {
735                   $$=$1+1;
736                   if ($$%FIELDS_PER_FLUSH == 0) 
737                     flush_list($$/FIELDS_PER_FLUSH - 1, FIELDS_PER_FLUSH);
738                 }
739             ;
741 varlist1  :     var                     
742           {
743            nvarbuffer = 0; 
744            add_varbuffer($1);
745            $$ = ($1 == 0) ? 1 : 0;
746           }
747           |     varlist1 ',' var        
748           { 
749            add_varbuffer($3);
750            $$ = ($3 == 0) ? $1 + 1 : $1;
751           }
752           ;
753                 
754 var       :     singlevar { $$ = $1; }
755           |     varexp '[' expr1 ']' 
756           {
757            $$ = 0;              /* indexed variable */
758           }
759           |     varexp '.' NAME
760           {
761             code_constant($3);
762             $$ = 0;             /* indexed variable */
763           }
764           ;
765                 
766 singlevar :     NAME
767           {
768            int local = lua_localname($1);
769            if (local == -1)     /* global var */
770             $$ = luaI_findsymbol($1)+1;  /* return positive value */
771            else
772             $$ = -(local+1);            /* return negative value */
773           }
774           ;
776 varexp  : var { lua_pushvar($1); }
777         ;
778           
779 localdeclist  : NAME {store_localvar($1, 0); $$ = 1;}
780           | localdeclist ',' NAME 
781             {
782              store_localvar($3, $1);
783              $$ = $1+1;
784             }
785           ;
786                 
787 decinit   : /* empty */  { $$ = 0; }
788           | '=' exprlist1 { $$ = $2; }
789           ;
790