Debian Codegraph @

packages/seacas/libraries/aprepro_lib/aprepro.ll

raw
1 s"}/* -*- Mode: c++ -*- */
2
3 /*
4 * Copyright(C) 1999-2024 National Technology & Engineering Solutions
5 * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
6 * NTESS, the U.S. Government retains certain rights in this software.
7 *
8 * See packages/seacas/LICENSE for details
9 */
10
11
12 %{
13
14 #include <assert.h>
15 #include <fstream>
16 #include <iostream>
17 #include <sstream>
18 #include <stack>
19 #include <stdio.h>
20 #include <string.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23
24 #include "apr_scanner.h"
25 #include "aprepro.h"
26 #include "apr_util.h"
27 #include "apr_getline.h"
28 #include "apr_tokenize.h"
29 #include "fmt/format.h"
30 #include "fmt/ostream.h"
31
32
33 #define YY_NO_UNISTD_H
34 /* import the parser's token type into a local typedef */
35 typedef SEAMS::Parser::token token;
36 typedef SEAMS::Parser::token_type token_type;
37
38 /* By default yylex returns int, we use token_type. Unfortunately yyterminate
39 * by default returns 0, which is not of token_type. */
40 #define yyterminate() return token::END
41
42 #define show(x) *(aprepro->infoStream) << "<" << x << ">" << std::flush;
43 namespace SEAMS {
44 extern bool echo;
45 void yyerror(const char *s);
46 }
47
48 namespace {
49 bool begin_double_brace = false;
50 bool end_double_brace = false;
51 bool string_is_ascii(const char *line, size_t len)
52 {
53 for (size_t i = 0; i < len; i++) {
54 if (!(std::isspace(static_cast<unsigned char>(line[i])) || std::isprint(static_cast<unsigned char>(line[i])))) {
55 return false;
56 }
57 }
58 return true;
59 }
60 } // namespace
61
62 int file_must_exist = 0; /* Global used by include/conditional include */
63
64 /* Global variables used by the looping mechanism */
65 SEAMS::file_rec *outer_file = nullptr;
66 int loop_lvl = 0;
67 std::fstream *tmp_file;
68 const char *temp_f;
69
70 #if defined __NVCC__
71 #pragma diag_suppress code_is_unreachable
72 #endif
73
74 #define MAX_IF_NESTING 1024
75
76 int if_state[MAX_IF_NESTING] = {0}; // INITIAL
77 int if_case_run[MAX_IF_NESTING] = {false}; /* Has any if or elseif condition executed */
78 int if_lvl = 0;
79 int if_skip_level = 0;
80 bool suppress_nl = false;
81 bool switch_active = false; // Are we in a switch
82 bool switch_case_run = false; // has there been a case which matched condition run?
83 bool switch_skip_to_endcase = false;
84 double switch_condition = 0.0; // Value specified in "switch(condition)"
85
86 // For substitution history
87 size_t curr_index = 0;
88 std::string history_string;
89 size_t hist_start = 0;
90
91 #define YY_USER_ACTION curr_index += yyleng;
92
93 %}
94 /*** Flex Declarations and Options ***/
95
96 /* enable c++ scanner class generation */
97 %option c++
98
99 /* change the name of the scanner class. results in "SEAMSFlexLexer" */
100 %option prefix="SEAMS"
101
102 /* enable scanner to generate debug output. disable this for release
103 * versions. */
104 %option debug
105
106 /* enables the use of start condition stacks */
107 %option stack
108
109 qstring \"[^\"\n]*[\"\n]
110 mlstring \'[^\']*[\']
111 D [0-9]
112 E [Ee][+-]?{D}+
113 L [A-Za-z_]
114 id {L}({L}|{D}|:)*
115 WS [ \t\f]*
116 NL "\n"
117 number {D}*\.({D}+)?({E})?
118 integer {D}+({E})?
119
120 %START PARSING GET_FILENAME IF_SKIP GET_VAR VERBATIM IF_WHILE_SKIP GET_LOOP_VAR LOOP LOOP_SKIP END_CASE_SKIP
121
122 %%
123 <VERBATIM>{
124 "{VERBATIM(OFF)}" { BEGIN(INITIAL); }
125 [A-Za-z0-9_ ]* |
126 . { if (echo) ECHO; }
127 "\n" { if (echo) ECHO; aprepro.ap_file_list.top().lineno++; }
128 }
129
130 <INITIAL>{
131 "{VERBATIM(ON)}" { BEGIN(VERBATIM); }
132 {WS}"{ECHO}" |
133 {WS}"{ECHO(ON)}" { echo = true; }
134 {WS}"{NOECHO}" |
135 {WS}"{ECHO(OFF)}" { echo = false; }
136
137 {WS}"{IMMUTABLE(ON)}" { aprepro.stateImmutable = true; }
138 {WS}"{IMMUTABLE(OFF)}" { aprepro.stateImmutable = aprepro.ap_options.immutable; }
139
140 {WS}"{"[Ll]"oop"{WS}"(" {
141 BEGIN(GET_LOOP_VAR);
142 }
143 }
144
145 <GET_LOOP_VAR>{
146 .+")}".*"\n" {
147 aprepro.ap_file_list.top().lineno++;
148 /* `yytext` includes closing `)}` and newline... Strip these */
149 char *pt = strchr(yytext, ')');
150 *pt = '\0';
151 auto tokens = tokenize(yytext, " ,\t");
152 if (aprepro.ap_options.debugging) {
153 fmt::print(stderr, "DEBUG LOOP: tokens = {}\n",
154 fmt::join(tokens, ", "));
155 }
156
157 /* Determine if the first token is a symbol or an explicit number... */
158 auto count = tokens[0];
159 bool all_dig = count.find_first_not_of("0123456789") == std::string::npos;
160 int loop_iterations = 0;
161 if (all_dig) {
162 loop_iterations = std::stoi(count);
163 }
164 else {
165 symrec *s;
166 if (!check_valid_var(tokens[0].c_str())) {
167 aprepro.warning("Invalid variable name syntax '" + tokens[0] + "'");
168 BEGIN(LOOP_SKIP);
169 } else {
170 s = aprepro.getsym(tokens[0]);
171 if (s == nullptr || (s->type != token::SVAR && s->type != token::IMMSVAR && s->value.var == 0.)) {
172 BEGIN(LOOP_SKIP);
173 }
174 else {
175 loop_iterations = (int)s->value.var;
176 }
177 }
178 }
179
180 if (loop_iterations <= 0) {
181 BEGIN(LOOP_SKIP);
182 if (aprepro.ap_options.debugging) {
183 fmt::print(
184 stderr,
185 "DEBUG LOOP: iteration count = {}, Skipping loop...\n", loop_iterations);
186 }
187 }
188 else {
189 temp_f = get_temp_filename();
190 SEAMS::file_rec new_file(temp_f, 0, true, loop_iterations);
191 outer_file = &aprepro.ap_file_list.top();
192 new_file.loop_level = outer_file->loop_level + 1;
193
194 // Get optional loop index...
195 std::string sym_name;
196 if (tokens.size() == 1) {
197 // Default loop index variable name if not specified in loop command.
198 sym_name = fmt::format("__loop_{}", new_file.loop_level);
199 }
200 else {
201 sym_name = tokens[1];
202 }
203 SEAMS::symrec *li = aprepro.getsym(sym_name);
204 if (li == nullptr) {
205 li = aprepro.putsym(sym_name, SEAMS::Aprepro::SYMBOL_TYPE::VARIABLE, true);
206 }
207
208 // Get optional loop index initial value. Default to 0 if not specified.
209 double init = 0.0;
210 if (tokens.size() >= 3) {
211 init = std::stod(tokens[2]);
212 }
213 li->value.var = init;
214
215 // Get optional loop index increment value. Default to 1 if not specified.
216 if (tokens.size() >= 4) {
217 double increment = std::stod(tokens[3]);
218 new_file.loop_increment = increment;
219 }
220
221 new_file.loop_index = li;
222 aprepro.ap_file_list.push(new_file);
223
224 tmp_file = new std::fstream(temp_f, std::ios::out);
225 loop_lvl++;
226 BEGIN(LOOP);
227 aprepro.isCollectingLoop = true;
228 if (aprepro.ap_options.debugging) {
229 fmt::print(stderr, "DEBUG LOOP: iteration count = {}, loop_index variable = {}, initial value = {}, increment = {}\n",
230 loop_iterations, sym_name, init, new_file.loop_increment);
231 }
232 }
233 }
234 }
235
236 <LOOP>{
237 {WS}"{"[Ee]"nd"[Ll]"oop".*"\n" {
238 outer_file->lineno++;
239 if(loop_lvl > 0)
240 --loop_lvl;
241
242 if (loop_lvl == 0) {
243 BEGIN(INITIAL);
244 tmp_file->close();
245 delete tmp_file;
246
247 if(!aprepro.doLoopSubstitution)
248 yy_push_state(VERBATIM);
249
250 aprepro.isCollectingLoop = false;
251
252 yyin = aprepro.open_file(aprepro.ap_file_list.top().name, "r");
253 yyFlexLexer::yypush_buffer_state (yyFlexLexer::yy_create_buffer( yyin, YY_BUF_SIZE));
254 curr_index = 0;
255 }
256 else {
257 (*tmp_file) << yytext;
258 }
259 }
260
261 {WS}"{"[Ll]"oop"{WS}"(".*"\n" {
262 loop_lvl++; /* Nested Loop */
263 (*tmp_file) << yytext;
264 outer_file->lineno++;
265 }
266
267 {WS}"{"[Aa]"bort"[Ll]"oop".*"\n" {
268 if(aprepro.ap_options.interactive ||
269 aprepro.string_interactive())
270 {
271 aprepro.warning("Aborting loop(s).", false);
272
273 // Leave the looping state and remove the loop file
274 BEGIN(INITIAL);
275 tmp_file->close();
276 delete tmp_file;
277
278 if(aprepro.ap_file_list.top().tmp_file) {
279 remove(aprepro.ap_file_list.top().name.c_str());
280 aprepro.ap_file_list.pop();
281 }
282
283 loop_lvl = 0;
284 aprepro.isCollectingLoop = false;
285 }
286 }
287
288 .*"\n" {
289 (*tmp_file) << yytext;
290 outer_file->lineno++;
291 }
292 }
293
294 <LOOP_SKIP>{
295 {WS}"{"[Ee]"nd"[Ll]"oop".*"\n" {
296 aprepro.ap_file_list.top().lineno++;
297 if(loop_lvl > 0)
298 --loop_lvl;
299
300 if (loop_lvl == 0) {
301 BEGIN(INITIAL);
302 aprepro.isCollectingLoop = false;
303 }
304 }
305
306 {WS}"{"[Ll]"oop"{WS}"(".*"\n" {
307 loop_lvl++; /* Nested Loop */
308 aprepro.ap_file_list.top().lineno++;
309 }
310
311 {WS}"{"[Aa]"bort"[Ll]"oop".*"\n" {
312 if(aprepro.ap_options.interactive ||
313 aprepro.string_interactive())
314 {
315 aprepro.warning("Aborting loops(s).", false);
316
317 // Leave the looping state
318 BEGIN(INITIAL);
319
320 loop_lvl = 0;
321 aprepro.isCollectingLoop = false;
322 }
323 }
324
325 .*"\n" { /* Do not increment line count */
326 ;
327 }
328 }
329
330 <END_CASE_SKIP>{WS}"{"{WS}"case".*"\n" {
331 yyless(0);
332 curr_index = 0;
333 BEGIN(INITIAL);
334 switch_skip_to_endcase = false;
335 }
336
337 <INITIAL,END_CASE_SKIP>{WS}"{"{WS}"default"{WS}"}".*"\n" {
338 if (!switch_active) {
339 yyerror("default statement found outside switch statement.");
340 }
341
342 if (!switch_case_run) {
343 switch_case_run = true;
344 BEGIN(INITIAL);
345 switch_skip_to_endcase = false;
346 if (aprepro.ap_options.debugging)
347 fprintf (stderr, "DEBUG SWITCH: 'default' code executing at line %d\n",
348 aprepro.ap_file_list.top().lineno);
349 }
350 else {
351 if (aprepro.ap_options.debugging)
352 fprintf (stderr, "DEBUG SWITCH: 'default' not executing since a previous case already ran at line %d\n",
353 aprepro.ap_file_list.top().lineno);
354
355 /* Need to skip all code until end of case */
356 BEGIN(END_CASE_SKIP);
357 }
358 }
359
360 <END_CASE_SKIP>{WS}"{"{WS}"endswitch"{WS}"}".*"\n" {
361 aprepro.ap_file_list.top().lineno++;
362 BEGIN(INITIAL);
363 switch_active = false;
364 switch_skip_to_endcase = false;
365 suppress_nl = false;
366 if (aprepro.ap_options.debugging)
367 fprintf (stderr, "DEBUG SWITCH: 'endswitch' at line %d\n",
368 aprepro.ap_file_list.top().lineno);
369 }
370
371 <END_CASE_SKIP>.*"\n" { aprepro.ap_file_list.top().lineno++; }
372
373 <INITIAL>{WS}"{"{WS}"endswitch"{WS}"}".*"\n" {
374 aprepro.ap_file_list.top().lineno++;
375 if (!switch_active) {
376 yyerror("endswitch statement found without matching switch.");
377 }
378 switch_active = false;
379 switch_skip_to_endcase = false;
380 }
381
382 <INITIAL>{
383 /* This restores the old behavior of ifdef and ifndef
384 * where they would eat up any leading whitespace on
385 * a line.
386 */
387 {WS}"{"[Ii]"fdef"{WS}"(" {
388 // Used to avoid undefined variable warnings in old ifdef/ifndef construct
389 aprepro.inIfdefGetvar = true;
390 unput('(');
391 unput('f');
392 unput('e');
393 unput('d');
394 unput('f');
395 unput('i');
396 unput('_');
397 unput('{');
398 curr_index = 0;
399 }
400
401 {WS}"{"[Ii]"fndef"{WS}"(" {
402 // Used to avoid undefined variable warnings in old ifdef/ifndef construct
403 aprepro.inIfdefGetvar = true;
404 unput('(');
405 unput('f');
406 unput('e');
407 unput('d');
408 unput('n');
409 unput('f');
410 unput('i');
411 unput('_');
412 unput('{');
413 curr_index = 0;
414 }
415 }
416
417 <IF_WHILE_SKIP>{
418 /* If an if was found while skipping, then eat
419 * that entire if block until endif
420 * found since there is no way that
421 * any of the code in that if block could be executed.
422 * Make sure to handle multiple levels of skipped ifs...
423 *
424 * NOTE: if_lvl was not incremented, so don't need to decrement when
425 * endif found.
426 */
427 {WS}"{"[Ee]"nd"[Ii]"f}".*"\n" {
428 aprepro.ap_file_list.top().lineno++;
429 if (--if_skip_level == 0)
430 BEGIN(IF_SKIP);
431 }
432
433 {WS}"{"[Ii]"fdef"{WS}"(".*"\n" {
434 aprepro.ap_file_list.top().lineno++;
435 if_skip_level++;
436 }
437
438 {WS}"{"[Ii]"f"{WS}"(".*"\n" {
439 aprepro.ap_file_list.top().lineno++;
440 if_skip_level++;
441 }
442
443 {WS}"{"[Ii]"fndef"{WS}"(".*"\n" {
444 aprepro.ap_file_list.top().lineno++;
445 if_skip_level++;
446 }
447
448 .*"\n" {
449 aprepro.ap_file_list.top().lineno++;
450 }
451 }
452
453 <IF_SKIP>{
454 /* IF an if, ifdef, or ifndef found while skipping, then
455 * skip the entire block up and including the endif.
456 * The (IF_WHILE_SKIP) start condition handles this skipping.
457 */
458 {WS}"{"[Ii]"fdef"{WS}"(" {
459 if (aprepro.ap_options.debugging)
460 fprintf (stderr, "DEBUG IF: 'ifdef' found while skipping at line %d\n",
461 aprepro.ap_file_list.top().lineno);
462 if_skip_level = 1;
463 BEGIN(IF_WHILE_SKIP);
464 }
465
466 {WS}"{"[Ii]"f"{WS}"(" {
467 if (aprepro.ap_options.debugging)
468 fprintf (stderr, "DEBUG IF: 'ifdef' found while skipping at line %d\n",
469 aprepro.ap_file_list.top().lineno);
470 if_skip_level = 1;
471 BEGIN(IF_WHILE_SKIP);
472 }
473
474 {WS}"{"[Ii]"fndef"{WS}"(" {
475 if (aprepro.ap_options.debugging)
476 fprintf (stderr, "DEBUG IF: 'ifndef' found while skipping at line %d\n",
477 aprepro.ap_file_list.top().lineno);
478 if_skip_level = 1;
479 BEGIN(IF_WHILE_SKIP);
480 }
481 }
482
483 {WS}"{"[Ee]"lse}".*"\n" {
484 aprepro.ap_file_list.top().lineno++;
485 if (aprepro.ap_options.debugging)
486 fprintf (stderr, "DEBUG IF: 'else' at level = %d at line %d\n",
487 if_lvl, aprepro.ap_file_list.top().lineno);
488 if(YY_START == VERBATIM) {
489 if(echo) ECHO;
490 }
491 else if (if_state[if_lvl] == IF_SKIP) {
492 if (!if_case_run[if_lvl]) {
493 BEGIN(INITIAL);
494 if_state[if_lvl] = INITIAL;
495 if_case_run[if_lvl] = true;
496 } else {
497 BEGIN(IF_SKIP);
498 if_state[if_lvl] = IF_SKIP;
499 }
500 }
501 else if (if_state[if_lvl] == INITIAL) {
502 BEGIN(IF_SKIP);
503 if_state[if_lvl] = IF_SKIP;
504 }
505
506 /* If neither is true, this is a nested
507 if that should be skipped */
508 }
509
510 <IF_SKIP>{
511 {WS}"{"{WS}[Ee]"lse"[Ii]"f".*"\n" {
512 /* If any previous 'block' of this if has executed, then
513 * just skip this block; otherwise see if condition is
514 * true and execute this block
515 */
516 if (aprepro.ap_options.debugging)
517 fprintf (stderr, "DEBUG IF: 'elseif' at level = %d at line %d\n",
518 if_lvl, aprepro.ap_file_list.top().lineno);
519
520 if (if_case_run[if_lvl]) { /* A previous else/elseif has run */
521 aprepro.ap_file_list.top().lineno++;
522 /* Already in IF_SKIP, so don't need to change state */
523 } else {
524 /* Need to check the elseif condition; push back and parse */
525 yyless(0);
526 curr_index = 0;
527 BEGIN(INITIAL);
528 if_state[if_lvl] = INITIAL;
529 }
530 }
531
532 [A-Za-z0-9_ ]* |
533 \\\{ |
534 \\\} |
535 . { ; }
536
537 "\n" {
538 aprepro.ap_file_list.top().lineno++;
539 }
540 }
541
542 {WS}"{"[Ee]"nd"[Ii]"f}".*"\n" {
543
544 if(YY_START == VERBATIM) {
545 if(echo) ECHO;
546 }
547 else {
548 if (if_state[if_lvl] == IF_SKIP ||
549 if_state[if_lvl] == INITIAL) {
550 BEGIN(INITIAL);
551 suppress_nl = false;
552 }
553 /* If neither is true, this is a nested
554 if that should be skipped */
555 if (aprepro.ap_options.debugging)
556 printf ("DEBUG IF: 'endif' at level = %d at line %d\n",
557 if_lvl, aprepro.ap_file_list.top().lineno);
558 if (--if_lvl < 0) {
559 if_lvl = 0;
560 yyerror("Improperly Nested ifdef/ifndef statements");
561 }
562 /* Ignore endif if not skipping */
563 }
564 aprepro.ap_file_list.top().lineno++;
565 }
566
567 <INITIAL>{WS}"{"[Ii]"nclude"{WS}"(" { BEGIN(GET_FILENAME);
568 file_must_exist = true; }
569 <INITIAL>{WS}"{"[Cc]"include"{WS}"(" { BEGIN(GET_FILENAME);
570 file_must_exist = false; }
571 <GET_FILENAME>.+")"{WS}"}"{NL}* {
572 aprepro.ap_file_list.top().lineno++;
573 BEGIN(INITIAL);
574 {
575 symrec *s;
576 int quoted = 0;
577 char *pt = strchr(yytext, ')');
578 *pt = '\0';
579 /* Check to see if surrounded by double quote */
580 if ((pt = strchr(yytext, '"')) != nullptr) {
581 yytext++;
582 quoted = 1;
583 }
584 if ((pt = strrchr(yytext, '"')) != nullptr) {
585 *pt = '\0';
586 quoted = 1;
587 }
588
589 if (quoted == 0) {
590 /* See if this is an aprepro variable referring to a name */
591 s = aprepro.getsym(yytext);
592 if (s == nullptr || (s->type != token::SVAR && s->type != token::IMMSVAR)) {
593 pt = yytext;
594 } else {
595 pt = (char*)s->value.svar.c_str();
596 }
597 } else {
598 pt = yytext;
599 }
600
601 bool added = add_include_file(pt, file_must_exist);
602
603 if(added && !aprepro.doIncludeSubstitution)
604 yy_push_state(VERBATIM);
605
606 aprepro.ap_file_list.top().lineno++;
607 }
608 }
609
610 <PARSING>{integer} |
611 <PARSING>{number} { sscanf (yytext, "%lf", &yylval->val);
612 return(token::NUM); }
613
614 <PARSING>{WS} ; // Empty rule
615
616 <PARSING>{id} {
617 symrec *s;
618 s = aprepro.getsym(yytext);
619 if (s == nullptr)
620 s = aprepro.putsym (yytext, SEAMS::Aprepro::SYMBOL_TYPE::UNDEFINED_VARIABLE, false);
621 yylval->tptr = s;
622 return((token::yytokentype)s->type);
623 }
624 <PARSING>"=" return(token::EQUAL);
625 <PARSING>"+=" return(token::EQ_PLUS);
626 <PARSING>"-=" return(token::EQ_MINUS);
627 <PARSING>"*=" return(token::EQ_TIME);
628 <PARSING>"/=" return(token::EQ_DIV);
629 <PARSING>"^=" return(token::EQ_POW);
630 <PARSING>"**=" return(token::EQ_POW);
631 <PARSING>"++" return(token::INC);
632 <PARSING>"--" return(token::DEC);
633 <PARSING>"+" return(token::PLU);
634 <PARSING>"-" return(token::SUB);
635 <PARSING>"*" return(token::TIM);
636 <PARSING>"~" return(token::TIM); /* ~ is same as multiply */
637 <PARSING>"//" return(token::CONCAT); /* String concatenation */
638 <PARSING>"/" return(token::DIV);
639 <PARSING>"%" return(token::MOD);
640 <PARSING>"^" return(token::POW);
641 <PARSING>"**" return(token::POW);
642 <PARSING>"\n" aprepro.ap_file_list.top().lineno++;
643 <PARSING>"(" return(token::LPAR);
644 <PARSING>")" return(token::RPAR);
645 <PARSING>"," return(token::COMMA);
646 <PARSING>";" return(token::SEMI);
647 <PARSING>":" return(token::COLON);
648 <PARSING>"?" return(token::QUEST);
649 <PARSING>"<" return(token::LT);
650 <PARSING>">" return(token::GT);
651 <PARSING>"<=" return(token::LE);
652 <PARSING>">=" return(token::GE);
653 <PARSING>"==" return(token::EQ);
654 <PARSING>"!=" return(token::NE);
655 <PARSING>"&&" return(token::LAND);
656 <PARSING>"||" return(token::LOR);
657 <PARSING>"!" return(token::NOT);
658 <PARSING>"[" return(token::LBRACK);
659 <PARSING>"]" return(token::RBRACK);
660 <PARSING>{qstring} {
661 char *pt = strrchr(yytext, '"');
662 *pt = '\0';
663 new_string(yytext+1, &yylval->string);
664 return token::QSTRING; }
665
666 <PARSING>{mlstring} {
667 char *pt = strrchr(yytext, '\'');
668 *pt = '\0';
669 new_string(yytext+1, &yylval->string);
670 return token::QSTRING; }
671
672 <PARSING>"}" {
673 // Add to the history string
674 save_history_string();
675
676 if (switch_skip_to_endcase)
677 BEGIN(END_CASE_SKIP);
678 else
679 BEGIN(if_state[if_lvl]);
680 return(token::RBRACE);
681 }
682
683
684 <PARSING>"}}" {
685 if (begin_double_brace) {
686 end_double_brace = true;
687 }
688 else {
689 yyerror("Found an unexpected double end brace ('}}').\n\t"
690 "It can only end an expression started with a double brace ('{{').\n\tCheck syntax.");
691 }
692
693 // Add to the history string
694 save_history_string();
695
696 if (switch_skip_to_endcase)
697 BEGIN(END_CASE_SKIP);
698 else
699 BEGIN(if_state[if_lvl]);
700 unput('}');
701 unput('O');
702 unput('H');
703 unput('C');
704 unput('E');
705 unput('{');
706 return(token::RBRACE);
707 }
708
709
710 \\\{ { if (echo) LexerOutput("{", 1); }
711
712 \\\} { if (echo) LexerOutput("}", 1); }
713
714 "{{" {
715 // Check if we need to save the substitution history first.
716 if(aprepro.ap_options.keep_history &&
717 (aprepro.ap_file_list.top().name != "_string_"))
718 {
719 if (curr_index > yyleng)
720 hist_start = curr_index - yyleng;
721 else
722 hist_start = 0;
723 }
724
725 BEGIN(PARSING);
726 echo = false;
727 begin_double_brace = true;
728 return(token::LBRACE);
729 }
730
731 "{" {
732 // Check if we need to save the substitution history first.
733 if(aprepro.ap_options.keep_history &&
734 (aprepro.ap_file_list.top().name != "_string_"))
735 {
736 if (curr_index > yyleng)
737 hist_start = curr_index - yyleng;
738 else
739 hist_start = 0;
740 }
741
742 BEGIN(PARSING);
743
744 return(token::LBRACE);
745 }
746
747 [Ee][Xx][Ii][Tt] |
748 [Qq][Uu][Ii][Tt] {
749 if (aprepro.ap_options.end_on_exit) {
750 if (echo) ECHO;
751 return((token::yytokentype)-1);
752 }
753 else
754 if (echo) ECHO;
755 }
756
757
758 \$ { if (echo) ECHO; }
759
760
761 {id} |
762 . { if (echo && if_state[if_lvl] != IF_SKIP) ECHO; }
763
764 "\n" { if (echo && !suppress_nl) ECHO; suppress_nl = false;
765 if (end_double_brace) {
766 echo = true;
767 begin_double_brace = false;
768 end_double_brace = false;
769 }
770 aprepro.ap_file_list.top().lineno++;
771 }
772
773 %%
774
775 /* When the scanner receives an end-of-file indication from YY_INPUT, it then
776 * checks the yywrap() function. If yywrap() returns false (zero), then it is
777 * assumed that the function has gone ahead and set up `yyin' to point to
778 * another input file, and scanning continues. If it returns true (non-zero),
779 * then the scanner terminates, returning 0 to its caller. */
780
781 namespace SEAMS
782 {
783
784 Scanner::Scanner(Aprepro & aprepro_yyarg, std::istream * in, std::ostream * out)
785 : SEAMSFlexLexer(in, out), aprepro(aprepro_yyarg)
786 {
787 aprepro.outputStream.push(out);
788 }
789
790 Scanner::~Scanner() {
791 while (aprepro.ap_file_list.size() > 1) {
792 auto kk = aprepro.ap_file_list.top();
793 if (kk.name != "STDIN") {
794 yyFlexLexer::yy_load_buffer_state();
795 delete yyin;
796 yyin = nullptr;
797 }
798 aprepro.ap_file_list.pop();
799 yyFlexLexer::yypop_buffer_state();
800 };
801 }
802
803 bool Scanner::add_include_file(const std::string &filename, bool must_exist)
804 {
805 std::fstream *yytmp = nullptr;
806 if (must_exist)
807 yytmp = aprepro.open_file(filename, "r");
808 else
809 yytmp = aprepro.check_open_file(filename, "r");
810
811 if (yytmp) {
812 if (yyin && !yy_init) {
813 yyFlexLexer::yypush_buffer_state(yyFlexLexer::yy_create_buffer(yyin, YY_BUF_SIZE));
814 }
815
816 yyin = yytmp;
817 aprepro.info("Included File: '" + filename + "'", true);
818
819 SEAMS::file_rec new_file(filename.c_str(), 0, false, 0);
820 aprepro.ap_file_list.push(new_file);
821
822 yyFlexLexer::yypush_buffer_state(yyFlexLexer::yy_create_buffer(yytmp, YY_BUF_SIZE));
823 curr_index = 0;
824 }
825 return yytmp != nullptr;
826 }
827
828 void Scanner::LexerOutput(const char *buf, int size)
829 {
830 // Do this before writing so that we have the correct index in the
831 // output stream.
832 if (aprepro.ap_options.keep_history) {
833 aprepro.add_history(history_string, buf);
834 history_string.clear();
835 hist_start = 0;
836 }
837
838 aprepro.outputStream.top()->write(buf, size);
839 if (aprepro.ap_options.interactive && aprepro.outputStream.size() == 1) {
840 // In interactive mode, output to stdout in addition to the
841 // output stream, unless user has redirected output...
842 std::cout << buf;
843 }
844 }
845
846 int Scanner::LexerInput(char *buf, int max_size)
847 {
848 if (yyin->eof() || yyin->fail()) {
849 return 0;
850 }
851
852 if (aprepro.ap_options.interactive && yyin == &std::cin && isatty(0) != 0 && isatty(1) != 0) {
853 char *line = SEAMS::getline_int(nullptr);
854
855 if (strlen(line) == 0) {
856 return 0;
857 }
858
859 if (!string_is_ascii(line, strlen(line))) {
860 aprepro.warning("input line contains non-ASCII (probably UTF-8) characters which might be parsed incorrectly.");
861 }
862
863 SEAMS::gl_histadd(line);
864
865 if (strlen(line) > (size_t)max_size - 2) {
866 yyerror("input line is too long");
867 return 0;
868 }
869
870 strcpy(buf, line);
871 strcat(buf, "\n");
872
873 return strlen(buf);
874 }
875 else {
876 (void)yyin->read(buf, max_size);
877
878 if (yyin->bad()) {
879 return -1;
880 }
881 else {
882 if (!string_is_ascii(buf, yyin->gcount())) {
883 aprepro.warning("input file contains non-ASCII (probably UTF-8) characters which will might be parsed incorrectly.");
884 }
885 return yyin->gcount();
886 }
887 }
888 }
889
890 int Scanner::yywrap()
891 {
892 // Clear the history string.
893 history_string.clear();
894 hist_start = 0;
895 curr_index = 0;
896
897 // If we are using the string interactive method, we want to return to
898 // our original state if parsing was cutoff prematurely.
899 if (aprepro.string_interactive() && YY_START == PARSING) {
900 if (switch_skip_to_endcase) {
901 BEGIN(END_CASE_SKIP);
902 }
903 else {
904 BEGIN(if_state[if_lvl]);
905 }
906 }
907
908 if (aprepro.ap_file_list.size() <= 1) { /* End of main file, not in nested include */
909 return (1);
910 }
911 else if (aprepro.string_interactive() && loop_lvl) {
912 return (1);
913 }
914 else if (aprepro.isCollectingLoop) {
915 yyerror("End-of-file detected inside loop. Check loop syntax. {endloop} must be on line by "
916 "itself.");
917 return (1);
918 }
919 else {
920 /* We are in an included or looping file */
921 if (aprepro.ap_file_list.top().tmp_file) {
922 if (aprepro.ap_options.debugging) {
923 std::cerr << "DEBUG LOOP: Loop count = " << aprepro.ap_file_list.top().loop_count << "\n";
924 }
925 if (--aprepro.ap_file_list.top().loop_count <= 0) {
926 // On Windows, you can't remove the temp file until all the references to the
927 // file object have been released, so we will delete it here.
928 delete yyin;
929 yyin = nullptr;
930
931 if (aprepro.ap_file_list.top().name != "_string_") {
932 if (!aprepro.ap_options.debugging) {
933 remove(aprepro.ap_file_list.top().name.c_str()); /* Delete file if temporary */
934 }
935 if (!aprepro.doLoopSubstitution) {
936 yy_pop_state();
937 }
938 }
939
940 aprepro.ap_file_list.pop();
941 yyFlexLexer::yypop_buffer_state();
942 }
943 else {
944 // Do not pop ap_file_list; we are rereading that file...
945 delete yyin;
946 yyin = nullptr;
947 yyFlexLexer::yypop_buffer_state();
948 yyin = aprepro.open_file(aprepro.ap_file_list.top().name, "r");
949 yyFlexLexer::yypush_buffer_state(yyFlexLexer::yy_create_buffer(yyin, YY_BUF_SIZE));
950 aprepro.ap_file_list.top().lineno = 0;
951
952 if (aprepro.ap_file_list.top().loop_index != nullptr) {
953 aprepro.ap_file_list.top().loop_index->value.var += aprepro.ap_file_list.top().loop_increment;
954 }
955 }
956 }
957 else {
958 delete yyin;
959 yyin = nullptr;
960 aprepro.ap_file_list.pop();
961 yyFlexLexer::yypop_buffer_state();
962
963 if (aprepro.ap_file_list.top().name == "standard input") {
964 yyin = &std::cin;
965 }
966
967 /* Turn echoing back on at end of included files. */
968 echo = true;
969
970 // If we are not doing aprepro substitutions for the included file, but
971 // just collecting lines, pop the state from VERBATIM back to what it
972 // was previously.
973 if (!aprepro.doIncludeSubstitution) {
974 yy_pop_state();
975 }
976
977 /* Set immutable mode back to global immutable
978 * state at end of included file*/
979 aprepro.stateImmutable = aprepro.ap_options.immutable;
980 }
981
982 // Reset the current character index.
983 curr_index = 0;
984 if (yyin != nullptr) {
985 curr_index = yyin->tellg();
986 }
987
988 return (0);
989 }
990 }
991
992 /* Print error message to standard error and return. Note: internally
993 * 'lineno' starts at zero. To avoid confusion, we add 1 to value
994 * when it is output.
995 */
996
997 void Scanner::yyerror(const char *s) { aprepro.error(s); }
998
999 char *Scanner::execute(char string[])
1000 {
1001 /* Push the contents of 'string' onto the stack to be reread.
1002 * 'string' will be surrounded by {} so it must be a valid expression.
1003 */
1004
1005 /*
1006 * NOTE: The closing } has not yet been scanned in the call to execute();
1007 * therefore, we read it ourselves using input(), then we push:
1008 * '}{' + our string + '}'
1009 */
1010 int i;
1011 while ((i = yyFlexLexer::yyinput()) != '}' && i != EOF)
1012 curr_index++; /* eat up values */
1013
1014 // Increment curr_index to account for the '}' and save history
1015 curr_index++;
1016 save_history_string();
1017
1018 /* Allocate space for string + '}' + '{' + end_of_string */
1019 std::string new_string;
1020 new_string += "}{";
1021 new_string += string;
1022 new_string += "}";
1023
1024 aprepro.ap_file_list.push(SEAMS::file_rec("_string_", 0, true, -1));
1025
1026 auto ins = new std::istringstream(new_string); // Declare an input string stream.
1027 yyFlexLexer::yypush_buffer_state(yyFlexLexer::yy_create_buffer(ins, new_string.size()));
1028 return (nullptr);
1029 }
1030
1031 /* Push the contents of 'string' onto the stack to be reread.
1032 * 'string' will not be surrounded by {}.
1033 */
1034
1035 char *Scanner::rescan(char *string)
1036 {
1037 int i;
1038 /*
1039 * NOTE: The closing } has not yet been scanned in the call to rescan();
1040 * therefore, we read it ourselves using input(), then we push our
1041 * string and then put the closing } back on the stack last
1042 * (to be read first),
1043 */
1044 while ((i = yyFlexLexer::yyinput()) != '}' && i != EOF)
1045 curr_index++; /* eat up values */
1046
1047 // Increment curr_index to account for the '}' and save history
1048 curr_index++;
1049 save_history_string();
1050
1051 {
1052 aprepro.ap_file_list.push(SEAMS::file_rec("_string_", 0, true, -1));
1053 std::string new_string("}");
1054 new_string += string;
1055
1056 auto ins = new std::istringstream(new_string); // Declare an input string stream.
1057 yyFlexLexer::yypush_buffer_state(yyFlexLexer::yy_create_buffer(ins, new_string.size()));
1058 }
1059 return (nullptr);
1060 }
1061
1062 char *Scanner::import_handler(char *string)
1063 {
1064 /*
1065 * NOTE: The closing } has not yet been scanned in the call to rescan();
1066 * therefore, we read it ourselves using input().
1067 */
1068 int i = 0;
1069 while ((i = yyFlexLexer::yyinput()) != '}' && i != EOF)
1070 curr_index++; /* eat up values */
1071
1072 add_include_file(string, true);
1073 std::string info_string = std::string("Imported File: '") + string + "'";
1074 aprepro.info(info_string, true);
1075
1076 if (!aprepro.doIncludeSubstitution) {
1077 yy_push_state(VERBATIM);
1078 }
1079
1080 /*
1081 * Now we need to push back the closing } so it is the first thing read.
1082 * We no longer have the initial file stream (is is pushed down on stack)
1083 * so we need to add a new file stream consisting of just a single character.
1084 * Wasteful, but best I can come up with at this time.
1085 */
1086 aprepro.ap_file_list.push(SEAMS::file_rec("_string_", 0, true, -1));
1087 std::string new_string("}");
1088 auto ins = new std::istringstream(new_string); // Declare an input string stream.
1089 yyFlexLexer::yypush_buffer_state(yyFlexLexer::yy_create_buffer(ins, new_string.size()));
1090
1091 if (aprepro.ap_options.debugging) {
1092 std::cerr << "DEBUG IMPORT: " << string << "\n";
1093 }
1094 return (nullptr);
1095 }
1096
1097 char *Scanner::if_handler(double x)
1098 {
1099 if_lvl++;
1100 if (if_lvl >= MAX_IF_NESTING) {
1101 yyerror("Too many nested if statements");
1102 }
1103 else {
1104 if (x == 0) {
1105 if_state[if_lvl] = IF_SKIP;
1106 if_case_run[if_lvl] = false;
1107 }
1108 else {
1109 suppress_nl = true;
1110 if_state[if_lvl] = INITIAL;
1111 if_case_run[if_lvl] = true;
1112 }
1113 if (aprepro.ap_options.debugging) {
1114 std::cerr << "DEBUG IF: If level " << if_lvl << " " << if_state[if_lvl] << "\n";
1115 }
1116 }
1117 return (nullptr);
1118 }
1119
1120 char *Scanner::elseif_handler(double x)
1121 {
1122 if (x == 0 || if_case_run[if_lvl]) {
1123 if_state[if_lvl] = IF_SKIP;
1124 }
1125 else {
1126 suppress_nl = 1;
1127 if_state[if_lvl] = INITIAL;
1128 if_case_run[if_lvl] = true;
1129 }
1130 if (aprepro.ap_options.debugging) {
1131 std::cerr << "DEBUG IF: elseif at level " << if_lvl << " " << if_state[if_lvl] << "\n";
1132 }
1133 return (nullptr);
1134 }
1135
1136 char *Scanner::switch_handler(double x)
1137 {
1138 // save that we are in a switch statement
1139 // save the value of 'x' for use in deciding which case to execute
1140 if (switch_active) {
1141 yyerror("switch statement found while switch already active. Nested switch not supported.");
1142 }
1143
1144 switch_active = true;
1145 switch_case_run = false;
1146 switch_condition = x;
1147 switch_skip_to_endcase = true; /* Skip everything until first case */
1148 suppress_nl = true;
1149
1150 if (aprepro.ap_options.debugging) {
1151 std::cerr << "DEBUG SWITCH: 'switch' with condition = " << switch_condition << " at line "
1152 << aprepro.ap_file_list.top().lineno << "\n";
1153 }
1154 return (nullptr);
1155 }
1156
1157 char *Scanner::case_handler(double x)
1158 {
1159 // make sure we are in a switch statement
1160 // if 'x' matches the value saved in the switch statement
1161 // and no other case has been executed, then
1162 // execute the code in the case and set a flag indicating
1163 // the switch has run;
1164 // if 'x' does not match the value saved, then skip to endcase
1165 suppress_nl = true;
1166
1167 if (!switch_active) {
1168 yyerror("case statement found outside switch statement.");
1169 }
1170
1171 if (!switch_case_run && x == switch_condition) {
1172 switch_case_run = true;
1173 if (aprepro.ap_options.debugging) {
1174 fprintf(stderr,
1175 "DEBUG SWITCH: 'case' condition = %g matches switch condition = %g at line %d\n", x,
1176 switch_condition, aprepro.ap_file_list.top().lineno);
1177 }
1178 }
1179 else {
1180 if (aprepro.ap_options.debugging) {
1181 fprintf(stderr, "DEBUG SWITCH: 'case' condition = %g does not match switch condition = %g "
1182 "(or case already matched) at line %d\n",
1183 x, switch_condition, aprepro.ap_file_list.top().lineno);
1184 }
1185
1186 // Need to skip all code until end of case
1187 switch_skip_to_endcase = true;
1188 }
1189 return (nullptr);
1190 }
1191
1192 void Scanner::save_history_string()
1193 {
1194 if (!aprepro.ap_options.keep_history) {
1195 return;
1196 }
1197
1198 // Don't do it if the file is the one used by execute and rescan.
1199 if (aprepro.ap_file_list.top().name == "_string_" ||
1200 aprepro.ap_file_list.top().name == "standard input") {
1201 return;
1202 }
1203
1204 size_t hist_end = curr_index;
1205 size_t len = hist_end - hist_start;
1206
1207 if (len <= 0)
1208 return;
1209
1210 // Clear any possible end-of-stream if e.g., reading from a istringstream.
1211 std::ios::iostate state = yyin->rdstate();
1212 size_t loc = yyin->tellg();
1213 yyin->clear();
1214
1215 // Go back in the stream to where we started keeping history.
1216 yyin->seekg(hist_start);
1217 if (!yyin->good()) {
1218 yyerror("Stream state bad in `save_history_string` seekg");
1219 return;
1220 }
1221
1222 // Read everything up to this point again and save it.
1223 auto tmp = new char[len + 1];
1224 yyin->read(tmp, len);
1225 if (!yyin->good()) {
1226 yyerror("Stream state bad in `save_history_string` read");
1227 return;
1228 }
1229 tmp[len] = '\0';
1230
1231 history_string = tmp;
1232 delete[] tmp;
1233 hist_start = 0;
1234
1235 // restore stream state
1236 yyin->seekg(loc);
1237 yyin->setstate(state);
1238 }
1239 }
1240
1241 /* This implementation of SEAMSFlexLexer::yylex() is required to fill the
1242 * vtable of the class SEAMSFlexLexer. We define the scanner's main yylex
1243 * function via YY_DECL to reside in the Scanner class instead. */
1244
1245 #ifdef yylex
1246 #undef yylex
1247 #endif
1248 int SEAMSFlexLexer::yylex()
1249 {
1250 std::cerr << "in SEAMSFlexLexer::yylex() !" << '\n';
1251 return 0;
1252 }
1253
1254 /* When the scanner receives an end-of-file indication from YY_INPUT, it then
1255 * checks the yywrap() function. If yywrap() returns false (zero), then it is
1256 * assumed that the function has gone ahead and set up `yyin' to point to
1257 * another input file, and scanning continues. If it returns true (non-zero),
1258 * then the scanner terminates, returning 0 to its caller. */
1259
1260 int SEAMSFlexLexer::yywrap() { return 1; }