Debian Codegraph @

terps/tads/tads3/tct3stm.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/tads3/TCT3STM.CPP,v 1.1 1999/07/11 00:46:57 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 tct3stm.cpp - TADS 3 Compiler - T3 VM Code Generator - statement classes
15 Function
16 Generate code for the T3 VM. This file contains statement classes,
17 in order to segregate the code generation classes required for the
18 full compiler from those required for subsets that require only
19 expression parsing (such as debuggers).
20 Notes
21
22 Modified
23 05/08/99 MJRoberts - Creation
24 */
25
26 #include <stdio.h>
27
28 #include "t3std.h"
29 #include "os.h"
30 #include "tcprs.h"
31 #include "tct3.h"
32 #include "tcgen.h"
33 #include "vmtype.h"
34 #include "vmwrtimg.h"
35 #include "vmfile.h"
36 #include "tcmain.h"
37 #include "tcerr.h"
38
39
40 /* ------------------------------------------------------------------------ */
41 /*
42 * 'if' statement
43 */
44
45 /*
46 * generate code
47 */
48 void CTPNStmIf::gen_code(int, int)
49 {
50 /* add a line record */
51 add_debug_line_rec();
52
53 /*
54 * if the condition has a constant value, don't bother generating
55 * code for both branches
56 */
57 if (cond_expr_->is_const())
58 {
59 int val;
60
61 /* determine whether it's true or false */
62 val = cond_expr_->get_const_val()->get_val_bool();
63
64 /*
65 * Warn about it if it's always false (in which case the 'then'
66 * code is unreachable); or it's always true and we have an
67 * 'else' part (since the 'else' part is unreachable). Don't
68 * warn if it's true and there's no 'else' part, since this
69 * merely means that there's some redundant source code, but
70 * will have no effect on the generated code.
71 */
72 if (!val)
73 {
74 /*
75 * It's false - the 'then' part cannot be executed. If this
76 * isn't a compile-time constant expression, warn about it.
77 */
78 if (!cond_expr_->get_const_val()->is_ctc())
79 log_warning(TCERR_IF_ALWAYS_FALSE);
80
81 /* generate the 'else' part if there is one */
82 if (else_part_ != 0)
83 gen_code_substm(else_part_);
84 }
85 else
86 {
87 /* it's true - the 'else' part cannot be executed */
88 if (else_part_ != 0)
89 log_warning(TCERR_IF_ALWAYS_TRUE);
90
91 /* generate the 'then' part */
92 if (then_part_ != 0)
93 gen_code_substm(then_part_);
94 }
95
96 /* we're done */
97 return;
98 }
99
100 /*
101 * If both the 'then' and 'else' parts are null statements, we're
102 * evaluating the condition purely for side effects. Simply
103 * evaluate the condition in this case, since there's no need to so
104 * much as test the condition once evaluated.
105 */
106 if (then_part_ == 0 && else_part_ == 0)
107 {
108 /* generate the condition, discarding the result */
109 cond_expr_->gen_code(TRUE, TRUE);
110
111 /* we're done */
112 return;
113 }
114
115 /*
116 * The condition is non-constant, and we have at least one subclause,
117 * so we must evaluate the condition expression. To minimize the
118 * amount of jumping, check whether we have a true part, else part, or
119 * both, and generate the branching accordingly.
120 */
121 if (then_part_ != 0)
122 {
123 CTcCodeLabel *lbl_else;
124 CTcCodeLabel *lbl_end;
125
126 /*
127 * We have a true part, so we will want to evaluate the expression
128 * and jump past the true part if the expression is false. Create
129 * a label for the false branch.
130 */
131 lbl_else = G_cs->new_label_fwd();
132
133 /* generate the condition expression */
134 cond_expr_->gen_code_cond(0, lbl_else);
135
136 /* generate the 'then' part */
137 gen_code_substm(then_part_);
138
139 /* if there's an 'else' part, generate it */
140 if (else_part_ != 0)
141 {
142 /* at the end of the 'then' part, jump past the 'else' part */
143 lbl_end = gen_jump_ahead(OPC_JMP);
144
145 /* this is the start of the 'else' part */
146 def_label_pos(lbl_else);
147
148 /* generate the 'else' part */
149 gen_code_substm(else_part_);
150
151 /* set the label for the jump over the 'else' part */
152 def_label_pos(lbl_end);
153 }
154 else
155 {
156 /*
157 * there's no 'else' part - set the label for the jump past the
158 * 'then' part
159 */
160 def_label_pos(lbl_else);
161 }
162 }
163 else
164 {
165 CTcCodeLabel *lbl_end;
166
167 /*
168 * There's no 'then' part, so there must be an 'else' part (we
169 * wouldn't have gotten this far if both 'then' and 'else' are
170 * empty). To minimize branching, evaluate the condition and jump
171 * past the 'else' part if the condition is true, falling through
172 * to the 'else' part otherwise. Create a label for the end of the
173 * statement, which is also the empty 'then' part.
174 */
175 lbl_end = G_cs->new_label_fwd();
176
177 /* evaluate the condition and jump to the end if it's true */
178 cond_expr_->gen_code_cond(lbl_end, 0);
179
180 /* generate the 'else' part */
181 gen_code_substm(else_part_);
182
183 /* set the label for the jump over the 'else' part */
184 def_label_pos(lbl_end);
185 }
186 }
187
188 /* ------------------------------------------------------------------------ */
189 /*
190 * 'for' statement
191 */
192
193 /*
194 * generate code
195 */
196 void CTPNStmFor::gen_code(int, int)
197 {
198 CTcCodeLabel *top_lbl;
199 CTcCodeLabel *end_lbl;
200 CTcCodeLabel *cont_lbl;
201 CTPNStmEnclosing *old_enclosing;
202 CTcPrsSymtab *old_frame;
203
204 /* set my local frame if necessary */
205 old_frame = G_cs->set_local_frame(symtab_);
206
207 /*
208 * add a line record - note that we add the line record after
209 * setting up the local frame, so that the 'for' statement itself
210 * appears within its own inner scope
211 */
212 add_debug_line_rec();
213
214 /* push the enclosing statement */
215 old_enclosing = G_cs->set_enclosing(this);
216
217 /* if there's an initializer expression, generate it */
218 if (init_expr_ != 0)
219 init_expr_->gen_code(TRUE, TRUE);
220
221 /* set the label for the top of the loop */
222 top_lbl = new_label_here();
223
224 /* allocate a forward label for 'continue' jumps */
225 cont_lbl = G_cs->new_label_fwd();
226
227 /* allocate a forward label for the end of the loop */
228 end_lbl = G_cs->new_label_fwd();
229
230 /* generate the implicit conditions for any 'in' clauses */
231 for (CTPNForIn *i = in_exprs_ ; i != 0 ; i = i->getnxt())
232 i->gen_forstm_cond(end_lbl);
233
234 /*
235 * If there's an explicit condition clause, generate its code, jumping
236 * to the end of the loop if the condition is false.
237 */
238 if (cond_expr_ != 0)
239 cond_expr_->gen_code_cond(0, end_lbl);
240
241 /*
242 * set our labels, so that 'break' and 'continue' statements in our
243 * body will know where to go
244 */
245 break_lbl_ = end_lbl;
246 cont_lbl_ = cont_lbl;
247
248 /* if we have a body, generate it */
249 if (body_stm_ != 0)
250 gen_code_substm(body_stm_);
251
252 /*
253 * add another line record - we're now generating code again for the
254 * original 'for' line, even though it's after the body
255 */
256 //$$$ add_debug_line_rec();
257
258 /* this is where we come for 'continue' statements */
259 def_label_pos(cont_lbl);
260
261 /* generate the reinitializer expression, if we have one */
262 if (reinit_expr_ != 0)
263 reinit_expr_->gen_code(TRUE, TRUE);
264
265 /* generate the implicit reinitializers for any 'in' clauses */
266 for (CTPNForIn *i = in_exprs_ ; i != 0 ; i = i->getnxt())
267 i->gen_forstm_reinit();
268
269 /* jump back to the top of the loop */
270 G_cg->write_op(OPC_JMP);
271 G_cs->write_ofs2(top_lbl, 0);
272
273 /*
274 * we're at the end of the loop - this is where we jump for 'break'
275 * and when the condition becomes false
276 */
277 def_label_pos(end_lbl);
278
279 /* restore the enclosing statement */
280 G_cs->set_enclosing(old_enclosing);
281
282 /* restore the enclosing local scope */
283 G_cs->set_local_frame(old_frame);
284 }
285
286 /* ------------------------------------------------------------------------ */
287 /*
288 * 'for var in expr' node
289 */
290
291 /*
292 * Generate code. This is called during the initializer phase of the 'for'
293 * that we're part of. We create the collection enumerator and assign the
294 * first value from the enumerator to the lvalue.
295 */
296 void CTPNVarIn::gen_code(int, int)
297 {
298 /* generate the iterator initializer */
299 gen_iter_init(expr_, iter_local_id_, "for");
300 }
301
302 /*
303 * Static method: generate the iterator initializer
304 */
305 void CTPNVarIn::gen_iter_init(CTcPrsNode *coll_expr, int iter_local_id,
306 const char *kw)
307 {
308 /*
309 * Look up the createIterator property of the Collection metaclass.
310 * This property is defined by the Collection specification as the
311 * property in the first (zeroeth) slot in the method table for
312 * Collection. If Collection isn't defined, or this slot isn't
313 * defined, it's an error.
314 */
315 CTcPrsNode *create_iter = G_cg->get_metaclass_prop("collection", 0);
316
317 /* if we didn't find the property, it's an error */
318 #if 0 /* GLK: Modified from upstream. */
319 if (create_iter != VM_INVALID_PROP)
320 #else
321 if (create_iter != 0)
322 #endif
323 {
324 /*
325 * generate a call to the createIterator() property on the
326 * collection expression
327 */
328 if (coll_expr != 0)
329 coll_expr->gen_code_member(FALSE, create_iter, FALSE, 0, FALSE, 0);
330
331 /* assign the result to the internal iterator stack local */
332 CTcSymLocal::s_gen_code_setlcl_stk(iter_local_id, FALSE);
333 }
334 else
335 {
336 /* tell them about the problem */
337 G_tok->log_error(TCERR_FOREACH_NO_CREATEITER, kw);
338 }
339 }
340
341 /*
342 * Generate code for the condition portion of the 'for'. We check to see
343 * if there's a next value: if so we fetch it into our lvalue, it not we
344 * break the loop.
345 */
346 void CTPNVarIn::gen_forstm_cond(CTcCodeLabel *endlbl)
347 {
348 /* generate the code */
349 gen_iter_cond(lval_, iter_local_id_, endlbl, "for");
350 }
351
352 /*
353 * Generate code for the condition portion of a for..in or a foreach..in.
354 */
355 void CTPNVarIn::gen_iter_cond(CTcPrsNode *lval, int iter_local_id,
356 CTcCodeLabel *&end_lbl, const char *kw)
357 {
358 #if 1
359 /* if the caller didn't provide an end-of-loop label, create one */
360 if (end_lbl == 0)
361 end_lbl = G_cs->new_label_fwd();
362
363 /*
364 * Generate the ITERNEXT <iterator local>, <end offset>. This pushes
365 * the next iterator value if available, otherwise jumps to the end
366 * label (without pushing anything onto the stack).
367 */
368 G_cg->write_op(OPC_ITERNEXT);
369 G_cs->write2(iter_local_id);
370 G_cs->write_ofs2(end_lbl, 0);
371
372 /* we're on the looping branch - ITERNEXT pushed the next value */
373 G_cg->note_push();
374
375 /* assign the next value to the loop control lvalue */
376 if (lval != 0)
377 lval->gen_code_asi(TRUE, 1, TC_ASI_SIMPLE, "=", 0, FALSE, TRUE, 0);
378 else
379 {
380 G_cg->write_op(OPC_DISC);
381 G_cg->note_pop();
382 }
383
384 #else
385 /*
386 * Look up Iterator.getNext() (iterator metaclass method index 0) and
387 * Iterator.isNextAvailable() (index 1).
388 */
389 CTcPrsNode *get_next = G_cg->get_metaclass_prop("iterator", 0);
390 CTcPrsNode *next_avail = G_cg->get_metaclass_prop("iterator", 1);
391
392 /* generate the isNextAvailable test */
393 if (next_avail != 0)
394 {
395 /* get the internal iterator local */
396 CTcSymLocal::s_gen_code_getlcl(iter_local_id, FALSE);
397
398 /* generate a call to the property */
399 CTcPrsNode::s_gen_member_rhs(
400 FALSE, next_avail, FALSE, 0, FALSE, FALSE);
401
402 /*
403 * generate a jump to the end of the loop, creating the label if
404 * the caller didn't already
405 */
406 if (end_lbl != 0)
407 {
408 /* jump to the caller's end label */
409 G_cg->write_op(OPC_JF);
410 G_cs->write_ofs2(end_lbl, 0);
411 }
412 else
413 {
414 /* we need a new label */
415 end_lbl = gen_jump_ahead(OPC_JF);
416 }
417
418 /* the JF pops an element off the stack */
419 G_cg->note_pop();
420 }
421 else
422 {
423 /* this property is required to be defined - this is an error */
424 G_tok->log_error(TCERR_FOREACH_NO_ISNEXTAVAIL, kw);
425
426 /*
427 * generate an arbitrary 'end' label if the caller didn't already
428 * create one - we're not going to end up generating valid code
429 * anyway, but since we're not going to abort code generation,
430 * it'll avoid problems elsewhere if we have a valid label assigned
431 */
432 if (end_lbl == 0)
433 end_lbl = new_label_here();
434 }
435
436 /* generate the code to get the next element of the iteration */
437 if (get_next != 0)
438 {
439 /* get the internal iterator local */
440 CTcSymLocal::s_gen_code_getlcl(iter_local_id, FALSE);
441
442 /* generate a call to the property */
443 CTcPrsNode::s_gen_member_rhs(FALSE, get_next, FALSE, 0, FALSE, FALSE);
444
445 /* assign the result to the iterator lvalue */
446 if (lval != 0)
447 lval->gen_code_asi(TRUE, 1, TC_ASI_SIMPLE, "=", 0, FALSE, TRUE, 0);
448 }
449 else
450 {
451 /* this property is required to be defined - this is an error */
452 G_tok->log_error(TCERR_FOREACH_NO_GETNEXT, kw);
453 }
454 #endif
455 }
456
457 /*
458 * Generate code for the reinit portion of the 'for'. We do nothing on
459 * this step; we do the test and fetch as one operation in the condition
460 * instead, since the iterator test has to be done ahead of the fetch.
461 */
462 void CTPNVarIn::gen_forstm_reinit()
463 {
464 /* do nothing on this phase */
465 }
466
467
468 /* ------------------------------------------------------------------------ */
469 /*
470 * 'for var in from..to' node
471 */
472
473 /*
474 * Generate code. This is called during the initializer pharse of the
475 * 'for' that we're part of. We evaluate the 'from' and 'to' expressions,
476 * assign the 'from' to the lvalue, and save the 'to' in a private local
477 * variable.
478 */
479 void CTPNVarInRange::gen_code(int, int)
480 {
481 /* assign the 'from' expression to the lvalue */
482 lval_->gen_code_asi(TRUE, 1, TC_ASI_SIMPLE, "=", from_expr_,
483 FALSE, TRUE, 0);
484
485 /*
486 * if the 'to' expression is non-constant, evaluate it and save it in a
487 * local, so that we don't have to re-evaluate it on each iteration
488 */
489 if (!to_expr_->is_const())
490 {
491 /* evaluate the 'to' expression */
492 to_expr_->gen_code(FALSE, FALSE);
493
494 /* assign it to our stack local */
495 CTcSymLocal::s_gen_code_setlcl_stk(to_local_id_, FALSE);
496 }
497
498 /*
499 * likewise, if there's a non-constant 'step' expression, evaluate it
500 * and store it in our step stack local
501 */
502 if (step_expr_ != 0 && !step_expr_->is_const())
503 {
504 /* generate the step expression value */
505 step_expr_->gen_code(FALSE, FALSE);
506
507 /* generate the assignment to our local */
508 CTcSymLocal::s_gen_code_setlcl_stk(step_local_id_, FALSE);
509
510 /* replace the step expression with the local */
511 step_expr_ = new CTPNSymResolved(new CTcSymLocal(
512 ".step", 5, FALSE, FALSE, step_local_id_));
513 }
514 }
515
516 /*
517 * Generate code for the condition portion of the 'for'. We test our
518 * lvalue to see if we've passed the 'to' limit, in which case we break out
519 * of the loop.
520 */
521 void CTPNVarInRange::gen_forstm_cond(CTcCodeLabel *endlbl)
522 {
523 /* push the lvalue */
524 lval_->gen_code(FALSE, FALSE);
525
526 /*
527 * push the 'to' expression - if it's constant, generate the constant
528 * expression value, otherwise get the local
529 */
530 if (to_expr_->is_const())
531 to_expr_->gen_code(FALSE, FALSE);
532 else
533 CTcSymLocal::s_gen_code_getlcl(to_local_id_, FALSE);
534
535 /*
536 * If the step expression is a constant, compare based on the sign of
537 * the constant expression: if positive, we stop when the lval is
538 * greater than the 'to' limit; if negative, we stop when the lval is
539 * less than to 'to' limit. If the expression isn't a constant, we
540 * have to test the sign at run-time.
541 */
542 int s = 0;
543 if (step_expr_ == 0)
544 {
545 /* no step expression -> default step is 1, sign is positive */
546 s = 1;
547 }
548 else if (step_expr_->is_const())
549 {
550 /* explicit step expression with a constant value - check the type */
551 switch (step_expr_->get_const_val()->get_type())
552 {
553 case TC_CVT_INT:
554 /* integer - get its sign */
555 s = step_expr_->get_const_val()->get_val_int() < 0 ? -1 : 1;
556 break;
557
558 case TC_CVT_FLOAT:
559 /* BigNumber value - check for a '-' */
560 s = step_expr_->get_const_val()->get_val_float()[0] == '-'
561 ? -1 : 1;
562 break;
563
564 default:
565 /* others will have to be interpreted at run-time */
566 s = 0;
567 break;
568 }
569 }
570
571 /*
572 * if we have a known sign, generate a fixed test, otherwise generate a
573 * run-time test
574 */
575 if (s > 0)
576 {
577 /* positive constant - we're looping up to the 'to' limit */
578 G_cg->write_op(OPC_JGT);
579 G_cs->write_ofs2(endlbl, 0);
580
581 /* JGT pops 2 */
582 G_cg->note_pop(2);
583 }
584 else if (s < 0)
585 {
586 /* negative constant - we're looping down to the 'to' limit */
587 G_cg->write_op(OPC_JLT);
588 G_cs->write_ofs2(endlbl, 0);
589
590 /* JLT pops 2 */
591 G_cg->note_pop(2);
592 }
593 else
594 {
595 /*
596 * Variable step - generate a run-time test:
597 *
598 *. ; test the sign of the step expression: if step < 0 goto $1
599 *. push <step>
600 *. push 0
601 *. jlt $1
602 *. ; positive branch: if lval > to goto endlbl else goto $2
603 *. jgt endlbl
604 *. jmp $2
605 *. ; negative branch: if lval < to goto endlbl
606 *. $1:
607 *. jlt endlbl
608 *. ; end of test
609 *. $2:
610 */
611
612 /* push <step>; push 0; jlt $1 */
613 step_expr_->gen_code(FALSE, FALSE);
614 G_cg->write_op(OPC_PUSH_0);
615 G_cg->note_push();
616 CTcCodeLabel *l1 = gen_jump_ahead(OPC_JLT);
617 G_cg->note_pop(2);
618
619 /* positive branch: jgt endlbl; jmp $2 */
620 G_cg->write_op(OPC_JGT);
621 G_cs->write_ofs2(endlbl, 0);
622 CTcCodeLabel *l2 = gen_jump_ahead(OPC_JMP);
623
624 /* negative branch: $1: jlt endlbl */
625 def_label_pos(l1);
626 G_cg->write_op(OPC_JLT);
627 G_cs->write_ofs2(endlbl, 0);
628
629 /* $2: */
630 def_label_pos(l2);
631
632 /*
633 * we took one or the other of the positive or negative branch, and
634 * each one did a JxT that popped two elements
635 */
636 G_cg->note_pop(2);
637 }
638 }
639
640 /*
641 * Generate code for the reinit portion of the 'for'. We add 'step' to our
642 * lvalue.
643 */
644 void CTPNVarInRange::gen_forstm_reinit()
645 {
646 /*
647 * If we have a step expression, generate "lval += step". Otherwise
648 * just generate "++lval".
649 */
650 if (step_expr_ != 0)
651 {
652 /* generate "lval += step" */
653 CTPNAddAsi_gen_code(lval_, step_expr_, TRUE);
654 }
655 else
656 {
657 /* increment the control variable */
658 CTPNPreInc_gen_code(lval_, TRUE);
659 }
660 }
661
662
663 /* ------------------------------------------------------------------------ */
664 /*
665 * 'foreach' statement
666 */
667
668 /*
669 * generate code
670 */
671 void CTPNStmForeach::gen_code(int, int)
672 {
673 /* set my local frame if necessary */
674 CTcPrsSymtab *old_frame = G_cs->set_local_frame(symtab_);
675
676 /*
677 * add a line record - note that we add the line record after
678 * setting up the local frame, so that the 'for' statement itself
679 * appears within its own inner scope
680 */
681 add_debug_line_rec();
682
683 /* push the enclosing statement */
684 CTPNStmEnclosing *old_enclosing = G_cs->set_enclosing(this);
685
686 /* if there's a collection expression, generate it */
687 if (coll_expr_ != 0)
688 CTPNVarIn::gen_iter_init(coll_expr_, iter_local_id_, "foreach");
689
690 /* set the label for the top of the loop */
691 CTcCodeLabel *top_lbl = new_label_here();
692
693 /* check for and fetch the next value */
694 CTcCodeLabel *end_lbl = 0;
695 CTPNVarIn::gen_iter_cond(iter_expr_, iter_local_id_, end_lbl, "foreach");
696
697 /*
698 * set our labels, so that 'break' and 'continue' statements in our
699 * body will know where to go
700 */
701 break_lbl_ = end_lbl;
702 cont_lbl_ = top_lbl;
703
704 /* if we have a body, generate it */
705 if (body_stm_ != 0)
706 gen_code_substm(body_stm_);
707
708 /*
709 * add another line record - we're now generating code again for the
710 * original 'foreach' line, even though it's after the body
711 */
712 //$$$ add_debug_line_rec();
713
714 /* jump back to the top of the loop */
715 G_cg->write_op(OPC_JMP);
716 G_cs->write_ofs2(top_lbl, 0);
717
718 /*
719 * we're at the end of the loop - this is where we jump for 'break'
720 * and when the condition becomes false
721 */
722 if (end_lbl != 0)
723 def_label_pos(end_lbl);
724
725 /* restore the enclosing statement */
726 G_cs->set_enclosing(old_enclosing);
727
728 /* restore the enclosing local scope */
729 G_cs->set_local_frame(old_frame);
730 }
731
732 /* ------------------------------------------------------------------------ */
733 /*
734 * 'while' statement
735 */
736
737 /*
738 * generate code
739 */
740 void CTPNStmWhile::gen_code(int, int)
741 {
742 CTcCodeLabel *top_lbl;
743 CTcCodeLabel *end_lbl;
744 CTPNStmEnclosing *old_enclosing;
745
746 /* add a line record */
747 add_debug_line_rec();
748
749 /* push the enclosing statement */
750 old_enclosing = G_cs->set_enclosing(this);
751
752 /* set the label for the top of the loop */
753 top_lbl = new_label_here();
754
755 /* generate a label for the end of the loop */
756 end_lbl = G_cs->new_label_fwd();
757
758 /* generate the condition, jumping to the end of the loop if false */
759 cond_expr_->gen_code_cond(0, end_lbl);
760
761 /*
762 * set the 'break' and 'continue' label in our node, so that 'break'
763 * and 'continue' statements in subnodes can find the labels during
764 * code generation
765 */
766 break_lbl_ = end_lbl;
767 cont_lbl_ = top_lbl;
768
769 /* if we have a body, generate it */
770 if (body_stm_ != 0)
771 gen_code_substm(body_stm_);
772
773 /*
774 * add another line record - the jump back to the top of the loop is
775 * part of the 'while' itself
776 */
777 //$$$ add_debug_line_rec();
778
779 /* jump back to the top of the loop */
780 G_cg->write_op(OPC_JMP);
781 G_cs->write_ofs2(top_lbl, 0);
782
783 /*
784 * we're at the end of the loop - this is where we jump for 'break'
785 * and when the condition becomes false
786 */
787 def_label_pos(end_lbl);
788
789 /* restore the enclosing statement */
790 G_cs->set_enclosing(old_enclosing);
791 }
792
793
794 /* ------------------------------------------------------------------------ */
795 /*
796 * 'do-while' statement
797 */
798
799 /*
800 * generate code
801 */
802 void CTPNStmDoWhile::gen_code(int, int)
803 {
804 CTcCodeLabel *top_lbl;
805 CTcCodeLabel *end_lbl;
806 CTcCodeLabel *cont_lbl;
807 CTPNStmEnclosing *old_enclosing;
808
809 /* add a line record */
810 add_debug_line_rec();
811
812 /* push the enclosing statement */
813 old_enclosing = G_cs->set_enclosing(this);
814
815 /* set the label for the top of the loop */
816 top_lbl = new_label_here();
817
818 /* create a label for after the loop, for any enclosed 'break's */
819 end_lbl = G_cs->new_label_fwd();
820
821 /*
822 * create a label for just before the expression, for any enclosed
823 * 'continue' statements
824 */
825 cont_lbl = G_cs->new_label_fwd();
826
827 /* set our 'break' and 'continue' labels in our node */
828 break_lbl_ = end_lbl;
829 cont_lbl_ = cont_lbl;
830
831 /* if we have a body, generate it */
832 if (body_stm_ != 0)
833 gen_code_substm(body_stm_);
834
835 /* set the debug source position to the 'while' clause's location */
836 add_debug_line_rec(while_desc_, while_linenum_);
837
838 /* put the 'continue' label here, just before the condition */
839 def_label_pos(cont_lbl);
840
841 /*
842 * Generate the condition. If the condition is true, jump back to the
843 * top label; otherwise fall through out of the loop structure.
844 */
845 cond_expr_->gen_code_cond(top_lbl, 0);
846
847 /* we're past the end of the loop - this is where we jump for 'break' */
848 def_label_pos(end_lbl);
849
850 /* restore the enclosing statement */
851 G_cs->set_enclosing(old_enclosing);
852 }
853
854
855 /* ------------------------------------------------------------------------ */
856 /*
857 * 'break' statement
858 */
859
860 /*
861 * generate code
862 */
863 void CTPNStmBreak::gen_code(int, int)
864 {
865 /* add a line record */
866 add_debug_line_rec();
867
868 /*
869 * ask the enclosing statement to do the work - if there's no
870 * enclosing statement, or none of the enclosing statements can
871 * perform the break, it's an error
872 */
873 if (G_cs->get_enclosing() == 0
874 || !G_cs->get_enclosing()->gen_code_break(lbl_, lbl_len_))
875 {
876 /*
877 * log the error - if there's a label, the problem is that we
878 * couldn't find the label, otherwise it's that we can't perform
879 * a 'break' here at all
880 */
881 if (lbl_ == 0)
882 G_tok->log_error(TCERR_INVALID_BREAK);
883 else
884 G_tok->log_error(TCERR_INVALID_BREAK_LBL, (int)lbl_len_, lbl_);
885 }
886 }
887
888 /* ------------------------------------------------------------------------ */
889 /*
890 * 'continue' statement
891 */
892
893 /*
894 * generate code
895 */
896 void CTPNStmContinue::gen_code(int, int)
897 {
898 /* add a line record */
899 add_debug_line_rec();
900
901 /*
902 * ask the enclosing statement to do the work - if there's no
903 * enclosing statement, or none of the enclosing statements can
904 * perform the break, it's an error
905 */
906 if (G_cs->get_enclosing() == 0
907 || !G_cs->get_enclosing()->gen_code_continue(lbl_, lbl_len_))
908 {
909 /*
910 * log the error - if there's a label, the problem is that we
911 * couldn't find the label, otherwise it's that we can't perform
912 * a 'break' here at all
913 */
914 if (lbl_ == 0)
915 G_tok->log_error(TCERR_INVALID_CONTINUE);
916 else
917 G_tok->log_error(TCERR_INVALID_CONT_LBL, (int)lbl_len_, lbl_);
918 }
919 }
920
921 /* ------------------------------------------------------------------------ */
922 /*
923 * 'switch' statement
924 */
925
926 /*
927 * generate code
928 */
929 void CTPNStmSwitch::gen_code(int, int)
930 {
931 CTPNStmSwitch *enclosing_switch;
932 int i;
933 char buf[VMB_DATAHOLDER + VMB_UINT2];
934 CTcCodeLabel *end_lbl;
935 CTPNStmEnclosing *old_enclosing;
936
937 /* add a line record */
938 add_debug_line_rec();
939
940 /* push the enclosing statement */
941 old_enclosing = G_cs->set_enclosing(this);
942
943 /*
944 * Generate the controlling expression. We want to keep the value,
945 * hence 'discard' is false, and we need assignment (not 'for
946 * condition') conversion rules, because we're going to use the
947 * value in direct comparisons
948 */
949 expr_->gen_code(FALSE, FALSE);
950
951 /* make myself the current innermost switch */
952 enclosing_switch = G_cs->set_switch(this);
953
954 /*
955 * if we can flow out of the switch, allocate a label for the end of
956 * the switch body
957 */
958 if ((get_control_flow(FALSE) & TCPRS_FLOW_NEXT) != 0)
959 end_lbl = G_cs->new_label_fwd();
960 else
961 end_lbl = 0;
962
963 /* the end label is the 'break' location for subnodes */
964 break_lbl_ = end_lbl;
965
966 /*
967 * Write my SWITCH opcode, and the placeholder case table. We'll
968 * fill in the case table with its real values as we encounter the
969 * cases in the course of generating the code. For now, all we know
970 * is the number of cases we need to put into the table.
971 */
972 G_cg->write_op(OPC_SWITCH);
973
974 /* the SWITCH opcode pops the controlling expression value */
975 G_cg->note_pop();
976
977 /* write the number of cases */
978 G_cs->write2(case_cnt_);
979
980 /*
981 * remember where the first case slot is - the 'case' parse nodes
982 * will use this to figure out where to write their slot data
983 */
984 case_slot_ofs_ = G_cs->get_ofs();
985
986 /*
987 * Write the placeholder case slots - each case slot gets a
988 * DATA_HOLDER for the case value, plus an INT2 for the branch
989 * offset. For now, completely zero each case slot.
990 */
991 memset(buf, 0, VMB_DATAHOLDER + VMB_UINT2);
992 for (i = 0 ; i < case_cnt_ ; ++i)
993 G_cs->write(buf, VMB_DATAHOLDER + VMB_UINT2);
994
995 /* write a placeholder for the default jump */
996 if (has_default_)
997 {
998 /*
999 * remember where the 'default' slot is, so that the 'default'
1000 * parse node can figure out where to write its branch offset
1001 */
1002 default_slot_ofs_ = G_cs->get_ofs();
1003
1004 /*
1005 * Write the placeholder for the 'default' slot - this just gets
1006 * an INT2 for the 'default' jump offset. As with the case
1007 * labels, just zero it for now; we'll fill it in later when we
1008 * encounter the 'default' case.
1009 */
1010 G_cs->write2(0);
1011 }
1012 else
1013 {
1014 /*
1015 * there's no default slot, so the 'default' slot is simply a
1016 * jump to the end of the switch body - generate a jump ahead to
1017 * our end label
1018 */
1019 G_cs->write_ofs2(end_lbl, 0);
1020 }
1021
1022 /*
1023 * generate the switch body - this will fill in the case table as we
1024 * encounter the 'case' nodes in the parse tree
1025 */
1026 if (body_ != 0)
1027 gen_code_substm(body_);
1028
1029 /*
1030 * We're past the body - if we have an end label, set it here. (We
1031 * won't have created an end label if control can't flow out of the
1032 * switch; this allows us to avoid generating unreachable instructions
1033 * after the switch, which would only increase the code size for no
1034 * reason.)
1035 */
1036 if (end_lbl != 0)
1037 def_label_pos(end_lbl);
1038
1039 /* restore the enclosing switch */
1040 G_cs->set_switch(enclosing_switch);
1041
1042 /* restore the enclosing statement */
1043 G_cs->set_enclosing(old_enclosing);
1044 }
1045
1046 /* ------------------------------------------------------------------------ */
1047 /*
1048 * 'case' label statement
1049 */
1050
1051 /*
1052 * generate code
1053 */
1054 void CTPNStmCase::gen_code(int, int)
1055 {
1056 ulong slot_ofs;
1057 ulong jump_ofs;
1058
1059 /*
1060 * we must have an active 'switch' statement, and our expression
1061 * value must be a constant -- if either of these is not true, we
1062 * have an internal error of some kind, because we should never get
1063 * this far if these conditions weren't true
1064 */
1065 if (G_cs->get_switch() == 0 || !expr_->is_const())
1066 G_tok->throw_internal_error(TCERR_GEN_BAD_CASE);
1067
1068 /* allocate our case slot from the enclosing 'switch' statement */
1069 slot_ofs = G_cs->get_switch()->alloc_case_slot();
1070
1071 /* write the case table entry as a DATAHOLDER value */
1072 G_cg->write_const_as_dh(G_cs, slot_ofs, expr_->get_const_val());
1073
1074 /*
1075 * Add the jump offset. This is the offset from this INT2 entry in
1076 * our case slot to the current output offset. The INT2 is offset
1077 * from the start of our slot by the DATAHOLDER value.
1078 */
1079 jump_ofs = G_cs->get_ofs() - (slot_ofs + VMB_DATAHOLDER);
1080 G_cs->write2_at(slot_ofs + VMB_DATAHOLDER, (int)jump_ofs);
1081
1082 /*
1083 * because we can jump here (via the case table), we cannot allow
1084 * peephole optimizations from past instructions - clear the
1085 * peephole
1086 */
1087 G_cg->clear_peephole();
1088
1089 /* generate our substatement, if we have one */
1090 if (stm_ != 0)
1091 gen_code_substm(stm_);
1092 }
1093
1094 /* ------------------------------------------------------------------------ */
1095 /*
1096 * 'default' label statement
1097 */
1098
1099 /*
1100 * generate code
1101 */
1102 void CTPNStmDefault::gen_code(int, int)
1103 {
1104 ulong slot_ofs;
1105 char buf[VMB_UINT2];
1106 ulong jump_ofs;
1107
1108 /*
1109 * we must have an active 'switch' statement -- if we don't, we have
1110 * an internal error of some kind, because we should never have
1111 * gotten this far
1112 */
1113 if (G_cs->get_switch() == 0)
1114 G_tok->throw_internal_error(TCERR_GEN_BAD_CASE);
1115
1116 /* ask the switch where our slot goes */
1117 slot_ofs = G_cs->get_switch()->get_default_slot();
1118
1119 /*
1120 * Set the jump offset. This is the offset from our slot entry in
1121 * the case table to the current output offset.
1122 */
1123 jump_ofs = G_cs->get_ofs() - slot_ofs;
1124 oswp2(buf, (int)jump_ofs);
1125
1126 /* write our slot entry to the case table */
1127 G_cs->write_at(slot_ofs, buf, VMB_UINT2);
1128
1129 /*
1130 * because we can jump here (via the case table), we cannot allow
1131 * peephole optimizations from past instructions - clear the
1132 * peephole
1133 */
1134 G_cg->clear_peephole();
1135
1136 /* generate our substatement, if we have one */
1137 if (stm_ != 0)
1138 gen_code_substm(stm_);
1139 }
1140
1141 /* ------------------------------------------------------------------------ */
1142 /*
1143 * code label statement
1144 */
1145
1146 /*
1147 * ininitialize
1148 */
1149 CTPNStmLabel::CTPNStmLabel(CTcSymLabel *lbl, CTPNStmEnclosing *enclosing)
1150 : CTPNStmLabelBase(lbl, enclosing)
1151 {
1152 /*
1153 * we don't have a 'goto' label yet - we'll allocate it on demand
1154 * during code generation (labels are local in scope to a code body
1155 * so we can't allocate this until code generation begins for our
1156 * containing code body)
1157 */
1158 goto_label_ = 0;
1159
1160 /*
1161 * we don't yet have a 'break' label - we'll allocate this when
1162 * someone first refers to it
1163 */
1164 break_label_ = 0;
1165 }
1166
1167 /*
1168 * get our code label
1169 */
1170 CTcCodeLabel *CTPNStmLabel::get_goto_label()
1171 {
1172 /* if we don't have a label already, allocate it */
1173 if (goto_label_ == 0)
1174 goto_label_ = G_cs->new_label_fwd();
1175
1176 /* return the label */
1177 return goto_label_;
1178 }
1179
1180 /*
1181 * generate code
1182 */
1183 void CTPNStmLabel::gen_code(int, int)
1184 {
1185 CTPNStmEnclosing *old_enclosing;
1186
1187 /* push the enclosing statement */
1188 old_enclosing = G_cs->set_enclosing(this);
1189
1190 /*
1191 * Define our label position - this is where we come if someone does
1192 * a 'goto' to this label. (Note that we might not have a 'goto'
1193 * label defined yet - if we weren't forward-referenced by a 'goto'
1194 * statement, we won't have a label defined. Call get_goto_label()
1195 * to ensure we create a label if it doesn't already exist.)
1196 */
1197 def_label_pos(get_goto_label());
1198
1199 /*
1200 * add the source location of the label - this probably will have no
1201 * effect, since we don't generate any code for the label itself,
1202 * but it's harmless so do it anyway to guard against weird cases
1203 */
1204 add_debug_line_rec();
1205
1206 /*
1207 * generate code for the labeled statement, discarding any
1208 * calculated value
1209 */
1210 if (stm_ != 0)
1211 gen_code_substm(stm_);
1212
1213 /*
1214 * If we have a 'break' label, it means that code within our labeled
1215 * statement (i.e., nested within the label) did a 'break' to leave
1216 * the labeled statement. The target of the break is the next
1217 * statement after the labeled statement, which comes next, so
1218 * define the label here.
1219 */
1220 if (break_label_ != 0)
1221 def_label_pos(break_label_);
1222
1223 /* restore the enclosing statement */
1224 G_cs->set_enclosing(old_enclosing);
1225 }
1226
1227
1228 /*
1229 * generate code for a 'break'
1230 */
1231 int CTPNStmLabel::gen_code_break(const textchar_t *lbl, size_t lbl_len)
1232 {
1233 /*
1234 * If the 'break' doesn't specify a label, inherit the default
1235 * handling, since we're not a default 'break' target. If there's a
1236 * label, and the label isn't our label, also inherit the default,
1237 * since the target lies somewhere else.
1238 */
1239 if (lbl == 0 || G_cs->get_goto_symtab() == 0
1240 || G_cs->get_goto_symtab()->find(lbl, lbl_len) != lbl_)
1241 return CTPNStmLabelBase::gen_code_break(lbl, lbl_len);
1242
1243 /*
1244 * if we don't yet have a 'break' label defined, define one now
1245 * (it's a forward declaration, because we won't know where it goes
1246 * until we finish generating the entire body of the statement
1247 * contained in the label)
1248 */
1249 if (break_label_ == 0)
1250 break_label_ = G_cs->new_label_fwd();
1251
1252 /* jump to the label */
1253 G_cg->write_op(OPC_JMP);
1254 G_cs->write_ofs2(break_label_, 0);
1255
1256 /* handled */
1257 return TRUE;
1258 }
1259
1260
1261 /*
1262 * generate code for a 'continue'
1263 */
1264 int CTPNStmLabel::gen_code_continue(const textchar_t *lbl, size_t lbl_len)
1265 {
1266 /*
1267 * If there's no label, inherit the default handling, since we're
1268 * not a default 'continue' target. If there's a label, and the
1269 * label isn't our label, also inherit the default, since the target
1270 * lies somewhere else.
1271 */
1272 if (lbl == 0 || G_cs->get_goto_symtab() == 0
1273 || G_cs->get_goto_symtab()->find(lbl, lbl_len) != lbl_)
1274 return CTPNStmLabelBase::gen_code_continue(lbl, lbl_len);
1275
1276 /*
1277 * It's a 'continue' with my label - ask my enclosed statement to do
1278 * the work; return failure if I have no enclosed statement. Note
1279 * that we use a special call - generate a *labeled* continue - to
1280 * let the statement know that it must perform the 'continue'
1281 * itself and cannot defer to enclosing statements.
1282 */
1283 if (stm_ != 0)
1284 return stm_->gen_code_labeled_continue();
1285 else
1286 return FALSE;
1287 }
1288
1289
1290 /* ------------------------------------------------------------------------ */
1291 /*
1292 * 'try'
1293 */
1294
1295 /*
1296 * generate code
1297 */
1298 void CTPNStmTry::gen_code(int, int)
1299 {
1300 ulong start_ofs;
1301 ulong end_ofs;
1302 CTPNStmCatch *cur_catch;
1303 CTcCodeLabel *end_lbl;
1304 CTPNStmEnclosing *old_enclosing;
1305 int finally_never_returns;
1306
1307 /* we have no end label yet */
1308 end_lbl = 0;
1309
1310 /*
1311 * add the source location of the 'try' - it probably won't be
1312 * needed, because we don't generate any code before the protected
1313 * body, but it's harmless and makes sure we have a good source
1314 * location in weird cases
1315 */
1316 add_debug_line_rec();
1317
1318 /* push the enclosing statement */
1319 old_enclosing = G_cs->set_enclosing(this);
1320
1321 /*
1322 * If we have a 'finally' clause, we must allocate a
1323 * forward-reference code label for it. We need to be able to reach
1324 * the 'finally' clause throughout generation of the protected code
1325 * and the 'catch' blocks.
1326 */
1327 if (finally_stm_ != 0)
1328 finally_lbl_ = G_cs->new_label_fwd();
1329 else
1330 finally_lbl_ = 0;
1331
1332 /* note where the protected code begins */
1333 start_ofs = G_cs->get_ofs();
1334
1335 /* generate the protected code */
1336 if (body_stm_ != 0)
1337 gen_code_substm(body_stm_);
1338
1339 /*
1340 * Check to see if we have a 'finally' block that never returns. If we
1341 * have a 'finally' block, and it doesn't flow to its next statement,
1342 * then our LJSR's to the 'finally' block will never return.
1343 */
1344 finally_never_returns =
1345 (finally_stm_ != 0
1346 && (finally_stm_->get_control_flow(FALSE) & TCPRS_FLOW_NEXT) == 0);
1347
1348 /*
1349 * if there's a "finally" clause, we must generate a local subroutine
1350 * call to the "finally" block
1351 */
1352 gen_jsr_finally();
1353
1354 /*
1355 * We must now jump past the "catch" and "finally" code blocks. If the
1356 * "finally" block itself doesn't flow to the next statement, then
1357 * there's no need to do this, since we'll never be reached here. If
1358 * there's no "finally" block, then we won't have LJSR'd anywhere, so
1359 * this code is definitely reachable.
1360 */
1361 if (!finally_never_returns)
1362 end_lbl = gen_jump_ahead(OPC_JMP);
1363
1364 /*
1365 * Note where the protected code ends - it ends at one byte below
1366 * the current write offset, because the current write offset is the
1367 * next byte we'll write. The code range we store in the exception
1368 * table is inclusive of the endpoints.
1369 */
1370 end_ofs = G_cs->get_ofs() - 1;
1371
1372 /* generate the 'catch' blocks */
1373 for (cur_catch = first_catch_stm_ ; cur_catch != 0 ;
1374 cur_catch = cur_catch->get_next_catch())
1375 {
1376 /* generate the 'catch' block */
1377 cur_catch->gen_code_catch(start_ofs, end_ofs);
1378
1379 /* call the 'finally' block after the 'catch' finishes */
1380 gen_jsr_finally();
1381
1382 /*
1383 * If there's a finally block, or there's another 'catch' after me,
1384 * generate a jump past the remaining catch/finally blocks.
1385 *
1386 * If we do have a finally that doesn't flow to the next statement
1387 * (i.e., we throw or return out of the finally), then there's no
1388 * need to generate a jump, since we'll never come back here from
1389 * the finally block.
1390 */
1391 if (!finally_never_returns
1392 && (finally_stm_ != 0 || cur_catch->get_next_catch() != 0))
1393 {
1394 /*
1395 * if we have no end label yet, generate one now - we might
1396 * not have one because we might not have been able to reach
1397 * any previous jump to the end of the catch (because we threw
1398 * or returned out of the end of all blocks to this point, for
1399 * example)
1400 */
1401 if (end_lbl == 0)
1402 {
1403 /* we have no label - generate a new one now */
1404 end_lbl = gen_jump_ahead(OPC_JMP);
1405 }
1406 else
1407 {
1408 /* we already have an end label - generate a jump to it */
1409 G_cg->write_op(OPC_JMP);
1410 G_cs->write_ofs2(end_lbl, 0);
1411 }
1412 }
1413 }
1414
1415 /*
1416 * Restore the enclosing statement. We enclose the protected code
1417 * and all of the 'catch' blocks, because all of these must leave
1418 * through the 'finally' handler. We do not, however, enclose the
1419 * 'finally' handler itself - once it's entered, we do not invoke it
1420 * again as it leaves.
1421 */
1422 G_cs->set_enclosing(old_enclosing);
1423
1424 /* generate the 'finally' block, if we have one */
1425 if (finally_stm_ != 0)
1426 {
1427 /*
1428 * Generate the 'finally' code. The 'finally' block is executed
1429 * for the 'try' block plus all of the 'catch' blocks, so the
1430 * ending offset is the current position (less one byte, since
1431 * the range is inclusive), which encompasses all of the 'catch'
1432 * blocks
1433 */
1434 finally_stm_->gen_code_finally(start_ofs, G_cs->get_ofs() - 1, this);
1435 }
1436
1437 /*
1438 * we're now past all of the "catch" and "finally" blocks, so we can
1439 * define the jump label for jumping past those blocks (we make this
1440 * jump from the end of the protected code) - note that we might not
1441 * have actually generated the label, since we might never have
1442 * reached any code which jumped to it
1443 */
1444 if (end_lbl != 0)
1445 def_label_pos(end_lbl);
1446 }
1447
1448 /*
1449 * Generate code for a 'break' within our protected code or a 'catch'.
1450 * We'll first generate a call to our 'finally' block, if we have one,
1451 * then let the enclosing statement handle the break.
1452 */
1453 int CTPNStmTry::gen_code_break(const textchar_t *lbl, size_t lbl_len)
1454 {
1455 /* if we have a 'finally' block, invoke it as a local subroutine call */
1456 gen_jsr_finally();
1457
1458 /*
1459 * If there's an enclosing statement, let it generate the break; if
1460 * there's not, return failure, because we're not a meaningful
1461 * target for break.
1462 */
1463 if (enclosing_)
1464 return enclosing_->gen_code_break(lbl, lbl_len);
1465 else
1466 return FALSE;
1467 }
1468
1469 /*
1470 * Generate code for a 'break' within our protected code or a 'catch'.
1471 * We'll first generate a call to our 'finally' block, if we have one,
1472 * then let the enclosing statement handle the break.
1473 */
1474 int CTPNStmTry::gen_code_continue(const textchar_t *lbl, size_t lbl_len)
1475 {
1476 /* if we have a 'finally' block, invoke it as a local subroutine call */
1477 gen_jsr_finally();
1478
1479 /*
1480 * if there's an enclosing statement, let it generate the continue;
1481 * if there's not, return failure, because we're not a meaningful
1482 * target for continue
1483 */
1484 if (enclosing_)
1485 return enclosing_->gen_code_continue(lbl, lbl_len);
1486 else
1487 return FALSE;
1488 }
1489
1490 /*
1491 * Generate a local subroutine call to our 'finally' block, if we have
1492 * one. This should be used when executing a break, continue, goto, or
1493 * return out of the protected code or a 'catch' block, or when merely
1494 * falling off the end of the protected code or 'catch' block.
1495 */
1496 void CTPNStmTry::gen_jsr_finally()
1497 {
1498 /* if we have a 'finally', call it */
1499 if (finally_lbl_ != 0)
1500 {
1501 /* generate the local subroutine call */
1502 G_cg->write_op(OPC_LJSR);
1503 G_cs->write_ofs2(finally_lbl_, 0);
1504
1505 /*
1506 * the LJSR pushes a value, which is then immediately popped (we
1507 * must note the push and pop because it affects our maximum
1508 * stack depth requirement)
1509 */
1510 G_cg->note_push();
1511 G_cg->note_pop();
1512
1513 /*
1514 * whatever follows the LJSR is logically at the end of the
1515 * 'finally' block
1516 */
1517 add_debug_line_rec(finally_stm_->get_end_desc(),
1518 finally_stm_->get_end_linenum());
1519 }
1520 }
1521
1522
1523 /* ------------------------------------------------------------------------ */
1524 /*
1525 * 'catch'
1526 */
1527
1528 /*
1529 * generate code
1530 */
1531 void CTPNStmCatch::gen_code(int, int)
1532 {
1533 /* this can't be called directly - use gen_code_catch() instead */
1534 G_tok->throw_internal_error(TCERR_CATCH_FINALLY_GEN_CODE);
1535 }
1536
1537 /*
1538 * generate code for the 'catch'
1539 */
1540 void CTPNStmCatch::gen_code_catch(ulong start_prot_ofs, ulong end_prot_ofs)
1541 {
1542 CTcSymbol *sym;
1543 ulong exc_obj_id;
1544 CTcPrsSymtab *old_frame;
1545
1546 /* add the source location of the 'catch' clause */
1547 add_debug_line_rec();
1548
1549 /* set the local scope */
1550 old_frame = G_cs->set_local_frame(symtab_);
1551
1552 /* look up the object defining the class of exceptions to catch */
1553 sym = G_cs->get_symtab()->find_or_def_undef(exc_class_,
1554 exc_class_len_, FALSE);
1555
1556 /* assume we won't find a valid object ID */
1557 exc_obj_id = VM_INVALID_OBJ;
1558
1559 /* if it's an object, get its ID */
1560 if (sym->get_type() == TC_SYM_OBJ)
1561 {
1562 /* get its object ID */
1563 exc_obj_id = ((CTcSymObj *)sym)->get_obj_id();
1564 }
1565 else if (sym->get_type() != TC_SYM_UNKNOWN)
1566 {
1567 /*
1568 * it's defined, but it's not an object - log an error (note
1569 * that we don't log an error if the symbol is undefined,
1570 * because find_or_def_undef() will already have logged an error
1571 * for us)
1572 */
1573 log_error(TCERR_CATCH_EXC_NOT_OBJ, (int)exc_class_len_, exc_class_);
1574 }
1575
1576 /* add our exception table entry */
1577 G_cg->get_exc_table()->add_catch(start_prot_ofs, end_prot_ofs,
1578 exc_obj_id, G_cs->get_ofs());
1579
1580 /* don't allow any peephole optimizations to affect this offset */
1581 G_cg->clear_peephole();
1582
1583 /*
1584 * the VM automatically pushes a value onto the stack to perform the
1585 * 'catch'
1586 */
1587 G_cg->note_push();
1588
1589 /*
1590 * generate a SETLCL for our formal parameter, so that the exception
1591 * object is stored in our local variable
1592 */
1593 exc_var_->gen_code_setlcl();
1594
1595 /* generate code for our statement, if we have one */
1596 if (body_ != 0)
1597 gen_code_substm(body_);
1598
1599 /* restore the enclosing local scope */
1600 G_cs->set_local_frame(old_frame);
1601 }
1602
1603 /* ------------------------------------------------------------------------ */
1604 /*
1605 * 'finally'
1606 */
1607
1608 /*
1609 * generate code
1610 */
1611 void CTPNStmFinally::gen_code(int, int)
1612 {
1613 /* this can't be called directly - use gen_code_finally() instead */
1614 G_tok->throw_internal_error(TCERR_CATCH_FINALLY_GEN_CODE);
1615 }
1616
1617
1618 /*
1619 * generate code for the 'finally'
1620 */
1621 void CTPNStmFinally::gen_code_finally(ulong start_prot_ofs,
1622 ulong end_prot_ofs,
1623 CTPNStmTry *try_stm)
1624 {
1625 CTPNStmEnclosing *old_enclosing;
1626
1627 /*
1628 * set the source location for our prolog code to the 'finally'
1629 * clause's start
1630 */
1631 add_debug_line_rec();
1632
1633 /* push the enclosing statement */
1634 old_enclosing = G_cs->set_enclosing(this);
1635
1636 /*
1637 * add our exception table entry - use the invalid object ID as a
1638 * special flag to indicate that we catch all exceptions
1639 */
1640 G_cg->get_exc_table()->add_catch(start_prot_ofs, end_prot_ofs,
1641 VM_INVALID_OBJ, G_cs->get_ofs());
1642
1643 /* don't allow any peephole optimizations to affect this offset */
1644 G_cg->clear_peephole();
1645
1646 /* the VM pushes the exception onto the stack before calling us */
1647 G_cg->note_push();
1648
1649 /*
1650 * When we get called due to an exception, we want to run the
1651 * 'finally' code block and then re-throw the exception. First, store
1652 * the exception parameter in our special local stack slot that we
1653 * allocated specifically for the purpose of being a temporary holder
1654 * for this value.
1655 */
1656 CTcSymLocal::s_gen_code_setlcl_stk(exc_local_id_, FALSE);
1657
1658 /* call the 'finally' block */
1659 try_stm->gen_jsr_finally();
1660
1661 /*
1662 * After the 'finally' block returns, we must re-throw the
1663 * exception. Retrieve the contents of our local where we stashed
1664 * the exception object and re-throw the exception.
1665 */
1666 CTcSymLocal::s_gen_code_getlcl(exc_local_id_, FALSE);
1667
1668 /* re-throw the exception - this pops the exception object */
1669 G_cg->write_op(OPC_THROW);
1670 G_cg->note_pop();
1671
1672 /*
1673 * set the source location to the 'finally' clause once again, since
1674 * we changed the source location in the course of generating the
1675 * catch-all handler
1676 */
1677 add_debug_line_rec();
1678
1679 /* this is where the 'finally' code block begins - define our label */
1680 def_label_pos(try_stm->get_finally_lbl());
1681
1682 /*
1683 * The 'finally' block is the target of LJSR instructions, since we
1684 * must run the 'finally' block's code from numerous code paths.
1685 * The first thing we must do is pop the return address and stash it
1686 * in a local variable. (We note an extra push, since the LJSR will
1687 * have pushed the value before transferring control here.)
1688 */
1689 G_cg->note_push();
1690 CTcSymLocal::s_gen_code_setlcl_stk(jsr_local_id_, FALSE);
1691
1692 /* generate the code block, if there is one */
1693 if (body_ != 0)
1694 gen_code_substm(body_);
1695
1696 /* return from the 'finally' subroutine */
1697 G_cg->write_op(OPC_LRET);
1698 G_cs->write2(jsr_local_id_);
1699
1700 /* restore the enclosing statement */
1701 G_cs->set_enclosing(old_enclosing);
1702 }
1703
1704 /*
1705 * It is not legal to enter a 'finally' block via a 'goto' statement,
1706 * because there is no valid way to exit the 'finally' block in this
1707 * case.
1708 */
1709 int CTPNStmFinally::check_enter_by_goto(CTPNStmGoto *goto_stm,
1710 CTPNStmLabel *)
1711 {
1712 /* this is illegal - log an error */
1713 goto_stm->log_error(TCERR_GOTO_INTO_FINALLY);
1714
1715 /* indicate that it's not allowed */
1716 return FALSE;
1717 }
1718
1719
1720 /* ------------------------------------------------------------------------ */
1721 /*
1722 * 'throw' statement
1723 */
1724
1725 /*
1726 * generate code
1727 */
1728 void CTPNStmThrow::gen_code(int, int)
1729 {
1730 /* add a line record */
1731 add_debug_line_rec();
1732
1733 /*
1734 * generate our expression - we use the result (discard = false),
1735 * and we are effectively assigning the result, so we can't use the
1736 * 'for condition' rules
1737 */
1738 expr_->gen_code(FALSE, FALSE);
1739
1740 /* generate the 'throw' */
1741 G_cg->write_op(OPC_THROW);
1742
1743 /* 'throw' pops the expression from the stack */
1744 G_cg->note_pop();
1745 }
1746
1747 /* ------------------------------------------------------------------------ */
1748 /*
1749 * 'goto' statement
1750 */
1751
1752 /*
1753 * generate code
1754 */
1755 void CTPNStmGoto::gen_code(int, int)
1756 {
1757 CTcSymbol *sym;
1758 CTPNStmLabel *label_stm;
1759
1760 /* add a line record */
1761 add_debug_line_rec();
1762
1763 /*
1764 * look up our label symbol in the 'goto' table for the function,
1765 * and get the label statement node from the label
1766 */
1767 if (G_cs->get_goto_symtab() == 0
1768 || (sym = G_cs->get_goto_symtab()->find(lbl_, lbl_len_)) == 0
1769 || sym->get_type() != TC_SYM_LABEL
1770 || (label_stm = ((CTcSymLabel *)sym)->get_stm()) == 0)
1771 {
1772 /* log an error */
1773 log_error(TCERR_INVALID_GOTO_LBL, (int)lbl_len_, lbl_);
1774
1775 /* give up */
1776 return;
1777 }
1778
1779 /*
1780 * Tell any enclosing statements to unwind their 'try' blocks for a
1781 * transfer to the given label. We only need to go as far as the
1782 * most deeply nested enclosing statement we have in common with the
1783 * label, because we'll be transferring control entirely within the
1784 * confines of that enclosing statement.
1785 */
1786 if (G_cs->get_enclosing() != 0)
1787 {
1788 /* generate the unwinding code */
1789 G_cs->get_enclosing()->gen_code_unwind_for_goto(this, label_stm);
1790 }
1791 else
1792 {
1793 CTPNStmEnclosing *enc;
1794
1795 /*
1796 * The 'goto' isn't enclosed in any statements. This means that
1797 * we are entering every block that contains the target label.
1798 * Some blocks don't allow entering via 'goto', so we must check
1799 * at this point to see if any of the enclosing blocks are
1800 * problematic.
1801 */
1802 for (enc = label_stm ; enc != 0 ; enc = enc->get_enclosing())
1803 {
1804 /*
1805 * make sure we're allowed to enter this statement - if not,
1806 * stop scanning, so that we display only one such error
1807 */
1808 if (!enc->check_enter_by_goto(this, label_stm))
1809 break;
1810 }
1811 }
1812
1813 /* generate a jump to the label */
1814 G_cg->write_op(OPC_JMP);
1815 G_cs->write_ofs2(label_stm->get_goto_label(), 0);
1816 }
1817
1818
1819 /* ------------------------------------------------------------------------ */
1820 /*
1821 * Generic enclosing statement node
1822 */
1823
1824 /*
1825 * Generate code for a break, given the target code label object and the
1826 * target label symbol, if any. This can be used for any of the looping
1827 * statement types.
1828 */
1829 int CTPNStmEnclosing::gen_code_break_loop(CTcCodeLabel *code_label,
1830 const textchar_t *lbl,
1831 size_t lbl_len)
1832 {
1833 /*
1834 * If the statement is labeled, let the enclosing statement handle
1835 * it -- since it's labeled, we can't assume the statement refers to
1836 * us without searching for the enclosing label.
1837 */
1838 if (lbl != 0)
1839 {
1840 /* if there's an enclosing statement, let it handle it */
1841 if (enclosing_ != 0)
1842 return enclosing_->gen_code_break(lbl, lbl_len);
1843
1844 /*
1845 * there's no enclosing statement, and we can't handle this
1846 * because it has an explicit label attached - indicate that no
1847 * break has been generated and give up
1848 */
1849 return FALSE;
1850 }
1851
1852 /*
1853 * It's unlabeled, so we can take it by default as the nearest
1854 * enclosing statement for which 'break' makes sense -- generate the
1855 * jump to the given code label.
1856 */
1857 G_cg->write_op(OPC_JMP);
1858 G_cs->write_ofs2(code_label, 0);
1859
1860 /* we have generated the break */
1861 return TRUE;
1862 }
1863
1864 /*
1865 * Generate code for a continue, given the target code label object and
1866 * the target label symbol, if any. This can be used for any of the
1867 * looping statement types.
1868 */
1869 int CTPNStmEnclosing::gen_code_continue_loop(CTcCodeLabel *code_label,
1870 const textchar_t *lbl,
1871 size_t lbl_len)
1872 {
1873 /*
1874 * If the statement is labeled, let the enclosing statement handle
1875 * it -- since it's labeled, we can't assume the statement refers to
1876 * us without searching for the enclosing label.
1877 */
1878 if (lbl != 0)
1879 {
1880 /* if there's an enclosing statement, let it handle it */
1881 if (enclosing_ != 0)
1882 return enclosing_->gen_code_continue(lbl, lbl_len);
1883
1884 /*
1885 * there's no enclosing statement, and we can't handle this
1886 * because it has an explicit label attached - indicate that no
1887 * continue has been generated and give up
1888 */
1889 return FALSE;
1890 }
1891
1892 /*
1893 * it's unlabeled, so we can take it by default as the nearest
1894 * enclosing statement for which 'continue' makes sense -- generate
1895 * the jump to the given code label
1896 */
1897 G_cg->write_op(OPC_JMP);
1898 G_cs->write_ofs2(code_label, 0);
1899
1900 /* we have generated the continue */
1901 return TRUE;
1902 }
1903
1904 /*
1905 * Generate the code necessary to unwind the stack for executing a
1906 * 'goto' to the given labeled statement>
1907 */
1908 void CTPNStmEnclosing::gen_code_unwind_for_goto(CTPNStmGoto *goto_stm,
1909 CTPNStmLabel *target)
1910 {
1911 CTPNStmEnclosing *enc;
1912
1913 /*
1914 * Detmerine if the target statement is enclosed within this
1915 * statement. If it is, we do not need to unwind from this
1916 * statement or any of its enclosing statements, because control
1917 * will remain within this statement.
1918 *
1919 * To make this determination, start at the target label and search
1920 * up its list of enclosing statements. If we reach 'this', we know
1921 * that we enclose the target. If we reach the outermost enclosing
1922 * statement, we know that we do not enclose the taret.
1923 */
1924 for (enc = target ; enc != 0 ; enc = enc->get_enclosing())
1925 {
1926 /*
1927 * if we found ourself in the list of enclosing statements
1928 * around the target label, the label is contained within us,
1929 * hence we do not need to generate any code to leave, because
1930 * we're not leaving - simply return immediately without looking
1931 * any further
1932 */
1933 if (enc == this)
1934 {
1935 /*
1936 * 'this' is the common ancestor of both the 'goto' and the
1937 * target label, so we're not transferring control in or out
1938 * of 'this' or any enclosing statement. However, we are
1939 * transfering control IN through all of the statements that
1940 * enclose the label up to but not including 'this'.
1941 *
1942 * Some types of statements do not allow control transfers
1943 * in to enclosed labels - in particular, we can't use
1944 * 'goto' to transfer control into a 'finally' clause.
1945 * Check all statements that enclose the label up to but not
1946 * including 'this', and make sure they will allow a
1947 * transfer in.
1948 *
1949 * Note that we make this check now, only after we've found
1950 * the common ancestor, because we can't tell if we're
1951 * actually entering any blocks until we find the common
1952 * ancestor.
1953 */
1954 for (enc = target ; enc != 0 && enc != this ;
1955 enc = enc->get_enclosing())
1956 {
1957 /* make sure we're allowed to enter this statement */
1958 if (!enc->check_enter_by_goto(goto_stm, target))
1959 break;
1960 }
1961
1962 /*
1963 * we're not transferring out of this statement or any
1964 * enclosing statement, since the source 'goto' and the
1965 * target label are both contained within 'this' - we're
1966 * done unwinding for the transfer
1967 */
1968 return;
1969 }
1970 }
1971
1972 /* generate code to transfer out of this statement */
1973 gen_code_for_transfer_out();
1974
1975 /* check for an enclosing statement */
1976 if (enclosing_ != 0)
1977 {
1978 /*
1979 * We are enclosed by another statement or statements. This
1980 * means that we haven't found a common ancestor yet, so we
1981 * might be leaving the enclosing block as well - continue on to
1982 * our enclosing statement.
1983 */
1984 enclosing_->gen_code_unwind_for_goto(goto_stm, target);
1985 }
1986 else
1987 {
1988 /*
1989 * This is the outermost significant enclosing statement, which
1990 * means that we are transferring control into a completely
1991 * unrelated block. As a result, we will enter every statement
1992 * that encloses the target label.
1993 *
1994 * We must check each block we're entering to see if it allows
1995 * entry by 'goto' statements. Since we now know there is no
1996 * common ancestor, and thus that we're entering every block
1997 * enclosing the target label, we must check every block
1998 * enclosing the target label to see if they allow transfers in
1999 * via 'goto' statements.
2000 */
2001 for (enc = target ; enc != 0 ; enc = enc->get_enclosing())
2002 {
2003 /* make sure we're allowed to enter this statement */
2004 if (!enc->check_enter_by_goto(goto_stm, target))
2005 break;
2006 }
2007 }
2008 }
2009
2010
2011 /* ------------------------------------------------------------------------ */
2012 /*
2013 * Anonymous function
2014 */
2015
2016 /*
2017 * generate code
2018 */
2019 void CTPNAnonFunc::gen_code(int discard, int)
2020 {
2021 /* if we're discarding the value, don't bother generating the code */
2022 if (discard)
2023 return;
2024
2025 /*
2026 * Push each context object - these are the additional arguments to
2027 * the anonymous function pointer object's constructor beyond the
2028 * function pointer itself. Note that we must push the arguments in
2029 * reverse order of our list, since arguments are always pushed from
2030 * last to first.
2031 */
2032 int argc = 0;
2033 for (CTcCodeBodyCtx *cur_ctx = code_body_->get_ctx_tail() ; cur_ctx != 0 ;
2034 cur_ctx = cur_ctx->prv_, ++argc)
2035 {
2036 /*
2037 * find our context matching this context - the caller's
2038 * contexts are all one level lower than the callee's contexts,
2039 * because the caller is at the next recursion level out
2040 */
2041 int our_varnum;
2042 if (!G_cs->get_code_body()
2043 ->get_ctx_var_for_level(cur_ctx->level_ - 1, &our_varnum))
2044 {
2045 /* this should never happen */
2046 assert(FALSE);
2047 }
2048
2049 /*
2050 * push this context object - to do this, simply retrieve the
2051 * value of the local variable in our frame that contains this
2052 * context level
2053 */
2054 CTcSymLocal::s_gen_code_getlcl(our_varnum, FALSE);
2055 }
2056
2057 /*
2058 * The first argument (and thus last pushed) to the constructor is the
2059 * constant function pointer that refers to the code of the anonymous
2060 * function.
2061 *
2062 * For regular static compilation, the function pointer is a simple
2063 * code offset constant. For run-time compilation (in the debugger or
2064 * interpreter "eval()" facility), it's a DynamicFunc representing the
2065 * dynamically compiled code.
2066 */
2067 if (G_cg->is_eval_for_dyn())
2068 {
2069 /*
2070 * Dynamic (run-time) compilation - the bytecode is in a
2071 * dynamically created DynamicFunc instance. The dynamic compiler
2072 * assigns object IDs for the anonymous function code body before
2073 * generating any code for any referencing object, so we simply
2074 * generate a PUSHOBJ for the code body's object ID.
2075 */
2076 G_cg->write_op(OPC_PUSHOBJ);
2077 G_cs->write_obj_id(code_body_->get_dyn_obj_id());
2078 }
2079 else
2080 {
2081 /* conventional static compiler - the bytecode is in the code pool */
2082 G_cg->write_op(OPC_PUSHFNPTR);
2083 code_body_->add_abs_fixup(G_cs);
2084 G_cs->write4(0);
2085 }
2086
2087 /* count the argument */
2088 ++argc;
2089
2090 /* note the push of the function pointer argument */
2091 G_cg->note_push();
2092
2093 /*
2094 * If we have a local context, we need to create an anonymous function
2095 * metaclass object that combines the function pointer with the local
2096 * context. If we don't have a local context, this is a simple static
2097 * function that we can call directly, in which case we're already done
2098 * since we've pushed the function pointer.
2099 */
2100 if (argc > 1 || code_body_->has_local_ctx())
2101 {
2102 /*
2103 * We have a local context, so we need create to create the
2104 * anonymous function metaclass object. Generate the NEW.
2105 */
2106 if (argc <= 255)
2107 {
2108 G_cg->write_op(OPC_NEW1);
2109 G_cs->write((char)argc);
2110 G_cs->write((char)G_cg->get_predef_meta_idx(TCT3_METAID_ANONFN));
2111 }
2112 else
2113 {
2114 G_cg->write_op(OPC_NEW2);
2115 G_cs->write2(argc);
2116 G_cs->write2(G_cg->get_predef_meta_idx(TCT3_METAID_ANONFN));
2117 }
2118
2119 /* push the object value */
2120 G_cg->write_op(OPC_GETR0);
2121
2122 /* the 'new' popped the arguments, then we pushed the result */
2123 G_cg->note_pop(argc - 1);
2124 }
2125 }
2126
2127 /* ------------------------------------------------------------------------ */
2128 /*
2129 * Implicit constructor
2130 */
2131 void CTPNStmImplicitCtor::gen_code(int /*discard*/, int /*for_condition*/)
2132 {
2133 /*
2134 * Generate a call to inherit each superclass constructor. Pass the
2135 * same argument list we received by expanding the varargs list
2136 * parameter in local 0.
2137 */
2138 for (CTPNSuperclass *sc = obj_stm_->get_first_sc() ; sc != 0 ;
2139 sc = sc->nxt_)
2140 {
2141 /*
2142 * if this one is valid, generate code to call its constructor -
2143 * it's valid if it has an object symbol
2144 */
2145 CTcSymObj *sc_sym = (CTcSymObj *)sc->get_sym();
2146 if (sc_sym != 0 && sc_sym->get_type() == TC_SYM_OBJ)
2147 {
2148 /* push the argument counter so far (no other arguments) */
2149 G_cg->write_op(OPC_PUSH_0);
2150 G_cg->note_push();
2151
2152 /* get the varargs list local */
2153 CTcSymLocal::s_gen_code_getlcl(0, FALSE);
2154
2155 /* convert it to varargs */
2156 G_cg->write_op(OPC_MAKELSTPAR);
2157
2158 /* note the extra push and pop for the argument count */
2159 G_cg->note_push();
2160 G_cg->note_pop();
2161
2162 /* it's a varargs call */
2163 G_cg->write_op(OPC_VARARGC);
2164
2165 /* generate an EXPINHERIT to this superclass */
2166 G_cg->write_op(OPC_EXPINHERIT);
2167 G_cs->write(0); /* varargs -> argc ignored */
2168 G_cs->write_prop_id(G_prs->get_constructor_prop());
2169 G_cs->write_obj_id(sc_sym->get_obj_id());
2170
2171 /*
2172 * this removes arguments (the varargs list variable and
2173 * argument count)
2174 */
2175 G_cg->note_pop(2);
2176 }
2177 }
2178 }
2179
2180
2181
2182 /* ------------------------------------------------------------------------ */
2183 /*
2184 * Object Property list entry - value node
2185 */
2186 void CTPNObjProp::gen_code(int, int)
2187 {
2188 vm_val_t val;
2189 char buf[VMB_DATAHOLDER];
2190
2191 /* get the correct data stream */
2192 CTcDataStream *str = objdef_->get_obj_sym()->get_stream();
2193
2194 /* set the current source location for error reporting */
2195 G_tok->set_line_info(file_, linenum_);
2196
2197 /* generate code for our expression or our code body, as appropriate */
2198 if (code_body_ != 0)
2199 {
2200 /* if this is a constructor, mark the code body accordingly */
2201 if (prop_sym_->get_prop() == G_prs->get_constructor_prop())
2202 code_body_->set_constructor(TRUE);
2203
2204 /* if it's static, do some extra work */
2205 if (is_static_)
2206 {
2207 /* mark the code body as static */
2208 code_body_->set_static();
2209
2210 /*
2211 * add the obj.prop to the static ID stream, so the VM knows to
2212 * invoke this initializer at start-up
2213 */
2214 G_static_init_id_stream
2215 ->write_obj_id(objdef_->get_obj_sym()->get_obj_id());
2216 G_static_init_id_stream
2217 ->write_prop_id(prop_sym_->get_prop());
2218 }
2219
2220 /* tell our code body to generate the code */
2221 code_body_->gen_code(FALSE, FALSE);
2222
2223 /*
2224 * Set up our code offset value. Write a code offset of zero for
2225 * now, since we won't know the correct offset until link time.
2226 */
2227 val.set_codeofs(0);
2228
2229 /*
2230 * Add a fixup to the code body's fixup list for our dataholder, so
2231 * that we fix up the property value when we link. Note that the
2232 * fixup is one byte into our object stream from the current
2233 * offset, because the first byte is the type.
2234 */
2235 CTcAbsFixup::add_abs_fixup(code_body_->get_fixup_list_head(),
2236 str, str->get_ofs() + 1);
2237
2238 /* write out our value in DATAHOLDER format */
2239 vmb_put_dh(buf, &val);
2240 str->write(buf, VMB_DATAHOLDER);
2241 }
2242 else if (expr_ != 0)
2243 {
2244 /*
2245 * if my value is constant, write out a dataholder for the constant
2246 * value to the stream; otherwise, write out our code and store a
2247 * pointer to the code
2248 */
2249 if (expr_->is_const())
2250 {
2251 /* write the constant value to the object stream */
2252 G_cg->write_const_as_dh(str, str->get_ofs(),
2253 expr_->get_const_val());
2254 }
2255 else if (expr_->is_dstring())
2256 {
2257 /* it's a double-quoted string node */
2258 CTPNDstr *dstr = (CTPNDstr *)expr_;
2259
2260 /*
2261 * Add the string to the constant pool. Note that the fixup
2262 * will be one byte from the current object stream offset,
2263 * since we need to write the type byte first.
2264 */
2265 G_cg->add_const_str(dstr->get_str(), dstr->get_str_len(),
2266 str, str->get_ofs() + 1);
2267
2268 /*
2269 * Set up the dstring value. Use a zero placeholder for now;
2270 * add_const_str() already added a fixup for us that will
2271 * supply the correct value at link time.
2272 */
2273 val.set_dstring(0);
2274 vmb_put_dh(buf, &val);
2275 str->write(buf, VMB_DATAHOLDER);
2276 }
2277 else
2278 {
2279 /* we should never get here */
2280 G_tok->throw_internal_error(TCERR_INVAL_PROP_CODE_GEN);
2281 }
2282 }
2283 }
2284
2285 /*
2286 * Generate code for an inline object instantiation
2287 */
2288 void CTPNObjProp::gen_code_inline_obj()
2289 {
2290 /* set the current source location for error reporting */
2291 G_tok->set_line_info(file_, linenum_);
2292
2293 /* generate code for our expression or our code body, as appropriate */
2294 if (inline_method_ != 0)
2295 {
2296 /*
2297 * Code as an in-line method. This means that the code was
2298 * specified as an explicit method in braces; we compile it as an
2299 * anonymous method so that it can access locals in enclosing
2300 * scopes. Generate the code to construct the closure object, then
2301 * call obj.setMethod(prop, anonMethod) to bind it as a method of
2302 * the object. This will make it act like a regular method, in
2303 * that evaluating the property will call the method.
2304 */
2305 inline_method_->gen_code(FALSE, FALSE);
2306
2307 /* generate the setMethod */
2308 gen_setMethod();
2309 }
2310 else if (expr_ != 0)
2311 {
2312 /* check the type of expression */
2313 if (expr_->is_dstring())
2314 {
2315 /*
2316 * Double-quoted string - generate obj.setMethod(prop, string)
2317 */
2318
2319 /* push the string contents as a regular sstring constant */
2320 CTPNDstr *dstr = (CTPNDstr *)expr_;
2321 CTPNConst::s_gen_code_str(dstr->get_str(), dstr->get_str_len());
2322
2323 /* get the setMethod property */
2324 gen_setMethod();
2325 }
2326 else
2327 {
2328 /*
2329 * Expression, constant or live. Generate the code to evaluate
2330 * the expression; this runs at the moment of evaluating the
2331 * overall inline object expression, so we caputre the value of
2332 * the expression at the time we create the inline object
2333 * instance (and fix the value at that point - this isn't a
2334 * method that's invoked when the property is evaluated).
2335 */
2336
2337 /* push the new object referene */
2338 G_cg->write_op(OPC_DUP);
2339 G_cg->note_push();
2340
2341 /* it's a constant value - do a setprop; start with my value */
2342 expr_->gen_code(FALSE, FALSE);
2343
2344 /* if it doesn't have a return value, set the property to nil */
2345 if (!expr_->has_return_value())
2346 {
2347 G_cg->write_op(OPC_PUSHNIL);
2348 G_cg->note_push();
2349 }
2350
2351 /* get the object and value into the proper order */
2352 G_cg->write_op(OPC_SWAP);
2353
2354 /* generate the setprop for <obj>.<prop> = <value> */
2355 G_cg->write_op(OPC_SETPROP);
2356 G_cs->write_prop_id(prop_sym_->get_prop());
2357 G_cg->note_pop(2);
2358 }
2359 }
2360 }
2361
2362 /*
2363 * Generate a setMethod call. The caller must push the value for the
2364 * setMethod, and the object ID must be on the stack just above that.
2365 */
2366 void CTPNObjProp::gen_setMethod()
2367 {
2368 /* look up the setMethod property */
2369 CTcSymProp *setm = (CTcSymProp *)G_prs->get_global_symtab()->find(
2370 "setMethod", 9);
2371 if (setm == 0 || setm->get_type() != TC_SYM_PROP)
2372 {
2373 G_tok->log_error(TCERR_SYM_NOT_PROP, 9, "setMethod");
2374 return;
2375 }
2376
2377 /* push the property ID */
2378 G_cg->write_op(OPC_PUSHPROPID);
2379 G_cs->write_prop_id(prop_sym_->get_prop());
2380 G_cg->note_push();
2381
2382 /* re-push the object reference (it's on the stack above the value) */
2383 G_cg->write_op(OPC_GETSPN);
2384 G_cs->write(2);
2385 G_cg->note_push();
2386
2387 /* generate <obj>.setMethod(<prop>, string) */
2388 G_cg->write_op(OPC_CALLPROP);
2389 G_cs->write(2);
2390 G_cs->write_prop_id(setm->get_prop());
2391 G_cg->note_pop(3);
2392 }
2393
2394 /* ------------------------------------------------------------------------ */
2395 /*
2396 * Inline object definition
2397 */
2398
2399 /*
2400 * Generate code. An inline object definition creates a new instance of
2401 * the object on each evaluation, and creates a new instance of each
2402 * anonymous method contained in the property list. The result of the
2403 * expression is the new object reference.
2404 */
2405 void CTPNInlineObject::gen_code(int discard, int for_condition)
2406 {
2407 /*
2408 * First, create the object via TadsObject.createInstanceOf(), with the
2409 * list of superclasses as the arguments. Use the no-constructor form
2410 * of the call, since we'll invoke the new object's construct() method
2411 * directly instead.
2412 */
2413
2414 /*
2415 * push the superclass references, from last to first (standard
2416 * right-to-left order for the method arguments)
2417 */
2418 int sccnt = 0;
2419 for (CTPNSuperclass *sc = sclist_.tail_ ; sc != 0 ; sc = sc->prv_, ++sccnt)
2420 sc->get_sym()->gen_code(FALSE);
2421
2422 /* look up TadsObject */
2423 CTcPrsSymtab *tab = G_prs->get_global_symtab();
2424 CTcSymMetaclass *tadsobj = (CTcSymMetaclass *)tab->find("TadsObject", 10);
2425 if (tadsobj == 0 || tadsobj->get_type() != TC_SYM_METACLASS)
2426 {
2427 G_tok->log_error(TCERR_UNDEF_METACLASS, 10, "TadsObject");
2428 return;
2429 }
2430
2431 /* look up createInstanceOf */
2432 const char *cioname = "createInstanceOf";
2433 size_t ciolen = 16;
2434 CTcSymProp *cio = (CTcSymProp *)tab->find(cioname, ciolen);
2435 if (cio == 0 || cio->get_type() != TC_SYM_PROP)
2436 {
2437 G_tok->log_error(TCERR_SYM_NOT_PROP, (int)ciolen, cioname);
2438 return;
2439 }
2440
2441 /* call TadsObject.createInstanceOf() */
2442 G_cg->write_op(OPC_OBJCALLPROP);
2443 G_cs->write((char)sccnt);
2444 G_cs->write_obj_id(tadsobj->get_class_obj());
2445 G_cs->write_prop_id(cio->get_prop());
2446 G_cg->note_pop(sccnt);
2447
2448 /* push the new object reference as the result of the overall expression */
2449 G_cg->write_op(OPC_GETR0);
2450 G_cg->note_push();
2451
2452 /* assume we won't find a constructor among the properties */
2453 int has_ctor = FALSE;
2454
2455 /* install each property or method */
2456 for (CTPNObjProp *prop = proplist_.first_ ; prop != 0 ;
2457 prop = prop->get_next_prop())
2458 {
2459 /* generate the property/method setup */
2460 prop->gen_code_inline_obj();
2461
2462 /* note if it's a constructor */
2463 if (prop->get_prop_sym()->get_prop() == G_prs->get_constructor_prop())
2464 has_ctor = TRUE;
2465 }
2466
2467 /* if there's an explicit constructor defined, call it */
2468 if (has_ctor)
2469 {
2470 G_cg->write_op(OPC_DUP);
2471 G_cg->write_op(OPC_CALLPROP);
2472 G_cs->write(0);
2473 G_cs->write_prop_id(G_prs->get_constructor_prop());
2474 }
2475 }