Debian Codegraph @

terps/tads/tads3/tctok.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/tads3/tctok.cpp,v 1.5 1999/07/11 00:46:58 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 tctok.cpp - TADS3 compiler tokenizer
15 Function
16
17 Notes
18 The tokenizer features an integrated C-style preprocessor. The
19 preprocessor is integrated into the tokenizer for efficiency; since
20 the preprocessor uses the same lexical structure as the the TADS
21 language, we need only tokenize the input stream once, and the result
22 can be used both for preprocessing and for parsing.
23 Modified
24 04/12/99 MJRoberts - Creation
25 */
26
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <time.h>
31
32 #include "os.h"
33 #include "t3std.h"
34 #include "vmerr.h"
35 #include "vmhash.h"
36 #include "tcerr.h"
37 #include "tcerrnum.h"
38 #include "tctok.h"
39 #include "tcsrc.h"
40 #include "tcmain.h"
41 #include "tchost.h"
42 #include "tcprs.h"
43 #include "tctarg.h"
44 #include "charmap.h"
45 #include "vmdatasrc.h"
46 #include "vmfile.h"
47
48
49 /* ------------------------------------------------------------------------ */
50 /*
51 * Standard macro table. This implements the interface using a standard
52 * hash table object.
53 */
54 class CTcBasicMacroTable: public CTcMacroTable
55 {
56 public:
57 CTcBasicMacroTable(int hash_table_size, CVmHashFunc *hash_function,
58 int own_hash_func)
59 : tab(hash_table_size, hash_function, own_hash_func)
60 {
61 }
62
63 virtual void add(CVmHashEntry *entry) { tab.add(entry); }
64 virtual void remove(CVmHashEntry *entry) { tab.remove(entry); }
65 virtual CVmHashEntry *find(const char *str, size_t len)
66 { return tab.find(str, len); }
67 virtual void enum_entries(void (*func)(void *, CVmHashEntry *), void *ctx)
68 { tab.enum_entries(func, ctx); }
69 virtual void debug_dump() { tab.debug_dump(); }
70
71 private:
72 /* our hash table */
73 CVmHashTable tab;
74 };
75
76 /* ------------------------------------------------------------------------ */
77 /*
78 * string embedded expression context
79 */
80 void tok_embed_ctx::start_expr(wchar_t qu, int triple, int report)
81 {
82 if (level < countof(stk))
83 {
84 s = stk + level;
85 s->enter(qu, triple);
86 }
87 else if (report)
88 {
89 G_tok->log_error(TCERR_EMBEDDING_TOO_DEEP);
90 }
91 ++level;
92 }
93
94
95 /* ------------------------------------------------------------------------ */
96 /*
97 * Initialize the tokenizer
98 */
99 CTcTokenizer::CTcTokenizer(CResLoader *res_loader,
100 const char *default_charset)
101 {
102 int i;
103 os_time_t timer;
104 struct tm *tblk;
105 const char *tstr;
106 char timebuf[50];
107 struct kwdef
108 {
109 const char *kw_text;
110 tc_toktyp_t kw_tok_id;
111 };
112 static const kwdef kwlist[] =
113 {
114 { "self", TOKT_SELF },
115 { "targetprop", TOKT_TARGETPROP },
116 { "targetobj", TOKT_TARGETOBJ },
117 { "definingobj", TOKT_DEFININGOBJ },
118 { "inherited", TOKT_INHERITED },
119 { "delegated", TOKT_DELEGATED },
120 { "argcount", TOKT_ARGCOUNT },
121 { "if", TOKT_IF },
122 { "else", TOKT_ELSE },
123 { "for", TOKT_FOR },
124 { "while", TOKT_WHILE },
125 { "do", TOKT_DO },
126 { "switch", TOKT_SWITCH },
127 { "case", TOKT_CASE },
128 { "default", TOKT_DEFAULT },
129 { "goto", TOKT_GOTO },
130 { "break", TOKT_BREAK },
131 { "continue", TOKT_CONTINUE },
132 // { "and", TOKT_AND },
133 // { "or", TOKT_OR },
134 // { "not", TOKT_NOT },
135 { "function", TOKT_FUNCTION },
136 { "return", TOKT_RETURN },
137 { "local", TOKT_LOCAL },
138 { "object", TOKT_OBJECT },
139 { "nil", TOKT_NIL },
140 { "true", TOKT_TRUE },
141 { "pass", TOKT_PASS },
142 { "external", TOKT_EXTERNAL },
143 { "extern", TOKT_EXTERN },
144 { "formatstring", TOKT_FORMATSTRING },
145 { "class", TOKT_CLASS },
146 { "replace", TOKT_REPLACE },
147 { "modify", TOKT_MODIFY },
148 { "new", TOKT_NEW },
149 // { "delete", TOKT_DELETE },
150 { "throw", TOKT_THROW },
151 { "try", TOKT_TRY },
152 { "catch", TOKT_CATCH },
153 { "finally", TOKT_FINALLY },
154 { "intrinsic", TOKT_INTRINSIC },
155 { "dictionary", TOKT_DICTIONARY },
156 { "grammar", TOKT_GRAMMAR },
157 { "enum", TOKT_ENUM },
158 { "template", TOKT_TEMPLATE },
159 { "static", TOKT_STATIC },
160 { "foreach", TOKT_FOREACH },
161 { "export", TOKT_EXPORT },
162 { "propertyset", TOKT_PROPERTYSET },
163 { "transient", TOKT_TRANSIENT },
164 { "replaced", TOKT_REPLACED },
165 { "property", TOKT_PROPERTY },
166 { "operator", TOKT_OPERATOR },
167 { "method", TOKT_METHOD },
168 { "invokee", TOKT_INVOKEE },
169
170 // { "void", TOKT_VOID },
171 // { "int", TOKT_INT },
172 // { "string", TOKT_STRING },
173 // { "list", TOKT_LIST },
174 // { "boolean", TOKT_BOOLEAN },
175 // { "any", TOKT_ANY },
176
177 /* end-of-table marker */
178 { 0, TOKT_INVALID }
179 };
180 const kwdef *kwp;
181
182 /* remember my resource loader */
183 res_loader_ = res_loader;
184
185 /* there's no stream yet */
186 str_ = 0;
187
188 /* no external source yet */
189 ext_src_ = 0;
190
191 /* start numbering the file descriptors at zero */
192 next_filedesc_id_ = 0;
193
194 /* there are no file descriptors yet */
195 desc_head_ = 0;
196 desc_tail_ = 0;
197 desc_list_ = 0;
198 desc_list_cnt_ = desc_list_alo_ = 0;
199
200 /* empty out the input line buffer */
201 clear_linebuf();
202
203 /* start out with a minimal line buffer size */
204 linebuf_.ensure_space(4096);
205 expbuf_.ensure_space(4096);
206
207 /* set up at the beginning of the input line buffer */
208 start_new_line(&linebuf_, 0);
209
210 /* remember the default character set */
211 default_charset_ = lib_copy_str(default_charset);
212
213 /* we don't have a default character mapper yet */
214 default_mapper_ = 0;
215
216 /* create an input mapper for the default character set, if specified */
217 if (default_charset != 0)
218 default_mapper_ = CCharmapToUni::load(res_loader, default_charset);
219
220 /*
221 * if the default character set wasn't specified, or we failed to
222 * load a mapper for the specified character set, use a plain ASCII
223 * mapper
224 */
225 if (default_mapper_ == 0)
226 default_mapper_ = new CCharmapToUniASCII();
227
228 /* presume we're not in preprocessor-only mode */
229 pp_only_mode_ = FALSE;
230
231 /* presume we're not in list-includes mode */
232 list_includes_mode_ = FALSE;
233
234 /* presume we're not in test report mode */
235 test_report_mode_ = FALSE;
236
237 /* allow preprocessing directives */
238 allow_pp_ = TRUE;
239
240 /* there are no previously-included files yet */
241 prev_includes_ = 0;
242
243 /* by default, use the "collapse" mode for newlines in strings */
244 string_newline_spacing_ = NEWLINE_SPACING_COLLAPSE;
245
246 /* start out with ALL_ONCE mode off */
247 all_once_ = FALSE;
248
249 /* by default, ignore redundant includes without warning */
250 warn_on_ignore_incl_ = FALSE;
251
252 /* there are no include path entries yet */
253 incpath_head_ = incpath_tail_ = 0;
254
255 /* not in a quoted string yet */
256 in_quote_ = '\0';
257 in_triple_ = FALSE;
258
259 /* not in a #if block yet */
260 if_sp_ = 0;
261 if_false_level_ = 0;
262
263 /* not processing a preprocessor constant expression */
264 in_pp_expr_ = FALSE;
265
266 /* we don't have a current or appended line yet */
267 last_desc_ = 0;
268 last_linenum_ = 0;
269 appended_desc_ = 0;
270 appended_linenum_ = 0;
271
272 /* allocate the first token-list block */
273 init_src_block_list();
274
275 /* create the #define and #undef symbol tables */
276 defines_ = new CTcBasicMacroTable(512, new CVmHashFuncCS(), TRUE);
277 undefs_ = new CVmHashTable(64, new CVmHashFuncCS(), TRUE);
278
279 /* create the special __LINE__ and __FILE__ macros */
280 defines_->add(new CTcHashEntryPpLINE(this));
281 defines_->add(new CTcHashEntryPpFILE(this));
282
283 /* get the current time and date */
284 timer = os_time(0);
285 tblk = os_localtime(&timer);
286 tstr = asctime(tblk);
287
288 /*
289 * add the __DATE__ macro - the format is "Mmm dd yyyy", where "Mmm"
290 * is the three-letter month name generated by asctime(), "dd" is
291 * the day of the month, with a leading space for numbers less than
292 * ten, and "yyyy" is the year.
293 */
294 sprintf(timebuf, "'%.3s %2d %4d'",
295 tstr + 4, tblk->tm_mday, tblk->tm_year + 1900);
296 add_define("__DATE__", timebuf);
297
298 /* add the __TIME__ macro - 24-hour "hh:mm:ss" format */
299 sprintf(timebuf, "'%.8s'", tstr + 11);
300 add_define("__TIME__", timebuf);
301
302 /*
303 * Allocate a pool of macro resources. The number we start with is
304 * arbitrary, since we'll add more as needed, but we want to try to
305 * allocate enough up front that we avoid time-consuming memory
306 * allocations later. On the other hand, we don't want to
307 * pre-allocate a huge number of objects that we'll never use.
308 */
309 for (macro_res_avail_ = 0, macro_res_head_ = 0, i = 0 ; i < 7 ; ++i)
310 {
311 CTcMacroRsc *rsc;
312
313 /* allocate a new object */
314 rsc = new CTcMacroRsc();
315
316 /* add it onto the master list */
317 rsc->next_ = macro_res_head_;
318 macro_res_head_ = rsc;
319
320 /* add it onto the available list */
321 rsc->next_avail_ = macro_res_avail_;
322 macro_res_avail_ = rsc;
323 }
324
325 /* create the keyword hash table */
326 kw_ = new CVmHashTable(64, new CVmHashFuncCS(), TRUE);
327
328 /* populate the keyword table */
329 for (kwp = kwlist ; kwp->kw_text != 0 ; ++kwp)
330 kw_->add(new CTcHashEntryKw(kwp->kw_text, kwp->kw_tok_id));
331
332 /* no ungot tokens yet */
333 unget_head_ = unget_cur_ = 0;
334
335 /* no string capture file */
336 string_fp_ = 0;
337 string_fp_map_ = 0;
338
339 /* there's no current token yet */
340 curtok_.settyp(TOKT_NULLTOK);
341 curtok_.set_text("<Start of Input>", 16);
342 }
343
344 /*
345 * Initialize the source save block list
346 */
347 void CTcTokenizer::init_src_block_list()
348 {
349 /* allocate the first source block */
350 src_cur_ = src_head_ = new CTcTokSrcBlock();
351
352 /* set up to write into the first block */
353 src_ptr_ = src_head_->get_buf();
354 src_rem_ = TCTOK_SRC_BLOCK_SIZE;
355 }
356
357
358 /* ------------------------------------------------------------------------ */
359 /*
360 * Delete the tokenizer
361 */
362 CTcTokenizer::~CTcTokenizer()
363 {
364 /* delete all streams */
365 delete_source();
366
367 /* delete the string capture file */
368 if (string_fp_ != 0)
369 delete string_fp_;
370
371 /* delete all file descriptors */
372 while (desc_head_ != 0)
373 {
374 /* remember the next descriptor */
375 CTcTokFileDesc *nxt = desc_head_->get_next();
376
377 /* delete this one */
378 delete desc_head_;
379
380 /* move on to the next one */
381 desc_head_ = nxt;
382 }
383
384 /* delete the unget list */
385 unget_cur_ = 0;
386 while (unget_head_ != 0)
387 {
388 /* remember the next element */
389 CTcTokenEle *nxt = unget_head_->getnxt();
390
391 /* delete this element */
392 delete unget_head_;
393
394 /* advance to the next element */
395 unget_head_ = nxt;
396 }
397
398 /* delete the file descriptor index array */
399 if (desc_list_ != 0)
400 t3free(desc_list_);
401
402 /* delete our default character set string copy */
403 lib_free_str(default_charset_);
404
405 /* release our reference on our default character mapper */
406 default_mapper_->release_ref();
407
408 /* forget about all of our previous include files */
409 while (prev_includes_ != 0)
410 {
411 tctok_incfile_t *nxt;
412
413 /* remember the next file */
414 nxt = prev_includes_->nxt;
415
416 /* delete this one */
417 t3free(prev_includes_);
418
419 /* move on to the next one */
420 prev_includes_ = nxt;
421 }
422
423 /* delete the include path list */
424 while (incpath_head_ != 0)
425 {
426 tctok_incpath_t *nxt;
427
428 /* remember the next entry in the path */
429 nxt = incpath_head_->nxt;
430
431 /* delete this entry */
432 t3free(incpath_head_);
433
434 /* move on to the next one */
435 incpath_head_ = nxt;
436 }
437
438 /* delete the macro resources */
439 while (macro_res_head_ != 0)
440 {
441 CTcMacroRsc *nxt;
442
443 /* remember the next one */
444 nxt = macro_res_head_->next_;
445
446 /* delete this one */
447 delete macro_res_head_;
448
449 /* move on to the next one */
450 macro_res_head_ = nxt;
451 }
452
453 /* delete the token list */
454 delete src_head_;
455
456 /* delete the #define and #undef symbol tables */
457 delete defines_;
458 delete undefs_;
459
460 /* delete the keyword hash table */
461 delete kw_;
462
463 /* if we created a mapping for the string capture file, release it */
464 if (string_fp_map_ != 0)
465 string_fp_map_->release_ref();
466 }
467
468 /* ------------------------------------------------------------------------ */
469 /*
470 * Clear the line buffer
471 */
472 void CTcTokenizer::clear_linebuf()
473 {
474 /* clear the buffer */
475 linebuf_.clear_text();
476
477 /* reset our read point to the start of the line buffer */
478 p_.set(linebuf_.get_buf());
479 }
480
481 /* ------------------------------------------------------------------------ */
482 /*
483 * Get a textual representation of an operator token
484 */
485 const char *CTcTokenizer::get_op_text(tc_toktyp_t op)
486 {
487 struct tokname_t
488 {
489 tc_toktyp_t typ;
490 const char *nm;
491 };
492 static const tokname_t toknames[] =
493 {
494 { TOKT_EOF, "<end of file>" },
495 { TOKT_SYM, "<symbol>" },
496 { TOKT_INT, "<integer>" },
497 { TOKT_SSTR, "<single-quoted string>" },
498 { TOKT_DSTR, "<double-quoted string>" },
499 { TOKT_DSTR_START, "<double-quoted string>" },
500 { TOKT_DSTR_MID, "<double-quoted string>" },
501 { TOKT_DSTR_END, "<double-quoted string>" },
502 { TOKT_RESTR, "<regex string>" },
503 { TOKT_LPAR, "(" },
504 { TOKT_RPAR, ")" },
505 { TOKT_COMMA, "," },
506 { TOKT_DOT, "." },
507 { TOKT_LBRACE, "{" },
508 { TOKT_RBRACE, "}", },
509 { TOKT_LBRACK, "[", },
510 { TOKT_RBRACK, "]", },
511 { TOKT_EQ, "=", },
512 { TOKT_EQEQ, "==", },
513 { TOKT_ASI, ":=" },
514 { TOKT_PLUS, "+" },
515 { TOKT_MINUS, "-" },
516 { TOKT_TIMES, "*" },
517 { TOKT_DIV, "/", },
518 { TOKT_MOD, "%" },
519 { TOKT_GT, ">" },
520 { TOKT_LT, "<" },
521 { TOKT_GE, ">=" },
522 { TOKT_LE, "<=" },
523 { TOKT_NE, "!=" },
524 { TOKT_ARROW, "->" },
525 { TOKT_COLON, ":" },
526 { TOKT_SEM, ";" },
527 { TOKT_AND, "&" },
528 { TOKT_ANDAND, "&&" },
529 { TOKT_OR, "|" },
530 { TOKT_OROR, "||" },
531 { TOKT_XOR, "^" },
532 { TOKT_SHL, "<<" },
533 { TOKT_ASHR, ">>" },
534 { TOKT_LSHR, ">>>" },
535 { TOKT_INC, "++" },
536 { TOKT_DEC, "--" },
537 { TOKT_PLUSEQ, "+=" },
538 { TOKT_MINEQ, "-=" },
539 { TOKT_TIMESEQ, "*=" },
540 { TOKT_DIVEQ, "/=" },
541 { TOKT_MODEQ, "%=" },
542 { TOKT_ANDEQ, "&=" },
543 { TOKT_OREQ, "|=" },
544 { TOKT_XOREQ, "^=" },
545 { TOKT_SHLEQ, "<<=" },
546 { TOKT_ASHREQ, ">>=" },
547 { TOKT_LSHREQ, ">>>=" },
548 { TOKT_NOT, "! (not)" },
549 { TOKT_BNOT, "~" },
550 { TOKT_POUND, "#" },
551 { TOKT_POUNDPOUND, "##" },
552 { TOKT_POUNDAT, "#@" },
553 { TOKT_ELLIPSIS, "..." },
554 { TOKT_QUESTION, "?" },
555 { TOKT_QQ, "??" },
556 { TOKT_COLONCOLON, "::" },
557 { TOKT_FLOAT, "<float>" },
558 { TOKT_BIGINT, "<bigint>" },
559 { TOKT_AT, "@" },
560 { TOKT_DOTDOT, ".." },
561 { TOKT_SELF, "self" },
562 { TOKT_TARGETPROP, "targetprop" },
563 { TOKT_TARGETOBJ, "targetobj" },
564 { TOKT_DEFININGOBJ, "definingobj" },
565 { TOKT_INHERITED, "inherited" },
566 { TOKT_DELEGATED, "delegated" },
567 { TOKT_IF, "if" },
568 { TOKT_ELSE, "else" },
569 { TOKT_FOR, "for" },
570 { TOKT_WHILE, "while" },
571 { TOKT_DO, "do" },
572 { TOKT_SWITCH, "switch" },
573 { TOKT_CASE, "case" },
574 { TOKT_DEFAULT, "default" },
575 { TOKT_GOTO, "goto" },
576 { TOKT_BREAK, "break" },
577 { TOKT_CONTINUE, "continue" },
578 { TOKT_FUNCTION, "function" },
579 { TOKT_RETURN, "return" },
580 { TOKT_LOCAL, "local" },
581 { TOKT_OBJECT, "object" },
582 { TOKT_NIL, "nil" },
583 { TOKT_TRUE, "true" },
584 { TOKT_PASS, "pass" },
585 { TOKT_EXTERNAL, "external" },
586 { TOKT_EXTERN, "extern" },
587 { TOKT_FORMATSTRING, "formatstring" },
588 { TOKT_CLASS, "class" },
589 { TOKT_REPLACE, "replace" },
590 { TOKT_MODIFY, "modify" },
591 { TOKT_NEW, "new" },
592 // { TOKT_DELETE, "delete" },
593 { TOKT_THROW, "throw" },
594 { TOKT_TRY, "try" },
595 { TOKT_CATCH, "catch" },
596 { TOKT_FINALLY, "finally" },
597 { TOKT_INTRINSIC, "intrinsic" },
598 { TOKT_DICTIONARY, "dictionary" },
599 { TOKT_GRAMMAR, "grammar" },
600 { TOKT_ENUM, "enum" },
601 { TOKT_TEMPLATE, "template" },
602 { TOKT_STATIC, "static" },
603 { TOKT_FOREACH, "foreach" },
604 { TOKT_EXPORT, "export" },
605 { TOKT_PROPERTYSET, "propertyset" },
606 { TOKT_TRANSIENT, "transient" },
607 { TOKT_REPLACED, "replaced" },
608 { TOKT_PROPERTY, "property" },
609 { TOKT_OPERATOR, "operator" },
610 { TOKT_METHOD, "method" },
611 { TOKT_INVOKEE, "invokee" },
612
613 // { TOKT_VOID, "void" },
614 // { TOKT_INTKW, "int" },
615 // { TOKT_STRING, "string" },
616 // { TOKT_LIST, "list" },
617 // { TOKT_BOOLEAN, "boolean" },
618 // { TOKT_ANY, "any"},
619
620 { TOKT_INVALID, 0 }
621 };
622 const tokname_t *p;
623
624 /* search for the token */
625 for (p = toknames ; p->nm != 0 ; ++p)
626 {
627 /* if this is our token, return the associated name string */
628 if (p->typ == op)
629 return p->nm;
630 }
631
632 /* we didn't find it */
633 return "<unknown>";
634 }
635
636 /* ------------------------------------------------------------------------ */
637 /*
638 * Reset the tokenizer. Delete the current source object and all of the
639 * saved source text. This can be used after compilation of a unit
640 * (such as a debugger expression) is completed and the intermediate
641 * parser state is no longer needed.
642 */
643 void CTcTokenizer::reset()
644 {
645 /* delete the source object */
646 delete_source();
647
648 /* delete saved token text */
649 if (src_head_ != 0)
650 {
651 /* delete the list */
652 delete src_head_;
653
654 /* re-initialize the source block list */
655 init_src_block_list();
656 }
657 }
658
659 /* ------------------------------------------------------------------------ */
660 /*
661 * Delete the source file, if any, including any parent include files.
662 */
663 void CTcTokenizer::delete_source()
664 {
665 /* delete the current stream and all enclosing parents */
666 while (str_ != 0)
667 {
668 CTcTokStream *nxt;
669
670 /* remember the next stream in the list */
671 nxt = str_->get_parent();
672
673 /* delete this stream */
674 delete str_;
675
676 /* move up to the next one */
677 str_ = nxt;
678 }
679
680 /* there are no more streams */
681 str_ = 0;
682 }
683
684
685 /* ------------------------------------------------------------------------ */
686 /*
687 * Set up to read a source file. Returns zero on success, or a non-zero
688 * error code on failure.
689 */
690 int CTcTokenizer::set_source(const char *src_filename, const char *orig_name)
691 {
692 CTcTokFileDesc *desc;
693 CTcSrcFile *src;
694 int charset_error;
695 int default_charset_error;
696
697 /* empty out the input line buffer */
698 clear_linebuf();
699
700 /* set up at the beginning of the input line buffer */
701 start_new_line(&linebuf_, 0);
702
703 /* create a reader for the source file */
704 src = CTcSrcFile::open_source(src_filename, res_loader_,
705 default_charset_, &charset_error,
706 &default_charset_error);
707 if (src == 0)
708 {
709 /* if we had a problem loading the default character set, log it */
710 if (default_charset_error)
711 log_error(TCERR_CANT_LOAD_DEFAULT_CHARSET, default_charset_);
712
713 /* return failure */
714 return TCERR_CANT_OPEN_SRC;
715 }
716
717 /* find or create a file descriptor for this filename */
718 desc = get_file_desc(src_filename, strlen(src_filename), FALSE,
719 orig_name, strlen(orig_name));
720
721 /*
722 * Create a stream to read the source file. The new stream has no
723 * parent, because this is the top-level source file, and was not
724 * included from any other file.
725 */
726 str_ = new CTcTokStream(desc, src, 0, charset_error, if_sp_);
727
728 /* success */
729 return 0;
730 }
731
732 /*
733 * Set up to read source code from a memory buffer
734 */
735 void CTcTokenizer::set_source_buf(const char *buf, size_t len)
736 {
737 CTcSrcMemory *src;
738
739 /* empty out the input line buffer */
740 clear_linebuf();
741
742 /* reset the scanning state to the start of a brand new stream */
743 in_pp_expr_ = FALSE;
744 last_linenum_ = 0;
745 unsplicebuf_.clear_text();
746 in_quote_ = '\0';
747 in_triple_ = FALSE;
748 comment_in_embedding_.reset();
749 macro_in_embedding_.reset();
750 main_in_embedding_.reset();
751 if_sp_ = 0;
752 if_false_level_ = 0;
753 unget_cur_ = 0;
754
755 /* set up at the beginning of the input line buffer */
756 start_new_line(&linebuf_, 0);
757
758 /* create a reader for the memory buffer */
759 src = new CTcSrcMemory(buf, len, default_mapper_);
760
761 /*
762 * Create a stream to read the source file. The new stream has no
763 * parent, because this is the top-level source file, and was not
764 * included from any other file.
765 */
766 str_ = new CTcTokStream(0, src, 0, 0, if_sp_);
767 }
768
769 /* ------------------------------------------------------------------------ */
770 /*
771 * Stuff text into the source stream.
772 */
773 void CTcTokenizer::stuff_text(const char *txt, size_t len, int expand)
774 {
775 CTcTokString expbuf;
776 int p_ofs;
777
778 /* if desired, expand macros */
779 if (expand)
780 {
781 /* expand macros in the text, storing the result in 'expbuf' */
782 expand_macros(&expbuf, txt, len);
783
784 /* use the expanded version as the stuffed text now */
785 txt = expbuf.get_text();
786 len = expbuf.get_text_len();
787 }
788
789 /* get the current p_ offset */
790 p_ofs = p_.getptr() - curbuf_->get_text();
791
792 /* insert the text into the buffer */
793 curbuf_->insert(p_ofs, txt, len);
794
795 /* reset p_ in case the curbuf_ buffer was reallocated for expansion */
796 start_new_line(curbuf_, p_ofs);
797 }
798
799 /* ------------------------------------------------------------------------ */
800 /*
801 * Find or create a file descriptor for a given filename
802 */
803 CTcTokFileDesc *CTcTokenizer::get_file_desc(const char *fname,
804 size_t fname_len,
805 int always_create,
806 const char *orig_fname,
807 size_t orig_fname_len)
808 {
809 CTcTokFileDesc *orig_desc;
810 CTcTokFileDesc *desc;
811
812 /* presume we won't find an original descriptor in the list */
813 orig_desc = 0;
814
815 /*
816 * Search the list of existing descriptors to find one that matches.
817 * Do this regardless of whether we're allowed to re-use an existing
818 * one or not - even if we're creating a new one unconditionaly, we
819 * need to know if there's an earlier copy that already exists so we
820 * can associate the new one with the original.
821 */
822 for (desc = desc_head_ ; desc != 0 ; desc = desc->get_next())
823 {
824 /* check for a name match */
825 if (strlen(desc->get_fname()) == fname_len
826 && memcmp(desc->get_fname(), fname, fname_len) == 0)
827 {
828 /*
829 * if we're allowed to return an existing descriptor, return
830 * this one, since it's for the same filename
831 */
832 if (!always_create)
833 return desc;
834
835 /*
836 * we have to create a new descriptor even though we have an
837 * existing one - remember the original so we can point the
838 * new one back to the original
839 */
840 orig_desc = desc;
841
842 /*
843 * no need to look any further - we've found the first
844 * instance of this filename in our list
845 */
846 break;
847 }
848 }
849
850 /* we didn't find a match - create a new descriptor */
851 desc = new CTcTokFileDesc(fname, fname_len, next_filedesc_id_++,
852 orig_desc, orig_fname, orig_fname_len);
853
854 /* link it in at the end of the master list */
855 desc->set_next(0);
856 if (desc_tail_ == 0)
857 desc_head_ = desc;
858 else
859 desc_tail_->set_next(desc);
860 desc_tail_ = desc;
861
862 /* expand our array index if necessary */
863 if (desc_list_cnt_ >= desc_list_alo_)
864 {
865 size_t siz;
866
867 /* allocate or expand the array */
868 desc_list_alo_ += 10;
869 siz = desc_list_alo_ * sizeof(desc_list_[0]);
870 if (desc_list_ == 0)
871 desc_list_ = (CTcTokFileDesc **)t3malloc(siz);
872 else
873 desc_list_ = (CTcTokFileDesc **)t3realloc(desc_list_, siz);
874 }
875
876 /* add the new array entry */
877 desc_list_[desc_list_cnt_++] = desc;
878
879 /* return it */
880 return desc;
881 }
882
883
884 /* ------------------------------------------------------------------------ */
885 /*
886 * Add an include path entry. Each new entry goes at the end of the
887 * list, after all previous entries.
888 */
889 void CTcTokenizer::add_inc_path(const char *path)
890 {
891 tctok_incpath_t *entry;
892
893 /* create a new path list entry */
894 entry = (tctok_incpath_t *)t3malloc(sizeof(tctok_incpath_t)
895 + strlen(path));
896
897 /* store the path in the entry */
898 strcpy(entry->path, path);
899
900 /* link this entry at the end of our list */
901 if (incpath_tail_ != 0)
902 incpath_tail_->nxt = entry;
903 else
904 incpath_head_ = entry;
905 incpath_tail_ = entry;
906 entry->nxt = 0;
907 }
908
909
910 /* ------------------------------------------------------------------------ */
911 /*
912 * Set the string capture file.
913 */
914 void CTcTokenizer::set_string_capture(osfildef *fp)
915 {
916 /* delete any old capture file */
917 if (string_fp_ != 0)
918 delete string_fp_;
919
920 /*
921 * Remember the new capture file. Use a duplicate handle, since we
922 * pass ownership of the handle to the CVmFileSource object (i.e.,
923 * it'll close the handle when done).
924 */
925 string_fp_ = new CVmFileSource(osfdup(fp, "w"));
926
927 /*
928 * if we don't already have a character mapping to translate from
929 * our internal unicode characters back into the source file
930 * character set, create one now
931 */
932 if (string_fp_map_ == 0)
933 {
934 /* try creating a mapping for the default character set */
935 if (default_charset_ != 0)
936 string_fp_map_ =
937 CCharmapToLocal::load(res_loader_, default_charset_);
938
939 /* if we couldn't create the mapping, use a default ASCII mapping */
940 if (string_fp_map_ == 0)
941 string_fp_map_ = CCharmapToLocal::load(res_loader_, "us-ascii");
942 }
943 }
944
945
946 /* ------------------------------------------------------------------------ */
947 /*
948 * Get the next token in the input stream, reading additional lines from
949 * the source file as needed.
950 */
951 tc_toktyp_t CTcTokenizer::next()
952 {
953 /* the current token is about to become the previous token */
954 prvtok_ = curtok_;
955
956 /* if there's an un-got token, return it */
957 if (unget_cur_ != 0)
958 {
959 /* get the current unget token */
960 curtok_ = *unget_cur_;
961
962 /* we've now consumed this ungotten token */
963 unget_cur_ = unget_cur_->getprv();
964
965 /* return the new token's type */
966 return curtok_.gettyp();
967 }
968
969 /* if there's an external source, get its next token */
970 if (ext_src_ != 0)
971 {
972 const CTcToken *ext_tok;
973
974 /* get the next token from the external source */
975 ext_tok = ext_src_->get_next_token();
976
977 /* check to see if we got a token */
978 if (ext_tok == 0)
979 {
980 /*
981 * restore the current token in effect before this source was
982 * active
983 */
984 curtok_ = *ext_src_->get_enclosing_curtok();
985
986 /*
987 * this source has no more tokens - restore the enclosing
988 * source, and keep going so we try getting a token from it
989 */
990 ext_src_ = ext_src_->get_enclosing_source();
991
992 /* return the token type */
993 return curtok_.gettyp();
994 }
995 else
996 {
997 /* we got a token - copy it to our internal token buffer */
998 curtok_ = *ext_tok;
999
1000 /* return its type */
1001 return curtok_.gettyp();
1002 }
1003 }
1004
1005 /* keep going until we get a valid token */
1006 for (;;)
1007 {
1008 /*
1009 * read the next token from the current line, applying
1010 * appropriate string translations and storing strings and
1011 * symbols in the source block list
1012 */
1013 tc_toktyp_t typ = next_on_line_xlat_keep();
1014
1015 /* if it's the "null" token, skip it and read another token */
1016 if (typ == TOKT_NULLTOK)
1017 continue;
1018
1019 /* if we found a valid token, we're done - return the token */
1020 if (typ != TOKT_EOF)
1021 return typ;
1022
1023 /*
1024 * if we're at the end of a preprocess line, don't read another
1025 * line - just return end of file
1026 */
1027 if (p_.getch() == TOK_END_PP_LINE)
1028 return TOKT_EOF;
1029
1030 /*
1031 * we've reached the end of the line - read another line,
1032 * applying preprocessing directives and expanding macros as
1033 * needed
1034 */
1035 if (read_line_pp())
1036 {
1037 /* no more lines are available - return end of file */
1038 return TOKT_EOF;
1039 }
1040 }
1041 }
1042
1043 /* ------------------------------------------------------------------------ */
1044 /*
1045 * clear external token sources, returning to the true input stream
1046 */
1047 void CTcTokenizer::clear_external_sources()
1048 {
1049 /*
1050 * restore the current token as it was before the outermost external
1051 * source was first established
1052 */
1053 if (ext_src_ != 0)
1054 {
1055 CTcTokenSource *outer;
1056
1057 /* find the outermost source */
1058 for (outer = ext_src_ ; outer->get_enclosing_source() != 0 ;
1059 outer = ext_src_->get_enclosing_source()) ;
1060
1061 /* restore its original next token */
1062 curtok_ = *ext_src_->get_enclosing_curtok();
1063 }
1064
1065 /* there's no external source now */
1066 ext_src_ = 0;
1067 }
1068
1069 /* ------------------------------------------------------------------------ */
1070 /*
1071 * Make a safely storable copy of the current token.
1072 */
1073 const CTcToken *CTcTokenizer::copycur()
1074 {
1075 /* if it's already a type that we store safely, return the current token */
1076 if (is_tok_safe(curtok_.gettyp()))
1077 return getcur();
1078
1079 /* save the current token's text in permanent tokenizer memory */
1080 curtok_.set_text(store_source(curtok_.get_text(), curtok_.get_text_len()),
1081 curtok_.get_text_len());
1082
1083 /* return the current token, now that we've made it safe */
1084 return &curtok_;
1085 }
1086
1087 /*
1088 * Make a safely storable copy of a given token.
1089 */
1090 void CTcTokenizer::copytok(CTcToken *dst, const CTcToken *src)
1091 {
1092 /* start with an exact copy of the token */
1093 *dst = *src;
1094
1095 /* if the token is a symbol, it already has a safe copy */
1096 if (is_tok_safe(src->gettyp()))
1097 return;
1098
1099 /* save the token's text in permanent tokenizer memory */
1100 dst->set_text(store_source(dst->get_text(), dst->get_text_len()),
1101 dst->get_text_len());
1102 }
1103
1104 /*
1105 * Is the given token type "safe"? A safe token is one whose text is
1106 * always saved in the tokenizer source list, which means that the text
1107 * pointer is safe as long as the tokenizer object exists. A non-safe
1108 * token is one whose text pointer points directly into the current line
1109 * buffer, meaning that its text buffer is only guaranteed to last until
1110 * the next token fetch.
1111 */
1112 int CTcTokenizer::is_tok_safe(tc_toktyp_t typ)
1113 {
1114 switch (typ)
1115 {
1116 case TOKT_SYM:
1117 case TOKT_SSTR:
1118 case TOKT_SSTR_START:
1119 case TOKT_SSTR_MID:
1120 case TOKT_SSTR_END:
1121 case TOKT_DSTR:
1122 case TOKT_DSTR_START:
1123 case TOKT_DSTR_MID:
1124 case TOKT_DSTR_END:
1125 case TOKT_RESTR:
1126 case TOKT_FLOAT:
1127 case TOKT_BIGINT:
1128 /* these types are always stored in the source list */
1129 return TRUE;
1130
1131 default:
1132 /* other types are not always safely stored */
1133 return FALSE;
1134 }
1135 }
1136
1137
1138 /* ------------------------------------------------------------------------ */
1139 /*
1140 * Check to see if the current token matches the given text
1141 */
1142 int CTcTokenizer::cur_tok_matches(const char *txt, size_t len)
1143 {
1144 /* if the length matches, and the text matches exactly, it matches */
1145 return (getcur()->get_text_len() == len
1146 && memcmp(getcur()->get_text(), txt, len) == 0);
1147 }
1148
1149 /* ------------------------------------------------------------------------ */
1150 /*
1151 * Look ahead to see if we match a pair of symbol tokens
1152 */
1153 int CTcTokenizer::look_ahead(const char *s1, const char *s2)
1154 {
1155 /* if the first token doesn't match, the sequence doesn't match */
1156 if (cur() != TOKT_SYM || !cur_tok_matches(s1, strlen(s1)))
1157 return FALSE;
1158
1159 /* check the next token - if it matches, we have a sequence match */
1160 if (next() == TOKT_SYM && cur_tok_matches(s2, strlen(s2)))
1161 {
1162 /* got it - skip the second token and return success */
1163 next();
1164 return TRUE;
1165 }
1166
1167 /*
1168 * no match - but we've already read the next token, so put it back
1169 * before we return failure
1170 */
1171 unget();
1172 return FALSE;
1173 }
1174
1175 /*
1176 * Peek ahead - same as look_ahead, but doesn't skip anything on a
1177 * successful match.
1178 */
1179 int CTcTokenizer::peek_ahead(const char *s1, const char *s2)
1180 {
1181 /* if the first token doesn't match, the sequence doesn't match */
1182 if (cur() != TOKT_SYM || !cur_tok_matches(s1, strlen(s1)))
1183 return FALSE;
1184
1185 /* check the next token - if it matches, we have a sequence match */
1186 int match = (next() == TOKT_SYM && cur_tok_matches(s2, strlen(s2)));
1187
1188 /* whatever happened, un-get the second token, since we're just peeking */
1189 unget();
1190
1191 /* return the match indication */
1192 return match;
1193 }
1194
1195
1196 /* ------------------------------------------------------------------------ */
1197 /*
1198 * Un-get the current token
1199 */
1200 void CTcTokenizer::unget()
1201 {
1202 /* unget, backing up to the internally saved previous token */
1203 unget(&prvtok_);
1204 }
1205
1206 /*
1207 * Un-get the current token and back up to the specified previous token.
1208 */
1209 void CTcTokenizer::unget(const CTcToken *prv)
1210 {
1211 /* push the current token onto the unget stack */
1212 push(&curtok_);
1213
1214 /* go back to the previous token */
1215 curtok_ = *prv;
1216
1217 /* the internally saved previous token is no longer valid */
1218 prvtok_.settyp(TOKT_INVALID);
1219 }
1220
1221 /*
1222 * Push a token into the stream
1223 */
1224 void CTcTokenizer::push(const CTcToken *tok)
1225 {
1226 /* if the unget list is empty, create the initial entry */
1227 if (unget_head_ == 0)
1228 unget_head_ = new CTcTokenEle();
1229
1230 /* advance to the next slot in the list */
1231 if (unget_cur_ == 0)
1232 {
1233 /* no last ungot token - set up at the head of the list */
1234 unget_cur_ = unget_head_;
1235 }
1236 else if (unget_cur_->getnxt() != 0)
1237 {
1238 /* there's another slot available - advance to it */
1239 unget_cur_ = unget_cur_->getnxt();
1240 }
1241 else
1242 {
1243 /* the list is full - we need to allocate a new slot */
1244 CTcTokenEle *newele = new CTcTokenEle();
1245
1246 /* link it at the end of the list */
1247 unget_cur_->setnxt(newele);
1248 newele->setprv(unget_cur_);
1249
1250 /* advance to it */
1251 unget_cur_ = newele;
1252 }
1253
1254 /* save the pushed token */
1255 unget_cur_->set(*tok);
1256 }
1257
1258 /* ------------------------------------------------------------------------ */
1259 /*
1260 * Assume that we should have just found a '>>' terminating an embedded
1261 * expression in a string. If possible, back out the previous token and
1262 * re-scan it as though it had started with '>>'.
1263 *
1264 * This is to be called by a higher-level parser when it determines that,
1265 * syntactically, we should have found the '>>' leaving an embedded
1266 * expression.
1267 */
1268 void CTcTokenizer::assume_missing_str_cont()
1269 {
1270 xlat_string_to_src(&main_in_embedding_, TRUE);
1271 }
1272
1273
1274 /* ------------------------------------------------------------------------ */
1275 /*
1276 * Skip whitespace and macro expansion markers
1277 */
1278 void CTcTokenizer::skip_ws_and_markers(utf8_ptr *p)
1279 {
1280 /* keep going until we find something interesting */
1281 for (;;)
1282 {
1283 wchar_t cur;
1284
1285 /* get the current character */
1286 cur = p->getch();
1287
1288 /*
1289 * if it's a macro expansion end marker, skip it as though it
1290 * were whitespace; otherwise, if it's whitespace, skip it;
1291 * otherwise, we're done skipping leading whitespace
1292 */
1293 if (cur == TOK_MACRO_EXP_END)
1294 {
1295 /* skip the embedded pointer value that follows */
1296 p->set(p->getptr() + 1 + sizeof(CTcHashEntryPp *));
1297 }
1298 else if (is_space(cur))
1299 {
1300 /* skip the space */
1301 p->inc();
1302 }
1303 else
1304 {
1305 /* it's not whitespace or equivalent - we're done */
1306 return;
1307 }
1308 }
1309 }
1310
1311 /* ------------------------------------------------------------------------ */
1312 /*
1313 * Get the next token from the input stream, operating on the current
1314 * line only.
1315 */
1316 tc_toktyp_t CTcTokenizer::next_on_line(utf8_ptr *p, CTcToken *tok,
1317 tok_embed_ctx *ec, int expanding)
1318 {
1319 tc_toktyp_t typ;
1320
1321 /* skip whitespace */
1322 skip_ws_and_markers(p);
1323
1324 /* remember where the token starts */
1325 utf8_ptr start = *p;
1326
1327 /* get the initial character */
1328 wchar_t cur = p->getch();
1329
1330 /* if there's nothing left in the current line, return EOF */
1331 if (cur == '\0')
1332 {
1333 /* indicate end of file */
1334 typ = TOKT_EOF;
1335 goto done;
1336 }
1337
1338 /* skip the initial character */
1339 p->inc();
1340
1341 /* presume the token will not be marked as fully macro-expanded */
1342 tok->set_fully_expanded(FALSE);
1343
1344 /* see what we have */
1345 switch(cur)
1346 {
1347 case TOK_MACRO_FORMAL_FLAG:
1348 /*
1349 * this is a two-byte formal parameter sequence in a macro
1350 * expansion - skip the second byte of the two-byte sequence,
1351 * and return the special token type for this sequence
1352 */
1353 typ = TOKT_MACRO_FORMAL;
1354
1355 /*
1356 * skip the second byte - note that we want to skip exactly one
1357 * byte, regardless of what the byte looks like as a utf-8
1358 * partial character, since it's not a utf-8 character at all
1359 */
1360 p->set(p->getptr() + 1);
1361 break;
1362
1363 case TOK_MACRO_FOREACH_FLAG:
1364 /*
1365 * this is the special macro '#foreach' flag - return it as a
1366 * special pseudo-token
1367 */
1368 typ = TOKT_MACRO_FOREACH;
1369 break;
1370
1371 case TOK_MACRO_IFEMPTY_FLAG:
1372 /* #ifempty macro flag */
1373 typ = TOKT_MACRO_IFEMPTY;
1374 break;
1375
1376 case TOK_MACRO_IFNEMPTY_FLAG:
1377 /* #ifnempty macro flag */
1378 typ = TOKT_MACRO_IFNEMPTY;
1379 break;
1380
1381 case TOK_MACRO_ARGCOUNT_FLAG:
1382 /* it's the special macro '#argcount' flag */
1383 typ = TOKT_MACRO_ARGCOUNT;
1384 break;
1385
1386 case TOK_FULLY_EXPANDED_FLAG:
1387 /* set the token flag indicating that it has been fully expanded */
1388 tok->set_fully_expanded(TRUE);
1389
1390 /* the token symbol starts at the byte after the flag byte */
1391 start = p->getptr();
1392
1393 /* read the first character of the symbol */
1394 cur = p->getch();
1395 p->inc();
1396
1397 /* tokenize the symbol that follows */
1398 goto tokenize_symbol;
1399
1400 case TOK_END_PP_LINE:
1401 /*
1402 * Preprocess line-ending marker - when we reach the end of a
1403 * preprocessor line, we can't read another source line, because
1404 * a preprocessor directive consists of only a single logical
1405 * source line. Once we see this, return end-of-file until the
1406 * caller explicitly reads a new source line.
1407 *
1408 * Keep the read pointer stuck on this flag byte, so that we
1409 * return end-of-file on a subsequent attempt to get the next
1410 * token.
1411 */
1412 *p = start;
1413 typ = TOKT_EOF;
1414 break;
1415
1416 case '0':
1417 case '1':
1418 case '2':
1419 case '3':
1420 case '4':
1421 case '5':
1422 case '6':
1423 case '7':
1424 case '8':
1425 case '9':
1426 {
1427 /*
1428 * Start out with the leading digit in the accumulator. Note
1429 * that the character set internally is always UTF-8.
1430 */
1431 ulong acc = value_of_digit(cur);
1432
1433 /*
1434 * The overflow limit differs for positive and negative values,
1435 * but we can't be sure at this point which we have, since even
1436 * if there's a '-' before the number, it could be a
1437 * subtraction operator rather than a negation operator. We
1438 * can't know until we've folded constants whether the number
1439 * is positive or negative. Use the lower limit for now; the
1440 * compiler will un-promote values after constant folding if
1441 * they end up fitting after all, which will handle the case of
1442 * INT32MINVAL, whose absolute value is higher than this limit.
1443 */
1444 const ulong ovlimit = 2147483647U;
1445
1446 /*
1447 * If it's a leading zero, treat as octal or hex. '0x' means
1448 * hex; otherwise, '0' means octal.
1449 */
1450 if (cur == '0')
1451 {
1452 /* check for hex - if it's not hex, it's octal */
1453 if (p->getch() == 'x' || p->getch() == 'X')
1454 {
1455 /* skip the 'x' */
1456 p->inc();
1457
1458 /*
1459 * scan the hex number - keep going until we find
1460 * something that's not a hex digit
1461 */
1462 for (;;)
1463 {
1464 /* get this character */
1465 cur = p->getch();
1466
1467 /* if it's not a hex digit, stop scanning */
1468 if (!is_xdigit(cur))
1469 break;
1470
1471 /* check for 32-bit integer overflow */
1472 if ((acc & 0xF0000000) != 0)
1473 goto do_int_overflow;
1474
1475 /*
1476 * Shift the accumulator and add this digit's value.
1477 * Note that we can save a test - if the character is
1478 * >= lower-case 'a', we know it's not an upper-case
1479 * letter because the lower-case letters all have
1480 * values above the upper-case letters in UTF-8
1481 * encoding (which we always use as the internal
1482 * character set). Since we already know it's a
1483 * valid hex digit (we wouldn't be here if it
1484 * weren't), we can just check to see if it's at
1485 * least lower-case 'a', and we automatically know
1486 * then whether it's in the 'a'-'f' range or the
1487 * 'A'-'F' range.
1488 */
1489 acc *= 16;
1490 acc += value_of_xdigit(cur);
1491
1492 /* move on */
1493 p->inc();
1494 }
1495 }
1496 else
1497 {
1498 /* scan octal digits */
1499 for ( ; is_odigit(p->getch()) ; p->inc())
1500 {
1501 /* check for overflow */
1502 if ((acc & 0xE0000000) != 0)
1503 goto do_int_overflow;
1504
1505 /* add the digit */
1506 acc = 8*acc + value_of_odigit(p->getch());
1507 }
1508
1509 /*
1510 * If we stopped on a digit outside of the octal range,
1511 * consume any remaining digits, and flag it as an
1512 * error. Leaving subsequent decimal digits as a
1513 * separate token tends to be confusing, since in most
1514 * cases the inclusion of decimal digits means that the
1515 * user didn't really intend this to be an octal number
1516 * after all. For instance, the leading zero might be
1517 * there for formatting reasons, and the user simply
1518 * forgot to take into account that it triggers octal
1519 * interpretation.
1520 */
1521 if (is_digit(p->getch()))
1522 {
1523 /* skip subsequent digits */
1524 for (p->inc() ; is_digit(p->getch()) ; p->inc()) ;
1525
1526 /* flag the error */
1527 if (!expanding)
1528 log_error(TCERR_DECIMAL_IN_OCTAL,
1529 p->getptr() - start.getptr(),
1530 start.getptr());
1531 }
1532 }
1533 }
1534 else
1535 {
1536 /* scan decimal digits */
1537 for ( ; is_digit(p->getch()) ; p->inc())
1538 {
1539 /* check for integer overflow in the shift */
1540 if (acc > 214748364)
1541 goto do_int_overflow;
1542
1543 /* shift the accumulator */
1544 acc *= 10;
1545
1546 /* get the digit */
1547 int d = value_of_digit(p->getch());
1548
1549 /* check for overflow adding the digit */
1550 if ((unsigned)acc > ovlimit - d)
1551 goto do_int_overflow;
1552
1553 /* add the digit */
1554 acc += d;
1555 }
1556 }
1557
1558 /*
1559 * If we stopped at a decimal point or an exponent, it's a
1560 * floating point number. This doesn't count if we have two
1561 * periods in a row - ".." - because that's either a range
1562 * marker operator or an ellipsis operator.
1563 */
1564 if (p->getch() == '.' && p->getch_at(1) != '.')
1565 {
1566 typ = TOKT_FLOAT;
1567 goto do_float;
1568 }
1569 else if (p->getch() == 'e' || p->getch() == 'E')
1570 {
1571 typ = TOKT_FLOAT;
1572 goto do_float;
1573 }
1574
1575 /* it's an integer value */
1576 typ = TOKT_INT;
1577
1578 /* set the integer value */
1579 tok->set_int_val(acc);
1580 }
1581 break;
1582
1583 do_int_overflow:
1584 /* mark it as an integer that overflowed into a float type */
1585 typ = TOKT_BIGINT;
1586
1587 do_float:
1588 {
1589 /* haven't found a decimal point yet */
1590 int found_decpt = FALSE;
1591 int is_hex = FALSE;
1592
1593 /* start over at the beginning of the number */
1594 *p = start;
1595
1596 /* skip any leading sign */
1597 if (p->getch() == '-')
1598 p->inc();
1599
1600 /* skip any leading "0x" */
1601 if (typ == TOKT_BIGINT && p->getch() == '0')
1602 {
1603 wchar_t c1 = p->getch_at(1);
1604 if (c1 == 'x' || c1 == 'X')
1605 {
1606 is_hex = TRUE;
1607 p->inc_by(2);
1608 }
1609 }
1610
1611 /* parse the rest of the float */
1612 for ( ; ; p->inc())
1613 {
1614 /* get this character and move on */
1615 cur = p->getch();
1616
1617 /* see what we have */
1618 if (is_digit(cur))
1619 {
1620 /* we have another digit; just keep going */
1621 }
1622 else if (is_hex && is_xdigit(cur))
1623 {
1624 /* we have another hex digit, so keep going */
1625 }
1626 else if (!found_decpt && !is_hex && cur == '.')
1627 {
1628 /* it's the decimal point - note it and keep going */
1629 found_decpt = TRUE;
1630
1631 /* if it started as a promoted int, it's really a float */
1632 if (typ == TOKT_BIGINT)
1633 typ = TOKT_FLOAT;
1634 }
1635 else if (cur == 'e' || cur == 'E')
1636 {
1637 /* it might not be an exponent - look ahead to find out */
1638 utf8_ptr p2 = *p;
1639 p2.inc();
1640
1641 /* if we have a sign, skip it */
1642 if ((cur = p2.getch()) == '-' || cur == '+')
1643 p2.inc();
1644
1645 /* we need at least one digit to make an exponent */
1646 if (!is_digit(p2.getch()))
1647 break;
1648
1649 /* skip digits */
1650 while (is_digit(p2.getch()))
1651 p2.inc();
1652
1653 /* advance to the end of the exponent */
1654 *p = p2;
1655
1656 /* if it started as a promoted int, it's now a float */
1657 if (typ == TOKT_BIGINT)
1658 typ = TOKT_FLOAT;
1659
1660 /* the end of the exponent is the end of the number */
1661 break;
1662 }
1663 else
1664 {
1665 /* everything else ends the number */
1666 break;
1667 }
1668 }
1669 }
1670 break;
1671
1672 case '"':
1673 case '\'':
1674 *p = start;
1675 return tokenize_string(p, tok, ec, expanding);
1676
1677 case '(':
1678 typ = TOKT_LPAR;
1679 if (ec != 0)
1680 ec->parens(1);
1681 break;
1682
1683 case ')':
1684 typ = TOKT_RPAR;
1685 if (ec != 0)
1686 ec->parens(-1);
1687 break;
1688
1689 case ',':
1690 typ = TOKT_COMMA;
1691 break;
1692
1693 case '.':
1694 /* check for '..', '...', and floating-point numbers */
1695 if (p->getch() == '.')
1696 {
1697 /* it's either '..' or '...' */
1698 p->inc();
1699 if (p->getch() == '.')
1700 {
1701 p->inc();
1702 typ = TOKT_ELLIPSIS;
1703 }
1704 else
1705 typ = TOKT_DOTDOT;
1706 }
1707 else if (is_digit(p->getch()))
1708 {
1709 typ = TOKT_FLOAT;
1710 goto do_float;
1711 }
1712 else
1713 typ = TOKT_DOT;
1714 break;
1715
1716 case '{':
1717 typ = TOKT_LBRACE;
1718 if (ec != 0)
1719 ec->parens(1);
1720 break;
1721
1722 case '}':
1723 typ = TOKT_RBRACE;
1724 if (ec != 0)
1725 ec->parens(-1);
1726 break;
1727
1728 case '[':
1729 typ = TOKT_LBRACK;
1730 if (ec != 0)
1731 ec->parens(1);
1732 break;
1733
1734 case ']':
1735 typ = TOKT_RBRACK;
1736 if (ec != 0)
1737 ec->parens(-1);
1738 break;
1739
1740 case '=':
1741 /* check for '==' */
1742 if (p->getch() == '=')
1743 {
1744 p->inc();
1745 typ = TOKT_EQEQ;
1746 }
1747 else
1748 typ = TOKT_EQ;
1749 break;
1750
1751 case ':':
1752 /* check for '::' */
1753 if (p->getch() == ':')
1754 {
1755 p->inc();
1756 typ = TOKT_COLONCOLON;
1757 }
1758 else
1759 typ = TOKT_COLON;
1760 break;
1761
1762 case '?':
1763 /* check for '??' */
1764 if (p->getch() == '?')
1765 {
1766 p->inc();
1767 typ = TOKT_QQ;
1768 }
1769 else
1770 typ = TOKT_QUESTION;
1771 break;
1772
1773 case '+':
1774 /* check for '++' and '+=' */
1775 if (p->getch() == '+')
1776 {
1777 p->inc();
1778 typ = TOKT_INC;
1779 }
1780 else if (p->getch() == '=')
1781 {
1782 p->inc();
1783 typ = TOKT_PLUSEQ;
1784 }
1785 else
1786 typ = TOKT_PLUS;
1787 break;
1788
1789 case '-':
1790 /* check for '--', '->' and '-=' */
1791 if (p->getch() == '-')
1792 {
1793 p->inc();
1794 typ = TOKT_DEC;
1795 }
1796 else if (p->getch() == '=')
1797 {
1798 p->inc();
1799 typ = TOKT_MINEQ;
1800 }
1801 else if (p->getch() == '>')
1802 {
1803 p->inc();
1804 typ = TOKT_ARROW;
1805 }
1806 else
1807 typ = TOKT_MINUS;
1808 break;
1809
1810 case '*':
1811 /* check for '*=' */
1812 if (p->getch() == '=')
1813 {
1814 p->inc();
1815 typ = TOKT_TIMESEQ;
1816 }
1817 else
1818 typ = TOKT_TIMES;
1819 break;
1820
1821 case '/':
1822 /* check for '/=' */
1823 if (p->getch() == '=')
1824 {
1825 p->inc();
1826 typ = TOKT_DIVEQ;
1827 }
1828 else
1829 typ = TOKT_DIV;
1830 break;
1831
1832 case '%':
1833 /* check for '%=' */
1834 if (p->getch() == '=')
1835 {
1836 p->inc();
1837 typ = TOKT_MODEQ;
1838 }
1839 else
1840 typ = TOKT_MOD;
1841 break;
1842
1843 case '>':
1844 /* check for '>>=', '>>' and '>=' */
1845 if (p->getch() == '=')
1846 {
1847 p->inc();
1848 typ = TOKT_GE;
1849 }
1850 else if (p->getch() == '>')
1851 {
1852 /* check for the end of an embedded expression */
1853 if (ec != 0 && ec->in_expr() && ec->parens() == 0)
1854 {
1855 *p = start;
1856 return tokenize_string(p, tok, ec, expanding);
1857 }
1858
1859 /* check for '>>>' and '>>=' */
1860 p->inc();
1861 if (p->getch() == '>')
1862 {
1863 /* skip the '>' and check for '>>>=' */
1864 p->inc();
1865 if (p->getch() == '=')
1866 {
1867 p->inc();
1868 typ = TOKT_LSHREQ;
1869 }
1870 else
1871 typ = TOKT_LSHR;
1872 }
1873 else if (p->getch() == '=')
1874 {
1875 p->inc();
1876 typ = TOKT_ASHREQ;
1877 }
1878 else
1879 typ = TOKT_ASHR;
1880 }
1881 else
1882 typ = TOKT_GT;
1883 break;
1884
1885 case '<':
1886 /* check for '<<=', '<<', '<>', and '<=' */
1887 if (p->getch() == '=')
1888 {
1889 p->inc();
1890 typ = TOKT_LE;
1891 }
1892 else if (p->getch() == '<')
1893 {
1894 /* check for '<<=' */
1895 p->inc();
1896 if (p->getch() == '=')
1897 {
1898 p->inc();
1899 typ = TOKT_SHLEQ;
1900 }
1901 else
1902 typ = TOKT_SHL;
1903 }
1904 #if 0
1905 else if (p->getch() == '>')
1906 {
1907 /* '<>' is obsolete */
1908 if (!expanding)
1909 log_error(TCERR_LTGT_OBSOLETE);
1910
1911 /* ... but for now proceed as though it's != */
1912 p->inc();
1913 typ = TOKT_NE;
1914 }
1915 #endif
1916 else
1917 typ = TOKT_LT;
1918 break;
1919
1920 case ';':
1921 typ = TOKT_SEM;
1922 break;
1923
1924 case '&':
1925 /* check for '&&' and '&=' */
1926 if (p->getch() == '&')
1927 {
1928 p->inc();
1929 typ = TOKT_ANDAND;
1930 }
1931 else if (p->getch() == '=')
1932 {
1933 p->inc();
1934 typ = TOKT_ANDEQ;
1935 }
1936 else
1937 typ = TOKT_AND;
1938 break;
1939
1940 case '|':
1941 /* check for '||' and '|=' */
1942 if (p->getch() == '|')
1943 {
1944 p->inc();
1945 typ = TOKT_OROR;
1946 }
1947 else if (p->getch() == '=')
1948 {
1949 p->inc();
1950 typ = TOKT_OREQ;
1951 }
1952 else
1953 typ = TOKT_OR;
1954 break;
1955
1956 case '^':
1957 /* check for '^=' */
1958 if (p->getch() == '=')
1959 {
1960 p->inc();
1961 typ = TOKT_XOREQ;
1962 }
1963 else
1964 typ = TOKT_XOR;
1965 break;
1966
1967 case '!':
1968 /* check for '!=' */
1969 if (p->getch() == '=')
1970 {
1971 p->inc();
1972 typ = TOKT_NE;
1973 }
1974 else
1975 typ = TOKT_NOT;
1976 break;
1977
1978 case '~':
1979 typ = TOKT_BNOT;
1980 break;
1981
1982 case '@':
1983 typ = TOKT_AT;
1984 break;
1985
1986 case '#':
1987 /* check for '##' and '#@' */
1988 if (p->getch() == '#')
1989 {
1990 p->inc();
1991 typ = TOKT_POUNDPOUND;
1992 }
1993 else if (p->getch() == '@')
1994 {
1995 p->inc();
1996 typ = TOKT_POUNDAT;
1997 }
1998 else
1999 typ = TOKT_POUND;
2000 break;
2001
2002 case 'R':
2003 /* check for regular expression string syntax */
2004 if (p->getch() == '"' || p->getch() == '\'')
2005 {
2006 /*
2007 * It's a regular expression string. Tokenize the string
2008 * portion as normal, but mark it as a regex string rather than
2009 * a regular string.
2010 */
2011 *p = start;
2012 return tokenize_string(p, tok, ec, expanding);
2013 }
2014 /* not a regex string - fall through to default case */
2015
2016 default:
2017 /* check to see if it's a symbol */
2018 if (is_syminit(cur) || !is_ascii(cur))
2019 {
2020 tokenize_symbol:
2021 wchar_t non_ascii = 0;
2022 const char *stop = 0;
2023
2024 /* note if we're starting with a non-ASCII character */
2025 if (!is_ascii(cur))
2026 non_ascii = cur;
2027
2028 /*
2029 * scan the identifier (note that we've already skipped the
2030 * first character, so we start out at length = 1)
2031 */
2032 for (;;)
2033 {
2034 /*
2035 * If it's a non-ASCII character, assume it's an accented
2036 * character that's meant (erroneously) to be part of the
2037 * symbol name; note the error, but keep the character in
2038 * the symbol even though it's illegal, since this is more
2039 * likely to keep us synchronized with the intended token
2040 * structure of the source.
2041 *
2042 * Otherwise, stop on any non-symbol character.
2043 */
2044 wchar_t ch = p->getch();
2045 if (!is_ascii(ch))
2046 {
2047 if (non_ascii == 0)
2048 non_ascii = ch;
2049 }
2050 else if (!is_sym(ch))
2051 break;
2052
2053 /* skip this character */
2054 const char *prv = p->getptr();
2055 p->inc();
2056
2057 /* if this character would push us over the limit, end here */
2058 if (stop == 0
2059 && p->getptr() - start.getptr() >= TOK_SYM_MAX_LEN)
2060 stop = prv;
2061 }
2062
2063 /* if we found any non-ASCII characters, flag an error */
2064 if (non_ascii != 0)
2065 log_error(TCERR_NON_ASCII_SYMBOL,
2066 (int)(p->getptr() - start.getptr()), start.getptr(),
2067 (int)non_ascii);
2068
2069 /* if we truncated the symbol, issue a warning */
2070 if (stop != 0 && !expanding)
2071 log_warning(TCERR_SYMBOL_TRUNCATED,
2072 (int)(p->getptr() - start.getptr()), start.getptr(),
2073 (int)(stop - start.getptr()), start.getptr());
2074
2075 /* it's a symbol */
2076 typ = TOKT_SYM;
2077 }
2078 else
2079 {
2080 /* invalid token */
2081 typ = TOKT_INVALID;
2082 }
2083 break;
2084 }
2085
2086 done:
2087 /* set the type */
2088 tok->settyp(typ);
2089
2090 /* set the text */
2091 tok->set_text(start.getptr(), p->getptr() - start.getptr());
2092
2093 /* return the type */
2094 return typ;
2095 }
2096
2097 /*
2098 * get the next token, limiting to the length of the source buffer
2099 */
2100 tc_toktyp_t CTcTokenizer::next_on_line(const CTcTokString *srcbuf,
2101 utf8_ptr *p, CTcToken *tok,
2102 tok_embed_ctx *ec, int expanding)
2103 {
2104 /*
2105 * save the embedding context, in case the next token isn't part of the
2106 * narrowed section of the buffer we're scanning
2107 */
2108 tok_embed_ctx oldec = *ec;
2109
2110 /* get the next token */
2111 next_on_line(p, tok, ec, expanding);
2112
2113 /* if the token is past the end of the line, return EOF */
2114 if (tok->get_text() >= srcbuf->get_text_end())
2115 {
2116 /* set the token to indicate end of line */
2117 tok->settyp(TOKT_EOF);
2118
2119 /* set the token to point to the end of the buffer */
2120 tok->set_text(srcbuf->get_text_end(), 0);
2121
2122 /* restore the embedding context */
2123 *ec = oldec;
2124 }
2125
2126 /* return the token type */
2127 return tok->gettyp();
2128 }
2129
2130 /*
2131 * Get the next token on the line, translating escapes in strings. This
2132 * updates the line buffer in-place to incorporate the translated string
2133 * text.
2134 */
2135 tc_toktyp_t CTcTokenizer::next_on_line_xlat(utf8_ptr *p, CTcToken *tok,
2136 tok_embed_ctx *ec)
2137 {
2138 /* skip whitespace */
2139 skip_ws_and_markers(p);
2140
2141 /* if this is a string, translate escapes */
2142 switch(p->getch())
2143 {
2144 case '"':
2145 case '\'':
2146 /* translate the string */
2147 return xlat_string(p, tok, ec);
2148
2149 case '>':
2150 /* if we're in an embedding, check for '>>' */
2151 if (ec != 0 && ec->in_expr()
2152 && ec->parens() == 0
2153 && p->getch_at(1) == '>')
2154 return tokenize_string(p, tok, ec, FALSE);
2155
2156 /* use the default case */
2157 goto do_normal;
2158
2159 case 'R':
2160 /* check for a regex string */
2161 if (p->getch_at(1) == '"' || p->getch_at(1) == '\'')
2162 return tokenize_string(p, tok, ec, FALSE);
2163
2164 /* not a regex string - fall through to the default handling */
2165
2166 default:
2167 do_normal:
2168 /* for anything else, use the default tokenizer */
2169 return next_on_line(p, tok, ec, FALSE);
2170 }
2171 }
2172
2173 /*
2174 * Look up a keyword
2175 */
2176 int CTcTokenizer::look_up_keyword(const CTcToken *tok, tc_toktyp_t *kwtok)
2177 {
2178 CTcHashEntryKw *kw;
2179
2180 /* look it up in the keyword table */
2181 kw = (CTcHashEntryKw *)kw_->find(tok->get_text(), tok->get_text_len());
2182 if (kw != 0)
2183 {
2184 /* we found the keyword - set 'kw' to the keyword token id */
2185 *kwtok = kw->get_tok_id();
2186
2187 /* tell the caller we found it */
2188 return TRUE;
2189 }
2190 else
2191 {
2192 /* tell the caller it's not a keyword */
2193 return FALSE;
2194 }
2195 }
2196
2197 /*
2198 * Get the next token on the line, translating escape sequences in
2199 * strings, and storing strings and symbols in the source block list.
2200 * This routine also translates keywords for token types.
2201 */
2202 tc_toktyp_t CTcTokenizer::next_on_line_xlat_keep()
2203 {
2204 tc_toktyp_t typ;
2205
2206 /* keep going until we find a valid symbol */
2207 for (;;)
2208 {
2209 /* skip whitespace and macro expansion flags */
2210 skip_ws_and_markers(&p_);
2211
2212 /* see what we have */
2213 switch(p_.getch())
2214 {
2215 case '"':
2216 case '\'':
2217 /* it's a string - translate and save it */
2218 return xlat_string_to_src(&main_in_embedding_, FALSE);
2219
2220 case '>':
2221 /* if we're in an embedding, this is the end of it */
2222 if (main_in_embedding_.in_expr()
2223 && main_in_embedding_.parens() == 0
2224 && p_.getch_at(1) == '>')
2225 return xlat_string_to_src(&main_in_embedding_, FALSE);
2226
2227 /* use the normal parsing */
2228 goto do_normal;
2229
2230 case 'R':
2231 /* check for a regex string */
2232 if (p_.getch_at(1) == '"' || p_.getch_at(1) == '\'')
2233 return xlat_string_to_src(&main_in_embedding_, FALSE);
2234
2235 /* not a regex string - fall through to the default case */
2236
2237 default:
2238 do_normal:
2239 /* for anything else, use the default tokenizer */
2240 typ = next_on_line(&p_, &curtok_, &main_in_embedding_, FALSE);
2241
2242 /* check the token type */
2243 switch(typ)
2244 {
2245 case TOKT_SYM:
2246 /* symbol */
2247 {
2248 const char *p;
2249 CTcHashEntryKw *kw;
2250
2251 /* look it up in the keyword table */
2252 kw = (CTcHashEntryKw *)kw_->find(curtok_.get_text(),
2253 curtok_.get_text_len());
2254 if (kw != 0)
2255 {
2256 /* replace the token with the keyword token type */
2257 typ = kw->get_tok_id();
2258 curtok_.settyp(typ);
2259 }
2260 else
2261 {
2262 /* ordinary symbol - save the text */
2263 p = store_source(curtok_.get_text(),
2264 curtok_.get_text_len());
2265
2266 /*
2267 * change the token's text to point to the
2268 * source block, so that this token's text
2269 * pointer will remain permanently valid (the
2270 * original copy, in the source line buffer,
2271 * will be overwritten as soon as we read
2272 * another source line; we don't want the caller
2273 * to have to worry about this, so we return the
2274 * permanent copy)
2275 */
2276 curtok_.set_text(p, curtok_.get_text_len());
2277 }
2278 }
2279 break;
2280
2281 case TOKT_FLOAT:
2282 case TOKT_BIGINT:
2283 /* floating-point number (or promoted large integer) */
2284 {
2285 const char *p;
2286
2287 /*
2288 * save the text so that it remains permanently
2289 * valid - we keep track of floats by the original
2290 * text, and let the code generator produce the
2291 * appropriate object file representation
2292 */
2293 p = store_source(curtok_.get_text(),
2294 curtok_.get_text_len());
2295 curtok_.set_text(p, curtok_.get_text_len());
2296 }
2297 break;
2298
2299 case TOKT_INVALID:
2300 /*
2301 * check for unmappable characters - these will show up as
2302 * Unicode U+FFFD, the "replacement character"; log it as
2303 * 'unmappable' if applicable, otherwise as an invalid
2304 * character
2305 */
2306 if (utf8_ptr::s_getch(curtok_.get_text()) == 0xfffd)
2307 log_error_curtok(TCERR_UNMAPPABLE_CHAR);
2308 else
2309 log_error_curtok(TCERR_INVALID_CHAR);
2310
2311 /* skip this character */
2312 p_.inc();
2313
2314 /* keep going */
2315 continue;
2316
2317 default:
2318 break;
2319 }
2320 }
2321
2322 /* return the type */
2323 return typ;
2324 }
2325 }
2326
2327
2328 /*
2329 * Translate the string at the current token position in the input
2330 * stream to the source block list.
2331 */
2332 tc_toktyp_t CTcTokenizer::xlat_string_to_src(
2333 tok_embed_ctx *ec, int force_embed_end)
2334 {
2335 /*
2336 * Reserve space for the entire rest of the line. This is
2337 * conservative, in that we will definitely need less space than
2338 * this. This might cause us to waste a little space here and
2339 * there, since we will over-allocate when we have a short string
2340 * early in a long line, but this will save us the time of scanning
2341 * the string twice just to see how long it is.
2342 */
2343 reserve_source(curbuf_->get_text_len() -
2344 (p_.getptr() - curbuf_->get_text()));
2345
2346 /* translate into the source block */
2347 tc_toktyp_t typ = xlat_string_to(
2348 src_ptr_, &p_, &curtok_, ec, force_embed_end);
2349
2350 /* commit the space in the source block */
2351 commit_source(curtok_.get_text_len() + 1);
2352
2353 /* return the string token */
2354 return typ;
2355 }
2356
2357 /*
2358 * Translate a string, setting up the token structure for the string,
2359 * and writing the translated version of the string directly over the
2360 * original source buffer of the string.
2361 *
2362 * Since a translated string can only shrink (because a translated
2363 * escape sequence is always shorter than the original source version),
2364 * we don't need a separate buffer, but can simply translate into the
2365 * source buffer, overwriting the original string as we go.
2366 */
2367 tc_toktyp_t CTcTokenizer::xlat_string(utf8_ptr *p, CTcToken *tok,
2368 tok_embed_ctx *ec)
2369 {
2370 /*
2371 * write the translated string over the original string's text,
2372 * starting at the character after the quote
2373 */
2374 char *dst = p->getptr() + 1;
2375
2376 /* translate the string into our destination buffer */
2377 return xlat_string_to(dst, p, tok, ec, FALSE);
2378 }
2379
2380 /*
2381 * Count a run of consecutive quotes
2382 */
2383 static int count_quotes(const utf8_ptr *p, wchar_t qu)
2384 {
2385 /* count quotes */
2386 int cnt = 0;
2387 for (utf8_ptr qp((utf8_ptr *)p) ; qp.getch() == qu ; qp.inc(), ++cnt);
2388
2389 /* return the count */
2390 return cnt;
2391 }
2392
2393 /*
2394 * Translate a string, setting up the token structure for the string.
2395 * We'll update the line buffer in-place to incorporate the translated
2396 * string text.
2397 */
2398 tc_toktyp_t CTcTokenizer::xlat_string_to(
2399 char *dstp, utf8_ptr *p, CTcToken *tok, tok_embed_ctx *ec,
2400 int force_embed_end)
2401 {
2402 /* set up our output utf8 pointer */
2403 utf8_ptr dst(dstp);
2404
2405 /* note the open quote character */
2406 wchar_t qu = p->getch();
2407
2408 /* set the appropriate string token type */
2409 tok->settyp(qu == '"' ? TOKT_DSTR :
2410 qu == '\'' ? TOKT_SSTR :
2411 qu == 'R' ? TOKT_RESTR :
2412 ec != 0 ? ec->endtok() :
2413 TOKT_INVALID);
2414
2415 /* if it's a regex string, skip the 'R' and note the actual quote type */
2416 if (qu == 'R')
2417 {
2418 p->inc();
2419 qu = p->getch();
2420 }
2421
2422 /*
2423 * If we're at a quote (rather than at '>>' for continuing from an
2424 * embedded expression), count consecutive open quotes, to determine if
2425 * we're in a triple-quoted string.
2426 */
2427 int triple = FALSE;
2428 if (qu == '"' || qu == '\'')
2429 {
2430 /* count the consecutive open quotes */
2431 if (count_quotes(p, qu) >= 3)
2432 {
2433 /* skip past the additional two open quotes */
2434 p->inc();
2435 p->inc();
2436
2437 /* note that we're in a triple-quoted string */
2438 triple = TRUE;
2439 }
2440 }
2441
2442 /* skip the open quote */
2443 p->inc();
2444
2445 /* check for the end of an embedded expression (forced or actual) */
2446 if (force_embed_end)
2447 {
2448 /*
2449 * they want us to assume the embedding ends here, regardless of
2450 * what we're looking at - act the same as though we had
2451 * actually seen '>>', but don't skip any input (in fact, back
2452 * up one, since we already skipped one character for what we
2453 * had thought was the open quote
2454 */
2455 p->dec();
2456
2457 /* restore the enclosing string context */
2458 qu = ec->qu();
2459 triple = ec->triple();
2460 tok->settyp(ec->endtok());
2461
2462 /* clear the caller's in-embedding status */
2463 ec->end_expr();
2464 }
2465 else if (qu == '>' && ec->parens() == 0)
2466 {
2467 /* skip the second '>' */
2468 p->inc();
2469
2470 /* restore the enclosing string context */
2471 qu = ec->qu();
2472 triple = ec->triple();
2473
2474 /* end the expression */
2475 ec->end_expr();
2476 }
2477
2478 /* scan the string and translate quotes */
2479 for (;;)
2480 {
2481 /* get this character */
2482 wchar_t cur = p->getch();
2483
2484 /* if this is the matching quote, we're done */
2485 if (cur == qu)
2486 {
2487 /*
2488 * If we're in a triple-quote string, count consecutive quotes.
2489 * Triple quotes are greedy: if we have N>3 quotes in a row,
2490 * the first N-3 are inside the string, and the last 3 are the
2491 * terminating quotes.
2492 */
2493 if (triple)
2494 {
2495 /* we need at least three quotes to end the string */
2496 int qcnt = count_quotes(p, qu);
2497 if (qcnt >= 3)
2498 {
2499 /* copy all but the last three quotes to the output */
2500 for ( ; qcnt > 3 ; --qcnt, p->inc())
2501 dst.setch(qu);
2502
2503 /* skip the three quotes */
2504 p->inc_by(3);
2505
2506 /* done with the string */
2507 break;
2508 }
2509 }
2510 else
2511 {
2512 /*
2513 * It's an ordinary string, which ends with just one
2514 * matching quote, so we're done no matter what follows.
2515 * Skip the quote and stop scanning.
2516 */
2517 p->inc();
2518 break;
2519 }
2520 }
2521
2522 /*
2523 * if we find an end-of-line within the string, it's an error -
2524 * we should always splice strings together onto a single line
2525 * before starting to tokenize the line
2526 */
2527 if (cur == '\0')
2528 {
2529 /* set the token's text pointer */
2530 size_t bytelen = dst.getptr() - dstp;
2531 tok->set_text(dstp, bytelen);
2532
2533 /* null-terminate the result string */
2534 dst.setch('\0');
2535
2536 /*
2537 * get the length of the unterminated string so far, but for
2538 * error logging, limit the length to twenty characters --
2539 * we just want to give the user enough information to find
2540 * the string in error, without making the error message
2541 * huge
2542 */
2543 utf8_ptr dp(dstp);
2544 size_t charlen = dp.len(bytelen);
2545 if (charlen > 20)
2546 bytelen = dp.bytelen(20);
2547
2548 /*
2549 * Check for a special heuristic case. If the string was of
2550 * zero length, and we have something sitting in our
2551 * unsplice buffer, here's what probably happened: the input
2552 * was missing a ">>" sequence at the end of an embedded
2553 * expression, and the parser told us to put it back in. We
2554 * had earlier decided we needed to splice up to a quote to
2555 * end what looked to us like an unterminated string. If
2556 * this is the case, we and the parser are working at cross
2557 * purposes; the parser is smarter than we are, so we should
2558 * synchronize with it.
2559 */
2560 if (tok->get_text_len() == 0
2561 && qu == '"'
2562 && unsplicebuf_.get_text_len() != 0)
2563 {
2564 /*
2565 * we must have spliced a line to finish a string -
2566 * insert the quote into the splice buffer, and ignore
2567 * it here
2568 */
2569
2570 /*
2571 * make sure there's room for one more character (plus a
2572 * null byte)
2573 */
2574 unsplicebuf_.ensure_space(unsplicebuf_.get_text_len() + 2);
2575
2576 /* get the buffer pointer */
2577 char *buf = unsplicebuf_.get_buf();
2578
2579 /* make room for the '"' */
2580 memmove(buf + 1, buf, unsplicebuf_.get_text_len());
2581 unsplicebuf_.set_text_len(unsplicebuf_.get_text_len() + 1);
2582
2583 /* add the '"' */
2584 *buf = '"';
2585
2586 /*
2587 * return the 'null token' to tell the caller to try
2588 * again - do not log an error at this point
2589 */
2590 return TOKT_NULLTOK;
2591 }
2592
2593 /* log the error */
2594 log_error(TCERR_UNTERM_STRING,
2595 (char)qu, (int)bytelen, dstp, (char)qu);
2596
2597 /* return the string type */
2598 return tok->gettyp();
2599 }
2600
2601 /* if this is an escape, translate it */
2602 if (cur == '\\')
2603 {
2604 /* translate the escape */
2605 xlat_escape(&dst, p, qu, triple);
2606 continue;
2607 }
2608 else if (ec != 0
2609 && tok->gettyp() != TOKT_RESTR
2610 && cur == '<' && p->getch_at(1) == '<')
2611 {
2612 /*
2613 * It's the start of an embedded expression - change the type
2614 * to so indicate. If we think we have a regular SSTR or DSTR,
2615 * switch to the appropriate START type, since the part up to
2616 * here is actually the starting fragment of a string with an
2617 * embedded expression. If we think we're in an END section,
2618 * switch to the corresponding MID section, since we're parsing
2619 * a fragment that already followed an embedding. The only
2620 * other possibility is that we're in a MID section, in which
2621 * case just stay in the same MID section.
2622 */
2623 tc_toktyp_t tt = tok->gettyp();
2624 tok->settyp(tt == TOKT_DSTR ? TOKT_DSTR_START :
2625 tt == TOKT_DSTR_END ? TOKT_DSTR_MID :
2626 tt == TOKT_SSTR ? TOKT_SSTR_START :
2627 tt == TOKT_SSTR_END ? TOKT_SSTR_MID :
2628 tt);
2629
2630 /* skip the << */
2631 p->inc_by(2);
2632
2633 /*
2634 * Check for a '%' sprintf-style formatting sequence. If we
2635 * have a '%' immediately after the second '<', it's a sprintf
2636 * format code.
2637 */
2638 if (p->getch() == '%')
2639 {
2640 /* remember the starting point of the format string */
2641 utf8_ptr fmt(p);
2642
2643 /* scan the format spec */
2644 scan_sprintf_spec(p);
2645
2646 /* translate escapes */
2647 utf8_ptr dst(&fmt);
2648 xlat_escapes(&dst, &fmt, p);
2649
2650 /* push the format spec into the token stream */
2651 CTcToken ftok;
2652 ftok.set_text(fmt.getptr(), dst.getptr() - fmt.getptr());
2653 ftok.settyp(TOKT_FMTSPEC);
2654 push(&ftok);
2655 }
2656
2657 /* tell the caller we're in an embedding */
2658 ec->start_expr(qu, triple, TRUE);
2659
2660 /* stop scanning */
2661 break;
2662 }
2663
2664 /* copy this character to the output position */
2665 dst.setch(cur);
2666
2667 /* get the next character */
2668 p->inc();
2669 }
2670
2671 /* set the token's text pointer */
2672 tok->set_text(dstp, dst.getptr() - dstp);
2673
2674 /* null-terminate the result string */
2675 dst.setch('\0');
2676
2677 /* return the string type */
2678 return tok->gettyp();
2679 }
2680
2681 /*
2682 * Translate all escapes in a string
2683 */
2684 void CTcTokenizer::xlat_escapes(utf8_ptr *dst, const utf8_ptr *srcp,
2685 const utf8_ptr *endp)
2686 {
2687 /* set up writable copy of the source */
2688 utf8_ptr p(srcp);
2689
2690 /* scan the string */
2691 while (p.getptr() < endp->getptr())
2692 {
2693 /* check for an escape */
2694 wchar_t ch = p.getch();
2695 if (ch == '\\')
2696 {
2697 /* escape - translate it */
2698 xlat_escape(dst, &p, 0, FALSE);
2699 }
2700 else
2701 {
2702 /* ordinary character - copy it as is */
2703 dst->setch(ch);
2704 p.inc();
2705 }
2706 }
2707 }
2708
2709 /*
2710 * Skip a \ escape sequence
2711 */
2712 void CTcTokenizer::skip_escape(utf8_ptr *p)
2713 {
2714 if (p->getch() == '\\')
2715 {
2716 /* translate an escape into an empty buffer */
2717 char buf[10];
2718 utf8_ptr dst(buf);
2719 xlat_escape(&dst, p, 0, FALSE);
2720 }
2721 else
2722 {
2723 /* just skip the character */
2724 p->inc();
2725 }
2726 }
2727
2728 /*
2729 * Translate a \ escape sequence
2730 */
2731 void CTcTokenizer::xlat_escape(utf8_ptr *dst, utf8_ptr *p,
2732 wchar_t qu, int triple)
2733 {
2734 int i, acc;
2735
2736 /* get the character after the escape */
2737 p->inc();
2738 wchar_t cur = p->getch();
2739
2740 /* see what we have */
2741 switch(cur)
2742 {
2743 case '^':
2744 /* caps - 0x000F */
2745 cur = 0x000F;
2746 break;
2747
2748 case '"':
2749 case '\'':
2750 /*
2751 * If we're in triple-quote mode, and this is the matching quote, a
2752 * single backslash escapes a whole run of consecutive quotes, so
2753 * skip the whole run.
2754 */
2755 if (triple && cur == qu)
2756 {
2757 /* copy and skip all consecutive quotes */
2758 for ( ; p->getch() == qu ; dst->setch(cur), p->inc()) ;
2759
2760 /* we're done */
2761 return;
2762 }
2763 break;
2764
2765 case 'v':
2766 /* miniscules - 0x000E */
2767 cur = 0x000E;
2768 break;
2769
2770 case 'b':
2771 /* blank line - 0x000B */
2772 cur = 0x000B;
2773 break;
2774
2775 case ' ':
2776 /* quoted space - 0x0015 */
2777 cur = 0x0015;
2778 break;
2779
2780 case 'n':
2781 /* newline - explicitly use Unicode 10 character */
2782 cur = 10;
2783 break;
2784
2785 case 'r':
2786 /* return - explicitly use Unicode 13 character */
2787 cur = 13;
2788 break;
2789
2790 case 't':
2791 /* tab - explicitly use Unicode 9 character */
2792 cur = 9;
2793 break;
2794
2795 case 'u':
2796 /*
2797 * Hex unicode character number. Read up to 4 hex digits that
2798 * follow the 'u', and use that as a Unicode character ID.
2799 */
2800 for (i = 0, acc = 0, p->inc() ; i < 4 ; ++i, p->inc())
2801 {
2802 /* get the next character */
2803 cur = p->getch();
2804
2805 /*
2806 * if it's another hex digit, add it into the accumulator;
2807 * otherwise, we're done
2808 */
2809 if (is_xdigit(cur))
2810 acc = 16*acc + value_of_xdigit(cur);
2811 else
2812 break;
2813 }
2814
2815 /* use the accumulated value as the character number */
2816 dst->setch((wchar_t)acc);
2817
2818 /* we've already skipped ahead to the next character, so we're done */
2819 return;
2820
2821 case '0':
2822 case '1':
2823 case '2':
2824 case '3':
2825 case '4':
2826 case '5':
2827 case '6':
2828 case '7':
2829 /*
2830 * Octal ASCII character number. Accumulate up to three octal
2831 * numbers, and use the result as a character ID.
2832 */
2833 for (i = 0, acc = 0 ; i < 3 ; ++i, p->inc())
2834 {
2835 /* get the next character */
2836 cur = p->getch();
2837
2838 /*
2839 * if it's another digit, and it would leave our result in the
2840 * 0-255 range, count it; if not, we're done
2841 */
2842 if (is_odigit(cur))
2843 {
2844 /* compute the new value */
2845 long new_acc = 8*acc + value_of_odigit(cur);
2846
2847 /* if this would be too high, don't count it */
2848 if (new_acc > 255)
2849 break;
2850 else
2851 acc = new_acc;
2852 }
2853 else
2854 break;
2855 }
2856
2857 /* use the accumulated value as the character number */
2858 dst->setch((wchar_t)acc);
2859
2860 /*
2861 * continue with the current character, since we've already skipped
2862 * ahead to the next one
2863 */
2864 return;
2865
2866 case 'x':
2867 /*
2868 * Hex ASCII character number. Read up to two hex digits as a
2869 * character number.
2870 */
2871 for (i = 0, acc = 0, p->inc() ; i < 2 ; ++i, p->inc())
2872 {
2873 /* get the next character */
2874 cur = p->getch();
2875
2876 /*
2877 * if it's another hex digit, add it into the accumulator;
2878 * otherwise, we're done
2879 */
2880 if (is_xdigit(cur))
2881 acc = 16*acc + value_of_xdigit(cur);
2882 else
2883 break;
2884 }
2885
2886 /* use the accumulated value as the character number */
2887 dst->setch((wchar_t)acc);
2888
2889 /*
2890 * continue with the current character, since we've already skipped
2891 * ahead to the next one
2892 */
2893 return;
2894
2895 case '<':
2896 case '>':
2897 case '\\':
2898 /* just copy these literally */
2899 break;
2900
2901 default:
2902 /* log a pedantic error */
2903 log_pedantic(TCERR_BACKSLASH_SEQ, cur);
2904
2905 /* copy anything else as-is, including the backslash */
2906 dst->setch('\\');
2907 break;
2908 }
2909
2910 /* set the output character */
2911 dst->setch(cur);
2912
2913 /* skip the current character */
2914 p->inc();
2915 }
2916
2917 /*
2918 * Scan a sprintf format spec
2919 */
2920 void CTcTokenizer::scan_sprintf_spec(utf8_ptr *p)
2921 {
2922 /* skip the '%' */
2923 p->inc();
2924
2925 /* scan the flags section */
2926 for (int done = FALSE ; !done ; )
2927 {
2928 switch (p->getch())
2929 {
2930 case '[':
2931 /* skip digits and the closing ']' */
2932 for (p->inc() ; is_digit(p->getch()) ; p->inc()) ;
2933 if (p->getch() == ']')
2934 p->inc();
2935 break;
2936
2937 case '_':
2938 /* padding spec - skip this and the next character */
2939 p->inc();
2940 if (p->getch() != 0)
2941 skip_escape(p);
2942 break;
2943
2944 case '-':
2945 case '+':
2946 case ' ':
2947 case ',':
2948 case '#':
2949 /* format spec - just skip it */
2950 p->inc();
2951 break;
2952
2953 default:
2954 /* anything else means we're done with the flags */
2955 done = TRUE;
2956 break;
2957 }
2958 }
2959
2960 /* scan the width */
2961 for ( ; is_digit(p->getch()) ; p->inc()) ;
2962
2963 /* scan the precision */
2964 if (p->getch() == '.')
2965 for (p->inc() ; is_digit(p->getch()) ; p->inc()) ;
2966
2967 /* the next character is the format spec - skip it */
2968 if (p->getch() != 0)
2969 skip_escape(p);
2970 }
2971
2972
2973 /*
2974 * Skip a string, setting up the token structure for the string. This
2975 * routine only parses to the end of the line; if the line ends with the
2976 * string unterminated, we'll flag an error.
2977 */
2978 tc_toktyp_t CTcTokenizer::tokenize_string(
2979 utf8_ptr *p, CTcToken *tok, tok_embed_ctx *ec, int expanding)
2980 {
2981 /* remember where the text starts */
2982 const char *start = p->getptr();
2983
2984 /* check for a regex string - R'...' or R"..." */
2985 int regex = (p->getch() == 'R');
2986 if (regex)
2987 p->inc();
2988
2989 /* note the quote type, for matching later */
2990 wchar_t qu = p->getch();
2991
2992 /* skip the quote in the input */
2993 p->inc();
2994
2995 /* check for triple quotes */
2996 int triple = FALSE;
2997 if ((qu == '"' || qu == '\'') && count_quotes(p, qu) >= 2)
2998 {
2999 /* note the triple quotes */
3000 triple = TRUE;
3001
3002 /* skip the open quotes */
3003 p->inc();
3004 p->inc();
3005 }
3006
3007 /* determine the token type based on the quote type */
3008 tc_toktyp_t typ;
3009 int allow_embedding;
3010 switch(qu)
3011 {
3012 case '\'':
3013 /* single-quoted string */
3014 typ = TOKT_SSTR;
3015 allow_embedding = (ec != 0);
3016 break;
3017
3018 case '"':
3019 /* regular double-quoted string */
3020 typ = TOKT_DSTR;
3021 allow_embedding = (ec != 0);
3022 break;
3023
3024 case '>':
3025 /* get the ending type for the embedding */
3026 if (ec != 0)
3027 {
3028 /* return to the enclosing string context */
3029 typ = ec->endtok();
3030 qu = ec->qu();
3031 triple = ec->triple();
3032
3033 /* allow more embeddings */
3034 allow_embedding = TRUE;
3035
3036 /* exit the expression context */
3037 ec->end_expr();
3038 }
3039 else
3040 {
3041 /* we can only finish an embedding if we were already in one */
3042 typ = TOKT_INVALID;
3043 qu = '"';
3044 allow_embedding = FALSE;
3045 }
3046
3047 /* skip the extra '>' character */
3048 p->inc();
3049 break;
3050
3051 default:
3052 /* anything else is invalid */
3053 typ = TOKT_INVALID;
3054 qu = '"';
3055 allow_embedding = FALSE;
3056 break;
3057 }
3058
3059 /* if it's a regex string, it has special handling */
3060 if (regex)
3061 {
3062 /* embeddings aren't allowed in regex strings */
3063 allow_embedding = FALSE;
3064
3065 /* the token type is 'regex string' */
3066 typ = TOKT_RESTR;
3067 }
3068
3069 /* this is where the string's contents start */
3070 const char *contents_start = p->getptr();
3071
3072 /* we don't know where it ends yet */
3073 const char *contents_end;
3074
3075 /* scan the string */
3076 for (;;)
3077 {
3078 /* get the current character */
3079 wchar_t cur = p->getch();
3080
3081 /* see what we have */
3082 if (cur == '\\')
3083 {
3084 /* escape sequence - skip an extra character */
3085 p->inc();
3086
3087 /*
3088 * if we're in a triple-quoted string, and this matches the
3089 * quote type, a single '\' escapes all consecutive quotes
3090 */
3091 if (triple && p->getch() == qu)
3092 {
3093 /* skip the whole run of quotes */
3094 for ( ; p->getch() == qu ; p->inc()) ;
3095
3096 /* take it from the top, as we've already skipped them all */
3097 continue;
3098 }
3099 }
3100 else if (cur == '<' && allow_embedding && p->getch_at(1) == '<')
3101 {
3102 /*
3103 * it's the start of an embedded expression - return the
3104 * appropriate embedded string part type
3105 */
3106 typ = (typ == TOKT_DSTR ? TOKT_DSTR_START :
3107 typ == TOKT_DSTR_END ? TOKT_DSTR_MID :
3108 typ == TOKT_SSTR ? TOKT_SSTR_START :
3109 typ == TOKT_SSTR_END ? TOKT_SSTR_MID :
3110 typ);
3111
3112 /* remember that we're in an embedding in the token stream */
3113 ec->start_expr(qu, triple, !expanding);
3114
3115 /* this is where the contents end */
3116 contents_end = p->getptr();
3117
3118 /* skip the two embedding characters */
3119 p->inc();
3120 p->inc();
3121
3122 /* we're done - set the text in the token */
3123 tok->set_text(start, p->getptr() - start);
3124
3125 /* done */
3126 break;
3127 }
3128 else if (cur == qu)
3129 {
3130 /*
3131 * if we're in a triple-quoted string, it ends at a triple
3132 * quote, except that any additional consecutive quotes go
3133 * inside the string rather than outside
3134 */
3135 if (triple)
3136 {
3137 /* we need at least three quotes in a row to end the string */
3138 int qcnt = count_quotes(p, qu);
3139 if (qcnt >= 3)
3140 {
3141 /* the contents include any quotes before the last 3 */
3142 p->inc_by(qcnt - 3);
3143 contents_end = p->getptr();
3144
3145 /* skip the three close quotes */
3146 p->inc_by(3);
3147 }
3148 else
3149 {
3150 /* it's not ending; skip the quotes and carry on */
3151 p->inc_by(qcnt);
3152 continue;
3153 }
3154 }
3155 else
3156 {
3157 /* note where the string ends */
3158 contents_end = p->getptr();
3159
3160 /* skip the closing quote */
3161 p->inc();
3162 }
3163
3164 /* we're done - set the text in the token */
3165 tok->set_text(start, p->getptr() - start);
3166
3167 /* done */
3168 break;
3169 }
3170 else if (cur == '\0')
3171 {
3172 /* this is where the contents end */
3173 contents_end = p->getptr();
3174
3175 /*
3176 * We have an unterminated string. If we're evaluating a
3177 * preprocessor constant expression, log an error; otherwise
3178 * let it go for now, since we'll catch the error during the
3179 * normal tokenizing pass for parsing.
3180 */
3181 if (G_tok->in_pp_expr_)
3182 log_error(TCERR_PP_UNTERM_STRING);
3183
3184 /* set the partial text */
3185 tok->set_text(start, p->getptr() - start);
3186
3187 /* end of line - return with the string unfinished */
3188 break;
3189 }
3190
3191 /* skip this character of input */
3192 p->inc();
3193 }
3194
3195 /*
3196 * if we're not in preprocessor mode, and we're saving string text,
3197 * write the string to the string text output file
3198 */
3199 if (!G_tok->in_pp_expr_ && G_tok->string_fp_ != 0
3200 && contents_start != contents_end)
3201 {
3202 /* write the line, translating back to the source character set */
3203 G_tok->string_fp_map_
3204 ->write_file(G_tok->string_fp_, contents_start,
3205 (size_t)(contents_end - contents_start));
3206
3207 /* add a newline */
3208 G_tok->string_fp_->write("\n", 1);
3209 }
3210
3211 /* set the type in the token */
3212 tok->settyp(typ);
3213
3214 /* return the token type */
3215 return tok->gettyp();
3216 }
3217
3218
3219 /* ------------------------------------------------------------------------ */
3220 /*
3221 * Read a source line and handle preprocessor directives. This routine
3222 * will transparently handle #include, #define, and other directives;
3223 * when this routine returns, the input buffer will have a line of text
3224 * that contains no # directive.
3225 *
3226 * Returns zero on success, non-zero upon reaching the end of the input.
3227 */
3228 int CTcTokenizer::read_line_pp()
3229 {
3230 /*
3231 * Read the next line from the input. If that fails, return an end
3232 * of file indication.
3233 */
3234 int ofs = read_line(FALSE);
3235 if (ofs == -1)
3236 return 1;
3237
3238 /*
3239 * before we process comments, note whether or not the line started
3240 * out within a character string
3241 */
3242 int started_in_string = (in_quote_ != '\0');
3243
3244 /* set up our source pointer to the start of the new line */
3245 start_new_line(&linebuf_, ofs);
3246
3247 /* skip leading whitespace */
3248 while (is_space(p_.getch()))
3249 p_.inc();
3250
3251 /*
3252 * If this line begins with a '#', process the directive. Ignore
3253 * any initial '#' if the line started off in a string.
3254 */
3255 if (!started_in_string && p_.getch() == '#' && allow_pp_)
3256 {
3257 struct pp_kw_def
3258 {
3259 const char *kw;
3260 int process_in_false_if;
3261 void (CTcTokenizer::*func)();
3262 };
3263 static pp_kw_def kwlist[] =
3264 {
3265 { "charset", FALSE, &CTcTokenizer::pp_charset },
3266 { "pragma", FALSE, &CTcTokenizer::pp_pragma },
3267 { "include", FALSE, &CTcTokenizer::pp_include },
3268 { "define", FALSE, &CTcTokenizer::pp_define },
3269 { "if", TRUE, &CTcTokenizer::pp_if },
3270 { "ifdef", TRUE, &CTcTokenizer::pp_ifdef },
3271 { "ifndef", TRUE, &CTcTokenizer::pp_ifndef },
3272 { "else", TRUE, &CTcTokenizer::pp_else },
3273 { "elif", TRUE, &CTcTokenizer::pp_elif },
3274 { "endif", TRUE, &CTcTokenizer::pp_endif },
3275 { "error", FALSE, &CTcTokenizer::pp_error },
3276 { "undef", FALSE, &CTcTokenizer::pp_undef },
3277 { "line", FALSE, &CTcTokenizer::pp_line },
3278 { 0, 0, 0 }
3279 };
3280 pp_kw_def *kwp;
3281 const char *kwtxt;
3282 size_t kwlen;
3283
3284 /* skip the '#' */
3285 p_.inc();
3286
3287 /*
3288 * If the line ended inside a comment, read the next line until
3289 * we're no longer in a comment. The ANSI C preprocessor rules
3290 * say that a newline in a comment should not be treated as a
3291 * lexical newline, so pretend that the next line is part of the
3292 * preprocessor line in such a case.
3293 */
3294 while (str_->is_in_comment())
3295 {
3296 size_t p_ofs;
3297
3298 /* remember the current offset in the line buffer */
3299 p_ofs = p_.getptr() - linebuf_.get_buf();
3300
3301 /* append another line - stop at the end of the stream */
3302 if (read_line(TRUE) == -1)
3303 break;
3304
3305 /* restore the line pointer, in case the buffer moved */
3306 start_new_line(&linebuf_, p_ofs);
3307 }
3308
3309 /* read the directive */
3310 next_on_line();
3311
3312 /*
3313 * if we've reached the end of the line, it's a null directive;
3314 * simply return an empty line
3315 */
3316 if (curtok_.gettyp() == TOKT_EOF)
3317 {
3318 clear_linebuf();
3319 return 0;
3320 }
3321
3322 /* get the text and length of the keyword */
3323 kwtxt = curtok_.get_text();
3324 kwlen = curtok_.get_text_len();
3325
3326 /* if it's not a symbol, it's not a valid directive */
3327 if (curtok_.gettyp() != TOKT_SYM)
3328 {
3329 /* log the error and return an empty line */
3330 log_error(TCERR_INV_PP_DIR, (int)kwlen, kwtxt);
3331 clear_linebuf();
3332 return 0;
3333 }
3334
3335 /* determine which keyword we have, and process it */
3336 for (kwp = kwlist ; kwp->kw != 0 ; ++kwp)
3337 {
3338 /* is this our keyword? */
3339 if (strlen(kwp->kw) == kwlen
3340 && memcmp(kwtxt, kwp->kw, kwlen) == 0)
3341 {
3342 /*
3343 * This is our directive.
3344 *
3345 * If we're in the false branch of a #if block, only
3346 * process the directive if it's a kind of directive
3347 * that we should process in false #if branches. The
3348 * only directives that we process in #if branches are
3349 * those that would affect the #if branching, such as a
3350 * #endif or a nested #if.
3351 */
3352 if (!in_false_if() || kwp->process_in_false_if)
3353 {
3354 /* invoke the handler to process the directive */
3355 (this->*(kwp->func))();
3356 }
3357 else
3358 {
3359 /*
3360 * we're in a #if branch not taken - simply clear
3361 * the buffer
3362 */
3363 clear_linebuf();
3364 }
3365
3366 /* we don't need to look any further */
3367 break;
3368 }
3369 }
3370
3371 /*
3372 * if we didn't find the keyword, log an error and otherwise
3373 * ignore the entire line
3374 */
3375 if (kwp->kw == 0)
3376 log_error(TCERR_INV_PP_DIR, (int)kwlen, kwtxt);
3377
3378 /*
3379 * Preprocessor lines must always be entirely self-contained.
3380 * Therefore, it's not valid for a string to start on a
3381 * preprocessor line and continue onto subsequent lines. If
3382 * we're marked as being inside a string, there must have been
3383 * an error on the preprocessor line. Simply clear the
3384 * in-string flag; we don't need to issue an error at this
3385 * point, since the preprocessor line handler should have
3386 * already caught the problem and reported an error.
3387 */
3388 in_quote_ = '\0';
3389 }
3390 else
3391 {
3392 /*
3393 * There's no preprocessor directive.
3394 *
3395 * If we're in a false #if branch, return an empty line. We
3396 * return an empty line rather than skipping to the next line so
3397 * that the caller sees the same number of lines as are in the
3398 * original source.
3399 */
3400 if (in_false_if())
3401 {
3402 /*
3403 * it's a #if not taken - we don't want to compile the line
3404 * at all, so just clear it out
3405 */
3406 clear_linebuf();
3407 expbuf_.clear_text();
3408 }
3409 else
3410 {
3411 /*
3412 * If we ended the line in a string, splice additional lines
3413 * onto the end of this line until we find the end of the
3414 * string, then unsplice the part after the end of the
3415 * string.
3416 */
3417 if (in_quote_ != '\0')
3418 {
3419 /* splice additional lines to finish the quote */
3420 splice_string();
3421 }
3422
3423 /*
3424 * Expand macros in the line, splicing additional source
3425 * lines if necessary to fill out any incomplete actual
3426 * parameter lists.
3427 */
3428 start_new_line(&linebuf_, 0);
3429 expand_macros_curline(TRUE, FALSE, FALSE);
3430 }
3431
3432 /* store the line in the appropriate place */
3433 if (pp_only_mode_)
3434 {
3435 /*
3436 * we're only preprocessing - store the macro-expanded line
3437 * back in the line buffer so that the caller can read out
3438 * the final preprocessed text
3439 */
3440 linebuf_.copy(expbuf_.get_text(), expbuf_.get_text_len());
3441 }
3442 else
3443 {
3444 /*
3445 * We're compiling - simply read subsequent tokens out of
3446 * the expansion buffer.
3447 */
3448 start_new_line(&expbuf_, 0);
3449 }
3450 }
3451
3452 /* return success */
3453 return 0;
3454 }
3455
3456 /* ------------------------------------------------------------------------ */
3457 /*
3458 * Read the next line from the input file. Returns a pointer to the
3459 * start of the newly-read data on success, or null if we reach the end
3460 * of the input.
3461 *
3462 * If 'append' is true, we'll add the line on to the end of the existing
3463 * buffer; otherwise, we'll overwrite what's in the buffer.
3464 *
3465 * The only preprocessing performed in this routine is line-splicing.
3466 * Any line that ends with a backslash character will be spliced with
3467 * the following line, with the backslash and newline removed.
3468 *
3469 * The new line will be stored in our internal buffer, and will be
3470 * null-terminated with the trailing newline removed.
3471 *
3472 * If we reach the end of the current file, and there's an enclosing
3473 * file, we'll resume reading from the enclosing file. Hence, when this
3474 * routine returns non-zero, it indicates that we've reached the end of
3475 * the entire source, not just of the current file.
3476 */
3477 int CTcTokenizer::read_line(int append)
3478 {
3479 /* if there's no input stream, indicate end-of-file */
3480 if (str_ == 0)
3481 return -1;
3482
3483 /* if we're not appending, clear out the line buffer */
3484 if (!append)
3485 {
3486 /* start with an empty line */
3487 clear_linebuf();
3488
3489 /* note the current input position */
3490 last_desc_ = str_->get_desc();
3491 last_linenum_ = str_->get_next_linenum();
3492 }
3493
3494 /* note where the new data starts */
3495 size_t len = linebuf_.get_text_len();
3496 size_t start_len = len;
3497
3498 /*
3499 * if there's anything in the unsplice buffer, use it as the new
3500 * line
3501 */
3502 if (unsplicebuf_.get_text_len() != 0)
3503 {
3504 /*
3505 * Copy the unsplice buffer as the current line. Note that we
3506 * don't have to worry about any of the complicated cases, such
3507 * as whether or not it ends with a newline or a backslash,
3508 * because the unspliced line was already processed as an input
3509 * line when we read it in the first place.
3510 */
3511 linebuf_.append(unsplicebuf_.get_text(), unsplicebuf_.get_text_len());
3512
3513 /* clear the unsplice buffer, since it's been consumed now */
3514 unsplicebuf_.clear_text();
3515
3516 /*
3517 * make the current line the appended line - if we're
3518 * unsplicing, it means that we appended, so the current line is
3519 * now the line from which the last appended text came
3520 */
3521 last_desc_ = appended_desc_;
3522 last_linenum_ = appended_linenum_;
3523
3524 /* return the offset of the new text */
3525 return start_len;
3526 }
3527
3528 /* if we're appending, note where the appendage is coming from */
3529 if (append)
3530 {
3531 /* remember the last source line appended */
3532 appended_desc_ = str_->get_desc();
3533 appended_linenum_ = str_->get_next_linenum();
3534 }
3535
3536 /* keep going until we finish reading the input line */
3537 for ( ;; )
3538 {
3539 /* read a line of text from the input file */
3540 size_t curlen = str_->get_src()->read_line(
3541 linebuf_.get_buf() + len, linebuf_.get_buf_size() - len);
3542
3543 /* check for end of file */
3544 if (curlen == 0)
3545 {
3546 /*
3547 * We've reached the end of the current input stream. If
3548 * we've already read anything into the current line, it
3549 * means that the file ended in mid-line, without a final
3550 * newline character; ignore this and proceed with the line
3551 * as it now stands in this case.
3552 */
3553 if (len > start_len)
3554 break;
3555
3556 /*
3557 * We've finished with this stream. If there's a parent
3558 * stream, return to it; otherwise, we're at the end of the
3559 * source.
3560 */
3561
3562 /*
3563 * if we didn't close all of the #if/#ifdef levels opened
3564 * within this file, flag one or more errors
3565 */
3566 while (if_sp_ > str_->get_init_if_level())
3567 {
3568 /* get the filename from the #if stack */
3569 const char *fname = if_stack_[if_sp_ - 1].desc->get_fname();
3570
3571 /* if we're in test reporting mode, use the root name only */
3572 if (test_report_mode_)
3573 fname = os_get_root_name((char *)fname);
3574
3575 /* log the error */
3576 log_error(TCERR_IF_WITHOUT_ENDIF,
3577 if_stack_[if_sp_ - 1].linenum,
3578 (int)strlen(fname), fname);
3579
3580 /* discard the #if level */
3581 pop_if();
3582 }
3583
3584 /* remember the old stream */
3585 CTcTokStream *old_str = str_;
3586
3587 /* return to the parent stream, if there is one */
3588 str_ = str_->get_parent();
3589
3590 /* delete the old stream now that we're done with it */
3591 delete old_str;
3592
3593 /* note the new file the line will be coming from */
3594 if (!append && str_ != 0)
3595 {
3596 last_desc_ = str_->get_desc();
3597 last_linenum_ = str_->get_next_linenum();
3598 }
3599
3600 /* if there's no stream, return end of file */
3601 if (str_ == 0)
3602 return -1;
3603
3604 /*
3605 * restore the #pragma newline_spacing mode that was in effect
3606 * when we interrupted the parent stream
3607 */
3608 string_newline_spacing_ = str_->get_newline_spacing();
3609
3610 /* if there's a parser, notify it of the new pragma C mode */
3611 #if 0 // #pragma C is not currently used
3612 if (G_prs != 0)
3613 G_prs->set_pragma_c(str_->is_pragma_c());
3614 #endif
3615
3616 /* go back to read the next line from the parent */
3617 continue;
3618 }
3619
3620 /* set the new length of the buffer contents */
3621 len += curlen - 1;
3622 linebuf_.set_text_len(len);
3623
3624 /*
3625 * Check the result to see if it ends in a newline. If not, it
3626 * means either that we don't have room in the buffer for the
3627 * full source line, or we've reached the last line in the file,
3628 * and it doesn't end with a newline.
3629 *
3630 * Note that the file reader will always supply us with '\n'
3631 * newlines, regardless of the local operating system
3632 * conventions.
3633 *
3634 * Also, check to see if the line ends with '\\'. If so, remove
3635 * the '\\' character and read the next line, since this
3636 * indicates that the logical line continues onto the next
3637 * newline-deliminted line.
3638 */
3639 if (len != 0 && linebuf_.get_text()[len - 1] != '\n')
3640 {
3641 /*
3642 * There's no newline, hence the file reader wasn't able to
3643 * fit the entire line into our buffer, or else we've read
3644 * the last line in the file and there's no newline at the
3645 * end. If we haven't reached the end of the file, expand
3646 * our line buffer to make room to read more from this same
3647 * line.
3648 */
3649 if (!str_->get_src()->at_eof())
3650 linebuf_.expand();
3651 }
3652 else if (len > 1 && linebuf_.get_text()[len - 2] == '\\')
3653 {
3654 /*
3655 * There's a backslash at the end of the line, so they want
3656 * to continue this logical line. Remove the backslash, and
3657 * read the next line onto the end of the current line.
3658 *
3659 * Note that we must remove two characters from the end of
3660 * the line (and tested for buf_[len-2] above) because we
3661 * have both a backslash and a newline at the end of the
3662 * line.
3663 */
3664 len -= 2;
3665 linebuf_.set_text_len(len);
3666
3667 /* count reading the physical line */
3668 str_->count_line();
3669 }
3670 else
3671 {
3672 /* remove the newline from the buffer */
3673 if (len != 0)
3674 {
3675 --len;
3676 linebuf_.set_text_len(len);
3677 }
3678
3679 /* count reading the line */
3680 str_->count_line();
3681
3682 /* done */
3683 break;
3684 }
3685 }
3686
3687 /*
3688 * remove comments from the newly-read material - this replaces each
3689 * comment by a single whitespace character
3690 */
3691 process_comments(start_len);
3692
3693 /*
3694 * we've successfully read a line -- return the offset of the start of
3695 * the newly-read text
3696 */
3697 return start_len;
3698 }
3699
3700 /*
3701 * Un-splice a line at the given point. This breaks the current source
3702 * line in two, keeping the part before the given point as the current
3703 * line, but making the part from the given point to the end of the line
3704 * a new source line. We'll put the new source line into a special
3705 * holding buffer, and then fetch this part as a new line the next time
3706 * we read a line in read_line().
3707 */
3708 void CTcTokenizer::unsplice_line(const char *new_line_start)
3709 {
3710 /* make sure the starting point is within the current line */
3711 if (!(new_line_start >= linebuf_.get_text()
3712 && new_line_start <= linebuf_.get_text() + linebuf_.get_text_len()))
3713 {
3714 /* note the error - this is an internal problem */
3715 throw_internal_error(TCERR_UNSPLICE_NOT_CUR);
3716 return;
3717 }
3718
3719 /* calculate the length of the part we're keeping */
3720 size_t keep_len = new_line_start - linebuf_.get_text();
3721
3722 /*
3723 * prepend the remainder of the current line into the unsplice buffer
3724 * (we prepend it because the unsplice line is text that comes after
3725 * the current line - so anything in the current line comes before
3726 * anything already in the unsplice buffer)
3727 */
3728 unsplicebuf_.prepend(new_line_start, linebuf_.get_text_len() - keep_len);
3729
3730 /* cut off the current line at the given point */
3731 linebuf_.set_text_len(keep_len);
3732 }
3733
3734
3735 /* ------------------------------------------------------------------------ */
3736 /*
3737 * Store text in the source array
3738 */
3739 const char *CTcTokenizer::store_source(const char *txt, size_t len)
3740 {
3741 /* reserve space for the text */
3742 reserve_source(len);
3743
3744 /* store it */
3745 const char *p = store_source_partial(txt, len);
3746
3747 /* add a null terminator */
3748 static const char nt[1] = { '\0' };
3749 store_source_partial(nt, 1);
3750
3751 /* return the pointer to the stored space */
3752 return p;
3753 }
3754
3755 /*
3756 * Store partial source; use this AFTER reserving the necessary space. If
3757 * you want null-termination, be sure to reserve the extra byte for that
3758 * and include it in the string. This can be used to build a string piece
3759 * by piece; we simply add the text without null-terminating it.
3760 */
3761 const char *CTcTokenizer::store_source_partial(const char *txt, size_t len)
3762 {
3763 /* remember where the string starts */
3764 const char *p = src_ptr_;
3765
3766 /* store the text */
3767 memcpy(src_ptr_, txt, len);
3768
3769 /* advance the source block write position and length */
3770 src_ptr_ += len;
3771 src_rem_ -= len;
3772
3773 /* return the storage pointer */
3774 return p;
3775 }
3776
3777 /*
3778 * Reserve space for text in the source array. This always reserves the
3779 * requested amount of space, plus an extra byte for null termination.
3780 */
3781 void CTcTokenizer::reserve_source(size_t len)
3782 {
3783 /*
3784 * if we don't have enough space for this line in the current source
3785 * block, start a new block
3786 */
3787 if (len + 1 > src_rem_)
3788 {
3789 CTcTokSrcBlock *blk;
3790
3791 /*
3792 * if the line is too long for a source block, throw a fatal
3793 * error
3794 */
3795 if (len + 1 > TCTOK_SRC_BLOCK_SIZE)
3796 throw_fatal_error(TCERR_SRCLINE_TOO_LONG,
3797 (long)TCTOK_SRC_BLOCK_SIZE);
3798
3799 /* allocate a new block */
3800 blk = new CTcTokSrcBlock();
3801
3802 /* link it into our list */
3803 src_cur_->set_next(blk);
3804
3805 /* it's now the current block */
3806 src_cur_ = blk;
3807
3808 /* start writing at the start of this block */
3809 src_rem_ = TCTOK_SRC_BLOCK_SIZE;
3810 src_ptr_ = blk->get_buf();
3811 }
3812 }
3813
3814 /*
3815 * Commit space previously reserved and now used in the source block
3816 * list
3817 */
3818 void CTcTokenizer::commit_source(size_t len)
3819 {
3820 /* advance the write position past the committed text */
3821 src_ptr_ += len;
3822 src_rem_ -= len;
3823 }
3824
3825
3826 /* ------------------------------------------------------------------------ */
3827 /*
3828 * Expand macros in the current line from the current source pointer,
3829 * filling in expbuf_ with the expanded result.
3830 */
3831 int CTcTokenizer::expand_macros_curline(int read_more, int allow_defined,
3832 int append_to_expbuf)
3833 {
3834 int err;
3835
3836 /* expand macros in the current line */
3837 err = expand_macros(&linebuf_, &p_, &expbuf_, read_more, allow_defined,
3838 append_to_expbuf);
3839
3840 /* if that failed, return an error */
3841 if (err != 0)
3842 return err;
3843
3844 /*
3845 * if we're in preprocessor mode, clean up the text for human
3846 * consumption by removing our various expansion flags
3847 */
3848 if (pp_only_mode_)
3849 remove_expansion_flags(&expbuf_);
3850
3851 /* return the result */
3852 return err;
3853 }
3854
3855 /* ------------------------------------------------------------------------ */
3856 /*
3857 * Remove the special internal macro expansion flags from an expanded macro
3858 * buffer.
3859 */
3860 void CTcTokenizer::remove_expansion_flags(CTcTokString *buf)
3861 {
3862 utf8_ptr p;
3863 char *src;
3864 char *dst;
3865
3866 /*
3867 * Scan the expansion buffer and remove all of the no-more-expansion
3868 * flag bytes - we're done expanding the macro now, so we don't need
3869 * this information any longer. When we're writing out the
3870 * preprocessed source for human viewing, we don't want to leave these
3871 * internal markers in the expanded source.
3872 */
3873 for (src = dst = buf->get_buf(), p.set(src) ; p.getch() != '\0' ; )
3874 {
3875 /* if this isn't a macro flag, copy it */
3876 if (p.getch() == TOK_MACRO_EXP_END)
3877 {
3878 /* skip the flag byte and the following embedded pointer */
3879 src += 1 + sizeof(CTcHashEntryPp *);
3880 p.set(src);
3881 }
3882 else if (p.getch() == TOK_FULLY_EXPANDED_FLAG)
3883 {
3884 /* skip the flag byte */
3885 ++src;
3886 p.set(src);
3887 }
3888 else
3889 {
3890 /* skip this character */
3891 p.inc();
3892
3893 /* copy the bytes of this character as-is */
3894 while (src < p.getptr())
3895 *dst++ = *src++;
3896 }
3897 }
3898
3899 /* set the new buffer length */
3900 buf->set_text_len(dst - buf->get_buf());
3901 }
3902
3903 /* ------------------------------------------------------------------------ */
3904 /*
3905 * Expand macros in the current line, reading additional source lines if
3906 * necessary.
3907 *
3908 * 'src' is a pointer to the start of the text to expand; it must point
3909 * into the 'srcbuf' buffer. If 'src' is null, we'll simply start at
3910 * the beginning of the source buffer.
3911 */
3912 int CTcTokenizer::expand_macros(CTcTokString *srcbuf, utf8_ptr *src,
3913 CTcTokString *expbuf, int read_more,
3914 int allow_defined, int append)
3915 {
3916 tc_toktyp_t typ;
3917 CTcToken tok;
3918 CTcTokString *subexp;
3919 size_t startofs;
3920 utf8_ptr local_src;
3921 CTcTokStringRef local_srcbuf;
3922 CTcMacroRsc *res;
3923 int err;
3924
3925 /* presume success */
3926 err = 0;
3927
3928 /* get a macro expansion resource object */
3929 res = alloc_macro_rsc();
3930 if (res == 0)
3931 return 1;
3932
3933 /* get our subexpression buffer from the resource object */
3934 subexp = &res->line_exp_;
3935
3936 /* if there's no source buffer or source pointer, provide one */
3937 if (srcbuf == 0)
3938 {
3939 /*
3940 * there's no source buffer - provide our own non-allocated
3941 * buffer tied to the caller's buffer
3942 */
3943 local_srcbuf.set_buffer(src->getptr(), strlen(src->getptr()));
3944 srcbuf = &local_srcbuf;
3945 }
3946 else if (src == 0)
3947 {
3948 /*
3949 * there's no source pointer - start at the beginning of the
3950 * source buffer
3951 */
3952 local_src.set((char *)srcbuf->get_text());
3953 src = &local_src;
3954 }
3955
3956 /* clear the expansion buffer, unless we're appending to the buffer */
3957 if (!append)
3958 expbuf->clear_text();
3959
3960 /*
3961 * Make sure we have room for a copy of the source line. This is an
3962 * optimization for the simple case where we'll just copy the source
3963 * line unchanged, so that we don't have to repeatedly expand the
3964 * buffer; we will, however, expand the buffer dynamically later, if
3965 * this pre-allocation should prove to be insufficient.
3966 */
3967 expbuf->ensure_space(expbuf->get_text_len() + srcbuf->get_text_len());
3968
3969 /* note the starting offset, if we have an underlying string buffer */
3970 startofs = src->getptr() - srcbuf->get_text();
3971
3972 /* read the first token */
3973 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_, TRUE);
3974
3975 /* scan through the tokens on the line, looking for macros to expand */
3976 while (typ != TOKT_EOF)
3977 {
3978 /*
3979 * if it's a symbol, and it hasn't already been marked as fully
3980 * expanded, look it up in the #define table
3981 */
3982 if (typ == TOKT_SYM && !tok.get_fully_expanded())
3983 {
3984 CTcHashEntryPp *entry;
3985
3986 /*
3987 * Look up the symbol in the #define symbol table. If we
3988 * find it, expand the macro. Otherwise, if the "defined"
3989 * operator is active, check for that.
3990 *
3991 * Do not expand the macro if we find that it has already
3992 * been expanded on a prior scan through the current text.
3993 */
3994 entry = find_define(tok.get_text(), tok.get_text_len());
3995 if ((entry != 0
3996 && !scan_for_prior_expansion(*src, srcbuf->get_text_end(),
3997 entry))
3998 || (allow_defined
3999 && tok.get_text_len() == 7
4000 && memcmp(tok.get_text(), "defined", 7) == 0))
4001 {
4002 size_t macro_ofs;
4003 size_t rem_len;
4004 int expanded;
4005
4006 /* get the offset of the macro token in the source buffer */
4007 macro_ofs = tok.get_text() - srcbuf->get_text();
4008
4009 /* expand it into our sub-expansion buffer */
4010 if (entry != 0)
4011 {
4012 /* expand the macro */
4013 err = expand_macro(res, subexp, srcbuf, src,
4014 macro_ofs, entry,
4015 read_more, allow_defined, &expanded);
4016 }
4017 else
4018 {
4019 /* parse and expand the defined() operator */
4020 err = expand_defined(subexp, srcbuf, src);
4021
4022 /* "defined" always expands if there's not an error */
4023 expanded = TRUE;
4024 }
4025
4026 /* if an error occurred, return failure */
4027 if (err)
4028 goto done;
4029
4030 /*
4031 * if we expanded something, append everything we
4032 * skipped preceding the macro, then rescan; otherwise,
4033 * just keep going without a rescan
4034 */
4035 if (expanded)
4036 {
4037 /* copy the preceding text to the output */
4038 expbuf->append(srcbuf->get_text() + startofs,
4039 macro_ofs - startofs);
4040 }
4041 else
4042 {
4043 /*
4044 * we didn't expand - get the next token after the
4045 * macro
4046 */
4047 typ = next_on_line(srcbuf, src, &tok,
4048 &macro_in_embedding_, TRUE);
4049
4050 /* continue processing from this token */
4051 continue;
4052 }
4053
4054 /*
4055 * We must now insert the expansion into the source
4056 * buffer at the current point, and re-scan the
4057 * expansion, *along with* the rest of the original
4058 * source line (this is how ANSI C specifies the
4059 * process).
4060 *
4061 * If we can read more, we must be reading out of the
4062 * main input line buffer, so insert the expansion text
4063 * directly into the original source stream, and
4064 * continue reading out of the source stream; this will
4065 * simplify the case where we must read more data from
4066 * the file in the course of the expansion. If we can't
4067 * read more, simply copy the remainder of the current
4068 * input line onto the expanded macro and use it as the
4069 * new input buffer.
4070 */
4071
4072 /* get the current offset in the source line */
4073 startofs = src->getptr() - srcbuf->get_text();
4074
4075 /* figure out how much is left on the current line */
4076 rem_len = srcbuf->get_text_len() - startofs;
4077
4078 /* check to see if we can read more */
4079 if (read_more)
4080 {
4081 /*
4082 * we're reading from the original line input buffer
4083 * -- insert the expansion into the source buffer at
4084 * the current point, replacing the original macro
4085 * text
4086 */
4087
4088 /* make sure we have room for adding the expansion text */
4089 srcbuf->ensure_space(macro_ofs + rem_len
4090 + subexp->get_text_len());
4091
4092 /* make sure src is still pointing to the right place */
4093 src->set(srcbuf->get_buf() + macro_ofs);
4094
4095 /* move the remainder of the current line to make room */
4096 memmove(srcbuf->get_buf() + macro_ofs
4097 + subexp->get_text_len(),
4098 srcbuf->get_buf() + startofs,
4099 rem_len);
4100
4101 /* insert the expansion text */
4102 memcpy(srcbuf->get_buf() + macro_ofs, subexp->get_buf(),
4103 subexp->get_text_len());
4104
4105 /* set the new source length */
4106 srcbuf->set_text_len(macro_ofs + rem_len
4107 + subexp->get_text_len());
4108
4109 /* the new starting offset is the current position */
4110 startofs = macro_ofs;
4111
4112 /* get the next token */
4113 typ = next_on_line(srcbuf, src, &tok,
4114 &macro_in_embedding_, TRUE);
4115
4116 /* continue processing from this token */
4117 continue;
4118 }
4119 else
4120 {
4121 /*
4122 * we're reading from a read-only buffer -- add the
4123 * remainder of the source to the expansion buffer,
4124 * and recursively parse the remainder
4125 */
4126 subexp->append(srcbuf->get_text() + startofs, rem_len);
4127
4128 /*
4129 * evaluate the remainder recursively and append it
4130 * to the expansion already in progress
4131 */
4132 err = expand_macros(subexp, 0, expbuf, FALSE,
4133 allow_defined, TRUE);
4134
4135 /* we're done */
4136 goto done;
4137 }
4138 }
4139 }
4140
4141 /* get the next token */
4142 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_, TRUE);
4143 }
4144
4145 /* add the remainder of the source to the output */
4146 expbuf->append(srcbuf->get_text() + startofs,
4147 tok.get_text() - startofs - srcbuf->get_text());
4148
4149 done:
4150 /* release our macro resource object */
4151 release_macro_rsc(res);
4152
4153 /* return the result */
4154 return err;
4155 }
4156
4157 /*
4158 * Allocate a macro resource object. If we're out of resource objects
4159 * in the pool, we'll add another object to the pool.
4160 */
4161 CTcMacroRsc *CTcTokenizer::alloc_macro_rsc()
4162 {
4163 CTcMacroRsc *rsc;
4164
4165 /*
4166 * if there's anything in the available list, take the first item
4167 * off the list and return it
4168 */
4169 if (macro_res_avail_ != 0)
4170 {
4171 /* remember the item to return */
4172 rsc = macro_res_avail_;
4173
4174 /* remove it from the list */
4175 macro_res_avail_ = macro_res_avail_->next_avail_;
4176
4177 /* return it */
4178 return rsc;
4179 }
4180
4181 /* there's nothing on the available list - allocate a new item */
4182 rsc = new CTcMacroRsc();
4183
4184 /* if that failed, return failure */
4185 if (rsc == 0)
4186 {
4187 log_error(TCERR_OUT_OF_MEM_MAC_EXP);
4188 return 0;
4189 }
4190
4191 /* add it onto the master list */
4192 rsc->next_ = macro_res_head_;
4193 macro_res_head_ = rsc;
4194
4195 /* return it */
4196 return rsc;
4197 }
4198
4199 /*
4200 * Release a macro resource, returning it to the pool
4201 */
4202 void CTcTokenizer::release_macro_rsc(CTcMacroRsc *rsc)
4203 {
4204 /* put it back at the head of the available list */
4205 rsc->next_avail_ = macro_res_avail_;
4206 macro_res_avail_ = rsc;
4207 }
4208
4209 /*
4210 * Scan a buffer for a prior-expansion flag for a given macro. We'll
4211 * look through the buffer for a TOK_MACRO_EXP_END byte that mentions
4212 * the given symbol table entry; we'll return true if found, false if
4213 * not. True means that the symbol has already been expanded on a prior
4214 * scan of the text, so it should not be re-expanded now.
4215 */
4216 int CTcTokenizer::scan_for_prior_expansion(utf8_ptr src, const char *src_end,
4217 const CTcHashEntryPp *entry)
4218 {
4219 /* scan the buffer for the expansion flag byte */
4220 while (src.getptr() < src_end)
4221 {
4222 /* if this is the flag, check what follows */
4223 if (src.getch() == TOK_MACRO_EXP_END)
4224 {
4225 CTcHashEntryPp *flag_entry;
4226
4227 /* read the entry from the buffer */
4228 memcpy(&flag_entry, src.getptr() + 1, sizeof(flag_entry));
4229
4230 /* if it matches, indicate that we found it */
4231 if (entry == flag_entry)
4232 return TRUE;
4233
4234 /* it's not a match - keep scanning after this flag sequence */
4235 src.set(src.getptr() + 1 + sizeof(flag_entry));
4236 }
4237 else
4238 {
4239 /* it's not the flag - skip this character */
4240 src.inc();
4241 }
4242 }
4243
4244 /* we didn't find it */
4245 return FALSE;
4246 }
4247
4248 /*
4249 * Go through a macro expansion and translate from end-of-expansion
4250 * markers to individual token full-expansion markers. This is used
4251 * after we leave a recursion level to convert expanded text into text
4252 * suitable for use in further expansion at an enclosing recursion
4253 * level.
4254 */
4255 void CTcTokenizer::mark_full_exp_tokens(CTcTokString *dstbuf,
4256 const CTcTokString *srcbuf,
4257 int append) const
4258 {
4259 utf8_ptr p;
4260 CTcToken tok;
4261 const char *start;
4262 tok_embed_ctx ec;
4263
4264 /* clear the output buffer if we're not appending to existing text */
4265 if (!append)
4266 dstbuf->clear_text();
4267
4268 /* remember the starting point */
4269 start = srcbuf->get_text();
4270
4271 /* scan the source buffer */
4272 p.set((char *)start);
4273 for (;;)
4274 {
4275 CTcHashEntryPp *cur_entry;
4276 tc_toktyp_t typ;
4277 char ch;
4278
4279 /* get the next token; stop at the end of the line */
4280 typ = next_on_line(srcbuf, &p, &tok, &ec, TRUE);
4281 if (typ == TOKT_EOF)
4282 break;
4283
4284 /*
4285 * if this macro token is being expanded, and it's not already
4286 * marked for no more expansion, mark it
4287 */
4288 if (typ == TOKT_SYM
4289 && !tok.get_fully_expanded()
4290 && (cur_entry = find_define(tok.get_text(),
4291 tok.get_text_len())) != 0
4292 && scan_for_prior_expansion(p, srcbuf->get_text_end(), cur_entry))
4293 {
4294 /*
4295 * This token has been fully expanded in the substitution
4296 * buffer but hasn't yet been marked as such - we must
4297 * insert the fully-expanded marker. First, add up to the
4298 * current point to the output buffer.
4299 */
4300 if (tok.get_text() > start)
4301 dstbuf->append(start, tok.get_text() - start);
4302
4303 /* add the fully-expanded marker */
4304 ch = TOK_FULLY_EXPANDED_FLAG;
4305 dstbuf->append(&ch, 1);
4306
4307 /* the new starting point is the start of the symbol token */
4308 start = tok.get_text();
4309 }
4310 }
4311
4312 /* copy any remaining text to the output */
4313 if (tok.get_text() > start)
4314 dstbuf->append(start, tok.get_text() - start);
4315
4316 /*
4317 * Remove any macro expansion end markers from the output buffer.
4318 * We don't want to leave these around, because they don't apply to
4319 * the enclosing buffer into which we'll substitute this result.
4320 * Note that we've already ensured that these markers will be
4321 * respected for the substitution text by inserting "fully expanded"
4322 * markers in front of each token to which any of the markers we're
4323 * removing should apply.
4324 */
4325 remove_end_markers(dstbuf);
4326 }
4327
4328
4329 /*
4330 * Remove end markers from a buffer
4331 */
4332 void CTcTokenizer::remove_end_markers(CTcTokString *buf)
4333 {
4334 char *src;
4335 char *dst;
4336 utf8_ptr p;
4337
4338 /* scan the buffer */
4339 for (src = dst = buf->get_buf(), p.set(src) ;
4340 p.getptr() < buf->get_text_end() ; )
4341 {
4342 /* check for our flag */
4343 if (p.getch() == TOK_MACRO_EXP_END)
4344 {
4345 /* skip the flag byte and the following embedded pointer */
4346 src += 1 + sizeof(CTcHashEntryPp *);
4347 p.set(src);
4348 }
4349 else
4350 {
4351 /* skip this character */
4352 p.inc();
4353
4354 /* copy the bytes of this character as-is */
4355 while (src < p.getptr())
4356 *dst++ = *src++;
4357 }
4358 }
4359
4360 /* set the new buffer size */
4361 buf->set_text_len(dst - buf->get_buf());
4362 }
4363
4364
4365 /*
4366 * Expand the macro at the current token in the current line.
4367 *
4368 * 'src' is a pointer to the current position in 'srcbuf'. We'll update
4369 * 'src' to point to the next token after macro or its actual parameters
4370 * list, if it has one.
4371 */
4372 int CTcTokenizer::expand_macro(CTcMacroRsc *rsc, CTcTokString *expbuf,
4373 const CTcTokString *srcbuf, utf8_ptr *src,
4374 size_t macro_srcbuf_ofs,
4375 CTcHashEntryPp *entry, int read_more,
4376 int allow_defined, int *expanded)
4377 {
4378 CTcTokString *subexp;
4379 size_t argofs[TOK_MAX_MACRO_ARGS];
4380 size_t arglen[TOK_MAX_MACRO_ARGS];
4381 size_t startofs;
4382 const char *start;
4383 const char *end;
4384 int err;
4385 char flagbuf[1 + sizeof(entry)];
4386
4387 /* presume we won't do any expansion */
4388 *expanded = FALSE;
4389
4390 /* get our resources */
4391 subexp = &rsc->macro_exp_;
4392
4393 /* remember our parsing starting offset */
4394 startofs = src->getptr() - srcbuf->get_text();
4395
4396 /* clear the expansion output buffer */
4397 expbuf->clear_text();
4398
4399 /* if the macro has arguments, scan the actuals */
4400 if (entry->has_args())
4401 {
4402 int found_actuals;
4403
4404 /* read the macro arguments */
4405 if (parse_macro_actuals(srcbuf, src, entry, argofs, arglen,
4406 read_more, &found_actuals))
4407 {
4408 err = 1;
4409 goto done;
4410 }
4411
4412 /*
4413 * If we found no actuals, then this wasn't really an invocation
4414 * of the macro after all - a function-like macro invoked with
4415 * no arguments is simply not replaced. Store the original text
4416 * in the output buffer and return success.
4417 */
4418 if (!found_actuals)
4419 {
4420 /* copy the original text */
4421 expbuf->copy(srcbuf->get_text() + macro_srcbuf_ofs,
4422 startofs - macro_srcbuf_ofs);
4423
4424 /*
4425 * restore the source read pointer to where it was when we
4426 * started
4427 */
4428 src->set((char *)srcbuf->get_text() + startofs);
4429
4430 /* return success */
4431 err = 0;
4432 goto done;
4433 }
4434 }
4435
4436 /*
4437 * if there are arguments, replace the macro and substitute actuals
4438 * for the formals; otherwise, just copy the replacement text
4439 * directly
4440 */
4441 if (entry->get_argc() != 0)
4442 {
4443 /* substitute the actuals */
4444 if (substitute_macro_actuals(rsc, subexp, entry, srcbuf,
4445 argofs, arglen, allow_defined))
4446 {
4447 err = 1;
4448 goto done;
4449 }
4450
4451 /* set up to parse from the expansion buffer */
4452 start = subexp->get_text();
4453 end = start + subexp->get_text_len();
4454 }
4455 else
4456 {
4457 /*
4458 * use our local source buffer that simply references the
4459 * original expansion text, rather than making a copy of the
4460 * expansion text
4461 */
4462 start = entry->get_expansion();
4463 end = start + entry->get_expan_len();
4464 }
4465
4466 /* copy the expansion into the output buffer */
4467 expbuf->copy(start, end - start);
4468
4469 /*
4470 * After the end of the expansion sequence, insert the
4471 * fully-expanded flag plus a pointer to the symbol table entry that
4472 * we just expanded. This will allow us to detect during the
4473 * re-scan of the expansion text that this symbol has already been
4474 * expanded, in which case we must suppress further expansion of the
4475 * symbol. This allows us to follow the ANSI C rules for recursive
4476 * macro usage.
4477 */
4478 flagbuf[0] = TOK_MACRO_EXP_END;
4479 memcpy(&flagbuf[1], &entry, sizeof(entry));
4480 expbuf->append(flagbuf, sizeof(flagbuf));
4481
4482 /* indicate that we expanded the macro */
4483 *expanded = TRUE;
4484
4485 /* success */
4486 err = 0;
4487
4488 done:
4489 /* return the result */
4490 return err;
4491 }
4492
4493 /*
4494 * Parse a macro's actual parameter list, filling in the given hash
4495 * table with the arguments. Returns zero on success, non-zero on
4496 * error. 'entry' is the macro's defining symbol table entry.
4497 */
4498 int CTcTokenizer::parse_macro_actuals(const CTcTokString *srcbuf,
4499 utf8_ptr *src,
4500 const CTcHashEntryPp *entry,
4501 size_t argofs[TOK_MAX_MACRO_ARGS],
4502 size_t arglen[TOK_MAX_MACRO_ARGS],
4503 int read_more, int *found_actuals)
4504 {
4505 tc_toktyp_t typ;
4506 CTcToken tok;
4507 int argc;
4508 int spliced;
4509 int i;
4510
4511 /* presume we're not going to do any line splicing */
4512 spliced = FALSE;
4513
4514 /* no arguments parsed yet */
4515 argc = 0;
4516
4517 /* get the next token after the macro symbol */
4518 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_, TRUE);
4519
4520 /* splice another line if necessary */
4521 if (typ == TOKT_EOF && read_more)
4522 {
4523 /* splice a line */
4524 typ = actual_splice_next_line(srcbuf, src, &tok);
4525
4526 /* note the splice */
4527 spliced = TRUE;
4528 }
4529
4530 /* if we didn't find an open paren, there's no actual list after all */
4531 if (typ != TOKT_LPAR)
4532 {
4533 /* tell the caller we didn't find any actuals */
4534 *found_actuals = FALSE;
4535
4536 /* if we spliced a line, unsplice it at the current token */
4537 if (spliced)
4538 unsplice_line(tok.get_text());
4539
4540 /* return success */
4541 return 0;
4542 }
4543
4544 /* remember the offset of the start of the first argument */
4545 argofs[argc] = tok.get_text() + tok.get_text_len() - srcbuf->get_text();
4546
4547 /* skip the open paren */
4548 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_, TRUE);
4549
4550 /* read the arguments */
4551 while (typ != TOKT_RPAR)
4552 {
4553 utf8_ptr p;
4554 int paren_depth, bracket_depth, brace_depth;
4555 int sp_cnt;
4556
4557 /* if we have too many arguments, it's an error */
4558 if ((argc >= entry->get_argc() && !entry->has_varargs())
4559 || argc >= TOK_MAX_MACRO_ARGS)
4560 {
4561 /* log the error */
4562 log_error(TCERR_PP_MANY_MACRO_ARGS,
4563 (int)entry->getlen(), entry->getstr());
4564
4565 /* scan ahead to to close paren or end of line */
4566 while (typ != TOKT_RPAR && typ != TOKT_EOF)
4567 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_,
4568 TRUE);
4569
4570 /* done scanning arguments */
4571 break;
4572 }
4573
4574 /*
4575 * Skip tokens until we find the end of the argument. An argument
4576 * ends at:
4577 *
4578 * - a comma outside of nested parens, square brackets, or curly
4579 * braces
4580 *
4581 * - a close paren that doesn't match an open paren found earlier
4582 * in the same argument
4583 */
4584 paren_depth = bracket_depth = brace_depth = 0;
4585 for (;;)
4586 {
4587 /*
4588 * If it's a comma, and we're not in any sort of nested
4589 * brackets (parens, square brackets, or curly braces), the
4590 * comma ends the argument. A comma within any type of
4591 * brackets is part of the argument text.
4592 */
4593 if (typ == TOKT_COMMA
4594 && paren_depth == 0 && brace_depth == 0 && bracket_depth == 0)
4595 break;
4596
4597 /*
4598 * If it's a close paren, and it doesn't match an earlier open
4599 * paren in the same argument, it's the end of the argument.
4600 */
4601 if (typ == TOKT_RPAR && paren_depth == 0)
4602 break;
4603
4604 /*
4605 * if it's an open or close paren, brace, or bracket, adjust
4606 * the depth accordingly
4607 */
4608 switch(typ)
4609 {
4610 case TOKT_LPAR:
4611 ++paren_depth;
4612 break;
4613
4614 case TOKT_RPAR:
4615 --paren_depth;
4616 break;
4617
4618 case TOKT_LBRACE:
4619 ++brace_depth;
4620 break;
4621
4622 case TOKT_RBRACE:
4623 --brace_depth;
4624 break;
4625
4626 case TOKT_LBRACK:
4627 ++bracket_depth;
4628 break;
4629
4630 case TOKT_RBRACK:
4631 --bracket_depth;
4632 break;
4633
4634 default:
4635 break;
4636 }
4637
4638 /* get the next token */
4639 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_,
4640 TRUE);
4641
4642 /*
4643 * if we're at the end of the line, and we're allowed to
4644 * read more, splice the next line onto the current line
4645 */
4646 if (typ == TOKT_EOF && read_more)
4647 {
4648 /* splice a line */
4649 typ = actual_splice_next_line(srcbuf, src, &tok);
4650
4651 /* note that we've done some line splicing */
4652 spliced = TRUE;
4653 }
4654
4655 /* if we've reached the end of the file, stop */
4656 if (typ == TOKT_EOF)
4657 break;
4658 }
4659
4660 /* if we've reached the end of the file, stop */
4661 if (typ == TOKT_EOF)
4662 break;
4663
4664 /* remove any trailing whitespace from the actual's text */
4665 sp_cnt = 0;
4666 p.set((char *)tok.get_text());
4667 while (p.getptr() > srcbuf->get_text() + argofs[argc])
4668 {
4669 wchar_t ch;
4670
4671 /* move to the prior character */
4672 p.dec();
4673
4674 /* if it's not a space, stop looking */
4675 ch = p.getch();
4676 if (!is_space(ch))
4677 {
4678 /*
4679 * advance past this character so that we keep it in the
4680 * expansion
4681 */
4682 p.inc();
4683
4684 /*
4685 * if this last character was a backslash, and we removed
4686 * at least one space following it, keep the one space
4687 * that immediately follows the backslash, since that
4688 * space is part of the backslash's two-character escape
4689 * sequence
4690 */
4691 if (ch == '\\' && sp_cnt != 0)
4692 p.inc();
4693
4694 /* stop scanning */
4695 break;
4696 }
4697
4698 /* that's one more trailing space we've removed - count it */
4699 ++sp_cnt;
4700 }
4701
4702 /* note the argument length */
4703 arglen[argc] = (p.getptr() - srcbuf->get_text()) - argofs[argc];
4704
4705 /* count the argument */
4706 ++argc;
4707
4708 /* check for another argument */
4709 if (typ == TOKT_COMMA)
4710 {
4711 /* remember the offset of the start of this argument */
4712 argofs[argc] = tok.get_text() + tok.get_text_len()
4713 - srcbuf->get_text();
4714
4715 /* skip the comma and go back for another argument */
4716 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_,
4717 TRUE);
4718 }
4719 else if (typ == TOKT_RPAR)
4720 {
4721 /*
4722 * No need to look any further. Note that we don't want to
4723 * get another token, since we're done parsing the input
4724 * now, and we want to leave the token stream positioned for
4725 * the caller just after the extent of the macro, which, in
4726 * the case of this function-like macro, ends with the
4727 * closing paren.
4728 */
4729 break;
4730 }
4731 }
4732
4733 /* if we didn't find the right paren, flag the error */
4734 if (typ != TOKT_RPAR)
4735 {
4736 log_error(read_more
4737 ? TCERR_PP_MACRO_ARG_RPAR : TCERR_PP_MACRO_ARG_RPAR_1LINE,
4738 (int)entry->getlen(), entry->getstr());
4739 return 1;
4740 }
4741
4742 /* remove leading and trailing whitespace from each argument */
4743 for (i = 0 ; i < argc ; ++i)
4744 {
4745 const char *start;
4746 const char *end;
4747 utf8_ptr p;
4748 size_t del_len;
4749 int sp_cnt;
4750
4751 /* figure the limits of the argument text */
4752 start = srcbuf->get_text() + argofs[i];
4753 end = start + arglen[i];
4754
4755 /* remove leading whitespace */
4756 for (p.set((char *)start) ; p.getptr() < end && is_space(p.getch()) ;
4757 p.inc()) ;
4758
4759 /* set the new offset and length */
4760 del_len = p.getptr() - start;
4761 argofs[i] += del_len;
4762 arglen[i] -= del_len;
4763 start += del_len;
4764
4765 /* remove trailing whitespace */
4766 p.set((char *)end);
4767 sp_cnt = 0;
4768 while (p.getptr() > start)
4769 {
4770 wchar_t ch;
4771
4772 /* go to the prior character */
4773 p.dec();
4774
4775 /* if it's not whitespace, keep it */
4776 ch = p.getch();
4777 if (!is_space(ch))
4778 {
4779 /* put the character back */
4780 p.inc();
4781
4782 /*
4783 * if this is a backslash, and a space follows, keep the
4784 * immediately following space, since it's part of the
4785 * backslash sequence
4786 */
4787 if (ch == '\\' && sp_cnt != 0)
4788 p.inc();
4789
4790 /* we're done scanning */
4791 break;
4792 }
4793
4794 /* count another removed trailing space */
4795 ++sp_cnt;
4796 }
4797
4798 /* adjust the length */
4799 arglen[i] -= (end - p.getptr());
4800 }
4801
4802 /*
4803 * if we did any line splicing, cut off the rest of the line and
4804 * push it back into the logical input stream as a new line - this
4805 * will allow better error message positioning if errors occur in
4806 * the remainder of the line, since this means we'll only
4807 * artificially join onto one line the part of the new line that
4808 * contained the macro parameters
4809 */
4810 if (spliced)
4811 unsplice_line(tok.get_text() + tok.get_text_len());
4812
4813 /* make sure we found enough arguments */
4814 if (argc < entry->get_min_argc())
4815 {
4816 /* fill in the remaining arguments with empty strings */
4817 for ( ; argc < entry->get_argc() ; ++argc)
4818 {
4819 argofs[argc] = 0;
4820 arglen[argc] = 0;
4821 }
4822
4823 /* note the error, but proceed with empty arguments */
4824 log_warning(TCERR_PP_FEW_MACRO_ARGS,
4825 (int)entry->getlen(), entry->getstr());
4826 }
4827
4828 /*
4829 * if we have varargs, always supply an empty marker for the last
4830 * argument
4831 */
4832 if (entry->has_varargs() && argc < TOK_MAX_MACRO_ARGS)
4833 {
4834 argofs[argc] = 0;
4835 arglen[argc] = 0;
4836 }
4837
4838 /* success - we found an actual parameter list */
4839 *found_actuals = TRUE;
4840 return 0;
4841 }
4842
4843 /*
4844 * Splice a line for macro actual parameters. Sets the source pointer
4845 * to the start of the new line. Reads the first token on the spliced
4846 * line and returns it.
4847 *
4848 * We will splice new lines until we find a non-empty line or reach the
4849 * end of the input. If this returns EOF, it indicates that we've
4850 * reached the end of the entire input.
4851 */
4852 tc_toktyp_t CTcTokenizer::actual_splice_next_line(
4853 const CTcTokString *srcbuf, utf8_ptr *src, CTcToken *tok)
4854 {
4855 /* add a space onto the end of the current line */
4856 linebuf_.append(" ", 1);
4857
4858 /* keep going until we find a non-empty line */
4859 for (;;)
4860 {
4861 int new_line_ofs;
4862 tc_toktyp_t typ;
4863
4864 /* splice the next line onto the current line */
4865 new_line_ofs = read_line(TRUE);
4866
4867 /*
4868 * make sure we read additional lines as needed to complete any
4869 * strings left open at the end of the line
4870 */
4871 if (in_quote_ != '\0')
4872 splice_string();
4873
4874 /* if there was no more, return end of file */
4875 if (new_line_ofs == -1)
4876 return TOKT_EOF;
4877
4878 /* set the source to the start of the additional line */
4879 src->set((char *)linebuf_.get_text() + new_line_ofs);
4880
4881 /* get the next token */
4882 typ = next_on_line(srcbuf, src, tok, &macro_in_embedding_, TRUE);
4883
4884 /* if we didn't get EOF, it means we found a non-empty line */
4885 if (typ != TOKT_EOF)
4886 return typ;
4887 }
4888 }
4889
4890 /*
4891 * Substitute the actual parameters in a macro's expansion
4892 */
4893 int CTcTokenizer::substitute_macro_actuals(
4894 CTcMacroRsc *rsc, CTcTokString *subexp, CTcHashEntryPp *entry,
4895 const CTcTokString *srcbuf, const size_t *argofs, const size_t *arglen,
4896 int allow_defined)
4897 {
4898 const char *start;
4899 utf8_ptr expsrc;
4900 CTcToken prvtok;
4901 CTcToken prvprvtok;
4902 CTcToken tok;
4903 tc_toktyp_t typ;
4904 CTcTokString *actual_exp_buf;
4905 const size_t expand_max = 10;
4906 static struct expand_info_t
4907 {
4908 /* type of expansion (#foreach, #ifempty, #ifnempty) */
4909 tc_toktyp_t typ;
4910
4911 /*
4912 * flag: this is an iterator type (if this is true, the varargs
4913 * formal should be expanded to the current argument given by our
4914 * 'arg' member; if this is false, the varargs formal should be
4915 * expanded as the full varargs list)
4916 */
4917 int is_iterator;
4918
4919 /* the marker character that delimits the foreach arguments */
4920 wchar_t delim;
4921
4922 /* location of start of expansion region for foreach */
4923 utf8_ptr start;
4924
4925 /* current argument index */
4926 int arg;
4927
4928 /* the current expansion part (0 = first part, etc) */
4929 int part;
4930 }
4931 expand_stack[expand_max], *expand_sp;
4932
4933 /* get the actual expansion buffer from the resource object */
4934 actual_exp_buf = &rsc->actual_exp_buf_;
4935
4936 /*
4937 * Scan the replacement text for formals, and replace each formal
4938 * with the actual. Set up a pointer at the start of the expansion
4939 * text.
4940 */
4941 start = entry->get_expansion();
4942 expsrc.set((char *)start);
4943
4944 /* we don't yet have a previous token */
4945 prvtok.settyp(TOKT_EOF);
4946 prvprvtok.settyp(TOKT_EOF);
4947
4948 /* clear the expansion buffer */
4949 subexp->clear_text();
4950
4951 /* we have no #foreach/#ifempty/#ifnempty stack yet */
4952 expand_sp = expand_stack;
4953
4954 /* scan the tokens in the expansion text */
4955 for (typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE) ;
4956 typ != TOKT_EOF ; )
4957 {
4958 /*
4959 * check to see if we've reached the end of a
4960 * #foreach/#ifempty/#ifnempty
4961 */
4962 if (expand_sp != expand_stack)
4963 {
4964 /* check to see if we're at the delimiter */
4965 if (utf8_ptr::s_getch(tok.get_text()) == (expand_sp-1)->delim)
4966 {
4967 /* copy the prior expansion so far */
4968 if (tok.get_text() > start)
4969 subexp->append(start, tok.get_text() - start);
4970
4971 /* go back to the start of the token */
4972 expsrc.set((char *)tok.get_text());
4973
4974 /* see what kind of token we're expanding */
4975 switch((expand_sp-1)->typ)
4976 {
4977 case TOKT_MACRO_FOREACH:
4978 /* it's a #foreach - process the appropriate part */
4979 switch ((expand_sp-1)->part)
4980 {
4981 case 0:
4982 /*
4983 * We've been doing the first part, which is the
4984 * main expansion per actual. This delimiter thus
4985 * introduces the 'between' portion, which we copy
4986 * between each iteration, but not after the last
4987 * iteration. So, if we've just done the last
4988 * actual, skip this part entirely; otherwise,
4989 * keep going, using this part.
4990 */
4991 if (argofs[(expand_sp-1)->arg + 1] == 0)
4992 {
4993 /* skip this one remaining part */
4994 skip_delimited_group(&expsrc, 1);
4995
4996 /* we're finished with the iteration */
4997 goto end_foreach;
4998 }
4999 else
5000 {
5001 /*
5002 * we have more arguments, so we want to
5003 * expand this part - skip the deliter and
5004 * keep going
5005 */
5006 expsrc.inc();
5007
5008 /* we're now in the next part of the iterator */
5009 (expand_sp-1)->part++;
5010 }
5011 break;
5012
5013 case 1:
5014 /*
5015 * We've reached the end of the entire #foreach
5016 * string, so we're done with this iteration.
5017 * Skip the delimiter.
5018 */
5019 expsrc.inc();
5020
5021 end_foreach:
5022 /*
5023 * if we have more arguments, start over with the
5024 * next iteration; otherwise, pop the #foreach
5025 * level
5026 */
5027 if (argofs[(expand_sp-1)->arg + 1] == 0)
5028 {
5029 /* no more arguments - pop the #foreach level */
5030 --expand_sp;
5031 }
5032 else
5033 {
5034 /* we have more arguments - move to the next */
5035 (expand_sp-1)->arg++;
5036
5037 /* go back to the start of the expansion */
5038 expsrc = (expand_sp-1)->start;
5039
5040 /* we have no previous token for pasting ops */
5041 prvtok.settyp(TOKT_EOF);
5042 prvprvtok.settyp(TOKT_EOF);
5043
5044 /* we're back in the first part of the iterator */
5045 (expand_sp-1)->part = 0;
5046 }
5047 break;
5048 }
5049 break;
5050
5051 case TOKT_MACRO_IFEMPTY:
5052 case TOKT_MACRO_IFNEMPTY:
5053 /*
5054 * #ifempty or #ifnempty - we've reached the end of
5055 * the conditional text, so simply pop a level and
5056 * keep going after the delimiter
5057 */
5058
5059 /* skip the delimiter */
5060 expsrc.inc();
5061
5062 /* pop a level */
5063 --expand_sp;
5064
5065 /* done */
5066 break;
5067
5068 default:
5069 break;
5070 }
5071
5072 /* the next chunk starts here */
5073 start = expsrc.getptr();
5074
5075 /* get the next token */
5076 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE);
5077
5078 /* we have the next token, so back and process it */
5079 continue;
5080 }
5081 }
5082
5083 /* if it's a #foreach marker, start a #foreach iteration */
5084 if (typ == TOKT_MACRO_FOREACH && entry->has_varargs())
5085 {
5086 /* copy the prior expansion so far */
5087 if (tok.get_text() > start)
5088 subexp->append(start, tok.get_text() - start);
5089
5090 /* push a #foreach level, if possible */
5091 if (expand_sp - expand_stack >= expand_max)
5092 {
5093 /*
5094 * we can't create another level - log an error and ignore
5095 * this new level
5096 */
5097 log_error(TCERR_PP_FOREACH_TOO_DEEP);
5098 }
5099 else if (argofs[entry->get_argc() - 1] == 0)
5100 {
5101 /*
5102 * we have no actuals for the variable part of the
5103 * formals, so we must iterate zero times through the
5104 * #foreach part - in other words, simply skip ahead to
5105 * the end of the #foreach
5106 */
5107 skip_delimited_group(&expsrc, 2);
5108 }
5109 else
5110 {
5111 /* remember and skip the marker character */
5112 expand_sp->delim = expsrc.getch();
5113 expsrc.inc();
5114
5115 /* set the expansion type */
5116 expand_sp->typ = typ;
5117
5118 /*
5119 * remember the position where the #foreach started, since
5120 * we need to come back here for each use of the variable
5121 */
5122 expand_sp->start = expsrc;
5123
5124 /* we're an iterator type */
5125 expand_sp->is_iterator = TRUE;
5126
5127 /*
5128 * Start at the first argument in the variable part of the
5129 * argument list. The last formal corresponds to the
5130 * first variable argument.
5131 */
5132 expand_sp->arg = entry->get_argc() - 1;
5133
5134 /* we're in the main expansion part of the expression */
5135 expand_sp->part = 0;
5136
5137 /* push the new level */
5138 ++expand_sp;
5139 }
5140
5141 /* the next chunk starts here */
5142 start = expsrc.getptr();
5143
5144 /* get the next token */
5145 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE);
5146
5147 /* we have the next token, so back and process it */
5148 continue;
5149 }
5150
5151 /* if it's a varargs #ifempty or #ifnempty flag, expand it */
5152 if ((typ == TOKT_MACRO_IFEMPTY || typ == TOKT_MACRO_IFNEMPTY)
5153 && entry->has_varargs())
5154 {
5155 int is_empty;
5156 int expand;
5157
5158 /* copy the prior expansion so far */
5159 if (tok.get_text() > start)
5160 subexp->append(start, tok.get_text() - start);
5161
5162 /* determine if the varargs list is empty or not */
5163 is_empty = (argofs[entry->get_argc() - 1] == 0);
5164
5165 /*
5166 * decide whether or not expand it, according to the empty
5167 * state and the flag type
5168 */
5169 expand = ((is_empty && typ == TOKT_MACRO_IFEMPTY)
5170 || (!is_empty && typ == TOKT_MACRO_IFNEMPTY));
5171
5172 /*
5173 * if we're going to expand it, push a level; otherwise, just
5174 * skip the entire expansion
5175 */
5176 if (expand)
5177 {
5178 /* make sure we have room for another level */
5179 if (expand_sp - expand_stack >= expand_max)
5180 {
5181 /* no room - log an error and ignore the new level */
5182 log_error(TCERR_PP_FOREACH_TOO_DEEP);
5183 }
5184 else
5185 {
5186 /* remember and skip the delimiter */
5187 expand_sp->delim = expsrc.getch();
5188 expsrc.inc();
5189
5190 /*
5191 * we're not an iterator type, so inherit the
5192 * enclosing level's meaning of the varargs formal
5193 */
5194 if (expand_sp - expand_stack == 0)
5195 {
5196 /* outermost level - use the whole varargs list */
5197 expand_sp->is_iterator = FALSE;
5198 }
5199 else
5200 {
5201 /* use the enclosing level's meaning */
5202 expand_sp->is_iterator = (expand_sp-1)->is_iterator;
5203 expand_sp->arg = (expand_sp-1)->arg;
5204 }
5205
5206 /* set the expansion type */
5207 expand_sp->typ = typ;
5208
5209 /* push the new level */
5210 ++expand_sp;
5211 }
5212 }
5213 else
5214 {
5215 /* not expanding - just skip the entire expansion */
5216 skip_delimited_group(&expsrc, 1);
5217 }
5218
5219 /* the next chunk starts here */
5220 start = expsrc.getptr();
5221
5222 /* get the next token */
5223 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE);
5224
5225 /* we have the next token, so back and process it */
5226 continue;
5227 }
5228
5229 /* if it's a varargs #argcount indicator, expand it */
5230 if (typ == TOKT_MACRO_ARGCOUNT && entry->has_varargs())
5231 {
5232 char buf[20];
5233 int i;
5234
5235 /* copy the prior expansion so far */
5236 if (tok.get_text() > start)
5237 subexp->append(start, tok.get_text() - start);
5238
5239 /*
5240 * count the number of arguments after and including the
5241 * variable argument placeholder
5242 */
5243 for (i = entry->get_argc() - 1 ; argofs[i] != 0 ; ++i) ;
5244
5245 /* make a string out of the variable argument count */
5246 sprintf(buf, "%d", i - (entry->get_argc() - 1));
5247
5248 /* add the argument count to the output buffer */
5249 subexp->append(buf, strlen(buf));
5250
5251 /* the next chunk starts after the #argcount */
5252 start = expsrc.getptr();
5253
5254 /* get the next token */
5255 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE);
5256
5257 /* we have the next token, so back and process it */
5258 continue;
5259 }
5260
5261 /* if it's a symbol, check for an actual */
5262 if (typ == TOKT_MACRO_FORMAL)
5263 {
5264 const char *p;
5265 int argnum;
5266 size_t argnum_len;
5267 int pasting;
5268 int pasting_at_left, pasting_at_right;
5269 int stringize;
5270 char stringize_qu;
5271 tc_toktyp_t stringize_type;
5272 CTcToken paste_at_right_tok;
5273
5274 /* assume we'll copy up to the start of this token */
5275 p = tok.get_text();
5276
5277 /*
5278 * get the index of the actual in the argument vector --
5279 * this is given by the second byte of the special macro
5280 * parameter flag token
5281 */
5282 argnum = (int)(uchar)tok.get_text()[1] - 1;
5283
5284 /*
5285 * If we have varargs, and this is the varargs argument, and
5286 * the current #foreach stack level indicates that we're
5287 * iterating through the varargs list, treat this as a
5288 * reference to the current argument in the iteration.
5289 */
5290 if (expand_sp != expand_stack
5291 && argnum == entry->get_argc() - 1
5292 && (expand_sp-1)->is_iterator)
5293 {
5294 /*
5295 * we're on a #foreach iterator, and this is the varargs
5296 * formal - use the current #foreach iteration element
5297 * instead
5298 */
5299 argnum = (expand_sp-1)->arg;
5300 }
5301
5302 /*
5303 * Get the length of this argument. If we have varargs, and
5304 * this is the last formal, which is the placeholder for the
5305 * variable argument list, and we're not in a #foreach
5306 * iterator, the value is the value of the entire string of
5307 * variable arguments, including the commas.
5308 */
5309 if (expand_sp == expand_stack
5310 && entry->has_varargs()
5311 && argnum == entry->get_argc() - 1)
5312 {
5313 int i;
5314
5315 /*
5316 * It's the full varargs list - use the length from the
5317 * first varargs argument to the last. Find the last
5318 * argument.
5319 */
5320 for (i = argnum ;
5321 i < TOK_MAX_MACRO_ARGS && argofs[i] != 0 ; ++i) ;
5322
5323 /*
5324 * The full list length is the distance from the offset of
5325 * the first to the end of the last. If there are no
5326 * varargs arguments at all, the length is zero.
5327 */
5328 if (i == argnum)
5329 argnum_len = 0;
5330 else
5331 argnum_len = argofs[i-1] + arglen[i-1] - argofs[argnum];
5332 }
5333 else
5334 {
5335 /*
5336 * it's not the full varargs list, so just use the length
5337 * of this single actual
5338 */
5339 argnum_len = arglen[argnum];
5340 }
5341
5342 /* assume we won't do any token pasting or stringizing */
5343 pasting = pasting_at_left = pasting_at_right = FALSE;
5344 stringize = FALSE;
5345
5346 /*
5347 * if the previous token was a token-pasting operator,
5348 * remove it and any preceding whitespace from the source
5349 * material, since we want to append the actual parameter
5350 * text directly after the preceding token
5351 */
5352 check_paste_left:
5353 if (prvtok.gettyp() == TOKT_POUNDPOUND)
5354 {
5355 wchar_t prv_ch;
5356
5357 /*
5358 * note that we have token pasting - we're pasting
5359 * something to the left of this token (since we had a
5360 * "##" before this token
5361 */
5362 pasting = TRUE;
5363 pasting_at_left = TRUE;
5364
5365 /* go back to the ## token */
5366 p = prvtok.get_text();
5367
5368 /* remove any preceding whitespace */
5369 for (prv_ch = 0 ; p > start ; )
5370 {
5371 const char *prvp;
5372
5373 /* get the previous character */
5374 prvp = utf8_ptr::s_dec((char *)p);
5375 prv_ch = utf8_ptr::s_getch((char *)prvp);
5376
5377 /* if it's not a space, we're done */
5378 if (!is_space(prv_ch))
5379 break;
5380
5381 /* move back over this character */
5382 p = prvp;
5383 }
5384
5385 /*
5386 * Weird special case: if the previous character was a
5387 * comma, and the formal we're pasting is a variable
5388 * argument formal (i.e., the last formal in a varargs
5389 * macro), and the varargs list is empty, then remove the
5390 * comma. This is a handy shorthand notation that allows
5391 * the varargs list to be added to a comma-delimited list,
5392 * such as a function call's actuals or the contents of a
5393 * list.
5394 */
5395 if (prv_ch == ','
5396 && entry->has_varargs()
5397 && argnum == entry->get_argc() - 1
5398 && argofs[argnum] == 0)
5399 {
5400 /*
5401 * it's the special case - move back one more
5402 * character to delete the comma
5403 */
5404 p = utf8_ptr::s_dec((char *)p);
5405 }
5406 }
5407 else if (prvtok.gettyp() == TOKT_POUND
5408 || prvtok.gettyp() == TOKT_POUNDAT)
5409 {
5410 /* go back to the # token */
5411 p = prvtok.get_text();
5412
5413 /* note that we have stringizing */
5414 stringize = TRUE;
5415 stringize_type = prvtok.gettyp();
5416 stringize_qu = (prvtok.gettyp() == TOKT_POUND
5417 ? '"' : '\'');
5418
5419 /* go back one more token */
5420 prvtok = prvprvtok;
5421 prvprvtok.settyp(TOKT_EOF);
5422
5423 /*
5424 * go back and check for pasting again, since we could
5425 * be pasting to a stringized token
5426 */
5427 goto check_paste_left;
5428 }
5429
5430 /* copy the prior expansion so far */
5431 if (p > start)
5432 subexp->append(start, p - start);
5433
5434 /* remember the symbol as the previous token */
5435 prvprvtok = prvtok;
5436 prvtok = tok;
5437
5438 /* get the next token after the formal */
5439 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE);
5440
5441 /*
5442 * If it's followed by a token-pasting operator, we need to
5443 * paste the next token directly onto the end of the text we
5444 * just added to the buffer, skipping any intervening
5445 * whitespace; otherwise, we want to start adding again at
5446 * the next character after the original token.
5447 */
5448 if (typ == TOKT_POUNDPOUND)
5449 {
5450 utf8_ptr old_expsrc;
5451 CTcToken old_tok;
5452
5453 /* note that we have pasting to the right of this token */
5454 pasting = TRUE;
5455 pasting_at_right = TRUE;
5456
5457 /* remember where we started */
5458 old_expsrc = expsrc;
5459
5460 /* remember the current token for a moment */
5461 old_tok = tok;
5462
5463 /* skip to the next token after the ## */
5464 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE);
5465
5466 /* remember the token we're pasting to the right */
5467 paste_at_right_tok = tok;
5468
5469 /* check for pasting to a stringizer */
5470 if (stringize && typ == stringize_type)
5471 {
5472 /*
5473 * leave the ## in the stream for now - we'll fix it
5474 * up when we stringize the next token, rather than
5475 * doing so now
5476 */
5477 expsrc = old_expsrc;
5478 tok = old_tok;
5479 }
5480 else
5481 {
5482 /*
5483 * remember that we have a token-pasting operator,
5484 * so that we can tell that we're pasting when we
5485 * look at the next token
5486 */
5487 prvprvtok = prvtok;
5488 prvtok = old_tok;
5489 }
5490
5491 /* start next text from here */
5492 start = tok.get_text();
5493 }
5494 else
5495 {
5496 /* Start at the end of the symbol token */
5497 start = prvtok.get_text() + prvtok.get_text_len();
5498 }
5499
5500 /*
5501 * If we're not doing any pasting, recursively expand macros
5502 * in the actual expansion text. If we're pasting, do not
5503 * expand any macros in the expansion, since we want to do
5504 * the pasting before we do any expanding.
5505 */
5506 if (pasting && stringize)
5507 {
5508 int add_open;
5509 int add_close;
5510
5511 /* presume we'll include the open and close quotes */
5512 add_close = TRUE;
5513 add_open = TRUE;
5514
5515 /*
5516 * If we're pasting to the left, and the buffer so far
5517 * ends in the same quote we're adding to this token,
5518 * combine the strings by removing the preceding quote
5519 * and not adding the open quote on the new string
5520 */
5521 if (subexp->get_text_len() > 0
5522 && *(subexp->get_text_end() - 1) == stringize_qu)
5523 {
5524 /* remove the close quote from the expansion so far */
5525 subexp->set_text_len(subexp->get_text_len() - 1);
5526
5527 /* don't add the open quote to the new string */
5528 add_open = FALSE;
5529 }
5530
5531 /*
5532 * If we're pasting to the right, and we have a string
5533 * of the same type following, or we will be pasting a
5534 * stringizing pair, paste the two strings together to
5535 * form one string by removing the close quote from this
5536 * string and the open quote from the next string
5537 */
5538 if (pasting_at_right && *tok.get_text() == stringize_qu)
5539 add_close = FALSE;
5540
5541 /*
5542 * We're both stringizing this argument and pasting
5543 * another token - first stringize the actual.
5544 */
5545 stringize_macro_actual(subexp,
5546 srcbuf->get_text()
5547 + argofs[argnum], argnum_len,
5548 stringize_qu, add_open, add_close);
5549
5550 /*
5551 * if we decided to remove the closing quote, we want to
5552 * remove the open quote from the following string as
5553 * well - copy in the following string without its open
5554 * quote
5555 */
5556 if (!add_close)
5557 {
5558 /*
5559 * append the following token without its first
5560 * character (its open quote)
5561 */
5562 subexp->append(tok.get_text() + 1,
5563 tok.get_text_len() - 1);
5564
5565 /* move on to the next token */
5566 prvprvtok = prvtok;
5567 prvtok = tok;
5568 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_,
5569 TRUE);
5570
5571 /* start from the new token */
5572 start = tok.get_text();
5573 }
5574 }
5575 else if (pasting)
5576 {
5577 const char *argp;
5578 size_t len;
5579 int done;
5580 wchar_t quote_char;
5581
5582 /* get the actual argument information */
5583 argp = srcbuf->get_text() + argofs[argnum];
5584 len = argnum_len;
5585
5586 /*
5587 * if we're pasting to the left of this token, and the
5588 * token starts with a fully-expanded flag, remove the
5589 * flag - we're making up a new token out of this and
5590 * what comes before, so the token that we fully
5591 * expanded is disappearing, so the fully-expanded
5592 * status no longer applies
5593 */
5594 if (pasting_at_left && *argp == TOK_FULLY_EXPANDED_FLAG)
5595 {
5596 /* skip the flag */
5597 ++argp;
5598 --len;
5599 }
5600
5601 /* presume we won't find any quoted strings */
5602 quote_char = 0;
5603
5604 /*
5605 * check for string concatenation to the left - if we're
5606 * concatenating two strings of the same type, remove
5607 * the adjacent quotes to make it a single string
5608 */
5609 if (pasting_at_left
5610 && subexp->get_text_len() > 0
5611 && (*argp == '\'' || *argp == '"')
5612 && *(subexp->get_text_end() - 1) == *argp)
5613 {
5614 /* remove the close quote from the expansion so far */
5615 subexp->set_text_len(subexp->get_text_len() - 1);
5616
5617 /* remember the quote character */
5618 quote_char = *argp;
5619
5620 /* don't add the open quote to the new string */
5621 ++argp;
5622 --len;
5623 }
5624
5625 /* presume we won't have to do anything special */
5626 done = FALSE;
5627
5628 /*
5629 * If we're pasting at the right, also remove any
5630 * fully-expanded flag just before the last token in the
5631 * expansion.
5632 */
5633 if (pasting_at_right)
5634 {
5635 CTcToken old_tok;
5636 CTcToken tok;
5637 utf8_ptr p;
5638
5639 /* scan for the final token in the expansion string */
5640 p.set((char *)argp);
5641 old_tok.settyp(TOKT_INVALID);
5642 while (p.getptr() < argp + len)
5643 {
5644 /*
5645 * get another token - stop at EOF or if we go
5646 * past the bounds of the expansion text
5647 */
5648 if (next_on_line(&p, &tok, &macro_in_embedding_,
5649 TRUE)
5650 == TOKT_EOF
5651 || tok.get_text() >= argp + len)
5652 break;
5653
5654 /* remember the previous token */
5655 old_tok = tok;
5656 }
5657
5658 /*
5659 * if the final token is a symbol, and it has the
5660 * fully-expanded flag, we must omit the flag from
5661 * the appended text
5662 */
5663 if (old_tok.gettyp() == TOKT_SYM
5664 && old_tok.get_fully_expanded())
5665 {
5666 /*
5667 * append up to but not including the flag byte
5668 * preceding the final token
5669 */
5670 subexp->append(argp, tok.get_text() - 1 - argp);
5671
5672 /*
5673 * append from the last token to the end of the
5674 * expansion, skipping the flag byte
5675 */
5676 subexp->append(tok.get_text(),
5677 len - (tok.get_text() - argp));
5678
5679 /* we've done the appending */
5680 done = TRUE;
5681 }
5682 else if (quote_char != 0
5683 && paste_at_right_tok.get_text_len() != 0
5684 && *paste_at_right_tok.get_text() == quote_char)
5685 {
5686 /*
5687 * we're pasting two strings together - append
5688 * up to but not including the close quote
5689 */
5690 subexp->append(argp, len - 1);
5691
5692 /*
5693 * append the next token, but do not include the
5694 * open quote
5695 */
5696 subexp->append(paste_at_right_tok.get_text() + 1,
5697 paste_at_right_tok.get_text_len() - 1);
5698
5699 /*
5700 * restart after the right token, since we've
5701 * now fully processed that token
5702 */
5703 start = paste_at_right_tok.get_text()
5704 + paste_at_right_tok.get_text_len();
5705
5706 /* we're done */
5707 done = TRUE;
5708 }
5709 }
5710
5711 /*
5712 * append the actual without expansion, if we haven't
5713 * already handled it specially
5714 */
5715 if (!done)
5716 subexp->append(argp, len);
5717 }
5718 else if (stringize)
5719 {
5720 /* stringize the actual */
5721 stringize_macro_actual(subexp,
5722 srcbuf->get_text()
5723 + argofs[argnum], argnum_len,
5724 stringize_qu, TRUE, TRUE);
5725 }
5726 else
5727 {
5728 CTcTokStringRef actual_src_buf;
5729
5730 /* recursively expand macros in the actual text */
5731 actual_src_buf.
5732 set_buffer(srcbuf->get_text() + argofs[argnum],
5733 argnum_len);
5734 if (expand_macros(&actual_src_buf, 0, actual_exp_buf,
5735 FALSE, allow_defined, FALSE))
5736 return 1;
5737
5738 /*
5739 * Append the expanded actual, marking any
5740 * fully-expanded tokens as such and removing
5741 * end-of-expansion markers.
5742 *
5743 * We can't leave end-of-expansion markers in the
5744 * expanded actual text, because end-of-expansion
5745 * markers apply only to the current recursion level,
5746 * and we've now exited the actual's recursion level.
5747 * However, we must not expand further anything in the
5748 * actual's expansion that has already been fully
5749 * expanded. To achieve both of these goals, we switch
5750 * here from marking the run of text (with the end
5751 * marker) to marking individual tokens.
5752 */
5753 mark_full_exp_tokens(subexp, actual_exp_buf, TRUE);
5754 }
5755
5756 /* we've already read the next token, so proceed */
5757 continue;
5758 }
5759
5760 /* remember the current token as the previous token */
5761 prvprvtok = prvtok;
5762 prvtok = tok;
5763
5764 /* get the next token of the expansion */
5765 typ = next_on_line(&expsrc, &tok, &macro_in_embedding_, TRUE);
5766 }
5767
5768 /* copy the remaining replacement text */
5769 subexp->append(start, tok.get_text() - start);
5770
5771 /* success */
5772 return 0;
5773 }
5774
5775 /*
5776 * Skip the source of a delimited macro expansion area (#foreach,
5777 * #ifempty, #ifnempty).
5778 */
5779 void CTcTokenizer::skip_delimited_group(utf8_ptr *p, int parts_to_skip)
5780 {
5781 wchar_t delim;
5782
5783 /* get the delimiter character */
5784 delim = p->getch();
5785
5786 /*
5787 * if the delimiter put us at the end of the line, there's nothing to
5788 * skip
5789 */
5790 if (delim == 0 || delim == TOK_END_PP_LINE)
5791 return;
5792
5793 /* skip the delimiter */
5794 p->inc();
5795
5796 /* keep going until we've skipped the desired number of parts */
5797 while (parts_to_skip != 0)
5798 {
5799 wchar_t ch;
5800
5801 /* read the next character */
5802 ch = p->getch();
5803
5804 /* if it's the end of the line, give up */
5805 if (ch == 0 || ch == TOK_END_PP_LINE)
5806 {
5807 /*
5808 * we ran out of input before reaching the delimiter, so this
5809 * is implicitly the end of it
5810 */
5811 return;
5812 }
5813
5814 /* check what we have */
5815 if (ch == delim)
5816 {
5817 /* that's one less part to skip */
5818 --parts_to_skip;
5819
5820 /* skip it */
5821 p->inc();
5822 }
5823 else if (ch == TOK_MACRO_FOREACH_FLAG)
5824 {
5825 /* it's a nested #foreach - skip all of its parts */
5826 skip_delimited_group(p, 2);
5827 }
5828 else if (ch == TOK_MACRO_IFEMPTY_FLAG
5829 || ch == TOK_MACRO_IFNEMPTY_FLAG)
5830 {
5831 /* nested #ifempty or #ifnempty - skip its expansion */
5832 skip_delimited_group(p, 1);
5833 }
5834 else
5835 {
5836 /* it's nothing special to us - skip it */
5837 p->inc();
5838 }
5839 }
5840 }
5841
5842 /*
5843 * Stringize a macro actual parameter value into a macro expansion
5844 * buffer
5845 */
5846 void CTcTokenizer::stringize_macro_actual(CTcTokString *expbuf,
5847 const char *actual_val,
5848 size_t actual_len, char quote_char,
5849 int add_open_quote,
5850 int add_close_quote)
5851 {
5852 utf8_ptr src;
5853 const char *start;
5854 int in_inner_quote;
5855 wchar_t inner_quote_char;
5856 wchar_t prvch;
5857
5858 /* add the open quote if desired */
5859 if (add_open_quote)
5860 expbuf->append(&quote_char, 1);
5861
5862 /* remember the start of the current segment */
5863 start = actual_val;
5864
5865 /*
5866 * add the characters of the actual parameter value, quoting any
5867 * quotes or backslashes
5868 */
5869 for (src.set((char *)actual_val),
5870 in_inner_quote = FALSE, inner_quote_char = '\0', prvch = '\0' ;
5871 src.getptr() < actual_val + actual_len ; )
5872 {
5873 wchar_t cur;
5874
5875 /* get this character */
5876 cur = src.getch();
5877
5878 /* compress runs of whitespace to single spaces */
5879 if (is_space(cur) && prvch != '\\')
5880 {
5881 /* append up to this character */
5882 if (src.getptr() > start)
5883 expbuf->append(start, src.getptr() - start);
5884
5885 /* find the next non-space character */
5886 for ( ; src.getptr() < actual_val + actual_len ; src.inc())
5887 {
5888 if (!is_space(src.getch()))
5889 break;
5890 }
5891
5892 /*
5893 * if we're not at the start or end of the string, add a
5894 * single space to replace the entire run of whitespace --
5895 * don't do this at the start or end of the string, since
5896 * we must remove leading and trailing whitespace
5897 */
5898 if (prvch != '\0' && src.getptr() < actual_val + actual_len)
5899 expbuf->append(" ", 1);
5900
5901 /* note that the previous character is a space */
5902 prvch = cur;
5903
5904 /* this is the new starting point */
5905 start = src.getptr();
5906
5907 /* proceed - we're already at the next character */
5908 continue;
5909 }
5910
5911 /*
5912 * Check to see if we need to quote this character. Quote any
5913 * quote mark matching the enclosing quotes; also quote any
5914 * backslash that occurs within nested quotes within the source
5915 * material, but not backslashes that occur originally outside
5916 * quotes.
5917 */
5918 if (cur == quote_char
5919 || (cur == '\\' && in_inner_quote))
5920 {
5921 /* append the segment up to (but not including) this character */
5922 if (src.getptr() > start)
5923 expbuf->append(start, src.getptr() - start);
5924
5925 /* add an extra backslash */
5926 expbuf->append("\\", 1);
5927
5928 /* remember the start of the next segment */
5929 start = src.getptr();
5930 }
5931
5932 /*
5933 * if this is a quote character, and it's not itself escaped,
5934 * reverse our in-quote flag
5935 */
5936 if (prvch != '\\')
5937 {
5938 /*
5939 * If we're in an inner quote, and it's a match for the open
5940 * inner quote, we're no longer in a quote. Otherwise, if
5941 * we're not in quotes and this is some kind of quote, enter
5942 * the new quotes.
5943 */
5944 if (in_inner_quote && cur == inner_quote_char)
5945 {
5946 /* we're leaving the inner quoted string */
5947 in_inner_quote = FALSE;
5948 }
5949 else if (!in_inner_quote && (cur == '"' || cur == '\''))
5950 {
5951 /* we're entering a new inner quoted string */
5952 in_inner_quote = TRUE;
5953 inner_quote_char = cur;
5954 }
5955 }
5956
5957 /* remember this as the previous character */
5958 prvch = cur;
5959
5960 /* move on to the next character */
5961 src.inc();
5962 }
5963
5964 /* if there's anything in the final segment, append it */
5965 if (src.getptr() > start)
5966 expbuf->append(start, src.getptr() - start);
5967
5968 /* add the close quote if desired */
5969 if (add_close_quote)
5970 expbuf->append(&quote_char, 1);
5971 }
5972
5973 /*
5974 * Expand a "defined" preprocessor operator
5975 */
5976 int CTcTokenizer::expand_defined(CTcTokString *subexp,
5977 const CTcTokString *srcbuf, utf8_ptr *src)
5978 {
5979 CTcToken tok;
5980 tc_toktyp_t typ;
5981 int paren;
5982 int found;
5983
5984 /* get the next token */
5985 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_, FALSE);
5986
5987 /* note whether we have an open paren; if we do, skip it */
5988 paren = (typ == TOKT_LPAR);
5989 if (paren)
5990 typ = next_on_line(srcbuf, src, &tok, &macro_in_embedding_, FALSE);
5991
5992 /* get the symbol */
5993 if (typ != TOKT_SYM)
5994 {
5995 log_error(TCERR_PP_DEFINED_NO_SYM,
5996 (int)tok.get_text_len(), tok.get_text());
5997 return 1;
5998 }
5999
6000 /* look to see if the symbol is defined */
6001 found = (find_define(tok.get_text(), tok.get_text_len()) != 0);
6002
6003 /* expand the macro to "1" if found, "0" if not */
6004 subexp->copy(found ? "1" : "0", 1);
6005
6006 /* check for and skip the matching close paren */
6007 if (paren)
6008 {
6009 /* require the closing paren */
6010 if (next_on_line(srcbuf, src, &tok, &macro_in_embedding_, FALSE)
6011 != TOKT_RPAR)
6012 {
6013 /* generate an error if we don't find it */
6014 log_error(TCERR_PP_DEFINED_RPAR);
6015 return 1;
6016 }
6017 }
6018
6019 /* success */
6020 return 0;
6021 }
6022
6023
6024 /* ------------------------------------------------------------------------ */
6025 /*
6026 * Process comments. Replaces each character of a comment with a space.
6027 */
6028 void CTcTokenizer::process_comments(size_t start_ofs)
6029 {
6030 utf8_ptr src;
6031 utf8_ptr dst;
6032
6033 /* we haven't found a backslash followed by trailing space yet */
6034 int trailing_sp_after_bs = FALSE;
6035
6036 /*
6037 * Scan the line. When inside a comment, replace each character of
6038 * the comment with a space. When outside comments, simply copy
6039 * characters intact.
6040 *
6041 * Note that we need a separate src and dst pointer, because the
6042 * character length of the original and replaced characters may
6043 * change. Fortunately, the length will never do anything but
6044 * shrink or stay the same, since the only change we make is to
6045 * insert spaces, which are always one byte apiece in UTF-8; we can
6046 * therefore update the buffer in place.
6047 */
6048 for (src.set(linebuf_.get_buf() + start_ofs),
6049 dst.set(linebuf_.get_buf() + start_ofs) ;
6050 src.getch() != '\0' ; src.inc())
6051 {
6052 /* get the current character */
6053 wchar_t cur = src.getch();
6054
6055 /* check to see if we're in a comment */
6056 if (str_->is_in_comment())
6057 {
6058 /*
6059 * check to see if the comment is ending, or if we have an
6060 * apparent nested comment (which isn't allowed)
6061 */
6062 if (cur == '*' && src.getch_at(1) == '/')
6063 {
6064 /*
6065 * skip an extra character of the source - we'll skip
6066 * one in the main loop, so we only need to skip one
6067 * more now
6068 */
6069 src.inc();
6070
6071 /* we're no longer in a comment */
6072 str_->set_in_comment(FALSE);
6073 }
6074 else if (cur == '/' && src.getch_at(1) == '*')
6075 {
6076 /* looks like a nested comment - warn about it */
6077 if (!G_prs->get_syntax_only())
6078 log_warning(TCERR_NESTED_COMMENT);
6079 }
6080
6081 /* continue without copying anything from inside the comment */
6082 continue;
6083 }
6084 else if (in_quote_ != '\0')
6085 {
6086 /* see what we have */
6087 if (cur == '\\')
6088 {
6089 /*
6090 * It's a backslash sequence -- copy the backslash to
6091 * the output, and skip it. Note that we don't have to
6092 * worry about the line ending with a backslash, since
6093 * the line reader will already have considered that to
6094 * be a line splice.
6095 */
6096 src.inc();
6097 dst.setch(cur);
6098
6099 /* get the next character, so we copy it directly */
6100 cur = src.getch();
6101
6102 /*
6103 * if we're in a triple-quoted string, and this is an
6104 * escaped quote, the backslash escapes a whole run of
6105 * consecutive quotes that follow
6106 */
6107 if (in_triple_ && cur == in_quote_)
6108 {
6109 /* copy and skip any run of quotes, minus the last one */
6110 for (int qcnt = count_quotes(&src, cur) ; qcnt > 1 ;
6111 dst.setch(cur), src.inc(), --qcnt) ;
6112 }
6113 }
6114 else if (cur == in_quote_)
6115 {
6116 /* This is the close quote. Check for triple quotes. */
6117 if (in_triple_)
6118 {
6119 /* triple-quoted - we need three quotes in a row */
6120 int qcnt = count_quotes(&src, cur);
6121 if (qcnt >= 3)
6122 {
6123 /* copy and skip all but the last in the run */
6124 for (int i = 1 ; i < qcnt ; ++i, src.inc())
6125 dst.setch(cur);
6126
6127 /* close the string */
6128 in_quote_ = '\0';
6129 }
6130 }
6131 else
6132 {
6133 /* regular string, so it ends at the matching quote */
6134 in_quote_ = '\0';
6135 }
6136 }
6137 else if (cur == '<' && src.getch_at(1) == '<')
6138 {
6139 /*
6140 * it's an embedded expression starting point - skip the
6141 * first of the '<' characters (the enclosing loop will
6142 * skip the second one)
6143 */
6144 src.inc();
6145
6146 /* we're in an embedding now */
6147 comment_in_embedding_.start_expr(in_quote_, in_triple_, FALSE);
6148
6149 /* the string is done for now */
6150 in_quote_ = '\0';
6151
6152 /* copy the extra '<' to the output */
6153 dst.setch('<');
6154 }
6155 }
6156 else
6157 {
6158 /*
6159 * Monitor the stream for a backslash followed by trailing
6160 * spaces. If this is a backslash, note that we might have a
6161 * backslash with trailing spaces; if it's a space, we might
6162 * still have this, so leave the flag alone; if it's anything
6163 * else, clear the flag, since we've found something other
6164 * than backslashes and spaces.
6165 */
6166 if (cur == '\\')
6167 trailing_sp_after_bs = TRUE;
6168 else if (!is_space(cur))
6169 trailing_sp_after_bs = FALSE;
6170
6171 /* check to see if we're starting a comment */
6172 if (cur == '/')
6173 {
6174 switch(src.getch_at(1))
6175 {
6176 case '*':
6177 /* note that we're starting a comment */
6178 str_->set_in_comment(TRUE);
6179
6180 /*
6181 * replace the starting slash with a space - this
6182 * will effectively replace the entire comment with
6183 * a single space, since we won't copy anything else
6184 * from inside the comment
6185 */
6186 cur = ' ';
6187 break;
6188
6189 case '/':
6190 /*
6191 * comment to end of line - we can terminate the
6192 * line at the opening slash and return immediately,
6193 * because the entire rest of the line is to be
6194 * ignored
6195 */
6196 dst.setch('\0');
6197 return;
6198
6199 default:
6200 /* not a comment - copy it as-is */
6201 break;
6202 }
6203 }
6204 else if (cur == '"' || cur == '\'')
6205 {
6206 /* it's the start of a new string */
6207 in_quote_ = cur;
6208
6209 /* check for triple quotes */
6210 in_triple_ = (count_quotes(&src, cur) >= 3);
6211
6212 /* if in triple quotes, copy and skip the extra two qutoes */
6213 if (in_triple_)
6214 {
6215 src.inc_by(2);
6216 dst.setch(cur);
6217 dst.setch(cur);
6218 }
6219 }
6220 else if (cur < 0x09)
6221 {
6222 /*
6223 * it's a special flag character - we need to guarantee
6224 * that this character never occurs in input (it
6225 * shouldn't anyway, since it's a control character), so
6226 * translate it to a space
6227 */
6228 cur = ' ';
6229 }
6230 else if (comment_in_embedding_.in_expr()
6231 && (cur == '(' || cur == ')'))
6232 {
6233 /* adjust the paren level in an embedded expression */
6234 comment_in_embedding_.parens(cur == '(' ? 1 : -1);
6235 }
6236 else if (comment_in_embedding_.in_expr()
6237 && comment_in_embedding_.parens() == 0
6238 && cur == '>' && src.getch_at(1) == '>')
6239 {
6240 /* it's the end of an embedded expression */
6241 in_quote_ = comment_in_embedding_.qu();
6242 in_triple_ = comment_in_embedding_.triple();
6243 comment_in_embedding_.end_expr();
6244
6245 /* skip the extra '>' and copy it to the output */
6246 src.inc();
6247 dst.setch('>');
6248 }
6249 }
6250
6251 /* set the current character in the output */
6252 dst.setch(cur);
6253 }
6254
6255 /* set the updated line buffer length */
6256 linebuf_.set_text_len(dst.getptr() - linebuf_.get_buf());
6257
6258 /*
6259 * if we found a backslash with nothing following but whitespace, flag
6260 * a warning, since they might have meant the backslash as a line
6261 * continuation signal, but we're not interpreting it that way because
6262 * of the trailing whitespace
6263 */
6264 if (trailing_sp_after_bs)
6265 log_warning(TCERR_TRAILING_SP_AFTER_BS);
6266 }
6267
6268 /*
6269 * Splice strings. Splice additional lines onto the current line until
6270 * we find the end of the string.
6271 */
6272 void CTcTokenizer::splice_string()
6273 {
6274 /* presume we'll find proper termination */
6275 char unterm = '\0';
6276
6277 /*
6278 * remember the current in-quote and in-embedding status, as of the
6279 * end of the current line - when we splice, the line reader will
6280 * update these to the status at the end of the newly-read material,
6281 * but we want to scan from the beginning of the newly-read material
6282 */
6283 wchar_t in_quote = in_quote_;
6284 int in_triple = in_triple_;
6285 tok_embed_ctx old_ec = comment_in_embedding_;
6286
6287 /* note if the previous line ended with an explicit \n sequence */
6288 int explicit_nl = (linebuf_.get_text_len() >= 2
6289 && memcmp(linebuf_.get_text_end() - 2, "\\n", 2) == 0);
6290
6291 /* keep going until we find the end of the string */
6292 utf8_ptr p((char *)0);
6293 for (;;)
6294 {
6295 /* apply the newline spacing mode */
6296 switch (string_newline_spacing_)
6297 {
6298 case NEWLINE_SPACING_COLLAPSE:
6299 /*
6300 * Replace the newline and any subsequent run of whitespace
6301 * characters with a single space, unless the last line ended
6302 * with an explicit newline.
6303 */
6304 if (!explicit_nl)
6305 linebuf_.append(" ", 1);
6306 break;
6307
6308 case NEWLINE_SPACING_DELETE:
6309 /* delete the newline and subsequent whitespace */
6310 break;
6311
6312 case NEWLINE_SPACING_PRESERVE:
6313 /*
6314 * preserve the newline and subsequent whitespace exactly as
6315 * written in the source code, so convert the newline to an
6316 * explicit \n sequence (in source form, since we're building a
6317 * source line at this point)
6318 */
6319 linebuf_.append("\\n", 2);
6320 break;
6321 }
6322
6323 /* splice another line */
6324 int new_line_ofs = read_line(TRUE);
6325
6326 /* if we reached end of file, there's no more splicing we can do */
6327 if (new_line_ofs == -1)
6328 break;
6329
6330 /* get a pointer to the new text */
6331 char *new_line_p = (char *)linebuf_.get_text() + new_line_ofs;
6332 p.set(new_line_p);
6333
6334 /*
6335 * If we're in COLLAPSE or DELETE mode for newline spacing, skip
6336 * leading spaces in the new line. However, override this if the
6337 * previous line ended with an explicit \n sequence; this tells us
6338 * that the line break is explicitly part of the string and that
6339 * the subsequent whitespace is to be preserved.
6340 */
6341 if (string_newline_spacing_ != NEWLINE_SPACING_PRESERVE
6342 && !explicit_nl)
6343 for ( ; is_space(p.getch()) ; p.inc()) ;
6344
6345 /* check to see if the newly spliced text ends in an explicit \n */
6346 explicit_nl = (linebuf_.get_text_len() - new_line_ofs >= 2
6347 && memcmp(linebuf_.get_text_end() - 2, "\\n", 2) == 0);
6348
6349 /* if we skipped any spaces, remove them from the text */
6350 if (p.getptr() > new_line_p)
6351 {
6352 /* calculate the length of the rest of the line */
6353 size_t rem = linebuf_.get_text_len()
6354 - (p.getptr() - linebuf_.get_buf());
6355
6356 /* calculate the new length of the line */
6357 size_t new_len = (new_line_p - linebuf_.get_buf()) + rem;
6358
6359 /* move the rest of the line down over the spaces */
6360 memmove(new_line_p, p.getptr(), rem);
6361
6362 /* set the new length */
6363 linebuf_.set_text_len(new_len);
6364 }
6365
6366 /*
6367 * If the new line contains only "}" or ";", presume that the
6368 * string is unterminated and terminate it here. (This
6369 * heuristic could flag well-formed strings as erroneous, but
6370 * users can always work around this by moving these characters
6371 * onto lines that contain at least one other non-whitespace
6372 * character.)
6373 */
6374 p.set(new_line_p);
6375 if (p.getch() == '}' || p.getch() == ';')
6376 {
6377 /* skip trailing whitespace */
6378 for (p.inc() ; is_space(p.getch()) ; p.inc()) ;
6379
6380 /*
6381 * if there's nothing else on the line, presume it's an
6382 * unterminated string
6383 */
6384 if (p.getch() == '\0')
6385 {
6386 /* log the error */
6387 log_error(TCERR_POSSIBLE_UNTERM_STR,
6388 appended_linenum_);
6389
6390 /* remember that it's unterminated */
6391 unterm = (char)in_quote;
6392
6393 /*
6394 * since we're adding a presumed close quote that never
6395 * appears in the text, we need to figure the new
6396 * in-string status for the line; clear the in-quote
6397 * flag, and re-scan comments from the current point on
6398 * the line
6399 */
6400 in_quote_ = '\0';
6401 process_comments(new_line_p - linebuf_.get_buf());
6402
6403 /* we're done - unsplice from the start of the new line */
6404 p.set(new_line_p);
6405 goto done;
6406 }
6407 }
6408
6409 /* scan for the end of the string */
6410 for (p.set(new_line_p) ; ; p.inc())
6411 {
6412 /* get this character */
6413 wchar_t cur = p.getch();
6414
6415 /* see what we have */
6416 if (cur == '\\')
6417 {
6418 /* it's a backslash sequence - skip the extra character */
6419 p.inc();
6420
6421 /*
6422 * in a triple-quoted string, a backslash escapes a whole
6423 * run of consecutive quote characters
6424 */
6425 if (in_triple && p.getch() == in_quote)
6426 {
6427 /* skip all but the last consecutive quote */
6428 int qcnt = count_quotes(&p, in_quote);
6429 p.inc_by(qcnt - 1);
6430 }
6431 else if (p.getch() == '<')
6432 {
6433 /* skip a run of <'s */
6434 for ( ; p.getch() == '<' ; p.inc()) ;
6435 }
6436 }
6437 else if (cur == in_quote)
6438 {
6439 /* it's our quote character - check for triple quotes */
6440 if (in_triple)
6441 {
6442 /* in a triple-quoted string - we need 3+ to end it */
6443 int qcnt = count_quotes(&p, cur);
6444 if (qcnt >= 3)
6445 {
6446 /* we have at least 3 - skip them and exit */
6447 p.inc_by(qcnt);
6448 goto done;
6449 }
6450 }
6451 else
6452 {
6453 /* regular string - skip it and exit the string */
6454 p.inc();
6455 goto done;
6456 }
6457 }
6458 else if (cur == '<' && p.getch_at(1) == '<')
6459 {
6460 /*
6461 * it's an embedded expression starter - skip the '<<'
6462 * sequence and stop scanning
6463 */
6464 p.inc();
6465 p.inc();
6466
6467 /* check for a '%' sprintf code */
6468 if (p.getch() == '%')
6469 scan_sprintf_spec(&p);
6470
6471 /* done */
6472 goto done;
6473 }
6474 else if (cur == '\0')
6475 {
6476 /* end of line - go back and splice another line */
6477 break;
6478 }
6479 }
6480 }
6481
6482 done:
6483 /* if we actually spliced anything, unsplice it at the current point */
6484 if (p.getptr() != 0)
6485 unsplice_line(p.getptr());
6486
6487 /* if we found an unterminated string, supply implicit termination */
6488 if (unterm != '\0')
6489 linebuf_.append(&unterm, 1);
6490 }
6491
6492
6493 /* ------------------------------------------------------------------------ */
6494 /*
6495 * Process a #pragma directive
6496 */
6497 void CTcTokenizer::pp_pragma()
6498 {
6499 struct pp_kw_def
6500 {
6501 const char *kw;
6502 void (CTcTokenizer::*func)();
6503 };
6504 static pp_kw_def kwlist[] =
6505 {
6506 // { "c", &CTcTokenizer::pragma_c }, -- obsolete
6507 { "once", &CTcTokenizer::pragma_once },
6508 { "all_once", &CTcTokenizer::pragma_all_once },
6509 { "message", &CTcTokenizer::pragma_message },
6510 { "newline_spacing", &CTcTokenizer::pragma_newline_spacing },
6511 { "sourceTextGroup", &CTcTokenizer::pragma_source_text_group },
6512 { 0, 0 }
6513 };
6514 pp_kw_def *kwp;
6515 size_t kwlen;
6516
6517 /* get the pragma keyword */
6518 if (next_on_line() != TOKT_SYM)
6519 {
6520 log_warning(TCERR_UNKNOWN_PRAGMA,
6521 (int)curtok_.get_text_len(), curtok_.get_text());
6522 return;
6523 }
6524
6525 /* get the keyword length */
6526 kwlen = curtok_.get_text_len();
6527
6528 /* scan the pragma list */
6529 for (kwp = kwlist ; kwp->kw != 0 ; ++kwp)
6530 {
6531 /* is this our keyword? */
6532 if (strlen(kwp->kw) == kwlen
6533 && memicmp(curtok_.get_text(), kwp->kw, kwlen) == 0)
6534 {
6535 /* this is our keyword - invoke the handler */
6536 (this->*(kwp->func))();
6537
6538 /* we're done */
6539 return;
6540 }
6541 }
6542
6543 /* we didn't find it - generate a warning */
6544 log_warning(TCERR_UNKNOWN_PRAGMA, kwlen, curtok_.get_text());
6545 }
6546
6547 #if 0 // #pragma C is not currently used
6548 /*
6549 * Process a #pragma C directive
6550 */
6551 void CTcTokenizer::pragma_c()
6552 {
6553 tc_toktyp_t tok;
6554 int new_pragma_c;
6555
6556 /* get the next token */
6557 tok = next_on_line();
6558
6559 /*
6560 * "+" or empty (end of line or whitespace) indicates C mode; "-"
6561 * indicates standard mode
6562 */
6563 if (tok == TOKT_PLUS || tok == TOKT_EOF)
6564 new_pragma_c = TRUE;
6565 else if (tok == TOKT_MINUS)
6566 new_pragma_c = FALSE;
6567 else
6568 {
6569 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6570 new_pragma_c = str_->is_pragma_c();
6571 }
6572
6573 /*
6574 * retain the pragma in the result if we're in preprocess-only mode,
6575 * otherwise remove it
6576 */
6577 if (!pp_only_mode_)
6578 clear_linebuf();
6579
6580 /* set the mode in the stream */
6581 str_->set_pragma_c(new_pragma_c);
6582
6583 /* if there's a parser, notify it of the change */
6584 if (G_prs != 0)
6585 G_prs->set_pragma_c(new_pragma_c);
6586 }
6587 #endif
6588
6589 /*
6590 * Process a #pragma once directive
6591 */
6592 void CTcTokenizer::pragma_once()
6593 {
6594 /* add this file to the ONCE list */
6595 add_include_once(str_->get_desc()->get_fname());
6596
6597 /* don't retain this pragma in the result */
6598 clear_linebuf();
6599 }
6600
6601 /*
6602 * Process a #pragma all_once directive
6603 */
6604 void CTcTokenizer::pragma_all_once()
6605 {
6606 tc_toktyp_t tok;
6607
6608 /* get the next token */
6609 tok = next_on_line();
6610
6611 /*
6612 * "+" or empty (end of line or whitespace) indicates ALL_ONCE mode;
6613 * '-' indicates standard mode
6614 */
6615 if (tok == TOKT_PLUS || tok == TOKT_EOF)
6616 all_once_ = TRUE;
6617 else if (tok == TOKT_MINUS)
6618 all_once_ = FALSE;
6619 else
6620 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6621
6622 /* don't retain this pragma in the result */
6623 clear_linebuf();
6624 }
6625
6626 /*
6627 * Process a #pragma message directive
6628 */
6629 void CTcTokenizer::pragma_message()
6630 {
6631 size_t startofs;
6632
6633 /*
6634 * copy the source line through the "message" token to the macro
6635 * expansion buffer - we don't want to expand that part, but we want
6636 * it to appear in the expansion, so just copy the original
6637 */
6638 startofs = (curtok_.get_text() + curtok_.get_text_len()
6639 - linebuf_.get_text());
6640 expbuf_.copy(linebuf_.get_text(), startofs);
6641
6642 /* expand macros; don't allow reading additional lines */
6643 if (expand_macros_curline(FALSE, FALSE, TRUE))
6644 {
6645 clear_linebuf();
6646 return;
6647 }
6648
6649 /*
6650 * If we're in normal compilation mode, display the message. If we're
6651 * in preprocess-only mode, simply retain the message in the
6652 * preprocessed result, so that it shows up when the result is
6653 * compiled.
6654 *
6655 * Ignore messages in list-includes mode.
6656 */
6657 if (!pp_only_mode_ && !list_includes_mode_)
6658 {
6659 /* set up at the first post-processed token */
6660 start_new_line(&expbuf_, startofs);
6661
6662 /* if there's an open paren, skip it */
6663 if (next_on_line_xlat(0) == TOKT_LPAR)
6664 next_on_line_xlat(0);
6665 else
6666 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6667
6668 /* keep going until we reach the closing paren */
6669 while (curtok_.gettyp() != TOKT_RPAR
6670 && curtok_.gettyp() != TOKT_EOF)
6671 {
6672 /* display this token */
6673 switch(curtok_.gettyp())
6674 {
6675 case TOKT_SSTR:
6676 case TOKT_DSTR:
6677 case TOKT_SYM:
6678 /* display the text of the token */
6679 msg_str(curtok_.get_text(), curtok_.get_text_len());
6680 break;
6681
6682 case TOKT_INT:
6683 /* display the integer */
6684 msg_long(curtok_.get_int_val());
6685 break;
6686
6687 default:
6688 /* ignore anything else */
6689 break;
6690 }
6691
6692 /* get the next token */
6693 next_on_line_xlat(0);
6694 }
6695
6696 /* end the line */
6697 msg_str("\n", 1);
6698
6699 /* remove the message from the result text */
6700 clear_linebuf();
6701 }
6702 else
6703 {
6704 /* preprocessing - copy expanded text to line buffer */
6705 linebuf_.copy(expbuf_.get_text(), expbuf_.get_text_len());
6706 }
6707 }
6708
6709 /*
6710 * Process a #pragma newline_spacing(on/off) directive
6711 */
6712 void CTcTokenizer::pragma_newline_spacing()
6713 {
6714 newline_spacing_mode_t f;
6715
6716 /* if we're in preprocess-only mode, just pass the pragma through */
6717 if (pp_only_mode_)
6718 return;
6719
6720 /* get the '(' token and the on/off token */
6721 if (next_on_line() != TOKT_LPAR || next_on_line() != TOKT_SYM)
6722 {
6723 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6724 goto done;
6725 }
6726
6727 /* note the new mode flag */
6728 if (curtok_.get_text_len() == 2
6729 && memcmp(curtok_.get_text(), "on", 2) == 0)
6730 {
6731 /* 'on' - this is the old version of 'collapse' */
6732 f = NEWLINE_SPACING_COLLAPSE;
6733 }
6734 else if (curtok_.get_text_len() == 8
6735 && memcmp(curtok_.get_text(), "collapse", 8) == 0)
6736 {
6737 f = NEWLINE_SPACING_COLLAPSE;
6738 }
6739 else if (curtok_.get_text_len() == 3
6740 && memcmp(curtok_.get_text(), "off", 3) == 0)
6741 {
6742 /* 'off' - the old version of 'delete' */
6743 f = NEWLINE_SPACING_DELETE;
6744 }
6745 else if (curtok_.get_text_len() == 6
6746 && memcmp(curtok_.get_text(), "delete", 6) == 0)
6747 {
6748 f = NEWLINE_SPACING_DELETE;
6749 }
6750 else if (curtok_.get_text_len() == 8
6751 && memcmp(curtok_.get_text(), "preserve", 8) == 0)
6752 {
6753 f = NEWLINE_SPACING_PRESERVE;
6754 }
6755 else
6756 {
6757 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6758 goto done;
6759 }
6760
6761 /* make sure we have the ')' token */
6762 if (next_on_line() != TOKT_RPAR)
6763 {
6764 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6765 goto done;
6766 }
6767
6768 /* set the new mode */
6769 string_newline_spacing_ = f;
6770
6771 done:
6772 /* done - discard this line buffer */
6773 clear_linebuf();
6774 }
6775
6776
6777 /*
6778 * Process a #pragma sourceTextGroup(on/off) directive
6779 */
6780 void CTcTokenizer::pragma_source_text_group()
6781 {
6782 tc_toktyp_t tok;
6783 int f;
6784
6785 /* if we're in preprocess-only mode, just pass the pragma through */
6786 if (pp_only_mode_)
6787 return;
6788
6789 /* get the '(' token and the on/off token, if present */
6790 if ((tok = next_on_line()) == TOKT_EOF)
6791 {
6792 /* no on/off - by default it's on */
6793 f = TRUE;
6794 }
6795 else if (tok == TOKT_LPAR && next_on_line() == TOKT_SYM)
6796 {
6797 /* get the on/off mode */
6798 if (curtok_.get_text_len() == 2
6799 && memcmp(curtok_.get_text(), "on", 2) == 0)
6800 {
6801 /* it's 'on' */
6802 f = TRUE;
6803 }
6804 else if (curtok_.get_text_len() == 3
6805 && memcmp(curtok_.get_text(), "off", 3) == 0)
6806 {
6807 /* it's 'off' */
6808 f = FALSE;
6809 }
6810 else
6811 {
6812 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6813 goto done;
6814 }
6815
6816 /* make sure we have the ')' token */
6817 if (next_on_line() != TOKT_RPAR)
6818 {
6819 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6820 goto done;
6821 }
6822 }
6823 else
6824 {
6825 /* anything else is invalid syntax */
6826 log_warning(TCERR_BAD_PRAGMA_SYNTAX);
6827 goto done;
6828 }
6829
6830 /* set the new mode in the parser */
6831 G_prs->set_source_text_group_mode(f);
6832
6833 done:
6834 /* done - discard this line buffer */
6835 clear_linebuf();
6836 }
6837
6838
6839 /* ------------------------------------------------------------------------ */
6840 /*
6841 * Process a #charset directive
6842 */
6843 void CTcTokenizer::pp_charset()
6844 {
6845 /*
6846 * Encountering a #charset directive within the tokenizer is always
6847 * an error. If the file opener managed to use a #charset, we'll
6848 * never see it, because the file opener will have skipped it before
6849 * giving us the file.
6850 *
6851 * If we flagged a #charset error when opening the file, indicate
6852 * that the problem is that the character set given was unloadable;
6853 * otherwise, the problem is that #charset is in the wrong place.
6854 */
6855 log_error(str_ != 0 && str_->get_charset_error()
6856 ? TCERR_CANT_LOAD_CHARSET : TCERR_UNEXPECTED_CHARSET);
6857
6858 /* don't retain this pragma in the result */
6859 clear_linebuf();
6860 }
6861
6862 /* ------------------------------------------------------------------------ */
6863 /*
6864 * Process a #include directive
6865 */
6866 void CTcTokenizer::pp_include()
6867 {
6868 wchar_t match;
6869 int is_local;
6870 int is_absolute;
6871 utf8_ptr fname;
6872 CTcSrcFile *new_src;
6873 int charset_error;
6874 int default_charset_error;
6875 char full_name[OSFNMAX];
6876 char lcl_name[OSFNMAX];
6877 int found;
6878 CTcTokFileDesc *desc;
6879 int expand;
6880 utf8_ptr start;
6881
6882 /* presume we'll expand macros */
6883 expand = TRUE;
6884
6885 /*
6886 * Check to see if expansion is needed. Macro expansion is needed
6887 * only if the source line is not of one of the following forms:
6888 *
6889 *. #include "filename"
6890 *. #include <filename>
6891 */
6892 for (start = p_ ; is_space(p_.getch()) ; p_.inc()) ;
6893 switch(p_.getch())
6894 {
6895 case '<':
6896 /* look for a matching '>' */
6897 match = '>';
6898 goto find_match;
6899
6900 case '"':
6901 /* look for a matching '"' */
6902 match = '"';
6903 goto find_match;
6904
6905 find_match:
6906 /* find the matching character */
6907 for (p_.inc() ; p_.getch() != '\0' && p_.getch() != match ;
6908 p_.inc()) ;
6909
6910 /* if we found it, check for other characters on the line */
6911 if (p_.getch() == match)
6912 {
6913 /* skip the matching character */
6914 p_.inc();
6915
6916 /* skip whitespace */
6917 while (is_space(p_.getch()))
6918 p_.inc();
6919
6920 /*
6921 * make sure there's nothing else on the line - if not, it's
6922 * one of the approved formats, so there's no need to do
6923 * macro expansion
6924 */
6925 if (p_.getch() == 0)
6926 expand = FALSE;
6927 }
6928 break;
6929 }
6930
6931 /* go back to read from the original starting point */
6932 p_ = start;
6933
6934 /* expand macros if necessary */
6935 if (expand)
6936 {
6937 /* do the expansion */
6938 if (expand_macros_curline(FALSE, FALSE, FALSE))
6939 {
6940 /* clear the buffer and abort */
6941 clear_linebuf();
6942 return;
6943 }
6944
6945 /*
6946 * remove any expansion flags, so that we don't have to worry about
6947 * parsing or skipping them
6948 */
6949 remove_expansion_flags(&expbuf_);
6950
6951 /* read from the expansion buffer */
6952 start_new_line(&expbuf_, 0);
6953 }
6954
6955 /* skip leading whitespace */
6956 for ( ; is_space(p_.getch()) ; p_.inc()) ;
6957
6958 /* we have to be looking at at '"' or '<' character */
6959 if (p_.getch() == '"')
6960 {
6961 /* look for a matching quote, and look for a local file */
6962 match = '"';
6963 is_local = TRUE;
6964 }
6965 else if (p_.getch() == '<')
6966 {
6967 /* look for a matching angle bracket, and look for a system file */
6968 match = '>';
6969 is_local = FALSE;
6970 }
6971 else
6972 {
6973 /* invalid syntax - log an error and ignore the line */
6974 log_error(TCERR_BAD_INC_SYNTAX);
6975 clear_linebuf();
6976 return;
6977 }
6978
6979 /* skip the open quote, and remember where the filename starts */
6980 p_.inc();
6981 fname = p_;
6982
6983 /* find the matching quote */
6984 for ( ; p_.getch() != '\0' && p_.getch() != match ; p_.inc()) ;
6985
6986 /* if we didn't find the match, log an error and ignore the line */
6987 if (p_.getch() == '\0')
6988 {
6989 log_error(TCERR_BAD_INC_SYNTAX);
6990 clear_linebuf();
6991 return;
6992 }
6993 else
6994 {
6995 /*
6996 * We found the close quote. Before we parse the filename, make
6997 * one last check: if there's anything further on the line apart
6998 * from whitespace, it's extraneous, so issue a warning.
6999 */
7000
7001 /* remember where the close quote is */
7002 utf8_ptr closep = p_;
7003
7004 /* skip it, and then skip any trailing whitespace */
7005 for (p_.inc() ; is_space(p_.getch()) ; p_.inc()) ;
7006
7007 /* if we're not at the end of the line, issue a warning */
7008 if (p_.getch() != '\0')
7009 log_warning(TCERR_EXTRA_INC_SYNTAX);
7010
7011 /*
7012 * Null-terminate the filename. (We know there's nothing else
7013 * interesting in the buffer after the filename at this point, so
7014 * we don't care about overwriting the quote or anything that might
7015 * come after it.)
7016 */
7017 closep.setch('\0');
7018 }
7019
7020 /* check to see if the filename is absolute */
7021 is_absolute = os_is_file_absolute(fname.getptr());
7022
7023 /* we have yet to find the file */
7024 found = FALSE;
7025
7026 /*
7027 * in case the name is in portable URL notation, convert from URL
7028 * notation to local notation; we'll consider this form of the name
7029 * first, and only if we can't find it in this form will we try
7030 * treating the name as using local filename conventions
7031 */
7032 os_cvt_url_dir(lcl_name, sizeof(lcl_name), fname.getptr());
7033
7034 /*
7035 * Search for the included file.
7036 *
7037 * First, if it's a local file (in quotes rather than angle
7038 * brackets), start the search in the directory containing the
7039 * current file, then look in the directory containing the parent
7040 * file, and so on. If we fail to find it, proceed as for a
7041 * non-local file.
7042 */
7043 if (is_local && last_desc_ != 0)
7044 {
7045 CTcTokStream *cur_str;
7046 char pathbuf[OSFNMAX];
7047
7048 /* start with the current file, and search parents */
7049 for (cur_str = str_ ; cur_str != 0 ; cur_str = cur_str->get_parent())
7050 {
7051 /* get the path to the current file */
7052 os_get_path_name(pathbuf, sizeof(pathbuf),
7053 last_desc_->get_fname());
7054
7055 /*
7056 * try the URL-converted name first - this takes precedence
7057 * over a local interpretation of the name
7058 */
7059 os_build_full_path(full_name, sizeof(full_name),
7060 pathbuf, lcl_name);
7061 if (!osfacc(full_name))
7062 {
7063 found = TRUE;
7064 break;
7065 }
7066
7067 /* if it's a relative local name, try again with local naming */
7068 if (!is_absolute)
7069 {
7070 /*
7071 * build the full filename, treating the name as using
7072 * local system conventions
7073 */
7074 os_build_full_path(full_name, sizeof(full_name),
7075 pathbuf, fname.getptr());
7076
7077 /* if we found it, so note and stop searching */
7078 if (!osfacc(full_name))
7079 {
7080 found = TRUE;
7081 break;
7082 }
7083 }
7084 }
7085 }
7086
7087 /*
7088 * If we still haven't found the file (or if it's a non-local file,
7089 * in angle brackets), search the include path.
7090 */
7091 if (!found)
7092 {
7093 tctok_incpath_t *inc_path;
7094
7095 /* scan the include path */
7096 for (inc_path = incpath_head_ ; inc_path != 0 ;
7097 inc_path = inc_path->nxt)
7098 {
7099 /* try the URL-converted local name first */
7100 os_build_full_path(full_name, sizeof(full_name),
7101 inc_path->path, lcl_name);
7102 if (!osfacc(full_name))
7103 {
7104 found = TRUE;
7105 break;
7106 }
7107
7108 /* try with the local name, if it's a relative local name */
7109 if (!is_absolute)
7110 {
7111 /* build the full name for the file in this directory */
7112 os_build_full_path(full_name, sizeof(full_name),
7113 inc_path->path, fname.getptr());
7114
7115 /* if we found it, stop searching */
7116 if (!osfacc(full_name))
7117 {
7118 found = TRUE;
7119 break;
7120 }
7121 }
7122 }
7123 }
7124
7125 /*
7126 * If the filename specified an absolute path, and we didn't find a
7127 * file with any of the local interpretations, look at the absolute
7128 * path. Note that our portable URL-style notation doesn't allow
7129 * absolute notation, so we use only the exact name as specified in
7130 * the #include directive as the absolute form.
7131 */
7132 if (is_absolute && !found)
7133 {
7134 /* use the original filename as the full name */
7135 strcpy(full_name, fname.getptr());
7136
7137 /* try finding the file */
7138 found = !osfacc(full_name);
7139 }
7140
7141 /*
7142 * we have our copy of the filename now; we don't want to retain
7143 * this directive in the preprocessed source, so clear out the line
7144 * buffer now
7145 */
7146 clear_linebuf();
7147
7148 /*
7149 * if we didn't find the file anywhere, show an error and ignore the
7150 * #include directive
7151 */
7152 if (!found)
7153 {
7154 log_error(TCERR_INC_NOT_FOUND,
7155 (int)strlen(fname.getptr()), fname.getptr());
7156 return;
7157 }
7158
7159 /*
7160 * Check the list of included files that are marked for inclusion
7161 * only once. If we've already included this file, ignore this
7162 * redundant inclusion. Check based on the full filename that we
7163 * resolved from the search path.
7164 */
7165 if (find_include_once(full_name))
7166 {
7167 /* log an error if appropriate */
7168 if (warn_on_ignore_incl_)
7169 log_warning(TCERR_REDUNDANT_INCLUDE,
7170 (int)strlen(full_name), full_name);
7171
7172 /* ignore this #include directive */
7173 return;
7174 }
7175
7176 /* open a file source to read the file */
7177 new_src = CTcSrcFile::open_source(full_name, res_loader_,
7178 default_charset_, &charset_error,
7179 &default_charset_error);
7180
7181 /* if we couldn't open the file, log an error and ignore the line */
7182 if (new_src == 0)
7183 {
7184 /*
7185 * if the error was due to the default character set, log that
7186 * problem; otherwise, log the general file-open problem
7187 */
7188 if (default_charset_error)
7189 log_error(TCERR_CANT_LOAD_DEFAULT_CHARSET, default_charset_);
7190 else
7191 log_error(TCERR_INC_NOT_FOUND,
7192 (int)strlen(full_name), full_name);
7193
7194 /* we can go no further */
7195 return;
7196 }
7197
7198 /* get the descriptor for the source file */
7199 desc = get_file_desc(full_name, strlen(full_name), FALSE,
7200 fname.getptr(),
7201 fname.getptr() != 0 ? strlen(fname.getptr()) : 0);
7202
7203 /*
7204 * remember the current #pragma newline_spacing mode, so we can restore
7205 * it when we reinstate the current stream
7206 */
7207 str_->set_newline_spacing(string_newline_spacing_);
7208
7209 /*
7210 * Create and install the new file reader stream object. By
7211 * installing it as the current reader, we'll activate it so that
7212 * the next line read will come from the new stream. Note that the
7213 * current stream becomes the parent of the new stream, so that we
7214 * revert to the current stream when the new stream is exhausted;
7215 * this will allow us to pick up reading from the current stream at
7216 * the next line after the #include directive when we've finished
7217 * including the new file.
7218 */
7219 str_ = new CTcTokStream(desc, new_src, str_, charset_error, if_sp_);
7220
7221 /*
7222 * If we're in ALL_ONCE mode, it means that every single file we
7223 * include should be included only once.
7224 */
7225 if (all_once_)
7226 add_include_once(full_name);
7227
7228 /*
7229 * if we're in list-includes mode, write the name of the include file
7230 * to the standard output
7231 */
7232 if (list_includes_mode_)
7233 G_hostifc->print_msg("#include %s\n", full_name);
7234 }
7235
7236 /* ------------------------------------------------------------------------ */
7237 /*
7238 * Add a file to the include-once list. Once a file is in this list, we
7239 * won't include it again.
7240 */
7241 void CTcTokenizer::add_include_once(const char *fname)
7242 {
7243 tctok_incfile_t *prvinc;
7244
7245 /* if the file is already in the list, don't add it again */
7246 if (find_include_once(fname))
7247 return;
7248
7249 /* create a new entry for the filename */
7250 prvinc = (tctok_incfile_t *)t3malloc(sizeof(tctok_incfile_t)
7251 + strlen(fname));
7252
7253 /* save the filename */
7254 strcpy(prvinc->fname, fname);
7255
7256 /* link the new entry into our list */
7257 prvinc->nxt = prev_includes_;
7258 prev_includes_ = prvinc;
7259 }
7260
7261 /*
7262 * Find a file in the list of files to be included only once. Returns
7263 * true if the file is in the list, false if not.
7264 */
7265 int CTcTokenizer::find_include_once(const char *fname)
7266 {
7267 tctok_incfile_t *prvinc;
7268
7269 /* search the list */
7270 for (prvinc = prev_includes_ ; prvinc != 0 ; prvinc = prvinc->nxt)
7271 {
7272 /* if this one matches, we found it, so return true */
7273 if (os_file_names_equal(fname, prvinc->fname))
7274 return TRUE;
7275 }
7276
7277 /* we didn't find the file */
7278 return FALSE;
7279 }
7280
7281 /* ------------------------------------------------------------------------ */
7282 /*
7283 * Process a #define directive
7284 */
7285 void CTcTokenizer::pp_define()
7286 {
7287 const char *macro_name;
7288 size_t macro_len;
7289 const char *argv[TOK_MAX_MACRO_ARGS];
7290 size_t argvlen[TOK_MAX_MACRO_ARGS];
7291 int argc;
7292 int has_args;
7293 const char *expan;
7294 size_t expan_len;
7295 CTcHashEntryPp *entry, *old_entry;
7296 int has_varargs;
7297
7298 /* get the macro name */
7299 if (next_on_line() != TOKT_SYM)
7300 {
7301 log_error(TCERR_BAD_DEFINE_SYM,
7302 (int)curtok_.get_text_len(), curtok_.get_text());
7303 clear_linebuf();
7304 return;
7305 }
7306
7307 /* make a copy of the macro name */
7308 macro_name = curtok_.get_text();
7309 macro_len = curtok_.get_text_len();
7310
7311 /* no arguments yet */
7312 argc = 0;
7313
7314 /* presume we won't find a varargs marker */
7315 has_varargs = FALSE;
7316
7317 /*
7318 * If there's a '(' immediately after the macro name, without any
7319 * intervening whitespace, it has arguments; otherwise, it has no
7320 * arguments. Note which case we have.
7321 */
7322 if (p_.getch() == '(')
7323 {
7324 int done;
7325 tc_toktyp_t tok;
7326
7327 /* note that we have an argument list */
7328 has_args = TRUE;
7329
7330 /* assume we're not done yet */
7331 done = FALSE;
7332
7333 /* skip the paren and get the next token */
7334 p_.inc();
7335 tok = next_on_line();
7336
7337 /* check for an empty argument list */
7338 if (tok == TOKT_RPAR)
7339 {
7340 /* note that we're done with the arguments */
7341 done = TRUE;
7342 }
7343
7344 /* scan the argument list */
7345 while (!done)
7346 {
7347 /* if we have too many arguments, it's an error */
7348 if (argc >= TOK_MAX_MACRO_ARGS)
7349 {
7350 log_error(TCERR_TOO_MANY_MAC_PARMS,
7351 macro_name, macro_len, TOK_MAX_MACRO_ARGS);
7352 clear_linebuf();
7353 return;
7354 }
7355
7356 /* if we're at the end of the macro, it's an error */
7357 if (tok == TOKT_EOF)
7358 {
7359 /* log the error and ignore the line */
7360 log_error(TCERR_MACRO_NO_RPAR);
7361 clear_linebuf();
7362 return;
7363 }
7364
7365 /* check for a valid initial symbol character */
7366 if (tok != TOKT_SYM)
7367 {
7368 log_error_curtok(TCERR_BAD_MACRO_ARG_NAME);
7369 clear_linebuf();
7370 return;
7371 }
7372
7373 /* remember the argument name */
7374 argvlen[argc] = curtok_.get_text_len();
7375 argv[argc++] = curtok_.get_text();
7376
7377 /* get the next token */
7378 tok = next_on_line();
7379
7380 /* make sure we have a comma or paren following */
7381 if (tok == TOKT_COMMA)
7382 {
7383 /* we have more arguments - skip the comma */
7384 tok = next_on_line();
7385 }
7386 else if (tok == TOKT_ELLIPSIS)
7387 {
7388 /* skip the ellipsis */
7389 tok = next_on_line();
7390
7391 /* note the varargs marker */
7392 has_varargs = TRUE;
7393
7394 /* this must be the last argument */
7395 if (tok != TOKT_RPAR)
7396 {
7397 /* log the error */
7398 log_error_curtok(TCERR_MACRO_ELLIPSIS_REQ_RPAR);
7399
7400 /* discard the line and give up */
7401 clear_linebuf();
7402 return;
7403 }
7404
7405 /* that's the last argument - we can stop now */
7406 done = TRUE;
7407 }
7408 else if (tok == TOKT_RPAR)
7409 {
7410 /* no more arguments - note that we can stop now */
7411 done = TRUE;
7412 }
7413 else
7414 {
7415 /* invalid argument - log an error and discard the line */
7416 log_error_curtok(TCERR_MACRO_EXP_COMMA);
7417 clear_linebuf();
7418 return;
7419 }
7420 }
7421 }
7422 else
7423 {
7424 /*
7425 * there are no arguments - the macro's expansion starts
7426 * immediately after the end of the name and any subsequent
7427 * whitespace
7428 */
7429 has_args = FALSE;
7430 }
7431
7432 /* skip whitespace leading up to the expansion */
7433 while (is_space(p_.getch()))
7434 p_.inc();
7435
7436 /* the rest of the line is the expansion */
7437 expan = p_.getptr();
7438
7439 /* don't allow defining "defined" */
7440 if (macro_len == 7 && memcmp(macro_name, "defined", 7) == 0)
7441 {
7442 /* log an error */
7443 log_error(TCERR_REDEF_OP_DEFINED);
7444
7445 /* don't retain the directive in the preprocessed result */
7446 clear_linebuf();
7447
7448 /* ignore the definition */
7449 return;
7450 }
7451
7452 /* get the length of the expansion text */
7453 expan_len = strlen(expan);
7454
7455 /*
7456 * remove any trailing whitespace from the expansion text; however,
7457 * leave a trailing space if it's preceded by a backslash
7458 */
7459 while (expan_len > 0
7460 && is_space(expan[expan_len-1])
7461 && !(expan_len > 1 && expan[expan_len-2] == '\\'))
7462 --expan_len;
7463
7464 /* create an entry for the new macro */
7465 entry = new CTcHashEntryPpDefine(macro_name, macro_len, TRUE,
7466 has_args, argc, has_varargs,
7467 argv, argvlen, expan, expan_len);
7468
7469 /*
7470 * Check the symbol table to see if this symbol is already defined with
7471 * a different expansion. If so, show a warning, but honor the new
7472 * definition.
7473 */
7474 old_entry = find_define(macro_name, macro_len);
7475 if (old_entry != 0)
7476 {
7477 /*
7478 * Check for a trivial redefinition - if the number of arguments is
7479 * the same, and the type (object-like or function-like) is the
7480 * same, and the expansion string is identical, there's no need to
7481 * warn, because the redefinition has no effect and can thus be
7482 * safely ignored. Note that we must ignore any differences in the
7483 * whitespace in the expansions for this comparision.
7484 *
7485 * Compare the *parsed* versions of the expansions. This ensures
7486 * that we take into account changes to parameter names. For
7487 * example, the following two macros are equivalent, even though
7488 * their unparsed source texts are different, because they'd still
7489 * have identical expansions for any given parameter value:
7490 *
7491 *. #define A(x) x
7492 *. #define A(y) y
7493 *
7494 * Likewise, the following two macros are NOT equivalent, even
7495 * though their unparsed source texts are identical, because they
7496 * could have different expansions for a given parameter value:
7497 *
7498 *. #define A(x) x
7499 *. #define A(y) x
7500 */
7501 if ((old_entry->has_args() != 0) == (has_args != 0)
7502 && old_entry->get_argc() == argc
7503 && lib_strequal_collapse_spaces(entry->get_expansion(),
7504 entry->get_expan_len(),
7505 old_entry->get_expansion(),
7506 old_entry->get_expan_len()))
7507 {
7508 /* it's a non-trivial redefinition - ignore it */
7509 delete entry;
7510 goto done;
7511 }
7512
7513 /* log a warning about the redefinition */
7514 log_warning(TCERR_MACRO_REDEF, (int)macro_len, macro_name);
7515
7516 /* remove and delete the old entry */
7517 defines_->remove(old_entry);
7518
7519 /* if the item isn't already in the #undef table, add it */
7520 if (find_undef(macro_name, macro_len) == 0)
7521 {
7522 /*
7523 * move the entry to the #undef table so that we can keep track
7524 * of the fact that this macro's definition has changed in the
7525 * course of the compilation
7526 */
7527 undefs_->add(old_entry);
7528 }
7529 else
7530 {
7531 /*
7532 * the name is already in the #undef table, so we don't need
7533 * another copy - just forget about the old entry entirely
7534 */
7535 delete old_entry;
7536 }
7537 }
7538
7539 /* add it to the hash table */
7540 defines_->add(entry);
7541
7542 done:
7543 /* don't retain the directive in the preprocessed source */
7544 clear_linebuf();
7545 }
7546
7547
7548 /* ------------------------------------------------------------------------ */
7549 /*
7550 * Process a #ifdef directive
7551 */
7552 void CTcTokenizer::pp_ifdef()
7553 {
7554 /* process the ifdef/ifndef with a positive sense */
7555 pp_ifdef_or_ifndef(TRUE);
7556 }
7557
7558 /*
7559 * Process a #ifndef directive
7560 */
7561 void CTcTokenizer::pp_ifndef()
7562 {
7563 /* process the ifdef/ifndef with a negative sense */
7564 pp_ifdef_or_ifndef(FALSE);
7565 }
7566
7567 /*
7568 * Process a #ifdef or #ifndef. If 'sense' is true, we'll take the
7569 * branch if the symbol is defined (hence #ifdef), otherwise we'll take
7570 * it if the symbol isn't defined (hence #ifndef).
7571 */
7572 void CTcTokenizer::pp_ifdef_or_ifndef(int sense)
7573 {
7574 char macro_name[TOK_SYM_MAX_BUFFER];
7575 int found;
7576 tok_if_t state;
7577
7578 /* make sure we have a valid symbol */
7579 if (pp_get_lone_ident(macro_name, sizeof(macro_name)))
7580 {
7581 /* clear the line buffer */
7582 clear_linebuf();
7583
7584 /*
7585 * push a true if to avoid cascading errors for matching #endif
7586 * or #else
7587 */
7588 push_if(TOKIF_IF_YES);
7589
7590 /* we're done */
7591 return;
7592 }
7593
7594 /* check to see if it's defined */
7595 found = (find_define(macro_name, strlen(macro_name)) != 0);
7596
7597 /*
7598 * if we found it and they wanted it found, or we didn't find it and
7599 * they didn't want it found, take a true branch; otherwise, take a
7600 * false branch
7601 */
7602 if ((sense != 0) == (found != 0))
7603 state = TOKIF_IF_YES;
7604 else
7605 state = TOKIF_IF_NO;
7606
7607 /* push the new #if state */
7608 push_if(state);
7609
7610 /* don't retain the directive in the preprocessed source */
7611 clear_linebuf();
7612 }
7613
7614 /* ------------------------------------------------------------------------ */
7615 /*
7616 * Process a #if directive
7617 */
7618 void CTcTokenizer::pp_if()
7619 {
7620 CTcConstVal val;
7621
7622 /* expand macros; don't allow reading additional lines */
7623 if (expand_macros_curline(FALSE, TRUE, FALSE))
7624 goto do_error;
7625
7626 /*
7627 * we don't need the original source line any more, and we don't
7628 * want to copy it to the preprocessed output, so clear it
7629 */
7630 clear_linebuf();
7631
7632 /* parse out of the expansion buffer */
7633 start_new_line(&expbuf_, 0);
7634
7635 /* parse the preprocessor expression */
7636 if (pp_parse_expr(&val, TRUE, TRUE, TRUE))
7637 {
7638 /*
7639 * we can't get a value; treat the expression as true and
7640 * continue parsing, so that we don't throw off the #if nesting
7641 * level
7642 */
7643 val.set_bool(TRUE);
7644 }
7645
7646 /* push the new state according to the value of the expression */
7647 push_if(val.get_val_bool() ? TOKIF_IF_YES : TOKIF_IF_NO);
7648
7649 /* done */
7650 return;
7651
7652 do_error:
7653 /* clear the line buffer */
7654 clear_linebuf();
7655
7656 /*
7657 * push a true if - even though we can't evaluate the condition, we
7658 * can at least avoid a cascade of errors for the matching #endif
7659 * and #else
7660 */
7661 push_if(TOKIF_IF_YES);
7662 }
7663
7664 /* ------------------------------------------------------------------------ */
7665 /*
7666 * Process a #elif directive
7667 */
7668 void CTcTokenizer::pp_elif()
7669 {
7670 CTcConstVal val;
7671
7672 /* expand macros; don't allow reading additional lines */
7673 if (expand_macros_curline(FALSE, TRUE, FALSE))
7674 {
7675 clear_linebuf();
7676 return;
7677 }
7678
7679 /* parse out of the expansion buffer */
7680 start_new_line(&expbuf_, 0);
7681
7682 /* parse the preprocessor expression */
7683 if (pp_parse_expr(&val, TRUE, TRUE, TRUE))
7684 {
7685 clear_linebuf();
7686 return;
7687 }
7688
7689 /*
7690 * make sure that the #elif occurs in the same file as the
7691 * corresponding #if
7692 */
7693 if (if_sp_ <= str_->get_init_if_level())
7694 {
7695 /* log the error */
7696 log_error(TCERR_PP_ELIF_NOT_IN_SAME_FILE);
7697
7698 /* clear the text and abort */
7699 clear_linebuf();
7700 return;
7701 }
7702
7703 /* check the current #if state */
7704 switch(get_if_state())
7705 {
7706 case TOKIF_IF_YES:
7707 /*
7708 * we just took the #if branch, so don't take this or any
7709 * subsequent #elif or #else branch, regardless of the value of
7710 * the condition - set the state to DONE to indicate that we're
7711 * skipping everything through the endif
7712 */
7713 change_if_state(TOKIF_IF_DONE);
7714 break;
7715
7716 case TOKIF_IF_NO:
7717 /*
7718 * We haven't yet taken a #if or #elif branch, so we can take
7719 * this branch if its condition is true. If this branch's
7720 * condition is false, stay with NO so that we will consider
7721 * future #elif and #else branches.
7722 */
7723 if (val.get_val_bool())
7724 change_if_state(TOKIF_IF_YES);
7725 break;
7726
7727 case TOKIF_IF_DONE:
7728 /*
7729 * we've already taken a #if or #elif branch, so we must ignore
7730 * this and subsequent #elif and #else branches until we get to
7731 * our #endif - just stay in state DONE
7732 */
7733 break;
7734
7735 case TOKIF_NONE:
7736 case TOKIF_ELSE_YES:
7737 case TOKIF_ELSE_NO:
7738 /*
7739 * we're not in a #if branch at all, or we're inside a #else; a
7740 * #elif is not legal here
7741 */
7742 log_error(TCERR_PP_ELIF_WITHOUT_IF);
7743 break;
7744 }
7745
7746 /* don't retain the directive in the preprocessed source */
7747 clear_linebuf();
7748 }
7749
7750 /* ------------------------------------------------------------------------ */
7751 /*
7752 * Process a #else directive
7753 */
7754 void CTcTokenizer::pp_else()
7755 {
7756 /* make sure there's nothing but whitespace on the line */
7757 if (next_on_line() != TOKT_EOF)
7758 log_error(TCERR_PP_EXTRA);
7759
7760 /*
7761 * make sure that the #else occurs in the same file as the
7762 * corresponding #if
7763 */
7764 if (if_sp_ <= str_->get_init_if_level())
7765 {
7766 /* log the error */
7767 log_error(TCERR_PP_ELSE_NOT_IN_SAME_FILE);
7768
7769 /* clear the text and abort */
7770 clear_linebuf();
7771 return;
7772 }
7773
7774 /* check our current #if state */
7775 switch(get_if_state())
7776 {
7777 case TOKIF_IF_YES:
7778 case TOKIF_IF_DONE:
7779 /*
7780 * we've already taken a true #if branch, so we don't want to
7781 * process the #else part - switch to a false #else branch
7782 */
7783 change_if_state(TOKIF_ELSE_NO);
7784 break;
7785
7786 case TOKIF_IF_NO:
7787 /*
7788 * we haven't yet found a true #if branch, so take the #else
7789 * branch -- switch to a true #else branch
7790 */
7791 change_if_state(TOKIF_ELSE_YES);
7792 break;
7793
7794 case TOKIF_NONE:
7795 case TOKIF_ELSE_YES:
7796 case TOKIF_ELSE_NO:
7797 /*
7798 * we're not in a #if at all, or we're in a #else - log an error
7799 * and ignore it
7800 */
7801 log_error(TCERR_PP_ELSE_WITHOUT_IF);
7802 break;
7803 }
7804
7805 /* don't retain the directive in the preprocessed source */
7806 clear_linebuf();
7807 }
7808
7809 /* ------------------------------------------------------------------------ */
7810 /*
7811 * Process a #endif directive
7812 */
7813 void CTcTokenizer::pp_endif()
7814 {
7815 /* make sure the rest of the line is blank */
7816 if (next_on_line() != TOKT_EOF)
7817 log_error(TCERR_PP_EXTRA);
7818
7819 /* ignore the rest of the line */
7820 clear_linebuf();
7821
7822 /* if we're not in a #if in the same file it's an error */
7823 if (if_sp_ == 0)
7824 {
7825 log_error(TCERR_PP_ENDIF_WITHOUT_IF);
7826 return;
7827 }
7828 else if (if_sp_ <= str_->get_init_if_level())
7829 {
7830 log_error(TCERR_PP_ENDIF_NOT_IN_SAME_FILE);
7831 return;
7832 }
7833
7834 /* pop a #if level */
7835 pop_if();
7836
7837 /* don't retain the directive in the preprocessed source */
7838 clear_linebuf();
7839 }
7840
7841 /* ------------------------------------------------------------------------ */
7842 /*
7843 * Process a #error directive
7844 */
7845 void CTcTokenizer::pp_error()
7846 {
7847 size_t startofs;
7848
7849 /*
7850 * copy the source line through the "error" token to the macro
7851 * expansion buffer - we don't want to expand that part, but we want
7852 * it to appear in the expansion, so just copy the original
7853 */
7854 startofs = (curtok_.get_text() + curtok_.get_text_len()
7855 - linebuf_.get_text());
7856 expbuf_.copy(linebuf_.get_text(), startofs);
7857
7858 /* expand macros; don't allow reading additional lines */
7859 if (expand_macros_curline(FALSE, FALSE, TRUE))
7860 {
7861 clear_linebuf();
7862 return;
7863 }
7864
7865 /* clean up any expansion flags embedded in the buffer */
7866 remove_expansion_flags(&expbuf_);
7867
7868 /*
7869 * If we're in preprocess-only mode, simply retain the text in the
7870 * processed result, so that the error is processed on a subsequent
7871 * compilation of the result; otherwise, display the error.
7872 *
7873 * Ignore #error directives in list-includes mode as well.
7874 */
7875 if (!pp_only_mode_ && !list_includes_mode_)
7876 {
7877 /* display the error */
7878 log_error(TCERR_ERROR_DIRECTIVE,
7879 (int)expbuf_.get_text_len() - startofs,
7880 expbuf_.get_text() + startofs);
7881
7882 /* clear the directive from the result */
7883 clear_linebuf();
7884 }
7885 else
7886 {
7887 /* preprocessing - copy expanded text to line buffer */
7888 linebuf_.copy(expbuf_.get_text(), expbuf_.get_text_len());
7889 }
7890 }
7891
7892 /* ------------------------------------------------------------------------ */
7893 /*
7894 * Process a #undef directive
7895 */
7896 void CTcTokenizer::pp_undef()
7897 {
7898 char macro_name[TOK_SYM_MAX_BUFFER];
7899
7900 /* get the macro name */
7901 if (pp_get_lone_ident(macro_name, sizeof(macro_name)))
7902 {
7903 clear_linebuf();
7904 return;
7905 }
7906
7907 /* remove it */
7908 undefine(macro_name);
7909
7910 /* don't retain the directive in the preprocessed source */
7911 clear_linebuf();
7912 }
7913
7914 /*
7915 * Programmatically delete a preprocesor symbol
7916 */
7917 void CTcTokenizer::undefine(const char *sym, size_t len)
7918 {
7919 CTcHashEntryPp *entry;
7920
7921 /*
7922 * find the macro - if it wasn't defined, silently ignore it, since
7923 * it's legal to #undef a symbol that wasn't previously defined
7924 */
7925 entry = find_define(sym, len);
7926 if (entry != 0 && entry->is_undefable())
7927 {
7928 /* remove it */
7929 defines_->remove(entry);
7930
7931 /* if it's not already in the #undef table, move it there */
7932 if (find_undef(sym, len) == 0)
7933 {
7934 /* move it to the #undef table */
7935 undefs_->add(entry);
7936 }
7937 else
7938 {
7939 /*
7940 * the name is already in the #undef table, so we don't need to
7941 * add it again - we can forget about this entry entirely
7942 */
7943 delete entry;
7944 }
7945 }
7946 }
7947
7948 /* ------------------------------------------------------------------------ */
7949 /*
7950 * Process a #line directive
7951 */
7952 void CTcTokenizer::pp_line()
7953 {
7954 CTcConstVal val_line;
7955 CTcConstVal val_fname;
7956 CTcTokFileDesc *desc;
7957
7958 /* expand macros; don't allow reading additional lines */
7959 if (expand_macros_curline(FALSE, TRUE, FALSE))
7960 {
7961 clear_linebuf();
7962 return;
7963 }
7964
7965 /*
7966 * we don't need the original source line any more, and we don't
7967 * want to copy it to the preprocessed output, so clear it
7968 */
7969 clear_linebuf();
7970
7971 /* set up to parse from the expansion */
7972 start_new_line(&expbuf_, 0);
7973
7974 /* evaluate the line number expression */
7975 if (pp_parse_expr(&val_line, TRUE, FALSE, TRUE))
7976 return;
7977
7978 /* if it's not an integer constant, it's an error */
7979 if (val_line.get_type() != TC_CVT_INT)
7980 {
7981 log_error(TCERR_LINE_REQ_INT);
7982 return;
7983 }
7984
7985 /* evaluate the filename expression */
7986 if (pp_parse_expr(&val_fname, FALSE, TRUE, TRUE))
7987 return;
7988
7989 /* the filename must be a string expression */
7990 if (val_fname.get_type() != TC_CVT_SSTR)
7991 {
7992 log_error(TCERR_LINE_FILE_REQ_STR);
7993 return;
7994 }
7995
7996 /* find or create a descriptor for the filename */
7997 desc = get_file_desc(val_fname.get_val_str(),
7998 val_fname.get_val_str_len(), FALSE, 0, 0);
7999
8000 /* set the new line number and descriptor in the current stream */
8001 if (str_ != 0)
8002 {
8003 str_->set_next_linenum(val_line.get_val_int());
8004 str_->set_desc(desc);
8005 }
8006
8007 /*
8008 * retain the pragma in the result if we're in preprocess-only mode,
8009 * otherwise remove it
8010 */
8011 if (!pp_only_mode_)
8012 clear_linebuf();
8013 }
8014
8015 /* ------------------------------------------------------------------------ */
8016 /*
8017 * Look up a symbol in the #define symbol table
8018 */
8019 CTcHashEntryPp *CTcTokenizer::find_define(const char *sym, size_t len) const
8020 {
8021 /* look it up in the #define symbol table and return the result */
8022 return (CTcHashEntryPp *)defines_->find(sym, len);
8023 }
8024
8025 /*
8026 * Look up a symbol in the #undef table
8027 */
8028 CTcHashEntryPp *CTcTokenizer::find_undef(const char *sym, size_t len) const
8029 {
8030 /* look it up in the #define symbol table and return the result */
8031 return (CTcHashEntryPp *)undefs_->find(sym, len);
8032 }
8033
8034 /*
8035 * Add a preprocessor macro definition
8036 */
8037 void CTcTokenizer::add_define(const char *sym, size_t len,
8038 const char *expansion, size_t expan_len)
8039 {
8040 CTcHashEntryPp *entry;
8041
8042 /* create an entry for the macro, with no argument list */
8043 entry = new CTcHashEntryPpDefine(sym, len, TRUE, FALSE, 0, FALSE, 0, 0,
8044 expansion, expan_len);
8045
8046 /* add the new entry to the table */
8047 defines_->add(entry);
8048 }
8049
8050 /*
8051 * Add a preprocessor macro definition
8052 */
8053 void CTcTokenizer::add_define(CTcHashEntryPp *entry)
8054 {
8055 /* add the entry to our symbol table */
8056 defines_->add(entry);
8057 }
8058
8059 /*
8060 * parse an expression
8061 */
8062 int CTcTokenizer::pp_parse_expr(CTcConstVal *val, int read_first,
8063 int last_on_line, int add_line_ending)
8064 {
8065 CTcPrsNode *expr_tree;
8066 char ch;
8067
8068 /* add the line ending marker if required */
8069 if (add_line_ending)
8070 {
8071 /*
8072 * append the special end-of-preprocess-line to the macro
8073 * expansion buffer
8074 */
8075 ch = TOK_END_PP_LINE;
8076 expbuf_.append(&ch, 1);
8077 }
8078
8079 /*
8080 * note that we're pasing a preprocessor expression; this affects
8081 * error logging in certain cases
8082 */
8083 in_pp_expr_ = TRUE;
8084
8085 /*
8086 * parse the expression in preprocessor mode, so that double-quoted
8087 * strings can be concatenated and compared
8088 */
8089 G_prs->set_pp_expr_mode(TRUE);
8090
8091 /* get the first token on the line if desired */
8092 if (read_first)
8093 next();
8094
8095 /* parse the expression */
8096 expr_tree = G_prs->parse_expr();
8097
8098 /* make sure we're at the end of the line if desired */
8099 if (last_on_line && next() != TOKT_EOF)
8100 log_error(TCERR_PP_EXPR_EXTRA);
8101
8102 /* if we added the special pp-line-ending marker, remove it */
8103 if (add_line_ending)
8104 {
8105 /*
8106 * the marker is always the last character - remove it simply by
8107 * shortening the buffer by a character
8108 */
8109 expbuf_.set_text_len(expbuf_.get_text_len() - 1);
8110 }
8111
8112 /* return to normal expression mode */
8113 G_prs->set_pp_expr_mode(FALSE);
8114
8115 /* return to normal tokenizing mode */
8116 in_pp_expr_ = FALSE;
8117
8118 /* if we didn't get a valid expression, return failure */
8119 if (expr_tree == 0)
8120 return 1;
8121
8122 /* make sure we got a constant */
8123 if (!expr_tree->is_const())
8124 {
8125 log_error(TCERR_PP_EXPR_NOT_CONST);
8126 return 1;
8127 }
8128
8129 /* fill in the caller's value */
8130 *val = *expr_tree->get_const_val();
8131
8132 /* success */
8133 return 0;
8134 }
8135
8136 /* ------------------------------------------------------------------------ */
8137 /*
8138 * #define enumeration callback context
8139 */
8140 struct def_enum_cb_t
8141 {
8142 /* original callback function */
8143 void (*cb)(void *, CTcHashEntryPp *);
8144
8145 /* original callback context */
8146 void *ctx;
8147 };
8148
8149 /*
8150 * #define enumeration callback. This is a simple impedence matcher on the
8151 * way to the real callbac; we cast the generic hash entry type to the
8152 * CTcHashEntryPp subclass for the benefit of the real callback.
8153 */
8154 static void enum_defines_cb(void *ctx0, CVmHashEntry *entry)
8155 {
8156 def_enum_cb_t *ctx;
8157
8158 /* get our real context */
8159 ctx = (def_enum_cb_t *)ctx0;
8160
8161 /* invoke the real callback, casting the entry reference appropriately */
8162 (*ctx->cb)(ctx->ctx, (CTcHashEntryPp *)entry);
8163 }
8164
8165 /*
8166 * Enumerate the entries in the #define table through a callback
8167 */
8168 void CTcTokenizer::enum_defines(void (*cb)(void *, CTcHashEntryPp *),
8169 void *ctx)
8170 {
8171 def_enum_cb_t myctx;
8172
8173 /* set up our impedence-matcher context with the real callback info */
8174 myctx.cb = cb;
8175 myctx.ctx = ctx;
8176
8177 /* enumerate through our impedence-matcher callback */
8178 defines_->enum_entries(&enum_defines_cb, &myctx);
8179 }
8180
8181 /* ------------------------------------------------------------------------ */
8182 /*
8183 * Get a lone identifier for a preprocessor directive. The identifier
8184 * must be the only thing left on the line; we'll generate an error if
8185 * extra characters follow on the line.
8186 *
8187 * If there's no identifier on the line, or there's more information
8188 * after the identifier, logs an error and returns non-zero; returns
8189 * zero on success.
8190 */
8191 int CTcTokenizer::pp_get_lone_ident(char *buf, size_t bufl)
8192 {
8193 /* get the next token, and make sure it's a symbol */
8194 if (next_on_line() != TOKT_SYM)
8195 {
8196 log_error_curtok(TCERR_BAD_DEFINE_SYM);
8197 return 1;
8198 }
8199
8200 /* return an error if it doesn't fit */
8201 if (curtok_.get_text_len() > bufl)
8202 return 1;
8203
8204 /* copy the text */
8205 memcpy(buf, curtok_.get_text(), curtok_.get_text_len());
8206 buf[curtok_.get_text_len()] = '\0';
8207
8208 /* make sure there's nothing else on the line but whitespace */
8209 if (next_on_line() != TOKT_EOF)
8210 {
8211 log_error(TCERR_PP_EXTRA);
8212 return 1;
8213 }
8214
8215 /* success */
8216 return 0;
8217 }
8218
8219 /* ------------------------------------------------------------------------ */
8220 /*
8221 * Push a new #if level
8222 */
8223 void CTcTokenizer::push_if(tok_if_t state)
8224 {
8225 /* if we're out of space in the stack, throw a fatal error */
8226 if (if_sp_ == TOK_MAX_IF_NESTING)
8227 throw_fatal_error(TCERR_IF_NESTING_OVERFLOW);
8228
8229 /*
8230 * if we're in a nested #if in a false #if, increase the nested
8231 * false #if level
8232 */
8233 if (in_false_if())
8234 ++if_false_level_;
8235
8236 /* push the state, remembering where the #if was defined */
8237 if_stack_[if_sp_].desc = last_desc_;
8238 if_stack_[if_sp_].linenum = last_linenum_;
8239 if_stack_[if_sp_++].state = state;
8240 }
8241
8242 /*
8243 * Pop a #if level
8244 */
8245 void CTcTokenizer::pop_if()
8246 {
8247 /* if we're in a nested #if in a false #if, pop the nesting level */
8248 if (if_false_level_ != 0)
8249 --if_false_level_;
8250
8251 /* pop the main if level */
8252 if (if_sp_ != 0)
8253 --if_sp_;
8254 }
8255
8256
8257 /* ------------------------------------------------------------------------ */
8258 /*
8259 * Log an error
8260 */
8261 void CTcTokenizer::log_error(int errnum, ...)
8262 {
8263 va_list marker;
8264
8265 /* display the message */
8266 va_start(marker, errnum);
8267 G_tcmain->v_log_error(G_tok->get_last_desc(), G_tok->get_last_linenum(),
8268 TC_SEV_ERROR, errnum, marker);
8269 va_end(marker);
8270 }
8271
8272 /*
8273 * Log an error with the current token's text as the parameter data,
8274 * suitable for use with a "%.*s" display format entry
8275 */
8276 void CTcTokenizer::log_error_curtok(int errnum)
8277 {
8278 /*
8279 * display the message, passing "%.*s" parameter data for the
8280 * current token text: an integer giving the length of the token
8281 * text, and a pointer to the token text
8282 */
8283 log_error_or_warning_curtok(TC_SEV_ERROR, errnum);
8284 }
8285
8286 /*
8287 * Log an error or warning for the current token
8288 */
8289 void CTcTokenizer::log_error_or_warning_curtok(tc_severity_t sev, int errnum)
8290 {
8291 /* log the error with our current token */
8292 log_error_or_warning_with_tok(sev, errnum, getcur());
8293 }
8294
8295 /*
8296 * Log an error or warning with the given token
8297 */
8298 void CTcTokenizer::log_error_or_warning_with_tok(
8299 tc_severity_t sev, int errnum, const CTcToken *tok)
8300 {
8301 const char *tok_txt;
8302 size_t tok_len;
8303 char buf[128];
8304 const char *prefix;
8305 const char *suffix;
8306 utf8_ptr src;
8307 utf8_ptr dst;
8308 size_t rem;
8309 size_t outchars;
8310
8311 /* see what we have */
8312 switch(tok->gettyp())
8313 {
8314 case TOKT_SSTR:
8315 /* show the string in quotes, but limit the length */
8316 prefix = "'";
8317 suffix = "'";
8318 goto format_string;
8319
8320 case TOKT_DSTR:
8321 prefix = "\"";
8322 suffix = "\"";
8323 goto format_string;
8324
8325 case TOKT_DSTR_START:
8326 prefix = "\"";
8327 suffix = "<<";
8328 goto format_string;
8329
8330 case TOKT_DSTR_MID:
8331 prefix = ">>";
8332 suffix = "<<";
8333 goto format_string;
8334
8335 case TOKT_DSTR_END:
8336 prefix = ">>";
8337 suffix = "\"";
8338 goto format_string;
8339
8340 case TOKT_RESTR:
8341 prefix = "R'";
8342 suffix = "'";
8343 goto format_string;
8344
8345 format_string:
8346 /* set the prefix */
8347 strcpy(buf, prefix);
8348
8349 /*
8350 * show the string, but limit the length, and convert control
8351 * characters to escaped representation
8352 */
8353 src.set((char *)tok->get_text());
8354 rem = tok->get_text_len();
8355 for (dst.set(buf + strlen(buf)), outchars = 0 ;
8356 rem != 0 && outchars < 20 ; src.inc(&rem), ++outchars)
8357 {
8358 /* if this is a control character, escape it */
8359 if (src.getch() < 32)
8360 {
8361 dst.setch('\\');
8362
8363 switch(src.getch())
8364 {
8365 case 10:
8366 dst.setch('n');
8367 break;
8368
8369 case 13:
8370 dst.setch('r');
8371 break;
8372
8373 case 0x000F:
8374 dst.setch('^');
8375 break;
8376
8377 case 0x000E:
8378 dst.setch('v');
8379 break;
8380
8381 case 0x000B:
8382 dst.setch('b');
8383 break;
8384
8385 case 0x0015:
8386 dst.setch(' ');
8387 break;
8388
8389 case 9:
8390 dst.setch('t');
8391 break;
8392
8393 default:
8394 dst.setch('x');
8395 dst.setch('0' + int_to_xdigit((src.getch() >> 12) & 0xf));
8396 dst.setch('0' + int_to_xdigit((src.getch() >> 8) & 0xf));
8397 dst.setch('0' + int_to_xdigit((src.getch() >> 4) & 0xf));
8398 dst.setch('0' + int_to_xdigit((src.getch()) & 0xf));
8399 break;
8400 }
8401 }
8402 else
8403 {
8404 /* put this character as-is */
8405 dst.setch(src.getch());
8406 }
8407 }
8408
8409 /* if there's more string left, add "..." */
8410 if (rem != 0)
8411 {
8412 dst.setch('.');
8413 dst.setch('.');
8414 dst.setch('.');
8415 }
8416
8417 /* add the suffix */
8418 strcpy(dst.getptr(), suffix);
8419
8420 /* use this buffer as the token string to display */
8421 tok_txt = buf;
8422 tok_len = strlen(tok_txt);
8423 break;
8424
8425 case TOKT_EOF:
8426 /* show a special "<End Of File>" marker */
8427 tok_txt = "<End Of File>";
8428 tok_len = strlen(tok_txt);
8429 break;
8430
8431 default:
8432 /* just show the current token text */
8433 tok_txt = tok->get_text();
8434 tok_len = tok->get_text_len();
8435 break;
8436 }
8437
8438 /* log the error */
8439 G_tcmain->log_error(get_last_desc(), get_last_linenum(),
8440 sev, errnum, tok_len, tok_txt);
8441 }
8442
8443 /*
8444 * Log a warning
8445 */
8446 void CTcTokenizer::log_warning(int errnum, ...)
8447 {
8448 va_list marker;
8449
8450 /* display the message */
8451 va_start(marker, errnum);
8452 G_tcmain->v_log_error(G_tok->get_last_desc(), G_tok->get_last_linenum(),
8453 TC_SEV_WARNING, errnum, marker);
8454 va_end(marker);
8455 }
8456
8457 /*
8458 * Log a pedantic warning
8459 */
8460 void CTcTokenizer::log_pedantic(int errnum, ...)
8461 {
8462 va_list marker;
8463
8464 /* display the message */
8465 va_start(marker, errnum);
8466 G_tcmain->v_log_error(G_tok->get_last_desc(), G_tok->get_last_linenum(),
8467 TC_SEV_PEDANTIC, errnum, marker);
8468 va_end(marker);
8469 }
8470
8471 /*
8472 * Log a warning with the current token's text as the parameter data,
8473 * suitable for use with a "%.*s" display format entry
8474 */
8475 void CTcTokenizer::log_warning_curtok(int errnum)
8476 {
8477 /*
8478 * display the warning message, passing "%.*s" parameter data for
8479 * the current token text: an integer giving the length of the token
8480 * text, and a pointer to the token text
8481 */
8482 log_error_or_warning_curtok(TC_SEV_WARNING, errnum);
8483 }
8484
8485 /*
8486 * Log and throw an internal error
8487 */
8488 void CTcTokenizer::throw_internal_error(int errnum, ...)
8489 {
8490 va_list marker;
8491
8492 /* display the message */
8493 va_start(marker, errnum);
8494 G_tcmain->v_log_error(G_tok->get_last_desc(), G_tok->get_last_linenum(),
8495 TC_SEV_INTERNAL, errnum, marker);
8496 va_end(marker);
8497
8498 /* throw the generic internal error, since we've logged this */
8499 err_throw(TCERR_INTERNAL_ERROR);
8500 }
8501
8502 /*
8503 * Log and throw a fatal error
8504 */
8505 void CTcTokenizer::throw_fatal_error(int errnum, ...)
8506 {
8507 va_list marker;
8508
8509 /* display the message */
8510 va_start(marker, errnum);
8511 G_tcmain->v_log_error(G_tok->get_last_desc(), G_tok->get_last_linenum(),
8512 TC_SEV_FATAL, errnum, marker);
8513 va_end(marker);
8514
8515 /* throw the generic fatal error, since we've logged this */
8516 err_throw(TCERR_FATAL_ERROR);
8517 }
8518
8519 /*
8520 * display a string value
8521 */
8522 void CTcTokenizer::msg_str(const char *str, size_t len) const
8523 {
8524 /* display the string through the host interface */
8525 G_hostifc->print_msg("%.*s", (int)len, str);
8526 }
8527
8528 /*
8529 * display a numeric value
8530 */
8531 void CTcTokenizer::msg_long(long val) const
8532 {
8533 /* display the number through the host interface */
8534 G_hostifc->print_msg("%ld", val);
8535 }
8536
8537 /* ------------------------------------------------------------------------ */
8538 /*
8539 * Tokenizer Input Stream implementation
8540 */
8541
8542 /*
8543 * create a token input stream
8544 */
8545 CTcTokStream::CTcTokStream(CTcTokFileDesc *desc, CTcSrcObject *src,
8546 CTcTokStream *parent, int charset_error,
8547 int init_if_level)
8548 {
8549 /* remember the underlying source file */
8550 src_ = src;
8551
8552 /* remember the file descriptor */
8553 desc_ = desc;
8554
8555 /* remember the containing stream */
8556 parent_ = parent;
8557
8558 /* the next line to read is line number 1 */
8559 next_linenum_ = 1;
8560
8561 /* remember if there was a #charset error */
8562 charset_error_ = charset_error;
8563
8564 /* we're not in a comment yet */
8565 in_comment_ = FALSE;
8566
8567 /* remember the starting #if level */
8568 init_if_level_ = init_if_level;
8569
8570 #if 0 // #pragma C is not currently used
8571 /*
8572 * start out in parent's pragma C mode, or in non-C mode if we have
8573 * no parent
8574 */
8575 if (parent != 0)
8576 pragma_c_ = parent->is_pragma_c();
8577 else
8578 pragma_c_ = TRUE;
8579 #endif
8580 }
8581
8582 /*
8583 * delete a token input stream
8584 */
8585 CTcTokStream::~CTcTokStream()
8586 {
8587 /* we own the underlying file, so delete it */
8588 if (src_ != 0)
8589 delete src_;
8590 }
8591
8592 /* ------------------------------------------------------------------------ */
8593 /*
8594 * File Descriptor
8595 */
8596
8597 /*
8598 * Get the length of a string with each instance of the given quote
8599 * character escaped with a backslash. We'll also count the escapes we
8600 * need for each backslash.
8601 */
8602 static size_t get_quoted_len(const char *str, wchar_t qu)
8603 {
8604 utf8_ptr p;
8605 size_t len;
8606
8607 /*
8608 * scan the string for instances of the quote mark; each one adds an
8609 * extra byte to the length needed, since each one requires a
8610 * backslash character to escape the quote mark
8611 */
8612 for (p.set((char *)str), len = strlen(str) ; p.getch() != '\0' ; p.inc())
8613 {
8614 wchar_t ch;
8615
8616 /*
8617 * check to see if this character is quotable - it is quotable if
8618 * it's a backslash or it's the quote character we're escaping
8619 */
8620 ch = p.getch();
8621 if (ch == qu || ch == '\\')
8622 {
8623 /*
8624 * we need to escape this character, so add a byte for the
8625 * backslash we'll need to insert
8626 */
8627 ++len;
8628 }
8629 }
8630
8631 /* return the length we calculated */
8632 return len;
8633 }
8634
8635 /*
8636 * Build a quoted string. Fills in dst with the source string with each
8637 * of the given quote marks and each backslash escaped with a backslash.
8638 * Use get_quoted_len() to determine how much space to allocate for the
8639 * destination buffer.
8640 */
8641 static void build_quoted_str(char *dstbuf, const char *src, wchar_t qu)
8642 {
8643 utf8_ptr p;
8644 utf8_ptr dst;
8645
8646 /* scan the source string for escapable characters */
8647 for (p.set((char *)src), dst.set(dstbuf), dst.setch(qu) ;
8648 p.getch() != '\0' ; p.inc())
8649 {
8650 wchar_t ch;
8651
8652 /* get this source character */
8653 ch = p.getch();
8654
8655 /* add a quote if we have a backslash or the quote character */
8656 if (ch == '\\' || ch == qu)
8657 {
8658 /* add a backslash to escape the character */
8659 dst.setch('\\');
8660 }
8661
8662 /* add the character */
8663 dst.setch(ch);
8664 }
8665
8666 /* add the close quote and trailing null */
8667 dst.setch(qu);
8668 dst.setch('\0');
8669 }
8670
8671 /*
8672 * create a file descriptor
8673 */
8674 CTcTokFileDesc::CTcTokFileDesc(const char *fname, size_t fname_len,
8675 int index, CTcTokFileDesc *orig_desc,
8676 const char *orig_fname, size_t orig_fname_len)
8677 {
8678 const char *rootname;
8679
8680 /* no source pages are allocated yet */
8681 src_pages_ = 0;
8682 src_pages_alo_ = 0;
8683
8684 /* remember the first instance of this filename in the list */
8685 orig_ = orig_desc;
8686
8687 /* there's nothing else in our chain yet */
8688 next_ = 0;
8689
8690 /* remember my index in the master list */
8691 index_ = index;
8692
8693 /* if there's a filename, save a copy of the name */
8694 fname_ = lib_copy_str(fname, fname_len);
8695
8696 /* if there's an original filename save it as well */
8697 orig_fname_ = lib_copy_str(orig_fname, orig_fname_len);
8698
8699 /*
8700 * get the root filename, since we need to build a quoted version of
8701 * that as well as of the basic filename
8702 */
8703 rootname = os_get_root_name(fname_);
8704
8705 /*
8706 * Allocate space for the quoted versions of the filename - make room
8707 * for the filename plus the quotes (one on each end) and a null
8708 * terminator byte.
8709 */
8710 dquoted_fname_ = (char *)t3malloc(get_quoted_len(fname_, '"') + 3);
8711 squoted_fname_ = (char *)t3malloc(get_quoted_len(fname_, '\'') + 3);
8712 dquoted_rootname_ = (char *)t3malloc(get_quoted_len(rootname, '"') + 3);
8713 squoted_rootname_ = (char *)t3malloc(get_quoted_len(rootname, '\'') + 3);
8714
8715 /* build the quoted version of the name */
8716 build_quoted_str(dquoted_fname_, fname_, '"');
8717 build_quoted_str(squoted_fname_, fname_, '\'');
8718 build_quoted_str(dquoted_rootname_, rootname, '"');
8719 build_quoted_str(squoted_rootname_, rootname, '\'');
8720 }
8721
8722 /*
8723 * delete the descriptor
8724 */
8725 CTcTokFileDesc::~CTcTokFileDesc()
8726 {
8727 /* delete the filename and original filename strings */
8728 lib_free_str(fname_);
8729 lib_free_str(orig_fname_);
8730
8731 /* delete the quotable filename strings */
8732 t3free(dquoted_fname_);
8733 t3free(squoted_fname_);
8734 t3free(dquoted_rootname_);
8735 t3free(squoted_rootname_);
8736
8737 /* delete each source page we've allocated */
8738 if (src_pages_ != 0)
8739 {
8740 size_t i;
8741
8742 /* go through the index array and delete each allocated page */
8743 for (i = 0 ; i < src_pages_alo_ ; ++i)
8744 {
8745 /* if this page was allocated, delete it */
8746 if (src_pages_[i] != 0)
8747 t3free(src_pages_[i]);
8748 }
8749
8750 /* delete the source page index array */
8751 t3free(src_pages_);
8752 }
8753 }
8754
8755 /*
8756 * Source page structure. Each page tracks a block of source lines.
8757 */
8758 const size_t TCTOK_SRC_PAGE_CNT = 1024;
8759 struct CTcTokSrcPage
8760 {
8761 /*
8762 * Array of line entries on this page. Each entry is zero if it
8763 * hasn't been assigned yet, and contains the absolute image file
8764 * address of the generated code for the source line if it has been
8765 * assigned.
8766 */
8767 ulong ofs[TCTOK_SRC_PAGE_CNT];
8768 };
8769
8770
8771 /*
8772 * Add a source line
8773 */
8774 void CTcTokFileDesc::add_source_line(ulong linenum, ulong line_addr)
8775 {
8776 size_t page_idx;
8777 size_t idx;
8778
8779 /* get the index of the page containing this source line */
8780 page_idx = linenum / TCTOK_SRC_PAGE_CNT;
8781
8782 /* get the index of the entry within the page */
8783 idx = linenum % TCTOK_SRC_PAGE_CNT;
8784
8785 /*
8786 * determine if our page index table is large enough, and expand it
8787 * if not
8788 */
8789 if (page_idx >= src_pages_alo_)
8790 {
8791 size_t siz;
8792 size_t new_alo;
8793
8794 /* allocate or expand the source pages array */
8795 new_alo = page_idx + 16;
8796 siz = new_alo * sizeof(src_pages_[0]);
8797 if (src_pages_ == 0)
8798 src_pages_ = (CTcTokSrcPage **)t3malloc(siz);
8799 else
8800 src_pages_ = (CTcTokSrcPage **)t3realloc(src_pages_, siz);
8801
8802 /* clear the new part */
8803 memset(src_pages_ + src_pages_alo_, 0,
8804 (new_alo - src_pages_alo_) * sizeof(src_pages_[0]));
8805
8806 /* remember the new allocation size */
8807 src_pages_alo_ = new_alo;
8808 }
8809
8810 /* if this page isn't allocated, do so now */
8811 if (src_pages_[page_idx] == 0)
8812 {
8813 /* allocate the new page */
8814 src_pages_[page_idx] = (CTcTokSrcPage *)
8815 t3malloc(sizeof(CTcTokSrcPage));
8816
8817 /* clear it */
8818 memset(src_pages_[page_idx], 0, sizeof(CTcTokSrcPage));
8819 }
8820
8821 /*
8822 * if this source line entry has been previously set, don't change
8823 * it; otherwise, store the new setting
8824 */
8825 if (src_pages_[page_idx]->ofs[idx] == 0)
8826 src_pages_[page_idx]->ofs[idx] = line_addr;
8827 }
8828
8829 /*
8830 * Enumerate source lines
8831 */
8832 void CTcTokFileDesc::enum_source_lines(void (*cbfunc)(void *, ulong, ulong),
8833 void *cbctx)
8834 {
8835 size_t page_idx;
8836 CTcTokSrcPage **pg;
8837
8838 /* loop over all of the pages */
8839 for (page_idx = 0, pg = src_pages_ ; page_idx < src_pages_alo_ ;
8840 ++page_idx, ++pg)
8841 {
8842 size_t i;
8843 ulong linenum;
8844 ulong *p;
8845
8846 /* if this page is not populated, skip it */
8847 if (*pg == 0)
8848 continue;
8849
8850 /* calculate the starting line number for this page */
8851 linenum = page_idx * TCTOK_SRC_PAGE_CNT;
8852
8853 /* loop over the entries on this page */
8854 for (i = 0, p = (*pg)->ofs ; i < TCTOK_SRC_PAGE_CNT ;
8855 ++i, ++p, ++linenum)
8856 {
8857 /* if this entry has been set, call the callback */
8858 if (*p != 0)
8859 (*cbfunc)(cbctx, linenum, *p);
8860 }
8861 }
8862 }
8863
8864 /* ------------------------------------------------------------------------ */
8865 /*
8866 * #define symbol table hash entry
8867 */
8868
8869 /*
8870 * create an entry
8871 */
8872 CTcHashEntryPpDefine::CTcHashEntryPpDefine(const textchar_t *str, size_t len,
8873 int copy, int has_args, int argc,
8874 int has_varargs,
8875 const char **argv,
8876 const size_t *argvlen,
8877 const char *expansion,
8878 size_t expan_len)
8879 : CTcHashEntryPp(str, len, copy)
8880 {
8881 /* copy the argument list if necessary */
8882 has_args_ = has_args;
8883 has_varargs_ = has_varargs;
8884 argc_ = argc;
8885 if (argc != 0)
8886 {
8887 int i;
8888
8889 /* allocate the argument list */
8890 argv_ = (char **)t3malloc(argc * sizeof(*argv_));
8891
8892 /* allocate the parameters hash table */
8893 params_table_ = new CVmHashTable(16, new CVmHashFuncCS(), TRUE);
8894
8895 /* allocate the entry list */
8896 arg_entry_ = (CTcHashEntryPpArg **)
8897 t3malloc(argc * sizeof(arg_entry_[0]));
8898
8899 /* copy the arguments */
8900 for (i = 0 ; i < argc ; ++i)
8901 {
8902 CTcHashEntryPpArg *entry;
8903
8904 /* copy the argument name */
8905 argv_[i] = lib_copy_str(argv[i], argvlen[i]);
8906
8907 /*
8908 * Create the hash entries for this parameters. We'll use
8909 * this entry to look up tokens in the expansion text for
8910 * matches to the formal names when expanding the macro.
8911 *
8912 * Note that we'll refer directly to our local copy of the
8913 * argument name, so we don't need to make another copy in
8914 * the hash entry.
8915 */
8916 entry = new CTcHashEntryPpArg(argv_[i], argvlen[i], FALSE, i);
8917 params_table_->add(entry);
8918
8919 /* add it to our by-index list */
8920 arg_entry_[i] = entry;
8921 }
8922 }
8923 else
8924 {
8925 /* no arguments */
8926 argv_ = 0;
8927 params_table_ = 0;
8928 arg_entry_ = 0;
8929 }
8930
8931 /* save the original version of the expansion */
8932 orig_expan_ = lib_copy_str(expansion, expan_len);
8933 orig_expan_len_ = expan_len;
8934
8935 /* parse the expansion, and save the parsed result */
8936 parse_expansion(argvlen);
8937 }
8938
8939 /*
8940 * Parse the expansion text.
8941 */
8942 void CTcHashEntryPpDefine::parse_expansion(const size_t *argvlen)
8943 {
8944 /*
8945 * If there are arguments, scan the expansion for formal parameter
8946 * names. For each one we find, replace it with the special
8947 * TOK_MACRO_FORMAL_FLAG character followed by a one-byte value giving
8948 * the argument index. This special sequence is less costly to find
8949 * when we're expanding the macros - by doing the search here, we only
8950 * need to do it once, rather than each time we expand the macro.
8951 */
8952 if (argc_ != 0)
8953 {
8954 utf8_ptr src;
8955 size_t dstofs;
8956 tc_toktyp_t typ;
8957 CTcToken tok;
8958 const char *start;
8959 tok_embed_ctx ec;
8960 size_t expan_len = orig_expan_len_;
8961
8962 /*
8963 * Generate our modified expansion text in the tokenizer's macro
8964 * definition scratch buffer. Initially, make sure we have room
8965 * for a copy of the text; we'll resize the buffer later if we find
8966 * we need even more.
8967 */
8968 CTcTokString *defbuf = &G_tok->defbuf_;
8969 defbuf->ensure_space(expan_len);
8970
8971 /* scan for argument names, and replace them */
8972 for (start = orig_expan_, dstofs = 0, src.set((char *)orig_expan_) ;; )
8973 {
8974 /* get the next token */
8975 typ = CTcTokenizer::next_on_line(&src, &tok, &ec, FALSE);
8976
8977 /* if we've reached the end of the expansion, we're done */
8978 if (typ == TOKT_EOF)
8979 break;
8980
8981 /*
8982 * If this is a formal parameter name, we'll replace it with a
8983 * special two-byte sequence; otherwise, we'll keep it
8984 * unchanged.
8985 */
8986 if (typ == TOKT_SYM)
8987 {
8988 /* look up the symbol in our argument table */
8989 CTcHashEntryPpArg *entry =
8990 (CTcHashEntryPpArg *)params_table_->find(
8991 tok.get_text(), tok.get_text_len());
8992
8993 /* check if we found it */
8994 if (entry != 0)
8995 {
8996 /* get the argument number from the entry */
8997 int i = entry->get_argnum();
8998
8999 /* get the length of the formal name */
9000 size_t arg_len = argvlen[i];
9001
9002 /*
9003 * the normal replacement length for a formal parameter
9004 * is two bytes - one byte for the flag, and one for
9005 * the formal parameter index
9006 */
9007 size_t repl_len = 2;
9008
9009 /* by default, the flag byte is the formal flag */
9010 char flag_byte = TOK_MACRO_FORMAL_FLAG;
9011
9012 /*
9013 * Check for special varargs control suffixes. If we
9014 * matched the last argument name, and this is a
9015 * varargs macro, we might have a suffix.
9016 */
9017 if (has_varargs_
9018 && i == argc_ - 1
9019 && src.getch() == '#')
9020 {
9021 /* check for the various suffixes */
9022 if (memcmp(src.getptr() + 1, "foreach", 7) == 0
9023 && !is_sym(src.getch_at(8)))
9024 {
9025 /*
9026 * include the suffix length in the token
9027 * length
9028 */
9029 arg_len += 8;
9030
9031 /*
9032 * the flag byte is the #foreach flag, which is
9033 * a one-byte sequence
9034 */
9035 flag_byte = TOK_MACRO_FOREACH_FLAG;
9036 repl_len = 1;
9037 }
9038 else if (memcmp(src.getptr() + 1,
9039 "argcount", 8) == 0
9040 && !is_sym(src.getch_at(9)))
9041 {
9042 /*
9043 * include the suffix length in the token
9044 * length
9045 */
9046 arg_len += 9;
9047
9048 /*
9049 * the flag byte is the #argcount flag, which
9050 * is a one-byte sequence
9051 */
9052 flag_byte = TOK_MACRO_ARGCOUNT_FLAG;
9053 repl_len = 1;
9054 }
9055 else if (memcmp(src.getptr() + 1,
9056 "ifempty", 7) == 0
9057 && !is_sym(src.getch_at(8)))
9058 {
9059 /* include the length */
9060 arg_len += 8;
9061
9062 /* set the one-byte flag */
9063 flag_byte = TOK_MACRO_IFEMPTY_FLAG;
9064 repl_len = 1;
9065 }
9066 else if (memcmp(src.getptr() + 1,
9067 "ifnempty", 8) == 0
9068 && !is_sym(src.getch_at(9)))
9069 {
9070 /* include the length */
9071 arg_len += 9;
9072
9073 /* set the one-byte flag */
9074 flag_byte = TOK_MACRO_IFNEMPTY_FLAG;
9075 repl_len = 1;
9076 }
9077 }
9078
9079 /*
9080 * calculate the new length - we're removing the
9081 * argument name and adding the replacement string in
9082 * its place
9083 */
9084 size_t new_len = expan_len + repl_len - arg_len;
9085
9086 /*
9087 * we need two bytes for the replacement - if this is
9088 * more than we're replacing, make sure we have room
9089 * for the extra
9090 */
9091 if (new_len > expan_len)
9092 defbuf->ensure_space(new_len);
9093
9094 /*
9095 * copy everything up to but not including the formal
9096 * name
9097 */
9098 if (tok.get_text() > start)
9099 {
9100 /* store the text */
9101 memcpy(defbuf->get_buf() + dstofs,
9102 start, tok.get_text() - start);
9103
9104 /* move past the stored text in the output */
9105 dstofs += tok.get_text() - start;
9106 }
9107
9108 /* the next segment starts after this token */
9109 start = tok.get_text() + arg_len;
9110
9111 /* store the flag byte */
9112 defbuf->get_buf()[dstofs++] = flag_byte;
9113
9114 /*
9115 * If appropriate, store the argument index - this
9116 * always fits in one byte because our hard limit on
9117 * formal parameters is less than 128 per macro. Note
9118 * that we add one to the index so that we never store
9119 * a zero byte, to avoid any potential confusion with a
9120 * null terminator byte.
9121 */
9122 if (repl_len > 1)
9123 defbuf->get_buf()[dstofs++] = (char)(i + 1);
9124
9125 /* remember the new length */
9126 expan_len = new_len;
9127 }
9128 }
9129 }
9130
9131 /* copy the last segment */
9132 if (tok.get_text() > start)
9133 memcpy(defbuf->get_buf() + dstofs, start, tok.get_text() - start);
9134
9135 /* set the new length */
9136 defbuf->set_text_len(expan_len);
9137
9138 /* save the parsed expansion */
9139 expan_ = lib_copy_str(defbuf->get_text());
9140 expan_len_ = expan_len;
9141 }
9142 else
9143 {
9144 /*
9145 * There are no arguments, so there's no parsing we need to do.
9146 * Just use the original as the parsed expansion.
9147 */
9148 expan_ = orig_expan_;
9149 expan_len_ = orig_expan_len_;
9150 }
9151 }
9152
9153 /*
9154 * delete
9155 */
9156 CTcHashEntryPpDefine::~CTcHashEntryPpDefine()
9157 {
9158 int i;
9159
9160 /* delete the argument list */
9161 if (argv_ != 0)
9162 {
9163 /* delete each argument string */
9164 for (i = 0 ; i < argc_ ; ++i)
9165 lib_free_str(argv_[i]);
9166
9167 /* delete the argument vector */
9168 t3free(argv_);
9169
9170 /* delete the argument entry list */
9171 t3free(arg_entry_);
9172
9173 /* delete the hash table */
9174 delete params_table_;
9175 }
9176
9177 /* delete the expansion */
9178 lib_free_str(expan_);
9179 if (orig_expan_ != expan_)
9180 lib_free_str(orig_expan_);
9181 }
9182
9183 /*
9184 * __LINE__ static buffer
9185 */
9186 char CTcHashEntryPpLINE::buf_[20];
9187
9188
9189 /* ------------------------------------------------------------------------ */
9190 /*
9191 * Load macro definitions from a file.
9192 */
9193 int CTcTokenizer::load_macros_from_file(CVmStream *fp,
9194 CTcTokLoadMacErr *err_handler)
9195 {
9196 long cnt;
9197 long i;
9198 size_t curarg;
9199 char *argv[TOK_MAX_MACRO_ARGS];
9200 size_t argvlen[TOK_MAX_MACRO_ARGS];
9201 size_t maxarg;
9202 int result;
9203 char *expan;
9204 size_t expmaxlen;
9205
9206 /* we haven't allocated any argument buffers yet */
9207 maxarg = 0;
9208
9209 /* allocate an initial expansion buffer */
9210 expmaxlen = 1024;
9211 expan = (char *)t3malloc(expmaxlen);
9212
9213 /* presume success */
9214 result = 0;
9215
9216 /* read the number of macros */
9217 cnt = fp->read_uint4();
9218
9219 /* read each macro */
9220 for (i = 0 ; i < cnt ; ++i)
9221 {
9222 char namebuf[TOK_SYM_MAX_LEN];
9223 size_t namelen;
9224 int flags;
9225 size_t argc;
9226 size_t explen;
9227 CTcHashEntryPp *entry;
9228 int has_args;
9229 int has_varargs;
9230
9231 /* read the name's length */
9232 namelen = fp->read_uint2();
9233 if (namelen > sizeof(namebuf))
9234 {
9235 /* log an error through the handler */
9236 err_handler->log_error(1);
9237
9238 /* give up - we can't read any more of the file */
9239 result = 1;
9240 goto done;
9241 }
9242
9243 /* read the name */
9244 fp->read_bytes(namebuf, namelen);
9245
9246 /* read and decode the flags */
9247 flags = fp->read_uint2();
9248 has_args = ((flags & 1) != 0);
9249 has_varargs = ((flags & 2) != 0);
9250
9251 /* read the number of arguments, and read each argument */
9252 argc = fp->read_uint2();
9253 for (curarg = 0 ; curarg < argc ; ++curarg)
9254 {
9255 /* read the length, and make sure it's valid */
9256 argvlen[curarg] = fp->read_uint2();
9257 if (argvlen[curarg] > TOK_SYM_MAX_LEN)
9258 {
9259 /* log an error */
9260 err_handler->log_error(2);
9261
9262 /* give up - we can't read any more of the file */
9263 result = 2;
9264 goto done;
9265 }
9266
9267 /*
9268 * if we haven't allocated a buffer for this argument slot yet,
9269 * allocate it now; allocate the buffer at the maximum symbol
9270 * size, so we can reuse the same buffer for an argument of
9271 * other macros we read later
9272 */
9273 while (curarg >= maxarg)
9274 argv[maxarg++] = (char *)t3malloc(TOK_SYM_MAX_LEN);
9275
9276 /* read the argument text */
9277 fp->read_bytes(argv[curarg], argvlen[curarg]);
9278 }
9279
9280 /* read the expansion size */
9281 explen = (size_t)fp->read_uint4();
9282
9283 /* expand the expansion buffer if necessary */
9284 if (explen > expmaxlen)
9285 {
9286 /*
9287 * overshoot a bit, so that we won't have to reallocate again
9288 * if we find a slightly larger expansion for a future macro
9289 */
9290 expmaxlen = explen + 512;
9291
9292 /* allocate the new buffer */
9293 expan = (char *)t3realloc(expan, expmaxlen);
9294 }
9295
9296 /* read the expansion */
9297 fp->read_bytes(expan, explen);
9298
9299 /*
9300 * Before we create the entry, check to see if there's an existing
9301 * entry with the same name.
9302 */
9303 entry = find_define(namebuf, namelen);
9304 if (entry != 0)
9305 {
9306 /*
9307 * We have another entry. If the entry is exactly the same,
9308 * then we can simply skip the current entry, because we simply
9309 * want to keep one copy of each macro that's defined
9310 * identically in mutiple compilation macros. If the entry is
9311 * different from the new one, delete both - a macro which
9312 * appears in two or more compilation units with different
9313 * meanings is NOT a global macro, and thus we can't include it
9314 * in the debugging records.
9315 */
9316 if (entry->is_pseudo()
9317 || entry->has_args() != has_args
9318 || entry->has_varargs() != has_varargs
9319 || entry->get_argc() != (int)argc
9320 || entry->get_orig_expan_len() != explen
9321 || memcmp(entry->get_orig_expansion(), expan, explen) != 0)
9322 {
9323 /*
9324 * The existing entry is different from the new entry, so
9325 * the macro has different meanings in different
9326 * compilation units, hence we cannot keep *either*
9327 * definition in the debug records. Delete the existing
9328 * macro, and do not create the new macro. If the existing
9329 * macro is a pseudo-macro, keep the old one (since it's
9330 * provided by the compiler itself), but still discard the
9331 * new one.
9332 */
9333 if (!entry->is_pseudo())
9334 undefine(namebuf, namelen);
9335 }
9336 else
9337 {
9338 /*
9339 * The new entry is identical to the old one, so keep it.
9340 * We only need one copy of the entry, though, so simply
9341 * keep the old one - there's no need to create a new entry
9342 * for the object file data.
9343 */
9344 }
9345 }
9346 else
9347 {
9348 /*
9349 * There's no existing macro with the same name, so create a
9350 * new entry based on the object file data.
9351 */
9352 entry = new CTcHashEntryPpDefine(namebuf, namelen, TRUE,
9353 has_args, argc, has_varargs,
9354 (const char **)argv, argvlen,
9355 expan, explen);
9356
9357 /* add it to the preprocessor's macro symbol table */
9358 add_define(entry);
9359 }
9360 }
9361
9362 done:
9363 /* free the argument buffers we allocated */
9364 for (curarg = 0 ; curarg < maxarg ; ++curarg)
9365 t3free(argv[curarg]);
9366
9367 /* free the expansion buffer */
9368 t3free(expan);
9369
9370 /* success */
9371 return result;
9372 }
9373
9374 /* ------------------------------------------------------------------------ */
9375 /*
9376 * Callback context for writing enumerated #define symbols to a file
9377 */
9378 struct write_macro_ctx_t
9379 {
9380 /* object file we're writing to */
9381 CVmFile *fp;
9382
9383 /* number of symbols written so far */
9384 unsigned long cnt;
9385 };
9386
9387 /*
9388 * Enumeration callback for writing the #define symbols to a file
9389 */
9390 static void write_macros_cb(void *ctx0, CTcHashEntryPp *entry)
9391 {
9392 write_macro_ctx_t *ctx = (write_macro_ctx_t *)ctx0;
9393 int flags;
9394 int i;
9395 CVmFile *fp = ctx->fp;
9396
9397 /*
9398 * if this is a pseudo-macro (such as __LINE__ or __FILE__), ignore it
9399 * - these macros do not have permanent global definitions, so they're
9400 * not usable in the debugger
9401 */
9402 if (entry->is_pseudo())
9403 return;
9404
9405 /*
9406 * If the macro was ever redefined or undefined, ignore it - the
9407 * debugger can only use truly global macros, which are macros that
9408 * have stable meanings throughout the compilation units where they
9409 * appear (and which do not have different meanings in different
9410 * compilation units, but that's not our concern at the moment). The
9411 * preprocessor keeps an "undef" table of everything undefined
9412 * (explicitly, or implicitly via redefinition), so look up this macro
9413 * in the undef table, and ignore the macro if it we find it.
9414 */
9415 if (G_tok->find_undef(entry->getstr(), entry->getlen()) != 0)
9416 return;
9417
9418 /* count this macro */
9419 ctx->cnt++;
9420
9421 /* write the macro's name */
9422 fp->write_uint2(entry->getlen());
9423 fp->write_bytes(entry->getstr(), entry->getlen());
9424
9425 /* write the flag bits */
9426 flags = 0;
9427 if (entry->has_args()) flags |= 1;
9428 if (entry->has_varargs()) flags |= 2;
9429 fp->write_uint2(flags);
9430
9431 /* write the number of arguments, and write each argument */
9432 fp->write_uint2(entry->get_argc());
9433 for (i = 0 ; i < entry->get_argc() ; ++i)
9434 {
9435 CTcHashEntryPpArg *arg;
9436
9437 /* get the argument */
9438 arg = entry->get_arg_entry(i);
9439
9440 /* write the parameter name */
9441 fp->write_uint2(arg->getlen());
9442 fp->write_bytes(arg->getstr(), arg->getlen());
9443 }
9444
9445 /* write the expansion */
9446 fp->write_uint4(entry->get_orig_expan_len());
9447 fp->write_bytes(entry->get_orig_expansion(), entry->get_orig_expan_len());
9448 }
9449
9450 /*
9451 * Write all #define symbols to a file, for debugging purposes. Writes
9452 * only symbols that have never been undefined or redefined, since the
9453 * debugger can only make use of global symbols (i.e., symbols with
9454 * consistent meanings through all compilation units in which they
9455 * appear).
9456 */
9457 void CTcTokenizer::write_macros_to_file_for_debug(CVmFile *fp)
9458 {
9459 long pos;
9460 long endpos;
9461 write_macro_ctx_t ctx;
9462
9463 /* write a placeholder for the symbol count */
9464 pos = fp->get_pos();
9465 fp->write_uint4(0);
9466
9467 /* write the symbols */
9468 ctx.fp = fp;
9469 ctx.cnt = 0;
9470 enum_defines(&write_macros_cb, &ctx);
9471
9472 /* go back and fix up the symbol count */
9473 endpos = fp->get_pos();
9474 fp->set_pos(pos);
9475 fp->write_uint4(ctx.cnt);
9476
9477 /* seek back to where we left off */
9478 fp->set_pos(endpos);
9479 }