implemented interfaces
[swftools.git] / lib / as3 / parser.y
1 /* parser.lex
2
3    Routines for compiling Flash2 AVM2 ABC Actionscript
4
5    Extension module for the rfxswf library.
6    Part of the swftools package.
7
8    Copyright (c) 2008 Matthias Kramm <kramm@quiss.org>
9  
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
23 %{
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <memory.h>
27 #include "abc.h"
28 #include "pool.h"
29 #include "files.h"
30 #include "tokenizer.h"
31 #include "registry.h"
32 #include "code.h"
33 #include "opcodes.h"
34
35 %}
36
37 //%glr-parser
38 //%expect-rr 1
39 %error-verbose
40
41 %union tokenunion {
42     enum yytokentype token;
43     int flags;
44
45     classinfo_t*classinfo;
46     classinfo_list_t*classinfo_list;
47
48     int number_int;
49     unsigned int number_uint;
50     double number_float;
51     code_t*code;
52     typedcode_t value;
53     typedcode_list_t*value_list;
54     param_t* param;
55     params_t params;
56     string_t str;
57     char*id;
58     constant_t*constant;
59 }
60
61
62 %token<id> T_IDENTIFIER
63 %token<str> T_STRING
64 %token<token> T_REGEXP
65 %token<token> T_EMPTY
66 %token<number_int> T_INT
67 %token<number_uint> T_UINT
68 %token<number_uint> T_BYTE
69 %token<number_uint> T_SHORT
70 %token<number_float> T_FLOAT
71
72 %token<token> KW_IMPLEMENTS
73 %token<token> KW_NAMESPACE "namespace"
74 %token<token> KW_PACKAGE "package"
75 %token<token> KW_PROTECTED
76 %token<token> KW_PUBLIC
77 %token<token> KW_PRIVATE
78 %token<token> KW_USE "use"
79 %token<token> KW_INTERNAL
80 %token<token> KW_NEW "new"
81 %token<token> KW_NATIVE
82 %token<token> KW_FUNCTION "function"
83 %token<token> KW_FOR "for"
84 %token<token> KW_CLASS "class"
85 %token<token> KW_CONST "const"
86 %token<token> KW_SET "set"
87 %token<token> KW_STATIC
88 %token<token> KW_IMPORT "import"
89 %token<token> KW_RETURN "return"
90 %token<token> KW_INTERFACE "interface"
91 %token<token> KW_NULL "null"
92 %token<token> KW_VAR "var"
93 %token<token> KW_DYNAMIC
94 %token<token> KW_OVERRIDE
95 %token<token> KW_FINAL
96 %token<token> KW_GET "get"
97 %token<token> KW_EXTENDS
98 %token<token> KW_FALSE "false"
99 %token<token> KW_TRUE "true"
100 %token<token> KW_BOOLEAN "Boolean"
101 %token<token> KW_UINT "uint"
102 %token<token> KW_INT "int"
103 %token<token> KW_WHILE "while"
104 %token<token> KW_NUMBER "Number"
105 %token<token> KW_STRING "String"
106 %token<token> KW_IF "if"
107 %token<token> KW_ELSE  "else"
108 %token<token> KW_BREAK   "break"
109 %token<token> KW_IS "is"
110 %token<token> KW_AS "as"
111
112 %token<token> T_EQEQ "=="
113 %token<token> T_EQEQEQ "==="
114 %token<token> T_NE "!="
115 %token<token> T_LE "<="
116 %token<token> T_GE ">="
117 %token<token> T_DIVBY "/=" 
118 %token<token> T_MODBY "%="
119 %token<token> T_MULBY "*="
120 %token<token> T_PLUSBY "+=" 
121 %token<token> T_MINUSBY "-="
122 %token<token> T_SHRBY ">>="
123 %token<token> T_SHLBY "<<="
124 %token<token> T_USHRBY ">>>="
125 %token<token> T_OROR "||"
126 %token<token> T_ANDAND "&&"
127 %token<token> T_COLONCOLON "::"
128 %token<token> T_MINUSMINUS "--"
129 %token<token> T_PLUSPLUS "++"
130 %token<token> T_DOTDOT ".."
131 %token<token> T_DOTDOTDOT "..."
132 %token<token> T_SHL "<<"
133 %token<token> T_USHR ">>>"
134 %token<token> T_SHR ">>"
135 %token<token> T_SEMICOLON ';'
136 %token<token> T_STAR '*'
137 %token<token> T_DOT '.'
138
139 %type <id> X_IDENTIFIER PACKAGE
140 %type <token> VARCONST
141 %type <code> CODE
142 %type <code> CODEPIECE
143 %type <code> CODEBLOCK MAYBECODE
144 %type <token> PACKAGE_DECLARATION
145 %type <token> FUNCTION_DECLARATION
146 %type <code> VARIABLE_DECLARATION ONE_VARIABLE VARIABLE_LIST
147 %type <token> CLASS_DECLARATION
148 %type <token> NAMESPACE_DECLARATION
149 %type <token> INTERFACE_DECLARATION
150 %type <code> VOIDEXPRESSION
151 %type <value> EXPRESSION NONCOMMAEXPRESSION
152 %type <value> MAYBEEXPRESSION
153 %type <value> E
154 %type <value> CONSTANT
155 %type <code> FOR IF WHILE MAYBEELSE BREAK RETURN
156 %type <token> USE_NAMESPACE
157 %type <code> FOR_INIT
158 %type <token> IMPORT
159 %type <classinfo> MAYBETYPE
160 %type <token> GETSET
161 %type <param> PARAM
162 %type <params> PARAM_LIST
163 %type <params> MAYBE_PARAM_LIST
164 %type <flags> MAYBE_MODIFIERS
165 %type <flags> MODIFIER_LIST
166 %type <constant> STATICCONSTANT MAYBESTATICCONSTANT
167 %type <classinfo_list> IMPLEMENTS_LIST
168 %type <classinfo> EXTENDS
169 %type <classinfo_list> EXTENDS_LIST
170 %type <classinfo> CLASS PACKAGEANDCLASS QNAME
171 %type <classinfo_list> QNAME_LIST
172 %type <classinfo> TYPE
173 %type <token> VAR
174 //%type <token> VARIABLE
175 %type <value> VAR_READ
176 %type <value> NEW
177 //%type <token> T_IDENTIFIER
178 %type <token> MODIFIER
179 %type <value> FUNCTIONCALL
180 %type <value_list> MAYBE_EXPRESSION_LIST EXPRESSION_LIST MAYBE_PARAM_VALUES
181
182 // precedence: from low to high
183 // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000012.html
184
185 %left prec_none
186 %right '?' ':'
187 %right '=' "/=" "%=" "*=" "+=" "-=" ">>=" "<<=" ">>>="
188 %left "||"
189 %left "&&"
190 %nonassoc '|'
191 %nonassoc '^'
192 %nonassoc '&'
193 %nonassoc "!=" "==" "===" "<=" '<' ">=" '>' // TODO: support "a < b < c" syntax?
194 %nonassoc "is"
195 %left prec_belowminus
196 %left '-'
197 %left '+'
198 %left "<<"
199 %left ">>>"
200 %left ">>"
201 %left '%'
202 %left '/'
203 %left '*'
204 %left '!'
205 %left '~'
206 %left "--" "++"
207 %left '['
208 %nonassoc "as"
209 %left '.' ".." "::"
210 %nonassoc T_IDENTIFIER
211 %left below_semicolon
212 %left ';'
213 %nonassoc "else"
214 %left '('
215
216 // needed for "return" precedence:
217 %nonassoc T_STRING T_REGEXP
218 %nonassoc T_INT T_UINT T_BYTE T_SHORT T_FLOAT
219 %nonassoc "new" "false" "true" "null"
220
221 %left prec_highest
222
223      
224 %{
225
226 static int yyerror(char*s)
227 {
228    syntaxerror("%s", s); 
229 }
230 static char* concat3str(const char* t1, const char* t2, const char* t3)
231 {
232     int l1 = strlen(t1);
233     int l2 = strlen(t2);
234     int l3 = strlen(t3);
235     char*text = malloc(l1+l2+l3+1);
236     memcpy(text   , t1, l1);
237     memcpy(text+l1, t2, l2);
238     memcpy(text+l1+l2, t3, l3);
239     text[l1+l2+l3] = 0;
240     return text;
241 }
242
243 typedef struct _import {
244     char*package;
245 } import_t;
246
247 DECLARE_LIST(import);
248
249 typedef struct _state {
250     abc_file_t*file;
251     abc_script_t*init;
252
253     int level;
254
255     char*package;     
256     char*function;
257     /* code that needs to be executed at the start of
258        a method (like initializing local registers) */
259     code_t*initcode;
260
261     import_list_t*wildcard_imports;
262     dict_t*imports;
263     char has_own_imports;
264    
265     /* class data */
266     classinfo_t*clsinfo;
267     abc_class_t*cls;
268     code_t*cls_init;
269     code_t*cls_static_init;
270     
271     /* method data */
272     memberinfo_t*minfo;
273     abc_method_t*m;
274
275     dict_t*vars;
276     char late_binding;
277 } state_t;
278
279 typedef struct _global {
280     int variable_count;
281 } global_t;
282
283 static global_t*global = 0;
284 static state_t* state = 0;
285
286 DECLARE_LIST(state);
287
288 #define MULTINAME(m,x) multiname_t m;namespace_t m##_ns;registry_fill_multiname(&m, &m##_ns, x);
289
290 /* warning: list length of namespace set is undefined */
291 #define MULTINAME_LATE(m, access, package) \
292     namespace_t m##_ns = {access, package}; \
293     namespace_set_t m##_nsset; \
294     namespace_list_t m##_l;m##_l.next = 0; \
295     m##_nsset.namespaces = &m##_l; \
296     m##_nsset = m##_nsset; \
297     m##_l.namespace = &m##_ns; \
298     multiname_t m = {MULTINAMEL, 0, &m##_nsset, 0};
299
300 static state_list_t*state_stack=0;
301     
302 static void init_globals()
303 {
304     global = rfx_calloc(sizeof(global_t));
305 }
306
307 static void new_state()
308 {
309     NEW(state_t, s);
310     NEW(state_list_t, sl);
311
312     state_t*oldstate = state;
313     if(state)
314         memcpy(s, state, sizeof(state_t)); //shallow copy
315     sl->next = state_stack;
316     sl->state = s;
317     if(!s->imports) {
318         s->imports = dict_new();
319     }
320     state_stack = sl;
321     state = s;
322     state->level++;
323     state->vars = dict_new();
324     state->initcode = 0;
325     state->has_own_imports = 0;
326 }
327 static void state_has_imports()
328 {
329     state->wildcard_imports = list_clone(state->wildcard_imports);
330     state->imports = dict_clone(state->imports);
331     state->has_own_imports = 1;
332 }
333
334 static void old_state()
335 {
336     if(!state_stack || !state_stack->next)
337         syntaxerror("invalid nesting");
338     state_t*oldstate = state;
339     state_list_t*old = state_stack;
340     state_stack = state_stack->next;
341     free(old);
342     state = state_stack->state;
343     /*if(state->initcode) {
344         printf("residual initcode\n");
345         code_dump(state->initcode, 0, 0, "", stdout);
346     }*/
347     if(oldstate->has_own_imports) {
348         list_free(oldstate->wildcard_imports);
349         dict_destroy(oldstate->imports);oldstate->imports=0;
350     }
351     state->initcode = code_append(state->initcode, oldstate->initcode);
352 }
353 void initialize_state()
354 {
355     init_globals();
356     new_state();
357
358     state->file = abc_file_new();
359     state->file->flags &= ~ABCFILE_LAZY;
360     
361     state->init = abc_initscript(state->file, 0, 0);
362     code_t*c = state->init->method->body->code;
363
364     c = abc_getlocal_0(c);
365     c = abc_pushscope(c);
366   
367     /* findpropstrict doesn't just return a scope object- it
368        also makes it "active" somehow. Push local_0 on the
369        scope stack and read it back with findpropstrict, it'll
370        contain properties like "trace". Trying to find the same
371        property on a "vanilla" local_0 yields only a "undefined" */
372     //c = abc_findpropstrict(c, "[package]::trace");
373     
374     /*c = abc_getlocal_0(c);
375     c = abc_findpropstrict(c, "[package]::trace");
376     c = abc_coerce_a(c);
377     c = abc_setlocal_1(c);
378
379     c = abc_pushbyte(c, 0);
380     c = abc_setlocal_2(c);
381    
382     code_t*xx = c = abc_label(c);
383     c = abc_findpropstrict(c, "[package]::trace");
384     c = abc_pushstring(c, "prop:");
385     c = abc_hasnext2(c, 1, 2);
386     c = abc_dup(c);
387     c = abc_setlocal_3(c);
388     c = abc_callpropvoid(c, "[package]::trace", 2);
389     c = abc_getlocal_3(c);
390     c = abc_kill(c, 3);
391     c = abc_iftrue(c,xx);*/
392
393     c = abc_findpropstrict(c, "[package]::trace");
394     c = abc_pushstring(c, "[entering global init function]");
395     c = abc_callpropvoid(c, "[package]::trace", 1);
396     
397     state->init->method->body->code = c;
398 }
399 void* finalize_state()
400 {
401     if(state->level!=1) {
402         syntaxerror("unexpected end of file");
403     }
404     abc_method_body_t*m = state->init->method->body;
405     //__ popscope(m);
406     
407     __ findpropstrict(m, "[package]::trace");
408     __ pushstring(m, "[leaving global init function]");
409     __ callpropvoid(m, "[package]::trace", 1);
410     __ returnvoid(m);
411     return state->file;
412 }
413
414
415 static void startpackage(char*name)
416 {
417     if(state->package) {
418         syntaxerror("Packages can not be nested."); 
419     } 
420     new_state();
421     /*printf("entering package \"%s\"\n", name);*/
422     state->package = name;
423 }
424 static void endpackage()
425 {
426     /*printf("leaving package \"%s\"\n", state->package);*/
427     old_state();
428 }
429
430 char*globalclass=0;
431 static void startclass(int flags, char*classname, classinfo_t*extends, classinfo_list_t*implements, char interface)
432 {
433     if(state->cls) {
434         syntaxerror("inner classes now allowed"); 
435     }
436     new_state();
437
438     token_list_t*t=0;
439     classinfo_list_t*mlist=0;
440     /*printf("entering class %s\n", name);
441     printf("  modifiers: ");for(t=modifiers->tokens;t;t=t->next) printf("%s ", t->token);printf("\n");
442     if(extends) 
443         printf("  extends: %s.%s\n", extends->package, extends->name);
444     printf("  implements (%d): ", list_length(implements));
445     for(mlist=implements;mlist;mlist=mlist->next)  {
446         printf("%s ", mlist->classinfo?mlist->classinfo->name:0);
447     }
448     printf("\n");
449     */
450
451     if(flags&~(FLAG_INTERNAL|FLAG_PUBLIC|FLAG_FINAL))
452         syntaxerror("invalid modifier(s)");
453
454     if((flags&(FLAG_PUBLIC|FLAG_INTERNAL)) == (FLAG_PUBLIC|FLAG_INTERNAL))
455         syntaxerror("public and internal not supported at the same time.");
456
457     /* create the class name, together with the proper attributes */
458     int access=0;
459     char*package=0;
460
461     if(!(flags&FLAG_PUBLIC) && !state->package) {
462         access = ACCESS_PRIVATE; package = current_filename;
463     } else if(!(flags&FLAG_PUBLIC) && state->package) {
464         access = ACCESS_PACKAGEINTERNAL; package = state->package;
465     } else if(state->package) {
466         access = ACCESS_PACKAGE; package = state->package;
467     } else {
468         syntaxerror("public classes only allowed inside a package");
469     }
470
471     if(registry_findclass(package, classname)) {
472         syntaxerror("Package \"%s\" already contains a class called \"%s\"", package, classname);
473     }
474    
475     /* build info struct */
476     int num_interfaces = (list_length(implements));
477     state->clsinfo = classinfo_register(access, package, classname, num_interfaces);
478     state->clsinfo->superclass = extends;
479     int pos = 0;
480     classinfo_list_t*l = implements;
481     for(l=implements;l;l=l->next) {
482         state->clsinfo->interfaces[pos++] = l->classinfo;
483     }
484
485     MULTINAME(classname2,state->clsinfo);
486     
487     multiname_t*extends2 = sig2mname(extends);
488
489     /*if(extends) {
490         state->cls_init = abc_getlocal_0(state->cls_init);
491         state->cls_init = abc_constructsuper(state->cls_init, 0);
492     }*/
493
494     state->cls = abc_class_new(state->file, &classname2, extends2);
495     if(flags&FLAG_FINAL) abc_class_final(state->cls);
496     if(flags&FLAG_DYNAMIC) abc_class_sealed(state->cls);
497     if(interface) abc_class_interface(state->cls);
498
499     for(mlist=implements;mlist;mlist=mlist->next) {
500         MULTINAME(m, mlist->classinfo);
501         abc_class_add_interface(state->cls, &m);
502     }
503
504     /* now write the construction code for this class */
505     int slotindex = abc_initscript_addClassTrait(state->init, &classname2, state->cls);
506
507     abc_method_body_t*m = state->init->method->body;
508     __ getglobalscope(m);
509     classinfo_t*s = extends;
510
511     int count=0;
512     
513     while(s) {
514         //TODO: take a look at the current scope stack, maybe 
515         //      we can re-use something
516         s = s->superclass;
517         if(!s) 
518         break;
519        
520         multiname_t*s2 = sig2mname(s);
521         __ getlex2(m, s2);
522         multiname_destroy(s2);
523
524         __ pushscope(m); count++;
525         m->code = m->code->prev->prev; // invert
526     }
527     /* continue appending after last op end */
528     while(m->code && m->code->next) m->code = m->code->next; 
529
530     /* TODO: if this is one of *our* classes, we can also 
531              do a getglobalscope/getslot <nr> (which references
532              the init function's slots) */
533     if(extends2) {
534         __ getlex2(m, extends2);
535         __ dup(m);
536         /* notice: we get a Verify Error #1107 if the top elemnt on the scope
537            stack is not the superclass */
538         __ pushscope(m);count++;
539     } else {
540         __ pushnull(m);
541         /* notice: we get a verify error #1107 if the top element on the scope 
542            stack is not the global object */
543         __ getlocal_0(m);
544         __ pushscope(m);count++;
545     }
546     __ newclass(m,state->cls);
547     while(count--) {
548         __ popscope(m);
549     }
550     __ setslot(m, slotindex);
551
552     /* flash.display.MovieClip handling */
553     if(!globalclass && (flags&FLAG_PUBLIC) && classinfo_equals(registry_getMovieClip(),extends)) {
554         if(state->package && state->package[0]) {
555             globalclass = concat3str(state->package, ".", classname);
556         } else {
557             globalclass = strdup(classname);
558         }
559     }
560     multiname_destroy(extends2);
561 }
562
563 static void endclass()
564 {
565     if(state->cls_init) {
566         if(!state->cls->constructor) {
567             abc_method_t*m = abc_class_constructor(state->cls, 0, 0);
568             m->body->code = code_append(m->body->code, state->cls_init);
569             m->body->code = abc_returnvoid(m->body->code);
570         } else {
571             code_t*c = state->cls->constructor->body->code;
572             c = code_append(state->cls_init, c);
573             state->cls->constructor->body->code = c;
574
575         }
576     }
577     if(state->cls_static_init) {
578         if(!state->cls->static_constructor) {
579             abc_method_t*m = abc_class_staticconstructor(state->cls, 0, 0);
580             m->body->code = state->cls_static_init;
581         } else {
582             state->cls->static_constructor->body->code = 
583                 code_append(state->cls_static_init, state->cls->static_constructor->body->code);
584         }
585     }
586
587     old_state();
588 }
589
590 typedef struct _variable {
591     int index;
592     classinfo_t*type;
593 } variable_t;
594
595 static int find_variable(char*name, classinfo_t**m)
596 {
597     state_list_t* s = state_stack;
598     while(s) {
599         variable_t*v = dict_lookup(s->state->vars, name);
600         if(v) {
601             if(m) {
602                 *m = v->type;
603             }
604             return v->index;
605         }
606         s = s->next;
607     }
608     return -1;
609
610 static int find_variable_safe(char*name, classinfo_t**m)
611 {
612     int i = find_variable(name, m);
613     if(i<0)
614         syntaxerror("undefined variable: %s", name);
615     return i;
616 }
617 static char variable_exists(char*name) 
618 {
619     return dict_lookup(state->vars, name)!=0;
620 }
621 static int new_variable(char*name, classinfo_t*type)
622 {
623     NEW(variable_t, v);
624     v->index = global->variable_count;
625     v->type = type;
626     dict_put(state->vars, name, v);
627     return global->variable_count++;
628 }
629 #define TEMPVARNAME "__as3_temp__"
630 static int gettempvar()
631 {
632     int i = find_variable(TEMPVARNAME, 0);
633     if(i<0) {
634         return new_variable(TEMPVARNAME, 0);
635     } else {
636         return i;
637     }
638 }
639
640 code_t* killvars(code_t*c) 
641 {
642     int t;
643     for(t=0;t<state->vars->hashsize;t++) {
644         dictentry_t*e =state->vars->slots[t];
645         while(e) {
646             variable_t*v = (variable_t*)e->data;
647             //do this always, otherwise register types don't match
648             //in the verifier when doing nested loops
649             //if(!TYPE_IS_BUILTIN_SIMPLE(type)) {
650             c = abc_kill(c, v->index);
651             e = e->next;
652         }
653     }
654     return c;
655 }
656
657
658 static void check_constant_against_type(classinfo_t*t, constant_t*c)
659 {
660 #define xassert(b) if(!(b)) syntaxerror("Invalid default value %s for type '%s'", constant_tostring(c), t->name)
661    if(TYPE_IS_NUMBER(t)) {
662         xassert(c->type == CONSTANT_FLOAT
663              || c->type == CONSTANT_INT
664              || c->type == CONSTANT_UINT);
665    } else if(TYPE_IS_UINT(t)) {
666         xassert(c->type == CONSTANT_UINT ||
667                (c->type == CONSTANT_INT && c->i>0));
668    } else if(TYPE_IS_INT(t)) {
669         xassert(c->type == CONSTANT_INT);
670    } else if(TYPE_IS_BOOLEAN(t)) {
671         xassert(c->type == CONSTANT_TRUE
672              || c->type == CONSTANT_FALSE);
673    }
674 }
675
676 static void startfunction(token_t*ns, int flags, enum yytokentype getset, char*name,
677                           params_t*params, classinfo_t*type)
678 {
679     token_list_t*t;
680     new_state();
681     global->variable_count = 0;
682     state->function = name;
683     
684     if(state->m) {
685         syntaxerror("not able to start another method scope");
686     }
687
688     multiname_t*type2 = sig2mname(type);
689     if(!strcmp(state->clsinfo->name,name)) {
690         state->m = abc_class_constructor(state->cls, type2, 0);
691     } else {
692         state->minfo = memberinfo_register(state->clsinfo, name, MEMBER_METHOD);
693         state->minfo->return_type = type;
694
695         state->m = abc_class_method(state->cls, type2, name, 0);
696         // getslot on a member slot only returns "undefined", so no need
697         // to actually store these
698         //state->minfo->slot = state->m->method->trait->slot_id;
699     }
700     if(getset == KW_GET) {
701         state->m->trait->kind = TRAIT_GETTER;
702     }
703     if(getset == KW_SET) {
704         state->m->trait->kind = TRAIT_SETTER;
705     }
706     if(params->varargs) {
707         state->m->flags |= METHOD_NEED_REST;
708     }
709
710     char opt=0;
711     param_list_t*p=0;
712     for(p=params->list;p;p=p->next) {
713         if(params->varargs && !p->next) {
714             break; //varargs: omit last parameter in function signature
715         }
716         multiname_t*m = sig2mname(p->param->type);
717         list_append(state->m->parameters, m);
718         if(p->param->value) {
719             check_constant_against_type(p->param->type, p->param->value);
720             opt=1;list_append(state->m->optional_parameters, p->param->value);
721         } else if(opt) {
722             syntaxerror("non-optional parameter not allowed after optional parameters");
723         }
724     }
725
726     /* state->vars is initialized by state_new */
727     if(new_variable("this", state->clsinfo)!=0) syntaxerror("Internal error");
728
729     for(p=params->list;p;p=p->next) {
730         new_variable(p->param->name, p->param->type);
731     }
732 }
733 static void endfunction(code_t*body)
734 {
735         
736     if(!(state->cls->flags & CLASS_INTERFACE)) {
737         code_t*c = 0;
738         if(state->late_binding) {
739             c = abc_getlocal_0(c);
740             c = abc_pushscope(c);
741         }
742         c = code_append(c, state->initcode);
743         c = code_append(c, body);
744
745         /* append return if necessary */
746         if(!c || c->opcode != OPCODE_RETURNVOID && 
747                  c->opcode != OPCODE_RETURNVALUE) {
748             c = abc_returnvoid(c);
749         }
750         if(state->m->body->code) syntaxerror("internal error");
751         state->m->body->code = c;
752     }
753     old_state();
754 }
755
756
757
758 char is_subtype_of(classinfo_t*type, classinfo_t*supertype)
759 {
760     return 1; // FIXME
761 }
762
763 void breakjumpsto(code_t*c, code_t*jump) 
764 {
765     while(c->prev) 
766         c=c->prev;
767     while(c) {
768         if(c->opcode == OPCODE___BREAK__) {
769             c->opcode = OPCODE_JUMP;
770             c->branch = jump;
771         }
772         c = c->next;
773     }
774 }
775
776 classinfo_t*join_types(classinfo_t*type1, classinfo_t*type2, char op)
777 {
778     if(!type1 || !type2) 
779         return registry_getanytype();
780     if(TYPE_IS_ANY(type1) || TYPE_IS_ANY(type2))
781         return registry_getanytype();
782     if(type1 == type2)
783         return type1;
784     return registry_getanytype();
785 }
786 code_t*converttype(code_t*c, classinfo_t*from, classinfo_t*to)
787 {
788     if(from==to)
789         return c;
790     if(!to) {
791         return abc_coerce_a(c);
792     }
793     MULTINAME(m, to);
794     if(!from) {
795         // cast an "any" type to a specific type. subject to
796         // runtime exceptions
797         return abc_coerce2(c, &m);
798     }
799     
800     if(TYPE_IS_NUMBER(from) && TYPE_IS_UINT(to)) {
801         return abc_coerce2(c, &m);
802     }
803     if(TYPE_IS_NUMBER(from) && TYPE_IS_INT(to)) {
804         return abc_coerce2(c, &m);
805     }
806     classinfo_t*supertype = from;
807     while(supertype) {
808         if(supertype == to) {
809              // target type is one of from's superclasses
810              return abc_coerce2(c, &m);
811         }
812         int t=0;
813         while(supertype->interfaces[t]) {
814             if(supertype->interfaces[t]==to) {
815                 // to type is one of from's interfaces
816                 return abc_coerce2(c, &m);
817             }
818             t++;
819         }
820         supertype = supertype->superclass;
821     }
822     syntaxerror("can't convert type %s to %s", from->name, to->name);
823 }
824
825 code_t*defaultvalue(code_t*c, classinfo_t*type)
826 {
827     if(TYPE_IS_INT(type) || TYPE_IS_UINT(type) || TYPE_IS_FLOAT(type)) {
828        c = abc_pushbyte(c, 0);
829     } else if(TYPE_IS_BOOLEAN(type)) {
830        c = abc_pushfalse(c);
831     } else {
832        c = abc_pushnull(c);
833     }
834     return c;
835 }
836
837 char is_pushundefined(code_t*c)
838 {
839     return (c && !c->prev && !c->next && c->opcode == OPCODE_PUSHUNDEFINED);
840 }
841
842 void parserassert(int b)
843 {
844     if(!b) syntaxerror("internal error: assertion failed");
845 }
846
847 static code_t* toreadwrite(code_t*in, code_t*middlepart, char justassign, char readbefore)
848 {
849     /* converts this:
850
851        [prefix code] [read instruction]
852
853        to this:
854
855        [prefix code] ([dup]) [read instruction] [middlepart] [setvar] [write instruction] [getvar]
856     */
857     
858     if(in && in->opcode == OPCODE_COERCE_A) {
859         in = code_cutlast(in);
860     }
861     if(in->next)
862         syntaxerror("internal error");
863
864     /* chop off read instruction */
865     code_t*prefix = in;
866     code_t*r = in;
867     if(r->prev) {
868         prefix = r->prev;r->prev = 0;
869         prefix->next=0;
870     } else {
871         prefix = 0;
872     }
873
874     char use_temp_var = readbefore;
875
876     /* generate the write instruction, and maybe append a dup to the prefix code */
877     code_t* write = abc_nop(0);
878     if(r->opcode == OPCODE_GETPROPERTY) {
879         write->opcode = OPCODE_SETPROPERTY;
880         multiname_t*m = (multiname_t*)r->data[0];
881         write->data[0] = multiname_clone(m);
882         if(m->type != QNAME)
883             syntaxerror("illegal lvalue: can't assign a value to this expression (not a qname)");
884         if(!justassign) {
885             use_temp_var = 1;
886             prefix = abc_dup(prefix); // we need the object, too
887         }
888     } else if(r->opcode == OPCODE_GETSLOT) {
889         write->opcode = OPCODE_SETSLOT;
890         write->data[0] = r->data[0];
891         if(!justassign) {
892             use_temp_var = 1;
893             prefix = abc_dup(prefix); // we need the object, too
894         }
895     } else if(r->opcode == OPCODE_GETLOCAL) { 
896         write->opcode = OPCODE_SETLOCAL;
897         write->data[0] = r->data[0];
898     } else if(r->opcode == OPCODE_GETLOCAL_0) { 
899         write->opcode = OPCODE_SETLOCAL_0;
900     } else if(r->opcode == OPCODE_GETLOCAL_1) { 
901         write->opcode = OPCODE_SETLOCAL_1;
902     } else if(r->opcode == OPCODE_GETLOCAL_2) { 
903         write->opcode = OPCODE_SETLOCAL_2;
904     } else if(r->opcode == OPCODE_GETLOCAL_3) { 
905         write->opcode = OPCODE_SETLOCAL_3;
906     } else {
907         code_dump(r, 0, 0, "", stdout);
908         syntaxerror("illegal lvalue: can't assign a value to this expression");
909     }
910     code_t* c = 0;
911     
912     int temp = -1;
913     if(!justassign) {
914         if(use_temp_var) {
915             /* with getproperty/getslot, we have to be extra careful not
916                to execute the read code twice, as it might have side-effects
917                (e.g. if the property is in fact a setter/getter combination)
918
919                So read the value, modify it, and write it again,
920                using prefix only once and making sure (by using a temporary
921                register) that the return value is what we just wrote */
922             temp = gettempvar();
923             c = code_append(c, prefix);
924             c = code_append(c, r);
925             if(readbefore) {
926                 c = abc_dup(c);
927                 c = abc_setlocal(c, temp);
928             }
929             c = code_append(c, middlepart);
930             if(!readbefore) {
931                 c = abc_dup(c);
932                 c = abc_setlocal(c, temp);
933             }
934             c = code_append(c, write);
935             c = abc_getlocal(c, temp);
936             c = abc_kill(c, temp);
937         } else {
938             /* if we're allowed to execute the read code twice *and*
939                the middlepart doesn't modify the code, things are easier.
940             */
941             code_t* r2 = code_dup(r);
942             //c = code_append(c, prefix);
943             parserassert(!prefix);
944             c = code_append(c, r);
945             c = code_append(c, middlepart);
946             c = code_append(c, write);
947             c = code_append(c, r2);
948         }
949     } else {
950         /* even smaller version: overwrite the value without reading
951            it out first */
952         if(prefix) {
953             c = code_append(c, prefix);
954             c = abc_dup(c);
955         }
956         c = code_append(c, middlepart);
957         c = code_append(c, write);
958         c = code_append(c, r);
959     }
960
961     return c;
962 }
963
964
965 %}
966
967
968 %%
969
970 /* ------------ code blocks / statements ---------------- */
971
972 PROGRAM: MAYBECODE
973
974 MAYBECODE: CODE {$$=$1;}
975 MAYBECODE:      {$$=code_new();}
976
977 CODE: CODE CODEPIECE {$$=code_append($1,$2);}
978 CODE: CODEPIECE {$$=$1;}
979
980 CODEPIECE: PACKAGE_DECLARATION   {$$=code_new();/*enters a scope*/}
981 CODEPIECE: CLASS_DECLARATION     {$$=code_new();/*enters a scope*/}
982 CODEPIECE: FUNCTION_DECLARATION  {$$=code_new();/*enters a scope*/}
983 CODEPIECE: INTERFACE_DECLARATION {$$=code_new();}
984 CODEPIECE: IMPORT                {$$=code_new();/*adds imports to current scope*/}
985 CODEPIECE: ';'                   {$$=code_new();}
986 CODEPIECE: VARIABLE_DECLARATION  {$$=$1}
987 CODEPIECE: VOIDEXPRESSION        {$$=$1}
988 CODEPIECE: FOR                   {$$=$1}
989 CODEPIECE: WHILE                 {$$=$1}
990 CODEPIECE: BREAK                 {$$=$1}
991 CODEPIECE: RETURN                {$$=$1}
992 CODEPIECE: IF                    {$$=$1}
993 CODEPIECE: NAMESPACE_DECLARATION {/*TODO*/$$=code_new();}
994 CODEPIECE: USE_NAMESPACE         {/*TODO*/$$=code_new();}
995
996 CODEBLOCK :  '{' MAYBECODE '}' {$$=$2;}
997 CODEBLOCK :  CODEPIECE ';'             {$$=$1;}
998 CODEBLOCK :  CODEPIECE %prec below_semicolon {$$=$1;}
999
1000 /* ------------ variables --------------------------- */
1001
1002 MAYBEEXPRESSION : '=' NONCOMMAEXPRESSION {$$=$2;}
1003                 |                {$$.c=abc_pushundefined(0);
1004                                   $$.t=TYPE_ANY;
1005                                  }
1006
1007 VAR : "const" | "var"
1008 VARIABLE_DECLARATION : VAR VARIABLE_LIST {$$=$2;}
1009
1010 VARIABLE_LIST: ONE_VARIABLE                   {$$ = $1;}
1011 VARIABLE_LIST: VARIABLE_LIST ',' ONE_VARIABLE {$$ = code_append($1, $3);}
1012
1013 ONE_VARIABLE: {} T_IDENTIFIER MAYBETYPE MAYBEEXPRESSION
1014 {
1015     if(variable_exists($2))
1016         syntaxerror("Variable %s already defined", $2);
1017    
1018     if(!is_subtype_of($4.t, $3)) {
1019         syntaxerror("Can't convert %s to %s", $4.t->name, 
1020                                               $3->name);
1021     }
1022
1023     int index = new_variable($2, $3);
1024     
1025     if($3) {
1026         if($4.c->prev || $4.c->opcode != OPCODE_PUSHUNDEFINED) {
1027             $$ = $4.c;
1028             $$ = converttype($$, $4.t, $3);
1029             $$ = abc_setlocal($$, index);
1030         } else {
1031             $$ = defaultvalue(0, $3);
1032             $$ = abc_setlocal($$, index);
1033         }
1034
1035         /* if this is a typed variable:
1036            push default value for type on stack */
1037         if($3) {
1038             state->initcode = defaultvalue(state->initcode, $3);
1039             state->initcode = abc_setlocal(state->initcode, index);
1040         }
1041     } else {
1042         if($4.c->prev || $4.c->opcode != OPCODE_PUSHUNDEFINED) {
1043             $$ = $4.c;
1044             $$ = abc_coerce_a($$);
1045             $$ = abc_setlocal($$, index);
1046         } else {
1047             $$ = code_new();
1048         }
1049     }
1050     
1051     /* that's the default for a local register, anyway
1052         else {
1053         state->initcode = abc_pushundefined(state->initcode);
1054         state->initcode = abc_setlocal(state->initcode, index);
1055     }*/
1056     //printf("variable %s -> %d (%s)\n", $2->text, index, $4.t?$4.t->name:"");
1057 }
1058
1059 /* ------------ control flow ------------------------- */
1060
1061 MAYBEELSE:  %prec prec_none {$$ = code_new();}
1062 MAYBEELSE: "else" CODEBLOCK {$$=$2;}
1063 //MAYBEELSE: ';' "else" CODEBLOCK {$$=$3;}
1064
1065 IF  : "if" '(' {new_state();} EXPRESSION ')' CODEBLOCK MAYBEELSE {
1066     $$ = state->initcode;state->initcode=0;
1067
1068     $$ = code_append($$, $4.c);
1069     code_t*myjmp,*myif = $$ = abc_iffalse($$, 0);
1070    
1071     $$ = code_append($$, $6);
1072     if($7) {
1073         myjmp = $$ = abc_jump($$, 0);
1074     }
1075     myif->branch = $$ = abc_label($$);
1076     if($7) {
1077         $$ = code_append($$, $7);
1078         myjmp->branch = $$ = abc_label($$);
1079     }
1080     
1081     $$ = killvars($$);old_state();
1082 }
1083
1084 FOR_INIT : {$$=code_new();}
1085 FOR_INIT : VARIABLE_DECLARATION
1086 FOR_INIT : VOIDEXPRESSION
1087
1088 FOR : "for" '(' {new_state();} FOR_INIT ';' EXPRESSION ';' VOIDEXPRESSION ')' CODEBLOCK {
1089     $$ = state->initcode;state->initcode=0;
1090
1091     $$ = code_append($$, $4);
1092     code_t*loopstart = $$ = abc_label($$);
1093     $$ = code_append($$, $6.c);
1094     code_t*myif = $$ = abc_iffalse($$, 0);
1095     $$ = code_append($$, $10);
1096     $$ = code_append($$, $8);
1097     $$ = abc_jump($$, loopstart);
1098     code_t*out = $$ = abc_label($$);
1099     breakjumpsto($$, out);
1100     myif->branch = out;
1101
1102     $$ = killvars($$);old_state();
1103 }
1104
1105 WHILE : "while" '(' {new_state();} EXPRESSION ')' CODEBLOCK {
1106     $$ = state->initcode;state->initcode=0;
1107
1108     code_t*myjmp = $$ = abc_jump($$, 0);
1109     code_t*loopstart = $$ = abc_label($$);
1110     $$ = code_append($$, $6);
1111     myjmp->branch = $$ = abc_label($$);
1112     $$ = code_append($$, $4.c);
1113     $$ = abc_iftrue($$, loopstart);
1114     code_t*out = $$ = abc_label($$);
1115     breakjumpsto($$, out);
1116
1117     $$ = killvars($$);old_state();
1118 }
1119
1120 BREAK : "break" {
1121     $$ = abc___break__(0);
1122 }
1123
1124 /* ------------ packages and imports ---------------- */
1125
1126 X_IDENTIFIER: T_IDENTIFIER
1127             | "package" {$$="package";}
1128
1129 PACKAGE: PACKAGE '.' X_IDENTIFIER {$$ = concat3str($1,".",$3);}
1130 PACKAGE: X_IDENTIFIER             {$$=$1;}
1131
1132 PACKAGE_DECLARATION : "package" PACKAGE '{' {startpackage($2)} MAYBECODE '}' {endpackage()}
1133 PACKAGE_DECLARATION : "package" '{' {startpackage("")} MAYBECODE '}' {endpackage()}
1134
1135 IMPORT : "import" QNAME {
1136        classinfo_t*c = $2;
1137        if(!c) 
1138             syntaxerror("Couldn't import class\n");
1139        state_has_imports();
1140        dict_put(state->imports, c->name, c);
1141        $$=0;
1142 }
1143 IMPORT : "import" PACKAGE '.' '*' {
1144        NEW(import_t,i);
1145        i->package = $2;
1146        state_has_imports();
1147        list_append(state->wildcard_imports, i);
1148        $$=0;
1149 }
1150
1151 /* ------------ classes and interfaces (header) -------------- */
1152
1153 MAYBE_MODIFIERS : {$$=0;}
1154 MAYBE_MODIFIERS : MODIFIER_LIST {$$=$1}
1155 MODIFIER_LIST : MODIFIER               {$$=$1;}
1156 MODIFIER_LIST : MODIFIER_LIST MODIFIER {$$=$1|$2;}
1157
1158 MODIFIER : KW_PUBLIC {$$=FLAG_PUBLIC;}
1159          | KW_PRIVATE {$$=FLAG_PRIVATE;}
1160          | KW_PROTECTED {$$=FLAG_PROTECTED;}
1161          | KW_STATIC {$$=FLAG_STATIC;}
1162          | KW_DYNAMIC {$$=FLAG_DYNAMIC;}
1163          | KW_FINAL {$$=FLAG_FINAL;}
1164          | KW_OVERRIDE {$$=FLAG_OVERRIDE;}
1165          | KW_NATIVE {$$=FLAG_NATIVE;}
1166          | KW_INTERNAL {$$=FLAG_INTERNAL;}
1167
1168 EXTENDS : {$$=registry_getobjectclass();}
1169 EXTENDS : KW_EXTENDS QNAME {$$=$2;}
1170
1171 EXTENDS_LIST : {$$=list_new();}
1172 EXTENDS_LIST : KW_EXTENDS QNAME_LIST {$$=$2;}
1173
1174 IMPLEMENTS_LIST : {$$=list_new();}
1175 IMPLEMENTS_LIST : KW_IMPLEMENTS QNAME_LIST {$$=$2;}
1176
1177 CLASS_DECLARATION : MAYBE_MODIFIERS "class" T_IDENTIFIER 
1178                               EXTENDS IMPLEMENTS_LIST 
1179                               '{' {startclass($1,$3,$4,$5, 0);} 
1180                               MAYBE_DECLARATION_LIST 
1181                               '}' {endclass();}
1182
1183 INTERFACE_DECLARATION : MAYBE_MODIFIERS "interface" T_IDENTIFIER 
1184                               EXTENDS_LIST 
1185                               '{' {startclass($1,$3,0,$4,1);}
1186                               MAYBE_IDECLARATION_LIST 
1187                               '}' {endclass();}
1188
1189 /* ------------ classes and interfaces (body) -------------- */
1190
1191 MAYBE_DECLARATION_LIST : 
1192 MAYBE_DECLARATION_LIST : DECLARATION_LIST
1193 DECLARATION_LIST : DECLARATION
1194 DECLARATION_LIST : DECLARATION_LIST DECLARATION
1195 DECLARATION : ';'
1196 DECLARATION : SLOT_DECLARATION
1197 DECLARATION : FUNCTION_DECLARATION
1198
1199 MAYBE_IDECLARATION_LIST : 
1200 MAYBE_IDECLARATION_LIST : IDECLARATION_LIST
1201 IDECLARATION_LIST : IDECLARATION
1202 IDECLARATION_LIST : IDECLARATION_LIST IDECLARATION
1203 IDECLARATION : ';'
1204 IDECLARATION : "var" T_IDENTIFIER {
1205     syntaxerror("variable declarations not allowed in interfaces");
1206 }
1207 IDECLARATION : MAYBE_MODIFIERS "function" GETSET T_IDENTIFIER '(' MAYBE_PARAM_LIST ')' MAYBETYPE {
1208     if($1&(FLAG_PUBLIC|FLAG_PRIVATE|FLAG_INTERNAL|FLAG_PROTECTED)) {
1209         syntaxerror("invalid method modifiers: interface methods are always public");
1210     }
1211     startfunction(0,$1,$3,$4,&$6,$8);
1212     endfunction(0);
1213 }
1214
1215 /* ------------ classes and interfaces (body, slots ) ------- */
1216
1217 VARCONST: "var" | "const"
1218 SLOT_DECLARATION: MAYBE_MODIFIERS VARCONST T_IDENTIFIER MAYBETYPE MAYBEEXPRESSION {
1219
1220     memberinfo_t* info = memberinfo_register(state->clsinfo, $3, MEMBER_SLOT);
1221     info->type = $4;
1222
1223     trait_t*t=0;
1224     if($4) {
1225         MULTINAME(m, $4);
1226         t=abc_class_slot(state->cls, $3, &m);
1227     } else {
1228         t=abc_class_slot(state->cls, $3, 0);
1229     }
1230     if($2==KW_CONST) {
1231         t->kind= TRAIT_CONST;
1232     }
1233     info->slot = t->slot_id;
1234     if($5.c && !is_pushundefined($5.c)) {
1235         code_t*c = 0;
1236         c = abc_getlocal_0(c);
1237         c = code_append(c, $5.c);
1238         c = converttype(c, $5.t, $4);
1239         c = abc_setslot(c, t->slot_id);
1240         //c = abc_setproperty(c, $3); 
1241         state->cls_init = code_append(state->cls_init, c);
1242     }
1243 }
1244
1245 /* ------------ constants -------------------------------------- */
1246
1247 MAYBESTATICCONSTANT: {$$=0;}
1248 MAYBESTATICCONSTANT: '=' STATICCONSTANT {$$=$2;}
1249
1250 STATICCONSTANT : T_BYTE {$$ = constant_new_int($1);}
1251 STATICCONSTANT : T_INT {$$ = constant_new_int($1);}
1252 STATICCONSTANT : T_UINT {$$ = constant_new_uint($1);}
1253 STATICCONSTANT : T_FLOAT {$$ = constant_new_float($1);}
1254 STATICCONSTANT : T_STRING {$$ = constant_new_string2($1.str,$1.len);}
1255 //STATICCONSTANT : T_NAMESPACE {$$ = constant_new_namespace($1);}
1256 STATICCONSTANT : KW_TRUE {$$ = constant_new_true($1);}
1257 STATICCONSTANT : KW_FALSE {$$ = constant_new_false($1);}
1258 STATICCONSTANT : KW_NULL {$$ = constant_new_null($1);}
1259
1260 /* ------------ classes and interfaces (body, functions) ------- */
1261
1262 // non-vararg version
1263 MAYBE_PARAM_LIST: {
1264     memset(&$$,0,sizeof($$));
1265 }
1266 MAYBE_PARAM_LIST: PARAM_LIST {
1267     $$=$1;
1268 }
1269
1270 // vararg version
1271 MAYBE_PARAM_LIST: "..." PARAM {
1272     memset(&$$,0,sizeof($$));
1273     $$.varargs=1;
1274     list_append($$.list, $2);
1275 }
1276 MAYBE_PARAM_LIST: PARAM_LIST ',' "..." PARAM {
1277     $$ =$1;
1278     $$.varargs=1;
1279     list_append($$.list, $4);
1280 }
1281
1282 // non empty
1283 PARAM_LIST: PARAM_LIST ',' PARAM {
1284     $$ = $1;
1285     list_append($$.list, $3);
1286 }
1287 PARAM_LIST: PARAM {
1288     memset(&$$,0,sizeof($$));
1289     list_append($$.list, $1);
1290 }
1291
1292 PARAM:  T_IDENTIFIER ':' TYPE MAYBESTATICCONSTANT {
1293      $$ = malloc(sizeof(param_t));
1294      $$->name=$1;
1295      $$->type = $3;
1296      $$->value = $4;
1297 }
1298 PARAM:  T_IDENTIFIER MAYBESTATICCONSTANT {
1299      $$ = malloc(sizeof(param_t));
1300      $$->name=$1;
1301      $$->type = TYPE_ANY;
1302      $$->value = $2;
1303 }
1304 GETSET : "get" {$$=$1;}
1305        | "set" {$$=$1;}
1306        |       {$$=0;}
1307
1308 FUNCTION_DECLARATION: MAYBE_MODIFIERS "function" GETSET T_IDENTIFIER '(' MAYBE_PARAM_LIST ')' 
1309                       MAYBETYPE '{' {startfunction(0,$1,$3,$4,&$6,$8)} MAYBECODE '}' 
1310 {
1311     if(!state->m) syntaxerror("internal error: undefined function");
1312     endfunction($11);
1313 }
1314
1315 /* ------------- package + class ids --------------- */
1316
1317 CLASS: T_IDENTIFIER {
1318
1319     /* try current package */
1320     $$ = registry_findclass(state->package, $1);
1321
1322     /* try explicit imports */
1323     dictentry_t* e = dict_get_slot(state->imports, $1);
1324     while(e) {
1325         if($$)
1326             break;
1327         if(!strcmp(e->key, $1)) {
1328             $$ = (classinfo_t*)e->data;
1329         }
1330         e = e->next;
1331     }
1332
1333     /* try package.* imports */
1334     import_list_t*l = state->wildcard_imports;
1335     while(l) {
1336         if($$)
1337             break;
1338         //printf("does package %s contain a class %s?\n", l->import->package, $1);
1339         $$ = registry_findclass(l->import->package, $1);
1340         l = l->next;
1341     }
1342
1343     /* try global package */
1344     if(!$$) {
1345         $$ = registry_findclass("", $1);
1346     }
1347
1348     if(!$$) syntaxerror("Could not find class %s\n", $1);
1349 }
1350
1351 PACKAGEANDCLASS : PACKAGE '.' T_IDENTIFIER {
1352     $$ = registry_findclass($1, $3);
1353     if(!$$) syntaxerror("Couldn't find class %s.%s\n", $1, $3);
1354 }
1355
1356 QNAME: PACKAGEANDCLASS
1357      | CLASS
1358
1359 QNAME_LIST : QNAME {$$=list_new();list_append($$, $1);}
1360 QNAME_LIST : QNAME_LIST ',' QNAME {$$=$1;list_append($$,$3);}
1361
1362 TYPE : QNAME      {$$=$1;}
1363      | '*'        {$$=registry_getanytype();}
1364      |  "String"  {$$=registry_getstringclass();}
1365      |  "int"     {$$=registry_getintclass();}
1366      |  "uint"    {$$=registry_getuintclass();}
1367      |  "Boolean" {$$=registry_getbooleanclass();}
1368      |  "Number"  {$$=registry_getnumberclass();}
1369
1370 MAYBETYPE: ':' TYPE {$$=$2;}
1371 MAYBETYPE:          {$$=0;}
1372
1373 /* ----------function calls, constructor calls ------ */
1374
1375 MAYBE_PARAM_VALUES :  %prec prec_none {$$=0;}
1376 MAYBE_PARAM_VALUES : '(' MAYBE_EXPRESSION_LIST ')' {$$=$2}
1377
1378 MAYBE_EXPRESSION_LIST : {$$=0;}
1379 MAYBE_EXPRESSION_LIST : EXPRESSION_LIST
1380 EXPRESSION_LIST : NONCOMMAEXPRESSION             {$$=list_new();
1381                                                   typedcode_t*t = malloc(sizeof(typedcode_t));
1382                                                   *t = $1;
1383                                                   list_append($$, t);}
1384 EXPRESSION_LIST : EXPRESSION_LIST ',' NONCOMMAEXPRESSION {$$=$1;
1385                                                   typedcode_t*t = malloc(sizeof(typedcode_t));
1386                                                   *t = $3;
1387                                                   list_append($$, t);}
1388
1389 NEW : "new" CLASS MAYBE_PARAM_VALUES {
1390     MULTINAME(m, $2);
1391     $$.c = code_new();
1392
1393     /* TODO: why do we have to *find* our own classes? */
1394     $$.c = abc_findpropstrict2($$.c, &m);
1395
1396     typedcode_list_t*l = $3;
1397     int len = 0;
1398     while(l) {
1399         $$.c = code_append($$.c, l->typedcode->c); // push parameters on stack
1400         l = l->next;
1401         len ++;
1402     }
1403     $$.c = abc_constructprop2($$.c, &m, len);
1404     $$.t = $2;
1405 }
1406
1407 /* TODO: use abc_call (for calling local variables),
1408          abc_callstatic (for calling own methods) 
1409          call (for closures)
1410 */
1411 FUNCTIONCALL : E '(' MAYBE_EXPRESSION_LIST ')' {
1412     typedcode_list_t*l = $3;
1413     int len = 0;
1414     code_t*paramcode = 0;
1415     while(l) {
1416         paramcode = code_append(paramcode, l->typedcode->c); // push parameters on stack
1417         l = l->next;
1418         len ++;
1419     }
1420        
1421     $$.c = $1.c;
1422     if($$.c->opcode == OPCODE_COERCE_A) {
1423         $$.c = code_cutlast($$.c);
1424     }
1425
1426     $$.t = TYPE_ANY;
1427     multiname_t*name = 0;
1428     if($$.c->opcode == OPCODE_GETPROPERTY) {
1429         name = multiname_clone($$.c->data[0]);
1430         $$.c = code_cutlast($$.c);
1431         $$.c = code_append($$.c, paramcode);
1432         $$.c = abc_callproperty2($$.c, name, len);
1433     } else if($$.c->opcode == OPCODE_GETSLOT) {
1434         int slot = (int)(ptroff_t)$$.c->data[0];
1435         trait_t*t = abc_class_find_slotid(state->cls,slot);//FIXME
1436         if(t->kind!=TRAIT_METHOD) {
1437             //flash allows to assign closures to members.
1438             //syntaxerror("not a function");
1439         }
1440         name = t->name;
1441         $$.c = code_cutlast($$.c);
1442         $$.c = code_append($$.c, paramcode);
1443         //$$.c = abc_callmethod($$.c, t->method, len); //#1051 illegal early access binding
1444         $$.c = abc_callproperty2($$.c, name, len);
1445     } else {
1446         $$.c = abc_getlocal_0($$.c);
1447         $$.c = code_append($$.c, paramcode);
1448         $$.c = abc_call($$.c, len);
1449     }
1450    
1451     memberinfo_t*f = 0;
1452    
1453     if(TYPE_IS_FUNCTION($1.t) &&
1454        (f = registry_findmember($1.t, "call"))) {
1455         $$.t = f->return_type;
1456     } else {
1457         $$.c = abc_coerce_a($$.c);
1458         $$.t = TYPE_ANY;
1459     }
1460 }
1461
1462 RETURN: "return" %prec prec_none {
1463     $$ = abc_returnvoid(0);
1464 }
1465 RETURN: "return" EXPRESSION {
1466     $$ = $2.c;
1467     $$ = abc_returnvalue($$);
1468 }
1469 // ----------------------- expression types -------------------------------------
1470
1471 NONCOMMAEXPRESSION : E        %prec prec_belowminus {$$=$1;}
1472 EXPRESSION : E                %prec prec_belowminus {$$ = $1;}
1473 EXPRESSION : EXPRESSION ',' E %prec prec_belowminus {
1474     $$.c = $1.c;
1475     $$.c = cut_last_push($$.c);
1476     $$.c = code_append($$.c,$3.c);
1477     $$.t = $3.t;
1478 }
1479 VOIDEXPRESSION : EXPRESSION %prec prec_belowminus {$$=cut_last_push($1.c);}
1480
1481 // ----------------------- expression evaluation -------------------------------------
1482
1483 E : CONSTANT
1484 E : VAR_READ %prec T_IDENTIFIER {$$ = $1;}
1485 E : NEW                         {$$ = $1;}
1486 E : T_REGEXP                    {$$.c = abc_pushundefined(0); /* FIXME */
1487                                  $$.t = TYPE_ANY;
1488                                 }
1489
1490 CONSTANT : T_BYTE {$$.c = abc_pushbyte(0, $1);
1491                    //MULTINAME(m, registry_getintclass());
1492                    //$$.c = abc_coerce2($$.c, &m); // FIXME
1493                    $$.t = TYPE_INT;
1494                   }
1495 CONSTANT : T_SHORT {$$.c = abc_pushshort(0, $1);
1496                     $$.t = TYPE_INT;
1497                    }
1498 CONSTANT : T_INT {$$.c = abc_pushint(0, $1);
1499                   $$.t = TYPE_INT;
1500                  }
1501 CONSTANT : T_UINT {$$.c = abc_pushuint(0, $1);
1502                    $$.t = TYPE_UINT;
1503                   }
1504 CONSTANT : T_FLOAT {$$.c = abc_pushdouble(0, $1);
1505                     $$.t = TYPE_FLOAT;
1506                    }
1507 CONSTANT : T_STRING {$$.c = abc_pushstring2(0, &$1);
1508                      $$.t = TYPE_STRING;
1509                     }
1510 CONSTANT : KW_TRUE {$$.c = abc_pushtrue(0);
1511                     $$.t = TYPE_BOOLEAN;
1512                    }
1513 CONSTANT : KW_FALSE {$$.c = abc_pushfalse(0);
1514                      $$.t = TYPE_BOOLEAN;
1515                     }
1516 CONSTANT : KW_NULL {$$.c = abc_pushnull(0);
1517                     $$.t = TYPE_NULL;
1518                    }
1519
1520 E : FUNCTIONCALL
1521 E : E '<' E {$$.c = code_append($1.c,$3.c);$$.c = abc_greaterequals($$.c);$$.c=abc_not($$.c);
1522              $$.t = TYPE_BOOLEAN;
1523             }
1524 E : E '>' E {$$.c = code_append($1.c,$3.c);$$.c = abc_greaterthan($$.c);
1525              $$.t = TYPE_BOOLEAN;
1526             }
1527 E : E "<=" E {$$.c = code_append($1.c,$3.c);$$.c = abc_greaterthan($$.c);$$.c=abc_not($$.c);
1528               $$.t = TYPE_BOOLEAN;
1529              }
1530 E : E ">=" E {$$.c = code_append($1.c,$3.c);$$.c = abc_greaterequals($$.c);
1531               $$.t = TYPE_BOOLEAN;
1532              }
1533 E : E "==" E {$$.c = code_append($1.c,$3.c);$$.c = abc_equals($$.c);
1534               $$.t = TYPE_BOOLEAN;
1535              }
1536 E : E "===" E {$$.c = code_append($1.c,$3.c);$$.c = abc_strictequals($$.c);
1537               $$.t = TYPE_BOOLEAN;
1538              }
1539 E : E "!=" E {$$.c = code_append($1.c,$3.c);$$.c = abc_equals($$.c);$$.c = abc_not($$.c);
1540               $$.t = TYPE_BOOLEAN;
1541              }
1542
1543 E : E "||" E {$$.t = join_types($1.t, $3.t, 'O');
1544               $$.c = $1.c;
1545               $$.c = converttype($$.c, $1.t, $$.t);
1546               $$.c = abc_dup($$.c);
1547               code_t*jmp = $$.c = abc_iftrue($$.c, 0);
1548               $$.c = cut_last_push($$.c);
1549               $$.c = code_append($$.c,$3.c);
1550               $$.c = converttype($$.c, $3.t, $$.t);
1551               code_t*label = $$.c = abc_label($$.c);
1552               jmp->branch = label;
1553              }
1554 E : E "&&" E {
1555               $$.t = join_types($1.t, $3.t, 'A');
1556               /*printf("%08x:\n",$1.t);
1557               code_dump($1.c, 0, 0, "", stdout);
1558               printf("%08x:\n",$3.t);
1559               code_dump($3.c, 0, 0, "", stdout);
1560               printf("joining %08x and %08x to %08x\n", $1.t, $3.t, $$.t);*/
1561               $$.c = $1.c;
1562               $$.c = converttype($$.c, $1.t, $$.t);
1563               $$.c = abc_dup($$.c);
1564               code_t*jmp = $$.c = abc_iffalse($$.c, 0);
1565               $$.c = cut_last_push($$.c);
1566               $$.c = code_append($$.c,$3.c);
1567               $$.c = converttype($$.c, $3.t, $$.t);
1568               code_t*label = $$.c = abc_label($$.c);
1569               jmp->branch = label;              
1570              }
1571
1572 E : '!' E    {$$.c=$2.c;
1573               $$.c = abc_not($$.c);
1574               $$.t = TYPE_BOOLEAN;
1575              }
1576
1577 E : E '-' E
1578 E : E '/' E
1579 E : E '+' E {$$.c = code_append($1.c,$3.c);$$.c = abc_add($$.c);$$.c=abc_coerce_a($$.c);
1580              $$.t = join_types($1.t, $3.t, '+');
1581             }
1582 E : E '%' E {$$.c = code_append($1.c,$3.c);$$.c = abc_modulo($$.c);$$.c=abc_coerce_a($$.c);
1583              $$.t = join_types($1.t, $3.t, '%');
1584             }
1585 E : E '*' E {$$.c = code_append($1.c,$3.c);$$.c = abc_multiply($$.c);$$.c=abc_coerce_a($$.c);
1586              $$.t = join_types($1.t, $3.t, '*');
1587             }
1588
1589 E : E "as" E
1590 E : E "is" E
1591 E : '(' E ')' {$$=$2;}
1592 E : '-' E {$$=$2;}
1593
1594 E : E '[' E ']' {
1595   $$.c = $1.c;
1596   $$.c = code_append($$.c, $3.c);
1597  
1598   MULTINAME_LATE(m, $1.t?$1.t->access:ACCESS_PACKAGE, "");
1599   $$.c = abc_getproperty2($$.c, &m);
1600 }
1601
1602 E : E "*=" E { 
1603                code_t*c = $3.c;
1604                if(TYPE_IS_INT($3.t) || TYPE_IS_UINT($3.t)) {
1605                 c=abc_multiply_i(c);
1606                } else {
1607                 c=abc_multiply(c);
1608                }
1609                c=converttype(c, join_types($1.t, $3.t, '*'), $1.t);
1610                $$.c = toreadwrite($1.c, c, 0, 0);
1611                $$.t = $1.t;
1612               }
1613 E : E "%=" E { 
1614                code_t*c = abc_modulo($3.c);
1615                c=converttype(c, join_types($1.t, $3.t, '%'), $1.t);
1616                $$.c = toreadwrite($1.c, c, 0, 0);
1617                $$.t = $1.t;
1618               }
1619 E : E "<<=" E { 
1620                code_t*c = abc_lshift($3.c);
1621                c=converttype(c, join_types($1.t, $3.t, '<'), $1.t);
1622                $$.c = toreadwrite($1.c, c, 0, 0);
1623                $$.t = $1.t;
1624               }
1625 E : E ">>=" E { 
1626                code_t*c = abc_rshift($3.c);
1627                c=converttype(c, join_types($1.t, $3.t, '>'), $1.t);
1628                $$.c = toreadwrite($1.c, c, 0, 0);
1629                $$.t = $1.t;
1630               }
1631 E : E ">>>=" E { 
1632                code_t*c = abc_urshift($3.c);
1633                c=converttype(c, join_types($1.t, $3.t, 'U'), $1.t);
1634                $$.c = toreadwrite($1.c, c, 0, 0);
1635                $$.t = $1.t;
1636               }
1637 E : E "/=" E { 
1638                code_t*c = abc_divide($3.c);
1639                c=converttype(c, join_types($1.t, $3.t, '/'), $1.t);
1640                $$.c = toreadwrite($1.c, c, 0, 0);
1641                $$.t = $1.t;
1642               }
1643 E : E "+=" E { 
1644                code_t*c = $3.c;
1645                if(TYPE_IS_INT($3.t) || TYPE_IS_UINT($3.t)) {
1646                 c=abc_add_i(c);
1647                } else {
1648                 c=abc_add(c);
1649                }
1650                c=converttype(c, join_types($1.t, $3.t, '+'), $1.t);
1651                
1652                $$.c = toreadwrite($1.c, c, 0, 0);
1653                $$.t = $1.t;
1654               }
1655 E : E "-=" E { code_t*c = $3.c; 
1656                if(TYPE_IS_INT($3.t) || TYPE_IS_UINT($3.t)) {
1657                 c=abc_subtract_i(c);
1658                } else {
1659                 c=abc_subtract(c);
1660                }
1661                c=converttype(c, join_types($1.t, $3.t, '-'), $1.t);
1662                
1663                $$.c = toreadwrite($1.c, c, 0, 0);
1664                $$.t = $1.t;
1665              }
1666 E : E '=' E { code_t*c = 0;
1667               c = code_append(c, $3.c);
1668               c = converttype(c, $3.t, $1.t);
1669               $$.c = toreadwrite($1.c, c, 1, 0);
1670               $$.t = $1.t;
1671             }
1672
1673 // TODO: use inclocal where appropriate
1674 E : E "++" { code_t*c = 0;
1675              classinfo_t*type = $1.t;
1676              if(TYPE_IS_INT(type) || TYPE_IS_UINT(type)) {
1677                  c=abc_increment_i(c);
1678              } else {
1679                  c=abc_increment(c);
1680                  type = TYPE_NUMBER;
1681              }
1682              c=converttype(c, type, $1.t);
1683              $$.c = toreadwrite($1.c, c, 0, 1);
1684              $$.t = $1.t;
1685            }
1686 E : E "--" { code_t*c = 0;
1687              classinfo_t*type = $1.t;
1688              if(TYPE_IS_INT(type) || TYPE_IS_UINT(type)) {
1689                  c=abc_decrement_i(c);
1690              } else {
1691                  c=abc_decrement(c);
1692                  type = TYPE_NUMBER;
1693              }
1694              c=converttype(c, type, $1.t);
1695              $$.c = toreadwrite($1.c, c, 0, 1);
1696              $$.t = $1.t;
1697             }
1698
1699 E : "++" E { code_t*c = 0;
1700              classinfo_t*type = $2.t;
1701              if(TYPE_IS_INT(type) || TYPE_IS_UINT(type)) {
1702                  c=abc_increment_i(c);
1703              } else {
1704                  c=abc_increment(c);
1705                  type = TYPE_NUMBER;
1706              }
1707              c=converttype(c, type, $2.t);
1708              $$.c = toreadwrite($2.c, c, 0, 0);
1709              $$.t = $2.t;
1710            }
1711
1712 E : "--" E { code_t*c = 0;
1713              classinfo_t*type = $2.t;
1714              if(TYPE_IS_INT(type) || TYPE_IS_UINT(type)) {
1715                  c=abc_decrement_i(c);
1716              } else {
1717                  c=abc_decrement(c);
1718                  type = TYPE_NUMBER;
1719              }
1720              c=converttype(c, type, $2.t);
1721              $$.c = toreadwrite($2.c, c, 0, 0);
1722              $$.t = $2.t;
1723            }
1724
1725 E : E '.' T_IDENTIFIER
1726             {$$.c = $1.c;
1727              if($$.t) {
1728                  memberinfo_t*f = registry_findmember($$.t, $3);
1729
1730                  if(f && f->slot) {
1731                      $$.c = abc_getslot($$.c, f->slot);
1732                  } else {
1733                      namespace_t ns = {$$.t->access, ""}; // needs to be "", not $$.t->package
1734                      multiname_t m = {QNAME, &ns, 0, $3};
1735                      $$.c = abc_getproperty2($$.c, &m);
1736                  }
1737                  /* determine type */
1738                  if(f) {
1739                     if(f->kind == MEMBER_METHOD) {
1740                         $$.t = TYPE_FUNCTION(f);
1741                     } else {
1742                         $$.t = f->type;
1743                     }
1744                  } else {
1745                     $$.c = abc_coerce_a($$.c);
1746                     $$.t = registry_getanytype();
1747                  }
1748              } else {
1749                  namespace_t ns = {ACCESS_PACKAGE, ""};
1750                  multiname_t m = {QNAME, &ns, 0, $3};
1751                  $$.c = abc_getproperty2($$.c, &m);
1752                  $$.c = abc_coerce_a($$.c);
1753                  $$.t = registry_getanytype();
1754              }
1755             }
1756
1757 VAR_READ : T_IDENTIFIER {
1758     $$.t = 0;
1759     $$.c = 0;
1760     int i;
1761     memberinfo_t*f = 0;
1762     if((i = find_variable($1, &$$.t)) >= 0) {
1763         // $1 is a local variable
1764         $$.c = abc_getlocal($$.c, i);
1765     } else if((f = registry_findmember(state->clsinfo, $1))) {
1766         // $1 is a function in this class
1767         if(f->kind == MEMBER_METHOD) {
1768             $$.t = TYPE_FUNCTION(f);
1769         } else {
1770             $$.t = f->type;
1771         }
1772         if(f->slot>0) {
1773             $$.c = abc_getlocal_0($$.c);
1774             $$.c = abc_getslot($$.c, f->slot);
1775         } else {
1776             namespace_t ns = {state->clsinfo->access, ""};
1777             multiname_t m = {QNAME, &ns, 0, $1};
1778             $$.c = abc_getlocal_0($$.c);
1779             $$.c = abc_getproperty2($$.c, &m);
1780         }
1781     } else {
1782         // let the avm2 resolve $1 
1783         if(strcmp($1,"trace"))
1784         warning("Couldn't resolve %s, doing late binding", $1);
1785         state->late_binding = 1;
1786
1787         $$.t = 0;
1788         $$.c = abc_findpropstrict($$.c, $1);
1789         $$.c = abc_getproperty($$.c, $1);
1790     }
1791 }
1792
1793 //TODO: 
1794 //VARIABLE : VARIABLE ".." T_IDENTIFIER // descendants
1795 //VARIABLE : VARIABLE "::" VARIABLE // namespace declaration
1796 //VARIABLE : VARIABLE "::" '[' EXPRESSION ']' // qualified expression
1797
1798 // ----------------- namespaces -------------------------------------------------
1799
1800 NAMESPACE_DECLARATION : MAYBE_MODIFIERS "namespace" T_IDENTIFIER {$$=$2;}
1801 NAMESPACE_DECLARATION : MAYBE_MODIFIERS "namespace" T_IDENTIFIER '=' T_IDENTIFIER {$$=$2;}
1802 NAMESPACE_DECLARATION : MAYBE_MODIFIERS "namespace" T_IDENTIFIER '=' T_STRING {$$=$2;}
1803
1804 USE_NAMESPACE : "use" "namespace" T_IDENTIFIER
1805