Debian Codegraph @

terps/tads/tads3/tcprs.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/tads3/TCPRS.CPP,v 1.5 1999/07/11 00:46:53 MJRoberts Exp $";
4 #endif
5
6 /*
7 * Copyright (c) 1999, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 tcprs.cpp - TADS 3 Compiler Parser
15 Function
16 This parser module contains code required for any parser usage, both
17 for a full compiler and for a debugger.
18 Notes
19
20 Modified
21 04/30/99 MJRoberts - Creation
22 */
23
24 #include <stdlib.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <assert.h>
28 #include <stdarg.h>
29
30 #include "os.h"
31 #include "t3std.h"
32 #include "tcprs.h"
33 #include "tctarg.h"
34 #include "tcgen.h"
35 #include "vmhash.h"
36 #include "tcmain.h"
37 #include "vmfile.h"
38 #include "tctok.h"
39 #include "vmbignum.h"
40
41
42 /* ------------------------------------------------------------------------ */
43 /*
44 * Expression Operator parser objects. These objects are linked
45 * together in a network that defines the order of precedence for
46 * expression operators.
47 *
48 * These objects use static storage. This is acceptable, even though
49 * these objects aren't all "const" qualified, because the compiler uses
50 * a single global parser object; since there's only the one parser,
51 * there only needs to be a single network of these objects.
52 */
53
54 /* unary operator parser */
55 static CTcPrsOpUnary S_op_unary;
56
57 /* factor group */
58 static const CTcPrsOpMul S_op_mul;
59 static const CTcPrsOpDiv S_op_div;
60 static const CTcPrsOpMod S_op_mod;
61 static const CTcPrsOpBin *const
62 S_grp_factor[] = { &S_op_mul, &S_op_div, &S_op_mod, 0 };
63 static const CTcPrsOpBinGroup S_op_factor(&S_op_unary, &S_op_unary,
64 S_grp_factor);
65
66 /* term group */
67 static const CTcPrsOpAdd S_op_add;
68 static const CTcPrsOpSub S_op_sub;
69 static const CTcPrsOpBin *const S_grp_term[] = { &S_op_add, &S_op_sub, 0 };
70 static const CTcPrsOpBinGroup S_op_term(&S_op_factor, &S_op_factor,
71 S_grp_term);
72
73 /* shift group */
74 static const CTcPrsOpShl S_op_shl;
75 static const CTcPrsOpAShr S_op_ashr;
76 static const CTcPrsOpLShr S_op_lshr;
77 static const CTcPrsOpBin *const S_grp_shift[] =
78 { &S_op_shl, &S_op_ashr, &S_op_lshr, 0 };
79 static const CTcPrsOpBinGroup S_op_shift(&S_op_term, &S_op_term,
80 S_grp_shift);
81
82 /* magnitude comparisons group */
83 static const CTcPrsOpGt S_op_gt;
84 static const CTcPrsOpGe S_op_ge;
85 static const CTcPrsOpLt S_op_lt;
86 static const CTcPrsOpLe S_op_le;
87 static const CTcPrsOpBin *const
88 S_grp_relcomp[] = { &S_op_gt, &S_op_ge, &S_op_lt, &S_op_le, 0 };
89 static const CTcPrsOpBinGroup S_op_relcomp(&S_op_shift, &S_op_shift,
90 S_grp_relcomp);
91
92 /*
93 * Equality/inequality comparison group. Note that the equality operator
94 * is non-const because we want the option to change the operator on the
95 * fly based on syntax mode - '==' in C-mode, '=' in TADS traditional mode.
96 * (This was a feature of tads 2, but we have since deprecated it in tads
97 * 3, so this ability is actually just vestigial at this point. No harm in
98 * keeping around the code internally for it, though, since it's pretty
99 * simple.)
100 *
101 * Note also that this is a special binary group - this one recognizes the
102 * non-keyword operators 'is in' and 'not in'.
103 */
104 static CTcPrsOpEq S_op_eq;
105 static const CTcPrsOpNe S_op_ne;
106 static const CTcPrsOpBin *const
107 S_grp_eqcomp[] = { &S_op_eq, &S_op_ne, 0 };
108 static const CTcPrsOpBinGroupCompare
109 S_op_eqcomp(&S_op_relcomp, &S_op_relcomp, S_grp_eqcomp);
110
111 /* bitwise AND operator */
112 static const CTcPrsOpBAnd S_op_band(&S_op_eqcomp, &S_op_eqcomp);
113
114 /* bitwise XOR operator */
115 static const CTcPrsOpBXor S_op_bxor(&S_op_band, &S_op_band);
116
117 /* bitwise OR operator */
118 static const CTcPrsOpBOr S_op_bor(&S_op_bxor, &S_op_bxor);
119
120 /* logical AND operator */
121 static const CTcPrsOpAnd S_op_and(&S_op_bor, &S_op_bor);
122
123 /* logical OR operator */
124 static const CTcPrsOpOr S_op_or(&S_op_and, &S_op_and);
125
126 /* if-nil operator ?? */
127 static const CTcPrsOpIfnil S_op_ifnil;
128
129 /* conditional operator */
130 static const CTcPrsOpIf S_op_if;
131
132 /*
133 * assignment operator - note that this is non-const, because we must be
134 * able to change the operator - '=' in C-mode, and ':=' in TADS
135 * traditional mode
136 */
137 static CTcPrsOpAsi S_op_asi;
138
139 /* comma operator */
140 static const CTcPrsOpComma S_op_comma(&S_op_asi, &S_op_asi);
141
142
143 /* ------------------------------------------------------------------------ */
144 /*
145 * Embedded expression token list. We capture the tokens of an embedded
146 * expression in a private list for a first scan, to compare against the
147 * list of special embedding templates. If we determine that the embedding
148 * is a simple expression, or that a portion of it is an expression, we'll
149 * push the captured tokens back into the token stream via 'unget'.
150 */
151 class CTcEmbedTokenList
152 {
153 public:
154 CTcEmbedTokenList()
155 {
156 /* create the initial list entry */
157 wrt = head = new CTcTokenEle();
158 cnt = 0;
159 }
160
161 ~CTcEmbedTokenList()
162 {
163 /* delete the token list */
164 while (head != 0)
165 {
166 CTcTokenEle *nxt = head->getnxt();
167 delete head;
168 head = nxt;
169 }
170 }
171
172 /* reset the list */
173 void reset()
174 {
175 /* set the read and write pointers to the allocated list head */
176 wrt = head;
177 cnt = 0;
178 }
179
180 /* get the number of tokens remaining */
181 int getcnt() const { return cnt; }
182
183 /* get the head elemenet */
184 const CTcToken *get_head() const { return head; }
185
186 /* remove the head element */
187 void unlink_head(CTcToken *tok)
188 {
189 if (head != 0)
190 {
191 /* copy the token to the caller's buffer */
192 G_tok->copytok(tok, head);
193
194 /* unlink it */
195 CTcTokenEle *h = head;
196 head = head->getnxt();
197 --cnt;
198
199 /* delete it */
200 delete h;
201 }
202 else
203 {
204 /* no token available - return EOF */
205 tok->settyp(TOKT_EOF);
206 }
207 }
208
209 /* add a token to the list */
210 void add_tok(const CTcToken *tok)
211 {
212 /* fill in the write token */
213 G_tok->copytok(wrt, tok);
214
215 /* if this is the last item in the list, add another */
216 if (wrt->getnxt() == 0)
217 {
218 CTcTokenEle *ele = new CTcTokenEle();
219 ele->setprv(wrt);
220 wrt->setnxt(ele);
221 }
222
223 /* advance the write pointer */
224 wrt = wrt->getnxt();
225
226 /* count it */
227 ++cnt;
228 }
229
230 /*
231 * Unget the captured tokens, skipping the first n tokens and the last
232 * m tokens.
233 */
234 void unget(int n = 0, int m = 0)
235 {
236 /* skip the last 'm' tokens */
237 CTcTokenEle *ele;
238 int i;
239 for (ele = wrt->getprv(), i = cnt ; m != 0 && ele != 0 ;
240 ele = ele->getprv(), --m, --i) ;
241
242 /* unget tokens until we're down to the first 'n' */
243 for ( ; ele != 0 && i > n ; ele = ele->getprv(), --i)
244 G_tok->unget(ele);
245 }
246
247 /* match a string of space-delimited tokens */
248 int match(const char *txt)
249 {
250 /* count the tokens */
251 int argn = 0;
252 const char *p;
253 for (p = txt ; *p != '\0' ; ++argn)
254 {
255 /* skip leading spaces */
256 for ( ; is_space(*p) ; ++p) ;
257
258 /* scan to the next space */
259 for ( ; *p != '\0' && !is_space(*p) ; ++p) ;
260 }
261
262 /* if we don't have enough tokens to match the input, we can't match */
263 if (cnt < argn)
264 return FALSE;
265
266 /* check the arguments against the list */
267 CTcTokenEle *ele;
268 int tokn;
269 for (tokn = cnt, ele = head, p = txt ; tokn != 0 && argn != 0 ;
270 ele = ele->getnxt(), --tokn, --argn)
271 {
272 /* get this argument */
273 for ( ; is_space(*p) ; ++p) ;
274 const char *arg = p;
275
276 /* find the end of the argument */
277 for ( ; *p != '\0' && !is_space(*p) ; ++p) ;
278 size_t len = p - arg;
279
280 /* check for special arguments */
281 if (arg[0] == '*')
282 {
283 /*
284 * '*' - this matches one or more tokens in the token list
285 * up to the last remaining arguments after the '*'. Skip
286 * arguments until the token list and remaining argument
287 * list are the same length.
288 */
289 for ( ; tokn > argn ; ele = ele->getnxt(), --tokn) ;
290 }
291 else
292 {
293 /* it's a literal - check for a match */
294 if (!ele->text_matches(arg, len))
295 return FALSE;
296 }
297 }
298
299 /* if the lists ran out at the same time, it's a match */
300 return (tokn == 0 && argn == 0);
301 }
302
303 /* match a string template definition */
304 int match(CTcStrTemplate *tpl)
305 {
306 /* if we don't have enough tokens to match, don't bother looking */
307 if (cnt < tpl->cnt)
308 return FALSE;
309
310 /* check the arguments against the list */
311 CTcTokenEle *ele, *tele;
312 int tokn, tpln;
313 for (tokn = cnt, tpln = tpl->cnt, ele = head, tele = tpl->head ;
314 tokn != 0 && tpln != 0 ;
315 ele = ele->getnxt(), tele = tele->getnxt(), --tokn, --tpln)
316 {
317 /* check for special arguments */
318 if (tele->text_matches("*", 1))
319 {
320 /*
321 * '*' - this matches one or more tokens in the token list
322 * up to the last remaining arguments after the '*'. Skip
323 * arguments until the token list and remaining argument
324 * list are the same length.
325 */
326 for ( ; tokn > tpln ; ele = ele->getnxt(), --tokn) ;
327 }
328 else
329 {
330 /* it's a literal - check for a match */
331 if (!ele->text_matches(tele->get_text(), tele->get_text_len()))
332 return FALSE;
333 }
334 }
335
336 /* if the lists ran out at the same time, it's a match */
337 return (tokn == 0 && tpln == 0);
338 }
339
340 /*
341 * Reduce our token list to include only the tokens matching the '*' in
342 * a template. This presumes that the template actually does match.
343 */
344 void reduce(CTcStrTemplate *tpl)
345 {
346 /* find the first token in our list matching '*' in the template */
347 CTcTokenEle *src, *tele;
348 int rem, trem;
349 for (src = head, tele = tpl->head, rem = cnt, trem = tpl->cnt ;
350 src != 0 && tele != 0 ;
351 src = src->getnxt(), tele = tele->getnxt(), --rem, --trem)
352 {
353 /* stop when we reach '*' in the template */
354 if (tele->text_matches("*", 1))
355 break;
356 }
357
358 /* skip the '*' in the template */
359 trem -= 1;
360
361 /*
362 * The number of tokens matching '*' is the number left in our
363 * list, minus the number left in the token list after the '*'.
364 */
365 rem -= trem;
366 cnt = rem;
367
368 /* if we had any leading fixed tokens to remove, remove them */
369 if (src != head)
370 {
371 CTcTokenEle *dst;
372 for (dst = head ; rem != 0 && src != 0 ;
373 src = src->getnxt(), dst = dst->getnxt(), --rem)
374 {
375 /* copy this token */
376 G_tok->copytok(dst, src);
377 }
378 }
379
380 /* move the write pointer to the proper position */
381 for (wrt = head, rem = cnt ; rem != 0 ; wrt = wrt->getnxt(), --rem) ;
382 }
383
384 protected:
385 /* head of the allocated list */
386 CTcTokenEle *head;
387
388 /* current write pointer */
389 CTcTokenEle *wrt;
390
391 /* number of tokens currently in the list */
392 int cnt;
393 };
394
395
396 /* ------------------------------------------------------------------------ */
397 /*
398 * Main Parser
399 */
400
401 /*
402 * initialize the parser
403 */
404 CTcParser::CTcParser()
405 {
406 size_t i;
407
408 /* we don't have any module information yet */
409 module_name_ = 0;
410 module_seqno_ = 0;
411
412 /* start out in normal mode */
413 pp_expr_mode_ = FALSE;
414 src_group_mode_ = FALSE;
415
416 /* create the global symbol table */
417 global_symtab_ = new CTcPrsSymtab(0);
418
419 /* no enclosing statement yet */
420 enclosing_stm_ = 0;
421
422 /* no source location yet */
423 cur_desc_ = 0;
424 cur_linenum_ = 0;
425
426 /* no dictionaries yet */
427 dict_cur_ = 0;
428 dict_head_ = dict_tail_ = 0;
429
430 /* no object file dictionary list yet */
431 obj_dict_list_ = 0;
432 obj_file_dict_idx_ = 0;
433
434 /* no dictionary properties yet */
435 dict_prop_head_ = 0;
436
437 /* no grammar productions yet */
438 gramprod_head_ = gramprod_tail_ = 0;
439
440 /* no object file symbol list yet */
441 obj_sym_list_ = 0;
442 obj_file_sym_idx_ = 0;
443
444 /* no object templates yet */
445 template_head_ = template_tail_ = 0;
446
447 /* allocate some initial template parsing space */
448 template_expr_max_ = 16;
449 template_expr_ = (CTcObjTemplateInst *)G_prsmem->
450 alloc(sizeof(template_expr_[0]) * template_expr_max_);
451
452 /* no string templates yet */
453 str_template_head_ = str_template_tail_ = 0;
454
455 /* no locals yet */
456 local_cnt_ = max_local_cnt_ = 0;
457
458 /* no local or goto symbol table yet */
459 local_symtab_ = 0;
460 enclosing_local_symtab_ = 0;
461 goto_symtab_ = 0;
462
463 /* no debugger local symbol table yet */
464 debug_symtab_ = 0;
465
466 /* not in a preprocessor constant expression */
467 pp_expr_mode_ = FALSE;
468
469 /* assume we're doing full compilation */
470 syntax_only_ = FALSE;
471
472 /* no nested top-level statements yet */
473 nested_stm_head_ = 0;
474 nested_stm_tail_ = 0;
475
476 /* no anonymous objects yet */
477 anon_obj_head_ = 0;
478 anon_obj_tail_ = 0;
479
480 /* no non-symbol objects yet */
481 nonsym_obj_head_ = 0;
482 nonsym_obj_tail_ = 0;
483
484 /* allocate an initial context variable property array */
485 ctx_var_props_size_ = 50;
486 ctx_var_props_ = (tctarg_prop_id_t *)
487 t3malloc(ctx_var_props_size_ * sizeof(tctarg_prop_id_t));
488
489 /* no context variable properties assigned yet */
490 ctx_var_props_cnt_ = 0;
491 ctx_var_props_used_ = 0;
492
493 /*
494 * no context variable indices assigned yet - start at one higher
495 * than the index at which we always store 'self'
496 */
497 next_ctx_arr_idx_ = TCPRS_LOCAL_CTX_METHODCTX + 1;
498
499 /* 'self' isn't valid yet */
500 self_valid_ = FALSE;
501
502 /* start at enum ID 1 (let 0 serve as an invalid value) */
503 next_enum_id_ = 1;
504
505 /* the '+' property is not yet defined */
506 plus_prop_ = 0;
507
508 /* no exported symbols yet */
509 exp_head_ = exp_tail_ = 0;
510
511 /* allocate an initial '+' stack */
512 plus_stack_alloc_ = 32;
513 plus_stack_ = (CTPNStmObject **)
514 t3malloc(plus_stack_alloc_ * sizeof(*plus_stack_));
515
516 /* clear out the stack */
517 for (i = 0 ; i < plus_stack_alloc_ ; ++i)
518 plus_stack_[i] = 0;
519
520 /* there's no current code body (function/method body) yet */
521 cur_code_body_ = 0;
522
523 /* nothing in the local context has been referenced yet */
524 self_referenced_ = FALSE;
525 local_ctx_needs_self_ = FALSE;
526 full_method_ctx_referenced_ = FALSE;
527 local_ctx_needs_full_method_ctx_ = FALSE;
528
529 /* create the embedded expression list object */
530 embed_toks_ = new CTcEmbedTokenList();
531 }
532
533 /*
534 * Add a special built-in property symbol
535 */
536 CTcSymProp *CTcParser::def_special_prop(int def, const char *name,
537 tc_prop_id *idp)
538 {
539 /* we haven't created or found the property yet */
540 CTcSymProp *propsym = 0;
541
542 /* define or look up the property, as required */
543 if (def)
544 {
545 /* allocate the ID */
546 tctarg_prop_id_t id = G_cg->new_prop_id();
547
548 /* create the symbol */
549 propsym = new CTcSymProp(name, strlen(name), FALSE, id);
550
551 /* mark it as referenced, since the compiler itself uses it */
552 propsym->mark_referenced();
553
554 /* add it to the global symbol table */
555 global_symtab_->add_entry(propsym);
556 }
557 else
558 {
559 /* find the entry */
560 CTcSymbol *sym = global_symtab_->find(name, strlen(name));
561
562 /* check to see if we found a property symbol */
563 if (sym != 0 && sym->get_type() == TC_SYM_PROP)
564 {
565 /* got it - use the definition we found */
566 propsym = (CTcSymProp *)sym;
567 }
568 else
569 {
570 /* not found - create a dummy symbol for it */
571 propsym = new CTcSymProp(name, strlen(name), FALSE,
572 TCTARG_INVALID_PROP);
573 }
574 }
575
576 /* hand the property ID back to the caller if they want it */
577 if (idp != 0)
578 *idp = (propsym != 0 ? propsym->get_prop() : TCTARG_INVALID_PROP);
579
580 /* return the symbol */
581 return propsym;
582 }
583
584 /*
585 * Initialize. This must be called after the code generator is set up.
586 */
587 void CTcParser::init()
588 {
589 /* define the special properties */
590 cache_special_props(TRUE);
591 }
592
593 /*
594 * Define or look up the special properties. If 'def' is true, we'll
595 * create definitions; otherwise we'll look up the definitions in the
596 * existing symbol table. The former case is for normal initialization of
597 * a new compiler; the latter is for use in dynamic compilation, where the
598 * global symbol table is provided by the running program.
599 */
600 void CTcParser::cache_special_props(int def)
601 {
602 tc_prop_id propid;
603
604 /* add a "construct" property for constructors */
605 constructor_sym_ = def_special_prop(def, "construct", &constructor_prop_);
606
607 /* add a "finalize" property for finalizers */
608 def_special_prop(def, "finalize", &finalize_prop_);
609
610 /* add some properties for grammar production match objects */
611 graminfo_prop_ = def_special_prop(def, "grammarInfo");
612 gramtag_prop_ = def_special_prop(def, "grammarTag");
613
614 /* add a "miscVocab" property for miscellaneous vocabulary words */
615 def_special_prop(def, "miscVocab", &propid);
616 miscvocab_prop_ = (tc_prop_id)propid;
617
618 /* add a "lexicalParent" property for a nested object's parent */
619 lexical_parent_sym_ = def_special_prop(def, "lexicalParent");
620
621 /* add a "sourceTextOrder" property */
622 src_order_sym_ = def_special_prop(def, "sourceTextOrder");
623
624 /* start the sourceTextOrder index at 1 */
625 src_order_idx_ = 1;
626
627 /* add a "sourceTextGroup" property */
628 src_group_sym_ = def_special_prop(def, "sourceTextGroup");
629
630 /* we haven't created the sourceTextGroup referral object yet */
631 src_group_id_ = TCTARG_INVALID_OBJ;
632
633 /* add a "sourceTextGroupName" property */
634 src_group_mod_sym_ = def_special_prop(def, "sourceTextGroupName");
635
636 /* add a "sourceTextGroupOrder" property */
637 src_group_seq_sym_ = def_special_prop(def, "sourceTextGroupOrder");
638
639 /* define the operator overload properties */
640 ov_op_add_ = def_special_prop(def, "operator +");
641 ov_op_sub_ = def_special_prop(def, "operator -");
642 ov_op_mul_ = def_special_prop(def, "operator *");
643 ov_op_div_ = def_special_prop(def, "operator /");
644 ov_op_mod_ = def_special_prop(def, "operator %");
645 ov_op_xor_ = def_special_prop(def, "operator ^");
646 ov_op_shl_ = def_special_prop(def, "operator <<");
647 ov_op_ashr_ = def_special_prop(def, "operator >>");
648 ov_op_lshr_ = def_special_prop(def, "operator >>>");
649 ov_op_bnot_ = def_special_prop(def, "operator ~");
650 ov_op_bor_ = def_special_prop(def, "operator |");
651 ov_op_band_ = def_special_prop(def, "operator &");
652 ov_op_neg_ = def_special_prop(def, "operator negate");
653 ov_op_idx_ = def_special_prop(def, "operator []");
654 ov_op_setidx_ = def_special_prop(def, "operator []=");
655 }
656
657 /* get the grammarTag property ID */
658 tc_prop_id CTcParser::get_grammarTag_prop() const
659 {
660 return gramtag_prop_ != 0
661 ? gramtag_prop_->get_prop()
662 : TCTARG_INVALID_PROP;
663 }
664
665 /* get the grammarInfo property ID */
666 tc_prop_id CTcParser::get_grammarInfo_prop() const
667 {
668 return graminfo_prop_ != 0
669 ? graminfo_prop_->get_prop()
670 : TCTARG_INVALID_PROP;
671 }
672
673
674 /*
675 * destroy the parser
676 */
677 CTcParser::~CTcParser()
678 {
679 /*
680 * Note that we don't have to delete certain objects, because we
681 * allocated them out of the parser memory pool and will be
682 * automatically deleted when the pool is deleted. For example, we
683 * don't have to delete any symbol tables, including the global
684 * symbol table.
685 */
686
687 /* delete the module name, if it's known */
688 lib_free_str(module_name_);
689
690 /* delete the object file symbol fixup list, if present */
691 if (obj_sym_list_ != 0)
692 t3free(obj_sym_list_);
693
694 /* delete the object file dictionary fixup list, if present */
695 if (obj_dict_list_ != 0)
696 t3free(obj_dict_list_);
697
698 /* delete the context variable property list */
699 if (ctx_var_props_ != 0)
700 t3free(ctx_var_props_);
701
702 /* delete the export list */
703 while (exp_head_ != 0)
704 {
705 CTcPrsExport *nxt;
706
707 /* remember the next entry, since we're deleting our pointer to it */
708 nxt = exp_head_->get_next();
709
710 /* delete this entry */
711 delete exp_head_;
712
713 /* move on to the next */
714 exp_head_ = nxt;
715 }
716
717 /* delete the '+' stack */
718 t3free(plus_stack_);
719
720 /* delete the embedding look-ahead list */
721 delete embed_toks_;
722 }
723
724 /* ------------------------------------------------------------------------ */
725 /*
726 * Set the module information
727 */
728 void CTcParser::set_module_info(const char *name, int seqno)
729 {
730 /* if we have a name stored already, delete the old one */
731 lib_free_str(module_name_);
732
733 /* store the new name and sequence number */
734 module_name_ = lib_copy_str(name);
735 module_seqno_ = seqno;
736 }
737
738 /*
739 * Change the #pragma C mode. On changing this mode, we'll change the
740 * assignment operator and equality operator tokens. If 'mode' is true,
741 * we're in C mode; otherwise, we're in traditional TADS mode.
742 *
743 * #pragma C+: assignment is '=', equality is '=='
744 *. #pragma C-: assignment is ':=', equality is '='.
745 */
746 void CTcParser::set_pragma_c(int mode)
747 {
748 /* set the assignment operator */
749 S_op_asi.set_asi_op(mode ? TOKT_EQ : TOKT_ASI);
750
751 /* set the equality comparison operator */
752 S_op_eq.set_eq_op(mode ? TOKT_EQEQ : TOKT_EQ);
753 }
754
755 /*
756 * Parse an expression. This parses a top-level comma expression.
757 */
758 CTcPrsNode *CTcParser::parse_expr()
759 {
760 /* parse a comma expression */
761 return S_op_comma.parse();
762 }
763
764 /*
765 * Parse a condition expression. Warns if the outermost operator is a
766 * simple assignment.
767 */
768 CTcPrsNode *CTcParser::parse_cond_expr()
769 {
770 CTcPrsNode *cond;
771
772 /* parse the expression */
773 cond = parse_expr();
774
775 /*
776 * if the outermost operator is a simple assignment, display an
777 * error
778 */
779 if (cond != 0 && cond->is_simple_asi() && !G_prs->get_syntax_only())
780 G_tok->log_warning(TCERR_ASI_IN_COND);
781
782 /* return the result */
783 return cond;
784 }
785
786 /*
787 * Parse an assignment expression.
788 */
789 CTcPrsNode *CTcParser::parse_asi_expr()
790 {
791 /* parse an assignment expression */
792 return S_op_asi.parse();
793 }
794
795 /*
796 * Parse an expression or a double-quoted string expression
797 */
798 CTcPrsNode *CTcParser::parse_expr_or_dstr(int allow_comma_expr)
799 {
800 /*
801 * parse the appropriate kind of expression - if a comma expression is
802 * allowed, parse that, otherwise parse an assignment expression (as
803 * that's the next thing down the hierarchy from the comma operator)
804 */
805 return (allow_comma_expr ? S_op_comma.parse() : S_op_asi.parse());
806 }
807
808 /*
809 * Parse a required semicolon
810 */
811 int CTcParser::parse_req_sem()
812 {
813 const char eof_str[] = "<end of file>";
814
815 /* check to see if we found the semicolon */
816 if (G_tok->cur() == TOKT_SEM)
817 {
818 /* success - skip the semicolon and tell the caller to proceed */
819 G_tok->next();
820 return 0;
821 }
822
823 /*
824 * check what we have; the type of error we want to log depends on
825 * what we find next
826 */
827 switch(G_tok->cur())
828 {
829 case TOKT_RPAR:
830 /* log the extra ')' error */
831 G_tok->log_error(TCERR_EXTRA_RPAR);
832
833 /*
834 * we're probably in an expression that ended before the user
835 * thought it should; skip the extraneous material up to the
836 * next semicolon
837 */
838 return skip_to_sem();
839
840 case TOKT_RBRACK:
841 /* log the error */
842 G_tok->log_error(TCERR_EXTRA_RBRACK);
843
844 /* skip up to the next semicolon */
845 return skip_to_sem();
846
847 case TOKT_EOF:
848 /*
849 * missing semicolon at end of file - log the missing-semicolon
850 * error and tell the caller not to proceed, since there's
851 * nothing left to parse
852 */
853 G_tok->log_error(TCERR_EXPECTED_SEMI,
854 (int)sizeof(eof_str)-1, eof_str);
855 return 1;
856
857 default:
858 /*
859 * the source is probably just missing a semicolon; log the
860 * error, and tell the caller to proceed from the current
861 * position
862 */
863 G_tok->log_error_curtok(TCERR_EXPECTED_SEMI);
864 return 0;
865 }
866 }
867
868 /*
869 * Skip to the next semicolon
870 */
871 int CTcParser::skip_to_sem()
872 {
873 /* keep going until we find a semicolon or some other reason to stop */
874 for (;;)
875 {
876 /* see what we have next */
877 switch(G_tok->cur())
878 {
879 case TOKT_EOF:
880 /* end of file - tell the caller not to proceed */
881 return 1;
882
883 case TOKT_SEM:
884 /*
885 * it's the semicolon at last - skip it and tell the caller
886 * to proceed
887 */
888 G_tok->next();
889 return 0;
890
891 case TOKT_LBRACE:
892 case TOKT_RBRACE:
893 /*
894 * Don't skip past braces - the caller probably simply left
895 * out a semicolon at the end of a statement, and we've now
896 * reached the next block start or end. Stop here and tell
897 * the caller to proceed.
898 */
899 return 0;
900
901 default:
902 /* skip anything else */
903 G_tok->next();
904 break;
905 }
906 }
907 }
908
909 /*
910 * Parse an operator name. Call this when the current token is 'operator'
911 * and an operator name is expected. We'll fill in 'tok' with the pseudo
912 * property name of the operator ("operator +", etc).
913 */
914 int CTcParser::parse_op_name(CTcToken *tok, int *op_argp)
915 {
916 const char *propname;
917 int ok = TRUE;
918 int op_args = 0;
919
920 /* get the actual operator */
921 switch (G_tok->next())
922 {
923 case TOKT_SYM:
924 /* check for named operators */
925 if (G_tok->getcur()->text_matches("negate"))
926 {
927 propname = "operator negate";
928 op_args = 1;
929 }
930 else
931 {
932 /* unknown symbolic operator name */
933 G_tok->log_error_curtok(TCERR_BAD_OP_OVERLOAD);
934 ok = FALSE;
935 propname = "unknown_operator";
936 }
937 break;
938
939 case TOKT_PLUS:
940 propname = "operator +";
941 op_args = 2;
942 break;
943
944 case TOKT_MINUS:
945 propname = "operator -";
946 op_args = 2;
947 break;
948
949 case TOKT_TIMES:
950 propname = "operator *";
951 op_args = 2;
952 break;
953
954 case TOKT_DIV:
955 propname = "operator /";
956 op_args = 2;
957 break;
958
959 case TOKT_MOD:
960 propname = "operator %";
961 op_args = 2;
962 break;
963
964 case TOKT_XOR:
965 propname = "operator ^";
966 op_args = 2;
967 break;
968
969 case TOKT_SHL:
970 propname = "operator <<";
971 op_args = 2;
972 break;
973
974 case TOKT_ASHR:
975 propname = "operator >>";
976 op_args = 2;
977 break;
978
979 case TOKT_LSHR:
980 propname = "operator >>>";
981 op_args = 2;
982 break;
983
984 case TOKT_BNOT:
985 propname = "operator ~";
986 op_args = 1;
987 break;
988
989 case TOKT_OR:
990 propname = "operator |";
991 op_args = 2;
992 break;
993
994 case TOKT_AND:
995 propname = "operator &";
996 op_args = 2;
997 break;
998
999 case TOKT_LBRACK:
1000 /* we need at least a ']', and a '=' can follow */
1001 if (G_tok->next() != TOKT_RBRACK)
1002 G_tok->log_error_curtok(TCERR_EXPECTED_RBRACK_IN_OP);
1003
1004 /* check what follows that */
1005 if (G_tok->next() == TOKT_EQ)
1006 {
1007 /* it's the assign-to-index operator []= */
1008 propname = "operator []=";
1009 op_args = 3;
1010 }
1011 else
1012 {
1013 /* it's just the regular index operator [] */
1014 propname = "operator []";
1015 op_args = 2;
1016
1017 /* put back our peek-ahead token */
1018 G_tok->unget();
1019 }
1020 break;
1021
1022 default:
1023 /* it's not an operator we can override */
1024 G_tok->log_error_curtok(TCERR_BAD_OP_OVERLOAD);
1025 propname = "unknown_operator";
1026 ok = FALSE;
1027 break;
1028 }
1029
1030 /* copy the property name to the token */
1031 tok->set_text(propname, strlen(propname));
1032
1033 /* set the caller's argument counter if desired */
1034 if (op_argp != 0)
1035 *op_argp = op_args;
1036
1037 /* return the success/error indication */
1038 return ok;
1039 }
1040
1041 /*
1042 * Create a symbol node
1043 */
1044 CTcPrsNode *CTcParser::create_sym_node(const textchar_t *sym, size_t sym_len)
1045 {
1046 /*
1047 * First, look up the symbol in local scope. Local scope symbols
1048 * can always be resolved during parsing, because the language
1049 * requires that local scope items be declared before their first
1050 * use.
1051 */
1052 CTcPrsSymtab *symtab;
1053 CTcSymbol *entry = local_symtab_->find(sym, sym_len, &symtab);
1054
1055 /* if we found it in local scope, return a resolved symbol node */
1056 if (entry != 0 && symtab != global_symtab_)
1057 return new CTPNSymResolved(entry);
1058
1059 /* if there's a debugger local scope, look it up there */
1060 if (debug_symtab_ != 0)
1061 {
1062 /* look it up in the debug symbol table */
1063 tcprsdbg_sym_info info;
1064 if (debug_symtab_->find_symbol(sym, sym_len, &info))
1065 {
1066 /* found it - return a debugger local variable */
1067 return new CTPNSymDebugLocal(&info);
1068 }
1069 }
1070
1071 /*
1072 * We didn't find it in local scope, so the symbol cannot be resolved
1073 * until code generation - return an unresolved symbol node. Note a
1074 * possible implicit self-reference, since this could be a property of
1075 * 'self'.
1076 */
1077 set_self_referenced(TRUE);
1078 return new CTPNSym(sym, sym_len);
1079 }
1080
1081 /*
1082 * Add a nested top-level statement to our list
1083 */
1084 void CTcParser::add_nested_stm(CTPNStmTop *stm)
1085 {
1086 /* link it into our list */
1087 if (nested_stm_tail_ != 0)
1088 nested_stm_tail_->set_next_stm_top(stm);
1089 else
1090 nested_stm_head_ = stm;
1091 nested_stm_tail_ = stm;
1092 }
1093
1094 /*
1095 * Add an anonymous object to our list
1096 */
1097 void CTcParser::add_anon_obj(CTcSymObj *sym)
1098 {
1099 /* link it into our list */
1100 if (anon_obj_tail_ != 0)
1101 anon_obj_tail_->nxt_ = sym;
1102 else
1103 anon_obj_head_ = sym;
1104 anon_obj_tail_ = sym;
1105
1106 /* it's the last one */
1107 sym->nxt_ = 0;
1108
1109 /* mark the symbol as anonymous */
1110 sym->set_anon(TRUE);
1111 }
1112
1113 /*
1114 * Add a non-symbolic object to our list
1115 */
1116 void CTcParser::add_nonsym_obj(tctarg_obj_id_t id)
1117 {
1118 tcprs_nonsym_obj *obj;
1119
1120 /* allocate a link structure */
1121 obj = new (G_prsmem) tcprs_nonsym_obj(id);
1122
1123 /* link it into our list */
1124 if (nonsym_obj_tail_ != 0)
1125 nonsym_obj_tail_->nxt_ = obj;
1126 else
1127 nonsym_obj_head_ = obj;
1128 nonsym_obj_tail_ = obj;
1129 }
1130
1131 /*
1132 * Basic routine to read a length-prefixed symbol. Uses the given
1133 * temporary buffer, then stores the text in tokenizer memory (which
1134 * remains valid and available throughout compilation). If the length
1135 * exceeds the temporary buffer length, we'll flag the given error and
1136 * return null. The length return pointer can be null if the caller wants
1137 * the results null-terminated rather than returned with a counted length.
1138 * If the length pointer is given, the result will not be null-terminated.
1139 *
1140 */
1141 const char *CTcParser::read_len_prefix_str
1142 (CVmFile *fp, char *tmp_buf, size_t tmp_buf_len, size_t *ret_len,
1143 int err_if_too_long)
1144 {
1145 size_t read_len;
1146 size_t alloc_len;
1147
1148 /* read the length to read from the file */
1149 read_len = (size_t)fp->read_uint2();
1150
1151 /* if we need null termination, add a byte to the allocation length */
1152 alloc_len = read_len + (ret_len == 0 ? 1 : 0);
1153
1154 /* if it won't fit in the temporary buffer, it's an error */
1155 if (alloc_len > tmp_buf_len)
1156 {
1157 /* log the error and return failure */
1158 G_tcmain->log_error(0, 0, TC_SEV_ERROR, err_if_too_long);
1159 return 0;
1160 }
1161
1162 /* read the bytes into the temporary buffer */
1163 fp->read_bytes(tmp_buf, read_len);
1164
1165 /* add null termination if required, or set the return length if not */
1166 if (ret_len == 0)
1167 tmp_buf[read_len] = '\0';
1168 else
1169 *ret_len = read_len;
1170
1171 /* store the result in the tokenizer's text list and return the result */
1172 return G_tok->store_source(tmp_buf, alloc_len);
1173 }
1174
1175 /*
1176 * Read a length prefixed string into a given buffer. Returns zero on
1177 * success, non-zero on failure.
1178 */
1179 int CTcParser::read_len_prefix_str(CVmFile *fp, char *buf, size_t buf_len,
1180 int err_if_too_long)
1181 {
1182 size_t read_len;
1183 size_t alloc_len;
1184
1185 /* read the length to read from the file */
1186 read_len = (size_t)fp->read_uint2();
1187
1188 /* add a byte for null termination */
1189 alloc_len = read_len + 1;
1190
1191 /* if it won't fit in the temporary buffer, it's an error */
1192 if (alloc_len > buf_len)
1193 {
1194 /* log the error and return failure */
1195 G_tcmain->log_error(0, 0, TC_SEV_ERROR, err_if_too_long);
1196 return 1;
1197 }
1198
1199 /* read the bytes into the caller's buffer */
1200 fp->read_bytes(buf, read_len);
1201
1202 /* add null termination */
1203 buf[read_len] = '\0';
1204
1205 /* success */
1206 return 0;
1207 }
1208
1209 /* ------------------------------------------------------------------------ */
1210 /*
1211 * Add a generated object
1212 */
1213 CTcSymObj *CTcParser::add_gen_obj(const char *clsname)
1214 {
1215 /* look up the class symbol */
1216 CTcSymObj *cls = (CTcSymObj *)global_symtab_->find(
1217 clsname, strlen(clsname));
1218
1219 /* make sure we found an object symbol */
1220 if (cls != 0 && cls->get_type() == TC_SYM_OBJ)
1221 {
1222 /* got it - go create the object */
1223 return add_gen_obj(cls);
1224 }
1225 else
1226 {
1227 /* not an object - return failure */
1228 return 0;
1229 }
1230 }
1231
1232 /*
1233 * Add a generated object.
1234 */
1235 CTcSymObj *CTcParser::add_gen_obj(CTcSymObj *cls)
1236 {
1237 /* check for dynamic compilation */
1238 if (G_vmifc != 0)
1239 {
1240 /* create a live object in the VM, and wrap it in an anon symbol */
1241 tctarg_obj_id_t clsid = (cls != 0 ? cls->get_obj_id() :
1242 TCTARG_INVALID_OBJ);
1243 return new CTcSymObj(".anon", 5, FALSE, G_vmifc->new_obj(clsid),
1244 FALSE, TC_META_TADSOBJ, 0);
1245 }
1246 else
1247 {
1248 /* static mode */
1249 return add_gen_obj_stat(cls);
1250 }
1251 }
1252
1253 /*
1254 * Add a constant property value to a generated object
1255 */
1256 void CTcParser::add_gen_obj_prop(
1257 CTcSymObj *obj, const char *propn, const CTcConstVal *val)
1258 {
1259 /* look up the property - this counts as an explicit definition */
1260 CTcSymbol *sym = G_prs->get_global_symtab()
1261 ->find_or_def_prop_explicit(propn, strlen(propn), FALSE);
1262
1263 /* make sure we found it, and that it's a property symbol */
1264 if (sym != 0 && sym->get_type() == TC_SYM_PROP)
1265 {
1266 /* it's a property symbol - cast it */
1267 CTcSymProp *prop = (CTcSymProp *)sym;
1268
1269 /* check for dynamic compilation */
1270 if (G_vmifc != 0)
1271 {
1272 /* dynamic mode - add it to the live object in the VM */
1273 G_vmifc->set_prop(obj->get_obj_id(), prop->get_prop(), val);
1274 }
1275 else
1276 {
1277 /* static compilation - add the value to the object statement */
1278 add_gen_obj_prop_stat(obj, prop, val);
1279 }
1280 }
1281 }
1282
1283 /*
1284 * add an integer property value to a generated object
1285 */
1286 void CTcParser::add_gen_obj_prop(CTcSymObj *obj, const char *prop, int val)
1287 {
1288 /* set up a constant structure for the value */
1289 CTcConstVal c;
1290 c.set_int(val);
1291
1292 /* set the property */
1293 add_gen_obj_prop(obj, prop, &c);
1294 }
1295
1296 /*
1297 * add a string property value to a generated object
1298 */
1299 void CTcParser::add_gen_obj_prop(CTcSymObj *obj, const char *prop,
1300 const char *val)
1301 {
1302 /* set up a constant structure for the value */
1303 CTcConstVal c;
1304 c.set_sstr(val, strlen(val));
1305
1306 /* set the property */
1307 add_gen_obj_prop(obj, prop, &c);
1308 }
1309
1310 /* ------------------------------------------------------------------------ */
1311 /*
1312 * Constant Value
1313 */
1314
1315 /*
1316 * set a string value
1317 */
1318 void CTcConstVal::set_sstr(const char *val, size_t len)
1319 {
1320 /* store the type */
1321 typ_ = TC_CVT_SSTR;
1322
1323 /* store a pointer to the string */
1324 val_.strval_.strval_ = val;
1325 val_.strval_.strval_len_ = len;
1326
1327 /* for image file layout purposes, record the length of this string */
1328 G_cg->note_str(len);
1329 }
1330
1331 void CTcConstVal::set_sstr(const CTcToken *tok)
1332 {
1333 /* get the string from the token */
1334 if (tok != 0)
1335 set_sstr(tok->get_text(), tok->get_text_len());
1336 else
1337 set_sstr("", 0);
1338 }
1339
1340 void CTcConstVal::set_sstr(uint32_t ofs)
1341 {
1342 typ_ = TC_CVT_SSTR;
1343 val_.strval_.strval_ = 0;
1344 val_.strval_.strval_len_ = 0;
1345 val_.strval_.pool_ofs_ = ofs;
1346 }
1347
1348 /*
1349 * Set a regex string value
1350 */
1351 void CTcConstVal::set_restr(const CTcToken *tok)
1352 {
1353 typ_ = TC_CVT_RESTR;
1354 val_.strval_.strval_ = tok->get_text();
1355 val_.strval_.strval_len_ = tok->get_text_len();
1356 val_.strval_.pool_ofs_ = 0;
1357 }
1358
1359 /*
1360 * BigNumber string formatter buffer allocator. Allocates a buffer of the
1361 * required size from the parser memory pool.
1362 */
1363 class CBigNumStringBufPrsAlo: public IBigNumStringBuf
1364 {
1365 public:
1366 virtual char *get_buf(size_t need)
1367 { return new (G_prsmem) char[need]; }
1368 };
1369
1370 /* set a floating point value from a token string */
1371 void CTcConstVal::set_float(const char *str, size_t len, int promoted)
1372 {
1373 /* set the float */
1374 typ_ = TC_CVT_FLOAT;
1375 val_.floatval_.txt_ = str;
1376 val_.floatval_.len_ = len;
1377 promoted_ = promoted;
1378 }
1379
1380 /* set a floating point value from a vbignum_t */
1381 void CTcConstVal::set_float(const vbignum_t *val, int promoted)
1382 {
1383 /* format the value */
1384 CBigNumStringBufPrsAlo alo;
1385 const char *buf = val->format(&alo);
1386
1387 /*
1388 * read the length from the buffer - vbignum_t::format() fills in the
1389 * buffer using the TADS String format, with a two-byte little-endian
1390 * (VMB_LEN) length prefix
1391 */
1392 size_t len = vmb_get_len(buf);
1393 buf += VMB_LEN;
1394
1395 /* store it */
1396 set_float(buf, len, promoted);
1397 }
1398
1399 /* set a floating point value from a promoted integer value */
1400 void CTcConstVal::set_float(ulong i)
1401 {
1402 /* set up the bignum value */
1403 vbignum_t b(i);
1404
1405 /* store it as a promoted integer value */
1406 set_float(&b, TRUE);
1407 }
1408
1409 /*
1410 * Try demoting a float back to an int. This can be used after a
1411 * constant-folding operation to turn a previously promoted float back to
1412 * an int if the result of the calculation now fits the int type.
1413 */
1414 void CTcConstVal::demote_float()
1415 {
1416 /* if this is a promoted integer, see if we can demote it back to int */
1417 if (typ_ == TC_CVT_FLOAT && promoted_)
1418 {
1419 /* get the BigNumber value */
1420 vbignum_t b(val_.floatval_.txt_, val_.floatval_.len_, 0);
1421
1422 /* convert it to an integer */
1423 int ov;
1424 int32_t i = b.to_int(ov);
1425
1426 /* if it didn't overflow, demote the constant back to an int */
1427 if (!ov)
1428 set_int(i);
1429 }
1430 }
1431
1432
1433 /*
1434 * set a list value
1435 */
1436 void CTcConstVal::set_list(CTPNList *lst)
1437 {
1438 /* set the type */
1439 typ_ = TC_CVT_LIST;
1440
1441 /* remember the list */
1442 val_.listval_.l_ = lst;
1443
1444 /* for image file layout purposes, record the length of this list */
1445 G_cg->note_list(lst->get_count());
1446 }
1447
1448 void CTcConstVal::set_list(uint32_t ofs)
1449 {
1450 typ_ = TC_CVT_LIST;
1451 val_.listval_.l_ = 0;
1452 val_.listval_.pool_ofs_ = ofs;
1453 }
1454
1455 /*
1456 * Convert a value to a string
1457 */
1458 const char *CTcConstVal::cvt_to_str(char *buf, size_t bufl,
1459 size_t *result_len)
1460 {
1461 /* check my type */
1462 switch(typ_)
1463 {
1464 case TC_CVT_NIL:
1465 /* the result is "nil" */
1466 if (bufl < 4)
1467 return 0;
1468
1469 strcpy(buf, "nil");
1470 *result_len = 3;
1471 return buf;
1472
1473 case TC_CVT_TRUE:
1474 /* the result is "true" */
1475 if (bufl < 5)
1476 return 0;
1477
1478 strcpy(buf, "true");
1479 *result_len = 4;
1480 return buf;
1481
1482 case TC_CVT_SSTR:
1483 /* it's already a string */
1484 *result_len = get_val_str_len();
1485 return get_val_str();
1486
1487 case TC_CVT_INT:
1488 /* convert our signed integer value */
1489 if (bufl < 12)
1490 return 0;
1491
1492 sprintf(buf, "%ld", get_val_int());
1493 *result_len = strlen(buf);
1494 return buf;
1495
1496 case TC_CVT_FLOAT:
1497 /* we store these as strings */
1498 *result_len = get_val_float_len();
1499 return get_val_float();
1500
1501 default:
1502 /* can't convert other types */
1503 return 0;
1504 }
1505 }
1506
1507 /* is this a numeric value equal to zero? */
1508 int CTcConstVal::equals_zero() const
1509 {
1510 /* check for integer zero */
1511 if (typ_ == TC_CVT_INT && get_val_int() == 0)
1512 return TRUE;
1513
1514 /* check for a float zero */
1515 if (typ_ == TC_CVT_FLOAT)
1516 {
1517 vbignum_t v(get_val_float(), get_val_float_len(), 0);
1518 return v.is_zero();
1519 }
1520
1521 /* not zero */
1522 return FALSE;
1523 }
1524
1525 /*
1526 * Compare for equality to another constant value
1527 */
1528 int CTcConstVal::is_equal_to(const CTcConstVal *val) const
1529 {
1530 CTPNListEle *ele1;
1531 CTPNListEle *ele2;
1532
1533 /* check for float-int comparisons */
1534 if (typ_ == TC_CVT_INT && val->get_type() == TC_CVT_FLOAT)
1535 {
1536 vbignum_t a(get_val_int());
1537 vbignum_t b(val->get_val_float(), val->get_val_float_len(), 0);
1538 return a.compare(b) == 0;
1539 }
1540 if (typ_ == TC_CVT_FLOAT && val->get_type() == TC_CVT_INT)
1541 {
1542 vbignum_t a(get_val_float(), get_val_float_len(), 0);
1543 vbignum_t b(val->get_val_int());
1544 return a.compare(b) == 0;
1545 }
1546
1547 /*
1548 * if the types aren't equal, the values are not equal; otherwise,
1549 * check the various types
1550 */
1551 if (typ_ != val->get_type())
1552 {
1553 /* the types aren't equal, so the values are not equal */
1554 return FALSE;
1555 }
1556
1557 /* the types are the same; do the comparison based on the type */
1558 switch(typ_)
1559 {
1560 case TC_CVT_UNK:
1561 /* unknown type; unknown values can never be equal */
1562 return FALSE;
1563
1564 case TC_CVT_TRUE:
1565 case TC_CVT_NIL:
1566 /*
1567 * nil==nil and true==true; since we know the types are the
1568 * same, the values are the same
1569 */
1570 return TRUE;
1571
1572 case TC_CVT_INT:
1573 /* compare the integers */
1574 return (get_val_int() == val->get_val_int());
1575
1576 case TC_CVT_FLOAT:
1577 {
1578 vbignum_t a(get_val_float(), get_val_float_len(), 0);
1579 vbignum_t b(val->get_val_float(), val->get_val_float_len(), 0);
1580 return a.compare(b) == 0;
1581 }
1582
1583 case TC_CVT_SSTR:
1584 /* compare the strings */
1585 return (get_val_str_len() == val->get_val_str_len()
1586 && memcmp(get_val_str(), val->get_val_str(),
1587 get_val_str_len()) == 0);
1588
1589 case TC_CVT_LIST:
1590 /*
1591 * if the lists don't have the same number of elements, they're
1592 * not equal
1593 */
1594 if (get_val_list()->get_count() != val->get_val_list()->get_count())
1595 return FALSE;
1596
1597 /*
1598 * compare each element of each list; if they're all the same,
1599 * the values are the same
1600 */
1601 ele1 = get_val_list()->get_head();
1602 ele2 = val->get_val_list()->get_head();
1603 for ( ; ele1 != 0 && ele2 != 0 ;
1604 ele1 = ele1->get_next(), ele2 = ele2->get_next())
1605 {
1606 /* if these elements aren't equal, the lists aren't equal */
1607 if (!ele1->get_expr()->get_const_val()
1608 ->is_equal_to(ele2->get_expr()->get_const_val()))
1609 return FALSE;
1610 }
1611
1612 /* we didn't find any differences, so the lists are equal */
1613 return TRUE;
1614
1615 case TC_CVT_OBJ:
1616 /* if the object values are the same, the values match */
1617 return (get_val_obj() == val->get_val_obj());
1618
1619 case TC_CVT_PROP:
1620 /* if the property values are the same, the values match */
1621 return (get_val_prop() == val->get_val_prop());
1622
1623 case TC_CVT_FUNCPTR:
1624 /*
1625 * if both symbols are the same, the values match; otherwise,
1626 * they refer to different functions
1627 */
1628 return (get_val_funcptr_sym() == val->get_val_funcptr_sym());
1629
1630 default:
1631 /* unknown type; return unequal */
1632 return FALSE;
1633 }
1634 }
1635
1636
1637 /* ------------------------------------------------------------------------ */
1638 /*
1639 * Operator Parsers
1640 */
1641
1642 /* ------------------------------------------------------------------------ */
1643 /*
1644 * Parse a left-associative binary operator
1645 */
1646 CTcPrsNode *CTcPrsOpBin::parse() const
1647 {
1648 /* parse our left side - if that fails, return failure */
1649 CTcPrsNode *lhs = left_->parse();
1650 if (lhs == 0)
1651 return 0;
1652
1653 /* keep going as long as we find our operator */
1654 for (;;)
1655 {
1656 /* check my operator */
1657 if (G_tok->cur() == get_op_tok())
1658 {
1659 /* skip the matching token */
1660 G_tok->next();
1661
1662 /* parse the right-hand side */
1663 CTcPrsNode *rhs = right_->parse();
1664 if (rhs == 0)
1665 return 0;
1666
1667 /* try folding our subnodes into a constant value, if possible */
1668 CTcPrsNode *const_tree = eval_constant(lhs, rhs);
1669
1670 /*
1671 * if we couldn't calculate a constant value, build the tree
1672 * normally
1673 */
1674 if (const_tree == 0)
1675 {
1676 /*
1677 * Build my tree, then proceed to parse any additional
1678 * occurrences of our operator, with the result of
1679 * applying this occurrence of the operator as the
1680 * left-hand side of the new operator.
1681 */
1682 lhs = build_tree(lhs, rhs);
1683 }
1684 else
1685 {
1686 /* we got a constant value - use it as the result directly */
1687 lhs = const_tree;
1688 }
1689 }
1690 else
1691 {
1692 /*
1693 * it's not my operator - return what we thought might have
1694 * been our left-hand side
1695 */
1696 return lhs;
1697 }
1698 }
1699 }
1700
1701 /* ------------------------------------------------------------------------ */
1702 /*
1703 * Parse a group of left-associative binary operators at the same
1704 * precedence level
1705 */
1706 CTcPrsNode *CTcPrsOpBinGroup::parse() const
1707 {
1708 /* parse our left side - if that fails, return failure */
1709 CTcPrsNode *lhs = left_->parse();
1710 if (lhs == 0)
1711 return 0;
1712
1713 /* keep going as long as we find one of our operators */
1714 while (find_and_apply_op(&lhs)) ;
1715
1716 /* return the expression tree */
1717 return lhs;
1718 }
1719
1720 /*
1721 * Find an apply one of our operators to the already-parsed left-hand
1722 * side. Returns true if we found an operator, false if not.
1723 */
1724 int CTcPrsOpBinGroup::find_and_apply_op(CTcPrsNode **lhs) const
1725 {
1726 /* check each operator at this precedence level */
1727 for (const CTcPrsOpBin *const *op = ops_ ; *op != 0 ; ++op)
1728 {
1729 /* check this operator's token */
1730 if (G_tok->cur() == (*op)->get_op_tok())
1731 {
1732 /* skip the operator token */
1733 G_tok->next();
1734
1735 /* parse the right-hand side */
1736 CTcPrsNode *rhs = right_->parse();
1737 if (rhs == 0)
1738 {
1739 /* error - cancel the entire expression */
1740 *lhs = 0;
1741 return FALSE;
1742 }
1743
1744 /* try folding our subnodes into a constant value */
1745 CTcPrsNode *const_tree = (*op)->eval_constant(*lhs, rhs);
1746
1747 /*
1748 * if we couldn't calculate a constant value, build the tree
1749 * normally
1750 */
1751 if (const_tree == 0)
1752 {
1753 /*
1754 * build my tree, replacing the original left-hand side
1755 * with the new expression
1756 */
1757 *lhs = (*op)->build_tree(*lhs, rhs);
1758 }
1759 else
1760 {
1761 /* we got a constant value - use it as the result */
1762 *lhs = const_tree;
1763 }
1764
1765 /*
1766 * Tell the caller to proceed to parse any additional
1767 * occurrences of our operator - this will apply the next
1768 * occurrence of the operator as the left-hand side of the
1769 * new operator.
1770 */
1771 return TRUE;
1772 }
1773 }
1774
1775 /*
1776 * if we got here, we didn't find an operator - tell the caller that
1777 * we've reached the end of this operator's possible span
1778 */
1779 return FALSE;
1780 }
1781
1782
1783 /* ------------------------------------------------------------------------ */
1784 /*
1785 * Comparison operator group
1786 */
1787 CTcPrsNode *CTcPrsOpBinGroupCompare::parse() const
1788 {
1789 /* parse our left side - if that fails, return failure */
1790 CTcPrsNode *lhs = left_->parse();
1791 if (lhs == 0)
1792 return 0;
1793
1794 /* keep going as long as we find one of our operators */
1795 for (;;)
1796 {
1797 /*
1798 * try one of our regular operators - if we find it, go back for
1799 * another round to see if there's another operator following
1800 * the next expression
1801 */
1802 if (find_and_apply_op(&lhs))
1803 continue;
1804
1805 /*
1806 * check for the 'is in' operator - 'is' and 'in' aren't
1807 * keywords, so we must check for symbol tokens with the text of
1808 * these context-sensitive keywords
1809 */
1810 if (G_tok->cur() == TOKT_SYM
1811 && G_tok->getcur()->text_matches("is", 2))
1812 {
1813 /* we have 'is' - get the next token and check if it's 'in' */
1814 if (G_tok->next() == TOKT_SYM
1815 && G_tok->getcur()->text_matches("in", 2))
1816 {
1817 /* scan the expression list */
1818 CTPNArglist *rhs = parse_inlist();
1819 if (rhs == 0)
1820 return 0;
1821
1822 /* build the node */
1823 lhs = new CTPNIsIn(lhs, rhs);
1824
1825 /*
1826 * we've applied the 'is in' operator - go back for
1827 * another operator from the comparison group
1828 */
1829 continue;
1830 }
1831 else
1832 {
1833 /* it's not 'is in' - throw back the token and keep looking */
1834 G_tok->unget();
1835 }
1836 }
1837
1838 /*
1839 * Check for the 'not in' operator
1840 */
1841 if (G_tok->cur() == TOKT_SYM
1842 && G_tok->getcur()->text_matches("not", 3))
1843 {
1844 /* we have 'is' - get the next token and check if it's 'in' */
1845 if (G_tok->next() == TOKT_SYM
1846 && G_tok->getcur()->text_matches("in", 2))
1847 {
1848 /* scan the expression list */
1849 CTPNArglist *rhs = parse_inlist();
1850 if (rhs == 0)
1851 return 0;
1852
1853 /* build the node */
1854 lhs = new CTPNNotIn(lhs, rhs);
1855
1856 /*
1857 * we've applied the 'is in' operator - go back for
1858 * another operator from the comparison group
1859 */
1860 continue;
1861 }
1862 else
1863 {
1864 /* it's not 'is in' - throw back the token and keep looking */
1865 G_tok->unget();
1866 }
1867 }
1868
1869 /* we didn't find any of our operators - we're done */
1870 break;
1871 }
1872
1873 /* return the expression */
1874 return lhs;
1875 }
1876
1877 /*
1878 * parse the list for the right-hand side of an 'is in' or 'not in'
1879 * expression
1880 */
1881 CTPNArglist *CTcPrsOpBinGroupCompare::parse_inlist() const
1882 {
1883 int argc;
1884 CTPNArg *arg_head;
1885 CTPNArg *arg_tail;
1886
1887 /* skip the second keyword token, and check for an open paren */
1888 if (G_tok->next() == TOKT_LPAR)
1889 {
1890 /* skip the paren */
1891 G_tok->next();
1892 }
1893 else
1894 {
1895 /*
1896 * log an error, and keep going on the assumption that it was
1897 * merely omitted and the rest of the list is well-formed
1898 */
1899 G_tok->log_error_curtok(TCERR_IN_REQ_LPAR);
1900 }
1901
1902 /* keep going until we find the close paren */
1903 for (argc = 0, arg_head = arg_tail = 0 ;; )
1904 {
1905 CTcPrsNode *expr;
1906 CTPNArg *arg_cur;
1907
1908 /* if this is the close paren, we're done */
1909 if (G_tok->cur() == TOKT_RPAR)
1910 break;
1911
1912 /* parse this expression */
1913 expr = S_op_asi.parse();
1914 if (expr == 0)
1915 return 0;
1916
1917 /* count the argument */
1918 ++argc;
1919
1920 /* create a new argument node */
1921 arg_cur = new CTPNArg(expr);
1922
1923 /*
1924 * link the new node at the end of our list (this preserves the
1925 * order of the original list)
1926 */
1927 if (arg_tail != 0)
1928 arg_tail->set_next_arg(arg_cur);
1929 else
1930 arg_head = arg_cur;
1931 arg_tail = arg_cur;
1932
1933 /* we need to be looking at a comma or right paren */
1934 if (G_tok->cur() == TOKT_RPAR)
1935 {
1936 /* that's the end of the list */
1937 break;
1938 }
1939 else if (G_tok->cur() == TOKT_COMMA)
1940 {
1941 /* skip the comma and parse the next argument */
1942 G_tok->next();
1943 }
1944 else
1945 {
1946 /*
1947 * If we're at the end of the file, there's no point
1948 * proceding, so return failure. If we've reached something
1949 * that looks like a statement separator (semicolon, curly
1950 * brace), also return failure, since the problem is clearly
1951 * a missing right paren. Otherwise, assume that a comma
1952 * was missing and continue as though we have another
1953 * argument.
1954 */
1955 switch(G_tok->cur())
1956 {
1957 default:
1958 /* log an error */
1959 G_tok->log_error_curtok(TCERR_EXPECTED_IN_COMMA);
1960
1961 /*
1962 * if we're at the end of file, return what we have so
1963 * far; otherwise continue, assuming that they merely
1964 * left out a comma between two argument expressions
1965 */
1966 if (G_tok->cur() == TOKT_EOF)
1967 return new CTPNArglist(argc, arg_head);
1968 break;
1969
1970 case TOKT_SEM:
1971 case TOKT_LBRACE:
1972 case TOKT_RBRACE:
1973 case TOKT_DSTR_MID:
1974 case TOKT_DSTR_END:
1975 /*
1976 * we're apparently at the end of the statement; flag
1977 * the error as a missing right paren, and return what
1978 * we have so far
1979 */
1980 G_tok->log_error_curtok(TCERR_EXPECTED_IN_RPAR);
1981 return new CTPNArglist(argc, arg_head);
1982 }
1983 }
1984 }
1985
1986 /* skip the closing paren */
1987 G_tok->next();
1988
1989 /* create and return the argument list descriptor */
1990 return new CTPNArglist(argc, arg_head);
1991 }
1992
1993 /* ------------------------------------------------------------------------ */
1994 /*
1995 * Comma Operator
1996 */
1997
1998 /*
1999 * try to evaluate a constant expression
2000 */
2001 CTcPrsNode *CTcPrsOpComma::eval_constant(CTcPrsNode *left,
2002 CTcPrsNode *right) const
2003 {
2004 /*
2005 * if both sides are constants, the result is the constant on the
2006 * right side; we can't simply fold down to a right-side constant if
2007 * the left side is not constant, though, because we must still
2008 * evaluate the left side at run-time for any possible side effects
2009 */
2010 if (left->is_const() && right->is_const())
2011 {
2012 /* both are constants - simply return the right constant value */
2013 return right;
2014 }
2015 else
2016 {
2017 /*
2018 * one or the other is non-constant, so we can't fold the
2019 * expression - return null to so indicate
2020 */
2021 return 0;
2022 }
2023 }
2024
2025 /*
2026 * build a subtree for the comma operator
2027 */
2028 CTcPrsNode *CTcPrsOpComma::build_tree(CTcPrsNode *left,
2029 CTcPrsNode *right) const
2030 {
2031 return new CTPNComma(left, right);
2032 }
2033
2034 /* ------------------------------------------------------------------------ */
2035 /*
2036 * logical OR operator
2037 */
2038
2039 /*
2040 * try to evaluate a constant expression
2041 */
2042 CTcPrsNode *CTcPrsOpOr::eval_constant(CTcPrsNode *left,
2043 CTcPrsNode *right) const
2044 {
2045 /* check for constants */
2046 if (left->is_const())
2047 {
2048 CTcPrsNode *ret;
2049
2050 /*
2051 * Check for constants. If the first expression is constant,
2052 * the result will always be either 'true' (if the first
2053 * expression's constant value is true), or the value of the
2054 * second expression (if the first expression's constant value
2055 * is 'nil').
2056 *
2057 * Note that it doesn't matter whether or not the right side is
2058 * a constant. If the left is true, the right will never be
2059 * executed because of the short-circuit logic; if the left is
2060 * nil, the result will always be the result of the right value.
2061 */
2062 if (left->get_const_val()->get_val_bool())
2063 {
2064 /*
2065 * the left is true, so the result is always true, and the
2066 * right never gets executed
2067 */
2068 ret = left;
2069 }
2070 else
2071 {
2072 /* the left is nil, so the result is the right value */
2073 ret = right;
2074 }
2075
2076 /* ensure the result is a boolean value */
2077 if (ret->is_const())
2078 {
2079 /* make it a true/nil constant value */
2080 ret->get_const_val()
2081 ->set_bool(ret->get_const_val()->get_val_bool());
2082 }
2083 else
2084 {
2085 /* boolean-ize the value at run-time as needed */
2086 ret = new CTPNBoolize(ret);
2087 }
2088
2089 /* return the result */
2090 return ret;
2091 }
2092 else
2093 {
2094 /*
2095 * one or the other is non-constant, so we can't fold the
2096 * expression - return null to so indicate
2097 */
2098 return 0;
2099 }
2100 }
2101
2102 /*
2103 * build the subtree
2104 */
2105 CTcPrsNode *CTcPrsOpOr::build_tree(CTcPrsNode *left,
2106 CTcPrsNode *right) const
2107 {
2108 return new CTPNOr(left, right);
2109 }
2110
2111 /* ------------------------------------------------------------------------ */
2112 /*
2113 * logical AND operator
2114 */
2115
2116 /*
2117 * try to evaluate a constant expression
2118 */
2119 CTcPrsNode *CTcPrsOpAnd::eval_constant(CTcPrsNode *left,
2120 CTcPrsNode *right) const
2121 {
2122 /*
2123 * Check for constants. If the first expression is constant, the
2124 * result will always be either 'nil' (if the first expression's
2125 * constant value is nil), or the value of the second expression (if
2126 * the first expression's constant value is 'true').
2127 *
2128 * Note that it doesn't matter whether or not the right side is a
2129 * constant. If the left is nil, the right will never be executed
2130 * because of the short-circuit logic; if the left is true, the
2131 * result will always be the result of the right value.
2132 */
2133 if (left->is_const())
2134 {
2135 CTcPrsNode *ret;
2136
2137 /*
2138 * The left value is a constant, so we can eliminate the &&. If
2139 * the left value is nil, the result is nil; otherwise, it's the
2140 * right half.
2141 */
2142 if (left->get_const_val()->get_val_bool())
2143 {
2144 /* the left side is true - the result is the right side */
2145 ret = right;
2146 }
2147 else
2148 {
2149 /*
2150 * The left side is nil - the result is nil, and the right
2151 * side never gets executed.
2152 */
2153 ret = left;
2154 }
2155
2156 /* ensure the result is a boolean value */
2157 if (ret->is_const())
2158 {
2159 /* make it a true/nil constant value */
2160 ret->get_const_val()
2161 ->set_bool(ret->get_const_val()->get_val_bool());
2162 }
2163 else
2164 {
2165 /* boolean-ize the value at run-time as needed */
2166 ret = new CTPNBoolize(ret);
2167 }
2168
2169 /* return the result */
2170 return ret;
2171 }
2172 else
2173 {
2174 /*
2175 * one or the other is non-constant, so we can't fold the
2176 * expression - return null to so indicate
2177 */
2178 return 0;
2179 }
2180 }
2181
2182 /*
2183 * build the subtree
2184 */
2185 CTcPrsNode *CTcPrsOpAnd::build_tree(CTcPrsNode *left,
2186 CTcPrsNode *right) const
2187 {
2188 return new CTPNAnd(left, right);
2189 }
2190
2191 /* ------------------------------------------------------------------------ */
2192 /*
2193 * Generic Comparison Operator parser base class
2194 */
2195
2196 /*
2197 * evaluate a constant expression
2198 */
2199 CTcPrsNode *CTcPrsOpRel::eval_constant(CTcPrsNode *left,
2200 CTcPrsNode *right) const
2201 {
2202 /* check for constants */
2203 if (left->is_const() && right->is_const())
2204 {
2205 /* get the types */
2206 CTcConstVal *c1 = left->get_const_val();
2207 CTcConstVal *c2 = right->get_const_val();
2208 tc_constval_type_t typ1 = c1->get_type();
2209 tc_constval_type_t typ2 = c2->get_type();
2210
2211 /* determine what we're comparing */
2212 int sense;
2213 if (typ1 == TC_CVT_INT && typ2 == TC_CVT_INT)
2214 {
2215 /* get the values */
2216 long val1 = c1->get_val_int();
2217 long val2 = c2->get_val_int();
2218
2219 /* calculate the sense of the integer comparison */
2220 sense = (val1 < val2 ? -1 : val1 == val2 ? 0 : 1);
2221 }
2222 else if (typ1 == TC_CVT_SSTR && typ2 == TC_CVT_SSTR)
2223 {
2224 /* compare the string values */
2225 sense = strcmp(c1->get_val_str(), c2->get_val_str());
2226 }
2227 else if (typ1 == TC_CVT_FLOAT && typ2 == TC_CVT_FLOAT)
2228 {
2229 /* both are floats - get as BigNumber values */
2230 vbignum_t a(c1->get_val_float(), c1->get_val_float_len(), 0);
2231 vbignum_t b(c2->get_val_float(), c2->get_val_float_len(), 0);
2232 sense = a.compare(b);
2233 }
2234 else if (typ1 == TC_CVT_FLOAT && typ2 == TC_CVT_INT)
2235 {
2236 /* float vs int */
2237 vbignum_t a(c1->get_val_float(), c1->get_val_float_len(), 0);
2238 vbignum_t b(c2->get_val_int());
2239 sense = a.compare(b);
2240 }
2241 else if (typ1 == TC_CVT_INT && typ2 == TC_CVT_FLOAT)
2242 {
2243 vbignum_t a(c1->get_val_int());
2244 vbignum_t b(c2->get_val_float(), c2->get_val_float_len(), 0);
2245 sense = a.compare(b);
2246 }
2247 else
2248 {
2249 /* these types are incomparable */
2250 G_tok->log_error(TCERR_CONST_BAD_COMPARE,
2251 G_tok->get_op_text(get_op_tok()));
2252 return 0;
2253 }
2254
2255 /* set the result in the left value */
2256 c1->set_bool(get_bool_val(sense));
2257
2258 /* return the updated left value */
2259 return left;
2260 }
2261 else
2262 {
2263 /*
2264 * one or the other is non-constant, so we can't fold the
2265 * expression - return null to so indicate
2266 */
2267 return 0;
2268 }
2269 }
2270
2271
2272 /* ------------------------------------------------------------------------ */
2273 /*
2274 * greater-than operator
2275 */
2276
2277 /*
2278 * build the subtree
2279 */
2280 CTcPrsNode *CTcPrsOpGt::build_tree(CTcPrsNode *left,
2281 CTcPrsNode *right) const
2282 {
2283 return new CTPNGt(left, right);
2284 }
2285
2286 /* ------------------------------------------------------------------------ */
2287 /*
2288 * less-than operator
2289 */
2290
2291 /*
2292 * build the subtree
2293 */
2294 CTcPrsNode *CTcPrsOpLt::build_tree(CTcPrsNode *left,
2295 CTcPrsNode *right) const
2296 {
2297 return new CTPNLt(left, right);
2298 }
2299
2300 /* ------------------------------------------------------------------------ */
2301 /*
2302 * greater-or-equal operator
2303 */
2304
2305 /*
2306 * build the subtree
2307 */
2308 CTcPrsNode *CTcPrsOpGe::build_tree(CTcPrsNode *left,
2309 CTcPrsNode *right) const
2310 {
2311 return new CTPNGe(left, right);
2312 }
2313
2314 /* ------------------------------------------------------------------------ */
2315 /*
2316 * less-or-equal operator
2317 */
2318
2319 /*
2320 * build the subtree
2321 */
2322 CTcPrsNode *CTcPrsOpLe::build_tree(CTcPrsNode *left,
2323 CTcPrsNode *right) const
2324 {
2325 return new CTPNLe(left, right);
2326 }
2327
2328 /* ------------------------------------------------------------------------ */
2329 /*
2330 * General equality/inequality operators base class
2331 */
2332
2333 /*
2334 * evaluate a constant expression
2335 */
2336 CTcPrsNode *CTcPrsOpEqComp::eval_constant(CTcPrsNode *left,
2337 CTcPrsNode *right) const
2338 {
2339 int ops_equal;
2340
2341 /* check for constants */
2342 if (left->is_const() && right->is_const())
2343 {
2344 /* both sides are constants - determine if they're equal */
2345 ops_equal = left->get_const_val()
2346 ->is_equal_to(right->get_const_val());
2347
2348 /* set the result in the left value */
2349 left->get_const_val()->set_bool(get_bool_val(ops_equal));
2350
2351 /* return the updated left value */
2352 return left;
2353 }
2354 else if (left->is_addr() && right->is_addr())
2355 {
2356 CTcConstVal cval;
2357 int comparable;
2358
2359 /*
2360 * both sides are addresses - if they're both addresses of the
2361 * same subexpression, then the values are comparable as
2362 * compile-time constants
2363 */
2364 ops_equal = ((CTPNAddr *)left)
2365 ->is_addr_eq((CTPNAddr *)right, &comparable);
2366
2367 /* if they're not comparable, we can't fold this as a constant */
2368 if (!comparable)
2369 return 0;
2370
2371 /* generate the appropriate boolean result for the comparison */
2372 cval.set_bool(get_bool_val(ops_equal));
2373
2374 /* return a new constant node with the result */
2375 return new CTPNConst(&cval);
2376 }
2377 else
2378 {
2379 /*
2380 * one or the other is non-constant, so we can't fold the
2381 * expression - return null to so indicate
2382 */
2383 return 0;
2384 }
2385 }
2386
2387
2388 /* ------------------------------------------------------------------------ */
2389 /*
2390 * equality operator
2391 */
2392
2393 /*
2394 * build the subtree
2395 */
2396 CTcPrsNode *CTcPrsOpEq::build_tree(CTcPrsNode *left,
2397 CTcPrsNode *right) const
2398 {
2399 return new CTPNEq(left, right);
2400 }
2401
2402 /* ------------------------------------------------------------------------ */
2403 /*
2404 * inequality operator
2405 */
2406
2407 /*
2408 * build the subtree
2409 */
2410 CTcPrsNode *CTcPrsOpNe::build_tree(CTcPrsNode *left,
2411 CTcPrsNode *right) const
2412 {
2413 return new CTPNNe(left, right);
2414 }
2415
2416 /* ------------------------------------------------------------------------ */
2417 /*
2418 * 'is in' operator
2419 */
2420
2421 /*
2422 * construct
2423 */
2424 CTPNIsInBase::CTPNIsInBase(CTcPrsNode *lhs, class CTPNArglist *rhs)
2425 : CTPNBin(lhs, rhs)
2426 {
2427 /* presume we don't have a constant value */
2428 const_true_ = FALSE;
2429 }
2430
2431 /*
2432 * fold constants
2433 */
2434 CTcPrsNode *CTPNIsInBase::fold_binop()
2435 {
2436 CTPNArglist *lst;
2437 CTPNArg *arg;
2438 CTPNArg *prv;
2439 CTPNArg *nxt;
2440
2441 /* if the left-hand side isn't constant, there's nothing to do */
2442 if (!left_->is_const())
2443 return this;
2444
2445 /* the right side is always an argument list */
2446 lst = (CTPNArglist *)right_;
2447
2448 /* look for the value in the arguments */
2449 for (prv = 0, arg = lst->get_arg_list_head() ; arg != 0 ; arg = nxt)
2450 {
2451 /* remember the next argument, in case we eliminate this one */
2452 nxt = arg->get_next_arg();
2453
2454 /* check to see if this argument is a constant */
2455 if (arg->is_const())
2456 {
2457 /*
2458 * This one's a constant, so check to see if we found the
2459 * left side value. If the left side equals this value,
2460 * note that we found the value.
2461 */
2462 if (left_->get_const_val()->is_equal_to(arg->get_const_val()))
2463 {
2464 /*
2465 * The values are equal, so the result of the expression
2466 * is definitely 'true'.
2467 */
2468 const_true_ = TRUE;
2469
2470 /*
2471 * Because the 'is in' operator only evaluates operands
2472 * from the 'in' list until it finds one that matches,
2473 * any remaining operands will simply never be
2474 * evaluated. We can thus discard the rest of the
2475 * argument list.
2476 */
2477 nxt = 0;
2478 }
2479
2480 /*
2481 * We now know whether the left side equals this constant
2482 * list element. This is never going to change because both
2483 * values are constant, so there's no point in making this
2484 * same comparison over and over again at run-time. We can
2485 * thus eliminate this argument from the list.
2486 */
2487 lst->set_argc(lst->get_argc() - 1);
2488 if (prv == 0)
2489 lst->set_arg_list_head(nxt);
2490 else
2491 prv->set_next_arg(nxt);
2492 }
2493 }
2494
2495 /*
2496 * If the argument list is now completely empty, the result of the
2497 * expression is a constant.
2498 */
2499 if (lst->get_arg_list_head() == 0)
2500 {
2501 /* set the left operand's value to our result */
2502 left_->get_const_val()->set_bool(const_true_);
2503
2504 /* return the constant value in place of the entire expression */
2505 return left_;
2506 }
2507
2508 /* we're not a constant, to return myself unchanged */
2509 return this;
2510 }
2511
2512 /* ------------------------------------------------------------------------ */
2513 /*
2514 * 'not in' operator
2515 */
2516
2517 /*
2518 * construct
2519 */
2520 CTPNNotInBase::CTPNNotInBase(CTcPrsNode *lhs, class CTPNArglist *rhs)
2521 : CTPNBin(lhs, rhs)
2522 {
2523 /* presume we don't have a constant value */
2524 const_false_ = FALSE;
2525 }
2526
2527 /*
2528 * fold constants for binary operator
2529 */
2530 CTcPrsNode *CTPNNotInBase::fold_binop()
2531 {
2532 CTPNArglist *lst;
2533 CTPNArg *arg;
2534 CTPNArg *prv;
2535 CTPNArg *nxt;
2536
2537 /* if the left-hand side isn't constant, there's nothing to do */
2538 if (!left_->is_const())
2539 return this;
2540
2541 /* the right side is always an argument list */
2542 lst = (CTPNArglist *)right_;
2543
2544 /* look for the value in the arguments */
2545 for (prv = 0, arg = lst->get_arg_list_head() ; arg != 0 ; arg = nxt)
2546 {
2547 /* remember the next argument, in case we eliminate this one */
2548 nxt = arg->get_next_arg();
2549
2550 /* check to see if this argument is a constant */
2551 if (arg->is_const())
2552 {
2553 /*
2554 * This one's a constant, so check to see if we found the
2555 * left side value. If the left side equals this value,
2556 * note that we found the value.
2557 */
2558 if (left_->get_const_val()->is_equal_to(arg->get_const_val()))
2559 {
2560 /*
2561 * The values are equal, so the result of the expression
2562 * is definitely 'nil'.
2563 */
2564 const_false_ = TRUE;
2565
2566 /*
2567 * Because the 'not in' operator only evaluates operands
2568 * from the 'in' list until it finds one that matches,
2569 * any remaining operands will simply never be
2570 * evaluated. We can thus discard the rest of the
2571 * argument list.
2572 */
2573 nxt = 0;
2574 }
2575
2576 /*
2577 * We now know whether the left side equals this constant
2578 * list element. This is never going to change because both
2579 * values are constant, so there's no point in making this
2580 * same comparison over and over again at run-time. We can
2581 * thus eliminate this argument from the list.
2582 */
2583 lst->set_argc(lst->get_argc() - 1);
2584 if (prv == 0)
2585 lst->set_arg_list_head(nxt);
2586 else
2587 prv->set_next_arg(nxt);
2588 }
2589 }
2590
2591 /*
2592 * If the argument list is now completely empty, the result of the
2593 * expression is a constant.
2594 */
2595 if (lst->get_arg_list_head() == 0)
2596 {
2597 /* set the left operand's value to our result */
2598 left_->get_const_val()->set_bool(!const_false_);
2599
2600 /* return the constant value in place of the entire expression */
2601 return left_;
2602 }
2603
2604 /* we're not a constant, to return myself unchanged */
2605 return this;
2606 }
2607
2608 /* ------------------------------------------------------------------------ */
2609 /*
2610 * General arithmetic operator base class
2611 */
2612
2613 /*
2614 * evaluate constant value
2615 */
2616 CTcPrsNode *CTcPrsOpArith::eval_constant(CTcPrsNode *left,
2617 CTcPrsNode *right) const
2618 {
2619 /* check for constants */
2620 if (left->is_const() && right->is_const())
2621 {
2622 CTcConstVal *c1 = left->get_const_val();
2623 CTcConstVal *c2 = right->get_const_val();
2624 tc_constval_type_t typ1 = c1->get_type();
2625 tc_constval_type_t typ2 = c2->get_type();
2626
2627 /* check for ints, floats, or a combination */
2628 if (typ1 == TC_CVT_INT && typ2 == TC_CVT_INT)
2629 {
2630 /* calculate the int result */
2631 int ov;
2632 long r = calc_result(c1->get_val_int(), c2->get_val_int(), ov);
2633
2634 /* on overflow, recalculate using BigNumbers */
2635 if (ov)
2636 {
2637 /* calculate the BigNumber result */
2638 vbignum_t a(c1->get_val_int());
2639 vbignum_t b(c2->get_val_int());
2640 vbignum_t *c = calc_result(a, b);
2641
2642 /* if successful, assign it back to the left operand */
2643 if (c != 0)
2644 {
2645 c1->set_float(c, TRUE);
2646 delete c;
2647 }
2648 }
2649 else
2650 {
2651 /* success - assign the folded int to the left operand */
2652 c1->set_int(r);
2653 }
2654 }
2655 else if (typ1 == TC_CVT_FLOAT && typ2 == TC_CVT_FLOAT)
2656 {
2657 /* calculate the BigNumber result */
2658 vbignum_t a(c1->get_val_float(), c1->get_val_float_len(), 0);
2659 vbignum_t b(c2->get_val_float(), c2->get_val_float_len(), 0);
2660 vbignum_t *c = calc_result(a, b);
2661
2662 /* assign it back to the left operand */
2663 if (c != 0)
2664 {
2665 /* save the value and delete the calculation result */
2666 c1->set_float(c, c1->is_promoted() && c2->is_promoted());
2667 delete c;
2668
2669 /* check for possible demotion back to int */
2670 c1->demote_float();
2671 }
2672 }
2673 else if (typ1 == TC_CVT_FLOAT && typ2 == TC_CVT_INT)
2674 {
2675 /* calculate the BigNumber result */
2676 vbignum_t a(c1->get_val_float(), c1->get_val_float_len(), 0);
2677 vbignum_t b(c2->get_val_int());
2678 vbignum_t *c = calc_result(a, b);
2679
2680 /* assign it back to the left operand */
2681 if (c != 0)
2682 {
2683 /* save the value and delete the calculation result */
2684 c1->set_float(c, c1->is_promoted());
2685 delete c;
2686
2687 /* check for possible demotion back to int */
2688 c1->demote_float();
2689 }
2690 }
2691 else if (typ1 == TC_CVT_INT && typ2 == TC_CVT_FLOAT)
2692 {
2693 /* calculate the BigNumber result */
2694 vbignum_t a(c1->get_val_int());
2695 vbignum_t b(c2->get_val_float(), c2->get_val_float_len(), 0);
2696 vbignum_t *c = calc_result(a, b);
2697
2698 /* assign it back to the left operand */
2699 if (c != 0)
2700 {
2701 /* save the value and delete the calculation result */
2702 c1->set_float(c, c2->is_promoted());
2703 delete c;
2704
2705 /* check for possible demotion back to int */
2706 c1->demote_float();
2707 }
2708 }
2709 else
2710 {
2711 /* incompatible types - log an error */
2712 G_tok->log_error(TCERR_CONST_BINARY_REQ_NUM,
2713 G_tok->get_op_text(get_op_tok()));
2714 return 0;
2715 }
2716
2717 /* return the updated left value */
2718 return left;
2719 }
2720 else
2721 {
2722 /*
2723 * one or the other is non-constant, so we can't fold the
2724 * expression - return null to so indicate
2725 */
2726 return 0;
2727 }
2728 }
2729
2730 /* ------------------------------------------------------------------------ */
2731 /*
2732 * bitwise OR operator
2733 */
2734
2735 /*
2736 * build the subtree
2737 */
2738 CTcPrsNode *CTcPrsOpBOr::build_tree(CTcPrsNode *left,
2739 CTcPrsNode *right) const
2740 {
2741 return new CTPNBOr(left, right);
2742 }
2743
2744 /* ------------------------------------------------------------------------ */
2745 /*
2746 * bitwise AND operator
2747 */
2748
2749 /*
2750 * build the subtree
2751 */
2752 CTcPrsNode *CTcPrsOpBAnd::build_tree(CTcPrsNode *left,
2753 CTcPrsNode *right) const
2754 {
2755 return new CTPNBAnd(left, right);
2756 }
2757
2758 /* ------------------------------------------------------------------------ */
2759 /*
2760 * bitwise XOR operator
2761 */
2762
2763 /*
2764 * build the subtree
2765 */
2766 CTcPrsNode *CTcPrsOpBXor::build_tree(CTcPrsNode *left,
2767 CTcPrsNode *right) const
2768 {
2769 return new CTPNBXor(left, right);
2770 }
2771
2772
2773 /* ------------------------------------------------------------------------ */
2774 /*
2775 * shift left operator
2776 */
2777
2778 /*
2779 * build the subtree
2780 */
2781 CTcPrsNode *CTcPrsOpShl::build_tree(CTcPrsNode *left,
2782 CTcPrsNode *right) const
2783 {
2784 return new CTPNShl(left, right);
2785 }
2786
2787 /* ------------------------------------------------------------------------ */
2788 /*
2789 * arithmetic shift right operator
2790 */
2791
2792 /*
2793 * build the subtree
2794 */
2795 CTcPrsNode *CTcPrsOpAShr::build_tree(CTcPrsNode *left,
2796 CTcPrsNode *right) const
2797 {
2798 return new CTPNAShr(left, right);
2799 }
2800
2801 /* ------------------------------------------------------------------------ */
2802 /*
2803 * logical shift right operator
2804 */
2805
2806 /*
2807 * build the subtree
2808 */
2809 CTcPrsNode *CTcPrsOpLShr::build_tree(CTcPrsNode *left,
2810 CTcPrsNode *right) const
2811 {
2812 return new CTPNLShr(left, right);
2813 }
2814
2815 /* ------------------------------------------------------------------------ */
2816 /*
2817 * multiplication operator
2818 */
2819
2820 /*
2821 * build the subtree
2822 */
2823 CTcPrsNode *CTcPrsOpMul::build_tree(CTcPrsNode *left,
2824 CTcPrsNode *right) const
2825 {
2826 return new CTPNMul(left, right);
2827 }
2828
2829 /*
2830 * calculate a constant float result
2831 */
2832 vbignum_t *CTcPrsOpMul::calc_result(
2833 const vbignum_t &a, const vbignum_t &b) const
2834 {
2835 return a * b;
2836 }
2837
2838 /* ------------------------------------------------------------------------ */
2839 /*
2840 * division operator
2841 */
2842
2843 /*
2844 * build the subtree
2845 */
2846 CTcPrsNode *CTcPrsOpDiv::build_tree(CTcPrsNode *left,
2847 CTcPrsNode *right) const
2848 {
2849 return new CTPNDiv(left, right);
2850 }
2851
2852 /*
2853 * evaluate constant integer result
2854 */
2855 long CTcPrsOpDiv::calc_result(long a, long b, int &ov) const
2856 {
2857 /* check for divide-by-zero */
2858 if (b == 0)
2859 {
2860 /* log a divide-by-zero error */
2861 G_tok->log_error(TCERR_CONST_DIV_ZERO);
2862
2863 /* the result isn't really meaningful, but return something anyway */
2864 return 1;
2865 }
2866
2867 /*
2868 * check for overflow - there's only one way that integer division can
2869 * overflow, which is to divide INT32MINVAL by -1
2870 */
2871 ov = (a == INT32MINVAL && b == 1);
2872
2873 /* return the result */
2874 return a / b;
2875 }
2876
2877 /*
2878 * calculate a constant float result
2879 */
2880 vbignum_t *CTcPrsOpDiv::calc_result(
2881 const vbignum_t &a, const vbignum_t &b) const
2882 {
2883 /* check for division by zero */
2884 if (b.is_zero())
2885 {
2886 /* log an error, and just return the left operand */
2887 G_tok->log_error(TCERR_CONST_DIV_ZERO);
2888 return new vbignum_t(1L);
2889 }
2890 else
2891 {
2892 /* calculate the result */
2893 return a / b;
2894 }
2895 }
2896
2897 /* ------------------------------------------------------------------------ */
2898 /*
2899 * modulo operator
2900 */
2901
2902 /*
2903 * build the subtree
2904 */
2905 CTcPrsNode *CTcPrsOpMod::build_tree(CTcPrsNode *left,
2906 CTcPrsNode *right) const
2907 {
2908 return new CTPNMod(left, right);
2909 }
2910
2911 /*
2912 * evaluate constant result
2913 */
2914 long CTcPrsOpMod::calc_result(long a, long b, int &ov) const
2915 {
2916 /* there's no way for integer modulo to overflow */
2917 ov = FALSE;
2918
2919 /* check for divide-by-zero */
2920 if (b == 0)
2921 {
2922 /* log a divide-by-zero error */
2923 G_tok->log_error(TCERR_CONST_DIV_ZERO);
2924
2925 /* the result isn't really meaningful, but return something anyway */
2926 return 1;
2927 }
2928 else
2929 {
2930 /* return the result */
2931 return a % b;
2932 }
2933 }
2934
2935 /*
2936 * calculate a constant float result
2937 */
2938 vbignum_t *CTcPrsOpMod::calc_result(
2939 const vbignum_t &a, const vbignum_t &b) const
2940 {
2941 /* check for division by zero */
2942 if (b.is_zero())
2943 {
2944 /* log an error, and just return the left operand */
2945 G_tok->log_error(TCERR_CONST_DIV_ZERO);
2946 return new vbignum_t(1L);
2947 }
2948 else
2949 {
2950 /* calculate the result */
2951 return a % b;
2952 }
2953 }
2954
2955
2956 /* ------------------------------------------------------------------------ */
2957 /*
2958 * subtraction operator
2959 */
2960
2961 /*
2962 * build the subtree
2963 */
2964 CTcPrsNode *CTcPrsOpSub::build_tree(CTcPrsNode *left,
2965 CTcPrsNode *right) const
2966 {
2967 return new CTPNSub(left, right);
2968 }
2969
2970 /*
2971 * evaluate a constant value
2972 */
2973 CTcPrsNode *CTcPrsOpSub::eval_constant(CTcPrsNode *left,
2974 CTcPrsNode *right) const
2975 {
2976 if (left->is_const() && right->is_const())
2977 {
2978 tc_constval_type_t typ1, typ2;
2979
2980 /* get the types */
2981 typ1 = left->get_const_val()->get_type();
2982 typ2 = right->get_const_val()->get_type();
2983
2984 /* check our types */
2985 if ((typ1 == TC_CVT_INT || typ1 == TC_CVT_FLOAT)
2986 && (typ2 == TC_CVT_INT || typ2 == TC_CVT_FLOAT))
2987 {
2988 /* int/float minus int/float - use the inherited handling */
2989 return CTcPrsOpArith::eval_constant(left, right);
2990 }
2991 else if (typ1 == TC_CVT_LIST)
2992 {
2993 /* get the original list */
2994 CTPNList *lst = left->get_const_val()->get_val_list();
2995
2996 /*
2997 * if the right side is a list, remove each element of that
2998 * list from the list on the left; otherwise, remove the
2999 * value on the right from the list on the left
3000 */
3001 if (typ2 == TC_CVT_LIST)
3002 {
3003 /* remove each element of the rhs list from the lhs list */
3004 CTPNListEle *ele;
3005
3006 /* scan the list, adding each element */
3007 for (ele = right->get_const_val()
3008 ->get_val_list()->get_head() ;
3009 ele != 0 ; ele = ele->get_next())
3010 {
3011 /* add this element's underlying expression value */
3012 lst->remove_element(ele->get_expr()->get_const_val());
3013 }
3014 }
3015 else
3016 {
3017 /* remove the rhs value from the lhs list */
3018 lst->remove_element(right->get_const_val());
3019 }
3020 }
3021 else if (typ1 == TC_CVT_OBJ)
3022 {
3023 /*
3024 * assume it's an overloaded operator, in which case constant
3025 * evaluation isn't possible, but it could still be a legal
3026 * expression
3027 */
3028 return 0;
3029 }
3030 else
3031 {
3032 /* these types are incompatible - log an error */
3033 G_tok->log_error(TCERR_CONST_BINMINUS_INCOMPAT);
3034 return 0;
3035 }
3036
3037 /* return the updated left side */
3038 return left;
3039 }
3040 else
3041 {
3042 /* they're not constant - we can't generate a constant result */
3043 return 0;
3044 }
3045 }
3046
3047 /*
3048 * calculate a constant float result
3049 */
3050 vbignum_t *CTcPrsOpSub::calc_result(
3051 const vbignum_t &a, const vbignum_t &b) const
3052 {
3053 return a - b;
3054 }
3055
3056 /* ------------------------------------------------------------------------ */
3057 /*
3058 * addition operator
3059 */
3060
3061 /*
3062 * evaluate constant value
3063 */
3064 CTcPrsNode *CTcPrsOpAdd::eval_constant(CTcPrsNode *left,
3065 CTcPrsNode *right) const
3066 {
3067 /* check for constants */
3068 if (left->is_const() && right->is_const())
3069 {
3070 tc_constval_type_t typ1, typ2;
3071
3072 /* get the types */
3073 typ1 = left->get_const_val()->get_type();
3074 typ2 = right->get_const_val()->get_type();
3075
3076 /* check our types */
3077 if ((typ1 == TC_CVT_INT || typ1 == TC_CVT_FLOAT)
3078 && (typ2 == TC_CVT_INT || typ2 == TC_CVT_FLOAT))
3079 {
3080 /* int/float plus int/float - use the inherited handling */
3081 return CTcPrsOpArith::eval_constant(left, right);
3082 }
3083 else if (typ1 == TC_CVT_LIST)
3084 {
3085 /* get the original list */
3086 CTPNList *lst = left->get_const_val()->get_val_list();
3087
3088 /*
3089 * if the right side is also a list, concatenate it onto the
3090 * left list; otherwise, just add the right side as a new
3091 * element to the existing list
3092 */
3093 if (typ2 == TC_CVT_LIST)
3094 {
3095 CTPNListEle *ele;
3096
3097 /* scan the list, adding each element */
3098 for (ele = right->get_const_val()
3099 ->get_val_list()->get_head() ;
3100 ele != 0 ; ele = ele->get_next())
3101 {
3102 /* add this element's underlying expression value */
3103 lst->add_element(ele->get_expr());
3104 }
3105 }
3106 else
3107 {
3108 /* add a new list element for the right side */
3109 lst->add_element(right);
3110 }
3111
3112 /*
3113 * this list is longer than the original(s); tell the parser
3114 * about it in case it's the longest list yet
3115 */
3116 G_cg->note_list(lst->get_count());
3117 }
3118 else if (typ1 == TC_CVT_SSTR || typ2 == TC_CVT_SSTR)
3119 {
3120 char buf1[128];
3121 char buf2[128];
3122 const char *str1, *str2;
3123 size_t len1, len2;
3124 char *new_str;
3125
3126 /* if the second value is a list, we can't make a constant */
3127 if (typ2 == TC_CVT_LIST)
3128 return 0;
3129
3130 /* convert both values to strings if they're not already */
3131 str1 = left->get_const_val()
3132 ->cvt_to_str(buf1, sizeof(buf1), &len1);
3133 str2 = right->get_const_val()
3134 ->cvt_to_str(buf2, sizeof(buf2), &len2);
3135
3136 /* treat nil as an empty string */
3137 if (typ2 == TC_CVT_NIL)
3138 str1 = "", len2 = 0;
3139
3140 /*
3141 * if we couldn't convert one or the other, leave the result
3142 * non-constant
3143 */
3144 if (str1 == 0 || str2 == 0)
3145 return 0;
3146
3147 /*
3148 * allocate space in the node pool for the concatenation of
3149 * the two strings - if that fails, don't bother with the
3150 * concatenation
3151 */
3152 new_str = (char *)G_prsmem->alloc(len1 + len2 + 1);
3153 if (new_str == 0)
3154 return 0;
3155
3156 /* copy the two string values into the new space */
3157 memcpy(new_str, str1, len1);
3158 memcpy(new_str + len1, str2, len2);
3159 new_str[len1 + len2] = '\0';
3160
3161 /* set the new value in the left node */
3162 left->get_const_val()->set_sstr(new_str, len1 + len2);
3163 }
3164 else if (typ1 == TC_CVT_OBJ)
3165 {
3166 /*
3167 * assume it's an overloaded operator, in which case constant
3168 * evaluation isn't possible, but it could still be a legal
3169 * expression
3170 */
3171 return 0;
3172 }
3173 else
3174 {
3175 /* these types are incompatible - log an error */
3176 G_tok->log_error(TCERR_CONST_BINPLUS_INCOMPAT);
3177 return 0;
3178 }
3179
3180 /* return the updated left value */
3181 return left;
3182 }
3183 else
3184 {
3185 /* the values aren't constant, so the result isn't constant */
3186 return 0;
3187 }
3188 }
3189
3190 /*
3191 * calculate a constant float result
3192 */
3193 vbignum_t *CTcPrsOpAdd::calc_result(
3194 const vbignum_t &a, const vbignum_t &b) const
3195 {
3196 return a + b;
3197 }
3198
3199 /*
3200 * build the subtree
3201 */
3202 CTcPrsNode *CTcPrsOpAdd::build_tree(CTcPrsNode *left,
3203 CTcPrsNode *right) const
3204 {
3205 return new CTPNAdd(left, right);
3206 }
3207
3208 /* ------------------------------------------------------------------------ */
3209 /*
3210 * Assignment Operator Group
3211 */
3212
3213 /*
3214 * parse an assignment expression
3215 */
3216 CTcPrsNode *CTcPrsOpAsi::parse() const
3217 {
3218 /* start by parsing a conditional subexpression */
3219 CTcPrsNode *lhs = S_op_if.parse();
3220 if (lhs == 0)
3221 return 0;
3222
3223 /* get the next operator */
3224 tc_toktyp_t curtyp = G_tok->cur();
3225
3226 /* check to see if it's an assignment operator of some kind */
3227 switch(curtyp)
3228 {
3229 case TOKT_PLUSEQ:
3230 case TOKT_MINEQ:
3231 case TOKT_TIMESEQ:
3232 case TOKT_DIVEQ:
3233 case TOKT_MODEQ:
3234 case TOKT_ANDEQ:
3235 case TOKT_OREQ:
3236 case TOKT_XOREQ:
3237 case TOKT_SHLEQ:
3238 case TOKT_ASHREQ:
3239 case TOKT_LSHREQ:
3240 /* it's an assignment operator - process it */
3241 break;
3242
3243 default:
3244 /* check against the current simple-assignment operator */
3245 if (curtyp == asi_op_)
3246 {
3247 /* it's an assignment operator - process it */
3248 break;
3249 }
3250 else
3251 {
3252 /*
3253 * it's not an assignment - return the original
3254 * subexpression with no further elaboration
3255 */
3256 return lhs;
3257 }
3258 }
3259
3260 /* check for a valid lvalue */
3261 if (!lhs->check_lvalue())
3262 {
3263 /* log an error but continue parsing */
3264 G_tok->log_error(TCERR_INVALID_LVALUE,
3265 G_tok->get_op_text(G_tok->cur()));
3266 }
3267
3268 /* skip the assignment operator */
3269 G_tok->next();
3270
3271 /*
3272 * Recursively parse an assignment subexpression. Do this
3273 * recursively rather than iteratively, because assignment operators
3274 * group right-to-left. By recursively parsing an assignment, our
3275 * right-hand side will contain all remaining assignment expressions
3276 * incorporated into it.
3277 */
3278 CTcPrsNode *rhs = parse();
3279 if (rhs == 0)
3280 return 0;
3281
3282 /* build and return the result based on the operator type */
3283 switch(curtyp)
3284 {
3285 case TOKT_PLUSEQ:
3286 lhs = new CTPNAddAsi(lhs, rhs);
3287 break;
3288
3289 case TOKT_MINEQ:
3290 lhs = new CTPNSubAsi(lhs, rhs);
3291 break;
3292
3293 case TOKT_TIMESEQ:
3294 lhs = new CTPNMulAsi(lhs, rhs);
3295 break;
3296
3297 case TOKT_DIVEQ:
3298 lhs = new CTPNDivAsi(lhs, rhs);
3299 break;
3300
3301 case TOKT_MODEQ:
3302 lhs = new CTPNModAsi(lhs, rhs);
3303 break;
3304
3305 case TOKT_ANDEQ:
3306 lhs = new CTPNBAndAsi(lhs, rhs);
3307 break;
3308
3309 case TOKT_OREQ:
3310 lhs = new CTPNBOrAsi(lhs, rhs);
3311 break;
3312
3313 case TOKT_XOREQ:
3314 lhs = new CTPNBXorAsi(lhs, rhs);
3315 break;
3316
3317 case TOKT_SHLEQ:
3318 lhs = new CTPNShlAsi(lhs, rhs);
3319 break;
3320
3321 case TOKT_ASHREQ:
3322 lhs = new CTPNAShrAsi(lhs, rhs);
3323 break;
3324
3325 case TOKT_LSHREQ:
3326 lhs = new CTPNLShrAsi(lhs, rhs);
3327 break;
3328
3329 default:
3330 /* plain assignment operator */
3331 lhs = new CTPNAsi(lhs, rhs);
3332 break;
3333 }
3334
3335 /* return the result */
3336 return lhs;
3337 }
3338
3339 /* ------------------------------------------------------------------------ */
3340 /*
3341 * Ifnil operator ??
3342 */
3343
3344 CTcPrsNode *CTcPrsOpIfnil::parse() const
3345 {
3346 /* parse the conditional part */
3347 CTcPrsNode *first = S_op_or.parse();
3348 if (first == 0)
3349 return 0;
3350
3351 /* if we're not looking at the '??' operator, we're done */
3352 if (G_tok->cur() != TOKT_QQ)
3353 return first;
3354
3355 /* skip the '??' operator */
3356 G_tok->next();
3357
3358 /*
3359 * parse the second part, which can be any expression except ',', since
3360 * we have higher precedence than ','
3361 */
3362 CTcPrsNode *second = G_prs->parse_expr_or_dstr(FALSE);
3363 if (second == 0)
3364 return 0;
3365
3366 /* if the first expression is constant, we can fold immediately */
3367 if (first->is_const())
3368 {
3369 /* if it's nil, yield the second value, otherwise yield the first */
3370 return (first->get_const_val()->get_type() == TC_CVT_NIL
3371 ? second : first);
3372 }
3373 else
3374 {
3375 /* it's not a constant value - return a new if-nil node */
3376 return new CTPNIfnil(first, second);
3377 }
3378 }
3379
3380 /* ------------------------------------------------------------------------ */
3381 /*
3382 * Tertiary Conditional Operator
3383 */
3384
3385 CTcPrsNode *CTcPrsOpIf::parse() const
3386 {
3387 /* parse the conditional part */
3388 CTcPrsNode *first = S_op_ifnil.parse();
3389 if (first == 0)
3390 return 0;
3391
3392 /* if we're not looking at the '?' operator, we're done */
3393 if (G_tok->cur() != TOKT_QUESTION)
3394 return first;
3395
3396 /* skip the '?' operator */
3397 G_tok->next();
3398
3399 /*
3400 * parse the second part, which can be any expression, including a
3401 * double-quoted string expression or a comma expression (even though
3402 * the '?:' operator overall has higher precedence than ',', we can't
3403 * steal away operands from a ',' before our ':' because that would
3404 * leave the ':' with nothing to go with)
3405 */
3406 CTcPrsNode *second = G_prs->parse_expr_or_dstr(TRUE);
3407 if (second == 0)
3408 return 0;
3409
3410 /* make sure we have the ':' after the second part */
3411 if (G_tok->cur() != TOKT_COLON)
3412 {
3413 /*
3414 * log the error, but continue parsing as though we found the
3415 * ':' - if the ':' is simply missing, this will allow us to
3416 * recover and continue parsing the rest of the expression
3417 */
3418 G_tok->log_error(TCERR_QUEST_WITHOUT_COLON);
3419
3420 /* if we're at the end of file, there's no point in continuing */
3421 if (G_tok->cur() == TOKT_EOF)
3422 return 0;
3423 }
3424
3425 /* skip the ':' */
3426 G_tok->next();
3427
3428 /*
3429 * parse the third part, which can be any other expression, including a
3430 * double-quoted string expression - but not a comma expression, since
3431 * we have higher precedence than ','
3432 */
3433 CTcPrsNode *third = G_prs->parse_expr_or_dstr(FALSE);
3434 if (third == 0)
3435 return 0;
3436
3437 /*
3438 * If the condition is constant, we can choose the second or third
3439 * expression directly. It doesn't matter whether or not the second
3440 * and/or third parts are themselves constant, because a constant
3441 * condition means that we'll always execute only one of the
3442 * alternatives.
3443 */
3444 if (first->is_const())
3445 {
3446 /*
3447 * evaluate the conditional value as a true/false value, and
3448 * return the second part's constant if the condition is true,
3449 * or the third part's constant if the condition is false
3450 */
3451 return (first->get_const_val()->get_val_bool()
3452 ? second : third);
3453 }
3454 else
3455 {
3456 /* it's not a constant value - return a new conditional node */
3457 return new CTPNIf(first, second, third);
3458 }
3459 }
3460
3461 /* ------------------------------------------------------------------------ */
3462 /*
3463 * Bmbedded string expressions.
3464 */
3465
3466 /*
3467 * Embedded string tree generator. This abstracts the tree construction
3468 * for an embedded string, so that the same parser can be used for single
3469 * and double quoted strings.
3470 */
3471 struct CTcEmbedBuilder
3472 {
3473 /* is this a double-quoted string builder? */
3474 virtual int is_double() const = 0;
3475
3476 /* create the initial node for the leading fixed part of the string */
3477 virtual CTcPrsNode *lead_node() = 0;
3478
3479 /*
3480 * Finish the tree. If we skipped creating a tree because we had an
3481 * empty string in the lead position, and we haven't added anything to
3482 * it, this should create a non-null node to represent the final tree,
3483 * so we know it's not an error.
3484 */
3485 virtual CTcPrsNode *finish_tree(CTcPrsNode *cur) = 0;
3486
3487 /* parse an embedded expression */
3488 virtual CTcPrsNode *parse_expr() = 0;
3489
3490 /*
3491 * Add an embedding: create a node combining the tree before an
3492 * expression, an embedded expression, and the current token
3493 * representing the continuation of the string after the expression.
3494 */
3495 virtual CTcPrsNode *add_embedding(CTcPrsNode *cur, CTcPrsNode *sub) = 0;
3496
3497 /* add a string segment (a "mid" or "end" segment) */
3498 virtual CTcPrsNode *add_segment(CTcPrsNode *cur) = 0;
3499
3500 /* string mid/end token types */
3501 virtual tc_toktyp_t mid_tok() = 0;
3502 virtual tc_toktyp_t end_tok() = 0;
3503 };
3504
3505 /*
3506 * Embedded string tree generator for double-quoted strings. Double-quoted
3507 * strings with embeddings are converted to a series of comma expressions:
3508 *
3509 *. "one <<two>> three <<four>> five"
3510 *. -> "one ", say(two), " three ", say(four), " five";
3511 *
3512 * Note that the embedded expressions are wrapped in "say()" calls, since
3513 * we have to make sure they generate output. Some embeddings will
3514 * generate output as a side effect rather than as a value result, but
3515 * that's fine; in that case they'll perform their side effect (i.e.,
3516 * printing text) and then return nil, so the say() will add nothing to the
3517 * output stream.
3518 */
3519 struct CTcEmbedBuilderDbl: CTcEmbedBuilder
3520 {
3521 /* we're the builder for double-quoted strings */
3522 virtual int is_double() const { return TRUE; }
3523
3524 /* string mid/end token types */
3525 virtual tc_toktyp_t mid_tok() { return TOKT_DSTR_MID; }
3526 virtual tc_toktyp_t end_tok() { return TOKT_DSTR_END; }
3527
3528 /* build the leading node */
3529 virtual CTcPrsNode *lead_node()
3530 {
3531 /*
3532 * Create a node for the initial part of the string. This is just
3533 * an ordinary double-quoted string node. If the initial part of
3534 * the string is zero-length, don't create an initial node at all,
3535 * since this would just generate do-nothing code.
3536 */
3537 if (G_tok->getcur()->get_text_len() != 0)
3538 {
3539 /* create the node for the initial part of the string */
3540 return new CTPNDstr(G_tok->getcur()->get_text(),
3541 G_tok->getcur()->get_text_len());
3542 }
3543 else
3544 {
3545 /*
3546 * the initial part of the string is empty, so we don't need a
3547 * node for this portion
3548 */
3549 return 0;
3550 }
3551 }
3552
3553 /* finish the tree */
3554 virtual CTcPrsNode *finish_tree(CTcPrsNode *cur)
3555 {
3556 return (cur != 0 ? cur : new CTPNDstr("", 0));
3557 }
3558
3559 /* parse an embedded expression */
3560 virtual CTcPrsNode *parse_expr()
3561 {
3562 /*
3563 * an expression embedded in a dstring can be any value expression,
3564 * or another dstring expression
3565 */
3566 return G_prs->parse_expr_or_dstr(TRUE);
3567 }
3568
3569 /* add another embedding */
3570 virtual CTcPrsNode *add_embedding(CTcPrsNode *cur, CTcPrsNode *sub)
3571 {
3572 /* wrap the expresion in a "say()" embedding node */
3573 sub = new CTPNDstrEmbed(sub);
3574
3575 /*
3576 * Build a node representing everything so far: do this by
3577 * combining the sub-expression with everything preceding, using a
3578 * comma operator. This isn't necessary if there's nothing
3579 * preceding the sub-expression, since this means the
3580 * sub-expression itself is everything so far.
3581 */
3582 if (cur != 0)
3583 return new CTPNComma(cur, sub);
3584 else
3585 return sub;
3586 }
3587
3588 /* add a string segment */
3589 virtual CTcPrsNode *add_segment(CTcPrsNode *cur)
3590 {
3591 /*
3592 * Combine the part so far with the next string segment, using a
3593 * comma operator. If the next string segment is empty, there's no
3594 * need to add anything for it.
3595 */
3596 size_t len = G_tok->getcur()->get_text_len();
3597 if (len != 0)
3598 {
3599 /* create a node for the new string segment */
3600 CTcPrsNode *newstr = new CTPNDstr(
3601 G_tok->getcur()->get_text(), len);
3602
3603 /* combine it into the part so far with a comma operator */
3604 cur = new CTPNComma(cur, newstr);
3605 }
3606
3607 /* return the new combined node */
3608 return cur;
3609 }
3610 };
3611
3612 /*
3613 * Embedded string tree generator for single-quoted strings.
3614 *
3615 * Single-quoted strings with embeddings are translated as follows:
3616 *
3617 *. local a = 'one <<two>> three <<four>> five';
3618 *. -> local a = ('one ' + (two) + ' three ' + (four) + ' five');
3619 */
3620 struct CTcEmbedBuilderSgl: CTcEmbedBuilder
3621 {
3622 /* we're the builder for single-quoted strings */
3623 virtual int is_double() const { return FALSE; }
3624
3625 /* string mid/end token types */
3626 virtual tc_toktyp_t mid_tok() { return TOKT_SSTR_MID; }
3627 virtual tc_toktyp_t end_tok() { return TOKT_SSTR_END; }
3628
3629 /* build the leading node */
3630 virtual CTcPrsNode *lead_node()
3631 {
3632 /*
3633 * Create a string constant node for the first part of the string.
3634 * Note that we need this even if the string is empty, to guarantee
3635 * that the overall expression is treated as a string.
3636 */
3637 return string_node(G_tok->getcur());
3638 }
3639
3640 virtual CTcPrsNode *finish_tree(CTcPrsNode *cur)
3641 {
3642 return (cur != 0 ? cur : string_node(0));
3643 }
3644
3645 /* create a constant string node from the current token */
3646 CTcPrsNode *string_node(const CTcToken *tok)
3647 {
3648 CTcConstVal cval;
3649 cval.set_sstr(tok);
3650 return new CTPNConst(&cval);
3651 }
3652
3653 /* parse an embedded expression */
3654 virtual CTcPrsNode *parse_expr()
3655 {
3656 /* in a single-quoted string, we need a value expression */
3657 return G_prs->parse_expr();
3658 }
3659
3660 /* add another embedding */
3661 virtual CTcPrsNode *add_embedding(CTcPrsNode *cur, CTcPrsNode *sub)
3662 {
3663 /*
3664 * Combine the sub-expression with the preceding portion using an
3665 * addition operator. This will be interpreted as concatenation at
3666 * run-time since the left side is definitively a string.
3667 */
3668 return new CTPNAdd(cur, sub);
3669 }
3670
3671 /* add a string segment */
3672 virtual CTcPrsNode *add_segment(CTcPrsNode *cur)
3673 {
3674 /*
3675 * Add the next string segment. We can omit it if it's zero
3676 * length, as this will add nothing to the result.
3677 */
3678 if (G_tok->getcur()->get_text_len() != 0)
3679 {
3680 CTcConstVal cval;
3681 cval.set_sstr(G_tok->getcur());
3682 cur = new CTPNAdd(cur, new CTPNConst(&cval));
3683 }
3684
3685 /* return the new combined node */
3686 return cur;
3687 }
3688 };
3689
3690 /*
3691 * Embedding stack entry. Each nesting level keeps one of these structures
3692 * to track the enclosing constructs.
3693 */
3694 struct CTcEmbedLevel
3695 {
3696 /* set up the level, linking to our parent */
3697 CTcEmbedLevel(int typ, CTcEmbedLevel *parent)
3698 : typ(typ), parent(parent) { }
3699
3700 /* level type */
3701 int typ;
3702
3703 /* level types */
3704 static const int Outer = 0;
3705 static const int If = 1;
3706 static const int OneOf = 2;
3707 static const int FirstTime = 3;
3708
3709 /* parent level */
3710 CTcEmbedLevel *parent;
3711
3712 /* find a type among my parents */
3713 int is_in(int typ)
3714 {
3715 /* if this is my type or a parent's type, we're in this type */
3716 return (typ == this->typ
3717 || (parent != 0 && parent->is_in(typ)));
3718 }
3719 };
3720
3721 /*
3722 * Parse an embedded expression in a string. This handles embedding for
3723 * both single-quoted and double-quoted strings, using the tree builder
3724 * object to handle the differences. The two have the same parsing syntax,
3725 * but they do generate different parse trees.
3726 */
3727 CTcPrsNode *CTcPrsOpUnary::parse_embedding(CTcEmbedBuilder *b)
3728 {
3729 /* keep going until we reach the end of the string */
3730 for (;;)
3731 {
3732 /* parse a series of embeddings */
3733 int eos;
3734 CTcEmbedLevel level(CTcEmbedLevel::Outer, 0);
3735 CTcPrsNode *n = parse_embedding_list(b, eos, &level);
3736
3737 /* if we encountered an error or the end of the string, we're done */
3738 if (n == 0 || eos)
3739 return n;
3740
3741 /*
3742 * We stopped parsing without reaching the end of the string, so we
3743 * must have encountered a token that terminates a nested structure
3744 * - <<end>>, <<else>>, <<case>>, etc. Capture the current
3745 * embedding so we can check which type of end token it is.
3746 */
3747 const char *open_kw;
3748 parse_embedded_end_tok(b, &level, &open_kw);
3749 G_tok->log_error(TCERR_BAD_EMBED_END_TOK,
3750 (int)G_tok->getcur()->get_text_len(),
3751 G_tok->getcur()->get_text(), open_kw);
3752 }
3753 }
3754
3755 /*
3756 * Parse a series of embeddings
3757 */
3758 CTcPrsNode *CTcPrsOpUnary::parse_embedding_list(
3759 CTcEmbedBuilder *b, int &eos, CTcEmbedLevel *parent)
3760 {
3761 /* we haven't reached the end of the string yet */
3762 eos = FALSE;
3763
3764 /* create the node for the leading string */
3765 tc_toktyp_t curtyp = G_tok->cur();
3766 CTcPrsNode *cur = b->lead_node();
3767 G_tok->next();
3768
3769 /*
3770 * If we're starting with the final segment of the string, there's no
3771 * need to parse any further. We can enter with the final segment when
3772 * parsing sub-constructs such as <<if>>.
3773 */
3774 if (curtyp == b->end_tok())
3775 {
3776 /* tell the caller we're at the end of the string */
3777 eos = TRUE;
3778
3779 /* return the lead node */
3780 return b->finish_tree(cur);
3781 }
3782
3783 /* keep going until we find the end of the string */
3784 for (;;)
3785 {
3786 /* note the current error count */
3787 int nerr = G_tcmain->get_error_count();
3788
3789 /*
3790 * Capture tokens up to the next string segment, so that we can
3791 * compare the tokens to the embedding templates.
3792 */
3793 CTcEmbedTokenList *tl = G_prs->embed_toks_;
3794 capture_embedded(b, tl);
3795
3796 /*
3797 * First, check the special built-in syntax:
3798 *
3799 *. <<if expr>>
3800 *. <<unless expr>>
3801 *. <<one of>>
3802 */
3803 CTcPrsNode *sub = 0;
3804 const char *open_kw = 0;
3805 int check_end = TRUE;
3806 if (tl->match("if *"))
3807 {
3808 /* parse the "if" list */
3809 tl->unget(1, 0);
3810 sub = parse_embedded_if(b, FALSE, eos, parent);
3811 }
3812 else if (tl->match("unless *"))
3813 {
3814 /* parse the "unless" (which is just an inverted "if") */
3815 tl->unget(1);
3816 sub = parse_embedded_if(b, TRUE, eos, parent);
3817 }
3818 else if (tl->match("one of"))
3819 {
3820 /* parse the "one of" list */
3821 sub = parse_embedded_oneof(b, eos, parent);
3822 }
3823 else if (tl->match("first time"))
3824 {
3825 /* parse the "first time" */
3826 sub = parse_embedded_firsttime(b, eos, parent);
3827 }
3828 else if (parse_embedded_end_tok(tl, parent, &open_kw))
3829 {
3830 /*
3831 * We're at a terminator for a multi-part embedding construct.
3832 * Stop here and return what we have, with the token left at
3833 * the terminator. The caller is presumably parsing this
3834 * construct recursively, so it'll take it from here.
3835 */
3836 tl->unget();
3837 return b->finish_tree(cur);
3838 }
3839 else if (tl->getcnt() == 0)
3840 {
3841 /*
3842 * empty embedding, or we got here via error recovery; proceed
3843 * with the next segment without any embedding
3844 */
3845 sub = 0;
3846 }
3847 else
3848 {
3849 /*
3850 * No special syntax, so treat it as an expression. First,
3851 * check for a sprintf format spec - e.g., <<%2d x>>
3852 */
3853 CTcToken fmttok(TOKT_INVALID);
3854 if (tl->get_head()->gettyp() == TOKT_FMTSPEC)
3855 tl->unlink_head(&fmttok);
3856
3857 /* parse the embedded expression */
3858 sub = parse_embedded_expr(b, tl);
3859 if (sub == 0)
3860 return 0;
3861
3862 /* we can't have an end token immediately after an expression */
3863 check_end = FALSE;
3864
3865 /*
3866 * if we have a format spec, wrap the expression in a
3867 * sprintf node as sprintf(fmtspec, sub)
3868 */
3869 if (fmttok.gettyp() == TOKT_FMTSPEC)
3870 {
3871 /*
3872 * set up the argument list - fmtspec string, sub (note
3873 * that arg lists are built in reverse order)
3874 */
3875 CTcConstVal fmtcv;
3876 fmtcv.set_sstr(&fmttok);
3877 CTPNArg *args = new CTPNArg(sub);
3878 args->set_next_arg(new CTPNArg(new CTPNConst(&fmtcv)));
3879
3880 /* set up the sprintf call */
3881 sub = new CTPNCall(new CTPNSym("sprintf", 7),
3882 new CTPNArglist(2, args));
3883 }
3884 }
3885
3886 /* if we have an embedding, add it */
3887 if (sub != 0)
3888 cur = b->add_embedding(cur, sub);
3889
3890 /*
3891 * after the expression, we must find either another string segment
3892 * with another embedded expression following, or the final string
3893 * segment; anything else is an error
3894 */
3895 if (eos)
3896 {
3897 /*
3898 * We reached the end of the string in a sub-construct; there's
3899 * nothing more to add to the main string. Just return what we
3900 * have to the caller.
3901 */
3902 return b->finish_tree(cur);
3903 }
3904 else if ((curtyp = G_tok->cur()) == b->mid_tok())
3905 {
3906 /*
3907 * It's a string with yet another embedded expression. Add
3908 * this segment to the expression and proceed to the next
3909 * embedding.
3910 */
3911 cur = b->add_segment(cur);
3912 G_tok->next();
3913 }
3914 else if (curtyp == b->end_tok())
3915 {
3916 /*
3917 * It's the last segment of the string. Add the final segment
3918 * to the string.
3919 */
3920 cur = b->add_segment(cur);
3921 G_tok->next();
3922
3923 /* tell the caller we've reached the end, and return our tree */
3924 eos = TRUE;
3925 return b->finish_tree(cur);
3926 }
3927 else if (check_end && parse_embedded_end_tok(b, parent, &open_kw))
3928 {
3929 /*
3930 * We parsed a recursive list for <<if>>, <<one of>>, etc. End
3931 * tokens are implied when missing, so an end token at one
3932 * level can implicitly end multiple levels. We stopped at
3933 * such a token without consuming it, so it's for our caller to
3934 * digest. Simply return what we have and let the caller take
3935 * it from here.
3936 */
3937 return b->finish_tree(cur);
3938 }
3939 else if (G_tcmain->get_error_count() != nerr)
3940 {
3941 /*
3942 * We logged an error within a sub-expression, so it's not
3943 * surprising that we're not at a valid continuation token at
3944 * this point. Try syncing up with the source: look for a
3945 * continuation token or something that probably ends the
3946 * statement, such as a semicolon or right brace.
3947 */
3948 for (;;)
3949 {
3950 /* if we're at a statement ender, stop here */
3951 if (curtyp == TOKT_SEM || curtyp == TOKT_RBRACE)
3952 return b->finish_tree(cur);
3953
3954 /* if at eof, return failure */
3955 if (curtyp == TOKT_EOF)
3956 return 0;
3957
3958 /* if we're at a continuation token, resume parsing */
3959 if (curtyp == b->mid_tok() || curtyp == b->end_tok())
3960 break;
3961
3962 /* skip this token and keep looking for a sync point */
3963 curtyp = G_tok->next();
3964 }
3965 }
3966 else
3967 {
3968 /* anything else is invalid - log an error */
3969 G_tok->log_error_curtok(TCERR_EXPECTED_STR_CONT);
3970
3971 /*
3972 * Skip ahead until we find the next string segment or
3973 * something that looks like the end of the statement.
3974 */
3975 tl->reset();
3976 capture_embedded(b, tl);
3977
3978 /*
3979 * If we stopped at the next segment, carry on. Otherwise,
3980 * assume they simply left off the end of the string and return
3981 * what we have.
3982 */
3983 if (G_tok->cur() != b->mid_tok() && G_tok->cur() != b->end_tok())
3984 return (cur != 0 ? cur : b->finish_tree(sub));
3985 }
3986 }
3987 }
3988
3989 /*
3990 * Parse a single embedded expression
3991 */
3992 CTcPrsNode *CTcPrsOpUnary::parse_embedded_expr(
3993 CTcEmbedBuilder *b, CTcEmbedTokenList *tl)
3994 {
3995 /* search for a template for the expression */
3996 for (CTcStrTemplate *st = G_prs->get_str_template_head() ; st != 0 ;
3997 st = st->nxt)
3998 {
3999 /* check for a match */
4000 if (tl->match(st))
4001 {
4002 /*
4003 * This template matches. Generate the code as a call to the
4004 * template's processor function.
4005 */
4006 CTPNSymResolved *func = new CTPNSymResolved(st->func);
4007
4008 /*
4009 * If the template has a '*', the tokens matching the star are
4010 * a sub-expression that we evaluate as the argument to the
4011 * function. Otherwise we call it with no arguments.
4012 */
4013 CTPNArglist *arglist;
4014 if (st->star)
4015 {
4016 /*
4017 * If the template has any fixed tokens, reparse the
4018 * remaining tokens to see if they refer to a new template.
4019 * If the template was just '*', skip this, since we'd just
4020 * find the same match again.
4021 */
4022 CTcPrsNode *sub;
4023 if (st->cnt > 1)
4024 {
4025 /* remove the tokens that matched the fixed part */
4026 tl->reduce(st);
4027
4028 /* reparse as a new embedded expression */
4029 sub = parse_embedded_expr(b, tl);
4030 }
4031 else
4032 {
4033 /* the template is just '*', so parse a raw expression */
4034 tl->unget();
4035 sub = b->parse_expr();
4036 }
4037
4038 /* if we failed to parse a sub-expression, return failure */
4039 if (sub == 0)
4040 return 0;
4041
4042 /* create the argument list */
4043 arglist = new CTPNArglist(1, new CTPNArg(sub));
4044 }
4045 else
4046 {
4047 /* there's no argument list */
4048 arglist = new CTPNArglist(0, 0);
4049 }
4050
4051 /* create and return the call to the template function */
4052 return new CTPNCall(func, arglist);
4053 }
4054 }
4055
4056 /*
4057 * There's no template, so process it as an ordinary expression. Put
4058 * the captured token list back into the token stream, and parse an
4059 * expression node.
4060 */
4061 tl->unget();
4062 return b->parse_expr();
4063 }
4064
4065 /*
4066 * Capture an embedded expression to an embedded token list
4067 */
4068 void CTcPrsOpUnary::capture_embedded(CTcEmbedBuilder *b, CTcEmbedTokenList *tl)
4069 {
4070 /* reset the list */
4071 tl->reset();
4072
4073 /* we don't have any nested braces or parens yet */
4074 int braces = 0, parens = 0, bracks = 0;
4075
4076 /* run through the list */
4077 for (;;)
4078 {
4079 /* check what we have */
4080 switch (G_tok->cur())
4081 {
4082 case TOKT_LBRACE:
4083 ++braces;
4084 break;
4085
4086 case TOKT_RBRACE:
4087 /*
4088 * if we find an unbalanced close brace, assume that we've
4089 * reached the end of the statement without properly
4090 * terminating the string
4091 */
4092 if (--braces < 0)
4093 return;
4094 break;
4095
4096 case TOKT_LPAR:
4097 ++parens;
4098 break;
4099
4100 case TOKT_RPAR:
4101 --parens;
4102 break;
4103
4104 case TOKT_LBRACK:
4105 ++bracks;
4106 break;
4107
4108 case TOKT_RBRACK:
4109 --bracks;
4110 break;
4111
4112 case TOKT_SEM:
4113 /*
4114 * if we find a semicolon outside of braces, assume that we've
4115 * reached the end of the statement without properly
4116 * terminating the string
4117 */
4118 if (braces == 0)
4119 return;
4120 break;
4121
4122 case TOKT_EOF:
4123 return;
4124
4125 default:
4126 /* stop if we've reached the next string segment */
4127 if (G_tok->cur() == b->end_tok()
4128 || G_tok->cur() == b->mid_tok())
4129 return;
4130 break;
4131 }
4132
4133 /* add the token to the capture list and move on to the next */
4134 tl->add_tok(G_tok->getcur());
4135 G_tok->next();
4136 }
4137 }
4138
4139 /*
4140 * Parse an embedded "if" or "unless" construct. The two are the same,
4141 * except the "unless" inverts the condition.
4142 */
4143 CTcPrsNode *CTcPrsOpUnary::parse_embedded_if(
4144 CTcEmbedBuilder *b, int unless, int &eos, CTcEmbedLevel *parent)
4145 {
4146 /* set up our embedding stack level */
4147 CTcEmbedLevel level(CTcEmbedLevel::If, parent);
4148
4149 /* parse the condition expression */
4150 CTcPrsNode *cond = G_prs->parse_cond_expr();
4151 if (cond == 0)
4152 return 0;
4153
4154 /* if this is an "unless", invert the condition */
4155 if (unless)
4156 cond = new CTPNNot(cond);
4157
4158 /* parse the "then" list */
4159 CTcPrsNode *then = parse_embedding_list(b, eos, &level);
4160 if (then == 0)
4161 return 0;
4162
4163 /*
4164 * create our top-level 'if' node - leave the 'else' branch empty for
4165 * now; we'll build this out if we find an 'else'
4166 */
4167 CTPNIf *top = new CTPNIf(cond, then, 0);
4168
4169 /*
4170 * as we build out the 'else if' branches, we'll add elses to the tail
4171 * of the tree; this is currently the top node
4172 */
4173 CTPNIf *tail = top;
4174
4175 /* parse zero or more "else if" branches */
4176 int found_else = FALSE;
4177 while (!eos
4178 && (G_tok->cur() == TOKT_ELSE
4179 || G_tok->cur_tok_matches("otherwise")))
4180 {
4181 /* skip the "else"/"otherwise", and check for another "if" */
4182 if (G_tok->next() == TOKT_IF || G_tok->cur_tok_matches("unless"))
4183 {
4184 /*
4185 * <<else if cond>> or <<else unless cond>>. Note which sense
4186 * of the test we're using.
4187 */
4188 unless = (G_tok->cur() != TOKT_IF);
4189
4190 /* skip the "else"/"otherwise" and parse the condition */
4191 G_tok->next();
4192 cond = G_prs->parse_cond_expr();
4193 if (cond == 0)
4194 return 0;
4195
4196 /* if it's 'unless', invert the condition */
4197 if (unless)
4198 cond = new CTPNNot(cond);
4199
4200 /* parse the "then" list for this new branch */
4201 then = parse_embedding_list(b, eos, &level);
4202 if (then == 0)
4203 return 0;
4204
4205 /* add the new 'if' node to the 'else' of the tail of the tree */
4206 CTPNIf *sub = new CTPNIf(cond, then, 0);
4207 tail->set_else(sub);
4208
4209 /* this is the new tail, for adding the next 'else' */
4210 tail = sub;
4211 }
4212 else
4213 {
4214 /* it's the final else/otherwise - parse the branch */
4215 CTcPrsNode *sub = parse_embedding_list(b, eos, &level);
4216 if (sub == 0)
4217 return 0;
4218
4219 /* add it as the else branch of the tail node of the tree */
4220 tail->set_else(sub);
4221
4222 /* no more clauses of the "if" can follow an "else" */
4223 found_else = TRUE;
4224 break;
4225 }
4226 }
4227
4228 /*
4229 * if we ended without an "else", add an implicit "nil" as the final
4230 * "else" branch
4231 */
4232 if (!found_else)
4233 tail->set_else(b->finish_tree(0));
4234
4235 /*
4236 * If we're at an "end" token, this is the explicit close of the "if".
4237 * Otherwise, the "if" ended implicitly at the end of the string or at
4238 * a closing token for a containing structure.
4239 */
4240 if (!eos && G_tok->cur_tok_matches("end"))
4241 G_tok->next();
4242
4243 /* return the condition tree */
4244 return top;
4245 }
4246
4247 /*
4248 * "one of" enders
4249 */
4250 struct one_of_option
4251 {
4252 /* ending phrase */
4253 const char *endph;
4254
4255 /* list attribute string */
4256 const char *attr;
4257 };
4258 static one_of_option one_of_list[] =
4259 {
4260 { "purely at random", "rand" },
4261 { "then purely at random", "seq,rand" },
4262 { "at random" , "rand-norpt" },
4263 { "then at random", "seq,rand-norpt" },
4264 { "sticky random", "rand,stop" },
4265 { "as decreasingly likely outcomes", "rand-wt" },
4266 { "shuffled", "shuffle" },
4267 { "then shuffled", "seq,shuffle" },
4268 { "half shuffled", "shuffle2" },
4269 { "then half shuffled", "seq,shuffle2" },
4270 { "cycling", "seq" },
4271 { "stopping", "seq,stop" }
4272 };
4273
4274 /*
4275 * Parse an embedded "one of" construct
4276 */
4277 CTcPrsNode *CTcPrsOpUnary::parse_embedded_oneof(
4278 CTcEmbedBuilder *b, int &eos, CTcEmbedLevel *parent)
4279 {
4280 /* get the embedding token list capturer */
4281 CTcEmbedTokenList *tl = G_prs->embed_toks_;
4282
4283 /* set up our stack level */
4284 CTcEmbedLevel level(CTcEmbedLevel::OneOf, parent);
4285
4286 /* create a list node to hold the items */
4287 CTPNList *lst = new CTPNList();
4288
4289 /* keep going until we get to the end of the list */
4290 for (;;)
4291 {
4292 /* parse the next string or embedded expression */
4293 CTcPrsNode *ele = parse_embedding_list(b, eos, &level);
4294 if (ele == 0)
4295 return 0;
4296
4297 /* add this element to the list */
4298 lst->add_element(ele);
4299
4300 /* capture the ending token list */
4301 tl->reset();
4302 capture_embedded(b, tl);
4303
4304 /* if we're not at an OR, this is the end of the list */
4305 if (!tl->match("or") && !tl->match("||"))
4306 break;
4307 }
4308
4309 /*
4310 * Search for a match to one of our endings. If we don't find one, use
4311 * "purely at random" as the default.
4312 */
4313 const char *attrs = 0;
4314 for (size_t i = 0 ; i < countof(one_of_list) ; ++i)
4315 {
4316 /* check for a match */
4317 if (tl->match(one_of_list[i].endph))
4318 {
4319 /* got it - set this attribute and stop searching */
4320 attrs = one_of_list[i].attr;
4321 break;
4322 }
4323 }
4324
4325 /*
4326 * if we didn't find a match for the ending tokens, we must have the
4327 * ending for an enclosing structure; put the tokens back for the
4328 * enclosing structure to parse, and use "purely at random" as the
4329 * default
4330 */
4331 if (attrs == 0)
4332 {
4333 tl->unget();
4334 attrs = "rand";
4335 }
4336
4337 /* create the one-of list */
4338 return create_oneof_node(b, lst, attrs);
4339 }
4340
4341 /*
4342 * Create a one-of list node
4343 */
4344 CTcPrsNode *CTcPrsOpUnary::create_oneof_node(
4345 CTcEmbedBuilder *b, CTPNList *lst, const char *attrs)
4346 {
4347 /*
4348 * If we're actually compiling (not just doing a symbol extraction
4349 * pass), create our list state object. This is an anonymous
4350 * TadsObject of class OneOfIndexGen, with the following properties:
4351 *
4352 *. numItems = number of items in the list (integer)
4353 *. listAttrs = our 'attrs' list attributes value (string)
4354 */
4355 CTcSymObj *obj = 0;
4356 if (!G_prs->get_syntax_only())
4357 {
4358 /* geneate our anonymous OneOfIndexGen instance */
4359 obj = G_prs->add_gen_obj("OneOfIndexGen");
4360 if (obj != 0)
4361 {
4362 G_prs->add_gen_obj_prop(obj, "numItems", lst->get_count());
4363 G_prs->add_gen_obj_prop(obj, "listAttrs", attrs);
4364 }
4365 else
4366 {
4367 /* check to see if OneOfIndexGen is undefined */
4368 CTcSymbol *cls = G_prs->get_global_symtab()->find(
4369 "OneOfIndexGen", 13);
4370 if (cls == 0 || cls->get_type() != TC_SYM_OBJ)
4371 G_tok->log_error(TCERR_ONEOF_REQ_GENCLS);
4372 }
4373 }
4374
4375 /* return the <<one of>> node */
4376 return new CTPNStrOneOf(b->is_double(), lst, obj);
4377 }
4378
4379 /*
4380 * Parse an embedded "first time" structure
4381 */
4382 CTcPrsNode *CTcPrsOpUnary::parse_embedded_firsttime(
4383 CTcEmbedBuilder *b, int &eos, CTcEmbedLevel *parent)
4384 {
4385 /* get the embedding token list capturer */
4386 CTcEmbedTokenList *tl = G_prs->embed_toks_;
4387
4388 /* set up our stack level */
4389 CTcEmbedLevel level(CTcEmbedLevel::FirstTime, parent);
4390
4391 /* parse the embedding */
4392 CTcPrsNode *ele = parse_embedding_list(b, eos, &level);
4393 if (ele == 0)
4394 return 0;
4395
4396 /* capture the ending token list */
4397 tl->reset();
4398 capture_embedded(b, tl);
4399
4400 /*
4401 * check for our "only" list - if we don't match it, put the tokens
4402 * back, since they must be the ending list for an enclosing structure
4403 */
4404 if (!tl->match("only"))
4405 tl->unget();
4406
4407 /* create this as equivalent to <<one of>>our item<<or>><<stopping>> */
4408 CTPNList *lst = new CTPNList();
4409 lst->add_element(ele);
4410
4411 CTcConstVal cv;
4412 cv.set_sstr("", 0);
4413 lst->add_element(new CTPNConst(&cv));
4414
4415 /* create the <<one of>> node */
4416 return create_oneof_node(b, lst, "seq,stop");
4417 }
4418
4419
4420 /*
4421 * Check for an end token in an embedded expression construct. Reads from
4422 * the token stream, but restores the tokens when done.
4423 */
4424 int CTcPrsOpUnary::parse_embedded_end_tok(CTcEmbedBuilder *b,
4425 CTcEmbedLevel *parent,
4426 const char **open_kw)
4427 {
4428 /* capture the current expression's token list */
4429 CTcEmbedTokenList *tl = G_prs->embed_toks_;
4430 tl->reset();
4431 capture_embedded(b, tl);
4432
4433 /* parse the end token */
4434 int ret = parse_embedded_end_tok(tl, parent, open_kw);
4435
4436 /* un-get the captured tokens */
4437 tl->unget();
4438
4439 /* return the result */
4440 return ret;
4441 }
4442
4443 /*
4444 * Check for an end token in an embedded expression construct. Compares
4445 * tokens in the given capture list.
4446 */
4447 int CTcPrsOpUnary::parse_embedded_end_tok(CTcEmbedTokenList *tl,
4448 CTcEmbedLevel *parent,
4449 const char **open_kw)
4450 {
4451 /* presume we won't find a closing keyword */
4452 *open_kw = "unknown";
4453
4454 /*
4455 * consider ending keywords to always be significant, regardless of
4456 * context, since these are unambiguous with valid expressions
4457 */
4458 if (tl->match("else")
4459 || tl->match("else if *")
4460 || tl->match("else unless *"))
4461 {
4462 *open_kw = "<<if>> or <<unless>>";
4463 return TRUE;
4464 }
4465
4466 /* check for "if" ending tokens - else, end */
4467 if (tl->match("end")
4468 || tl->match("otherwise")
4469 || tl->match("otherwise if *")
4470 || tl->match("otherwise unless *"))
4471 {
4472 *open_kw = "<<if>> or <<unless>>";
4473 if (parent->is_in(CTcEmbedLevel::If))
4474 return TRUE;
4475 }
4476
4477 /* check for an "or", which delimits branches of a "one of" */
4478 if (tl->match("or") || tl->match("||"))
4479 {
4480 *open_kw = "<<one of>>";
4481 if (parent->is_in(CTcEmbedLevel::OneOf))
4482 return TRUE;
4483 }
4484
4485 /* check for "one of" ending tokens */
4486 for (size_t i = 0 ; i < countof(one_of_list) ; ++i)
4487 {
4488 if (tl->match(one_of_list[i].endph))
4489 {
4490 *open_kw = "<<one of>>";
4491 if (parent->is_in(CTcEmbedLevel::OneOf))
4492 return TRUE;
4493 break;
4494 }
4495 }
4496
4497 /* check for an "only", which ends a "first time" */
4498 if (tl->match("only"))
4499 {
4500 *open_kw = "<<first time>>";
4501 if (parent->is_in(CTcEmbedLevel::FirstTime))
4502 return TRUE;
4503 }
4504
4505 /* didn't find a close token */
4506 return FALSE;
4507 }
4508
4509
4510 /* ------------------------------------------------------------------------ */
4511 /*
4512 * Embedded <<one of>> list in a string
4513 */
4514
4515 CTcPrsNode *CTPNStrOneOfBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
4516 {
4517 lst_ = (CTPNList *)lst_->adjust_for_dyn(info);
4518 return this;
4519 }
4520
4521 CTcPrsNode *CTPNStrOneOfBase::fold_constants(CTcPrsSymtab *symtab)
4522 {
4523 lst_ = (CTPNList *)lst_->fold_constants(symtab);
4524 return this;
4525 }
4526
4527 /* ------------------------------------------------------------------------ */
4528 /*
4529 * Unary Operator Parser
4530 */
4531
4532 CTcPrsNode *CTcPrsOpUnary::parse() const
4533 {
4534 /* get the current token, which may be a prefix operator */
4535 tc_toktyp_t op = G_tok->cur();
4536
4537 /* check for prefix operators */
4538 switch(op)
4539 {
4540 case TOKT_AND:
4541 /* skip the '&' */
4542 G_tok->next();
4543
4544 /* parse the address expression */
4545 return parse_addr();
4546
4547 case TOKT_NOT:
4548 case TOKT_BNOT:
4549 case TOKT_PLUS:
4550 case TOKT_MINUS:
4551 case TOKT_INC:
4552 case TOKT_DEC:
4553 case TOKT_DELETE:
4554 {
4555 /* skip the operator */
4556 G_tok->next();
4557
4558 /*
4559 * recursively parse the unary expression to which to apply the
4560 * operator
4561 */
4562 CTcPrsNode *sub = parse();
4563 if (sub == 0)
4564 return 0;
4565
4566 /* apply the operator */
4567 switch(op)
4568 {
4569 case TOKT_NOT:
4570 /* apply the NOT operator */
4571 return parse_not(sub);
4572
4573 case TOKT_BNOT:
4574 /* apply the bitwise NOT operator */
4575 return parse_bnot(sub);
4576
4577 case TOKT_PLUS:
4578 /* apply the unary positive operator */
4579 return parse_pos(sub);
4580
4581 case TOKT_MINUS:
4582 /* apply the unary negation operator */
4583 return parse_neg(sub);
4584
4585 case TOKT_INC:
4586 /* apply the pre-increment operator */
4587 return parse_inc(TRUE, sub);
4588
4589 case TOKT_DEC:
4590 /* apply the pre-decrement operator */
4591 return parse_dec(TRUE, sub);
4592
4593 case TOKT_DELETE:
4594 /* apply the deletion operator */
4595 return parse_delete(sub);
4596
4597 default:
4598 /*
4599 * we shouldn't ever get here, since this switch should
4600 * contain every case that brought us into it in the first
4601 * place
4602 */
4603 return 0;
4604 }
4605 }
4606
4607 default:
4608 /* it's not a unary prefix operator - parse a postfix expression */
4609 return parse_postfix(TRUE, TRUE);
4610 }
4611 }
4612
4613 /*
4614 * parse a unary NOT expression
4615 */
4616 CTcPrsNode *CTcPrsOpUnary::parse_not(CTcPrsNode *subexpr)
4617 {
4618 /* try folding a constant value */
4619 CTcPrsNode *ret = eval_const_not(subexpr);
4620
4621 /*
4622 * if we got a constant result, return it; otherwise, create a NOT
4623 * node for code generation
4624 */
4625 if (ret != 0)
4626 return ret;
4627 else
4628 return new CTPNNot(subexpr);
4629 }
4630
4631 /*
4632 * evaluate a constant NOT expression
4633 */
4634 CTcPrsNode *CTcPrsOpUnary::eval_const_not(CTcPrsNode *subexpr)
4635 {
4636 /*
4637 * if the underlying expression is a constant value, apply the
4638 * operator
4639 */
4640 if (subexpr->is_const())
4641 {
4642 /* set the new value */
4643 subexpr->get_const_val()
4644 ->set_bool(!subexpr->get_const_val()->get_val_bool());
4645
4646 /* return the modified constant value */
4647 return subexpr;
4648 }
4649
4650 /* the result is not constant */
4651 return 0;
4652 }
4653
4654 /*
4655 * parse a unary bitwise NOT expression
4656 */
4657 CTcPrsNode *CTcPrsOpUnary::parse_bnot(CTcPrsNode *subexpr)
4658 {
4659 /*
4660 * if the underlying expression is a constant value, apply the
4661 * operator
4662 */
4663 if (subexpr->is_const())
4664 {
4665 /* we need an integer - log an error if it's not */
4666 if (subexpr->get_const_val()->get_type() != TC_CVT_INT)
4667 G_tok->log_error(TCERR_CONST_UNARY_REQ_NUM,
4668 G_tok->get_op_text(TOKT_BNOT));
4669 else
4670 subexpr->get_const_val()
4671 ->set_int(~subexpr->get_const_val()->get_val_int());
4672
4673 /* return the updated value */
4674 return subexpr;
4675 }
4676
4677 /* create the bitwise NOT node */
4678 return new CTPNBNot(subexpr);
4679 }
4680
4681 /*
4682 * parse a unary address expression
4683 */
4684 CTcPrsNode *CTcPrsOpUnary::parse_addr() const
4685 {
4686 /*
4687 * if it's a simple symbol, create an unresolved symbol node for it;
4688 * otherwise parse the entire expression
4689 */
4690 CTcPrsNode *subexpr;
4691 if (G_tok->cur() == TOKT_SYM)
4692 {
4693 /*
4694 * create an unresolved symbol node - we'll resolve this during
4695 * code generation
4696 */
4697 const CTcToken *tok = G_tok->getcur();
4698 subexpr = new CTPNSym(tok->get_text(), tok->get_text_len());
4699
4700 /*
4701 * If the symbol is undefined, assume it's a property, but make the
4702 * definition "weak". Starting in 3.1, &x can be a property ID, a
4703 * function pointer, or a built-in function pointer, so it's no
4704 * longer safe to just assume it's a property. If we don't see the
4705 * symbol used in any other context, we'll assume it's a property,
4706 * but mark it as "weak" if it's not already defined. This will
4707 * allow any conflicting definition to override the property
4708 * assumption without complaint.
4709 */
4710 G_prs->get_global_symtab()->find_or_def_prop_weak(
4711 tok->get_text(), tok->get_text_len(), FALSE);
4712
4713 /* skip the symbol */
4714 G_tok->next();
4715 }
4716 else if (G_tok->cur() == TOKT_OPERATOR)
4717 {
4718 /* operator property - parse the operator name */
4719 CTcToken proptok;
4720 if (G_prs->parse_op_name(&proptok))
4721 {
4722 /* skip the last token of the operator name */
4723 G_tok->next();
4724 }
4725
4726 /* create a symbol for it */
4727 subexpr = new CTPNSym(proptok.get_text(), proptok.get_text_len());
4728 }
4729 else
4730 {
4731 /* parse an expression */
4732 subexpr = parse();
4733 if (subexpr == 0)
4734 return 0;
4735 }
4736
4737 /*
4738 * The underlying expression must be something that has an address;
4739 * if it's not, it's an error.
4740 */
4741 if (!subexpr->has_addr())
4742 {
4743 /*
4744 * can't take the address of the subexpression - log an error,
4745 * but continue parsing the expression anyway
4746 */
4747 G_tok->log_error(TCERR_NO_ADDRESS);
4748 }
4749
4750 /* create the address node */
4751 return new CTPNAddr(subexpr);
4752 }
4753
4754 /*
4755 * parse a unary arithmetic positive expression
4756 */
4757 CTcPrsNode *CTcPrsOpUnary::parse_pos(CTcPrsNode *subexpr)
4758 {
4759 /*
4760 * if the underlying expression is a constant value, apply the
4761 * operator
4762 */
4763 if (subexpr->is_const())
4764 {
4765 /* if it's a float, a unary '+' has no effect at all */
4766 if (subexpr->get_const_val()->get_type() == TC_CVT_FLOAT)
4767 return subexpr;
4768
4769 /* we need an integer - log an error if it's not */
4770 if (subexpr->get_const_val()->get_type() != TC_CVT_INT)
4771 G_tok->log_error(TCERR_CONST_UNARY_REQ_NUM,
4772 G_tok->get_op_text(TOKT_PLUS));
4773
4774 /*
4775 * positive-ing a value doesn't change the value, so return the
4776 * original constant
4777 */
4778 return subexpr;
4779 }
4780
4781 /* create the unary positive node */
4782 return new CTPNPos(subexpr);
4783 }
4784
4785 /*
4786 * parse a unary arithmetic negation expression
4787 */
4788 CTcPrsNode *CTcPrsOpUnary::parse_neg(CTcPrsNode *subexpr)
4789 {
4790 /*
4791 * if the underlying expression is a constant value, apply the
4792 * operator
4793 */
4794 if (subexpr->is_const())
4795 {
4796 /* we need an integer or float */
4797 CTcConstVal *cval = subexpr->get_const_val();
4798 if (cval->get_type() == TC_CVT_INT)
4799 {
4800 /*
4801 * Negating an integer. There's a special overflow case to
4802 * check for: if we're negating INT32MINVAL, the result doesn't
4803 * fit in a signed integer, so we need to promote it to float.
4804 */
4805 long l = cval->get_val_int();
4806 if (l <= INT32MINVAL)
4807 {
4808 /* overflow - promote to BigNumber */
4809 vbignum_t b((ulong)2147483648U);
4810 cval->set_float(&b, TRUE);
4811 }
4812 else
4813 {
4814 /* set the value negative in the subexpression */
4815 cval->set_int(-l);
4816 }
4817 }
4818 else if (subexpr->get_const_val()->get_type() == TC_CVT_FLOAT)
4819 {
4820 /* get the original value */
4821 const char *ctxt = cval->get_val_float();
4822 size_t clen = cval->get_val_float_len();
4823
4824 /* if the old value is negative, simply remove the sign */
4825 if (clen > 0 && ctxt[0] == '-')
4826 {
4827 /* keep the old value, removing the sign */
4828 cval->set_float(ctxt + 1, clen - 1, cval->is_promoted());
4829 }
4830 else
4831 {
4832 /* allocate new buffer for the float text plus a '-' */
4833 char *new_txt = (char *)G_prsmem->alloc(clen + 1);
4834
4835 /* insert the minus sign */
4836 new_txt[0] = '-';
4837
4838 /* add the original string */
4839 memcpy(new_txt + 1, ctxt, clen);
4840
4841 /* update the subexpression's constant value to the new text */
4842 cval->set_float(new_txt, clen + 1, cval->is_promoted());
4843 }
4844
4845 /* check for possible demotion back to int */
4846 cval->demote_float();
4847 }
4848 else
4849 {
4850 /* log the error */
4851 G_tok->log_error(TCERR_CONST_UNARY_REQ_NUM,
4852 G_tok->get_op_text(TOKT_MINUS));
4853 }
4854
4855 /* return the modified constant value */
4856 return subexpr;
4857 }
4858
4859 /* create the unary negation node */
4860 return new CTPNNeg(subexpr);
4861 }
4862
4863
4864 /*
4865 * parse a pre-increment expression
4866 */
4867 CTcPrsNode *CTcPrsOpUnary::parse_inc(int pre, CTcPrsNode *subexpr)
4868 {
4869 /* require an lvalue */
4870 if (!subexpr->check_lvalue())
4871 {
4872 /* log an error, but continue parsing */
4873 G_tok->log_error(TCERR_INVALID_UNARY_LVALUE,
4874 G_tok->get_op_text(TOKT_INC));
4875 }
4876
4877 /* apply the increment operator */
4878 if (pre)
4879 return new CTPNPreInc(subexpr);
4880 else
4881 return new CTPNPostInc(subexpr);
4882 }
4883
4884 /*
4885 * parse a pre-decrement expression
4886 */
4887 CTcPrsNode *CTcPrsOpUnary::parse_dec(int pre, CTcPrsNode *subexpr)
4888 {
4889 /* require an lvalue */
4890 if (!subexpr->check_lvalue())
4891 {
4892 /* log an error, but continue parsing */
4893 G_tok->log_error(TCERR_INVALID_UNARY_LVALUE,
4894 G_tok->get_op_text(TOKT_DEC));
4895 }
4896
4897 /* apply the pre-increment operator */
4898 if (pre)
4899 return new CTPNPreDec(subexpr);
4900 else
4901 return new CTPNPostDec(subexpr);
4902 }
4903
4904 /*
4905 * parse a unary allocation expression
4906 */
4907 CTcPrsNode *CTcPrsOpUnary::parse_new(CTcPrsNode *subexpr, int is_transient)
4908 {
4909 /* create the allocation node */
4910 return new CTPNNew(subexpr, is_transient);
4911 }
4912
4913 /*
4914 * parse a unary deletion expression
4915 */
4916 CTcPrsNode *CTcPrsOpUnary::parse_delete(CTcPrsNode *subexpr)
4917 {
4918 /* the delete operator is obsolete in TADS 3 - warn about it */
4919 if (!G_prs->get_syntax_only())
4920 G_tok->log_warning(TCERR_DELETE_OBSOLETE);
4921
4922 /* create the deletion node */
4923 return new CTPNDelete(subexpr);
4924 }
4925
4926 /*
4927 * parse a postfix expression
4928 */
4929 CTcPrsNode *CTcPrsOpUnary::parse_postfix(int allow_member_expr,
4930 int allow_call_expr)
4931 {
4932 /* parse a primary expression */
4933 CTcPrsNode *sub = parse_primary();
4934 if (sub == 0)
4935 return 0;
4936
4937 /* keep going as long as we find postfix operators */
4938 for (;;)
4939 {
4940 /* check for a postfix operator */
4941 tc_toktyp_t op = G_tok->cur();
4942 switch(op)
4943 {
4944 case TOKT_LPAR:
4945 /* left paren - function or method call */
4946 if (allow_call_expr)
4947 {
4948 /* parse the function call expression */
4949 sub = parse_call(sub);
4950 }
4951 else
4952 {
4953 /* call expressions aren't allowed - stop here */
4954 return sub;
4955 }
4956 break;
4957
4958 case TOKT_LBRACK:
4959 /* left square bracket - subscript */
4960 sub = parse_subscript(sub);
4961 break;
4962
4963 case TOKT_DOT:
4964 /*
4965 * Dot - member selection. If a member expression is allowed
4966 * by the caller, parse it; otherwise, just return the
4967 * expression up to this point.
4968 */
4969 if (allow_member_expr)
4970 {
4971 /*
4972 * it's allowed - parse it and continue to look for other
4973 * postfix expressions following the member expression
4974 */
4975 sub = parse_member(sub);
4976 }
4977 else
4978 {
4979 /*
4980 * member expressions aren't allowed - stop here,
4981 * returning the expression up to this point
4982 */
4983 return sub;
4984 }
4985 break;
4986
4987 case TOKT_INC:
4988 /* post-increment */
4989 G_tok->next();
4990 sub = parse_inc(FALSE, sub);
4991 break;
4992
4993 case TOKT_DEC:
4994 /* post-decrement */
4995 G_tok->next();
4996 sub = parse_dec(FALSE, sub);
4997 break;
4998
4999 default:
5000 /* it's not a postfix operator - return the result */
5001 return sub;
5002 }
5003
5004 /* if the last parse failed, return failure */
5005 if (sub == 0)
5006 return 0;
5007 }
5008 }
5009
5010 /*
5011 * Parse an argument list
5012 */
5013 CTPNArglist *CTcPrsOpUnary::parse_arg_list()
5014 {
5015 /* skip the open paren */
5016 G_tok->next();
5017
5018 /* keep going until we find the close paren */
5019 int argc;
5020 CTPNArg *arg_head;
5021 for (argc = 0, arg_head = 0 ;; )
5022 {
5023 /* presume it's not a named argument */
5024 CTcToken param_name;
5025 param_name.settyp(TOKT_INVALID);
5026
5027 /* if this is the close paren, we're done */
5028 if (G_tok->cur() == TOKT_RPAR)
5029 break;
5030
5031 /* check for a named argument: "symbol: expression" */
5032 if (G_tok->cur() == TOKT_SYM)
5033 {
5034 /* remember the symbol, in case it is in fact a named argument */
5035 param_name = *G_tok->getcur();
5036
5037 /* peek ahead - if a colon follows, it's a named argument */
5038 if (G_tok->next() == TOKT_COLON)
5039 {
5040 /*
5041 * it's a named argument - we already have the name stashed
5042 * away for when we create the argument node, so simply
5043 * skip the colon so we can parse the argument value
5044 * expression
5045 */
5046 G_tok->next();
5047 }
5048 else
5049 {
5050 /*
5051 * No colon - it's a regular parameter expression. Put
5052 * back the token we peeked at, clear out the name token,
5053 * and keep parsing as normal.
5054 */
5055 G_tok->unget();
5056 param_name.settyp(TOKT_INVALID);
5057 }
5058 }
5059
5060 /*
5061 * parse this argument expression - this is an 'assignment'
5062 * expression, since a comma is an argument separator in this
5063 * context rather than an operator
5064 */
5065 CTcPrsNode *expr = S_op_asi.parse();
5066 if (expr == 0)
5067 return 0;
5068
5069 /* if this is a positional argument (not named), count it */
5070 if (param_name.gettyp() != TOKT_SYM)
5071 ++argc;
5072
5073 /* create a new argument node */
5074 CTPNArg *arg_cur = new CTPNArg(expr);
5075
5076 /* if it's a named argument, store the name in the argument node */
5077 arg_cur->set_name(&param_name);
5078
5079 /* check to see if the argument is followed by an ellipsis */
5080 if (G_tok->cur() == TOKT_ELLIPSIS)
5081 {
5082 /* this isn't allowed for a named argument */
5083 if (param_name.gettyp() == TOKT_SYM)
5084 G_tok->log_error(TCERR_NAMED_ARG_NO_ELLIPSIS);
5085
5086 /* skip the ellipsis */
5087 G_tok->next();
5088
5089 /* mark the argument as a list-to-varargs parameter */
5090 arg_cur->set_varargs(TRUE);
5091 }
5092
5093 /*
5094 * Link the new node in at the beginning of our list - this will
5095 * ensure that the list is built in reverse order, which is the
5096 * order in which we push the arguments onto the stack.
5097 */
5098 arg_cur->set_next_arg(arg_head);
5099 arg_head = arg_cur;
5100
5101 /* we need to be looking at a comma, right paren, or ellipsis */
5102 if (G_tok->cur() == TOKT_RPAR)
5103 {
5104 /* that's the end of the list */
5105 break;
5106 }
5107 else if (G_tok->cur() == TOKT_COMMA)
5108 {
5109 /* skip the comma and parse the next argument */
5110 G_tok->next();
5111 }
5112 else
5113 {
5114 /*
5115 * If we're at the end of the file, there's no point
5116 * proceding, so return failure. If we've reached something
5117 * that looks like a statement separator (semicolon, curly
5118 * brace), also return failure, since the problem is clearly
5119 * a missing right paren. Otherwise, assume that a comma
5120 * was missing and continue as though we have another
5121 * argument.
5122 */
5123 switch(G_tok->cur())
5124 {
5125 default:
5126 /* log an error */
5127 G_tok->log_error_curtok(TCERR_EXPECTED_ARG_COMMA);
5128
5129 /*
5130 * if we're at the end of file, return what we have so
5131 * far; otherwise continue, assuming that they merely
5132 * left out a comma between two argument expressions
5133 */
5134 if (G_tok->cur() == TOKT_EOF)
5135 return new CTPNArglist(argc, arg_head);
5136 break;
5137
5138 case TOKT_SEM:
5139 case TOKT_LBRACE:
5140 case TOKT_RBRACE:
5141 case TOKT_DSTR_MID:
5142 case TOKT_DSTR_END:
5143 /*
5144 * we're apparently at the end of the statement; flag
5145 * the error as a missing right paren, and return what
5146 * we have so far
5147 */
5148 G_tok->log_error_curtok(TCERR_EXPECTED_ARG_RPAR);
5149 return new CTPNArglist(argc, arg_head);
5150 }
5151 }
5152 }
5153
5154 /* skip the closing paren */
5155 G_tok->next();
5156
5157 /* create and return the argument list descriptor */
5158 return new CTPNArglist(argc, arg_head);
5159 }
5160
5161 /*
5162 * Parse a function call expression
5163 */
5164 CTcPrsNode *CTcPrsOpUnary::parse_call(CTcPrsNode *lhs)
5165 {
5166 /* parse the argument list */
5167 CTPNArglist *arglist = parse_arg_list();
5168 if (arglist == 0)
5169 return 0;
5170
5171 /* check for the special "defined()" syntax */
5172 if (lhs != 0 && lhs->sym_text_matches("defined", 7))
5173 {
5174 /* make sure we have one argument that's a symbol */
5175 CTcPrsNode *arg;
5176 if (arglist->get_argc() == 1
5177 && (arg = arglist->get_arg_list_head()->get_arg_expr())
5178 ->get_sym_text() != 0)
5179 {
5180 /* look up the symbol */
5181 CTcSymbol *sym = G_prs->get_global_symtab()->find(
5182 arg->get_sym_text(), arg->get_sym_text_len());
5183
5184 /*
5185 * The result is a constant 'true' or 'nil' node, depending on
5186 * whether the symbol is defined. Note that this is a "compile
5187 * time constant" expression, not a true constant - flag it as
5188 * such so that we don't generate a warning if this value is
5189 * used as the conditional expression of an if, while, or for.
5190 */
5191 CTcConstVal cval;
5192 cval.set_bool(sym != 0 && sym->get_type() != TC_SYM_UNKNOWN);
5193 cval.set_ctc(TRUE);
5194 return new CTPNConst(&cval);
5195 }
5196 else
5197 {
5198 /* invalid syntax */
5199 G_tok->log_error(TCERR_DEFINED_SYNTAX);
5200 }
5201 }
5202
5203 /* check for the special "__objref" syntax */
5204 if (lhs != 0 && lhs->sym_text_matches("__objref", 8))
5205 {
5206 /* assume we won't generate an error or warning if it's undefined */
5207 int errhandling = 0;
5208
5209 /* get the rightmost argument */
5210 CTPNArg *curarg = arglist->get_arg_list_head();
5211
5212 /* if we have other than two arguments, it's an error */
5213 if (arglist->get_argc() > 2)
5214 {
5215 G_tok->log_error(TCERR___OBJREF_SYNTAX);
5216 return lhs;
5217 }
5218
5219 /* if we have two arguments, get the warning/error mode */
5220 if (arglist->get_argc() == 2)
5221 {
5222 /* get the argument, and skip to the next to the left */
5223 CTcPrsNode *arg = curarg->get_arg_expr();
5224 curarg = curarg->get_next_arg();
5225
5226 /* it has to be "warn" or "error" */
5227 if (arg->sym_text_matches("warn", 4))
5228 {
5229 errhandling = 1;
5230 }
5231 else if (arg->sym_text_matches("error", 5))
5232 {
5233 errhandling = 2;
5234 }
5235 else
5236 {
5237 G_tok->log_error(TCERR___OBJREF_SYNTAX);
5238 return lhs;
5239 }
5240 }
5241
5242 /* the first argument must be a symbol */
5243 CTcPrsNode *arg = curarg->get_arg_expr();
5244 if (arg->get_sym_text() != 0)
5245 {
5246 /* look up the symbol */
5247 CTcSymbol *sym = G_prs->get_global_symtab()->find(
5248 arg->get_sym_text(), arg->get_sym_text_len());
5249
5250 /*
5251 * The result is the object reference value if the symbol is
5252 * defined as an object, or nil if it's undefined or something
5253 * other than an object.
5254 */
5255 CTcConstVal cval;
5256 if (sym != 0 && sym->get_type() == TC_SYM_OBJ)
5257 {
5258 /* it's an object - the result is the object symbol */
5259 return arg;
5260 }
5261 else
5262 {
5263 /* log a warning or error, if applicable */
5264 if (errhandling != 0 && !G_prs->get_syntax_only())
5265 {
5266 /* note whether it's undefined or otherwise defined */
5267 int errcode =
5268 (sym == 0 ? TCERR_UNDEF_SYM : TCERR_SYM_NOT_OBJ);
5269
5270 /* log an error or warning, as desired */
5271 if (errhandling == 1)
5272 G_tok->log_warning(
5273 errcode, (int)arg->get_sym_text_len(),
5274 arg->get_sym_text());
5275 else
5276 G_tok->log_error(
5277 errcode, (int)arg->get_sym_text_len(),
5278 arg->get_sym_text());
5279 }
5280
5281 /* not defined or non-object - the result is nil */
5282 cval.set_bool(FALSE);
5283 cval.set_ctc(TRUE);
5284 return new CTPNConst(&cval);
5285 }
5286 }
5287 else
5288 {
5289 /* invalid syntax */
5290 G_tok->log_error(TCERR___OBJREF_SYNTAX);
5291 }
5292 }
5293
5294 /* build and return the function call node */
5295 return new CTPNCall(lhs, arglist);
5296 }
5297
5298 /*
5299 * Parse a subscript expression
5300 */
5301 CTcPrsNode *CTcPrsOpUnary::parse_subscript(CTcPrsNode *lhs)
5302 {
5303 /* skip the '[' */
5304 G_tok->next();
5305
5306 /* parse the expression within the brackets */
5307 CTcPrsNode *subscript = S_op_comma.parse();
5308 if (subscript == 0)
5309 return 0;
5310
5311 /* check for the matching ']' */
5312 if (G_tok->cur() == TOKT_RBRACK)
5313 {
5314 /* got it - skip it */
5315 G_tok->next();
5316 }
5317 else
5318 {
5319 /* log an error, and forgive the missing ']' */
5320 G_tok->log_error_curtok(TCERR_EXPECTED_SUB_RBRACK);
5321 }
5322
5323 /* try folding constants */
5324 CTcPrsNode *cval = eval_const_subscript(lhs, subscript);
5325
5326 /*
5327 * if that worked, use the result; otherwise, build an expression
5328 * node to generate code for the subscript operator
5329 */
5330 if (cval != 0)
5331 return cval;
5332 else
5333 return new CTPNSubscript(lhs, subscript);
5334 }
5335
5336 /*
5337 * Evaluate a constant subscript value
5338 */
5339 CTcPrsNode *CTcPrsOpUnary::eval_const_subscript(
5340 CTcPrsNode *lhs, CTcPrsNode *subscript)
5341 {
5342 /* assume we won't be able to evaluate this as a constant */
5343 CTcPrsNode *c = 0;
5344
5345 /*
5346 * if we're subscripting a constant list by a constant index value,
5347 * we can evaluate a constant result
5348 */
5349 if (lhs->is_const() && subscript->is_const())
5350 {
5351 /* check the type of value we're indexing */
5352 switch (lhs->get_const_val()->get_type())
5353 {
5354 case TC_CVT_LIST:
5355 /*
5356 * It's a constant list. Lists can only be indexed by integer
5357 * values.
5358 */
5359 if (subscript->get_const_val()->get_type() == TC_CVT_INT)
5360 {
5361 /*
5362 * it's an integer - index the constant list by the
5363 * constant subscript to get the element value, which
5364 * replaces the entire list-and-index expression
5365 */
5366 c = lhs->get_const_val()->get_val_list()->get_const_ele(
5367 subscript->get_const_val()->get_val_int());
5368 }
5369 else
5370 {
5371 /* a list index must be an integer */
5372 G_tok->log_error(TCERR_CONST_IDX_NOT_INT);
5373 }
5374 break;
5375
5376 case TC_CVT_SSTR:
5377 case TC_CVT_OBJ:
5378 case TC_CVT_FUNCPTR:
5379 case TC_CVT_ANONFUNCPTR:
5380 case TC_CVT_FLOAT:
5381 /*
5382 * these types don't define indexing as a native operator, but
5383 * it's possible for this to be meaningful at run-time via
5384 * operator overloading; simply leave the constant expression
5385 * unevaluated so that we generate code to perform the index
5386 * operation at run-time
5387 */
5388 break;
5389
5390 default:
5391 /* other types definitely cannot be indexed */
5392 G_tok->log_error(TCERR_CONST_IDX_INV_TYPE);
5393 break;
5394 }
5395 }
5396
5397 /* return the constant result, if any */
5398 return c;
5399 }
5400
5401 /*
5402 * Parse a member selection ('.') expression. If no '.' is actually
5403 * present, then '.targetprop' is implied.
5404 */
5405 CTcPrsNode *CTcPrsOpUnary::parse_member(CTcPrsNode *lhs)
5406 {
5407 CTcPrsNode *rhs;
5408 int rhs_is_expr;
5409
5410 /*
5411 * If a '.' is present, skip it; otherwise, '.targetprop' is implied.
5412 */
5413 if (G_tok->cur() == TOKT_DOT)
5414 {
5415 /* we have an explicit property expression - skip the '.' */
5416 G_tok->next();
5417
5418 /* assume the property will be a simple symbol, not an expression */
5419 rhs_is_expr = FALSE;
5420
5421 /* we could have a symbol or a parenthesized expression */
5422 switch(G_tok->cur())
5423 {
5424 case TOKT_SYM:
5425 /*
5426 * It's a simple property name - create a symbol node. Note
5427 * that we must explicitly create an unresolved symbol node,
5428 * since we want to ignore any local variable with the same
5429 * name and look only in the global symbol table for a
5430 * property; we must hence defer resolving the symbol until
5431 * code generation.
5432 */
5433 rhs = new CTPNSym(G_tok->getcur()->get_text(),
5434 G_tok->getcur()->get_text_len());
5435
5436 /* skip the symbol token */
5437 G_tok->next();
5438
5439 /* proceed to check for an argument list */
5440 break;
5441
5442 case TOKT_LPAR:
5443 /*
5444 * It's a parenthesized expression - parse it. First, skip
5445 * the open paren - we don't want the sub-expression to go
5446 * beyond the close paren (if we didn't skip the open paren,
5447 * the open paren would be part of the sub-expression, hence
5448 * any postfix expression after the close paren would be
5449 * considered part of the sub-expression; this would be
5450 * invalid, since we might want to find a postfix actual
5451 * parameter list).
5452 */
5453 G_tok->next();
5454
5455 /* remember that it's an expression */
5456 rhs_is_expr = TRUE;
5457
5458 /* parse the sub-expression */
5459 rhs = S_op_comma.parse();
5460 if (rhs == 0)
5461 return 0;
5462
5463 /* require the close paren */
5464 if (G_tok->cur() == TOKT_RPAR)
5465 {
5466 /* skip the closing paren */
5467 G_tok->next();
5468 }
5469 else
5470 {
5471 /* log the error */
5472 G_tok->log_error_curtok(TCERR_EXPR_MISSING_RPAR);
5473
5474 /*
5475 * if we're at a semicolon or end of file, we must be on
5476 * to the next statement - stop trying to parse this one
5477 * if so; otherwise, continue on the assumption that they
5478 * merely left out the close paren and what follows is
5479 * more expression for us to process
5480 */
5481 if (G_tok->cur() == TOKT_SEM || G_tok->cur() == TOKT_EOF)
5482 return lhs;
5483 }
5484 break;
5485
5486 case TOKT_TARGETPROP:
5487 /*
5488 * it's an unparenthesized "targetprop" expression - skip the
5489 * keyword
5490 */
5491 G_tok->next();
5492
5493 /*
5494 * the property value is the result of evaluating
5495 * "targetprop", which is an expression
5496 */
5497 rhs = new CTPNTargetprop();
5498 rhs_is_expr = TRUE;
5499
5500 /* note the reference to the extended method context */
5501 G_prs->set_full_method_ctx_referenced(TRUE);
5502
5503 /* go parse the rest */
5504 break;
5505
5506 default:
5507 /* anything else is invalid - log an error */
5508 G_tok->log_error_curtok(TCERR_INVALID_PROP_EXPR);
5509
5510 /* skip the errant token so we don't loop on it */
5511 G_tok->next();
5512
5513 /* return what we have so far */
5514 return lhs;
5515 }
5516 }
5517 else
5518 {
5519 /* there's no property specified, so '.targetprop' is implied */
5520 rhs = new CTPNTargetprop();
5521 rhs_is_expr = TRUE;
5522
5523 /*
5524 * note the reference to the full method context (since
5525 * 'targetprop' is part of the extended method context beyond
5526 * 'self')
5527 */
5528 G_prs->set_full_method_ctx_referenced(TRUE);
5529 }
5530
5531 /* check for an argument list */
5532 if (G_tok->cur() == TOKT_LPAR)
5533 {
5534 CTPNArglist *arglist;
5535
5536 /* parse the argument list */
5537 arglist = parse_arg_list();
5538 if (arglist == 0)
5539 return 0;
5540
5541 /* create and return a member-with-arguments node */
5542 return new CTPNMemArg(lhs, rhs, rhs_is_expr, arglist);
5543 }
5544 else
5545 {
5546 /*
5547 * there's no argument list - create and return a simple member
5548 * node
5549 */
5550 return new CTPNMember(lhs, rhs, rhs_is_expr);
5551 }
5552 }
5553
5554 /*
5555 * Parse a primary expression
5556 */
5557 CTcPrsNode *CTcPrsOpUnary::parse_primary()
5558 {
5559 CTcPrsNode *sub;
5560 CTcConstVal cval;
5561 tc_toktyp_t t;
5562 CTcToken tok, tok2;
5563
5564 /* keep going until we find something interesting */
5565 for (;;)
5566 {
5567 /* determine what we have */
5568 switch(G_tok->cur())
5569 {
5570 case TOKT_LBRACE:
5571 /* short form of anonymous function */
5572 return parse_anon_func(TRUE, FALSE);
5573
5574 case TOKT_METHOD:
5575 /* parse an anonymous method */
5576 return parse_anon_func(FALSE, TRUE);
5577
5578 case TOKT_FUNCTION:
5579 /* parse an anonymous function */
5580 return parse_anon_func(FALSE, FALSE);
5581
5582 case TOKT_OBJECT:
5583 /* in-line object definition */
5584 return parse_inline_object(FALSE);
5585
5586 case TOKT_NEW:
5587 /* skip the operator and check for 'function' or 'method' */
5588 if ((t = G_tok->next()) == TOKT_FUNCTION)
5589 {
5590 /* it's an anonymous function definition - go parse it */
5591 sub = parse_anon_func(FALSE, FALSE);
5592 }
5593 else if (t == TOKT_METHOD)
5594 {
5595 /* anonymous method */
5596 sub = parse_anon_func(FALSE, TRUE);
5597 }
5598 else
5599 {
5600 /* check for the 'transient' keyword */
5601 int trans = (G_tok->cur() == TOKT_TRANSIENT);
5602 if (trans)
5603 G_tok->next();
5604
5605 /*
5606 * it's an ordinary 'new' expression - parse the primary
5607 * making up the name
5608 */
5609 sub = parse_primary();
5610
5611 /* if there's an argument list, parse the argument list */
5612 if (G_tok->cur() == TOKT_LPAR)
5613 sub = parse_call(sub);
5614
5615 /* create the 'new' node */
5616 sub = parse_new(sub, trans);
5617 }
5618 return sub;
5619
5620 case TOKT_LPAR:
5621 /* left parenthesis - skip it */
5622 G_tok->next();
5623
5624 /* parse the expression */
5625 sub = S_op_comma.parse();
5626 if (sub == 0)
5627 return 0;
5628
5629 /* require the matching right parenthesis */
5630 if (G_tok->cur() == TOKT_RPAR)
5631 {
5632 /* skip the right paren */
5633 G_tok->next();
5634 }
5635 else
5636 {
5637 /*
5638 * log an error; assume that the paren is simply
5639 * missing, so continue with our work
5640 */
5641 G_tok->log_error_curtok(TCERR_EXPR_MISSING_RPAR);
5642 }
5643
5644 /* return the parenthesized expression */
5645 return sub;
5646
5647 case TOKT_NIL:
5648 /* nil - the result is the constant value nil */
5649 cval.set_nil();
5650
5651 return_constant:
5652 /* skip the token */
5653 G_tok->next();
5654
5655 /* return a constant node */
5656 return new CTPNConst(&cval);
5657
5658 case TOKT_TRUE:
5659 /* true - the result is the constant value true */
5660 cval.set_true();
5661 goto return_constant;
5662
5663 case TOKT_INT:
5664 /* integer constant value */
5665 cval.set_int(G_tok->getcur()->get_int_val());
5666 goto return_constant;
5667
5668 case TOKT_FLOAT:
5669 /* floating point constant value */
5670 cval.set_float(G_tok->getcur()->get_text(),
5671 G_tok->getcur()->get_text_len(),
5672 FALSE);
5673 goto return_constant;
5674
5675 case TOKT_BIGINT:
5676 /* an integer constant promoted to float due to overflow */
5677 cval.set_float(G_tok->getcur()->get_text(),
5678 G_tok->getcur()->get_text_len(),
5679 TRUE);
5680 goto return_constant;
5681
5682 case TOKT_SSTR:
5683 handle_sstring:
5684 /* single-quoted string - the result is a constant string value */
5685 cval.set_sstr(G_tok->getcur());
5686 goto return_constant;
5687
5688 case TOKT_DSTR:
5689 /*
5690 * if we're in preprocessor expression mode, treat this the
5691 * same as a single-quoted string
5692 */
5693 if (G_prs->get_pp_expr_mode())
5694 goto handle_sstring;
5695
5696 /*
5697 * a string implicitly references 'self', because we could run
5698 * through the default output method on the current object
5699 */
5700 G_prs->set_self_referenced(TRUE);
5701
5702 /* build a double-quoted string node */
5703 sub = new CTPNDstr(G_tok->getcur()->get_text(),
5704 G_tok->getcur()->get_text_len());
5705
5706 /* skip the string */
5707 G_tok->next();
5708
5709 /* return the new node */
5710 return sub;
5711
5712 case TOKT_RESTR:
5713 /* regular expression string */
5714 cval.set_restr(G_tok->getcur());
5715 goto return_constant;
5716
5717 case TOKT_DSTR_START:
5718 /* a string implicitly references 'self' */
5719 G_prs->set_self_referenced(TRUE);
5720
5721 /* parse the embedding expression */
5722 {
5723 CTcEmbedBuilderDbl builder;
5724 return parse_embedding(&builder);
5725 }
5726
5727 case TOKT_SSTR_START:
5728 /* parse the embedded expression */
5729 {
5730 CTcEmbedBuilderSgl builder;
5731 return parse_embedding(&builder);
5732 }
5733
5734 case TOKT_LBRACK:
5735 /* parse the list */
5736 return parse_list();
5737
5738 case TOKT_SYM:
5739 /*
5740 * symbol - the meaning of the symbol is not yet known, so
5741 * create an unresolved symbol node
5742 */
5743 sub = G_prs->create_sym_node(G_tok->getcur()->get_text(),
5744 G_tok->getcur()->get_text_len());
5745
5746 /* skip the symbol token */
5747 G_tok->next();
5748
5749 /* return the new node */
5750 return sub;
5751
5752 case TOKT_SELF:
5753 /* note the explicit self-reference */
5754 G_prs->set_self_referenced(TRUE);
5755
5756 /* generate the "self" node */
5757 G_tok->next();
5758 return new CTPNSelf();
5759
5760 case TOKT_REPLACED:
5761 /* generate the "replaced" node */
5762 G_tok->next();
5763 return new CTPNReplaced();
5764
5765 case TOKT_TARGETPROP:
5766 /* note the explicit extended method context reference */
5767 G_prs->set_full_method_ctx_referenced(TRUE);
5768
5769 /* generate the "targetprop" node */
5770 G_tok->next();
5771 return new CTPNTargetprop();
5772
5773 case TOKT_TARGETOBJ:
5774 /* note the explicit extended method context reference */
5775 G_prs->set_full_method_ctx_referenced(TRUE);
5776
5777 /* generate the "targetobj" node */
5778 G_tok->next();
5779 return new CTPNTargetobj();
5780
5781 case TOKT_DEFININGOBJ:
5782 /* note the explicit extended method context reference */
5783 G_prs->set_full_method_ctx_referenced(TRUE);
5784
5785 /* generate the "definingobj" node */
5786 G_tok->next();
5787 return new CTPNDefiningobj();
5788
5789 case TOKT_INVOKEE:
5790 /* generate the "invokee" node */
5791 G_tok->next();
5792 return new CTPNInvokee();
5793
5794 case TOKT_ARGCOUNT:
5795 /* generate the "argcount" node */
5796 G_tok->next();
5797 return new CTPNArgc();
5798
5799 case TOKT_INHERITED:
5800 /* parse the "inherited" operation */
5801 return parse_inherited();
5802
5803 case TOKT_DELEGATED:
5804 /* parse the "delegated" operation */
5805 return parse_delegated();
5806
5807 case TOKT_RPAR:
5808 /* extra right paren - log an error */
5809 G_tok->log_error(TCERR_EXTRA_RPAR);
5810
5811 /* skip it and go back for more */
5812 G_tok->next();
5813 break;
5814
5815 case TOKT_RBRACK:
5816 /* extra right square bracket - log an error */
5817 G_tok->log_error(TCERR_EXTRA_RBRACK);
5818
5819 /* skip it and go back for more */
5820 G_tok->next();
5821 break;
5822
5823 case TOKT_DSTR_MID:
5824 case TOKT_DSTR_END:
5825 case TOKT_SEM:
5826 case TOKT_RBRACE:
5827 /*
5828 * this looks like the end of the statement, but we expected
5829 * an operand - note the error and end the statement
5830 */
5831 G_tok->log_error_curtok(TCERR_EXPECTED_OPERAND);
5832
5833 /*
5834 * Synthesize a constant zero as the operand value. Do not
5835 * skip the current token, because it's almost certainly not
5836 * meant to be part of the expression; we want to stay put
5837 * so that the caller can resynchronize on this token.
5838 */
5839 cval.set_int(G_tok->getcur()->get_int_val());
5840 return new CTPNConst(&cval);
5841
5842 case TOKT_POUND:
5843 /*
5844 * When evaluating a debugger expression, we accept a special
5845 * notation for certain types that can't always be represented
5846 * in ordinary source code:
5847 *
5848 *. #__obj n - object number n (n is in decimal)
5849 *. #__prop n - property number n
5850 *. #__sstr ofs - s-string at offset ofs (in decimal)
5851 *. #__list ofs - list at offset ofs
5852 *. #__enum n - enum n
5853 *. #__bifptr s i - built-in function pointer, set s, index i
5854 *. #__invalid - invalid type
5855 */
5856 tok = *G_tok->copycur();
5857 if (G_prs->is_debug_expr()
5858 && G_tok->next() == TOKT_SYM
5859 && ((tok2 = *G_tok->copycur()).text_matches("__obj", 5)
5860 || tok2.text_matches("__obj", 5)
5861 || tok2.text_matches("__prop", 6)
5862 || tok2.text_matches("__sstr", 6)
5863 || tok2.text_matches("__list", 6)
5864 || tok2.text_matches("__func", 6)
5865 || tok2.text_matches("__enum", 6)
5866 || tok2.text_matches("__bifptr", 8)))
5867 {
5868 /* get the integer value */
5869 if (G_tok->next() == TOKT_INT)
5870 {
5871 /* get and skip the integer value */
5872 long i = G_tok->getcur()->get_int_val();
5873 G_tok->next();
5874
5875 /* check which symbol we have */
5876 if (tok2.text_matches("__obj", 5))
5877 {
5878 /* generate an object expression */
5879 cval.set_obj(i, TC_META_UNKNOWN);
5880 return new CTPNDebugConst(&cval);
5881 }
5882 else if (tok2.text_matches("__prop", 6))
5883 {
5884 /* generate a property expression */
5885 cval.set_prop(i);
5886 return new CTPNDebugConst(&cval);
5887 }
5888 else if (tok2.text_matches("__sstr", 6))
5889 {
5890 /* generate a constant-pool string expression */
5891 cval.set_sstr(i);
5892 return new CTPNDebugConst(&cval);
5893 }
5894 else if (tok2.text_matches("__list", 6))
5895 {
5896 /* generate a constant-pool list expression */
5897 cval.set_list(i);
5898 return new CTPNDebugConst(&cval);
5899 }
5900 else if (tok2.text_matches("__func", 6))
5901 {
5902 /* generate a fake symbol for the function */
5903 CTcSymFunc *sym = new CTcSymFunc(
5904 ".anon", 5, FALSE, 0, 0, FALSE, FALSE,
5905 FALSE, FALSE, FALSE, TRUE);
5906
5907 /* set the absolute address */
5908 sym->set_abs_addr(i);
5909
5910 /* generate a code-pool function pointer expression */
5911 cval.set_funcptr(sym);
5912 return new CTPNDebugConst(&cval);
5913 }
5914 else if (tok2.text_matches("__enum", 6))
5915 {
5916 /* generate an enum expression */
5917 cval.set_enum(i);
5918 return new CTPNDebugConst(&cval);
5919 }
5920 else if (tok2.text_matches("__bifptr", 8))
5921 {
5922 /* get and skip the function index token */
5923 long j = G_tok->getcur()->get_int_val();
5924 G_tok->next();
5925
5926 /* set up a fake symbol for the function */
5927 CTcSymBif *sym = new CTcSymBif(
5928 ".anon", 5, FALSE, (ushort)i, (ushort)j,
5929 FALSE, 0, 0, FALSE);
5930
5931 /* generate a built-in function pointer expression */
5932 cval.set_bifptr(sym);
5933 return new CTPNDebugConst(&cval);
5934 }
5935 }
5936 else
5937 {
5938 /* it's not a special sequence - put back the tokens */
5939 G_tok->unget(&tok2);
5940 G_tok->unget(&tok);
5941 }
5942 }
5943 else
5944 {
5945 /* it's not one of our symbols - put back the '#' */
5946 G_tok->unget(&tok);
5947 }
5948
5949 /*
5950 * if we got this far, we didn't get a valid special debugger
5951 * value - complain about the '#'
5952 */
5953 goto bad_primary;
5954
5955 default:
5956 bad_primary:
5957 /* invalid primary expression - log the error */
5958 G_tok->log_error_curtok(TCERR_BAD_PRIMARY_EXPR);
5959
5960 /*
5961 * Skip the token that's causing the problem; this will
5962 * ensure that we don't loop indefinitely trying to figure
5963 * out what this token is about, and return a constant zero
5964 * value as the primary.
5965 */
5966 G_tok->next();
5967
5968 /* synthesize a constant zero as the operand value */
5969 cval.set_int(G_tok->getcur()->get_int_val());
5970 goto return_constant;
5971 }
5972 }
5973 }
5974
5975 /*
5976 * Parse an "inherited" expression
5977 */
5978 CTcPrsNode *CTcPrsOpUnary::parse_inherited()
5979 {
5980 CTcPrsNode *lhs;
5981
5982 /* skip the "inherited" keyword and check what follows */
5983 switch(G_tok->next())
5984 {
5985 case TOKT_SYM:
5986 /*
5987 * it's an "inherited superclass..." expression - set up the
5988 * "inherited superclass" node
5989 */
5990 lhs = new CTPNInhClass(G_tok->getcur()->get_text(),
5991 G_tok->getcur()->get_text_len());
5992
5993 /* this passes method context information to the inheritor */
5994 G_prs->set_full_method_ctx_referenced(TRUE);
5995
5996 /* skip the superclass token */
5997 G_tok->next();
5998
5999 /* parse the member expression portion normally */
6000 break;
6001
6002 case TOKT_LT:
6003 /*
6004 * '<' - this is the start of a multi-method type list. Parse the
6005 * list: type1 ',' type2 ',' ... '>', then the argument list to the
6006 * 'inherited' call.
6007 */
6008 {
6009 /* create the formal type list */
6010 CTcFormalTypeList *tl = new (G_prsmem)CTcFormalTypeList();
6011
6012 /* skip the '<' */
6013 G_tok->next();
6014
6015 /* parse each list element */
6016 for (int done = FALSE ; !done ; )
6017 {
6018 switch (G_tok->cur())
6019 {
6020 case TOKT_GT:
6021 /* end of the list - skip the '>', and we're done */
6022 G_tok->next();
6023 done = TRUE;
6024 break;
6025
6026 case TOKT_ELLIPSIS:
6027 /* '...' */
6028 tl->add_ellipsis();
6029
6030 /* this has to be the end of the list */
6031 if (G_tok->next() == TOKT_GT)
6032 G_tok->next();
6033 else
6034 G_tok->log_error_curtok(TCERR_MMINH_MISSING_GT);
6035
6036 /* assume the list ends here in any case */
6037 done = TRUE;
6038 break;
6039
6040 case TOKT_SYM:
6041 /* a type token - add it to the list */
6042 tl->add_typed_param(G_tok->getcur());
6043
6044 finish_type:
6045 /* skip the type token */
6046 switch (G_tok->next())
6047 {
6048 case TOKT_COMMA:
6049 /* another type follows */
6050 G_tok->next();
6051 break;
6052
6053 case TOKT_GT:
6054 G_tok->next();
6055 done = TRUE;
6056 break;
6057
6058 case TOKT_SYM:
6059 case TOKT_ELLIPSIS:
6060 case TOKT_TIMES:
6061 /* probably just a missing comma */
6062 G_tok->log_error_curtok(TCERR_MMINH_MISSING_COMMA);
6063 break;
6064
6065 default:
6066 /* anything else is an error */
6067 G_tok->log_error_curtok(TCERR_MMINH_MISSING_COMMA);
6068 G_tok->next();
6069 break;
6070 }
6071 break;
6072
6073 case TOKT_TIMES:
6074 /* '*' indicates an untyped parameter */
6075 tl->add_untyped_param();
6076 goto finish_type;
6077
6078 case TOKT_LPAR:
6079 /* probably a missing '>' */
6080 G_tok->log_error_curtok(TCERR_MMINH_MISSING_GT);
6081 done = TRUE;
6082 break;
6083
6084 case TOKT_COMMA:
6085 /* probably a missing type */
6086 G_tok->log_error_curtok(TCERR_MMINH_MISSING_ARG_TYPE);
6087 G_tok->next();
6088 break;
6089
6090 case TOKT_SEM:
6091 case TOKT_RPAR:
6092 case TOKT_EOF:
6093 /* all of these indicate a premature end of the list */
6094 G_tok->log_error_curtok(TCERR_MMINH_MISSING_ARG_TYPE);
6095 return 0;
6096
6097 default:
6098 /* anything else is an error */
6099 G_tok->log_error_curtok(TCERR_MMINH_MISSING_ARG_TYPE);
6100 G_prs->skip_to_sem();
6101 return 0;
6102 }
6103 }
6104
6105 /* the left-hand side is an "inherited" node, with the arg list */
6106 lhs = new CTPNInh();
6107 ((CTPNInh *)lhs)->set_typelist(tl);
6108
6109 /* an inherited<> expression must have an argument list */
6110 if (G_tok->cur() != TOKT_LPAR)
6111 {
6112 G_tok->log_error_curtok(TCERR_MMINH_MISSING_ARG_LIST);
6113 G_prs->skip_to_sem();
6114 return 0;
6115 }
6116 }
6117 break;
6118
6119 default:
6120 /*
6121 * There's no explicit superclass name listed, so the left-hand
6122 * side of the '.' expression is the simple "inherited" node.
6123 */
6124 lhs = new CTPNInh();
6125
6126 /*
6127 * Since we don't have an explicit superclass, we'll need the
6128 * method context at run-time to establish the next class in
6129 * inheritance order. Flag the need for the full method context.
6130 */
6131 G_prs->set_full_method_ctx_referenced(TRUE);
6132
6133 /* parse the member expression portion normally */
6134 break;
6135 }
6136
6137 /* parse and return the member expression */
6138 return parse_member(lhs);
6139 }
6140
6141 /*
6142 * Parse a "delegated" expression
6143 */
6144 CTcPrsNode *CTcPrsOpUnary::parse_delegated()
6145 {
6146 /* 'delegated' always references 'self' */
6147 G_prs->set_self_referenced(TRUE);
6148
6149 /* skip the "delegated" keyword */
6150 G_tok->next();
6151
6152 /*
6153 * Parse a postfix expression giving the delegatee. Don't allow
6154 * nested member subexpressions (unless they're enclosed in
6155 * parentheses, of course) - our implicit '.' postfix takes
6156 * precedence. Also, don't allow call subexpressions (unless enclosed
6157 * in parens), since a postfix argument list binds to the 'delegated'
6158 * expression, not to a subexpression involving a function/method
6159 * call.
6160 */
6161 CTcPrsNode *target = parse_postfix(FALSE, FALSE);
6162
6163 /* set up the "delegated" node */
6164 CTcPrsNode *lhs = new CTPNDelegated(target);
6165
6166 /* return the rest as a normal member expression */
6167 return parse_member(lhs);
6168 }
6169
6170 /*
6171 * Parse a list
6172 */
6173 CTcPrsNode *CTcPrsOpUnary::parse_list()
6174 {
6175 /* assume this isn't a lookup table (with "key->val" pairs) */
6176 int is_lookup_table = FALSE;
6177
6178 /* we're not at the default value for a lookup table ("*->val") */
6179 int at_def_val = FALSE;
6180
6181 /* set up a nil value for adding placeholders (for error recovery) */
6182 CTcConstVal nilval;
6183 nilval.set_nil();
6184
6185 /* skip the opening '[' */
6186 G_tok->next();
6187
6188 /*
6189 * create the list expression -- we'll add elements to the list as
6190 * we parse the elements
6191 */
6192 CTPNList *lst = new CTPNList();
6193
6194 /* scan all list elements */
6195 for (;;)
6196 {
6197 /* check what we have */
6198 switch(G_tok->cur())
6199 {
6200 case TOKT_RBRACK:
6201 /*
6202 * that's the end of the list - skip the closing bracket and
6203 * return the finished list
6204 */
6205 G_tok->next();
6206 goto done;
6207
6208 case TOKT_EOF:
6209 case TOKT_RBRACE:
6210 case TOKT_SEM:
6211 case TOKT_DSTR_MID:
6212 case TOKT_DSTR_END:
6213 /*
6214 * these would all seem to imply that the closing ']' was
6215 * missing from the list; flag the error and end the list
6216 * now
6217 */
6218 G_tok->log_error_curtok(TCERR_LIST_MISSING_RBRACK);
6219 goto done;
6220
6221 case TOKT_RPAR:
6222 /*
6223 * extra right paren - log an error, but then skip the paren
6224 * and try to keep parsing
6225 */
6226 G_tok->log_error(TCERR_LIST_EXTRA_RPAR);
6227 G_tok->next();
6228 break;
6229
6230 case TOKT_TIMES:
6231 /*
6232 * If a -> follows, this is the default value for a lookup
6233 * table list.
6234 */
6235 if (G_tok->next() == TOKT_ARROW)
6236 {
6237 /* skip the arrow and get to the value */
6238 G_tok->next();
6239
6240 /*
6241 * if this is a non-lookup table list with other entries,
6242 * this is an error
6243 */
6244 if (!is_lookup_table && lst->get_count() != 0)
6245 {
6246 /* log the error, but keep parsing the list */
6247 G_tok->log_error(TCERR_ARROW_IN_LIST, lst->get_count());
6248 }
6249 else
6250 {
6251 /* it's definitely a lookup list now */
6252 is_lookup_table = TRUE;
6253
6254 /* we're now on the default value */
6255 at_def_val = TRUE;
6256 }
6257 }
6258 else
6259 {
6260 /* it's not *-> - put back the next token */
6261 G_tok->unget();
6262 }
6263
6264 default:
6265 /* it must be the next element expression */
6266 break;
6267 }
6268
6269 /*
6270 * Attempt to parse another list element expression. Parse just
6271 * below a comma expression, because commas can be used to
6272 * separate list elements.
6273 */
6274 CTcPrsNode *ele = S_op_asi.parse();
6275 if (ele == 0)
6276 return 0;
6277
6278 /* add the element to the list */
6279 lst->add_element(ele);
6280
6281 /* if this was the default value, the list should end here */
6282 if (at_def_val && G_tok->cur() != TOKT_RBRACK)
6283 {
6284 /* log an error */
6285 G_tok->log_error_curtok(TCERR_LOOKUP_LIST_EXPECTED_END_AT_DEF);
6286
6287 /* we've left the default value */
6288 at_def_val = FALSE;
6289
6290 /*
6291 * if we're at a comma, add a nil value to the list to
6292 * resynchronize - they must want to add more Key->Value pairs
6293 */
6294 if (G_tok->cur() == TOKT_COMMA)
6295 lst->add_element(new CTPNConst(&nilval));
6296 }
6297
6298 /* check what follows the element */
6299 switch(G_tok->cur())
6300 {
6301 case TOKT_COMMA:
6302 /* skip the comma introducing the next element */
6303 G_tok->next();
6304
6305 /*
6306 * If this is a lookup table list, commas are only allowed at
6307 * even elements: [ODD -> EVEN, ODD -> EVEN...].
6308 */
6309 if (is_lookup_table && (lst->get_count() & 1) != 0)
6310 {
6311 /* log an error */
6312 G_tok->log_error(TCERR_LOOKUP_LIST_EXPECTED_ARROW,
6313 (lst->get_count()+1)/2);
6314
6315 /*
6316 * Add an implied nil element as the value. This will help
6317 * resynchronize with the source code in the most likely
6318 * case that they simply left out a ->value item, so that
6319 * we don't log alternating "expected comma" and "expected
6320 * arrow" messages on every subsequent delimiter.
6321 */
6322 lst->add_element(new CTPNConst(&nilval));
6323 }
6324
6325 /* if a close bracket follows, we seem to have an extra comma */
6326 if (G_tok->cur() == TOKT_RBRACK)
6327 {
6328 /*
6329 * log an error about the missing element, then end the
6330 * list here
6331 */
6332 G_tok->log_error_curtok(TCERR_LIST_EXPECT_ELEMENT);
6333 goto done;
6334 }
6335 break;
6336
6337 case TOKT_ARROW:
6338 /* skip the arrow */
6339 G_tok->next();
6340
6341 /*
6342 * '->' indicates a lookup table key->value list. This is an
6343 * all-or-nothing proposition: it has to be on every pair of
6344 * elements, or on none of them.
6345 */
6346 if (lst->get_count() == 1)
6347 {
6348 /* first element: this is now a lookup table list */
6349 is_lookup_table = TRUE;
6350 }
6351 else if (!is_lookup_table)
6352 {
6353 /*
6354 * it's not the first element, and we haven't seen arrows
6355 * before, so this list shouldn't have arrows at all
6356 */
6357 G_tok->log_error(TCERR_ARROW_IN_LIST, lst->get_count());
6358 }
6359 else if (is_lookup_table && (lst->get_count() & 1) == 0)
6360 {
6361 /*
6362 * We have an even number of elements, so an arrow is not
6363 * allowed here under any circumstances.
6364 */
6365 G_tok->log_error(TCERR_MISPLACED_ARROW_IN_LIST,
6366 lst->get_count()/2);
6367
6368 /*
6369 * They probably just left out the key value accidentally,
6370 * so add a nil value as the key. This will avoid a
6371 * cascade of errors for subsequent delimiters if they did
6372 * just leave out one item.
6373 */
6374 lst->add_element(new CTPNConst(&nilval));
6375 }
6376 break;
6377
6378 case TOKT_RBRACK:
6379 /*
6380 * we're done with the list - skip the bracket and return
6381 * the finished list
6382 */
6383 G_tok->next();
6384
6385 /*
6386 * If this is a lookup table list, make sure we ended on an
6387 * even number - if not, we're missing a ->Value entry. The
6388 * exception is that if the last value was a default, we end on
6389 * an odd item.
6390 */
6391 if (is_lookup_table
6392 && (lst->get_count() & 1) != 0
6393 && !at_def_val)
6394 {
6395 /* log the error */
6396 G_tok->log_error(TCERR_LOOKUP_LIST_EXPECTED_ARROW,
6397 (lst->get_count()+1)/2);
6398 }
6399 goto done;
6400
6401 case TOKT_EOF:
6402 case TOKT_LBRACE:
6403 case TOKT_RBRACE:
6404 case TOKT_SEM:
6405 case TOKT_DSTR_MID:
6406 case TOKT_DSTR_END:
6407 /*
6408 * these would all seem to imply that the closing ']' was
6409 * missing from the list; flag the error and end the list
6410 * now
6411 */
6412 G_tok->log_error_curtok(TCERR_LIST_MISSING_RBRACK);
6413 goto done;
6414
6415 default:
6416 /*
6417 * Anything else is an error - note that we expected a
6418 * comma, then proceed with parsing from the current token
6419 * as though we had found the comma (in all likelihood, the
6420 * comma was accidentally omitted). If we've reached the
6421 * end of the file, return what we have so far, since it's
6422 * pointless to keep looping.
6423 */
6424 G_tok->log_error_curtok(TCERR_LIST_EXPECT_COMMA);
6425
6426 /* give up on end of file, otherwise keep going */
6427 if (G_tok->cur() == TOKT_EOF)
6428 goto done;
6429 break;
6430 }
6431 }
6432
6433 done:
6434 /* tell the parser to note this list, in case it's the longest yet */
6435 G_cg->note_list(lst->get_count());
6436
6437 /* if it's a lookup table list, mark it as such */
6438 if (is_lookup_table)
6439 lst->set_lookup_table();
6440
6441 /* return the list */
6442 return lst;
6443 }
6444
6445
6446 /* ------------------------------------------------------------------------ */
6447 /*
6448 * Parse Allocation Object
6449 */
6450
6451 /*
6452 * memory allocator for parse nodes
6453 */
6454 void *CTcPrsAllocObj::operator new(size_t siz)
6455 {
6456 /* allocate the space out of the node pool */
6457 return G_prsmem->alloc(siz);
6458 }
6459
6460
6461 /* ------------------------------------------------------------------------ */
6462 /*
6463 * Parse Tree space manager
6464 */
6465
6466 /*
6467 * create
6468 */
6469 CTcPrsMem::CTcPrsMem()
6470 {
6471 /* we have no blocks yet */
6472 head_ = tail_ = 0;
6473
6474 /* allocate our first block */
6475 alloc_block();
6476 }
6477
6478 CTcPrsMem::~CTcPrsMem()
6479 {
6480 /* delete all objects in our pool */
6481 delete_all();
6482 }
6483
6484 /*
6485 * Save state, for later resetting
6486 */
6487 void CTcPrsMem::save_state(tcprsmem_state_t *state)
6488 {
6489 /* save the pool information in the state structure */
6490 state->tail = tail_;
6491 state->free_ptr = free_ptr_;
6492 state->rem = rem_;
6493 }
6494
6495 /*
6496 * Reset to initial state
6497 */
6498 void CTcPrsMem::reset()
6499 {
6500 /* delete all blocks */
6501 delete_all();
6502
6503 /* re-allocate the initial block */
6504 alloc_block();
6505
6506 /* fixups are allocated in parser memory, so they're gone now */
6507 G_objfixup = 0;
6508 G_propfixup = 0;
6509 G_enumfixup = 0;
6510 }
6511
6512 /*
6513 * Reset. This deletes all objects allocated out of the parser pool
6514 * since the state was saved.
6515 */
6516 void CTcPrsMem::reset(const tcprsmem_state_t *state)
6517 {
6518 tcprsmem_blk_t *cur;
6519
6520 /*
6521 * delete all of the blocks that were allocated after the last block
6522 * that existed when the state was saved
6523 */
6524 for (cur = state->tail->next_ ; cur != 0 ; )
6525 {
6526 tcprsmem_blk_t *nxt;
6527
6528 /* remember the next block */
6529 nxt = cur->next_;
6530
6531 /* delete this block */
6532 t3free(cur);
6533
6534 /* move on to the next one */
6535 cur = nxt;
6536 }
6537
6538 /* re-establish the saved last block */
6539 tail_ = state->tail;
6540
6541 /* make sure the list is terminated at the last block */
6542 tail_->next_ = 0;
6543
6544 /* re-establish the saved allocation point in the last block */
6545 free_ptr_ = state->free_ptr;
6546 rem_ = state->rem;
6547 }
6548
6549 /*
6550 * Delete all parser memory. This deletes all objects allocated out of
6551 * parser memory, so the caller must be sure that all of these objects
6552 * are unreferenced.
6553 */
6554 void CTcPrsMem::delete_all()
6555 {
6556 /* free all blocks */
6557 while (head_ != 0)
6558 {
6559 tcprsmem_blk_t *nxt;
6560
6561 /* remember the next block after this one */
6562 nxt = head_->next_;
6563
6564 /* free this block */
6565 t3free(head_);
6566
6567 /* move on to the next one */
6568 head_ = nxt;
6569 }
6570
6571 /* there's no tail now */
6572 tail_ = 0;
6573 }
6574
6575 /*
6576 * allocate a block
6577 */
6578 void CTcPrsMem::alloc_block()
6579 {
6580 tcprsmem_blk_t *blk;
6581
6582 /*
6583 * block size - pick a size that's large enough that we won't be
6584 * unduly inefficient (in terms of having tons of blocks), but still
6585 * friendly to 16-bit platforms (i.e., under 64k)
6586 */
6587 const size_t BLOCK_SIZE = 65000;
6588
6589 /* allocate space for the block */
6590 blk = (tcprsmem_blk_t *)t3malloc(sizeof(tcprsmem_blk_t) + BLOCK_SIZE - 1);
6591
6592 /* if that failed, throw an error */
6593 if (blk == 0)
6594 err_throw(TCERR_NO_MEM_PRS_TREE);
6595
6596 /* link in the block at the end of our list */
6597 blk->next_ = 0;
6598 if (tail_ != 0)
6599 tail_->next_ = blk;
6600 else
6601 head_ = blk;
6602
6603 /* the block is now the last block in the list */
6604 tail_ = blk;
6605
6606 /*
6607 * Set up to allocate out of our block. Make sure the free pointer
6608 * starts out on a worst-case alignment boundary; normally, the C++
6609 * compiler will properly align our "buf_" structure member on a
6610 * worst-case boundary, so this calculation won't actually change
6611 * anything, but this will help ensure portability even to weird
6612 * compilers.
6613 */
6614 free_ptr_ = (char *)osrndpt((unsigned char *)blk->buf_);
6615
6616 /*
6617 * get the amount of space remaining in the block (in the unlikely
6618 * event that worst-case alignment actually moved the free pointer
6619 * above the start of the buffer, we'll have lost a little space in
6620 * the buffer for the alignment offset)
6621 */
6622 rem_ = BLOCK_SIZE - (free_ptr_ - blk->buf_);
6623 }
6624
6625 /*
6626 * Allocate space
6627 */
6628 void *CTcPrsMem::alloc(size_t siz)
6629 {
6630 char *ret;
6631 size_t space_used;
6632
6633 /* if there's not enough space available, allocate a new block */
6634 if (siz > rem_)
6635 {
6636 /* allocate a new block */
6637 alloc_block();
6638
6639 /*
6640 * if there's still not enough room, the request must exceed the
6641 * largest block we can allocate
6642 */
6643 if (siz > rem_)
6644 G_tok->throw_internal_error(TCERR_PRS_BLK_TOO_BIG, (ulong)siz);
6645 }
6646
6647 /* return the free pointer */
6648 ret = free_ptr_;
6649
6650 /* advance the free pointer past the space, rounding for alignment */
6651 free_ptr_ = (char *)osrndpt((unsigned char *)free_ptr_ + siz);
6652
6653 /* deduct the amount of space we consumed from the available space */
6654 space_used = free_ptr_ - ret;
6655 if (space_used > rem_)
6656 rem_ = 0;
6657 else
6658 rem_ -= space_used;
6659
6660 /* return the allocated space */
6661 return ret;
6662 }
6663
6664 /* ------------------------------------------------------------------------ */
6665 /*
6666 * parse node base class
6667 */
6668
6669 /*
6670 * Make adjustments for dynamic evaluation
6671 */
6672 CTcPrsNode *CTcPrsNodeBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
6673 {
6674 /* by default, a node can't be used in dynamic evaluation */
6675 err_throw(VMERR_INVAL_DBG_EXPR);
6676 AFTER_ERR_THROW(return 0;)
6677 }
6678
6679
6680 /* ------------------------------------------------------------------------ */
6681 /*
6682 * constant node
6683 */
6684
6685 /*
6686 * adjust for debugger use
6687 */
6688 CTcPrsNode *CTPNConstBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
6689 {
6690 /* convert to a debugger-constant */
6691 return new CTPNDebugConst(&val_);
6692 }
6693
6694
6695 /* ------------------------------------------------------------------------ */
6696 /*
6697 * List parse node
6698 */
6699
6700 /*
6701 * add an element to a list
6702 */
6703 void CTPNListBase::add_element(CTcPrsNode *expr)
6704 {
6705 CTPNListEle *ele;
6706
6707 /* create a list element object for the new element */
6708 ele = new CTPNListEle(expr);
6709
6710 /* count the new entry */
6711 ++cnt_;
6712
6713 /* add the element to our linked list */
6714 ele->set_prev(tail_);
6715 if (tail_ != 0)
6716 tail_->set_next(ele);
6717 else
6718 head_ = ele;
6719 tail_ = ele;
6720
6721 /*
6722 * if the new element does not have a constant value, the list no
6723 * longer has a constant value (if it did before)
6724 */
6725 if (!expr->is_const())
6726 is_const_ = FALSE;
6727 }
6728
6729 /*
6730 * remove each occurrence of a given constant value from the list
6731 */
6732 void CTPNListBase::remove_element(const CTcConstVal *val)
6733 {
6734 CTPNListEle *cur;
6735
6736 /* scan the list */
6737 for (cur = head_ ; cur != 0 ; cur = cur->get_next())
6738 {
6739 /*
6740 * if this element is constant, compare it to the value to be
6741 * removed; if it matches, remove it
6742 */
6743 if (cur->get_expr()->is_const()
6744 && cur->get_expr()->get_const_val()->is_equal_to(val))
6745 {
6746 /* set the previous element's forward pointer */
6747 if (cur->get_prev() == 0)
6748 head_ = cur->get_next();
6749 else
6750 cur->get_prev()->set_next(cur->get_next());
6751
6752 /* set the next element's back pointer */
6753 if (cur->get_next() == 0)
6754 tail_ = cur->get_prev();
6755 else
6756 cur->get_next()->set_prev(cur->get_prev());
6757
6758 /* decrement our element counter */
6759 --cnt_;
6760 }
6761 }
6762 }
6763
6764 /*
6765 * Get the constant value of the element at the given index. Logs an
6766 * error and returns null if there's no such element.
6767 */
6768 CTcPrsNode *CTPNListBase::get_const_ele(int index)
6769 {
6770 CTPNListEle *ele;
6771
6772 /* if the index is negative, it's out of range */
6773 if (index < 1)
6774 {
6775 /* log the error and return failure */
6776 G_tok->log_error(TCERR_CONST_IDX_RANGE);
6777 return 0;
6778 }
6779
6780 /* scan the list for the given element */
6781 for (ele = head_ ; ele != 0 && index > 1 ;
6782 ele = ele->get_next(), --index) ;
6783
6784 /* if we ran out of elements, the index is out of range */
6785 if (ele == 0 || index != 1)
6786 {
6787 G_tok->log_error(TCERR_CONST_IDX_RANGE);
6788 return 0;
6789 }
6790
6791 /* return the element's constant value */
6792 return ele->get_expr();
6793 }
6794
6795 /*
6796 * Fold constants
6797 */
6798 CTcPrsNode *CTPNListBase::fold_constants(CTcPrsSymtab *symtab)
6799 {
6800 CTPNListEle *cur;
6801 int all_const;
6802
6803 /*
6804 * if the list is already constant, there's nothing extra we need to
6805 * do
6806 */
6807 if (is_const_)
6808 return this;
6809
6810 /* presume the result will be all constants */
6811 all_const = TRUE;
6812
6813 /* run through my list and fold each element */
6814 for (cur = head_ ; cur != 0 ; cur = cur->get_next())
6815 {
6816 /* fold this element */
6817 cur->fold_constants(symtab);
6818
6819 /*
6820 * if this element is not a constant, the whole list cannot be
6821 * constant
6822 */
6823 if (!cur->get_expr()->is_const())
6824 all_const = FALSE;
6825 }
6826
6827 /* if every element was a constant, the overall list is constant */
6828 if (all_const)
6829 is_const_ = TRUE;
6830
6831 /* return myself */
6832 return this;
6833 }
6834
6835 /*
6836 * Adjust for dynamic compilation
6837 */
6838 CTcPrsNode *CTPNListBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
6839 {
6840 CTPNListEle *cur;
6841
6842 /* run through my list and adjust each element */
6843 for (cur = head_ ; cur != 0 ; cur = cur->get_next())
6844 {
6845 /* adjust this element */
6846 cur->adjust_for_dyn(info);
6847 }
6848
6849 /*
6850 * force the list to be non-constant - in debugger mode, we have to
6851 * build the value we push as a dynamic object, never as an actual
6852 * constant, to ensure that the generated code can be deleted
6853 * immediately after being executed
6854 */
6855 is_const_ = FALSE;
6856
6857 /* return myself */
6858 return this;
6859 }
6860
6861 /* ------------------------------------------------------------------------ */
6862 /*
6863 * If-nil operator ?? node base class
6864 */
6865
6866 /*
6867 * fold constants
6868 */
6869 CTcPrsNode *CTPNIfnilBase::fold_constants(CTcPrsSymtab *symtab)
6870 {
6871 /* fold constants in the subnodes */
6872 first_ = first_->fold_constants(symtab);
6873 second_ = second_->fold_constants(symtab);
6874
6875 /*
6876 * if the first is now a constant, we can fold this entire expression
6877 * node by choosing the first or second node. Otherwise return myself
6878 * unchanged.
6879 */
6880 if (first_->is_const())
6881 {
6882 /*
6883 * if the first expression is nil, return the second, otherwise
6884 * return the first
6885 */
6886 return (first_->get_const_val()->get_type() == TC_CVT_NIL
6887 ? second_ : first_);
6888 }
6889 else
6890 {
6891 /* we can't fold this node any further - return it unchanged */
6892 return this;
6893 }
6894 }
6895
6896 /* ------------------------------------------------------------------------ */
6897 /*
6898 * conditional operator node base class
6899 */
6900
6901 /*
6902 * fold constants
6903 */
6904 CTcPrsNode *CTPNIfBase::fold_constants(CTcPrsSymtab *symtab)
6905 {
6906 /* fold constants in the subnodes */
6907 first_ = first_->fold_constants(symtab);
6908 second_ = second_->fold_constants(symtab);
6909 third_ = third_->fold_constants(symtab);
6910
6911 /*
6912 * if the first is now a constant, we can fold this entire
6913 * expression node by choosing the second or third based on its
6914 * value; otherwise, return myself unchanged
6915 */
6916 if (first_->is_const())
6917 {
6918 /*
6919 * The condition is a constant - the result is the 'then' or 'else'
6920 * part, based on the condition's value.
6921 */
6922 return (first_->get_const_val()->get_val_bool()
6923 ? second_ : third_);
6924 }
6925 else
6926 {
6927 /* we can't fold this node any further - return it unchanged */
6928 return this;
6929 }
6930 }
6931
6932
6933 /* ------------------------------------------------------------------------ */
6934 /*
6935 * Double-quoted string node - base class
6936 */
6937
6938 /*
6939 * create a double-quoted string node
6940 */
6941 CTPNDstrBase::CTPNDstrBase(const char *str, size_t len)
6942 {
6943 /* remember the string */
6944 str_ = str;
6945 len_ = len;
6946
6947 /*
6948 * note the length in the parser, in case it's the longest string
6949 * we've seen so far
6950 */
6951 G_cg->note_str(len);
6952 }
6953
6954 /*
6955 * adjust for dynamic (run-time) compilation
6956 */
6957 CTcPrsNode *CTPNDstrBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
6958 {
6959 /*
6960 * don't allow dstring evaluation in speculative mode, since we
6961 * can't execute anything with side effects in this mode
6962 */
6963 if (info->speculative)
6964 err_throw(VMERR_BAD_SPEC_EVAL);
6965
6966 /* return a debugger dstring node */
6967 return new CTPNDebugDstr(str_, len_);
6968 }
6969
6970 /* ------------------------------------------------------------------------ */
6971 /*
6972 * Address-of parse node
6973 */
6974
6975 /*
6976 * fold constants
6977 */
6978 CTcPrsNode *CTPNAddrBase::fold_constants(CTcPrsSymtab *symtab)
6979 {
6980 CTcPrsNode *ret;
6981
6982 /* ask the symbol to generate a constant expression for its address */
6983 ret = get_sub_expr()->fold_addr_const(symtab);
6984
6985 /*
6986 * if we got a constant value, return it; otherwise, return myself
6987 * unchanged
6988 */
6989 return (ret != 0 ? ret : this);
6990 }
6991
6992 /*
6993 * determine if my address equals that of another node
6994 */
6995 int CTPNAddrBase::is_addr_eq(const CTPNAddr *node, int *comparable) const
6996 {
6997 /*
6998 * If both sides are symbols, the addresses are equal if and only if
6999 * the symbols are identical. One symbol has exactly one meaning in
7000 * a given context, and no two symbols can have the same meaning.
7001 * (It's important that we be able to state this for all symbols,
7002 * because we can't necessarily know during parsing the meaning of a
7003 * given symbol, since the symbol could be a forward reference.)
7004 */
7005 if (get_sub_expr()->get_sym_text() != 0
7006 && node->get_sub_expr()->get_sym_text() != 0)
7007 {
7008 CTcPrsNode *sym1;
7009 CTcPrsNode *sym2;
7010
7011 /* they're both symbols, so they're comparable */
7012 *comparable = TRUE;
7013
7014 /* they're the same if both symbols have the same text */
7015 sym1 = get_sub_expr();
7016 sym2 = node->get_sub_expr();
7017 return (sym1->get_sym_text_len() == sym2->get_sym_text_len()
7018 && memcmp(sym1->get_sym_text(), sym2->get_sym_text(),
7019 sym1->get_sym_text_len()) == 0);
7020 }
7021
7022 /* they're not comparable */
7023 *comparable = FALSE;
7024 return FALSE;
7025 }
7026
7027 /* ------------------------------------------------------------------------ */
7028 /*
7029 * Symbol parse node base class
7030 */
7031
7032 /*
7033 * fold constants
7034 */
7035 CTcPrsNode *CTPNSymBase::fold_constants(CTcPrsSymtab *symtab)
7036 {
7037 CTcSymbol *sym;
7038 CTcPrsNode *ret;
7039
7040 /*
7041 * Look up my symbol. At this stage, don't assume a definition;
7042 * merely look to see if it's already known. We don't have enough
7043 * information to determine how we should define the symbol, so
7044 * leave it undefined until code generation if it's not already
7045 * known.
7046 */
7047 sym = symtab->find(get_sym_text(), get_sym_text_len());
7048 if (sym != 0)
7049 {
7050 /* ask the symbol to do the folding */
7051 ret = sym->fold_constant();
7052
7053 /* if that succeeded, return it; otherwise, return unchanged */
7054 return (ret != 0 ? ret : this);
7055 }
7056 else
7057 {
7058 /* not defined - return myself unchanged */
7059 return this;
7060 }
7061 }
7062
7063 /*
7064 * Fold my address to a constant node. If I have no address value, I'll
7065 * simply return myself unchanged. Note that it's an error if I have no
7066 * constant value, but we'll count on the code generator to report the
7067 * error, and simply ignore it for now.
7068 */
7069 CTcPrsNode *CTPNSymBase::fold_addr_const(CTcPrsSymtab *symtab)
7070 {
7071 CTcSymbol *sym;
7072
7073 /* look up my symbol; if we don't find it, don't define it */
7074 sym = symtab->find(get_sym_text(), get_sym_text_len());
7075 if (sym != 0)
7076 {
7077 /* we got a symbol - ask it to do the folding */
7078 return sym->fold_addr_const();
7079 }
7080 else
7081 {
7082 /* undefined symbol - there's no constant address value */
7083 return 0;
7084 }
7085 }
7086
7087 /*
7088 * Determine if I have a return value when called
7089 */
7090 int CTPNSymBase::has_return_value_on_call() const
7091 {
7092 CTcSymbol *sym;
7093
7094 /* try resolving my symbol */
7095 sym = G_prs->get_global_symtab()->find(sym_, len_);
7096
7097 /*
7098 * if we found a symbol, let it resolve the call; otherwise, assume
7099 * that we do have a return value
7100 */
7101 if (sym != 0)
7102 return sym->has_return_value_on_call();
7103 else
7104 return TRUE;
7105 }
7106
7107 /*
7108 * Determine if I am a valid lvalue
7109 */
7110 int CTPNSymBase::check_lvalue_resolved(class CTcPrsSymtab *symtab) const
7111 {
7112 CTcSymbol *sym;
7113
7114 /* look up the symbol in the given scope */
7115 sym = symtab->find(get_sym_text(), get_sym_text_len());
7116 if (sym != 0)
7117 {
7118 /* ask the symbol what it thinks */
7119 return sym->check_lvalue();
7120 }
7121 else
7122 {
7123 /* it's undefined - can't be an lvalue */
7124 return FALSE;
7125 }
7126 }
7127
7128 /*
7129 * adjust for dynamic (run-time) compilation
7130 */
7131 CTcPrsNode *CTPNSymBase::adjust_for_dyn(const tcpn_dyncomp_info *)
7132 {
7133 /*
7134 * If this symbol isn't defined in the global symbol table, we can't
7135 * evaluate this expression in the debugger - new symbols can never
7136 * be defined in the debugger, so there's no point in trying to hold
7137 * a forward reference as we normally would for an undefined symbol.
7138 * We need look only in the global symbol table because local
7139 * symbols will already have been resolved.
7140 */
7141 if (G_prs->get_global_symtab()->find(sym_, len_) == 0)
7142 {
7143 /* log the error, to generate an appropriate message */
7144 G_tok->log_error(TCERR_UNDEF_SYM, (int)len_, sym_);
7145
7146 /* throw the error as well */
7147 err_throw_a(TCERR_UNDEF_SYM, 2,
7148 ERR_TYPE_INT, (int)len_, ERR_TYPE_TEXTCHAR, sym_);
7149 }
7150
7151 /* return myself unchanged */
7152 return this;
7153 }
7154
7155
7156 /* ------------------------------------------------------------------------ */
7157 /*
7158 * Resolved Symbol parse node base class
7159 */
7160
7161 /*
7162 * fold constants
7163 */
7164 CTcPrsNode *CTPNSymResolvedBase::fold_constants(CTcPrsSymtab *symtab)
7165 {
7166 CTcPrsNode *ret;
7167
7168 /* ask the symbol to generate the folded constant value */
7169 ret = sym_->fold_constant();
7170
7171 /* if that succeeded, return it; otherwise, return myself unchanged */
7172 return (ret != 0 ? ret : this);
7173 }
7174
7175 /*
7176 * Fold my address to a constant node. If I have no address value, I'll
7177 * simply return myself unchanged. Note that it's an error if I have no
7178 * constant value, but we'll count on the code generator to report the
7179 * error, and simply ignore it for now.
7180 */
7181 CTcPrsNode *CTPNSymResolvedBase::fold_addr_const(CTcPrsSymtab *symtab)
7182 {
7183 /* ask my symbol to generate the folded constant value */
7184 return sym_->fold_addr_const();
7185 }
7186
7187
7188 /* ------------------------------------------------------------------------ */
7189 /*
7190 * Debugger local variable resolved symbol
7191 */
7192
7193 /*
7194 * construction
7195 */
7196 CTPNSymDebugLocalBase::CTPNSymDebugLocalBase(const tcprsdbg_sym_info *info)
7197 {
7198 /* save the type information */
7199 switch(info->sym_type)
7200 {
7201 case TC_SYM_LOCAL:
7202 var_id_ = info->var_id;
7203 ctx_arr_idx_ = info->ctx_arr_idx;
7204 frame_idx_ = info->frame_idx;
7205 is_param_ = FALSE;
7206 break;
7207
7208 case TC_SYM_PARAM:
7209 var_id_ = info->var_id;
7210 ctx_arr_idx_ = 0;
7211 frame_idx_ = info->frame_idx;
7212 is_param_ = TRUE;
7213 break;
7214
7215 default:
7216 /* other types are invalid */
7217 assert(FALSE);
7218 break;
7219 }
7220 }
7221
7222 /* ------------------------------------------------------------------------ */
7223 /*
7224 * Argument List parse node base class
7225 */
7226
7227 /*
7228 * fold constants
7229 */
7230 CTcPrsNode *CTPNArglistBase::fold_constants(CTcPrsSymtab *symtab)
7231 {
7232 /* fold each list element */
7233 CTPNArg *cur;
7234 for (cur = get_arg_list_head() ; cur != 0 ; cur = cur->get_next_arg())
7235 cur->fold_constants(symtab);
7236
7237 /* return myself with no further folding */
7238 return this;
7239 }
7240
7241 /*
7242 * adjust for dynamic (run-time) compilation
7243 */
7244 CTcPrsNode *CTPNArglistBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
7245 {
7246 /* adjust each argument list member */
7247 CTPNArg *arg;
7248 for (arg = list_ ; arg != 0 ; arg = arg->get_next_arg())
7249 {
7250 /*
7251 * adjust this argument; assume the argument node itself isn't
7252 * affected
7253 */
7254 arg->adjust_for_dyn(info);
7255 }
7256
7257 /* return myself otherwise unchanged */
7258 return this;
7259 }
7260
7261 /* ------------------------------------------------------------------------ */
7262 /*
7263 * Argument List Entry parse node base class
7264 */
7265
7266 /*
7267 * fold constants
7268 */
7269 CTcPrsNode *CTPNArgBase::fold_constants(CTcPrsSymtab *symtab)
7270 {
7271 /* fold my argument expression */
7272 arg_expr_ = arg_expr_->fold_constants(symtab);
7273
7274 /* return myself unchanged */
7275 return this;
7276 }
7277
7278 /*
7279 * Set the parameter name
7280 */
7281 void CTPNArgBase::set_name(const CTcToken *tok)
7282 {
7283 /* remember the name token */
7284 name_ = *tok;
7285 }
7286
7287 /* ------------------------------------------------------------------------ */
7288 /*
7289 * Member with no arguments
7290 */
7291
7292 /*
7293 * adjust for dynamic (run-time) compilation
7294 */
7295 CTcPrsNode *CTPNMemberBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
7296 {
7297 /* adjust the object and property expressions */
7298 obj_expr_ = obj_expr_->adjust_for_dyn(info);
7299 prop_expr_ = prop_expr_->adjust_for_dyn(info);
7300
7301 /* return myself otherwise unchanged */
7302 return this;
7303 }
7304
7305 /* ------------------------------------------------------------------------ */
7306 /*
7307 * Member with Arguments parse node base class
7308 */
7309
7310 /*
7311 * fold constants
7312 */
7313 CTcPrsNode *CTPNMemArgBase::fold_constants(CTcPrsSymtab *symtab)
7314 {
7315 /* fold constants in the object and property expressions */
7316 obj_expr_ = obj_expr_->fold_constants(symtab);
7317 prop_expr_ = prop_expr_->fold_constants(symtab);
7318
7319 /*
7320 * fold constants in the argument list; an argument list node never
7321 * changes to a new node type during constant folding, so we don't
7322 * need to update the member
7323 */
7324 arglist_->fold_constants(symtab);
7325
7326 /* return myself with no further evaluation */
7327 return this;
7328 }
7329
7330 /*
7331 * adjust for dynamic (run-time) compilation
7332 */
7333 CTcPrsNode *CTPNMemArgBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
7334 {
7335 /* don't allow in speculative mode due to possible side effects */
7336 if (info->speculative)
7337 err_throw(VMERR_BAD_SPEC_EVAL);
7338
7339 /*
7340 * adjust my object expression, property expression, and argument
7341 * list
7342 */
7343 obj_expr_ = obj_expr_->adjust_for_dyn(info);
7344 prop_expr_ = prop_expr_->adjust_for_dyn(info);
7345 arglist_->adjust_for_dyn(info);
7346
7347 /* return myself otherwise unchanged */
7348 return this;
7349 }
7350
7351
7352 /* ------------------------------------------------------------------------ */
7353 /*
7354 * Function/Method Call parse node base class
7355 */
7356
7357 /*
7358 * fold constants
7359 */
7360 CTcPrsNode *CTPNCallBase::fold_constants(CTcPrsSymtab *symtab)
7361 {
7362 /* fold my function expression */
7363 func_ = func_->fold_constants(symtab);
7364
7365 /* fold my argument list */
7366 arglist_->fold_constants(symtab);
7367
7368 /* return myself unchanged */
7369 return this;
7370 }
7371
7372 /*
7373 * adjust for dynamic (run-time) compilation
7374 */
7375 CTcPrsNode *CTPNCallBase::adjust_for_dyn(const tcpn_dyncomp_info *info)
7376 {
7377 /* don't allow in speculative mode because of side effects */
7378 if (info->speculative)
7379 err_throw(VMERR_BAD_SPEC_EVAL);
7380
7381 /* adjust the function expression */
7382 func_ = func_->adjust_for_dyn(info);
7383
7384 /* adjust the argument list (assume it doesn't change) */
7385 arglist_->adjust_for_dyn(info);
7386
7387 /* return myself otherwise unchanged */
7388 return this;
7389 }
7390
7391 /* ------------------------------------------------------------------------ */
7392 /*
7393 * Parser Symbol Table implementation
7394 */
7395
7396 /* static hash function */
7397 CVmHashFunc *CTcPrsSymtab::hash_func_ = 0;
7398
7399 /*
7400 * allocate parser symbol tables out of the parser memory pool
7401 */
7402 void *CTcPrsSymtab::operator new(size_t siz)
7403 {
7404 return G_prsmem->alloc(siz);
7405 }
7406
7407 /*
7408 * static initialization
7409 */
7410 void CTcPrsSymtab::s_init()
7411 {
7412 /* create our static hash function */
7413 if (hash_func_ == 0)
7414 hash_func_ = new CVmHashFuncCS();
7415 }
7416
7417 /*
7418 * static termination
7419 */
7420 void CTcPrsSymtab::s_terminate()
7421 {
7422 /* delete our static hash function */
7423 if (hash_func_ != 0)
7424 {
7425 delete hash_func_;
7426 hash_func_ = 0;
7427 }
7428 }
7429
7430 /*
7431 * initialize
7432 */
7433 CTcPrsSymtab::CTcPrsSymtab(CTcPrsSymtab *parent_scope)
7434 {
7435 size_t hash_table_size;
7436
7437 /*
7438 * Create the hash table. If we're at global scope (parent_scope ==
7439 * 0), create a large hash table, since we'll probably add lots of
7440 * symbols; otherwise, it's just a local table, which probably won't
7441 * have many entries, so create a small table.
7442 *
7443 * Note that we always use the static hash function object, hence
7444 * the table doesn't own the object.
7445 */
7446 hash_table_size = (parent_scope == 0 ? 512 : 32);
7447 hashtab_ = new (G_prsmem)
7448 CVmHashTable(hash_table_size, hash_func_, FALSE,
7449 new (G_prsmem) CVmHashEntry *[hash_table_size]);
7450
7451 /* remember the parent scope */
7452 parent_ = parent_scope;
7453
7454 /* we're not in a debugger frame list yet */
7455 list_index_ = 0;
7456 list_next_ = 0;
7457
7458 /* we don't have a generated byte code range yet */
7459 start_ofs_ = end_ofs_ = 0;
7460 }
7461
7462 /*
7463 * delete
7464 */
7465 CTcPrsSymtab::~CTcPrsSymtab()
7466 {
7467 /* delete our underlying hash table */
7468 delete hashtab_;
7469 }
7470
7471 /*
7472 * Find a symbol, marking it as referenced if we find it.
7473 */
7474 CTcSymbol *CTcPrsSymtab::find(const textchar_t *sym, size_t len,
7475 CTcPrsSymtab **symtab)
7476 {
7477 CTcSymbol *entry;
7478
7479 /* find the symbol */
7480 entry = find_noref(sym, len, symtab);
7481
7482 /* if we found an entry, mark it as referenced */
7483 if (entry != 0)
7484 entry->mark_referenced();
7485
7486 /* return the result */
7487 return entry;
7488 }
7489
7490 /*
7491 * Find a symbol. This base version does not affect the 'referenced'
7492 * status of the symbol we look up.
7493 */
7494 CTcSymbol *CTcPrsSymtab::find_noref(const textchar_t *sym, size_t len,
7495 CTcPrsSymtab **symtab)
7496 {
7497 /*
7498 * Look for the symbol. Start in the current symbol table, and work
7499 * outwards to the outermost enclosing table.
7500 */
7501 for (CTcPrsSymtab *curtab = this ; curtab != 0 ;
7502 curtab = curtab->get_parent())
7503 {
7504 /* look for the symbol in this table */
7505 CTcSymbol *entry = curtab->find_direct(sym, len);
7506 if (entry != 0)
7507 {
7508 /*
7509 * found it - if the caller wants to know about the symbol
7510 * table in which we actually found the symbol, return that
7511 * information
7512 */
7513 if (symtab != 0)
7514 *symtab = curtab;
7515
7516 /* return the symbol table entry we found */
7517 return entry;
7518 }
7519 }
7520
7521 /* we didn't find the symbol - return failure */
7522 return 0;
7523 }
7524
7525 /*
7526 * Find a symbol directly in this table
7527 */
7528 CTcSymbol *CTcPrsSymtab::find_direct(const textchar_t *sym, size_t len)
7529 {
7530 /* return the entry from our hash table */
7531 return (CTcSymbol *)get_hashtab()->find(sym, len);
7532 }
7533
7534 /*
7535 * Add a symbol to the table
7536 */
7537 void CTcPrsSymtab::add_entry(CTcSymbol *sym)
7538 {
7539 /* add it to the table */
7540 get_hashtab()->add(sym);
7541 }
7542
7543 /*
7544 * remove a symbol from the table
7545 */
7546 void CTcPrsSymtab::remove_entry(CTcSymbol *sym)
7547 {
7548 /* remove it from the underyling hash table */
7549 get_hashtab()->remove(sym);
7550 }
7551
7552 /*
7553 * Add a formal parameter symbol
7554 */
7555 CTcSymLocal *CTcPrsSymtab::add_formal(const textchar_t *sym, size_t len,
7556 int formal_num, int copy_str)
7557 {
7558 CTcSymLocal *lcl;
7559
7560 /*
7561 * Make sure it's not already defined in our own symbol table - if
7562 * it is, log an error and ignore the redundant definition. (We
7563 * only care about our own scope, not enclosing scopes, since it's
7564 * perfectly fine to hide variables in enclosing scopes.)
7565 */
7566 if (find_direct(sym, len) != 0)
7567 {
7568 /* log an error */
7569 G_tok->log_error(TCERR_FORMAL_REDEF, (int)len, sym);
7570
7571 /* don't add the symbol again */
7572 return 0;
7573 }
7574
7575 /* create the symbol entry */
7576 lcl = new CTcSymLocal(sym, len, copy_str, TRUE, formal_num);
7577
7578 /* add it to the table */
7579 add_entry(lcl);
7580
7581 /* return the new symbol */
7582 return lcl;
7583 }
7584
7585 /*
7586 * Add the current token as a local variable symbol, initially unreferenced
7587 * and uninitialized
7588 */
7589 CTcSymLocal *CTcPrsSymtab::add_local(int local_num)
7590 {
7591 return add_local(G_tok->getcur()->get_text(),
7592 G_tok->getcur()->get_text_len(),
7593 local_num, FALSE, FALSE, FALSE);
7594 }
7595
7596 /*
7597 * Add a local variable symbol
7598 */
7599 CTcSymLocal *CTcPrsSymtab::add_local(const textchar_t *sym, size_t len,
7600 int local_num, int copy_str,
7601 int init_assigned, int init_referenced)
7602 {
7603 CTcSymLocal *lcl;
7604
7605 /*
7606 * make sure the symbol isn't already defined in this scope; if it
7607 * is, log an error
7608 */
7609 if (find_direct(sym, len) != 0)
7610 {
7611 /* log the error */
7612 G_tok->log_error(TCERR_LOCAL_REDEF, (int)len, sym);
7613
7614 /* don't create the symbol again - return the original definition */
7615 return 0;
7616 }
7617
7618 /* create the symbol entry */
7619 lcl = new CTcSymLocal(sym, len, copy_str, FALSE, local_num);
7620
7621 /*
7622 * if the symbol is initially to be marked as referenced or
7623 * assigned, mark it now
7624 */
7625 if (init_assigned)
7626 lcl->set_val_assigned(TRUE);
7627 if (init_referenced)
7628 lcl->set_val_used(TRUE);
7629
7630 /* add it to the table */
7631 add_entry(lcl);
7632
7633 /* return the new local */
7634 return lcl;
7635 }
7636
7637 /*
7638 * Add a code label ('goto') symbol
7639 */
7640 CTcSymLabel *CTcPrsSymtab::add_code_label(const textchar_t *sym, size_t len,
7641 int copy_str)
7642 {
7643 CTcSymLabel *lbl;
7644
7645 /*
7646 * make sure the symbol isn't already defined in this scope; if it
7647 * is, log an error
7648 */
7649 if (find_direct(sym, len) != 0)
7650 {
7651 /* log the error */
7652 G_tok->log_error(TCERR_CODE_LABEL_REDEF, (int)len, sym);
7653
7654 /* don't create the symbol again - return the original definition */
7655 return 0;
7656 }
7657
7658 /* create the symbol entry */
7659 lbl = new CTcSymLabel(sym, len, copy_str);
7660
7661 /* add it to the table */
7662 add_entry(lbl);
7663
7664 /* return the new label */
7665 return lbl;
7666 }
7667
7668
7669 /*
7670 * Find a symbol; if the symbol isn't defined, add a new entry according
7671 * to the action flag. Because we add a symbol entry if the symbol
7672 * isn't defined, this *always* returns a valid symbol object.
7673 */
7674 CTcSymbol *CTcPrsSymtab::find_or_def(const textchar_t *sym, size_t len,
7675 int copy_str, tcprs_undef_action action)
7676 {
7677 /*
7678 * Look for the symbol. Start in the current symbol table, and work
7679 * outwards to the outermost enclosing table.
7680 */
7681 for (CTcPrsSymtab *curtab = this ; ; curtab = curtab->get_parent())
7682 {
7683 /* look for the symbol in this table */
7684 CTcSymbol *entry = (CTcSymbol *)curtab->find_direct(sym, len);
7685 if (entry != 0)
7686 {
7687 /* mark the entry as referenced */
7688 entry->mark_referenced();
7689
7690 /*
7691 * if this is a non-weak property definition, and this is a
7692 * property symbol, remove any existing weak flag from the
7693 * property symbol
7694 */
7695 if (entry->get_type() == TC_SYM_PROP
7696 && (action == TCPRS_UNDEF_ADD_PROP
7697 || action == TCPRS_UNDEF_ADD_PROP_NO_WARNING))
7698 ((CTcSymProp *)entry)->set_weak(FALSE);
7699
7700 /* found it - return the symbol */
7701 return entry;
7702 }
7703
7704 /*
7705 * If there's no parent symbol table, the symbol is undefined.
7706 * Add a new symbol according to the action parameter. Note
7707 * that we always add the new symbol at global scope, hence we
7708 * add it to 'curtab', not 'this'.
7709 */
7710 if (curtab->get_parent() == 0)
7711 {
7712 /* check which action we're being asked to perform */
7713 switch(action)
7714 {
7715 case TCPRS_UNDEF_ADD_UNDEF:
7716 /* add an "undefined" entry - log an error */
7717 G_tok->log_error(TCERR_UNDEF_SYM, (int)len, sym);
7718
7719 /* create a new symbol of type undefined */
7720 entry = new CTcSymUndef(sym, len, copy_str);
7721
7722 /* finish up */
7723 goto add_entry;
7724
7725 case TCPRS_UNDEF_ADD_PROP:
7726 case TCPRS_UNDEF_ADD_PROP_NO_WARNING:
7727 case TCPRS_UNDEF_ADD_PROP_WEAK:
7728 {
7729 /* create a new symbol of type property */
7730 CTcSymProp *prop = new CTcSymProp(
7731 sym, len, copy_str, G_cg->new_prop_id());
7732
7733 /* mark it as "weak" if desired */
7734 if (action == TCPRS_UNDEF_ADD_PROP_WEAK)
7735 prop->set_weak(TRUE);
7736
7737 /* use it as the new table entry */
7738 entry = prop;
7739 }
7740
7741 /* show a warning if desired */
7742 if (action == TCPRS_UNDEF_ADD_PROP)
7743 G_tok->log_warning(TCERR_ASSUME_SYM_PROP, (int)len, sym);
7744
7745 /* finish up */
7746 goto add_entry;
7747
7748 add_entry:
7749 /* add the new entry to the global table */
7750 add_to_global_symtab(curtab, entry);
7751
7752 /* return the new entry */
7753 return entry;
7754 }
7755 }
7756 }
7757 }
7758
7759 /*
7760 * Find a symbol. If the symbol is already defined as a "weak" property,
7761 * delete the existing symbol to make way for the overriding strong
7762 * definition.
7763 */
7764 CTcSymbol *CTcPrsSymtab::find_delete_weak(const char *name, size_t len)
7765 {
7766 /* look up the symbol */
7767 CTcSymbol *sym = find(name, len);
7768
7769 /* if it's a weak property definition, delete it */
7770 if (sym != 0
7771 && sym->get_type() == TC_SYM_PROP
7772 && ((CTcSymProp *)sym)->is_weak())
7773 {
7774 /* delete it and forget it */
7775 remove_entry(sym);
7776 sym = 0;
7777 }
7778
7779 /* return what we found */
7780 return sym;
7781 }
7782
7783
7784 /*
7785 * Enumerate the entries in a symbol table
7786 */
7787 void CTcPrsSymtab::enum_entries(void (*func)(void *, CTcSymbol *),
7788 void *ctx)
7789 {
7790 /*
7791 * Ask the hash table to perform the enumeration. We know that all
7792 * of our entries in the symbol table are CTcSymbol objects, so we
7793 * can coerce the callback function to the appropriate type without
7794 * danger.
7795 */
7796 get_hashtab()->enum_entries((void (*)(void *, CVmHashEntry *))func, ctx);
7797 }
7798
7799 /*
7800 * Scan the symbol table for unreferenced local variables
7801 */
7802 void CTcPrsSymtab::check_unreferenced_locals()
7803 {
7804 /* skip the check if we're only parsing for syntax */
7805 if (!G_prs->get_syntax_only())
7806 {
7807 /* run the symbols through our unreferenced local check callback */
7808 enum_entries(&unref_local_cb, this);
7809 }
7810 }
7811
7812 /*
7813 * Enumeration callback to check for unreferenced locals
7814 */
7815 void CTcPrsSymtab::unref_local_cb(void *, CTcSymbol *sym)
7816 {
7817 /* check the symbol */
7818 sym->check_local_references();
7819 }
7820
7821 /* ------------------------------------------------------------------------ */
7822 /*
7823 * Comma node
7824 */
7825
7826 /*
7827 * fold constants
7828 */
7829 CTcPrsNode *CTPNCommaBase::fold_binop()
7830 {
7831 /* use the normal addition folder */
7832 return S_op_comma.eval_constant(left_, right_);
7833 }
7834
7835
7836 /* ------------------------------------------------------------------------ */
7837 /*
7838 * Addition parse node
7839 */
7840
7841 /*
7842 * Fold constants. We override the default fold_constants() for
7843 * addition nodes because addition constancy can be affected by symbol
7844 * resolution. In particular, if we resolve symbols in a list, the list
7845 * could turn constant, which could in turn make the result of an
7846 * addition operator with the list as an operand turn constant.
7847 */
7848 CTcPrsNode *CTPNAddBase::fold_binop()
7849 {
7850 /* use the normal addition folder */
7851 return S_op_add.eval_constant(left_, right_);
7852 }
7853
7854 /* ------------------------------------------------------------------------ */
7855 /*
7856 * Subtraction parse node
7857 */
7858
7859 /*
7860 * Fold constants. We override the default fold_constants() for the
7861 * subtraction node because subtraction constancy can be affected by
7862 * symbol resolution. In particular, if we resolve symbols in a list,
7863 * the list could turn constant, which could in turn make the result of
7864 * a subtraction operator with the list as an operand turn constant.
7865 */
7866 CTcPrsNode *CTPNSubBase::fold_binop()
7867 {
7868 /* use the normal addition folder */
7869 return S_op_sub.eval_constant(left_, right_);
7870 }
7871
7872 /* ------------------------------------------------------------------------ */
7873 /*
7874 * Equality Comparison parse node
7875 */
7876
7877 /*
7878 * fold constants
7879 */
7880 CTcPrsNode *CTPNEqBase::fold_binop()
7881 {
7882 /* use the normal addition folder */
7883 return S_op_eq.eval_constant(left_, right_);
7884 }
7885
7886 /* ------------------------------------------------------------------------ */
7887 /*
7888 * Inequality Comparison parse node
7889 */
7890
7891 /*
7892 * fold constants
7893 */
7894 CTcPrsNode *CTPNNeBase::fold_binop()
7895 {
7896 /* use the normal addition folder */
7897 return S_op_ne.eval_constant(left_, right_);
7898 }
7899
7900 /* ------------------------------------------------------------------------ */
7901 /*
7902 * Logical AND parse node
7903 */
7904
7905 /*
7906 * fold constants
7907 */
7908 CTcPrsNode *CTPNAndBase::fold_binop()
7909 {
7910 /* use the normal addition folder */
7911 return S_op_and.eval_constant(left_, right_);
7912 }
7913
7914 /* ------------------------------------------------------------------------ */
7915 /*
7916 * Logical OR parse node
7917 */
7918
7919 /*
7920 * fold constants
7921 */
7922 CTcPrsNode *CTPNOrBase::fold_binop()
7923 {
7924 /* use the normal addition folder */
7925 return S_op_or.eval_constant(left_, right_);
7926 }
7927
7928 /* ------------------------------------------------------------------------ */
7929 /*
7930 * NOT parse node
7931 */
7932
7933 /*
7934 * fold constants
7935 */
7936 CTcPrsNode *CTPNNotBase::fold_unop()
7937 {
7938 /* use the normal addition folder */
7939 return S_op_unary.eval_const_not(sub_);
7940 }
7941
7942
7943 /* ------------------------------------------------------------------------ */
7944 /*
7945 * Subscript parse node
7946 */
7947
7948 /*
7949 * Fold constants. We override the default fold_constants() for
7950 * subscript nodes because subscript constancy can be affected by symbol
7951 * resolution. In particular, if we resolve symbols in a list, the list
7952 * could turn constant, which could in turn make the result of a
7953 * subscript operator with the list as an operand turn constant.
7954 */
7955 /* ------------------------------------------------------------------------ */
7956 /*
7957 * Equality Comparison parse node
7958 */
7959
7960 /*
7961 * fold constants
7962 */
7963 CTcPrsNode *CTPNSubscriptBase::fold_binop()
7964 {
7965 /* use the normal addition folder */
7966 return S_op_unary.eval_const_subscript(left_, right_);
7967 }
7968
7969
7970 /* ------------------------------------------------------------------------ */
7971 /*
7972 * Parser Symbol Table Entry base class
7973 */
7974
7975 /*
7976 * Allocate symbol objects from the parse pool, since these objects have
7977 * all of the lifespan characteristics of pool objects.
7978 */
7979 void *CTcSymbolBase::operator new(size_t siz)
7980 {
7981 return G_prsmem->alloc(siz);
7982 }
7983
7984 /* ------------------------------------------------------------------------ */
7985 /*
7986 * function symbol entry base
7987 */
7988
7989 /*
7990 * fold function name into a function address
7991 */
7992 CTcPrsNode *CTcSymFuncBase::fold_constant()
7993 {
7994 CTcConstVal cval;
7995
7996 /* set up the function pointer constant */
7997 cval.set_funcptr((CTcSymFunc *)this);
7998
7999 /* return a constant node with the function pointer */
8000 return new CTPNConst(&cval);
8001 }
8002
8003 /*
8004 * add an absolute fixup to my list
8005 */
8006 void CTcSymFuncBase::add_abs_fixup(CTcDataStream *ds, ulong ofs)
8007 {
8008 /* ask the code body to add the fixup */
8009 CTcAbsFixup::add_abs_fixup(&fixups_, ds, ofs);
8010 }
8011
8012 /*
8013 * add an absolute fixup at the current stream offset
8014 */
8015 void CTcSymFuncBase::add_abs_fixup(CTcDataStream *ds)
8016 {
8017 /* ask the code body to add the fixup */
8018 CTcAbsFixup::add_abs_fixup(&fixups_, ds, ds->get_ofs());
8019 }
8020
8021 /* ------------------------------------------------------------------------ */
8022 /*
8023 * local variable symbol entry base
8024 */
8025
8026 /*
8027 * initialize
8028 */
8029 CTcSymLocalBase::CTcSymLocalBase(const char *str, size_t len, int copy,
8030 int is_param, int var_num)
8031 : CTcSymbol(str, len, copy, (is_param ? TC_SYM_PARAM : TC_SYM_LOCAL))
8032 {
8033 /* remember the information */
8034 var_num_ = var_num;
8035 param_index_ = 0;
8036 is_param_ = is_param;
8037 is_named_param_ = FALSE;
8038 is_opt_param_ = FALSE;
8039 is_list_param_ = FALSE;
8040
8041 /* presume it's a regular stack variable (not a context local) */
8042 is_ctx_local_ = FALSE;
8043 ctx_orig_ = 0;
8044 ctx_var_num_ = 0;
8045 ctx_level_ = 0;
8046 ctx_var_num_set_ = FALSE;
8047
8048 /* presume there's no default value expression */
8049 defval_expr_ = 0;
8050
8051 /* so far, the value isn't used anywhere */
8052 val_used_ = FALSE;
8053 val_assigned_ = FALSE;
8054
8055 /* the symbol has not been referenced so far */
8056 referenced_ = FALSE;
8057
8058 /* remember where the symbol is defined in the source file */
8059 G_tok->get_last_pos(&src_desc_, &src_linenum_);
8060 }
8061
8062 /*
8063 * Mark the value of the variable as used
8064 */
8065 void CTcSymLocalBase::set_val_used(int f)
8066 {
8067 /* note the new status */
8068 val_used_ = f;
8069
8070 /* if we have now assigned the value, propagate to the original */
8071 if (f && ctx_orig_ != 0)
8072 ctx_orig_->set_val_used(TRUE);
8073 }
8074
8075 /*
8076 * Mark the value of the variable as assigned
8077 */
8078 void CTcSymLocalBase::set_val_assigned(int f)
8079 {
8080 /* note the new status */
8081 val_assigned_ = f;
8082
8083 /* if we have now assigned the value, propagate to the original */
8084 if (f && ctx_orig_ != 0)
8085 ctx_orig_->set_val_assigned(TRUE);
8086 }
8087
8088 /*
8089 * Check for references to this local
8090 */
8091 void CTcSymLocalBase::check_local_references()
8092 {
8093 int err;
8094 tc_severity_t sev = TC_SEV_WARNING;
8095
8096 /*
8097 * if this isn't an original, but is simply a copy of a variable
8098 * inherited from an enclosing scope (such as into an anonymous
8099 * function), don't bother even checking for errors - we'll let the
8100 * original symbol take care of reporting its own errors
8101 */
8102 if (ctx_orig_ != 0)
8103 return;
8104
8105 /*
8106 * Note if this is some kind of parameter. Some parameters are
8107 * represented as locals: varargs-list parameters, optional parameters,
8108 * and named parameters. We need to check for those kinds of
8109 * parameters specifically because they otherwise look like regular
8110 * local variables.
8111 */
8112 int param = (is_param() || is_list_param()
8113 || is_opt_param() || is_named_param());
8114
8115 /*
8116 * If it's unreferenced or unassigned (or both), log an error; note
8117 * that a formal parameter is always assigned, since the value is
8118 * assigned by the caller.
8119 */
8120 if (!get_val_used() && !get_val_assigned() && !param)
8121 {
8122 /* this is a regular local that was never assigned or referenced */
8123 err = TCERR_UNREFERENCED_LOCAL;
8124 }
8125 else if (!get_val_used())
8126 {
8127 if (param)
8128 {
8129 /* it's a parameter - generate only a pendantic error */
8130 sev = TC_SEV_PEDANTIC;
8131 err = TCERR_UNREFERENCED_PARAM;
8132 }
8133 else
8134 {
8135 /*
8136 * this is a regular local with a value that was assigned and
8137 * never used
8138 */
8139 err = TCERR_UNUSED_LOCAL_ASSIGNMENT;
8140 }
8141 }
8142 else if (!get_val_assigned() && !param)
8143 {
8144 /* it's used but never assigned */
8145 err = TCERR_UNASSIGNED_LOCAL;
8146 }
8147 else
8148 {
8149 /* no error */
8150 return;
8151 }
8152
8153 /*
8154 * display the warning message, showing the error location as the
8155 * source line where the local was defined
8156 */
8157 G_tcmain->log_error(get_src_desc(), get_src_linenum(),
8158 sev, err, (int)get_sym_len(), get_sym());
8159 }
8160
8161 /*
8162 * create a new context variable copy of this symbol
8163 */
8164 CTcSymbol *CTcSymLocalBase::new_ctx_var() const
8165 {
8166 /* create a new local with the same name */
8167 CTcSymLocal *lcl = new CTcSymLocal(
8168 get_sym(), get_sym_len(), FALSE, FALSE, 0);
8169
8170 /* refer the copy back to the original (i.e., me) */
8171 lcl->set_ctx_orig((CTcSymLocal *)this);
8172
8173 /* set up the context variable information */
8174 if (!is_ctx_local_)
8175 {
8176 /*
8177 * The original is a true local - we're at the first context
8178 * level, and we don't yet have a property assigned, since we
8179 * don't know if this variable is actually going to be
8180 * referenced.
8181 */
8182 lcl->set_ctx_level(1);
8183 }
8184 else
8185 {
8186 /*
8187 * The original was already a context variable - we're at one
8188 * higher context level in this function, and we use the same
8189 * context property as the original did.
8190 */
8191 lcl->set_ctx_level(ctx_level_ + 1);
8192 }
8193
8194 /* return the new symbol */
8195 return lcl;
8196 }
8197
8198 /*
8199 * Apply context variable conversion
8200 */
8201 int CTcSymLocalBase::apply_ctx_var_conv(
8202 CTcPrsSymtab *symtab, CTPNCodeBody *code_body)
8203 {
8204 /*
8205 * if this symbol isn't referenced, simply delete it from the table,
8206 * so that it doesn't get entered in the debug records; and there's
8207 * no need to propagate it back to the enclosing scope as a context
8208 * variable, since it's not referenced from this enclosed scope
8209 */
8210 if (!referenced_)
8211 {
8212 /* remove the symbol from the table */
8213 symtab->remove_entry(this);
8214
8215 /* this variable doesn't need to be converted */
8216 return FALSE;
8217 }
8218
8219 /*
8220 * convert the symbol in the enclosing scope to a context local, if
8221 * it's not already
8222 */
8223 if (ctx_orig_ != 0)
8224 {
8225 /* convert the original to a context symbol */
8226 ctx_orig_->convert_to_ctx_var(get_val_used(), get_val_assigned());
8227
8228 /*
8229 * ask the code body for the context object's local variable for
8230 * our recursion level
8231 */
8232 ctx_var_num_ = code_body->get_or_add_ctx_var_for_level(ctx_level_);
8233
8234 /* note that we've set our context variable ID */
8235 ctx_var_num_set_ = TRUE;
8236
8237 /* this variable was converted */
8238 return TRUE;
8239 }
8240
8241 /* this variable wasn't converted */
8242 return FALSE;
8243 }
8244
8245 /*
8246 * convert this variable to a context variable
8247 */
8248 void CTcSymLocalBase::convert_to_ctx_var(int val_used, int val_assigned)
8249 {
8250 /* if I'm not already a context local, mark me as a context local */
8251 if (!is_ctx_local_)
8252 {
8253 /* mark myself as a context local */
8254 is_ctx_local_ = TRUE;
8255
8256 /*
8257 * we haven't yet assigned our local context variable, since
8258 * we're still processing the inner scope at this point; just
8259 * store placeholders for now so we know to come back and fix
8260 * this up
8261 */
8262 ctx_var_num_ = 0;
8263 ctx_arr_idx_ = 0;
8264 }
8265
8266 /* note that I've been referenced */
8267 mark_referenced();
8268
8269 /* propagate the value-used and value-assigned flags */
8270 if (val_used)
8271 set_val_used(TRUE);
8272 if (val_assigned)
8273 set_val_assigned(TRUE);
8274
8275 /* propagate the conversion to the original symbol */
8276 if (ctx_orig_ != 0)
8277 ctx_orig_->convert_to_ctx_var(val_used, val_assigned);
8278 }
8279
8280 /*
8281 * finish the context variable conversion
8282 */
8283 void CTcSymLocalBase::finish_ctx_var_conv()
8284 {
8285 /*
8286 * If this isn't already marked as a context variable, there's
8287 * nothing to do - this variable must not have been referenced from
8288 * an anonymous function yet, and hence can be kept in the stack.
8289 *
8290 * Similarly, if my context local variable number has been assigned
8291 * already, there's nothing to do - we must have been set to refer
8292 * back to a context variable in an enclosing scope (this can happen
8293 * in a nested anonymous function).
8294 */
8295 if (!is_ctx_local_ || ctx_var_num_set_)
8296 return;
8297
8298 /*
8299 * tell the parser to create a local context for this scope, if it
8300 * hasn't already
8301 */
8302 G_prs->init_local_ctx();
8303
8304 /* use the local context variable specified by the parser */
8305 ctx_var_num_ = G_prs->get_local_ctx_var();
8306 ctx_var_num_set_ = TRUE;
8307
8308 /* assign our array index */
8309 if (ctx_arr_idx_ == 0)
8310 ctx_arr_idx_ = G_prs->alloc_ctx_arr_idx();
8311 }
8312
8313 /*
8314 * Get my context variable array index
8315 */
8316 int CTcSymLocalBase::get_ctx_arr_idx() const
8317 {
8318 /*
8319 * if I'm based on an original symbol from another scope, use the
8320 * same property ID as the original symbol
8321 */
8322 if (ctx_orig_ != 0)
8323 return ctx_orig_->get_ctx_arr_idx();
8324
8325 /* return my context property */
8326 return ctx_arr_idx_;
8327 }
8328
8329 /* ------------------------------------------------------------------------ */
8330 /*
8331 * object symbol entry base
8332 */
8333
8334 /*
8335 * fold the symbol as a constant
8336 */
8337 CTcPrsNode *CTcSymObjBase::fold_constant()
8338 {
8339 /* if it's not a TadsObject symbol, we can't fold it into a constant */
8340 if (get_metaclass() != TC_META_TADSOBJ)
8341 return 0;
8342
8343 /* set up the object constant */
8344 CTcConstVal cval;
8345 cval.set_obj(get_obj_id(), get_metaclass());
8346
8347 /* return a constant node */
8348 return new CTPNConst(&cval);
8349 }
8350
8351 /*
8352 * Add a superclass name entry.
8353 */
8354 void CTcSymObjBase::add_sc_name_entry(const char *txt, size_t len)
8355 {
8356 /* create the entry object */
8357 CTPNSuperclass *entry = new CTPNSuperclass(txt, len);
8358
8359 /* link it into our list */
8360 if (sc_name_tail_ != 0)
8361 sc_name_tail_->nxt_ = entry;
8362 else
8363 sc_name_head_ = entry;
8364 sc_name_tail_ = entry;
8365 }
8366
8367 /*
8368 * Check to see if I have a given superclass.
8369 */
8370 int CTcSymObjBase::has_superclass(class CTcSymObj *sc_sym) const
8371 {
8372 /*
8373 * Scan my direct superclasses. For each one, check to see if my
8374 * superclass matches the given superclass, or if my superclass
8375 * inherits from the given superclass.
8376 */
8377 for (CTPNSuperclass *entry = sc_name_head_ ; entry != 0 ;
8378 entry = entry->nxt_)
8379 {
8380 /* look up this symbol */
8381 CTcSymObj *entry_sym = (CTcSymObj *)G_prs->get_global_symtab()->find(
8382 entry->get_sym_txt(), entry->get_sym_len());
8383
8384 /*
8385 * if the entry's symbol doesn't exist or isn't an object symbol,
8386 * skip it
8387 */
8388 if (entry_sym == 0 || entry_sym->get_type() != TC_SYM_OBJ)
8389 continue;
8390
8391 /*
8392 * if it matches the given superclass, we've found the given
8393 * superclass among our direct superclasses, so we definitely have
8394 * the given superclass
8395 */
8396 if (entry_sym == sc_sym)
8397 return TRUE;
8398
8399 /*
8400 * ask the symbol if the given class is among its direct or
8401 * indirect superclasses - if it's a superclass of my superclass,
8402 * it's also my superclass
8403 */
8404 if (entry_sym->has_superclass(sc_sym))
8405 return TRUE;
8406 }
8407
8408 /*
8409 * we didn't find the given class anywhere among our superclasses or
8410 * their superclasses, so it must not be a superclass of ours
8411 */
8412 return FALSE;
8413 }
8414
8415 /*
8416 * Add a deleted property entry
8417 */
8418 void CTcSymObjBase::add_del_prop_to_list(CTcObjPropDel **list_head,
8419 CTcSymProp *prop_sym)
8420 {
8421 /* create the new entry */
8422 CTcObjPropDel *entry = new CTcObjPropDel(prop_sym);
8423
8424 /* link it into my list */
8425 entry->nxt_ = *list_head;
8426 *list_head = entry;
8427 }
8428
8429 /*
8430 * Add a self-reference fixup
8431 */
8432 void CTcSymObjBase::add_self_ref_fixup(CTcDataStream *stream, ulong ofs)
8433 {
8434 /* add a fixup to our list */
8435 CTcIdFixup::add_fixup(&fixups_, stream, ofs, obj_id_);
8436 }
8437
8438 /*
8439 * Add a word to my vocabulary
8440 */
8441 void CTcSymObjBase::add_vocab_word(const char *txt, size_t len,
8442 tctarg_prop_id_t prop)
8443 {
8444 /* create a new vocabulary entry */
8445 CTcVocabEntry *entry = new (G_prsmem) CTcVocabEntry(txt, len, prop);
8446
8447 /* link it into my list */
8448 entry->nxt_ = vocab_;
8449 vocab_ = entry;
8450 }
8451
8452 /*
8453 * Delete a vocabulary property from my list (for 'replace')
8454 */
8455 void CTcSymObjBase::delete_vocab_prop(tctarg_prop_id_t prop)
8456 {
8457 /* scan my list and delete each word defined for the given property */
8458 for (CTcVocabEntry *prv = 0, *entry = vocab_, *nxt = 0 ;
8459 entry != 0 ; entry = nxt)
8460 {
8461 /* remember the next entry */
8462 nxt = entry->nxt_;
8463
8464 /* if this entry is for the given property, unlink it */
8465 if (entry->prop_ == prop)
8466 {
8467 /*
8468 * it matches - unlink it from the list (note that we don't
8469 * have to delete the entry, because it's allocated in
8470 * parser memory and thus will be deleted when the parser is
8471 * deleted)
8472 */
8473 if (prv != 0)
8474 prv->nxt_ = nxt;
8475 else
8476 vocab_ = nxt;
8477
8478 /*
8479 * this entry is no longer in any list (we don't really have
8480 * to clear the 'next' pointer here, since nothing points to
8481 * 'entry' any more, but doing so will make it obvious that
8482 * the entry was removed from the list, which could be handy
8483 * during debugging from time to time)
8484 */
8485 entry->nxt_ = 0;
8486 }
8487 else
8488 {
8489 /*
8490 * this entry is still in the list, so it's now the previous
8491 * entry for our scan
8492 */
8493 prv = entry;
8494 }
8495 }
8496 }
8497
8498 /*
8499 * Add my words to the dictionary, associating the words with the given
8500 * object. This can be used to add my own words to the dictionary or to
8501 * add my words to a subclass's dictionary.
8502 */
8503 void CTcSymObjBase::inherit_vocab()
8504 {
8505 /*
8506 * if I've already inherited my superclass vocabulary, there's
8507 * nothing more we need to do
8508 */
8509 if (vocab_inherited_)
8510 return;
8511
8512 /* make a note that I've inherited my superclass vocabulary */
8513 vocab_inherited_ = TRUE;
8514
8515 /* inherit words from each superclass */
8516 for (CTcObjScEntry *sc = sc_ ; sc != 0 ; sc = sc->nxt_)
8517 {
8518 /* make sure this superclass has built its inherited list */
8519 sc->sym_->inherit_vocab();
8520
8521 /* add this superclass's words to my list */
8522 sc->sym_->add_vocab_to_subclass((CTcSymObj *)this);
8523 }
8524 }
8525
8526 /*
8527 * Add my vocabulary words to the given subclass's vocabulary list
8528 */
8529 void CTcSymObjBase::add_vocab_to_subclass(CTcSymObj *sub)
8530 {
8531 /* add each of my words to the subclass */
8532 for (CTcVocabEntry *entry = vocab_ ; entry != 0 ; entry = entry->nxt_)
8533 {
8534 /* add this word to my dictionary */
8535 sub->add_vocab_word(entry->txt_, entry->len_, entry->prop_);
8536 }
8537 }
8538
8539 /*
8540 * Set my base 'modify' object. This tells us the object that we're
8541 * modifying.
8542 */
8543 void CTcSymObjBase::set_mod_base_sym(CTcSymObj *sym)
8544 {
8545 /* remember the object I'm modifying */
8546 mod_base_sym_ = sym;
8547
8548 /*
8549 * set the other object's link back to me, so it knows that I'm the
8550 * object that's modifying it
8551 */
8552 if (sym != 0)
8553 sym->set_modifying_sym((CTcSymObj *)this);
8554 }
8555
8556 /*
8557 * Get the appropriate stream for a given metaclass
8558 */
8559 CTcDataStream *CTcSymObjBase::get_stream_from_meta(tc_metaclass_t meta)
8560 {
8561 switch(meta)
8562 {
8563 case TC_META_TADSOBJ:
8564 /* it's the regular object stream */
8565 return G_os;
8566
8567 case TC_META_ICMOD:
8568 /* intrinsic class modifier stream */
8569 return G_icmod_stream;
8570
8571 default:
8572 /* other metaclasses have no stream */
8573 return 0;
8574 }
8575 }
8576
8577 /*
8578 * Add a class-specific template
8579 */
8580 void CTcSymObjBase::add_template(CTcObjTemplate *tpl)
8581 {
8582 /* link it in at the tail of our list */
8583 if (template_tail_ != 0)
8584 template_tail_->nxt_ = tpl;
8585 else
8586 template_head_ = tpl;
8587 template_tail_ = tpl;
8588 }
8589
8590 /* ------------------------------------------------------------------------ */
8591 /*
8592 * metaclass symbol
8593 */
8594
8595 /*
8596 * add a property
8597 */
8598 void CTcSymMetaclassBase::add_prop(
8599 const char *txt, size_t len, const char *obj_fname, int is_static)
8600 {
8601 /* see if this property is already defined */
8602 CTcSymProp *prop_sym =
8603 (CTcSymProp *)G_prs->get_global_symtab()->find(txt, len);
8604 if (prop_sym != 0)
8605 {
8606 /* it's already defined - make sure it's a property */
8607 if (prop_sym->get_type() != TC_SYM_PROP)
8608 {
8609 /*
8610 * it's something other than a property - log the
8611 * appropriate type of error, depending on whether we're
8612 * loading this from an object file or from source code
8613 */
8614 if (obj_fname == 0)
8615 {
8616 /* creating from source - note the code location */
8617 G_tok->log_error_curtok(TCERR_REDEF_AS_PROP);
8618 }
8619 else
8620 {
8621 /* loading from an object file */
8622 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
8623 TCERR_OBJFILE_REDEF_SYM_TYPE,
8624 (int)len, txt, "property", obj_fname);
8625 }
8626
8627 /* forget the symbol - it's not a property */
8628 prop_sym = 0;
8629 }
8630 }
8631 else
8632 {
8633 /* add the property definition */
8634 prop_sym = new CTcSymProp(txt, len, FALSE, G_cg->new_prop_id());
8635 G_prs->get_global_symtab()->add_entry(prop_sym);
8636 }
8637
8638 /*
8639 * if we found a valid property symbol, add it to the metaclass
8640 * property list
8641 */
8642 if (prop_sym != 0)
8643 {
8644 /*
8645 * mark the symbol as referenced - even if we don't directly
8646 * make use of it, the metaclass table references this symbol
8647 */
8648 prop_sym->mark_referenced();
8649
8650 /* add the property to the metaclass list */
8651 add_prop(prop_sym, is_static);
8652 }
8653 }
8654
8655 /*
8656 * add a property
8657 */
8658 void CTcSymMetaclassBase::add_prop(class CTcSymProp *prop, int is_static)
8659 {
8660 /* create a new list entry for the property */
8661 CTcSymMetaProp *entry = new (G_prsmem) CTcSymMetaProp(prop, is_static);
8662
8663 /* link it at the end of our list */
8664 if (prop_tail_ != 0)
8665 prop_tail_->nxt_ = entry;
8666 else
8667 prop_head_ = entry;
8668 prop_tail_ = entry;
8669
8670 /* count the addition */
8671 ++prop_cnt_;
8672 }
8673
8674 /*
8675 * get the nth property in our table
8676 */
8677 CTcSymMetaProp *CTcSymMetaclassBase::get_nth_prop(int n) const
8678 {
8679 /* traverse the list to the desired index */
8680 CTcSymMetaProp *prop;
8681 for (prop = prop_head_ ; prop != 0 && n != 0 ; prop = prop->nxt_, --n) ;
8682
8683 /* return the property */
8684 return prop;
8685 }
8686
8687
8688 /* ------------------------------------------------------------------------ */
8689 /*
8690 * property symbol entry base
8691 */
8692
8693 /*
8694 * fold an address constant
8695 */
8696 CTcPrsNode *CTcSymPropBase::fold_addr_const()
8697 {
8698 /* set up the property pointer constant */
8699 CTcConstVal cval;
8700 cval.set_prop(get_prop());
8701
8702 /* return a constant node */
8703 return new CTPNConst(&cval);
8704 }
8705
8706 /* ------------------------------------------------------------------------ */
8707 /*
8708 * Enumerator symbol base
8709 */
8710
8711 /*
8712 * fold the symbol as a constant
8713 */
8714 CTcPrsNode *CTcSymEnumBase::fold_constant()
8715 {
8716 /* set up the enumerator constant */
8717 CTcConstVal cval;
8718 cval.set_enum(get_enum_id());
8719
8720 /* return a constant node */
8721 return new CTPNConst(&cval);
8722 }
8723
8724
8725 /* ------------------------------------------------------------------------ */
8726 /*
8727 * Parser dictionary hash table entry
8728 */
8729
8730 /*
8731 * add an item to my list of object associations
8732 */
8733 void CVmHashEntryPrsDict::add_item(tc_obj_id obj, tc_prop_id prop)
8734 {
8735 /* search my list for an existing association to the same obj/prop */
8736 CTcPrsDictItem *item;
8737 for (item = list_ ; item != 0 ; item = item->nxt_)
8738 {
8739 /* if it matches, we don't need to add this one again */
8740 if (item->obj_ == obj && item->prop_ == prop)
8741 return;
8742 }
8743
8744 /* not found - create a new item */
8745 item = new (G_prsmem) CTcPrsDictItem(obj, prop);
8746
8747 /* link it into my list */
8748 item->nxt_ = list_;
8749 list_ = item;
8750 }
8751
8752
8753 /* ------------------------------------------------------------------------ */
8754 /*
8755 * Code Body Parse Node
8756 */
8757
8758 /*
8759 * instantiate
8760 */
8761 CTPNCodeBodyBase::CTPNCodeBodyBase(
8762 CTcPrsSymtab *lcltab, CTcPrsSymtab *gototab, CTPNStm *stm,
8763 int argc, int opt_argc, int varargs,
8764 int varargs_list, CTcSymLocal *varargs_list_local, int local_cnt,
8765 int self_valid, CTcCodeBodyRef *enclosing_code_body)
8766 {
8767 /* remember the data in the code body */
8768 lcltab_ = lcltab;
8769 gototab_ = gototab;
8770 stm_ = stm;
8771 argc_ = argc;
8772 opt_argc_ = opt_argc;
8773 varargs_ = varargs;
8774 varargs_list_ = varargs_list;
8775 varargs_list_local_ = varargs_list_local;
8776 local_cnt_ = local_cnt;
8777 self_valid_ = self_valid;
8778 self_referenced_ = FALSE;
8779 full_method_ctx_referenced_ = FALSE;
8780 op_overload_ = FALSE;
8781 is_anon_method_ = FALSE;
8782 is_dyn_func_ = FALSE;
8783 is_dyn_method_ = FALSE;
8784
8785 /* remember the enclosing code body */
8786 enclosing_code_body_ = enclosing_code_body;
8787
8788 /* presume we won't need a local context object */
8789 has_local_ctx_ = FALSE;
8790 local_ctx_arr_size_ = 0;
8791 ctx_head_ = ctx_tail_ = 0;
8792 local_ctx_needs_self_ = FALSE;
8793 local_ctx_needs_full_method_ctx_ = FALSE;
8794
8795 /* presume we have an internal fixup list */
8796 fixup_owner_sym_ = 0;
8797 fixup_list_anchor_ = &internal_fixups_;
8798
8799 /* no internal fixups yet */
8800 internal_fixups_ = 0;
8801
8802 /* we haven't been replaced yet */
8803 replaced_ = FALSE;
8804
8805 /* leave it up to the caller to set the starting location */
8806 start_desc_ = 0;
8807 start_linenum_ = 0;
8808
8809 /*
8810 * remember the source location of the closing brace, which should
8811 * be the current location when we're instantiated
8812 */
8813 end_desc_ = G_tok->get_last_desc();
8814 end_linenum_ = G_tok->get_last_linenum();
8815 }
8816
8817
8818 /*
8819 * fold constants
8820 */
8821 CTcPrsNode *CTPNCodeBodyBase::fold_constants(class CTcPrsSymtab *)
8822 {
8823 /*
8824 * fold constants in our compound statement, in the scope of our
8825 * local symbol table
8826 */
8827 if (stm_ != 0)
8828 stm_->fold_constants(lcltab_);
8829
8830 /* we are not directly changed by this operation */
8831 return this;
8832 }
8833
8834 /*
8835 * Check for unreferenced labels
8836 */
8837 void CTPNCodeBodyBase::check_unreferenced_labels()
8838 {
8839 /*
8840 * enumerate our labels - skip this check if we're only parsing the
8841 * program for syntax
8842 */
8843 if (gototab_ != 0 && !G_prs->get_syntax_only())
8844 gototab_->enum_entries(&unref_label_cb, this);
8845 }
8846
8847 /*
8848 * Callback for enumerating labels for checking for unreferenced labels
8849 */
8850 void CTPNCodeBodyBase::unref_label_cb(void *, CTcSymbol *sym)
8851 {
8852 /* if it's a label, check it out */
8853 if (sym->get_type() == TC_SYM_LABEL)
8854 {
8855 CTcSymLabel *lbl = (CTcSymLabel *)sym;
8856
8857 /*
8858 * get its underlying statement, and make sure it has a
8859 * control-flow flag for goto, continue, or break
8860 */
8861 if (lbl->get_stm() != 0)
8862 {
8863 ulong flags;
8864
8865 /*
8866 * get the explicit control flow flags for this statement --
8867 * these flags indicate the use of the label in a goto,
8868 * break, or continue statement
8869 */
8870 flags = lbl->get_stm()->get_explicit_control_flow_flags();
8871
8872 /*
8873 * if the flags aren't set for at least one of the explicit
8874 * label uses, the label is unreferenced
8875 */
8876 if ((flags & (TCPRS_FLOW_GOTO | TCPRS_FLOW_BREAK
8877 | TCPRS_FLOW_CONT)) == 0)
8878 lbl->get_stm()->log_warning(TCERR_UNREFERENCED_LABEL,
8879 (int)lbl->get_sym_len(),
8880 lbl->get_sym());
8881 }
8882 }
8883 }
8884
8885 /*
8886 * add an absolute fixup to my list
8887 */
8888 void CTPNCodeBodyBase::add_abs_fixup(CTcDataStream *ds, ulong ofs)
8889 {
8890 /* ask the code body to add the fixup */
8891 CTcAbsFixup::add_abs_fixup(fixup_list_anchor_, ds, ofs);
8892 }
8893
8894 /*
8895 * add an absolute fixup at the current stream offset
8896 */
8897 void CTPNCodeBodyBase::add_abs_fixup(CTcDataStream *ds)
8898 {
8899 /* ask the code body to add the fixup */
8900 CTcAbsFixup::add_abs_fixup(fixup_list_anchor_, ds, ds->get_ofs());
8901 }
8902
8903 /*
8904 * Get the context variable for a given level
8905 */
8906 int CTPNCodeBodyBase::get_or_add_ctx_var_for_level(int level)
8907 {
8908 /* scan our list to see if the level is already assigned */
8909 CTcCodeBodyCtx *ctx;
8910 for (ctx = ctx_head_ ; ctx != 0 ; ctx = ctx->nxt_)
8911 {
8912 /* if we've already set up this level, return its variable */
8913 if (ctx->level_ == level)
8914 return ctx->var_num_;
8915 }
8916
8917 /* we didn't find it - allocate a new level structure */
8918 ctx = new (G_prsmem) CTcCodeBodyCtx();
8919
8920 /* set up its level and allocate a new variable and property for it */
8921 ctx->level_ = level;
8922 ctx->var_num_ = G_prs->alloc_ctx_holder_var();
8923
8924 /*
8925 * allocating a new variable probably increased the maximum local
8926 * variable count - update our information from the parser
8927 */
8928 local_cnt_ = G_prs->get_max_local_cnt();
8929
8930 /* link it into our list */
8931 ctx->prv_ = ctx_tail_;
8932 ctx->nxt_ = 0;
8933 if (ctx_tail_ != 0)
8934 ctx_tail_->nxt_ = ctx;
8935 else
8936 ctx_head_ = ctx;
8937 ctx_tail_ = ctx;
8938
8939 /* return the variable for the new level */
8940 return ctx->var_num_;
8941 }
8942
8943 /*
8944 * Find a local context for a given level
8945 */
8946 int CTPNCodeBodyBase::get_ctx_var_for_level(int level, int *varnum)
8947 {
8948 /* if they want level zero, it's our local context */
8949 if (level == 0)
8950 {
8951 /* set the variable ID to our local context variable */
8952 *varnum = local_ctx_var_;
8953
8954 /* return true only if we actually have a local context */
8955 return has_local_ctx_;
8956 }
8957
8958 /* scan our list to see if the level is already assigned */
8959 for (CTcCodeBodyCtx *ctx = ctx_head_ ; ctx != 0 ; ctx = ctx->nxt_)
8960 {
8961 /* if we've already set up this level, return its variable */
8962 if (ctx->level_ == level)
8963 {
8964 /* set the caller's variable number */
8965 *varnum = ctx->var_num_;
8966
8967 /* indicate that we found it */
8968 return TRUE;
8969 }
8970 }
8971
8972 /* didn't find it */
8973 return FALSE;
8974 }
8975
8976 /*
8977 * Get the immediately enclosing code body
8978 */
8979 CTPNCodeBody *CTPNCodeBodyBase::get_enclosing() const
8980 {
8981 /*
8982 * if we have no enclosing code body reference, we have no enclosing
8983 * code body
8984 */
8985 if (enclosing_code_body_ == 0)
8986 return 0;
8987
8988 /* get the code body from my enclosing code body reference object */
8989 return enclosing_code_body_->ptr;
8990 }
8991
8992 /*
8993 * Get the outermost enclosing code body
8994 */
8995 CTPNCodeBody *CTPNCodeBodyBase::get_outermost_enclosing() const
8996 {
8997 CTPNCodeBody *cur;
8998 CTPNCodeBody *nxt;
8999
9000 /*
9001 * scan each enclosing code body until we find one without an enclosing
9002 * code body
9003 */
9004 for (cur = 0, nxt = get_enclosing() ; nxt != 0 ;
9005 cur = nxt, nxt = nxt->get_enclosing()) ;
9006
9007 /* return what we found */
9008 return cur;
9009 }
9010
9011 /*
9012 * Get the base function symbol for a code body defining a modified
9013 * function (i.e., 'modify <funcname>...'). This is the function to which
9014 * 'replaced' refers within this code body and within nested code bodies.
9015 */
9016 class CTcSymFunc *CTPNCodeBodyBase::get_replaced_func() const
9017 {
9018 CTcSymFunc *b;
9019 CTPNCodeBody *enc;
9020
9021 /* if we have an associated function symbol, it's the base function */
9022 if ((b = get_func_sym()) != 0)
9023 return b->get_mod_base();
9024
9025 /*
9026 * if we have an enclosing code body, then 'replaced' here means the
9027 * same thing it does there, since we don't explicitly replace anything
9028 * here
9029 */
9030 if ((enc = get_enclosing()) != 0)
9031 return enc->get_replaced_func();
9032
9033 /* if we haven't found anything yet, we don't have a base function */
9034 return 0;
9035 }
9036
9037 /* ------------------------------------------------------------------------ */
9038 /*
9039 * Anonymous function
9040 */
9041
9042 /*
9043 * mark as replaced/obsolete
9044 */
9045 void CTPNAnonFuncBase::set_replaced(int flag)
9046 {
9047 if (code_body_ != 0)
9048 code_body_->set_replaced(flag);
9049 }
9050
9051 /* ------------------------------------------------------------------------ */
9052 /*
9053 * Generic statement node
9054 */
9055
9056 /*
9057 * initialize at the tokenizer's current source file position
9058 */
9059 CTPNStmBase::CTPNStmBase()
9060 {
9061 /* get the current source location from the parser */
9062 init(G_prs->get_cur_desc(), G_prs->get_cur_linenum());
9063 }
9064
9065 /*
9066 * log an error at this statement's source file position
9067 */
9068 void CTPNStmBase::log_error(int errnum, ...) const
9069 {
9070 va_list marker;
9071
9072 /* display the message */
9073 va_start(marker, errnum);
9074 G_tcmain->v_log_error(file_, linenum_, TC_SEV_ERROR, errnum, marker);
9075 va_end(marker);
9076 }
9077
9078 /*
9079 * log a warning at this statement's source file position
9080 */
9081 void CTPNStmBase::log_warning(int errnum, ...) const
9082 {
9083 va_list marker;
9084
9085 /* display the message */
9086 va_start(marker, errnum);
9087 G_tcmain->v_log_error(file_, linenum_, TC_SEV_WARNING, errnum, marker);
9088 va_end(marker);
9089 }
9090
9091 /*
9092 * Generate code for a sub-statement
9093 */
9094 void CTPNStmBase::gen_code_substm(CTPNStm *substm)
9095 {
9096 /* set the error reporting location to refer to the sub-statement */
9097 G_tok->set_line_info(substm->get_source_desc(),
9098 substm->get_source_linenum());
9099
9100 /* generate code for the sub-statement */
9101 substm->gen_code(TRUE, TRUE);
9102
9103 /* restore the error reporting location to the main statement */
9104 G_tok->set_line_info(get_source_desc(), get_source_linenum());
9105 }
9106
9107 /* ------------------------------------------------------------------------ */
9108 /*
9109 * superclass record
9110 */
9111
9112 /*
9113 * get my symbol
9114 */
9115 CTcSymbol *CTPNSuperclass::get_sym() const
9116 {
9117 /* if we know the symbol already, return it directly */
9118 if (sym_ != 0)
9119 return sym_;
9120
9121 /* look up my symbol by name in the global symbol table */
9122 return G_prs->get_global_symtab()->find(sym_txt_, sym_len_);
9123 }
9124
9125 /*
9126 * am I a subclass of the given class?
9127 */
9128 int CTPNSuperclass::is_subclass_of(const CTPNSuperclass *other) const
9129 {
9130 /*
9131 * if my name matches, we're a subclass (we are a subclass of
9132 * ourselves)
9133 */
9134 if (other->sym_len_ == sym_len_
9135 && memcmp(other->sym_txt_, sym_txt_, sym_len_) == 0)
9136 return TRUE;
9137
9138 /*
9139 * We're a subclass if any of our superclasses are subclasses of the
9140 * given object. Get my object symbol, and make sure it's really a
9141 * tads-object - if it's not, we're definitely not a subclass of
9142 * anything.
9143 */
9144 CTcSymObj *sym = (CTcSymObj *)get_sym();
9145 if (sym == 0
9146 || sym->get_type() != TC_SYM_OBJ
9147 || sym->get_metaclass() != TC_META_TADSOBJ)
9148 return FALSE;
9149
9150 /* scan our symbol's superclass list for a match */
9151 for (CTPNSuperclass *sc = sym->get_sc_name_head() ;
9152 sc != 0 ; sc = sc->nxt_)
9153 {
9154 /*
9155 * if this one's a subclass of the given class, we're a subclass
9156 * as well, since we're a subclass of this superclass
9157 */
9158 if (sc->is_subclass_of(other))
9159 return TRUE;
9160 }
9161
9162 /*
9163 * we didn't find any superclass that's a subclass of the given
9164 * class, so we're not a subclass of the given class
9165 */
9166 return FALSE;
9167 }
9168
9169
9170 /* ------------------------------------------------------------------------ */
9171 /*
9172 * 'return' statement
9173 */
9174
9175 /*
9176 * fold constants
9177 */
9178 CTcPrsNode *CTPNStmReturnBase::fold_constants(CTcPrsSymtab *symtab)
9179 {
9180 /* set our location for any errors that occur */
9181 G_tok->set_line_info(get_source_desc(), get_source_linenum());
9182
9183 /* fold constants in the expression, if we have one */
9184 if (expr_ != 0)
9185 expr_ = expr_->fold_constants(symtab);
9186
9187 /* we are not directly changed by this operation */
9188 return this;
9189 }
9190
9191 /* ------------------------------------------------------------------------ */
9192 /*
9193 * Formal type list
9194 */
9195
9196 /*
9197 * add a typed parameter to the list - 'tok' is the symbol giving the type
9198 * name
9199 */
9200 void CTcFormalTypeList::add_typed_param(const CTcToken *tok)
9201 {
9202 add(new (G_prsmem) CTcFormalTypeEle(tok->get_text(), tok->get_text_len()));
9203 }
9204
9205 /* add an untyped parameter to the list */
9206 void CTcFormalTypeList::add_untyped_param()
9207 {
9208 add(new (G_prsmem) CTcFormalTypeEle());
9209 }
9210
9211 /* add a list element */
9212 void CTcFormalTypeList::add(CTcFormalTypeEle *ele)
9213 {
9214 /* link it into our list */
9215 if (tail_ != 0)
9216 tail_->nxt_ = ele;
9217 else
9218 head_ = ele;
9219 tail_ = ele;
9220 ele->nxt_ = 0;
9221 }
9222
9223 /*
9224 * create a decorated name token for the multi-method defined by the given
9225 * function name and our type list
9226 */
9227 void CTcFormalTypeList::decorate_name(CTcToken *decorated_name,
9228 const CTcToken *func_base_name)
9229 {
9230 CTcFormalTypeEle *ele;
9231 size_t len;
9232 const char *p;
9233
9234 /* figure out how much space we need for the decorated name */
9235 for (len = func_base_name->get_text_len() + 1, ele = head_ ;
9236 ele != 0 ; ele = ele->nxt_)
9237 {
9238 /* add this type name's length, if there's a name */
9239 if (ele->name_ != 0)
9240 len += ele->name_len_;
9241
9242 /* add a semicolon after the type */
9243 len += 1;
9244 }
9245
9246 /* add "...;" if it's varargs */
9247 if (varargs_)
9248 len += 4;
9249
9250 /* allocate space for the name */
9251 G_tok->reserve_source(len);
9252
9253 /* start with the function name */
9254 p = G_tok->store_source_partial(func_base_name->get_text(),
9255 func_base_name->get_text_len());
9256
9257 /* add a "*" separator for the multi-method indicator */
9258 G_tok->store_source_partial("*", 1);
9259
9260 /* add each type name */
9261 for (ele = head_ ; ele != 0 ; ele = ele->nxt_)
9262 {
9263 /* add the type, if it has one (if not, leave the type empty) */
9264 if (ele->name_ != 0)
9265 G_tok->store_source_partial(ele->name_, ele->name_len_);
9266
9267 /* add a semicolon to terminate the parameter name */
9268 G_tok->store_source_partial(";", 1);
9269 }
9270
9271 /* add the varargs indicator ("...;"), if applicable */
9272 if (varargs_)
9273 G_tok->store_source_partial("...;", 4);
9274
9275 /* null-terminate it */
9276 G_tok->store_source_partial("\0", 1);
9277
9278 /* set the decorated token name */
9279 decorated_name->settyp(TOKT_SYM);
9280 decorated_name->set_text(p, len);
9281 }
9282
9283 /* formal list element - construction */
9284 CTcFormalTypeEle::CTcFormalTypeEle(const char *name, size_t len)
9285 {
9286 name_ = new (G_prsmem) char[len + 1];
9287 memcpy(name_, name, len);
9288 name_len_ = len;
9289 }