Debian Codegraph @

terps/tads/tads3/tcprs.h

raw symbols SCIP
1 /* $Header: d:/cvsroot/tads/tads3/tcprs.h,v 1.5 1999/07/11 00:46:58 MJRoberts Exp $ */
2
3 /*
4 * Copyright (c) 1999, 2002 Michael J. Roberts. All Rights Reserved.
5 *
6 * Please see the accompanying license file, LICENSE.TXT, for information
7 * on using and copying this software.
8 */
9 /*
10 Name
11 tcprs.h - TADS 3 Compiler - parser
12 Function
13
14 Notes
15
16 Modified
17 04/29/99 MJRoberts - Creation
18 */
19
20 #ifndef TCPRS_H
21 #define TCPRS_H
22
23 #include <assert.h>
24
25 #include "vmtype.h"
26 #include "t3std.h"
27 #include "tcglob.h"
28 #include "tctok.h"
29 #include "tctargty.h"
30 #include "tcprstyp.h"
31
32
33 /* ------------------------------------------------------------------------ */
34 /*
35 * Object ID type
36 */
37 typedef ulong tc_obj_id;
38
39 /*
40 * Property ID type
41 */
42 typedef uint tc_prop_id;
43
44
45 /* ------------------------------------------------------------------------ */
46 /*
47 * scope data structure
48 */
49 struct tcprs_scope_t
50 {
51 /* local symbol table */
52 class CTcPrsSymtab *local_symtab;
53
54 /* enclosing scope's local symbol table */
55 class CTcPrsSymtab *enclosing_symtab;
56
57 /* number of locals allocated in scope */
58 int local_cnt;
59 };
60
61 /* ------------------------------------------------------------------------ */
62 /*
63 * Code body parsing types. Each type of code body is essentially the
64 * same with minor variations, so we use a common code body parser that
65 * checks the parsing type to apply the variations.
66 */
67 enum tcprs_codebodytype
68 {
69 /* a standard function or method code body */
70 TCPRS_CB_NORMAL,
71
72 /* anonymous function */
73 TCPRS_CB_ANON_FN,
74
75 /* anonymous method */
76 TCPRS_CB_ANON_METHOD,
77
78 /* short-form anonymous function */
79 TCPRS_CB_SHORT_ANON_FN
80 };
81
82
83 /* ------------------------------------------------------------------------ */
84 /*
85 * the saved method context is always at index 1 in local variable context
86 * arrays, when we're using local variable context arrays
87 */
88 #define TCPRS_LOCAL_CTX_METHODCTX 1
89
90
91 /* ------------------------------------------------------------------------ */
92 /*
93 * Parser
94 */
95 class CTcParser
96 {
97 public:
98 CTcParser();
99 ~CTcParser();
100
101 /* initialize - call this after the code generator is set up */
102 void init();
103
104 /*
105 * reset - for dynamic code compilation in the interpreter, this resets
106 * internal state for the start of a new compilation
107 */
108 void reset()
109 {
110 /* forget any old local symbol table */
111 local_symtab_ = 0;
112
113 /* clear out all of our lists */
114 nested_stm_head_ = nested_stm_tail_ = 0;
115 anon_obj_head_ = anon_obj_tail_ = 0;
116 nonsym_obj_head_ = nonsym_obj_tail_ = 0;
117 exp_head_ = exp_tail_ = 0;
118 enclosing_stm_ = 0;
119 dict_cur_ = dict_head_ = dict_tail_ = 0;
120 dict_prop_head_ = 0;
121 gramprod_head_ = gramprod_tail_ = 0;
122 template_head_ = template_tail_ = 0;
123 cur_code_body_ = 0;
124
125 /* clear out any symbol table references */
126 local_symtab_ = 0;
127 enclosing_local_symtab_ = 0;
128 goto_symtab_ = 0;
129 }
130
131 /*
132 * define (def=TRUE) or look up (def=FALSE) a special compiler-defined
133 * property
134 */
135 class CTcSymProp *def_special_prop(int def, const char *name,
136 tc_prop_id *idp = 0);
137
138 /*
139 * Set the module information. This tells us the module's name (as
140 * it's given in the makefile (.t3m) or library (.tl) file) and its
141 * sequence number (an ordinal giving its position in the list of
142 * modules making up the overall program build). We use this
143 * information in generating the sourceTextGroup object.
144 */
145 void set_module_info(const char *name, int seqno);
146
147 /*
148 * Write an exported symbol file. An exported symbol file
149 * facilitates separate compilation by providing a listing of the
150 * symbols defined in another module. If module A depends on the
151 * symbols from module B, the user can first create an exported
152 * symbol file for module B, then can compile module A in the
153 * presence of B's symbol file, without actually loading B, and
154 * without manually entering a set of external definitions in module
155 * A's source code.
156 */
157 void write_symbol_file(class CVmFile *fp, class CTcMake *make_obj);
158
159 /*
160 * Seek to the start of the build configuration information in a symbol
161 * file. The return value is the number of bytes stored in the build
162 * configuration block; on return, the file object will have its seek
163 * offset set to the first byte of the build configuration data.
164 * Returns zero if the symbol file is invalid or does not contain any
165 * configuration data.
166 */
167 static ulong seek_sym_file_build_config_info(class CVmFile *fp);
168
169 /*
170 * Write the global table to an object file.
171 */
172 void write_to_object_file(class CVmFile *fp);
173
174 /*
175 * Read an object file and load it into the global symbol table. We
176 * will fill in the object and property ID translation tables
177 * provided with the translated values for the object and property
178 * symbols that we find in the object file.
179 *
180 * Returns zero on success; logs error messages and returns non-zero
181 * on error. Note that a non-zero value should be returned only
182 * when the file appears to be corrupted or an I/O error occurs;
183 * errors involving conflicting symbols, or other problems that do
184 * not prevent us from continuing to read the file in an orderly
185 * fashion, should not return failure but should simply log the
186 * error and continue; this way, we can detect any additional symbol
187 * conflicts or other errors. This routine should return failure
188 * only when it is not possible to continue reading the file.
189 */
190 int load_object_file(class CVmFile *fp,
191 const textchar_t *fname,
192 tctarg_obj_id_t *obj_xlat,
193 tctarg_prop_id_t *prop_xlat,
194 ulong *enum_xlat);
195
196 /*
197 * Apply internal object/property ID fixups. This traverses the
198 * symbol table and calls each symbol's apply_internal_fixups()
199 * method. This can be called once after loading all object files.
200 */
201 void apply_internal_fixups();
202
203 /*
204 * Read an exported symbol file. Reads the file and loads the
205 * global symbol table with the symbols in the file, with each
206 * symbol marked as external.
207 *
208 * This can be used for separate compilation. If module A depends
209 * on symbols in module B, first create a symbol file for module B,
210 * then module A can be compiled simply be pre-loading B's symbol
211 * file. Any symbol files that a module depends upon must be loaded
212 * before the module is compiled - symbol file loading must precede
213 * parsing.
214 *
215 * If any errors occur, we'll log the errors and return non-zero.
216 * We'll return zero on success.
217 */
218 int read_symbol_file(class CVmFile *fp);
219
220 /* get the global symbol table */
221 class CTcPrsSymtab *get_global_symtab() const { return global_symtab_; }
222
223 /* set the global symbol table */
224 class CTcPrsSymtab *set_global_symtab(class CTcPrsSymtab *t)
225 {
226 /* remember the old table */
227 class CTcPrsSymtab *old = global_symtab_;
228
229 /* set the new table */
230 global_symtab_ = t;
231
232 /* refresh the cache of special internal symbols */
233 cache_special_props(FALSE);
234
235 /* return the old symbol table */
236 return old;
237 }
238
239 /* get the current local symbol table */
240 class CTcPrsSymtab *get_local_symtab() const { return local_symtab_; }
241
242 /* get the 'goto' symbol table */
243 class CTcPrsSymtab *get_goto_symtab() const { return goto_symtab_; }
244
245 /* set the current pragma C mode */
246 void set_pragma_c(int mode);
247
248 /* turn preprocess expression mode on or off */
249 void set_pp_expr_mode(int f) { pp_expr_mode_ = f; }
250
251 /* get the current preprocess expression mode flag */
252 int get_pp_expr_mode() const { return pp_expr_mode_; }
253
254 /* set/get the sourceTextGroup mode */
255 void set_source_text_group_mode(int f);
256 int get_source_text_group_mode() const { return src_group_mode_; }
257
258 /* get/set the syntax-only mode flag */
259 int get_syntax_only() const { return syntax_only_; }
260 void set_syntax_only(int f) { syntax_only_ = f; }
261
262 /* get/set the debugger expression flag */
263 int is_debug_expr() const { return debug_expr_; }
264 void set_debug_expr(int f) { debug_expr_ = f; }
265
266 /*
267 * Get the constructor and finalize property ID's - all constructors
268 * and finalizers have these property ID's respectively
269 */
270 tc_prop_id get_constructor_prop() const { return constructor_prop_; }
271 tc_prop_id get_finalize_prop() const { return finalize_prop_; }
272
273 /* get the constructor property symbol */
274 class CTcSymProp *get_constructor_sym() const { return constructor_sym_; }
275
276 /* get the exported GrammarProd exported */
277 tc_prop_id get_grammarTag_prop() const;
278 tc_prop_id get_grammarInfo_prop() const;
279
280 /*
281 * Check for unresolved external symbols. Scans the global symbol
282 * table and logs an error for each unresolved external. Returns
283 * true if any unresolved externals exist, false if not.
284 */
285 int check_unresolved_externs();
286
287 /*
288 * build the dictionaries - scans the global symbol table, and
289 * inserts each object symbol's dictionary words into its
290 * corresponding dictionary
291 */
292 void build_dictionaries();
293
294 /* build the grammar productions */
295 void build_grammar_productions();
296
297 /*
298 * Top-level parser. Parse functions, objects, and other top-level
299 * definitions and declarations.
300 */
301 class CTPNStmProg *parse_top();
302
303 /*
304 * Parse a required semicolon. If the semicolon is present, we'll
305 * simply skip it. If it's missing, we'll log an error and try to
306 * resynchronize. If we find something that looks like it should go
307 * at the end of an expression, we'll try to skip up to the next
308 * semicolon; otherwise, we'll simply stay put.
309 *
310 * Returns zero if the caller should proceed, non-zero if we're at
311 * end of file, in which case there's nothing more for the caller to
312 * parse.
313 */
314 static int parse_req_sem();
315
316 /*
317 * Skip to the next semicolon, ignoring any tokens up to that point.
318 * This can be used when the caller encounters an error that makes
319 * it impossible to process the current statement further, and wants
320 * to find the next semicolon in the hope that it will be a good
321 * place to start again with the next statement.
322 *
323 * Returns zero if the caller should proceed, non-zero if we reach
324 * the end of the file.
325 */
326 static int skip_to_sem();
327
328 /*
329 * Parse an expression. This parses a top-level "comma" expression.
330 */
331 class CTcPrsNode *parse_expr();
332
333 /*
334 * Parse a condition expression. This parses a top-level "comma"
335 * expression, but displays a warning if the outermost operator in
336 * the expression is an assignment, because such expressions are
337 * very frequently meant as comparisons, but the '=' operator was
338 * inadvertantly used instead of '=='.
339 */
340 class CTcPrsNode *parse_cond_expr();
341
342 /*
343 * Parse a value expression or a double-quoted string expression
344 * (including a double-quoted string with embedded expressions). If
345 * allow_comma_expr is true, we'll parse a comma expression;
346 * otherwise, we'll parse an assignment expression. (A comma
347 * expression is broader than an assignment expression, since the
348 * comma separates assignment expressions.)
349 */
350 class CTcPrsNode *parse_expr_or_dstr(int allow_comma_expr);
351
352 /*
353 * Parse an assignment expression - this is the next precedence
354 * level down from comma expressions. In certain contexts, a
355 * top-level comma expression is not allowed because a comma has a
356 * separate meaning (in the initializer clause of a 'for' statement,
357 * for example, or in a list element).
358 */
359 class CTcPrsNode *parse_asi_expr();
360
361 /* parse an 'enum' top-level statement */
362 void parse_enum(int *err);
363
364 /* parse a 'dictionary' top-level statement */
365 class CTPNStmTop *parse_dict(int *err);
366
367 /* parse a 'grammar' top-level statement */
368 class CTPNStmTop *parse_grammar(int *err, int replace, int modify);
369
370 /* parse a grammar token list (an alternative list) */
371 void parse_gram_alts(int *err, class CTcSymObj *gram_obj,
372 class CTcGramProdEntry *prod,
373 struct CTcGramPropArrows *arrows,
374 class CTcGramAltFuncs *funcs);
375
376 /* parse and flatten a set of grammar rules */
377 class CTcPrsGramNode *flatten_gram_rule(int *err);
378
379 /* parse a 'grammar' OR node */
380 class CTcPrsGramNode *parse_gram_or(int *err, int level);
381
382 /* parse a 'grammar' CAT node */
383 class CTcPrsGramNode *parse_gram_cat(int *err, int level);
384
385 /* parse a 'grammar' qualifier int value */
386 int parse_gram_qual_int(int *err, const char *qual_name, int *stm_end);
387
388 /* skip to the end of a mal-formed grammar qualifier */
389 void parse_gram_qual_skip(int *err, int *stm_end);
390
391 /*
392 * Parse a 'function' top-level statement. If 'is_extern' is true,
393 * the function is being defined externally, so it should have no
394 * code body defined here (just the prototype). If 'replace' is
395 * true, we're replacing an existing function.
396 *
397 * If 'func_kw_present' is true, the 'function' keyword is present
398 * and must be skipped; otherwise, the function definition elides
399 * the 'function' keyword and starts directly with the function name
400 * symbol.
401 */
402 class CTPNStmTop *parse_function(int *err, int is_extern,
403 int replace, int modify,
404 int func_kw_present);
405
406 /* parse an 'intrinsic' top-level statement */
407 class CTPNStmTop *parse_intrinsic(int *err);
408
409 /* parse an 'intrinsic class' top-level statement */
410 class CTPNStmTop *parse_intrinsic_class(int *err);
411
412 /* parse an 'extern' top-level statement */
413 void parse_extern(int *err);
414
415 /*
416 * parse an object or function defintion (this is called when the
417 * first thing in a statement is a symbol; we must check what
418 * follows to determine what type of definition it is)
419 */
420 class CTPNStmTop *parse_object_or_func(int *err, int replace,
421 int suppress_error,
422 int *suppress_next_error);
423
424 /* parse a template definition statement */
425 class CTPNStmTop *parse_template_def(int *err,
426 const class CTcToken *class_tok);
427
428 /* parse a string template definition statement */
429 class CTPNStmTop *parse_string_template_def(int *err);
430
431 /* add a template definition */
432 void add_template_def(class CTcSymObj *class_sym,
433 class CTcObjTemplateItem *item_head,
434 size_t item_cnt);
435
436 /* add inherited template definitions */
437 void add_inherited_templates(class CTcSymObj *sc_sym,
438 class CTcObjTemplateItem *item_head,
439 size_t item_cnt);
440
441 /*
442 * expand the 'inherited' keyword in a template for the given
443 * superclass template and add the result to the template list for the
444 * class
445 */
446 void expand_and_add_inherited_template(class CTcSymObj *sc_sym,
447 class CTcObjTemplateItem *items,
448 class CTcObjTemplate *sc_tpl);
449
450 /*
451 * build a list of superclass templates, for expanding an 'inherited'
452 * token in a template definition
453 */
454 void build_super_template_list(struct inh_tpl_entry **list_head,
455 struct inh_tpl_entry **list_tail,
456 class CTcSymObj *sc_sym);
457
458 /* parse an 'object' statement */
459 class CTPNStmTop *parse_object_stm(int *err, int is_transient);
460
461 /*
462 * parse an object definition that starts with a '+' string; this
463 * also parses '+ property' statements
464 */
465 class CTPNStmTop *parse_plus_object(int *err);
466
467 /*
468 * Parse an object definition. If 'replace' is true, this
469 * definition is to replace a previous definition of the same
470 * object; if 'modify' is true, this definition is to modify a
471 * previous definition. If 'is_class' is true, the definition is
472 * for a class, otherwise it's for a static instance.
473 *
474 * If the definition uses the '+' notation to set the location,
475 * plus_cnt gives the number of '+' signs preceding the object
476 * definition.
477 */
478 class CTPNStmTop *parse_object(int *err, int replace, int modify,
479 int is_class, int plus_cnt,
480 int is_transient);
481
482 /* find or define an object symbol */
483 CTcSymObj *find_or_def_obj(const char *tok_txt, size_t tok_len,
484 int replace, int modify, int *is_class,
485 class CTcSymObj **mod_orig_sym,
486 class CTcSymMetaclass **meta_sym,
487 int *is_transient);
488
489 /* parse an anonymous object */
490 class CTPNStmObject *parse_anon_object(int *err, int plus_cnt,
491 int is_nested,
492 struct tcprs_term_info *term_info,
493 int is_transient);
494
495 /*
496 * Parse an object body. We start parsing from the colon that
497 * introduces the class list, and parse the class list and the
498 * property list for the object.
499 *
500 * If 'is_anon' is true, this is an anonymous object. 'obj_sym'
501 * should be null in this case.
502 *
503 * If 'is_nested' is true, this is a nested object defined in-line in
504 * an object's property list. Note that is_nested implies is_anon,
505 * since nested objects are always anonymous.
506 *
507 * If this is a 'modify' definition, 'mod_orig_tok' should be set up
508 * with the synthesized symbol for the modified base object;
509 * otherwise, 'mod_orig_tok' should be null.
510 *
511 * If 'meta_sym' is non-null, we're modifying an intrinsic class.
512 * This imposes certain restrictions; in particular, we cannot modify
513 * a method defined in the native interface to the class.
514 */
515 class CTPNStmObject *parse_object_body(
516 int *err, class CTcSymObj *obj_sym,
517 int is_class, int is_anon, int is_grammar, int is_nested,
518 int modify, class CTcSymObj *mod_orig_sym,
519 int plus_cnt, class CTcSymMetaclass *meta_sym,
520 struct tcprs_term_info *term_info, int is_transient);
521
522 /* parse an object definition's superclass list */
523 void parse_superclass_list(
524 class CTcSymObj *obj_sym, class CTPNSuperclassList &sclist);
525
526 /*
527 * Add a generated object. This is used for objects created implicitly
528 * rather than defined in the source code. For the static compiler,
529 * we'll create an anonymous object and set up its definition
530 * statements. For the dynamic compiler, we'll actually create the VM
531 * object directly.
532 */
533 class CTcSymObj *add_gen_obj(const char *clsname);
534 class CTcSymObj *add_gen_obj(class CTcSymObj *cls);
535 class CTcSymObj *add_gen_obj()
536 { return add_gen_obj((class CTcSymObj *)0); }
537
538 /* add constant property values to a generated object */
539 void add_gen_obj_prop(class CTcSymObj *obj, const char *prop, int val);
540 void add_gen_obj_prop(class CTcSymObj *obj, const char *prop,
541 const char *val);
542 void add_gen_obj_prop(class CTcSymObj *obj, const char *prop,
543 const CTcConstVal *val);
544
545 /* parse an object template instance in an object body */
546 void parse_obj_template(int *err, class CTPNObjDef *objdef, int is_inline);
547
548 /* search a superclass list for a template match */
549 const class CTcObjTemplate
550 *find_class_template(const class CTPNSuperclass *first_sc,
551 class CTcObjTemplateInst *src,
552 size_t src_cnt, const CTPNSuperclass **def_sc,
553 int *undescribed_class);
554
555 /* find a match for a given template in the given list */
556 const class CTcObjTemplate
557 *find_template_match(const class CTcObjTemplate *first_tpl,
558 class CTcObjTemplateInst *src,
559 size_t src_cnt);
560
561 /*
562 * Match a template to a given actual template parameter list. Returns
563 * true if we match, false if not. We'll fill in the actual list with
564 * the property symbols that we matched; these values are only
565 * meaningful if we return true to indicate a match.
566 */
567 int match_template(const class CTcObjTemplateItem *tpl_head,
568 class CTcObjTemplateInst *src, size_t src_cnt);
569
570 /* get the first string template */
571 class CTcStrTemplate *get_str_template_head() const
572 { return str_template_head_; }
573
574 /* parse an object's property list */
575 int parse_obj_prop_list(
576 int *err, class CTPNObjDef *objdef, class CTcSymMetaclass *meta_sym,
577 int modify, int is_nested, int braces, int is_inline,
578 struct tcprs_term_info *outer_term_info,
579 struct tcprs_term_info *term_info);
580
581 /* parse property definition within an object */
582 void parse_obj_prop(
583 int *err, class CTPNObjDef *objdef, int replace,
584 class CTcSymMetaclass *meta_sym, struct tcprs_term_info *term_info,
585 struct propset_def *propset_stack, int propset_depth,
586 int enclosing_obj_is_nested, int is_inline);
587
588 /* parse a class definition */
589 class CTPNStmTop *parse_class(int *err);
590
591 /* parse a 'modify' definition */
592 class CTPNStmTop *parse_modify(int *err);
593
594 /* parse a 'replace' definition */
595 class CTPNStmTop *parse_replace(int *err);
596
597 /* parse a 'property' statement */
598 void parse_property(int *err);
599
600 /* parse an 'export' statement */
601 void parse_export(int *err);
602
603 /* add an export for the given symbol; returns the new export record */
604 class CTcPrsExport *add_export(const char *sym, size_t sym_len);
605
606 /* add an export record to our list */
607 void add_export_to_list(class CTcPrsExport *exp);
608
609 /* get the head of the export list */
610 class CTcPrsExport *get_exp_head() const { return exp_head_; }
611
612 /* Set the parser's local_symtab */
613 void set_local_symtab(class CTcPrsSymtab *local_symtab);
614
615 /*
616 * Parse a function or method body, starting with the formal parameter
617 * list. If 'eq_before_brace' is set, we expect an '=' before the
618 * opening brace of the code body, and we allow the expression syntax,
619 * where an expression enclosed in parentheses can be used.
620 * 'self_valid' indicates whether or not 'self' is valid in the context
621 * of the code being compiled; for an object method, 'self' is usually
622 * valid, while for a stand-alone function it isn't.
623 */
624 class CTPNCodeBody *parse_code_body(int eq_before_brace, int is_obj_prop,
625 int self_valid,
626 int *p_argc, int *p_opt_argc,
627 int *p_varargs, int *p_varargs_list,
628 class CTcSymLocal **
629 p_varargs_list_local,
630 int *has_retval, int *err,
631 class CTcPrsSymtab *local_symtab,
632 tcprs_codebodytype cb_type,
633 struct propset_def *propset_stack,
634 int propset_depth,
635 struct CTcCodeBodyRef *enclosing,
636 class CTcFormalTypeList **type_list);
637
638 /* parse a nested code body (such as an anonymous function) */
639 class CTPNCodeBody *parse_nested_code_body(
640 int eq_before_brace,
641 int self_valid,
642 int *p_argc, int *p_opt_argc, int *p_varargs,
643 int *p_varargs_list, class CTcSymLocal **p_varargs_list_local,
644 int *has_retval, int *err,
645 class CTcPrsSymtab *local_symtab,
646 tcprs_codebodytype cb_type);
647
648 /* insert a propertyset expansion */
649 void insert_propset_expansion(struct propset_def *propset_stack,
650 int propset_depth);
651
652 /* parse a formal parameter list */
653 void parse_formal_list(int count_only, int opt_allowed,
654 int *argc, int *opt_argc, int *varargs,
655 int *varargs_list,
656 class CTcSymLocal **varargs_list_local,
657 int *err, int base_formal_num,
658 int for_short_anon_func,
659 class CTcFormalTypeList **type_list);
660
661 /*
662 * Parse a compound statement. If 'skip_lbrace' is true, we'll skip
663 * the opening '{', otherwise the caller must already have skipped it.
664 * If 'need_rbrace' is true, we require the block to be closed by an
665 * '}', which we'll skip before returning; otherwise, the block can end
666 * at end-of-file on the token stream.
667 *
668 * 'enclosing_symtab' is the enclosing scope's symbol table, and
669 * 'local_symtab' is the symbol table for the new scope within the
670 * compound statement; if the caller has not already allocated a new
671 * symbol table for the inner scope, it should simply pass the same
672 * value for both symbol tables.
673 *
674 * 'enclosing_switch' is the immediately enclosing switch statement, if
675 * any. This is only set when we're parsing the immediate body of a
676 * switch statement.
677 */
678 class CTPNStmComp *parse_compound(int *err,
679 int skip_lbrace, int need_rbrace,
680 class CTPNStmSwitch *enclosing_switch,
681 int use_enclosing_scope);
682
683 /* parse a local variable definition */
684 class CTPNStm *parse_local(int *err);
685
686 /* parse a local initializer */
687 class CTcPrsNode *parse_local_initializer(class CTcSymLocal *lcl,
688 int *err);
689
690 /*
691 * Parse an individual statement.
692 *
693 * If 'compound_use_enclosing_scope' is true, then if the statement
694 * is a compound statement (i.e., the current token is a left
695 * brace), the compound statement will use the current scope rather
696 * than creating its own scope. Normally, a compound statement
697 * establishes its own scope, so that local variables can hide
698 * locals and parameters defined outside the braces. In certain
699 * cases, however, locals defined within the braces should share the
700 * enclosing scope: at the top level of a function or method, for
701 * example, the formal parameters and the locals within the function
702 * body go in the same scope, so the function body's compound
703 * statement doesn't create its own scope.
704 */
705 class CTPNStm *parse_stm(int *err, class CTPNStmSwitch *enclosing_switch,
706 int compound_use_enclosing_scope);
707
708 /* parse a 'case' label */
709 class CTPNStm *parse_case(int *err,
710 class CTPNStmSwitch *enclosing_switch);
711
712 /* parse a 'default' label */
713 class CTPNStm *parse_default(int *err,
714 class CTPNStmSwitch *enclosing_switch);
715
716 /* parse an 'if' statement */
717 class CTPNStm *parse_if(int *err);
718
719 /* parse a 'return' statement */
720 class CTPNStm *parse_return(int *err);
721
722 /* parse a 'for' statement */
723 class CTPNStm *parse_for(int *err);
724
725 /* parse an 'in' clause in a 'for' statement */
726 class CTcPrsNode *parse_for_in_clause(
727 class CTcPrsNode *lval,
728 class CTPNForIn *&head, class CTPNForIn *&tail);
729
730 /* parse a 'foreach' statement */
731 class CTPNStm *parse_foreach(int *err);
732
733 /* parse a 'break' statement */
734 class CTPNStm *parse_break(int *err);
735
736 /* parse a 'continue' statement */
737 class CTPNStm *parse_continue(int *err);
738
739 /* parse a 'while' */
740 class CTPNStm *parse_while(int *err);
741
742 /* parse a 'do-while' */
743 class CTPNStm *parse_do_while(int *err);
744
745 /* parse a 'switch' */
746 class CTPNStm *parse_switch(int *err);
747
748 /* parse a 'goto' */
749 class CTPNStm *parse_goto(int *err);
750
751 /* parse a 'try' */
752 class CTPNStm *parse_try(int *err);
753
754 /* parse a 'throw' */
755 class CTPNStm *parse_throw(int *err);
756
757 /* parse an 'operator' property name */
758 int parse_op_name(class CTcToken *tok, int *op_argp = 0);
759
760 /*
761 * Create a symbol node. We'll look up the symbol in local scope.
762 * If we find the symbol in local scope, we'll return a resolved
763 * symbol node for the local scope item. If the symbol isn't
764 * defined in local scope, we'll return an unresolved symbol node,
765 * so that the symbol's resolution can be deferred until code
766 * generation.
767 */
768 class CTcPrsNode *create_sym_node(const textchar_t *sym, size_t sym_len);
769
770 /*
771 * Get the source file descriptor and line number for the current
772 * source line. We note this at the start of each statement, so
773 * that a statement node constructed when we finish parsing the
774 * statement can record the location of the start of the statement.
775 */
776 class CTcTokFileDesc *get_cur_desc() const { return cur_desc_; }
777 long get_cur_linenum() const { return cur_linenum_; }
778
779 /*
780 * Get/set the current enclosing statement. An enclosing statement
781 * is a 'try' or 'label:' container. At certain times, we need to
782 * know the current enclosing statement, or one of its enclosing
783 * statements; for example, a 'break' with a label must find the
784 * label in the enclosing statement list to know where to jump to
785 * after the 'break', and must also know about all of the enclosing
786 * 'try' blocks our to that point so that it can invoke their
787 * 'finally' blocks.
788 */
789 class CTPNStmEnclosing *get_enclosing_stm() const
790 { return enclosing_stm_; }
791 class CTPNStmEnclosing *set_enclosing_stm(class CTPNStmEnclosing *stm)
792 {
793 class CTPNStmEnclosing *old_enclosing;
794
795 /* remember the current enclosing statement for a moment */
796 old_enclosing = enclosing_stm_;
797
798 /* set the new enclosing statement */
799 enclosing_stm_ = stm;
800
801 /*
802 * return the previous enclosing statement - this allows the
803 * caller to restore the previous enclosing statement upon
804 * leaving a nested block, if that's why the caller is setting a
805 * new enclosing statement
806 */
807 return old_enclosing;
808 }
809
810 /* get the current code body reference object */
811 struct CTcCodeBodyRef *get_cur_code_body() const
812 { return cur_code_body_; }
813
814 /* determine if 'self' is valid in the current context */
815 int is_self_valid() const { return self_valid_; }
816
817 /*
818 * get/set the 'self' reference status - this indicates whether or not
819 * 'self' has been referenced, explicitly via the 'self'
820 * pseudo-variable or implicitly (such as via a property reference or
821 * method call), in the code body currently being parsed
822 */
823 int self_referenced() const { return self_referenced_; }
824 void set_self_referenced(int f) { self_referenced_ = f; }
825
826 /*
827 * get/set the full method context reference status - this indicates
828 * whether or not any of the method context variables (self,
829 * targetprop, targetobj, definingobj) have been referenced, explicitly
830 * or implicitly, in the code body currently being parsed
831 */
832 int full_method_ctx_referenced() const
833 { return full_method_ctx_referenced_; }
834 void set_full_method_ctx_referenced(int f)
835 { full_method_ctx_referenced_ = f; }
836
837 /*
838 * Get/set the flag indicating whether or not the local context of the
839 * outermost code body needs 'self'. The outer code body needs 'self'
840 * in the local context if any lexically nested code body requires
841 * access to 'self'.
842 */
843 int local_ctx_needs_self() const { return local_ctx_needs_self_; }
844 void set_local_ctx_needs_self(int f) { local_ctx_needs_self_ = f; }
845
846 /*
847 * Get/set the flag indicating whether or not the local context of the
848 * outermost code body needs the full method context stored in its
849 * local context. The outer code body needs the full context stored if
850 * any lexically nested code body requires access to any of the method
851 * context variables besides 'self' (targetprop, targetobj,
852 * definingobj).
853 */
854 int local_ctx_needs_full_method_ctx() const
855 { return local_ctx_needs_full_method_ctx_; }
856 void set_local_ctx_needs_full_method_ctx(int f)
857 { local_ctx_needs_full_method_ctx_ = f; }
858
859 /*
860 * Add a code label. This creates a 'goto' symbol table for the
861 * current code body if one doesn't already exist
862 */
863 class CTcSymLabel *add_code_label(const class CTcToken *tok);
864
865 /*
866 * Set the debugger local symbol table. Returns the previous symbol
867 * table so that it can be restored if desired.
868 */
869 class CTcPrsDbgSymtab *set_debug_symtab(class CTcPrsDbgSymtab *tab)
870 {
871 class CTcPrsDbgSymtab *old_tab;
872
873 /* remember the original for later use */
874 old_tab = debug_symtab_;
875
876 /* set the new table */
877 debug_symtab_ = tab;
878
879 /* return the original */
880 return old_tab;
881 }
882
883 /*
884 * given a (1-based) object file symbol index, get the symbol
885 */
886 class CTcSymbol *get_objfile_sym(uint idx)
887 { return (idx == 0 ? 0 : obj_sym_list_[idx - 1]); }
888
889 /*
890 * given a 1-based object file symbol index, get an object symbol;
891 * if the symbol does not refer to an object, we'll return null
892 */
893 class CTcSymObj *get_objfile_objsym(uint idx);
894
895 /*
896 * given an object file (1-based) object file dictionary index, get
897 * the dictionary entry
898 */
899 class CTcDictEntry *get_obj_dict(uint idx)
900 { return (idx == 0 ? 0 : obj_dict_list_[idx - 1]); }
901
902 /* add a dictionary object loaded from the object file */
903 void add_dict_from_obj_file(class CTcSymObj *sym);
904
905 /* add a symbol object loaded from the object file */
906 void add_sym_from_obj_file(uint idx, class CTcSymbol *sym);
907
908 /*
909 * Get the next object file symbol index. Object file symbol
910 * indices are used to relate symbols stored in the object file to
911 * the corresponding symbol object in memory when the object file is
912 * reloaded.
913 */
914 uint get_next_obj_file_sym_idx()
915 {
916 /* return the next index, consuming the index value */
917 return obj_file_sym_idx_++;
918 }
919
920 /*
921 * Get the next object file dictionary index.
922 */
923 uint get_next_obj_file_dict_idx()
924 {
925 /* return the next index, consuming the index value */
926 return obj_file_dict_idx_++;
927 }
928
929 /*
930 * add an anonymous function or other anonymous top-level statement
931 * to our list of nested top-level statements
932 */
933 void add_nested_stm(class CTPNStmTop *stm);
934
935 /* get the head of the nested statement list */
936 class CTPNStmTop *get_first_nested_stm() const
937 { return nested_stm_head_; }
938
939 /* add an anonymous object to our list */
940 void add_anon_obj(class CTcSymObj *obj);
941
942 /* add a non-symbolic object ID */
943 void add_nonsym_obj(tctarg_obj_id_t id);
944
945 /* determine if the current code body has a local context */
946 int has_local_ctx() const { return has_local_ctx_ != 0; }
947
948 /* get the local context variable number */
949 int get_local_ctx_var() const { return local_ctx_var_num_; }
950
951 /* set up a local context, in preparation for a nested code body */
952 void init_local_ctx();
953
954 /* finish the local context, after parsing a nested code body */
955 void finish_local_ctx(CTPNCodeBody *cb, class CTcPrsSymtab *local_symtab);
956
957 /*
958 * allocate a context variable index - this assigns an array index
959 * for a context variable within the context object that contains
960 * the shared locals for its scope
961 */
962 int alloc_ctx_arr_idx();
963
964 /* allocate a local for use as a local context holder */
965 int alloc_ctx_holder_var() { return alloc_local(); }
966
967 /* get the maximum number of locals required in the function */
968 int get_max_local_cnt() const { return max_local_cnt_; }
969
970 /* get the lexicalParent property symbol */
971 class CTcSymProp *get_lexical_parent_sym() const
972 { return lexical_parent_sym_; }
973
974 /*
975 * find a grammar production symbol, adding a new one if needed,
976 * returning the grammar production list entry for the object
977 */
978 class CTcGramProdEntry *declare_gramprod(const char *sym, size_t len);
979
980 /* find a grammar production list entry for a given object */
981 class CTcGramProdEntry *get_gramprod_entry(class CTcSymObj *sym);
982
983 /* find a grammar production symbol, adding a new one if needed */
984 class CTcSymObj *find_or_def_gramprod(const char *txt, size_t len,
985 class CTcGramProdEntry **entryp);
986
987 /* allocate a new enumerator ID */
988 ulong new_enum_id() { return next_enum_id_++; }
989
990 /* get the number of enumerator ID's allocated */
991 ulong get_enum_count() const { return next_enum_id_; }
992
993 /*
994 * Look up a property symbol, adding it if not yet defined. If the
995 * symbol is defined as another type, we'll show an error if
996 * show_err is true, and return null.
997 */
998 CTcSymProp *look_up_prop(const class CTcToken *tok, int show_err);
999
1000 /* get the '+' property for tracking the location graph */
1001 CTcSymProp *get_plus_prop() const { return plus_prop_; }
1002
1003 /*
1004 * Read a length-prefixed string from a file. Copies the string into
1005 * tokenizer space (which is guaranteed valid throughout compilation),
1006 * and returns a pointer to the tokenizer copy. If ret_len is null,
1007 * we'll return a null-terminated string; otherwise, we'll return a
1008 * non-null-terminated string and set *ret_len to the length of the
1009 * string.
1010 *
1011 * The string must fit in the temporary buffer to be read, but the
1012 * permanent tokenizer copy is returned rather than the temp buffer.
1013 * If the string doesn't fit in the temp buffer (with null
1014 * termination, if null termination is requested), we'll log the given
1015 * error.
1016 */
1017 static const char *read_len_prefix_str
1018 (CVmFile *fp, char *tmp_buf, size_t tmp_buf_len, size_t *ret_len,
1019 int err_if_too_long);
1020
1021 /*
1022 * Read a length-prefixed string into the given buffer, null
1023 * terminating the result. If the string is too long for the buffer,
1024 * we'll flag the given error code and return non-zero. If
1025 * successful, we'll return zero.
1026 */
1027 static int read_len_prefix_str(CVmFile *fp, char *buf, size_t buf_len,
1028 int err_if_too_long);
1029
1030
1031 /* get the miscVocab property symbol */
1032 tctarg_prop_id_t get_miscvocab_prop() const { return miscvocab_prop_; }
1033
1034 /* property symbols for the operator overload properties */
1035 class CTcSymProp *ov_op_add_;
1036 class CTcSymProp *ov_op_sub_;
1037 class CTcSymProp *ov_op_mul_;
1038 class CTcSymProp *ov_op_div_;
1039 class CTcSymProp *ov_op_mod_;
1040 class CTcSymProp *ov_op_xor_;
1041 class CTcSymProp *ov_op_shl_;
1042 class CTcSymProp *ov_op_ashr_;
1043 class CTcSymProp *ov_op_lshr_;
1044 class CTcSymProp *ov_op_bnot_;
1045 class CTcSymProp *ov_op_bor_;
1046 class CTcSymProp *ov_op_band_;
1047 class CTcSymProp *ov_op_neg_;
1048 class CTcSymProp *ov_op_idx_;
1049 class CTcSymProp *ov_op_setidx_;
1050
1051 /* embedded expression token capture list */
1052 class CTcEmbedTokenList *embed_toks_;
1053
1054 private:
1055 /* cache the special properties, defining them if desired */
1056 void cache_special_props(int def);
1057
1058 /*
1059 * Static compiler handling for object generation. These are
1060 * implemented only in the static compiler; they're stubbed out for the
1061 * dynamic compiler, because the dynamic compiler generates objects in
1062 * the live VM through the G_vmifc interface instead.
1063 */
1064 CTcSymObj *add_gen_obj_stat(class CTcSymObj *cls);
1065 void add_gen_obj_prop_stat(class CTcSymObj *obj, class CTcSymProp *prop,
1066 const CTcConstVal *val);
1067
1068 /* clear the anonymous function local context information */
1069 void clear_local_ctx();
1070
1071 /*
1072 * begin a property expression, saving parser state for later
1073 * restoration with finish_prop_expr
1074 */
1075 void begin_prop_expr(
1076 class CTcPrsPropExprSave *save_info, int is_static, int is_inline);
1077
1078 /*
1079 * Finish a property expression, wrapping it in a code body if
1080 * necessary to allow for an embedded anonymous function. Returns
1081 * null if no wrapping is required, in which case the original
1082 * expression should continue to be used, or the non-null code body
1083 * wrapper if needed, in which case the original expression should be
1084 * discarded in favor of the fully wrapped code body.
1085 */
1086 void finish_prop_expr(
1087 class CTcPrsPropExprSave *save_info, class CTcPrsNode* &expr,
1088 class CTPNCodeBody* &code_body, class CTPNAnonFunc* &inline_method,
1089 int is_static, int is_inline, class CTcSymProp *prop_sym);
1090
1091 /*
1092 * callback for symbol table enumeration for writing a symbol export
1093 * file
1094 */
1095 static void write_sym_cb(void *ctx, class CTcSymbol *sym);
1096
1097 /* callback for symbol table enumeration for writing an object file */
1098 static void write_obj_cb(void *ctx, class CTcSymbol *sym);
1099
1100 /* callback for symbol table enumeration for writing cross references */
1101 static void write_obj_ref_cb(void *ctx, class CTcSymbol *sym);
1102
1103 /* callback for symbol table enumeration for named grammar rules */
1104 static void write_obj_gram_cb(void *ctx, class CTcSymbol *sym);
1105
1106 /* callback for symbol table enumeration for merging grammar rules */
1107 static void build_grammar_cb(void *ctx, class CTcSymbol *sym);
1108
1109
1110 /*
1111 * Enter a scope. Upon entering, we'll remember the current local
1112 * variable data; on leaving, we'll restore the enclosing scope.
1113 */
1114 void enter_scope(struct tcprs_scope_t *info)
1115 {
1116 /* remember the current scope information */
1117 info->local_symtab = local_symtab_;
1118 info->enclosing_symtab = enclosing_local_symtab_;
1119 info->local_cnt = local_cnt_;
1120
1121 /*
1122 * We haven't yet allocated a symbol table local to the new
1123 * scope -- we defer this until we actually need to insert a
1124 * symbol into the new scope. In order to detect when we need
1125 * to create our own local symbol table, we keep track of the
1126 * enclosing symbol table; when the local table is the same as
1127 * the enclosing table, and we need to insert a symbol, it means
1128 * that we must create a new table for the current scope.
1129 */
1130 enclosing_local_symtab_ = local_symtab_;
1131 }
1132
1133 /* leave a scope */
1134 void leave_scope(struct tcprs_scope_t *info)
1135 {
1136 /* restore enclosing scope information */
1137 local_symtab_ = info->local_symtab;
1138 enclosing_local_symtab_ = info->enclosing_symtab;
1139
1140 /* return to the local count in the enclosing scope */
1141 // $$$ we can't actually do this because variables could
1142 // be allocated after this scope ends, but need lifetimes
1143 // that overlap with the enclosed scope; what we actually
1144 // need to do, if we wanted to optimize things, would be
1145 // to allow this block of variables to be used in *disjoint*
1146 // scopes, but not again in enclosing scopes. We can easily,
1147 // though suboptimally, handle this by simply not allowing
1148 // the variables in the enclosed scope to be re-used at all
1149 // in the current code block.
1150 // local_cnt_ = info->local_cnt;
1151 }
1152
1153 /*
1154 * Create a local symbol table in the current scope, if necessary.
1155 * If we've already created a local symbol table for the current
1156 * scope, this has no effect.
1157 */
1158 void create_scope_local_symtab();
1159
1160 /* allocate a new local variable ID */
1161 int alloc_local()
1162 {
1163 /*
1164 * if this exceeds the maximum depth in the block so far, note
1165 * the new maximum depth
1166 */
1167 if (local_cnt_ + 1 > max_local_cnt_)
1168 max_local_cnt_ = local_cnt_ + 1;
1169
1170 /* return the local number, and increment the counter */
1171 return local_cnt_++;
1172 }
1173
1174 /* find a dictionary symbol, adding a new one if needed */
1175 class CTcDictEntry *declare_dict(const char *sym, size_t len);
1176
1177 /* create a new dictionary list entry */
1178 class CTcDictEntry *create_dict_entry(class CTcSymObj *sym);
1179
1180 /* find a dictionary list entry for a given object */
1181 class CTcDictEntry *get_dict_entry(class CTcSymObj *sym);
1182
1183 /* create a new grammar production list entry */
1184 class CTcGramProdEntry *create_gramprod_entry(class CTcSymObj *sym);
1185
1186 /* symbol enumerator - look for unresolved external references */
1187 static void enum_sym_extref(void *ctx, class CTcSymbol *sym);
1188
1189 /* symbol enumerator - apply internal fixups */
1190 static void enum_sym_internal_fixup(void *ctx, class CTcSymbol *sym);
1191
1192 /* symbol enumerator - build dictionary */
1193 static void enum_sym_dict(void *ctx, class CTcSymbol *sym);
1194
1195 /* enumeration callback - context local conversion */
1196 static void enum_for_ctx_locals(void *ctx, class CTcSymbol *sym);
1197
1198 /* global symbol table */
1199 class CTcPrsSymtab *global_symtab_;
1200
1201 /* the constructor property ID and symbol */
1202 tc_prop_id constructor_prop_;
1203 class CTcSymProp *constructor_sym_;
1204
1205 /* the finalizer property ID */
1206 tc_prop_id finalize_prop_;
1207
1208 /* grammarInfo property symbol */
1209 class CTcSymProp *graminfo_prop_;
1210
1211 /* grammarTag property symbol */
1212 class CTcSymProp *gramtag_prop_;
1213
1214 /* miscVocab property ID */
1215 tctarg_prop_id_t miscvocab_prop_;
1216
1217 /* lexicalParent property symbol */
1218 class CTcSymProp *lexical_parent_sym_;
1219
1220 /* sourceTextOrder property symbol */
1221 class CTcSymProp *src_order_sym_;
1222
1223 /* sourceTextGroup property symbol */
1224 class CTcSymProp *src_group_sym_;
1225
1226 /* sourceTextGroupName, sourceTextGroupOrder */
1227 class CTcSymProp *src_group_mod_sym_;
1228 class CTcSymProp *src_group_seq_sym_;
1229
1230 /*
1231 * Source text order index. Each time we encounter an object
1232 * definition in the source code, we assign the current index value to
1233 * the object's 'sourceTextOrder' property, then we increment the
1234 * index. This provides the game program with information on the order
1235 * in which static objects appear in the source code, so that the
1236 * program can sort a collection of objects into their source file
1237 * order if desired.
1238 */
1239 long src_order_idx_;
1240
1241 /*
1242 * Source group object. If we're assigning source text group values,
1243 * we create an object for each source module to identify the module.
1244 */
1245 tctarg_obj_id_t src_group_id_;
1246
1247 /*
1248 * flag: in preprocessor constant expression mode; double-quoted
1249 * strings should be treated the same as single-quoted strings for
1250 * concatenation and comparisons
1251 */
1252 uint pp_expr_mode_ : 1;
1253
1254 /*
1255 * Is source text mode turned on? If this is true, we'll generate
1256 * sourceTextGroup properties for objects, otherwise we won't.
1257 */
1258 uint src_group_mode_ : 1;
1259
1260 /*
1261 * Flag: syntax-only mode. We use this mode to analyze the syntax
1262 * of the file without building the image; this is used, for
1263 * example, to build the exported symbol file for a source file. In
1264 * this mode, we'll suppress certain warnings and avoid doing work
1265 * that's not necessary for syntactic analysis; for example, we
1266 * won't show "unreachable code" errors.
1267 */
1268 uint syntax_only_ : 1;
1269
1270 /*
1271 * Flag: debugger expression mode. We accept some special internal
1272 * syntax in this mode that's not allowed in ordinary source code.
1273 */
1274 uint debug_expr_ : 1;
1275
1276 /*
1277 * Code block parsing state
1278 */
1279
1280 /*
1281 * 'goto' symbol table for the current code block - there's only one
1282 * 'goto' scope for an entire code block, so this never changes over
1283 * the course of a code block
1284 */
1285 class CTcPrsSymtab *goto_symtab_;
1286
1287 /*
1288 * Current local symbol table. Each inner scope that defines its
1289 * own local variables has its own local symbol table, nested within
1290 * the enclosing scope's. When leaving an inner scope, this should
1291 * always be restored to the local symbol table of the enclosing
1292 * scope.
1293 */
1294 class CTcPrsSymtab *local_symtab_;
1295
1296 /*
1297 * Enclosing local symbol table. If this is the same as
1298 * local_symtab_, it means that the current scope has not yet
1299 * created its own local symbol table. We defer this creation until
1300 * we find we actually need a local symbol table in a scope, since
1301 * most scopes don't define any of their own local variables.
1302 */
1303 class CTcPrsSymtab *enclosing_local_symtab_;
1304
1305 /*
1306 * Current debugger local symbol table. When we're compiling a
1307 * debugger expression, this will provide access to the current
1308 * local scope in the debug records.
1309 */
1310 class CTcPrsDbgSymtab *debug_symtab_;
1311
1312 /*
1313 * Number of local variables allocated so far in current code block
1314 * -- this reflects nesting to the current innermost scope, because
1315 * variables in inner scope are allocated in the same stack frame as
1316 * the enclosing scopes. When leaving an inner scope, this should
1317 * be restored
1318 */
1319 int local_cnt_;
1320
1321 /*
1322 * maximum local variable depth for the current code block -- this
1323 * reflects the maximum depth, including all inner scopes so far
1324 */
1325 int max_local_cnt_;
1326
1327 /*
1328 * Enclosing statement - this is the innermost 'try' or 'label:'
1329 * enclosing the current code.
1330 */
1331 class CTPNStmEnclosing *enclosing_stm_;
1332
1333 /* file descriptor and line number at start of current statement */
1334 class CTcTokFileDesc *cur_desc_;
1335 long cur_linenum_;
1336
1337 /* currently active dictionary */
1338 class CTcDictEntry *dict_cur_;
1339
1340 /* head and tail of dictionary list */
1341 class CTcDictEntry *dict_head_;
1342 class CTcDictEntry *dict_tail_;
1343
1344 /* head and tail of grammar production entry list */
1345 class CTcGramProdEntry *gramprod_head_;
1346 class CTcGramProdEntry *gramprod_tail_;
1347
1348 /*
1349 * array of symbols loaded from the object file - these are indexed
1350 * by the object file symbol index stored in symbol references in
1351 * the object file, allowing us to fix up references from one symbol
1352 * to another during loading
1353 */
1354 class CTcSymbol **obj_sym_list_;
1355
1356 /*
1357 * array of dictionary objects for the object file being loaded -
1358 * these are indexed by the dictionary index stored in symbol
1359 * references in the object file, allowing us to fix up references
1360 * from an object to its dictionary
1361 */
1362 class CTcDictEntry **obj_dict_list_;
1363
1364 /* next available object file dictionary index */
1365 uint obj_file_dict_idx_;
1366
1367 /* next available object file symbol index */
1368 uint obj_file_sym_idx_;
1369
1370 /* dictionary property list head */
1371 class CTcDictPropEntry *dict_prop_head_;
1372
1373 /*
1374 * Head and tail of list of nested top-level statements parsed for the
1375 * current top-level statement. This list includes anonymous
1376 * functions and nested objects, since these statements must
1377 * ultimately be linked into the top-level statement queue, but can't
1378 * be linked in while they're being parsed because of their nested
1379 * location in the recursive descent. We'll throw each new nested
1380 * top-level statement into this list as we parse them, then add this
1381 * list to the top-level statement list when we're done with the
1382 * entire program.
1383 */
1384 class CTPNStmTop *nested_stm_head_;
1385 class CTPNStmTop *nested_stm_tail_;
1386
1387 /*
1388 * Anonymous object list. This is a list of objects which are
1389 * defined without symbol names.
1390 */
1391 class CTcSymObj *anon_obj_head_;
1392 class CTcSymObj *anon_obj_tail_;
1393
1394 /*
1395 * Non-symbolic object list. This is a list of objects that are
1396 * defined without symbols at all.
1397 */
1398 struct tcprs_nonsym_obj *nonsym_obj_head_;
1399 struct tcprs_nonsym_obj *nonsym_obj_tail_;
1400
1401 /*
1402 * Object template list - this is the master list of templates for the
1403 * root object class.
1404 */
1405 class CTcObjTemplate *template_head_;
1406 class CTcObjTemplate *template_tail_;
1407
1408 /*
1409 * Object template instance parsing expression array. Each time we
1410 * define a new template, we'll make sure this array is long enough
1411 * for the longest defined template. We use this list when we're
1412 * parsing a template instance to keep track of the expressions in
1413 * the template instance - we can't know until we have the entire
1414 * list which template we're using, so we must keep track of the
1415 * entire list until we reach the end of the list.
1416 */
1417 class CTcObjTemplateInst *template_expr_;
1418 size_t template_expr_max_;
1419
1420 /*
1421 * String template list. String templates are unrelated to object
1422 * templates; these are for custom syntax in << >> expressions in
1423 * strings.
1424 */
1425 class CTcStrTemplate *str_template_head_;
1426 class CTcStrTemplate *str_template_tail_;
1427
1428 /* head and tail of exported symbol list */
1429 class CTcPrsExport *exp_head_;
1430 class CTcPrsExport *exp_tail_;
1431
1432 /*
1433 * Flag: current code body has a local variable context object. If
1434 * this is set, we must generate code that sets up the context
1435 * object on entry to the code body.
1436 */
1437 unsigned int has_local_ctx_ : 1;
1438
1439 /* local variable number of the code body's local variable context */
1440 int local_ctx_var_num_;
1441
1442 /* array of context variable property values */
1443 tctarg_prop_id_t *ctx_var_props_;
1444
1445 /* size of array */
1446 size_t ctx_var_props_size_;
1447
1448 /* number of context variable property values in the list */
1449 size_t ctx_var_props_cnt_;
1450
1451 /*
1452 * number of context variable property values assigned to the
1453 * current code body
1454 */
1455 size_t ctx_var_props_used_;
1456
1457 /* next available local variable context index */
1458 int next_ctx_arr_idx_;
1459
1460 /* reference to the current code body being parsed */
1461 CTcCodeBodyRef *cur_code_body_;
1462
1463 /* flag: 'self' is valid in current code body */
1464 int self_valid_;
1465
1466 /*
1467 * flag: 'self' is used (explicitly or implicitly, such as via a
1468 * property reference or method call) in the current code body
1469 */
1470 int self_referenced_;
1471
1472 /*
1473 * Flag: method context beyond 'self' (targetprop, targetobj,
1474 * definingobj) is referenced (explicitly or implicitly, such as via
1475 * 'inherited' or 'delegated') in the current code body.
1476 */
1477 int full_method_ctx_referenced_;
1478
1479 /*
1480 * Flags: the local context of the outermost code body requires
1481 * 'self'/the full method context to be stored.
1482 */
1483 int local_ctx_needs_self_;
1484 int local_ctx_needs_full_method_ctx_;
1485
1486 /* next available enumerator ID */
1487 ulong next_enum_id_;
1488
1489 /*
1490 * The '+' property - this is the property that defines the
1491 * containment graph for the purposes of the '+' syntax.
1492 */
1493 class CTcSymProp *plus_prop_;
1494
1495 /*
1496 * '+' property location stack. Each time the program defines an
1497 * object using the '+' notation to set the location, we'll update our
1498 * record here of the last object at that depth. Any time an object
1499 * is defined at depth N (i.e., using N '+' signs), its location is
1500 * set to the last object at depth N-1. An object with no '+' signs
1501 * is at depth zero.
1502 */
1503 class CTPNStmObject **plus_stack_;
1504 size_t plus_stack_alloc_;
1505
1506 /*
1507 * The module name and sequence number, if known. The module name is
1508 * the name as it appears on the command line, makefile (.t3m), or
1509 * library (.tl) file. The sequence number is an ordinal giving its
1510 * position in the list of modules making up the overall program build.
1511 * We use this information in generating the sourceTextGroup object.
1512 */
1513 char *module_name_;
1514 int module_seqno_;
1515 };
1516
1517
1518 /* ------------------------------------------------------------------------ */
1519 /*
1520 * Grammar tree parser - property arrow list
1521 */
1522 struct CTcGramPropArrows
1523 {
1524 CTcGramPropArrows() { cnt = 0; }
1525
1526 /* maximum number of arrows */
1527 static const size_t max_arrows = 100;
1528
1529 /* array of property arrows */
1530 class CTcSymProp *prop[max_arrows];
1531
1532 /* number of arrows */
1533 size_t cnt;
1534 };
1535
1536 /* ------------------------------------------------------------------------ */
1537 /*
1538 * Grammar tree parser - compiler interface functions. We abstract a
1539 * number of functions from the compiler interface to allow for differences
1540 * in behavior between regular static compilation and run-time construction
1541 * of grammar rules.
1542 */
1543 class CTcGramAltFuncs
1544 {
1545 public:
1546 /* look up a property symbol, defining it if it's undefined */
1547 virtual class CTcSymProp *look_up_prop(
1548 const class CTcToken *tok, int show_err) = 0;
1549
1550 /* declare a grammar production symbol */
1551 virtual class CTcGramProdEntry *declare_gramprod(
1552 const char *txt, size_t len) = 0;
1553
1554 /* check the given enum for use as a production token */
1555 virtual void check_enum_tok(class CTcSymEnum *enumsym) = 0;
1556
1557 /* handle EOF in an alternative list */
1558 virtual void on_eof(int *err) = 0;
1559 };
1560
1561
1562 /* ------------------------------------------------------------------------ */
1563 /*
1564 * Grammar tree node - base class
1565 */
1566 class CTcPrsGramNode: public CTcTokenSource
1567 {
1568 public:
1569 CTcPrsGramNode()
1570 {
1571 /* we have no siblings yet */
1572 next_ = 0;
1573 }
1574
1575 /* get the next token - does nothing by default */
1576 virtual const CTcToken *get_next_token() { return 0; }
1577
1578 /* consolidate OR nodes at the top of the subtree */
1579 virtual CTcPrsGramNode *consolidate_or() = 0;
1580
1581 /* flatten CAT nodes together in the tree */
1582 virtual void flatten_cat() { /* by default, do nothing */ }
1583
1584 /* am I an "or" node? */
1585 virtual int is_or() { return FALSE; }
1586
1587 /* am I a "cat" node? */
1588 virtual int is_cat() { return FALSE; }
1589
1590 /* get my token - if I'm not a token node, returns null */
1591 virtual const CTcToken *get_tok() const { return 0; }
1592
1593 /* initialize expansion - by default, we do nothing */
1594 virtual void init_expansion() { }
1595
1596 /*
1597 * Advance to the next expansion state. Returns true if we 'carry' out
1598 * of the current item, which means that we were already at our last
1599 * state and hence are wrapping back to our first state. Returns false
1600 * if we advanced to a new state without wrapping back.
1601 *
1602 * By default, since normal items have only one alternative, we don't
1603 * do anything but return a 'carry, since each advance takes us back to
1604 * our single and initial state.
1605 */
1606 virtual int advance_expansion() { return TRUE; }
1607
1608 /* clone the current expansion subtree */
1609 virtual CTcPrsGramNode *clone_expansion() const = 0;
1610
1611 /* next sibling node */
1612 CTcPrsGramNode *next_;
1613 };
1614
1615
1616
1617 /* ------------------------------------------------------------------------ */
1618 /*
1619 * Statement termination information. This is used for certain nested
1620 * definition parsers, where a lack of termination in the nested
1621 * definition is to be interpreted as being actually caused by a lack of
1622 * termination of the enclosing definition.
1623 */
1624 struct tcprs_term_info
1625 {
1626 /* initialize */
1627 void init(class CTcTokFileDesc *desc, long linenum)
1628 {
1629 /* remember the current location */
1630 desc_ = desc;
1631 linenum_ = linenum;
1632
1633 /* no termination error yet */
1634 unterm_ = FALSE;
1635 }
1636
1637 /*
1638 * source location where original terminator might have been - this is
1639 * where we decided to go into a nested definition, so if it turns out
1640 * that the definintion shouldn't have been nested after all, there
1641 * was missing termination here
1642 */
1643 class CTcTokFileDesc *desc_;
1644 long linenum_;
1645
1646 /*
1647 * flag: termination was in fact missing in the nested definition; the
1648 * nested parser sets this to relay the problem to the caller
1649 */
1650 int unterm_;
1651 };
1652
1653 /* ------------------------------------------------------------------------ */
1654 /*
1655 * Object template list entry
1656 */
1657 class CTcObjTemplate
1658 {
1659 public:
1660 CTcObjTemplate(class CTcObjTemplateItem *item_head, size_t item_cnt)
1661 {
1662 /* remember my item list */
1663 items_ = item_head;
1664 item_cnt_ = item_cnt;
1665
1666 /* not in a list yet */
1667 nxt_ = 0;
1668 }
1669
1670 /* head of list of template items */
1671 class CTcObjTemplateItem *items_;
1672
1673 /* number of items in the list */
1674 size_t item_cnt_;
1675
1676 /* next template in master list of templates */
1677 CTcObjTemplate *nxt_;
1678 };
1679
1680 /*
1681 * Object template list item
1682 */
1683 class CTcObjTemplateItem
1684 {
1685 public:
1686 CTcObjTemplateItem(class CTcSymProp *prop, tc_toktyp_t tok_type,
1687 int is_alt, int is_opt)
1688 {
1689 /* remember my defining information */
1690 prop_ = prop;
1691 tok_type_ = tok_type;
1692 is_alt_ = is_alt;
1693 is_opt_ = is_opt;
1694
1695 /* not in a list yet */
1696 nxt_ = 0;
1697 }
1698
1699 /* property that the item in this position defines */
1700 class CTcSymProp *prop_;
1701
1702 /* token type of item in this position */
1703 tc_toktyp_t tok_type_;
1704
1705 /* next item in this template's item list */
1706 CTcObjTemplateItem *nxt_;
1707
1708 /* flag: this item is an alternative to the previous item */
1709 unsigned int is_alt_ : 1;
1710
1711 /* flag: this item is optional */
1712 unsigned int is_opt_ : 1;
1713 };
1714
1715 /*
1716 * Template item instance - we keep track of the actual parameters to a
1717 * template with these items.
1718 */
1719 class CTcObjTemplateInst
1720 {
1721 public:
1722 /*
1723 * expression value for the actual parameter, as either a naked
1724 * expression (expr_) or as a code body (code_body_) - only one of
1725 * expr_ or code_body_ will be valid
1726 */
1727 class CTcPrsNode *expr_;
1728 class CTPNCodeBody *code_body_;
1729 class CTPNAnonFunc *inline_method_;
1730
1731 /*
1732 * the introductory token of the parameter - if the parameter is
1733 * introduced by an operator token, this will not be part of the
1734 * expression
1735 */
1736 tc_toktyp_t def_tok_;
1737
1738 /* the first token of the value */
1739 CTcToken expr_tok_;
1740
1741 /*
1742 * The property to which to assign this actual parameter value. This
1743 * isn't filled in until we match the full list to an actual template,
1744 * since we don't know the meanings of the parameters until we match
1745 * the actuals to an existing template in memory.
1746 */
1747 class CTcSymProp *prop_;
1748 };
1749
1750 /* ------------------------------------------------------------------------ */
1751 /*
1752 * 'propertyset' definition structure. Each property set defines a
1753 * property pattern and an optional argument list for the properties within
1754 * the propertyset group.
1755 */
1756 struct propset_def
1757 {
1758 /* the property name pattern */
1759 const char *prop_pattern;
1760 size_t prop_pattern_len;
1761
1762 /* head of list of tokens in the parameter list */
1763 struct propset_tok *param_tok_head;
1764 };
1765
1766 /*
1767 * propertyset token list entry
1768 */
1769 struct propset_tok
1770 {
1771 propset_tok(const CTcToken *t)
1772 {
1773 /* copy the token */
1774 this->tok = *t;
1775
1776 /* we're not in a list yet */
1777 nxt = 0;
1778 }
1779
1780 /* the token */
1781 CTcToken tok;
1782
1783 /* next token in the list */
1784 propset_tok *nxt;
1785 };
1786
1787 /*
1788 * Token source for parsing formal parameters using property set formal
1789 * lists. This retrieves tokens from a propertyset stack.
1790 */
1791 class propset_token_source: public CTcTokenSource
1792 {
1793 public:
1794 propset_token_source()
1795 {
1796 /* nothing in our list yet */
1797 nxt_tok = last_tok = 0;
1798 }
1799
1800 /* get the next token */
1801 virtual const CTcToken *get_next_token()
1802 {
1803 /* if we have another entry in our list, retrieve it */
1804 if (nxt_tok != 0)
1805 {
1806 /* remember the token to return */
1807 CTcToken *ret = &nxt_tok->tok;
1808
1809 /* advance our internal position to the next token */
1810 nxt_tok = nxt_tok->nxt;
1811
1812 /* return the token */
1813 return ret;
1814 }
1815 else
1816 {
1817 /* we have nothing more to return */
1818 return 0;
1819 }
1820 }
1821
1822 /* insert a token */
1823 void insert_token(const CTcToken *tok);
1824
1825 /* insert a token based on type */
1826 void insert_token(tc_toktyp_t typ, const char *txt, size_t len);
1827
1828 /* the next token we're to retrieve */
1829 propset_tok *nxt_tok;
1830
1831 /* tail of our list */
1832 propset_tok *last_tok;
1833 };
1834
1835 /* maximum propertyset nesting depth */
1836 const size_t MAX_PROPSET_DEPTH = 10;
1837
1838
1839
1840 /* ------------------------------------------------------------------------ */
1841 /*
1842 * String template entry. A string template defines custom syntax for
1843 * embedded << >> expressions in strings.
1844 */
1845 class CTcStrTemplate
1846 {
1847 public:
1848 CTcStrTemplate()
1849 {
1850 /* initially clear the token list */
1851 head = tail = 0;
1852 cnt = 0;
1853 star = FALSE;
1854
1855 /* no function symbol yet */
1856 func = 0;
1857
1858 /* not in the global list yet */
1859 nxt = 0;
1860 }
1861
1862 /* append a token to the list */
1863 void append_tok(const CTcToken *tok);
1864
1865 /* the token list */
1866 CTcTokenEle *head, *tail;
1867
1868 /* number of tokens in the list */
1869 int cnt;
1870
1871 /* do we have a '*' token? */
1872 int star;
1873
1874 /* the processor function symbol */
1875 class CTcSymFunc *func;
1876
1877 /* next list element */
1878 CTcStrTemplate *nxt;
1879 };
1880
1881 /* ------------------------------------------------------------------------ */
1882 /*
1883 * Non-symbolic object list entry
1884 */
1885 struct tcprs_nonsym_obj
1886 {
1887 tcprs_nonsym_obj(tctarg_obj_id_t id)
1888 {
1889 /* remember the ID */
1890 id_ = id;
1891
1892 /* not in a list yet */
1893 nxt_ = 0;
1894 }
1895
1896 /* ID of this object */
1897 tctarg_obj_id_t id_;
1898
1899 /* next entry in the list */
1900 tcprs_nonsym_obj *nxt_;
1901 };
1902
1903 /* ------------------------------------------------------------------------ */
1904 /*
1905 * Dictionary property list entry. Each time the source code defines a
1906 * dictionary property, we'll make an entry in this list.
1907 */
1908 class CTcDictPropEntry
1909 {
1910 public:
1911 CTcDictPropEntry(class CTcSymProp *prop)
1912 {
1913 /* remember the property */
1914 prop_ = prop;
1915
1916 /* not in a list yet */
1917 nxt_ = 0;
1918
1919 /* not defined for current object yet */
1920 defined_ = FALSE;
1921 }
1922
1923 /* my property */
1924 class CTcSymProp *prop_;
1925
1926 /* next entry in list */
1927 CTcDictPropEntry *nxt_;
1928
1929 /* flag: the current object definition includes this property */
1930 unsigned int defined_ : 1;
1931 };
1932
1933 /* ------------------------------------------------------------------------ */
1934 /*
1935 * Dictionary list entry. Each dictionary object gets an entry in this
1936 * list.
1937 */
1938 class CTcDictEntry
1939 {
1940 public:
1941 CTcDictEntry(class CTcSymObj *sym);
1942
1943 /* get/set my object file index */
1944 uint get_obj_idx() const { return obj_idx_; }
1945 void set_obj_idx(uint idx) { obj_idx_ = idx; }
1946
1947 /* get my object symbol */
1948 class CTcSymObj *get_sym() const { return sym_; }
1949
1950 /* get/set the next item in the list */
1951 CTcDictEntry *get_next() const { return nxt_; }
1952 void set_next(CTcDictEntry *nxt) { nxt_ = nxt; }
1953
1954 /* add a word to the table */
1955 void add_word(const char *txt, size_t len, int copy,
1956 tc_obj_id obj, tc_prop_id prop);
1957
1958 /* write my symbol to the object file if I haven't already done so */
1959 void write_sym_to_obj_file(CVmFile *fp);
1960
1961 /* get the hash table */
1962 class CVmHashTable *get_hash_table() const { return hashtab_; }
1963
1964 protected:
1965 /* enumeration callback - write to object file */
1966 static void enum_cb_writeobj(void *ctx, class CVmHashEntry *entry);
1967
1968 /* associated object symbol */
1969 class CTcSymObj *sym_;
1970
1971 /*
1972 * object file index (we use this to match up the dictionary objects
1973 * when we re-load the object file)
1974 */
1975 uint obj_idx_;
1976
1977 /* next item in the dictionary list */
1978 CTcDictEntry *nxt_;
1979
1980 /* hash table containing the word entries */
1981 class CVmHashTable *hashtab_;
1982 };
1983
1984
1985 /*
1986 * entry in a dictionary list
1987 */
1988 struct CTcPrsDictItem
1989 {
1990 CTcPrsDictItem(tc_obj_id obj, tc_prop_id prop)
1991 {
1992 obj_ = obj;
1993 prop_ = prop;
1994 nxt_ = 0;
1995 }
1996
1997 /* object */
1998 tc_obj_id obj_;
1999
2000 /* property */
2001 tc_prop_id prop_;
2002
2003 /* next entry in list */
2004 CTcPrsDictItem *nxt_;
2005 };
2006
2007 /*
2008 * Parser dictionary hash table entry
2009 */
2010 class CVmHashEntryPrsDict: public CVmHashEntryCS
2011 {
2012 public:
2013 CVmHashEntryPrsDict(const char *txt, size_t len, int copy)
2014 : CVmHashEntryCS(txt, len, copy)
2015 {
2016 /* nothing in my list yet */
2017 list_ = 0;
2018 }
2019
2020 /* add an item to my list */
2021 void add_item(tc_obj_id obj, tc_prop_id prop);
2022
2023 /* get the list head */
2024 struct CTcPrsDictItem *get_list() const { return list_; }
2025
2026 protected:
2027 /* list of object/property associations with this word */
2028 struct CTcPrsDictItem *list_;
2029 };
2030
2031 /* ------------------------------------------------------------------------ */
2032 /*
2033 * Grammar production list entry
2034 */
2035 class CTcGramProdEntry
2036 {
2037 public:
2038 CTcGramProdEntry(class CTcSymObj *prod_obj);
2039
2040 /* get my production object symbol */
2041 class CTcSymObj *get_prod_sym() const { return prod_sym_; }
2042
2043 /* get/set the next item in the list */
2044 CTcGramProdEntry *get_next() const { return nxt_; }
2045 void set_next(CTcGramProdEntry *nxt) { nxt_ = nxt; }
2046
2047 /* add an alternative */
2048 void add_alt(class CTcGramProdAlt *alt);
2049
2050 /* get the alternative list head */
2051 class CTcGramProdAlt *get_alt_head() const { return alt_head_; }
2052
2053 /* write to an object file */
2054 void write_to_obj_file(class CVmFile *fp);
2055
2056 /* load from an object file */
2057 static void load_from_obj_file(class CVmFile *fp,
2058 const tctarg_prop_id_t *prop_xlat,
2059 const ulong *enum_xlat,
2060 class CTcSymObj *private_owner);
2061
2062 /* move alternatives from my list to the given target list */
2063 void move_alts_to(CTcGramProdEntry *new_entry);
2064
2065 /* get/set explicitly-declared flag */
2066 int is_declared() const { return is_declared_; }
2067 void set_declared(int f) { is_declared_ = f; }
2068
2069 protected:
2070 /* associated production object symbol */
2071 class CTcSymObj *prod_sym_;
2072
2073 /* next item in the list */
2074 CTcGramProdEntry *nxt_;
2075
2076 /* head and tail of alternative list */
2077 class CTcGramProdAlt *alt_head_;
2078 class CTcGramProdAlt *alt_tail_;
2079
2080 /*
2081 * flag: this production was explicitly declared (this means that we
2082 * will consider it valid at link time even if it has no alternatives
2083 * defined)
2084 */
2085 unsigned int is_declared_ : 1;
2086 };
2087
2088 /*
2089 * Grammar production alternative. Each grammar production has one or
2090 * more alternatives that, when matched, generate the production.
2091 */
2092 class CTcGramProdAlt
2093 {
2094 public:
2095 CTcGramProdAlt(class CTcSymObj *obj_sym, class CTcDictEntry *dict);
2096
2097 /* get/set my score */
2098 int get_score() const { return score_; }
2099 void set_score(int score) { score_ = score; }
2100
2101 /* get/set my badness */
2102 int get_badness() const { return badness_; }
2103 void set_badness(int badness) { badness_ = badness; }
2104
2105 /* get my processor object symbol */
2106 class CTcSymObj *get_processor_obj() const { return obj_sym_; }
2107
2108 /* get/set the next list element */
2109 CTcGramProdAlt *get_next() const { return nxt_; }
2110 void set_next(CTcGramProdAlt *nxt) { nxt_ = nxt; }
2111
2112 /* add a token to my list */
2113 void add_tok(class CTcGramProdTok *tok);
2114
2115 /* get the head of my token list */
2116 class CTcGramProdTok *get_tok_head() const { return tok_head_; }
2117
2118 /* write to an object file */
2119 void write_to_obj_file(class CVmFile *fp);
2120
2121 /* load from an object file */
2122 static CTcGramProdAlt *
2123 load_from_obj_file(class CVmFile *fp,
2124 const tctarg_prop_id_t *prop_xlat,
2125 const ulong *enum_xlat);
2126
2127 /* get the dictionary in effect when the alternative was defined */
2128 class CTcDictEntry *get_dict() const { return dict_; }
2129
2130 protected:
2131 /* head and tail of our token list */
2132 class CTcGramProdTok *tok_head_;
2133 class CTcGramProdTok *tok_tail_;
2134
2135 /* dictionary in effect when alternative was defined */
2136 class CTcDictEntry *dict_;
2137
2138 /* the processor object associated with this alternative */
2139 class CTcSymObj *obj_sym_;
2140
2141 /* next alternative in our production */
2142 CTcGramProdAlt *nxt_;
2143
2144 /* score */
2145 int score_;
2146
2147 /* badness */
2148 int badness_;
2149 };
2150
2151 /* grammar production token types */
2152 enum tcgram_tok_type
2153 {
2154 /* unknown */
2155 TCGRAM_UNKNOWN,
2156
2157 /* match a production (given by the production object) */
2158 TCGRAM_PROD,
2159
2160 /* match a part of speech (given by the dictionary property) */
2161 TCGRAM_PART_OF_SPEECH,
2162
2163 /* match a literal string */
2164 TCGRAM_LITERAL,
2165
2166 /* token-type match */
2167 TCGRAM_TOKEN_TYPE,
2168
2169 /* free-floating end-of-string */
2170 TCGRAM_STAR,
2171
2172 /* match one of several parts of speech */
2173 TCGRAM_PART_OF_SPEECH_LIST
2174 };
2175
2176 /*
2177 * Grammar production alternative token
2178 */
2179 class CTcGramProdTok
2180 {
2181 public:
2182 CTcGramProdTok()
2183 {
2184 /* not in a list yet */
2185 nxt_ = 0;
2186
2187 /* no type yet */
2188 typ_ = TCGRAM_UNKNOWN;
2189
2190 /* no property association yte */
2191 prop_assoc_ = TCTARG_INVALID_PROP;
2192 }
2193
2194 /* get/set my next element */
2195 CTcGramProdTok *get_next() const { return nxt_; }
2196 void set_next(CTcGramProdTok *nxt) { nxt_ = nxt; }
2197
2198 /* set me to match a production object */
2199 void set_match_prod(class CTcSymObj *obj)
2200 {
2201 /* remember the production object */
2202 typ_ = TCGRAM_PROD;
2203 val_.obj_ = obj;
2204 }
2205
2206 /* set me to match a token type */
2207 void set_match_token_type(ulong enum_id)
2208 {
2209 /* remember the token enum ID */
2210 typ_ = TCGRAM_TOKEN_TYPE;
2211 val_.enum_id_ = enum_id;
2212 }
2213
2214 /* set me to match a dictionary property */
2215 void set_match_part_of_speech(tctarg_prop_id_t prop)
2216 {
2217 /* remember the part of speech */
2218 typ_ = TCGRAM_PART_OF_SPEECH;
2219 val_.prop_ = prop;
2220 }
2221
2222 /*
2223 * set me to match a list of parts of speech; each part of speech must
2224 * be separately added via add_match_part_ele()
2225 */
2226 void set_match_part_list();
2227
2228 /* add an element to the part-of-speech match list */
2229 void add_match_part_ele(tctarg_prop_id_t prop);
2230
2231 /* set me to match a literal string */
2232 void set_match_literal(const char *txt, size_t len)
2233 {
2234 /* remember the string */
2235 typ_ = TCGRAM_LITERAL;
2236 val_.str_.txt_ = txt;
2237 val_.str_.len_ = len;
2238 }
2239
2240 /* set me to match a free-floating end-of-string */
2241 void set_match_star()
2242 {
2243 /* set the type */
2244 typ_ = TCGRAM_STAR;
2245 }
2246
2247 /* get my type */
2248 tcgram_tok_type get_type() const { return typ_; }
2249
2250 /* get my value */
2251 class CTcSymObj *getval_prod() const { return val_.obj_; }
2252 tctarg_prop_id_t getval_part_of_speech() const { return val_.prop_; }
2253 const char *getval_literal_txt() const { return val_.str_.txt_; }
2254 const size_t getval_literal_len() const { return val_.str_.len_; }
2255 ulong getval_token_type() const { return val_.enum_id_; }
2256 size_t getval_part_list_len() const { return val_.prop_list_.len_; }
2257 tctarg_prop_id_t getval_part_list_ele(size_t idx) const
2258 { return val_.prop_list_.arr_[idx]; }
2259
2260 /*
2261 * get/set my property association - this is the property to which
2262 * the actual match to the rule is assigned when we match the rule
2263 */
2264 tctarg_prop_id_t get_prop_assoc() const { return prop_assoc_; }
2265 void set_prop_assoc(tctarg_prop_id_t prop) { prop_assoc_ = prop; }
2266
2267 /* write to an object file */
2268 void write_to_obj_file(class CVmFile *fp);
2269
2270 /* load from an object file */
2271 static CTcGramProdTok *
2272 load_from_obj_file(class CVmFile *fp,
2273 const tctarg_prop_id_t *prop_xlat,
2274 const ulong *enum_xlat);
2275
2276 protected:
2277 /* next token in my list */
2278 CTcGramProdTok *nxt_;
2279
2280 /* my type - this specifies how this token matches */
2281 tcgram_tok_type typ_;
2282
2283 /* match specification - varies according to my type */
2284 union
2285 {
2286 /* object - for matching a production */
2287 class CTcSymObj *obj_;
2288
2289 /* property - for matching a part of speech */
2290 tctarg_prop_id_t prop_;
2291
2292 /* token enum id - for matching a token type */
2293 ulong enum_id_;
2294
2295 /* literal string */
2296 struct
2297 {
2298 const char *txt_;
2299 size_t len_;
2300 } str_;
2301
2302 /* list of vocabulary elements */
2303 struct
2304 {
2305 /* number of array entries allocated */
2306 size_t alo_;
2307
2308 /* number of array entries actually used */
2309 size_t len_;
2310
2311 /* array of entries */
2312 tctarg_prop_id_t *arr_;
2313 } prop_list_;
2314 } val_;
2315
2316 /* property association */
2317 tctarg_prop_id_t prop_assoc_;
2318 };
2319
2320 /* ------------------------------------------------------------------------ */
2321 /*
2322 * Exported symbol record
2323 */
2324 class CTcPrsExport
2325 {
2326 public:
2327 /* create with the given compiler symbol */
2328 CTcPrsExport(const char *sym, size_t sym_len)
2329 {
2330 /* remember my name */
2331 sym_ = sym;
2332 sym_len_ = sym_len;
2333
2334 /*
2335 * we don't yet have an explicit external name, so export using
2336 * the internal name
2337 */
2338 ext_name_ = sym;
2339 ext_len_ = sym_len;
2340
2341 /* we're not in a list yet */
2342 nxt_ = 0;
2343 }
2344
2345 /* set the external name */
2346 void set_extern_name(const char *txt, size_t len)
2347 {
2348 ext_name_ = txt;
2349 ext_len_ = len;
2350 }
2351
2352 /* get the symbol name and length */
2353 const char *get_sym() const { return sym_; }
2354 size_t get_sym_len() const { return sym_len_; }
2355
2356 /* get the external name and length */
2357 const char *get_ext_name() const { return ext_name_; }
2358 size_t get_ext_len() const { return ext_len_; }
2359
2360 /* get/set the next entry in the list */
2361 CTcPrsExport *get_next() const { return nxt_; }
2362 void set_next(CTcPrsExport *nxt) { nxt_ = nxt; }
2363
2364 /* write to an object file */
2365 void write_to_obj_file(class CVmFile *fp);
2366
2367 /* read from an object file */
2368 static CTcPrsExport *read_from_obj_file(class CVmFile *fp);
2369
2370 /* determine if my external name matches the given export's */
2371 int ext_name_matches(const CTcPrsExport *exp) const
2372 {
2373 return (exp->get_ext_len() == get_ext_len()
2374 && memcmp(exp->get_ext_name(), get_ext_name(),
2375 get_ext_len()) == 0);
2376 }
2377
2378 /* determine if my name matches the given string */
2379 int ext_name_matches(const char *txt) const
2380 {
2381 return (get_ext_len() == get_strlen(txt)
2382 && memcmp(get_ext_name(), txt, get_ext_len()) == 0);
2383 }
2384
2385 /* determine if my name matches the leading substring */
2386 int ext_name_starts_with(const char *txt) const
2387 {
2388 return (get_ext_len() >= get_strlen(txt)
2389 && memcmp(get_ext_name(), txt, get_strlen(txt)) == 0);
2390 }
2391
2392 /* determine if my symbol name matches the given export's */
2393 int sym_matches(const CTcPrsExport *exp) const
2394 {
2395 return (exp->get_sym_len() == get_sym_len()
2396 && memcmp(exp->get_sym(), get_sym(), get_sym_len()) == 0);
2397 }
2398
2399 protected:
2400 /* symbol name - this is the internal compiler symbol being exported */
2401 const char *sym_;
2402 size_t sym_len_;
2403
2404 /* external name - this is the name visible to the VM loader */
2405 const char *ext_name_;
2406 size_t ext_len_;
2407
2408 /* next in list */
2409 CTcPrsExport *nxt_;
2410 };
2411
2412
2413 /* ------------------------------------------------------------------------ */
2414 /*
2415 * Parser Symbol Table. The parser maintains a hierarchy of symbol
2416 * tables; a local symbol table can be nested inside an enclosing
2417 * scope's symbol table, and so on up to the top-level block scope,
2418 * which is enclosed by the global scope. In addition, at function
2419 * scope there's a separate table for "goto" labels.
2420 */
2421
2422 /* find_or_def actions for undefined symbols */
2423 enum tcprs_undef_action
2424 {
2425 /* if undefined, add an "undefined" entry unconditionally */
2426 TCPRS_UNDEF_ADD_UNDEF,
2427
2428 /* add a "property" entry unconditionally, but warn about it */
2429 TCPRS_UNDEF_ADD_PROP,
2430
2431 /* add a "property" entry unconditionally, with no warning */
2432 TCPRS_UNDEF_ADD_PROP_NO_WARNING,
2433
2434 /* add a "weak" property entry without warning */
2435 TCPRS_UNDEF_ADD_PROP_WEAK
2436 };
2437
2438 /* parser symbol table */
2439 class CTcPrsSymtab
2440 {
2441 public:
2442 CTcPrsSymtab(CTcPrsSymtab *parent_scope);
2443 virtual ~CTcPrsSymtab();
2444
2445 /* allocate parser symbol tables out of the parser memory pool */
2446 void *operator new(size_t siz);
2447
2448 /*
2449 * perform static initialization/termination - call once at program
2450 * startup and shutdown (respectively)
2451 */
2452 static void s_init();
2453 static void s_terminate();
2454
2455 /* get the enclosing scope's symbol table */
2456 CTcPrsSymtab *get_parent() const { return parent_; }
2457
2458 /* find a symbol; returns null if the symbol isn't defined */
2459 class CTcSymbol *find(const textchar_t *sym, size_t len)
2460 { return find(sym, len, 0); }
2461
2462 class CTcSymbol *find(const textchar_t *sym)
2463 { return find(sym, strlen(sym), 0); }
2464
2465 /*
2466 * Find a symbol; returns null if the symbol isn't defined. If
2467 * symtab is not null, we'll fill it in with the actual symbol table
2468 * in which we found the symbol; this might be an enclosing symbol
2469 * table, since we search up the enclosing scope list.
2470 */
2471 class CTcSymbol *find(const textchar_t *sym, size_t len,
2472 CTcPrsSymtab **symtab);
2473
2474 /* find a symbol without changing its referenced status */
2475 class CTcSymbol *find_noref(const textchar_t *sym, size_t len,
2476 CTcPrsSymtab **symtab);
2477
2478 /*
2479 * Find a symbol; if the symbol isn't defined, log an error and add
2480 * the symbol as type "undefined". Because we add a symbol entry if
2481 * the symbol isn't defined, this *always* returns a valid symbol
2482 * object.
2483 */
2484 class CTcSymbol *find_or_def_undef(const char *sym, size_t len,
2485 int copy_str)
2486 {
2487 return find_or_def(sym, len, copy_str, TCPRS_UNDEF_ADD_UNDEF);
2488 }
2489
2490 /*
2491 * Find a symbol; if the symbol isn't defined, log a warning and
2492 * define the symbol as type property. Because we add an entry if
2493 * the symbol isn't defined, this *always* returns a valid symbol
2494 * object.
2495 */
2496 class CTcSymbol *find_or_def_prop(const char *sym, size_t len,
2497 int copy_str)
2498 {
2499 return find_or_def(sym, len, copy_str, TCPRS_UNDEF_ADD_PROP);
2500 }
2501
2502 /*
2503 * Find a symbol; if the symbol isn't defined, define the symbol as
2504 * type property with no warning. This should be used when it is
2505 * unambiguous that a symbol is meant as a property name. Because we
2506 * add an entry if the symbol isn't defined, this *always* returns a
2507 * valid symbol object.
2508 */
2509 class CTcSymbol *find_or_def_prop_explicit(
2510 const char *sym, size_t len, int copy_str)
2511 {
2512 return find_or_def(sym, len, copy_str,
2513 TCPRS_UNDEF_ADD_PROP_NO_WARNING);
2514 }
2515
2516 /*
2517 * Find a symbol; if the symbol isn't defined, define it as a property
2518 * without warning, but flag it as a "weak" definition.
2519 */
2520 class CTcSymbol *find_or_def_prop_weak(
2521 const char *sym, size_t len, int copy_str)
2522 {
2523 return find_or_def(sym, len, copy_str, TCPRS_UNDEF_ADD_PROP_WEAK);
2524 }
2525
2526 /*
2527 * Find a symbol. If the symbol isn't defined, and a "self" object
2528 * is available, define the symbol as a property. If the symbol
2529 * isn't defined an no "self" object is available, add an
2530 * "undefined" entry for the symbol.
2531 */
2532 class CTcSymbol *find_or_def_prop_implied(const char *sym, size_t len,
2533 int copy_str, int is_self_avail)
2534 {
2535 return find_or_def(sym, len, copy_str,
2536 is_self_avail
2537 ? TCPRS_UNDEF_ADD_PROP : TCPRS_UNDEF_ADD_UNDEF);
2538 }
2539
2540 /*
2541 * Find a symbol. If the symbol is already defined as a "weak"
2542 * property, delete it to make way for the new definition.
2543 */
2544 class CTcSymbol *find_delete_weak(const char *sym, size_t len);
2545
2546 /* add a formal parameter symbol */
2547 class CTcSymLocal *add_formal(const textchar_t *sym, size_t len,
2548 int formal_num, int copy_str);
2549
2550 /* add a local variable symbol */
2551 class CTcSymLocal *add_local(const textchar_t *sym, size_t len,
2552 int local_num, int copy_str,
2553 int init_assigned, int init_referenced);
2554
2555 /*
2556 * add the current token as a local symbol, initially unassigned and
2557 * unreferenced
2558 */
2559 class CTcSymLocal *add_local(int local_num);
2560
2561 /* add a 'goto' symbol */
2562 class CTcSymLabel *add_code_label(const textchar_t *sym, size_t len,
2563 int copy_str);
2564
2565 /* enumerate entries in the table through a callback */
2566 void enum_entries(void (*func)(void *, class CTcSymbol *), void *ctx);
2567
2568 /*
2569 * Scan the symbol table and check for unreferenced locals. Logs an
2570 * error for each unreferenced or unassigned local.
2571 */
2572 void check_unreferenced_locals();
2573
2574 /*
2575 * Get/set my debugging list index - this is the index of this table
2576 * in the list for this function or method. The index values start
2577 * at 1 - a value of zero indicates that the symbol table isn't part
2578 * of any list.
2579 */
2580 int get_list_index() const { return list_index_; }
2581 void set_list_index(int n) { list_index_ = n; }
2582
2583 /* get/set the next entry in the linked list */
2584 CTcPrsSymtab *get_list_next() const { return list_next_; }
2585 void set_list_next(CTcPrsSymtab *nxt) { list_next_ = nxt; }
2586
2587 /*
2588 * The low-level virtual interface. All searching and manipulation of
2589 * the underlying hash table goes through these routines. This allows
2590 * subclasses to implement the symbol table as a view of another data
2591 * structure.
2592 *
2593 * The compiler itself just uses the underlying hash table directly.
2594 * The dynamic compiler for interpreter "eval()" functionality uses a
2595 * customized version that creates a view of an underlying user-code
2596 * LookupTable object.
2597 */
2598
2599 /* find a symbol directly in this table, without searching parents */
2600 virtual class CTcSymbol *find_direct(const textchar_t *sym, size_t len);
2601
2602 /* add an entry to the table */
2603 virtual void add_entry(class CTcSymbol *sym);
2604
2605 /* remove an entry */
2606 virtual void remove_entry(class CTcSymbol *sym);
2607
2608 /* expand my byte code range to include the given location */
2609 void add_to_range(int ofs)
2610 {
2611 /*
2612 * if we don't have a starting offset yet, or this is before it,
2613 * this is the new start offset
2614 */
2615 if (start_ofs_ == 0 || ofs < start_ofs_)
2616 start_ofs_ = ofs;
2617
2618 /*
2619 * if we don't have an ending offset yet, or this is after it, this
2620 * is the ending offset
2621 */
2622 if (ofs > end_ofs_)
2623 end_ofs_ = ofs;
2624 }
2625
2626 /* get my bytecode offset range */
2627 int get_start_ofs() const { return start_ofs_; }
2628 int get_end_ofs() const { return end_ofs_; }
2629
2630 protected:
2631 /* add an entry to a global symbol table */
2632 static void add_to_global_symtab(CTcPrsSymtab *tab, CTcSymbol *entry);
2633
2634 /* get the underlying hash table */
2635 class CVmHashTable *get_hashtab() const { return hashtab_; }
2636
2637 /* enumeration callback - check for unreferenced locals */
2638 static void unref_local_cb(void *ctx, class CTcSymbol *sym);
2639
2640 /*
2641 * find a symbol, or define a new symbol, according to the given
2642 * action mode, if the symbol is undefined
2643 */
2644 class CTcSymbol *find_or_def(const textchar_t *sym, size_t len,
2645 int copy_str, tcprs_undef_action action);
2646
2647 /* enclosing scope (parent) symbol table */
2648 CTcPrsSymtab *parent_;
2649
2650 /* hash table */
2651 class CVmHashTable *hashtab_;
2652
2653 /* hash function */
2654 static class CVmHashFunc *hash_func_;
2655
2656 /*
2657 * Byte code range covered by this frame. This is the range of offsets
2658 * within the method where this frame is in effect. The range is
2659 * inclusive of the start offset and exclusive of the end offset.
2660 */
2661 int start_ofs_;
2662 int end_ofs_;
2663
2664 /*
2665 * Next symbol table in local scope chain. For each function or
2666 * method, we keep a simple linear list of the local scopes so that
2667 * they can be written to the debugging records. We also keep an
2668 * index value giving its position in the list, so that we can store
2669 * references to the table using the list index.
2670 */
2671 CTcPrsSymtab *list_next_;
2672 int list_index_;
2673 };
2674
2675
2676 /* ------------------------------------------------------------------------ */
2677 /*
2678 * Debugger symbol table interface. This is an abstract interface that
2679 * debuggers can implement to allow us to search for symbols that are
2680 * obtained from a compiled program's debugger records. To keep the
2681 * compiler independent of the target architecture and the debugger's
2682 * own internal structures, we define this abstract interface that the
2683 * debugger must implement.
2684 *
2685 * Since this type of symbol table is provided by a debugger as a view
2686 * on the symbol information in a previously compiled program, the
2687 * parser naturally has no need to add symbols to the table; hence the
2688 * only required operations are symbol lookups.
2689 */
2690 class CTcPrsDbgSymtab
2691 {
2692 public:
2693 /*
2694 * Get information on a symbol. Returns true if the symbol is
2695 * found, false if not. If we find the symbol, fills in the
2696 * information structure with the appropriate data.
2697 */
2698 virtual int find_symbol(const textchar_t *sym, size_t len,
2699 struct tcprsdbg_sym_info *info) = 0;
2700 };
2701
2702 /*
2703 * Debugger local symbol information structure
2704 */
2705 struct tcprsdbg_sym_info
2706 {
2707 /* symbol type */
2708 enum tc_symtype_t sym_type;
2709
2710 /* local/parameter number */
2711 uint var_id;
2712
2713 /* context variable index - 0 if it's not a context local */
2714 int ctx_arr_idx;
2715
2716 /* stack frame index */
2717 uint frame_idx;
2718 };
2719
2720
2721
2722 /* ------------------------------------------------------------------------ */
2723 /*
2724 * Parse Tree storage manager.
2725 *
2726 * The parse tree has some special characteristics that make it
2727 * desirable to use a special memory manager for it. First, the parse
2728 * tree consists of many small objects, so we would like to have as
2729 * little overhead per object for memory tracking as possible. Second,
2730 * parse tree objects all have a similar lifetime: we create the entire
2731 * parse tree as we scan the source, then use it to generate target
2732 * code, then discard the whole thing.
2733 *
2734 * To manage memory efficiently for the parse tree, we define our own
2735 * memory manager for parse tree objects. The memory manager is very
2736 * simple, fast, and has minimal per-object overhead. We simply
2737 * maintain a list of large blocks, then suballocate requests out of the
2738 * large blocks. Each time we run out of space in a block, we allocate
2739 * a new block. We do not keep track of any extra tracking information
2740 * per node, so a node cannot be individually freed; however, the entire
2741 * block list can be freed at once, which is exactly the behavior we
2742 * want.
2743 */
2744 class CTcPrsMem
2745 {
2746 public:
2747 CTcPrsMem();
2748 ~CTcPrsMem();
2749
2750 /* allocate storage */
2751 void *alloc(size_t siz);
2752
2753 /* save the current pool state, for later resetting */
2754 void save_state(struct tcprsmem_state_t *state);
2755
2756 /*
2757 * reset the pool to the given state - delete all objects allocated
2758 * in the pool since the state was saved
2759 */
2760 void reset(const struct tcprsmem_state_t *state);
2761
2762 /* reset to initial state */
2763 void reset();
2764
2765 private:
2766 /* delete all parser memory */
2767 void delete_all();
2768
2769 /* allocate a new block */
2770 void alloc_block();
2771
2772 /* head of list of memory blocks */
2773 struct tcprsmem_blk_t *head_;
2774
2775 /* tail of list and current memory block */
2776 struct tcprsmem_blk_t *tail_;
2777
2778 /* current allocation offset in last block */
2779 char *free_ptr_;
2780
2781 /* remaining space available in last block */
2782 size_t rem_;
2783 };
2784
2785 /*
2786 * state-saving structure
2787 */
2788 struct tcprsmem_state_t
2789 {
2790 /* current tail of memory block list */
2791 struct tcprsmem_blk_t *tail;
2792
2793 /* current allocation offset in last block */
2794 char *free_ptr;
2795
2796 /* current remaining space in last block */
2797 size_t rem;
2798 };
2799
2800
2801 /*
2802 * Provide an overridden operator new for allocating objects explicitly
2803 * from the pool
2804 */
2805 inline void *operator new(size_t siz, CTcPrsMem *pool)
2806 {
2807 return pool->alloc(siz);
2808 }
2809
2810 /*
2811 * provide an array operator new as well
2812 */
2813 inline void *operator new[](size_t siz, CTcPrsMem *pool)
2814 {
2815 return pool->alloc(siz);
2816 }
2817
2818
2819 /*
2820 * parse tree memory block
2821 */
2822 struct tcprsmem_blk_t
2823 {
2824 /* next block in the list */
2825 tcprsmem_blk_t *next_;
2826
2827 /*
2828 * This block's byte array (the array extends off the end of the
2829 * structure).
2830 */
2831 char buf_[1];
2832 };
2833
2834 /* ------------------------------------------------------------------------ */
2835 /*
2836 * Special array list subclass that uses parser memory
2837 */
2838 class CPrsArrayList: public CArrayList
2839 {
2840 protected:
2841 /*
2842 * override the memory management functions to use parser memory
2843 */
2844
2845 virtual void *alloc_mem(size_t siz)
2846 {
2847 /* allocate from the parser pool */
2848 return G_prsmem->alloc(siz);
2849 }
2850
2851 virtual void *realloc_mem(void *p, size_t oldsiz, size_t newsiz)
2852 {
2853 void *pnew;
2854
2855 /* allocate a new block from the parser pool */
2856 pnew = G_prsmem->alloc(newsiz);
2857
2858 /* copy from the old block to the new block */
2859 memcpy(pnew, p, oldsiz);
2860
2861 /* return the new block */
2862 return pnew;
2863 }
2864
2865 virtual void free_mem(void *p)
2866 {
2867 /*
2868 * do nothing - the parser pool automatically frees everything as a
2869 * block when terminating the parser
2870 */
2871 }
2872 };
2873
2874
2875 /* ------------------------------------------------------------------------ */
2876 /*
2877 * Expression Constant Value object. This object is used to express the
2878 * value of a constant expression.
2879 */
2880 class CTcConstVal
2881 {
2882 public:
2883 CTcConstVal()
2884 {
2885 /* the type is unknown */
2886 typ_ = TC_CVT_UNK;
2887
2888 /* assume it's a true constant, not just a compile-time constant */
2889 ctc_ = FALSE;
2890 }
2891
2892 /*
2893 * determine if this is a constant value - it is a constant if it
2894 * has any known value
2895 */
2896 int is_const() const { return (typ_ != TC_CVT_UNK); }
2897
2898 /*
2899 * set the type to unknown - this indicates that there is no valid
2900 * value, which generally means that the associated expression does
2901 * not have a constant value
2902 */
2903 void set_unknown() { typ_ = TC_CVT_UNK; }
2904
2905 /* set from another value */
2906 void set(const CTcConstVal *val)
2907 {
2908 /* copy the type */
2909 typ_ = val->typ_;
2910
2911 /* copy the value */
2912 val_ = val->val_;
2913 }
2914
2915 /* set an integer value */
2916 void set_int(long val) { typ_ = TC_CVT_INT; val_.intval_ = val; }
2917
2918 /* set a floating-point value */
2919 void set_float(const char *val, size_t len, int promoted);
2920
2921 /* set a floating-point value from a vbignum_t */
2922 void set_float(const class vbignum_t *val, int promoted);
2923
2924 /* set a floating-point value promoted from an integer */
2925 void set_float(ulong i);
2926
2927 /*
2928 * Check to see if a promoted float value can be demoted back to int.
2929 * If the value is a float that was flagged as promoted from an int
2930 * constant, and the value fits in an int32, we'll demote the value
2931 * back to an int. This has no effect if the value isn't a float,
2932 * wasn't promoted, or doesn't fit in an int. This can be used after a
2933 * constant-folding operation is applied to a value that was at some
2934 * point promoted from int to see if the promotion is no longer
2935 * required.
2936 */
2937 void demote_float();
2938
2939 /* set an enumerator value */
2940 void set_enum(ulong val) { typ_ = TC_CVT_ENUM; val_.enumval_ = val; }
2941
2942 /* set a single-quoted string value */
2943 void set_sstr(const char *val, size_t len);
2944 void set_sstr(const CTcToken *tok);
2945
2946 /* set a regex string value (R'...' or R"...") */
2947 void set_restr(const CTcToken *tok);
2948
2949 /* set a list value */
2950 void set_list(class CTPNList *lst);
2951
2952 /* for the debugger only: set a pre-resolved constant pool value */
2953 void set_sstr(uint32_t ofs);
2954 void set_list(uint32_t ofs);
2955
2956 /* set an object reference value */
2957 void set_obj(ulong obj, enum tc_metaclass_t meta)
2958 {
2959 typ_ = TC_CVT_OBJ;
2960 val_.objval_.id_ = obj;
2961 val_.objval_.meta_ = meta;
2962 }
2963
2964 /* set a property pointer value */
2965 void set_prop(uint prop)
2966 {
2967 typ_ = TC_CVT_PROP;
2968 val_.propval_ = prop;
2969 }
2970
2971 /* set a function pointer value */
2972 void set_funcptr(class CTcSymFunc *sym)
2973 {
2974 typ_ = TC_CVT_FUNCPTR;
2975 val_.funcptrval_ = sym;
2976 }
2977
2978 /* set an anonymous function pointer value */
2979 void set_anon_funcptr(class CTPNCodeBody *code_body)
2980 {
2981 typ_ = TC_CVT_ANONFUNCPTR;
2982 val_.codebodyval_ = code_body;
2983 }
2984
2985 /* set a built-in function pointer value */
2986 void set_bifptr(class CTcSymBif *sym)
2987 {
2988 typ_ = TC_CVT_BIFPTR;
2989 val_.bifptrval_ = sym;
2990 }
2991
2992 /* set a nil/true value */
2993 void set_nil() { typ_ = TC_CVT_NIL; }
2994 void set_true() { typ_ = TC_CVT_TRUE; }
2995
2996 /*
2997 * Set a vocabulary list placeholder. This has no actual value
2998 * during compilation; instead, this is just a placeholder. During
2999 * linking, we'll replace each of these with a list of strings
3000 * giving the actual vocabulary for the property.
3001 */
3002 void set_vocab_list() { typ_ = TC_CVT_VOCAB_LIST; }
3003
3004 /* set a nil/true value based on a boolean value */
3005 void set_bool(int val)
3006 {
3007 typ_ = (val ? TC_CVT_TRUE : TC_CVT_NIL);
3008 }
3009
3010 /* is this a boolean value? */
3011 int is_bool() const { return typ_ == TC_CVT_NIL || typ_ == TC_CVT_TRUE; }
3012
3013 /* get my type */
3014 tc_constval_type_t get_type() const { return typ_; }
3015
3016 /* get my int value (no type checking) */
3017 long get_val_int() const { return val_.intval_; }
3018
3019 /* get my floating point value (no type checking) */
3020 const char *get_val_float() const { return val_.floatval_.txt_; }
3021 size_t get_val_float_len() const { return val_.floatval_.len_; }
3022
3023 /* was the value promoted to float from int due to overflow? */
3024 int is_promoted() const { return promoted_; }
3025
3026 /* get my enumerator value (no type checking) */
3027 ulong get_val_enum() const { return val_.enumval_; }
3028
3029 /* get my string value (no type checking) */
3030 const char *get_val_str() const { return val_.strval_.strval_; }
3031 size_t get_val_str_len() const { return val_.strval_.strval_len_; }
3032
3033 /* get my list value (no type checking) */
3034 class CTPNList *get_val_list() const { return val_.listval_.l_; }
3035
3036 /*
3037 * for debugger expressions only: the string/list as a pre-resolved
3038 * constant pool address
3039 */
3040 uint32_t get_val_str_ofs() const { return val_.strval_.pool_ofs_; }
3041 uint32_t get_val_list_ofs() const { return val_.listval_.pool_ofs_; }
3042
3043 /* get my object reference value (no type checking) */
3044 ulong get_val_obj() const
3045 { return val_.objval_.id_; }
3046 enum tc_metaclass_t get_val_obj_meta() const
3047 { return val_.objval_.meta_; }
3048
3049 /* get my property pointer value (no type checking) */
3050 uint get_val_prop() const { return val_.propval_; }
3051
3052 /* get my function pointer symbol value (no type checking) */
3053 class CTcSymFunc *get_val_funcptr_sym() const
3054 { return val_.funcptrval_; }
3055
3056 /* get my anonymous function pointer value (no type checking) */
3057 class CTPNCodeBody *get_val_anon_func_ptr() const
3058 { return val_.codebodyval_; }
3059
3060 /* get my built-in function pointer symbol value (noi type checking) */
3061 class CTcSymBif *get_val_bifptr_sym() const
3062 { return val_.bifptrval_; }
3063
3064 /*
3065 * Determine if this value equals a given constant value. Returns
3066 * true if so, false if not. We'll set (*can_compare) to true if
3067 * the values are comparable, false if the comparison is not
3068 * meaningful.
3069 */
3070 int is_equal_to(const CTcConstVal *val) const;
3071
3072 /*
3073 * Convert an integer, nil, or true value to a string. Fills in the
3074 * buffer with the result of the conversion if the value wasn't
3075 * already a string. If the value is already a string, we'll simply
3076 * return a pointer to the original string without making a copy.
3077 * Returns null if the value is not convertible to a string.
3078 */
3079 const char *cvt_to_str(char *buf, size_t bufl, size_t *result_len);
3080
3081 /*
3082 * Get my true/nil value. Returns false if the value is nil or zero,
3083 * true if it's anything else.
3084 */
3085 int get_val_bool() const
3086 {
3087 return !(typ_ == TC_CVT_NIL || equals_zero());
3088 }
3089
3090 /* is this is a numeric value equal to zero? */
3091 int equals_zero() const;
3092
3093 /*
3094 * Set/get the compile-time constant flag. A compile-time constant is
3095 * a value that's constant at compile-time, but which can vary from one
3096 * compilation to the next. The defined() and __objref() operators
3097 * have this property.
3098 */
3099 void set_ctc(int f) { ctc_ = f; }
3100 int is_ctc() const { return ctc_; }
3101
3102 private:
3103 /* my type */
3104 tc_constval_type_t typ_;
3105
3106 union
3107 {
3108 /* integer value (valid when typ_ == TC_CVT_INT) */
3109 long intval_;
3110
3111 /* floating-point value (valid when typ_ == TC_CVT_FLOAT) */
3112 struct
3113 {
3114 const char *txt_;
3115 size_t len_;
3116 }
3117 floatval_;
3118
3119 /* enumerator value (valid when typ_ == TC_CVT_ENUM) */
3120 ulong enumval_;
3121
3122 /*
3123 * String value (valid when typ_ == TC_CVT_TYPE_SSTR). We need
3124 * to know the length separately, because the underyling string
3125 * may not be null-terminated.
3126 */
3127 struct
3128 {
3129 const char *strval_;
3130 size_t strval_len_;
3131
3132 /*
3133 * For debugger expressions only: the pre-resolved constant
3134 * pool address in the live running program of a string or list
3135 * expression. This type is indicated by setting the value
3136 * data type to string or list, and setting the token value
3137 * pointer for that type to null.
3138 */
3139 uint32_t pool_ofs_;
3140 }
3141 strval_;
3142
3143 /* my list value */
3144 struct
3145 {
3146 class CTPNList *l_;
3147
3148 /* for debugger expressions only: the pre-resolved pool address */
3149 uint32_t pool_ofs_;
3150 }
3151 listval_;
3152
3153 /* property ID value */
3154 uint propval_;
3155
3156 /* object reference value */
3157 struct
3158 {
3159 ulong id_;
3160 enum tc_metaclass_t meta_;
3161 }
3162 objval_;
3163
3164 /*
3165 * function pointer value - we store the underlying symbol,
3166 * since function pointers are generally not resolved until late
3167 * in the compilation
3168 */
3169 class CTcSymFunc *funcptrval_;
3170
3171 /* built-in function pointer value */
3172 class CTcSymBif *bifptrval_;
3173
3174 /*
3175 * code body pointer value - we store the underlying code body
3176 * for anonymous functions
3177 */
3178 class CTPNCodeBody *codebodyval_;
3179 } val_;
3180
3181 /*
3182 * Is this a compile-time constant value? A compile-time constant is a
3183 * value that has a fixed constant value as of compile time, but could
3184 * vary from one compilation to another. The defined() operator
3185 * produces this type of constant, for example.
3186 *
3187 * The main distinction between a true constant and a compile-time
3188 * constant is that true constants generate warnings when they produce
3189 * invariant code, such as when a true constant is used as the
3190 * condition of an 'if'. Compile-time constants are specifically for
3191 * producing code that's invariant once compiled, but which can vary
3192 * across compilations, allowing for more sophisticated configuration
3193 * management. For example, defined() makes it possible to produce
3194 * code that only gets compiled when a particular symbol is included in
3195 * the build, so that code in module A can refer to symbols defined in
3196 * module B when module B is included in the build, but will
3197 * automatically omit the referring code when module B is omitted.
3198 */
3199 uint ctc_ : 1;
3200
3201 /*
3202 * Is this a promoted value? This is set to true for promotions from
3203 * int to BigNumber that are due to overflows. This isn't set for
3204 * values explicitly entered as floating point values or that were
3205 * constant-folded from expressions containing explicit floats.
3206 */
3207 uint promoted_ : 1;
3208 };
3209
3210
3211 /* ------------------------------------------------------------------------ */
3212 /*
3213 * Assignment Types.
3214 */
3215
3216 enum tc_asitype_t
3217 {
3218 /* simple assignment: x = 1 */
3219 TC_ASI_SIMPLE,
3220
3221 /* add to: x += 1 */
3222 TC_ASI_ADD,
3223
3224 /* subtract from: x -= 1 */
3225 TC_ASI_SUB,
3226
3227 /* multiply by: x *= 1 */
3228 TC_ASI_MUL,
3229
3230 /* divide by: x /= 1 */
3231 TC_ASI_DIV,
3232
3233 /* modulo: x %= 1 */
3234 TC_ASI_MOD,
3235
3236 /* bitwise-and with: x &= 1 */
3237 TC_ASI_BAND,
3238
3239 /* bitwise-or with: x |= 1 */
3240 TC_ASI_BOR,
3241
3242 /* bitwise-xor with: x ^= 1 */
3243 TC_ASI_BXOR,
3244
3245 /* shift left: x <<= 1 */
3246 TC_ASI_SHL,
3247
3248 /* arithmetic shift right: x >>= 1 */
3249 TC_ASI_ASHR,
3250
3251 /* logical shift right: x >>>= 1 */
3252 TC_ASI_LSHR,
3253
3254 /* pre-increment */
3255 TC_ASI_PREINC,
3256
3257 /* pre-decrement */
3258 TC_ASI_PREDEC,
3259
3260 /* post-increment */
3261 TC_ASI_POSTINC,
3262
3263 /* post-decrement */
3264 TC_ASI_POSTDEC,
3265
3266 /*
3267 * Subscript assignment: []=
3268 *
3269 * This isn't actually an operator in the language, but subscripted
3270 * assignments are handled specially because of the way subscript
3271 * assignment generates a new container value. So a[b] = c is actually
3272 * treated as a = a.operator[]=(b, c).
3273 */
3274 TC_ASI_IDX
3275 };
3276
3277
3278 /* ------------------------------------------------------------------------ */
3279 /*
3280 * Formal parameter type list. For functions with declared formal
3281 * parameter types (such as multi-methods), we use this class to keep the
3282 * list of type names in the parameter list.
3283 */
3284 class CTcFormalTypeList
3285 {
3286 public:
3287 CTcFormalTypeList()
3288 {
3289 /* no entries in our type list yet */
3290 head_ = tail_ = 0;
3291
3292 /* assume this isn't a varargs list */
3293 varargs_ = FALSE;
3294 }
3295
3296 ~CTcFormalTypeList() { }
3297
3298 /* create the decorated name */
3299 void decorate_name(CTcToken *decorated_name,
3300 const CTcToken *func_base_name);
3301
3302 /* get the first parameter in the list */
3303 class CTcFormalTypeEle *get_first() const { return head_; }
3304
3305 /* add a typed variable to the list */
3306 void add_typed_param(const CTcToken *tok);
3307
3308 /* add an untyped variable to the list */
3309 void add_untyped_param();
3310
3311 /* add 'n' untyped variables to the list */
3312 void add_untyped_params(int n)
3313 {
3314 while (n-- > 0)
3315 add_untyped_param();
3316 }
3317
3318 /* add a trailing ellispsis (varargs indicator) */
3319 void add_ellipsis() { varargs_ = TRUE; }
3320
3321 protected:
3322 /* add a new list element */
3323 void add(class CTcFormalTypeEle *ele);
3324
3325 /* add/tail of parameter list */
3326 class CTcFormalTypeEle *head_, *tail_;
3327
3328 /* is this a varargs list? */
3329 int varargs_;
3330 };
3331
3332 /* formal parameter type list entry */
3333 class CTcFormalTypeEle
3334 {
3335 public:
3336 CTcFormalTypeEle() { name_ = 0; }
3337 CTcFormalTypeEle(const char *name, size_t len);
3338 ~CTcFormalTypeEle()
3339 {
3340 }
3341
3342 /* next element in list */
3343 CTcFormalTypeEle *nxt_;
3344
3345 /* type name */
3346 char *name_;
3347 size_t name_len_;
3348 };
3349
3350
3351 /* ------------------------------------------------------------------------ */
3352 /*
3353 * Expression Operator Parsers. We construct a tree of these operator
3354 * parsers so that we can express the expression grammar in a relatively
3355 * compact and declarative notation.
3356 */
3357
3358 /*
3359 * basic operator parser
3360 */
3361 class CTcPrsOp
3362 {
3363 public:
3364 /*
3365 * Parse an expression with this operator. Logs an error and
3366 * returns non-zero if the expression is not valid; on success,
3367 * returns zero.
3368 *
3369 * Fills in *val with the constant value, if any, of the expression.
3370 * If the expression does not have a constant value, *val's type
3371 * will be set to TC_CVT_UNKNOWN to indicate this.
3372 *
3373 * Returns a parse node if successful, or null if an error occurs
3374 * and the operator parser is unable to make a guess about what was
3375 * intended.
3376 */
3377 virtual class CTcPrsNode *parse() const = 0;
3378 };
3379
3380 /*
3381 * generic left-associative binary operator
3382 */
3383 class CTcPrsOpBin: public CTcPrsOp
3384 {
3385 public:
3386 CTcPrsOpBin()
3387 {
3388 /* no left or right subexpression specified */
3389 left_ = right_ = 0;
3390
3391 /* as-yet unknown operator token */
3392 op_tok_ = TOKT_INVALID;
3393 }
3394
3395 CTcPrsOpBin(tc_toktyp_t typ)
3396 {
3397 /* remember my operator token */
3398 op_tok_ = typ;
3399 }
3400
3401 CTcPrsOpBin(const CTcPrsOp *left, const CTcPrsOp *right, tc_toktyp_t typ)
3402 {
3403 /* remember my left and right sub-operators */
3404 left_ = left;
3405 right_ = right;
3406
3407 /* remember my operator token */
3408 op_tok_ = typ;
3409 }
3410
3411 /* parse the binary expression */
3412 class CTcPrsNode *parse() const;
3413
3414 /* build a new tree out of our left-hand and right-hand subtrees */
3415 virtual class CTcPrsNode
3416 *build_tree(class CTcPrsNode *left,
3417 class CTcPrsNode *right) const = 0;
3418
3419 /*
3420 * Try evaluating a constant result. If the two values can be
3421 * combined with the operator to yield a constant value result,
3422 * create a new parse node for the constant value (or update one of
3423 * the given subnodes) and return it. If we can't provide a
3424 * constant value, return null.
3425 *
3426 * By default, we'll indicate that the expression does not have a
3427 * valid constant value.
3428 */
3429 virtual class CTcPrsNode
3430 *eval_constant(class CTcPrsNode *left,
3431 class CTcPrsNode *right) const
3432 {
3433 /* indicate that we cannot synthesize a constant value */
3434 return 0;
3435 }
3436
3437 /* get/set my token */
3438 tc_toktyp_t get_op_tok() const { return op_tok_; }
3439 void set_op_tok(tc_toktyp_t tok) { op_tok_ = tok; }
3440
3441 protected:
3442 /* operator that can be parsed for my left-hand side */
3443 const CTcPrsOp *left_;
3444
3445 /* operator that can be parsed for my right-hand side */
3446 const CTcPrsOp *right_;
3447
3448 /* my operator token */
3449 tc_toktyp_t op_tok_;
3450 };
3451
3452 /*
3453 * Binary Operator Group. This is a group of operators at a common
3454 * precedence level. The group has an array of binary operators that
3455 * are all at the same level of precedence; we'll evaluate the left
3456 * suboperator, then check the token in the input stream against each of
3457 * our group's operators, applying the one that matches, if one matches.
3458 */
3459 class CTcPrsOpBinGroup: public CTcPrsOp
3460 {
3461 public:
3462 CTcPrsOpBinGroup(const CTcPrsOp *left, const CTcPrsOp *right,
3463 const class CTcPrsOpBin *const *ops)
3464 {
3465 /* remember my left and right suboperators */
3466 left_ = left;
3467 right_ = right;
3468
3469 /* remember the operators in my group */
3470 ops_ = ops;
3471 }
3472
3473 /* parse the expression */
3474 class CTcPrsNode *parse() const;
3475
3476 protected:
3477 /* find and apply an operator to the parsed left-hand side */
3478 int find_and_apply_op(CTcPrsNode **lhs) const;
3479
3480 /* my left and right suboperators */
3481 const CTcPrsOp *left_;
3482 const CTcPrsOp *right_;
3483
3484 /* group of binary operators at this precedence level */
3485 const class CTcPrsOpBin *const *ops_;
3486 };
3487
3488 /*
3489 * Binary operator group for comparison operators. This is a similar to
3490 * other binary groups, but also includes the special "is in" and "not
3491 * in" operators.
3492 */
3493 class CTcPrsOpBinGroupCompare: public CTcPrsOpBinGroup
3494 {
3495 public:
3496 CTcPrsOpBinGroupCompare(const class CTcPrsOp *left,
3497 const class CTcPrsOp *right,
3498 const class CTcPrsOpBin *const *ops)
3499 : CTcPrsOpBinGroup(left, right, ops)
3500 {
3501 }
3502
3503 class CTcPrsNode *parse() const;
3504
3505 protected:
3506 /* parse the 'in' list portion of the expression */
3507 class CTPNArglist *parse_inlist() const;
3508 };
3509
3510 /* comma operator */
3511 class CTcPrsOpComma: public CTcPrsOpBin
3512 {
3513 public:
3514 CTcPrsOpComma(const CTcPrsOp *left, const CTcPrsOp *right)
3515 : CTcPrsOpBin(left, right, TOKT_COMMA) { }
3516
3517 /* evaluate constant result */
3518 class CTcPrsNode
3519 *eval_constant(class CTcPrsNode *left,
3520 class CTcPrsNode *right) const;
3521
3522 /* build a new tree out of our left-hand and right-hand subtrees */
3523 class CTcPrsNode
3524 *build_tree(class CTcPrsNode *left,
3525 class CTcPrsNode *right) const;
3526 };
3527
3528 /* logical OR */
3529 class CTcPrsOpOr: public CTcPrsOpBin
3530 {
3531 public:
3532 CTcPrsOpOr(const CTcPrsOp *left, const CTcPrsOp *right)
3533 : CTcPrsOpBin(left, right, TOKT_OROR) { }
3534
3535 /* evaluate constant result */
3536 class CTcPrsNode
3537 *eval_constant(class CTcPrsNode *left,
3538 class CTcPrsNode *right) const;
3539
3540 /* build a new tree out of our left-hand and right-hand subtrees */
3541 class CTcPrsNode
3542 *build_tree(class CTcPrsNode *left,
3543 class CTcPrsNode *right) const;
3544 };
3545
3546 /* logical AND */
3547 class CTcPrsOpAnd: public CTcPrsOpBin
3548 {
3549 public:
3550 CTcPrsOpAnd(const CTcPrsOp *left, const CTcPrsOp *right)
3551 : CTcPrsOpBin(left, right, TOKT_ANDAND) { }
3552
3553 /* evaluate constant result */
3554 class CTcPrsNode
3555 *eval_constant(class CTcPrsNode *left,
3556 class CTcPrsNode *right) const;
3557
3558 /* build a new tree out of our left-hand and right-hand subtrees */
3559 class CTcPrsNode
3560 *build_tree(class CTcPrsNode *left,
3561 class CTcPrsNode *right) const;
3562 };
3563
3564 /* general magnitude comparison operators */
3565 class CTcPrsOpRel: public CTcPrsOpBin
3566 {
3567 public:
3568 CTcPrsOpRel(tc_toktyp_t typ) : CTcPrsOpBin(typ) { }
3569
3570 /* evaluate constant result */
3571 class CTcPrsNode
3572 *eval_constant(class CTcPrsNode *left,
3573 class CTcPrsNode *right) const;
3574
3575 protected:
3576 /*
3577 * Get the result true/false value, given the result of the
3578 * comparison. For example, if this is a greater-than operator,
3579 * this should return TRUE if comp > 0, FALSE otherwise.
3580 */
3581 virtual int get_bool_val(int comparison_value) const = 0;
3582 };
3583
3584 /* comparison - greater than */
3585 class CTcPrsOpGt: public CTcPrsOpRel
3586 {
3587 public:
3588 CTcPrsOpGt() : CTcPrsOpRel(TOKT_GT) { }
3589
3590 /* get the boolean value for a comparison sense */
3591 int get_bool_val(int comp) const { return comp > 0; }
3592
3593 /* build a new tree out of our left-hand and right-hand subtrees */
3594 class CTcPrsNode
3595 *build_tree(class CTcPrsNode *left,
3596 class CTcPrsNode *right) const;
3597 };
3598
3599 /* comparison - greater than or equal to */
3600 class CTcPrsOpGe: public CTcPrsOpRel
3601 {
3602 public:
3603 CTcPrsOpGe() : CTcPrsOpRel(TOKT_GE) { }
3604
3605 /* get the boolean value for a comparison sense */
3606 int get_bool_val(int comp) const { return comp >= 0; }
3607
3608 /* build a new tree out of our left-hand and right-hand subtrees */
3609 class CTcPrsNode
3610 *build_tree(class CTcPrsNode *left,
3611 class CTcPrsNode *right) const;
3612 };
3613
3614 /* comparison - less than */
3615 class CTcPrsOpLt: public CTcPrsOpRel
3616 {
3617 public:
3618 CTcPrsOpLt() : CTcPrsOpRel(TOKT_LT) { }
3619
3620 /* get the boolean value for a comparison sense */
3621 int get_bool_val(int comp) const { return comp < 0; }
3622
3623 /* build a new tree out of our left-hand and right-hand subtrees */
3624 class CTcPrsNode
3625 *build_tree(class CTcPrsNode *left,
3626 class CTcPrsNode *right) const;
3627 };
3628
3629 /* comparison - less than or equal to */
3630 class CTcPrsOpLe: public CTcPrsOpRel
3631 {
3632 public:
3633 CTcPrsOpLe() : CTcPrsOpRel(TOKT_LE) { }
3634
3635 /* get the boolean value for a comparison sense */
3636 int get_bool_val(int comp) const { return comp <= 0; }
3637
3638 /* build a new tree out of our left-hand and right-hand subtrees */
3639 class CTcPrsNode
3640 *build_tree(class CTcPrsNode *left,
3641 class CTcPrsNode *right) const;
3642 };
3643
3644 /*
3645 * Equality/inequality comparison
3646 */
3647 class CTcPrsOpEqComp: public CTcPrsOpBin
3648 {
3649 public:
3650 CTcPrsOpEqComp(tc_toktyp_t typ) : CTcPrsOpBin(typ) { }
3651
3652 /* evaluate constant result */
3653 class CTcPrsNode
3654 *eval_constant(class CTcPrsNode *left,
3655 class CTcPrsNode *right) const;
3656
3657 protected:
3658 /* get the boolean value to use if the operands are equal */
3659 virtual int get_bool_val(int ops_equal) const = 0;
3660 };
3661
3662
3663 /*
3664 * Equality comparison
3665 */
3666 class CTcPrsOpEq: public CTcPrsOpEqComp
3667 {
3668 public:
3669 /* start out in C mode - use '==' operator by default */
3670 CTcPrsOpEq()
3671 : CTcPrsOpEqComp(TOKT_EQEQ) { }
3672
3673 /* set the current equality operator */
3674 void set_eq_op(tc_toktyp_t op) { op_tok_ = op; }
3675
3676 /* build a new tree out of our left-hand and right-hand subtrees */
3677 class CTcPrsNode
3678 *build_tree(class CTcPrsNode *left,
3679 class CTcPrsNode *right) const;
3680
3681 /* get the boolean value to use if the operands are equal */
3682 virtual int get_bool_val(int ops_equal) const { return ops_equal; }
3683 };
3684
3685 /*
3686 * Inequality comparison
3687 */
3688 class CTcPrsOpNe: public CTcPrsOpEqComp
3689 {
3690 public:
3691 CTcPrsOpNe() : CTcPrsOpEqComp(TOKT_NE) { }
3692
3693 /* build a new tree out of our left-hand and right-hand subtrees */
3694 class CTcPrsNode
3695 *build_tree(class CTcPrsNode *left,
3696 class CTcPrsNode *right) const;
3697
3698 /* get the boolean value to use if the operands are equal */
3699 virtual int get_bool_val(int ops_equal) const { return !ops_equal; }
3700 };
3701
3702 /*
3703 * binary arithmetic operators
3704 */
3705 class CTcPrsOpArith: public CTcPrsOpBin
3706 {
3707 public:
3708 CTcPrsOpArith(tc_toktyp_t typ)
3709 : CTcPrsOpBin(typ) { }
3710
3711 CTcPrsOpArith(const CTcPrsOp *left, const CTcPrsOp *right,
3712 tc_toktyp_t typ)
3713 : CTcPrsOpBin(left, right, typ) { }
3714
3715 /* evaluate constant result */
3716 class CTcPrsNode
3717 *eval_constant(class CTcPrsNode *left,
3718 class CTcPrsNode *right) const;
3719
3720 protected:
3721 /* calculate the result of the operand applied to constant int values */
3722 virtual long calc_result(long val1, long val2, int &ov) const = 0;
3723
3724 /* calculate the result for constant float values */
3725 virtual class vbignum_t *calc_result(
3726 const class vbignum_t &a, const class vbignum_t &b) const = 0;
3727 };
3728
3729 /* bitwise OR */
3730 class CTcPrsOpBOr: public CTcPrsOpArith
3731 {
3732 public:
3733 CTcPrsOpBOr(const CTcPrsOp *left, const CTcPrsOp *right)
3734 : CTcPrsOpArith(left, right, TOKT_OR) { }
3735
3736 /* build a new tree out of our left-hand and right-hand subtrees */
3737 class CTcPrsNode
3738 *build_tree(class CTcPrsNode *left,
3739 class CTcPrsNode *right) const;
3740
3741 protected:
3742 /* calculate a constant integer result */
3743 virtual long calc_result(long val1, long val2, int &ov) const
3744 {
3745 ov = FALSE;
3746 return val1 | val2;
3747 }
3748
3749 /* calculate a constant float result */
3750 virtual class vbignum_t *calc_result(
3751 const class vbignum_t &a, const class vbignum_t &b) const
3752 {
3753 G_tok->log_error(TCERR_BAD_OP_FOR_FLOAT);
3754 return 0;
3755 }
3756 };
3757
3758 /* bitwise XOR */
3759 class CTcPrsOpBXor: public CTcPrsOpArith
3760 {
3761 public:
3762 CTcPrsOpBXor(const CTcPrsOp *left, const CTcPrsOp *right)
3763 : CTcPrsOpArith(left, right, TOKT_XOR) { }
3764
3765 /* build a new tree out of our left-hand and right-hand subtrees */
3766 class CTcPrsNode
3767 *build_tree(class CTcPrsNode *left,
3768 class CTcPrsNode *right) const;
3769
3770 protected:
3771 /* calculate the result */
3772 virtual long calc_result(long val1, long val2, int &ov) const
3773 {
3774 ov = FALSE;
3775 return val1 ^ val2;
3776 }
3777
3778 /* calculate a constant float result */
3779 virtual class vbignum_t *calc_result(
3780 const class vbignum_t &a, const class vbignum_t &b) const
3781 {
3782 G_tok->log_error(TCERR_BAD_OP_FOR_FLOAT);
3783 return 0;
3784 }
3785 };
3786
3787 /* bitwise AND */
3788 class CTcPrsOpBAnd: public CTcPrsOpArith
3789 {
3790 public:
3791 CTcPrsOpBAnd(const CTcPrsOp *left, const CTcPrsOp *right)
3792 : CTcPrsOpArith(left, right, TOKT_AND) { }
3793
3794 /* build a new tree out of our left-hand and right-hand subtrees */
3795 class CTcPrsNode
3796 *build_tree(class CTcPrsNode *left,
3797 class CTcPrsNode *right) const;
3798
3799 protected:
3800 /* calculate the result */
3801 virtual long calc_result(long val1, long val2, int &ov) const
3802 {
3803 ov = FALSE;
3804 return val1 & val2;
3805 }
3806
3807 /* calculate a constant float result */
3808 virtual class vbignum_t *calc_result(
3809 const class vbignum_t &a, const class vbignum_t &b) const
3810 {
3811 G_tok->log_error(TCERR_BAD_OP_FOR_FLOAT);
3812 return 0;
3813 }
3814 };
3815
3816 /*
3817 * shift left
3818 */
3819 class CTcPrsOpShl: public CTcPrsOpArith
3820 {
3821 public:
3822 CTcPrsOpShl() : CTcPrsOpArith(TOKT_SHL) { }
3823
3824 /* build a new tree out of our left-hand and right-hand subtrees */
3825 class CTcPrsNode
3826 *build_tree(class CTcPrsNode *left,
3827 class CTcPrsNode *right) const;
3828
3829 protected:
3830 long calc_result(long a, long b, int &ov) const
3831 {
3832 ov = FALSE;
3833 return a << b;
3834 }
3835
3836 /* calculate a constant float result */
3837 virtual class vbignum_t *calc_result(
3838 const class vbignum_t &a, const class vbignum_t &b) const
3839 {
3840 G_tok->log_error(TCERR_BAD_OP_FOR_FLOAT);
3841 return 0;
3842 }
3843 };
3844
3845 /*
3846 * arithmetic shift right
3847 */
3848 class CTcPrsOpAShr: public CTcPrsOpArith
3849 {
3850 public:
3851 CTcPrsOpAShr() : CTcPrsOpArith(TOKT_ASHR) { }
3852
3853 /* build a new tree out of our left-hand and right-hand subtrees */
3854 class CTcPrsNode
3855 *build_tree(class CTcPrsNode *left,
3856 class CTcPrsNode *right) const;
3857
3858 protected:
3859 long calc_result(long a, long b, int &ov) const
3860 {
3861 ov = FALSE;
3862 return t3_ashr(a, b);
3863 }
3864
3865 /* calculate a constant float result */
3866 virtual class vbignum_t *calc_result(
3867 const class vbignum_t &a, const class vbignum_t &b) const
3868 {
3869 G_tok->log_error(TCERR_BAD_OP_FOR_FLOAT);
3870 return 0;
3871 }
3872 };
3873
3874 /*
3875 * logical shift right
3876 */
3877 class CTcPrsOpLShr: public CTcPrsOpArith
3878 {
3879 public:
3880 CTcPrsOpLShr() : CTcPrsOpArith(TOKT_LSHR) { }
3881
3882 /* build a new tree out of our left-hand and right-hand subtrees */
3883 class CTcPrsNode
3884 *build_tree(class CTcPrsNode *left,
3885 class CTcPrsNode *right) const;
3886
3887 protected:
3888 /* calculate a constant integer result */
3889 long calc_result(long a, long b, int &ov) const
3890 {
3891 ov = FALSE;
3892 return t3_lshr(a, b);
3893 }
3894
3895 /* calculate a constant float result */
3896 virtual class vbignum_t *calc_result(
3897 const class vbignum_t &a, const class vbignum_t &b) const
3898 {
3899 G_tok->log_error(TCERR_BAD_OP_FOR_FLOAT);
3900 return 0;
3901 }
3902 };
3903
3904 /*
3905 * multiply
3906 */
3907 class CTcPrsOpMul: public CTcPrsOpArith
3908 {
3909 public:
3910 CTcPrsOpMul() : CTcPrsOpArith(TOKT_TIMES) { }
3911
3912 /* build a new tree out of our left-hand and right-hand subtrees */
3913 class CTcPrsNode
3914 *build_tree(class CTcPrsNode *left,
3915 class CTcPrsNode *right) const;
3916
3917 protected:
3918 /* calculate a constant integer result */
3919 long calc_result(long a, long b, int &ov) const
3920 {
3921 int64_t prod = a * b;
3922 ov = (prod > (int64_t)INT32MAXVAL || prod < (int64_t)INT32MINVAL);
3923 return (long)prod;
3924 }
3925
3926 /* calculate a constant float result */
3927 virtual class vbignum_t *calc_result(
3928 const class vbignum_t &a, const class vbignum_t &b) const;
3929 };
3930
3931 /*
3932 * divide
3933 */
3934 class CTcPrsOpDiv: public CTcPrsOpArith
3935 {
3936 public:
3937 CTcPrsOpDiv()
3938 : CTcPrsOpArith(TOKT_DIV) { }
3939
3940 CTcPrsOpDiv(tc_toktyp_t tok)
3941 : CTcPrsOpArith(tok) { }
3942
3943 /* build a new tree out of our left-hand and right-hand subtrees */
3944 class CTcPrsNode
3945 *build_tree(class CTcPrsNode *left,
3946 class CTcPrsNode *right) const;
3947
3948 protected:
3949 /* calculate a constant integer result */
3950 long calc_result(long a, long b, int &ov) const;
3951
3952 /* calculate a constant float result */
3953 virtual class vbignum_t *calc_result(
3954 const class vbignum_t &a, const class vbignum_t &b) const;
3955 };
3956
3957
3958 /*
3959 * mod - inherit from divide operator to pick up divide-by-zero checking
3960 */
3961 class CTcPrsOpMod: public CTcPrsOpDiv
3962 {
3963 public:
3964 CTcPrsOpMod() : CTcPrsOpDiv(TOKT_MOD) { }
3965
3966 /* build a new tree out of our left-hand and right-hand subtrees */
3967 class CTcPrsNode
3968 *build_tree(class CTcPrsNode *left,
3969 class CTcPrsNode *right) const;
3970
3971 protected:
3972 /* calculate a constant integer result */
3973 long calc_result(long a, long b, int &ov) const;
3974
3975 /* calculate a constant float result */
3976 virtual class vbignum_t *calc_result(
3977 const class vbignum_t &a, const class vbignum_t &b) const;
3978 };
3979
3980 /*
3981 * add
3982 */
3983 class CTcPrsOpAdd: public CTcPrsOpArith
3984 {
3985 public:
3986 CTcPrsOpAdd() : CTcPrsOpArith(TOKT_PLUS) { }
3987
3988 /* build a new tree out of our left-hand and right-hand subtrees */
3989 class CTcPrsNode
3990 *build_tree(class CTcPrsNode *left,
3991 class CTcPrsNode *right) const;
3992
3993 /* evaluate constant result */
3994 class CTcPrsNode
3995 *eval_constant(class CTcPrsNode *left,
3996 class CTcPrsNode *right) const;
3997
3998 protected:
3999 /* calculate a constant integer result */
4000 long calc_result(long a, long b, int &ov) const
4001 {
4002 int32_t sum = (int32_t)(a + b);
4003 ov = (a >= 0 ? b > 0 && sum < a : b < 0 && sum > a);
4004 return sum;
4005 }
4006
4007 /* calculate a constant float result */
4008 virtual class vbignum_t *calc_result(
4009 const class vbignum_t &a, const class vbignum_t &b) const;
4010 };
4011
4012 /*
4013 * subtract
4014 */
4015 class CTcPrsOpSub: public CTcPrsOpArith
4016 {
4017 public:
4018 CTcPrsOpSub() : CTcPrsOpArith(TOKT_MINUS) { }
4019
4020 /* build a new tree out of our left-hand and right-hand subtrees */
4021 class CTcPrsNode
4022 *build_tree(class CTcPrsNode *left,
4023 class CTcPrsNode *right) const;
4024
4025 /* evaluate constant result */
4026 class CTcPrsNode
4027 *eval_constant(class CTcPrsNode *left,
4028 class CTcPrsNode *right) const;
4029
4030 protected:
4031 /* calculate a constant integer result */
4032 long calc_result(long a, long b, int &ov) const
4033 {
4034 int32_t diff = (int32_t)(a - b);
4035 ov = (a >= 0 ? b < 0 && diff < a : b > 0 && diff > a);
4036 return diff;
4037 }
4038
4039 /* calculate a constant float result */
4040 virtual class vbignum_t *calc_result(
4041 const class vbignum_t &a, const class vbignum_t &b) const;
4042 };
4043
4044 /*
4045 * Unary Operators
4046 */
4047 class CTcPrsOpUnary: public CTcPrsOp
4048 {
4049 public:
4050 class CTcPrsNode *parse() const;
4051
4052 /*
4053 * evaluate a constant subscript expression; returns a constant
4054 * parse node expression if the subscript can be evaluated to a
4055 * compile-time constant, or null if not
4056 */
4057 static class CTcPrsNode
4058 *eval_const_subscript(class CTcPrsNode *lhs,
4059 class CTcPrsNode *subscript);
4060
4061 /*
4062 * evaluate a constant NOT expression; returns a constant parse node
4063 * expression if the logical negation can be evaluated to a
4064 * compile-time constant, or null if not
4065 */
4066 static class CTcPrsNode *eval_const_not(class CTcPrsNode *lhs);
4067
4068 /* parse a string with embedded expressions */
4069 static class CTcPrsNode *parse_embedding(struct CTcEmbedBuilder *builder);
4070
4071 /* parse a list */
4072 static class CTcPrsNode *parse_list();
4073
4074 /* parse a primary expression */
4075 static class CTcPrsNode *parse_primary();
4076
4077 /* parse an anonymous function */
4078 static class CTPNAnonFunc *parse_anon_func(int short_form, int is_method);
4079
4080 /* parse an in-line object definition */
4081 static class CTPNInlineObject *parse_inline_object(int has_colon);
4082
4083 protected:
4084 /* embedded expression: parse an expression list */
4085 static CTcPrsNode *parse_embedding_list(
4086 struct CTcEmbedBuilder *b, int &eos, struct CTcEmbedLevel *parent);
4087
4088 /* embedded expression: parse an <<if>> or <<unless>> embedding */
4089 static CTcPrsNode *parse_embedded_if(
4090 struct CTcEmbedBuilder *b, int unless,
4091 int &eos, struct CTcEmbedLevel *parent);
4092
4093 /* parse a single embedded expression */
4094 static CTcPrsNode *parse_embedded_expr(
4095 struct CTcEmbedBuilder *b, class CTcEmbedTokenList *tl);
4096
4097 /* embedded expression: parse an <<one of>> embedding */
4098 static CTcPrsNode *parse_embedded_oneof(
4099 struct CTcEmbedBuilder *b, int &eos, struct CTcEmbedLevel *parent);
4100
4101 /* embedded expression: parse an <<first time>>...<<only>> embedding */
4102 static CTcPrsNode *parse_embedded_firsttime(
4103 struct CTcEmbedBuilder *b, int &eos, struct CTcEmbedLevel *parent);
4104
4105 /* create the parse node for a <<one of>> structure */
4106 static CTcPrsNode *create_oneof_node(
4107 struct CTcEmbedBuilder *b, class CTPNList *lst, const char *attrs);
4108
4109 /* capture an embedded expression to a saved token list */
4110 static void capture_embedded(struct CTcEmbedBuilder *b,
4111 class CTcEmbedTokenList *tl);
4112
4113 /*
4114 * Match an end token for an embedded expression construct - <<end>>,
4115 * <<else>>, etc. This version parses captured tokens.
4116 */
4117 static int parse_embedded_end_tok(class CTcEmbedTokenList *tl,
4118 struct CTcEmbedLevel *parent,
4119 const char **open_kw);
4120
4121 /* parse an end token directly from the token stream */
4122 static int parse_embedded_end_tok(struct CTcEmbedBuilder *b,
4123 struct CTcEmbedLevel *parent,
4124 const char **open_kw);
4125
4126 /* parse a logical NOT operator */
4127 static class CTcPrsNode *parse_not(CTcPrsNode *sub);
4128
4129 /* parse a bitwise NOT operator */
4130 static class CTcPrsNode *parse_bnot(CTcPrsNode *sub);
4131
4132 /* parse an address-of operator */
4133 class CTcPrsNode *parse_addr() const;
4134
4135 /* parse an arithmetic positive operator */
4136 static class CTcPrsNode *parse_pos(CTcPrsNode *sub);
4137
4138 /* parse an arithmetic negative operator */
4139 static class CTcPrsNode *parse_neg(CTcPrsNode *sub);
4140
4141 /* parse a pre- or post-increment operator */
4142 static class CTcPrsNode *parse_inc(int pre, CTcPrsNode *sub);
4143
4144 /* parse a pre- or post-decrement operator */
4145 static class CTcPrsNode *parse_dec(int pre, CTcPrsNode *sub);
4146
4147 /* parse a 'new' operator */
4148 static class CTcPrsNode *parse_new(CTcPrsNode *sub, int is_transient);
4149
4150 /* parse a 'delete' operator */
4151 static class CTcPrsNode *parse_delete(CTcPrsNode *sub);
4152
4153 /* parse a postfix expression */
4154 static class CTcPrsNode *parse_postfix(int allow_member_expr,
4155 int allow_call_expr);
4156
4157 /* parse a function or method call */
4158 static class CTcPrsNode *parse_call(CTcPrsNode *lhs);
4159
4160 /* parse an argument list */
4161 static class CTPNArglist *parse_arg_list();
4162
4163 /* parse a subscript */
4164 static class CTcPrsNode *parse_subscript(CTcPrsNode *lhs);
4165
4166 /* parse a member selection ('.' operator) */
4167 static class CTcPrsNode *parse_member(CTcPrsNode *lhs);
4168
4169 /* parse an "inherited" expression */
4170 static class CTcPrsNode *parse_inherited();
4171
4172 /* parse a "delegated" expression */
4173 static class CTcPrsNode *parse_delegated();
4174 };
4175
4176 /*
4177 * if-nil operator ??
4178 */
4179 class CTcPrsOpIfnil: public CTcPrsOp
4180 {
4181 public:
4182 CTcPrsOpIfnil() { }
4183 class CTcPrsNode *parse() const;
4184 };
4185
4186 /*
4187 * tertiary conditional operator
4188 */
4189 class CTcPrsOpIf: public CTcPrsOp
4190 {
4191 public:
4192 CTcPrsOpIf() { }
4193 class CTcPrsNode *parse() const;
4194 };
4195
4196 /*
4197 * Assignment operators (including the regular assignment, "="/":=",
4198 * plus all calculate-and-assign operators: "+=", "-=", etc)
4199 */
4200 class CTcPrsOpAsi: public CTcPrsOp
4201 {
4202 public:
4203 CTcPrsOpAsi()
4204 {
4205 /* start out with the C-mode simple assignment operator */
4206 asi_op_ = TOKT_EQ;
4207 }
4208
4209 /* parse an assignment */
4210 class CTcPrsNode *parse() const;
4211
4212 /* set the current simple assignment operator */
4213 void set_asi_op(tc_toktyp_t tok) { asi_op_ = tok; }
4214
4215 private:
4216 /* current simple assignment operator */
4217 tc_toktyp_t asi_op_;
4218 };
4219
4220 #endif /* TCPRS_H */
4221