Debian Codegraph @

packages/seacas/libraries/aprepro_lib/apr_aprepro.cc

raw
1 // Copyright(C) 1999-2025 National Technology & Engineering Solutions
2 // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
3 // NTESS, the U.S. Government retains certain rights in this software.
4 //
5 // See packages/seacas/LICENSE for details
6
7 #include "apr_scanner.h" // for Scanner
8 #include "apr_util.h"
9 #include "aprepro.h" // for Aprepro, symrec, file_rec, etc
10 #include "aprepro_parser.h" // for Parser, Parser::token, etc
11 #include <cstdio>
12 #include <cstdlib> // for exit, EXIT_SUCCESS, etc
13 #include <cstring> // for strcmp
14 #include <fmt/color.h>
15 #include <fmt/format.h>
16 #include <fmt/ostream.h>
17 #include <fstream> // for operator<<, basic_ostream, etc
18 #include <iomanip> // for operator<<, setw, etc
19 #include <iostream> // for left, cerr, cout, streampos
20 #include <stack> // for stack
21 #include <stdexcept>
22 #include <string> // for string, operator==, etc
23 #include <unistd.h>
24 #include <vector> // for allocator, vector
25
26 #define HASHSIZE 5939
27
28 #define USE_ROBIN_MAP
29 #if defined USE_ROBIN_MAP
30 #include <robin_map.h>
31 #else
32 #include <unordered_map>
33 #endif
34
35 namespace {
36 const std::string version_short{"6.36"};
37 const std::string version_date{"(2025/02/05)"};
38 const std::string version_string = version_short + " " + version_date;
39
40 void output_copyright();
41
42 std::string get_value(const std::string &option, const std::string &optional_value)
43 {
44 size_t index = option.find_first_of('=');
45 std::string value;
46
47 if (index != std::string::npos) {
48 value = option.substr(index + 1);
49 }
50 else {
51 value = optional_value;
52 }
53 return value;
54 }
55 } // namespace
56
57 namespace SEAMS {
58 struct Symtable
59 {
60 Symtable() = default;
61 ~Symtable()
62 {
63 for (const auto &sym : sym_table) {
64 const auto &ptr = sym.second;
65 delete ptr;
66 }
67 }
68
69 void add(const std::string &name, SEAMS::symrec *ptr) { sym_table[name] = ptr; }
70 void erase(const std::string &name) { sym_table.erase(name); }
71 SEAMS::symrec *getsym(const char *sym_name)
72 {
73 auto ptr = sym_table.find(sym_name);
74 if (ptr != sym_table.end()) {
75 return ptr->second;
76 }
77 return nullptr;
78 }
79
80 #if defined USE_ROBIN_MAP
81 tsl::robin_pg_map<std::string, SEAMS::symrec *> sym_table{HASHSIZE};
82 const tsl::robin_pg_map<std::string, SEAMS::symrec *> &get() { return sym_table; }
83 #else
84 std::unordered_map<std::string, SEAMS::symrec *> sym_table{HASHSIZE};
85 const std::unordered_map<std::string, SEAMS::symrec *> &get() { return sym_table; }
86 #endif
87 };
88
89 Aprepro *aprepro = nullptr; // A global for use in the library. Clean this up...
90 bool echo = true;
91
92 Aprepro::Aprepro() : sym_table(new Symtable())
93 {
94 ap_file_list.emplace(file_rec());
95 init_table("$");
96 aprepro = this;
97
98 add_variable("__loop_level__", 0, false, true);
99 }
100
101 Aprepro::~Aprepro()
102 {
103 if (!outputStream.empty()) {
104 outputStream.top()->flush();
105 while (outputStream.size() > 1) {
106 std::ostream *output = outputStream.top();
107 outputStream.pop();
108 delete output;
109 }
110 }
111
112 // May need to delete this if set via --info=filename command.
113 // May need a flag to determine this...
114 infoStream->flush();
115 if (closeInfo) {
116 delete infoStream;
117 }
118
119 if ((stringScanner != nullptr) && stringScanner != lexer) {
120 delete stringScanner;
121 }
122
123 delete lexer;
124
125 aprepro = nullptr;
126
127 for (auto &arr_mem : array_allocations) {
128 delete arr_mem;
129 }
130 array_allocations.clear();
131
132 cleanup_memory();
133 }
134
135 const std::string &Aprepro::version() { return version_string; }
136 const std::string &Aprepro::short_version() { return version_short; }
137
138 std::string Aprepro::long_version() const
139 {
140 const auto &comment = getsym("_C_")->value.svar;
141 return comment + " Algebraic Preprocessor (Aprepro) version " + version();
142 }
143
144 void Aprepro::clear_results()
145 {
146 parsingResults.str("");
147 parsingResults.clear();
148 }
149
150 bool Aprepro::parse_stream(std::istream &in, const std::string &in_name)
151 {
152 std::istream *in_cpy = &in;
153 ap_file_list.top().name = in_name;
154
155 auto scanner = new Scanner(*this, in_cpy, &parsingResults);
156 this->lexer = scanner;
157
158 if (!ap_options.include_file.empty()) {
159 stateImmutable = true;
160 echo = false;
161 scanner->add_include_file(ap_options.include_file, true);
162 }
163
164 Parser parser(*this);
165 parser.set_debug_level(ap_options.trace_parsing);
166 return (parser.parse() == 0);
167 }
168
169 bool Aprepro::parse_file(const std::string &filename)
170 {
171 std::ifstream in(filename);
172 if (!in.good()) {
173 return false;
174 }
175 return parse_stream(in, filename);
176 }
177
178 bool Aprepro::parse_string(const std::string &input, const std::string &sname)
179 {
180 std::istringstream iss(input);
181 return parse_stream(iss, sname);
182 }
183
184 bool Aprepro::parse_strings(const std::vector<std::string> &input, const std::string &sname)
185 {
186 std::stringstream iss;
187 for (const auto &elem : input) {
188 iss << elem << '\n';
189 }
190 return parse_stream(iss, sname);
191 }
192
193 bool Aprepro::parse_string_interactive(const std::string &input)
194 {
195 stringInteractive = true;
196
197 if (ap_file_list.size() == 1) {
198 ap_file_list.top().name = "interactive_input";
199 }
200 if (stringScanner == nullptr) {
201 stringScanner = new Scanner(*this, &stringInput, &parsingResults);
202 }
203
204 if (!ap_options.include_file.empty()) {
205 stateImmutable = true;
206 echo = false;
207 stringScanner->add_include_file(ap_options.include_file, true);
208 }
209
210 this->lexer = stringScanner;
211
212 stringInput.str(input);
213 stringInput.clear();
214
215 Parser parser(*this);
216 parser.set_debug_level(ap_options.trace_parsing);
217 bool result = parser.parse() == 0;
218
219 stringInteractive = false;
220 return result;
221 }
222
223 void Aprepro::error(const std::string &msg, bool line_info, bool prefix) const
224 {
225 bool colorize = (errorStream == &std::cerr) && isatty(fileno(stderr));
226 std::string message = prefix ? fmt::format("Aprepro-{}: ERROR: {}", short_version(), msg)
227 : fmt::format("{}", msg);
228 std::string lines = line_info ? fmt::format(" ({}, line {})", ap_file_list.top().name,
229 ap_file_list.top().lineno)
230 : "";
231
232 if (colorize) {
233 fmt::print(*errorStream, "{}{}\n", fmt::styled(message, fmt::fg(fmt::color::red)), lines);
234 }
235 else {
236 fmt::print(*errorStream, "{}{}\n", message, lines);
237 }
238 parseErrorCount++;
239 }
240
241 void Aprepro::warning(const std::string &msg, bool line_info, bool prefix) const
242 {
243 if (!ap_options.warning_msg) {
244 return;
245 }
246
247 bool colorize = (warningStream == &std::cerr) && isatty(fileno(stderr));
248 std::string message =
249 prefix ? fmt::format("Aprepro: WARNING: {}", msg) : fmt::format("{}", msg);
250 std::string lines = line_info ? fmt::format(" ({}, line {})", ap_file_list.top().name,
251 ap_file_list.top().lineno)
252 : "";
253
254 if (colorize) {
255 fmt::print(*warningStream, "{}{}\n", fmt::styled(message, fmt::fg(fmt::color::yellow)),
256 lines);
257 }
258 else {
259 fmt::print(*warningStream, "{}{}\n", message, lines);
260 }
261 parseWarningCount++;
262 }
263
264 void Aprepro::info(const std::string &msg, bool line_info, bool prefix) const
265 {
266 if (!ap_options.info_msg) {
267 return;
268 }
269
270 bool colorize = (infoStream == &std::cout) && isatty(fileno(stdout));
271 std::string message = prefix ? fmt::format("Aprepro: INFO: {}", msg) : fmt::format("{}", msg);
272 std::string lines = line_info ? fmt::format(" ({}, line {})", ap_file_list.top().name,
273 ap_file_list.top().lineno)
274 : "";
275
276 if (colorize) {
277 fmt::print(*infoStream, "{}{}\n", fmt::styled(message, fmt::fg(fmt::color::blue)), lines);
278 }
279 else {
280 fmt::print(*infoStream, "{}{}\n", message, lines);
281 }
282 }
283
284 void Aprepro::set_error_streams(std::ostream *c_error, std::ostream *c_warning,
285 std::ostream *c_info, bool close_error, bool close_warning,
286 bool close_info)
287 {
288 if (c_error != nullptr) {
289 errorStream = c_error;
290 closeError = close_error;
291 }
292 if (c_warning != nullptr) {
293 warningStream = c_warning;
294 closeWarning = close_warning;
295 }
296 if (c_info != nullptr) {
297 infoStream = c_info;
298 closeInfo = close_info;
299 }
300 }
301
302 void Aprepro::set_error_streams(std::ostream *c_error, std::ostream *c_warning,
303 std::ostream *c_info)
304 {
305 set_error_streams(c_error, c_warning, c_info, false, false, false);
306 }
307
308 /* Two methods for opening files:
309
310 In OPEN_FILE, the file must exist or else the code will exit in
311 batch mode or return null pointer if interactive.
312
313 In CHECK_OPEN_FILE, it is OK if the file does not exist. A Null
314 'pointer' will be returned.
315 */
316 std::fstream *Aprepro::open_file(const std::string &file, const char *mode)
317 {
318 std::ios::openmode smode = std::ios::in;
319 if (mode[0] == 'w') {
320 smode = std::ios::out;
321 }
322
323 /* See if file exists in current directory (or as specified) */
324 auto pointer = new std::fstream(file, smode);
325 if ((pointer->bad() || !pointer->good()) && !ap_options.include_path.empty()) {
326 /* If there is an include path specified, try opening file there */
327 std::string file_path(ap_options.include_path);
328 file_path += "/";
329 file_path += file;
330 delete pointer;
331 pointer = new std::fstream(file_path, smode);
332 }
333
334 /* If pointer still null, print error message */
335 if (pointer->fail() || pointer->bad() || !pointer->good()) {
336 std::string err = "Can't open '" + file + "'. " + strerror(errno);
337 error(err, false);
338 delete pointer;
339 pointer = nullptr;
340 if (!stringInteractive) {
341 throw std::runtime_error(err);
342 }
343 }
344
345 return pointer;
346 }
347
348 std::fstream *Aprepro::check_open_file(const std::string &file, const char *mode)
349 {
350 std::ios::openmode smode = std::ios::in;
351 if (mode[0] == 'w') {
352 smode = std::ios::out;
353 }
354
355 auto pointer = new std::fstream(file, smode);
356
357 if ((pointer->bad() || !pointer->good()) && !ap_options.include_path.empty()) {
358 /* If there is an include path specified, try opening file there */
359 std::string file_path(ap_options.include_path);
360 file_path += "/";
361 file_path += file;
362 delete pointer;
363 pointer = new std::fstream(file_path, smode);
364 }
365 return pointer;
366 }
367
368 Aprepro::SYMBOL_TYPE Aprepro::get_symbol_type(const SEAMS::symrec *symbol) const
369 {
370 switch (symbol->type) {
371 case Parser::token::VAR: return SYMBOL_TYPE::VARIABLE;
372 case Parser::token::SVAR: return SYMBOL_TYPE::STRING_VARIABLE;
373 case Parser::token::AVAR: return SYMBOL_TYPE::ARRAY_VARIABLE;
374 case Parser::token::IMMVAR: return SYMBOL_TYPE::IMMUTABLE_VARIABLE;
375 case Parser::token::IMMSVAR: return SYMBOL_TYPE::IMMUTABLE_STRING_VARIABLE;
376 case Parser::token::UNDVAR: return SYMBOL_TYPE::UNDEFINED_VARIABLE;
377 case Parser::token::FNCT: return SYMBOL_TYPE::FUNCTION;
378 case Parser::token::SFNCT: return SYMBOL_TYPE::STRING_FUNCTION;
379 case Parser::token::AFNCT: return SYMBOL_TYPE::ARRAY_FUNCTION;
380 default: return SYMBOL_TYPE::INTERNAL;
381 }
382 }
383
384 symrec *Aprepro::putsym(const std::string &sym_name, SYMBOL_TYPE sym_type, bool is_internal)
385 {
386 int parser_type = 0;
387 bool is_function = false;
388 switch (sym_type) {
389 case SYMBOL_TYPE::VARIABLE: parser_type = Parser::token::VAR; break;
390 case SYMBOL_TYPE::STRING_VARIABLE: parser_type = Parser::token::SVAR; break;
391 case SYMBOL_TYPE::ARRAY_VARIABLE: parser_type = Parser::token::AVAR; break;
392 case SYMBOL_TYPE::IMMUTABLE_VARIABLE: parser_type = Parser::token::IMMVAR; break;
393 case SYMBOL_TYPE::IMMUTABLE_STRING_VARIABLE: parser_type = Parser::token::IMMSVAR; break;
394 case SYMBOL_TYPE::UNDEFINED_VARIABLE: parser_type = Parser::token::UNDVAR; break;
395 case SYMBOL_TYPE::FUNCTION:
396 parser_type = Parser::token::FNCT;
397 is_function = true;
398 break;
399 case SYMBOL_TYPE::STRING_FUNCTION:
400 parser_type = Parser::token::SFNCT;
401 is_function = true;
402 break;
403 case SYMBOL_TYPE::ARRAY_FUNCTION:
404 parser_type = Parser::token::AFNCT;
405 is_function = true;
406 break;
407 case SYMBOL_TYPE::INTERNAL: parser_type = Parser::token::UNDVAR; break;
408 }
409
410 // If the type is a function type, it can be overloaded as long as
411 // it returns the same type which means that the "parser_type" is
412 // the same. If we have a function, see if it has already been
413 // defined and if so, check that the parser_type matches and then
414 // return that pointer instead of creating a new symrec.
415
416 if (is_function) {
417 symrec *ptr = getsym(sym_name);
418 if (ptr != nullptr) {
419 if (ptr->type != parser_type) {
420 std::string err = "Overloaded function '" + sym_name + "' does not return same type";
421 error(err, false);
422 throw std::runtime_error(err);
423 }
424 // Function with this name already exists; return that
425 // pointer.
426 // Note that the info and syntax fields will contain the
427 // latest values, not the firstt...
428 return ptr;
429 }
430 }
431 else {
432 symrec *ptr = getsym(sym_name);
433 if (ptr != nullptr) {
434 std::string err = "Internal Error: Variable '" + sym_name + "' is already defined.";
435 error(err, false);
436 throw std::runtime_error(err);
437 }
438 }
439
440 auto ptr = new symrec(sym_name, parser_type, is_internal);
441 sym_table->add(sym_name, ptr);
442 return ptr;
443 }
444
445 namespace {
446 bool match_option(const std::string &option, const std::string &long_opt,
447 const std::string &short_opt, size_t min_length)
448 {
449 // See if `option` starts with 1 or 2 leading `-`.
450 size_t number_dash = option[0] == '-' ? (option[1] == '-' ? 2 : 1) : 0;
451
452 // See if `option` contains a `=`, save position...
453 auto equals = option.find('=');
454 if (equals == std::string::npos) {
455 equals = option.size();
456 }
457 else {
458 equals = equals - number_dash;
459 }
460
461 // NOTE: `option` contains two leading `--` or `-` and a single character...
462 if (!short_opt.empty() && number_dash == 1 && option.substr(1, equals) == short_opt) {
463 return true;
464 }
465
466 // Now deal with long options...
467 auto len_option = std::max(equals - 2, min_length);
468 return option.substr(2, len_option) == long_opt.substr(0, len_option);
469 }
470 } // namespace
471
472 int Aprepro::set_option(const std::string &option, const std::string &optional_value)
473 {
474 // Option should be of the form "--option" or "-O"
475 // I.e., double dash for long option, single dash for short.
476 // Option can be followed by "=value" if the option requires
477 // a value. The value will either be part of 'option' if it contains
478 // an '=', or it will be in 'optional_value'. if 'optional_value' used,
479 // return 1; else return 0;
480
481 // Some options (--include)
482 int ret_value = 0;
483
484 if (match_option(option, "debug", "d", 3)) {
485 ap_options.debugging = true;
486 }
487 else if (match_option(option, "dumpvars_json", "J", 13)) {
488 ap_options.dumpvars_json = true;
489 }
490 else if (match_option(option, "dumpvars", "D", 4)) {
491 ap_options.dumpvars = true;
492 }
493 else if (match_option(option, "version", "v", 3)) {
494 std::cerr << "Algebraic Preprocessor (Aprepro) version " << version() << "\n";
495 exit(EXIT_SUCCESS);
496 }
497 else if (match_option(option, "quiet", "q", 5)) {
498 // Do nothing, but don't report an error/warning. Handled elsewhere.
499 }
500 else if (match_option(option, "nowarning", "W", 6)) {
501 ap_options.warning_msg = false;
502 }
503 else if (match_option(option, "copyright", "C", 4)) {
504 output_copyright();
505 exit(EXIT_SUCCESS);
506 }
507 else if (match_option(option, "message", "M", 4)) {
508 ap_options.info_msg = true;
509 }
510 else if (match_option(option, "immutable", "X", 3)) {
511 ap_options.immutable = true;
512 stateImmutable = true;
513 }
514 else if (match_option(option, "errors_fatal", "f", 8)) {
515 ap_options.errors_fatal = true;
516 }
517 else if (match_option(option, "errors_and_warnings_fatal", "F", 9)) {
518 ap_options.errors_and_warnings_fatal = true;
519 ap_options.errors_fatal = true;
520 }
521 else if (match_option(option, "require_defined", "R", 3)) {
522 ap_options.require_defined = true;
523 }
524 else if (match_option(option, "trace", "t", 3)) {
525 ap_options.trace_parsing = true;
526 }
527 else if (match_option(option, "interactive", "i", 3)) {
528 ap_options.interactive = true;
529 }
530 else if (match_option(option, "one_based_index", "1", 3)) {
531 ap_options.one_based_index = true;
532 }
533 else if (match_option(option, "exit_on", "e", 3)) {
534 ap_options.end_on_exit = true;
535 }
536 else if (match_option(option, "info", "", 4)) {
537 std::string value = get_value(option, optional_value);
538 ret_value = value == optional_value ? 1 : 0;
539
540 if (!value.empty()) {
541 auto do_info = open_file(value, "w");
542 if (do_info != nullptr) {
543 set_error_streams(nullptr, nullptr, do_info, false, false, true);
544 }
545 }
546 }
547 else if (match_option(option, "include", "I", 3)) {
548 std::string value = get_value(option, optional_value);
549 ret_value = value == optional_value ? 1 : 0;
550
551 if (is_directory(value)) {
552 ap_options.include_path = value;
553 }
554 else {
555 ap_options.include_file = value;
556 }
557 }
558 else if (match_option(option, "keep_history", "k", 4)) {
559 ap_options.keep_history = true;
560 }
561
562 else if (match_option(option, "comment", "", 3) || (option[1] == 'c')) {
563 std::string comment;
564 // In short version, do not require equal sign (-c# -c// )
565 if (option[1] == 'c' && option.length() > 2 && option[2] != '=') {
566 comment = option.substr(2);
567 }
568 else {
569 comment = get_value(option, optional_value);
570 ret_value = comment == optional_value ? 1 : 0;
571 }
572 symrec *ptr = getsym("_C_");
573 if (ptr != nullptr) {
574 ptr->value.svar = comment;
575 }
576 }
577 else if (match_option(option, "full_precision", "p", 3)) {
578 symrec *ptr = getsym("_FORMAT");
579 if (ptr != nullptr) {
580 ptr->value.svar = "";
581 }
582 }
583
584 else if (match_option(option, "help", "h", 3)) {
585 std::cerr
586 << "\nAprepro version " << version() << "\n"
587 << "\nUsage: aprepro [options] [-I path] [-c char] [var=val] [filein] [fileout]\n"
588 << " --debug or -d: Dump all variables, debug loops/if/endif and keep temporary "
589 "files\n"
590 << " --dumpvars or -D: Dump all variables at end of run \n"
591 << " --dumpvars_json or -J: Dump all variables at end of run in json format\n"
592 << " --version or -v: Print version number to stderr \n"
593 << " --immutable or -X: All variables are immutable--cannot be modified\n"
594 << " --errors_fatal or -f: Exit program with nonzero status if errors are "
595 "encountered\n"
596 << " --errors_and_warnings_fatal or -F: Exit program with nonzero status if "
597 "warnings are encountered\n"
598 << "--require_defined or -R: Treat undefined variable warnings as fatal\n"
599 << "--one_based_index or -1: Array indexing is one-based (default = zero-based)\n"
600 << " --interactive or -i: Interactive use, no buffering \n"
601 << " --include=P or -I=P: Include file or include path \n"
602 << " : If P is path, then optionally prepended to all include "
603 "filenames\n"
604 << " : If P is file, then processed before processing input file\n"
605 << " : variables defined in P will be immutable.\n"
606 << " --exit_on or -e: End when 'Exit|EXIT|exit' entered \n"
607 << " --help or -h: Print this list \n"
608 << " --message or -M: Print INFO messages \n"
609 << " --info=file: Output INFO messages (e.g. DUMP() output) to file.\n"
610 << " --nowarning or -W: Do not print WARN messages \n"
611 << " --comment=char or -c=char: Change comment character to 'char' \n"
612 << " --full_precision -p: Floating point output uses as many digits as needed.\n"
613 << " --copyright or -C: Print copyright message \n"
614 << " --keep_history or -k: Keep a history of aprepro substitutions.\n"
615 << " (not for general interactive use) \n"
616 << " --quiet or -q: Do not print the header output line \n"
617 << " var=val: Assign value 'val' to variable 'var' \n"
618 << " Use var=\\\"sval\\\" for a string variable. 'var' will be "
619 "immutable.\n\n"
620 << "\tUnits Systems: si, cgs, cgs-ev, shock, swap, ft-lbf-s, ft-lbm-s, in-lbf-s\n"
621 << "\tEnter {DUMP()} for list of user-defined variables\n"
622 << "\tEnter {DUMP_FUNC()} for list of functions recognized by aprepro\n"
623 << "\tEnter {DUMP_PREVAR()} for list of predefined variables in aprepro\n\n"
624 << "\tDocumentation: "
625 "https://sandialabs.github.io/seacas-docs/sphinx/html/index.html#aprepro\n\n"
626 << "\t->->-> Send email to [email protected] for aprepro support.\n\n";
627 exit(EXIT_SUCCESS);
628 }
629 else {
630 warning("Unrecgonized option '" + option + "'. This option will be ignored.\n", false);
631 }
632 return ret_value;
633 }
634
635 array *Aprepro::make_array(size_t r, size_t c)
636 {
637 auto ptr = new array(r, c);
638 array_allocations.push_back(ptr);
639 return ptr;
640 }
641
642 array *Aprepro::make_array(const array &from)
643 {
644 auto ptr = new array(from);
645 array_allocations.push_back(ptr);
646 return ptr;
647 }
648
649 void Aprepro::redefine_array(array *array)
650 {
651 // This data pointer from an array is being redefined. Remove it
652 // from `array_allocations` to avoid double delete.
653 array_allocations.erase(std::remove(array_allocations.begin(), array_allocations.end(), array),
654 array_allocations.end());
655 delete array;
656 }
657
658 void Aprepro::add_variable(const std::string &sym_name, const std::string &sym_value,
659 bool immutable, bool internal)
660 {
661 if (check_valid_var(sym_name.c_str())) {
662 SYMBOL_TYPE type =
663 immutable ? SYMBOL_TYPE::IMMUTABLE_STRING_VARIABLE : SYMBOL_TYPE::STRING_VARIABLE;
664 symrec *var = getsym(sym_name);
665 if (var == nullptr) {
666 var = putsym(sym_name, type, internal);
667 }
668 else {
669 var->type = immutable ? Parser::token::IMMSVAR : Parser::token::SVAR;
670 }
671 var->value.svar = sym_value;
672 }
673 else {
674 warning("Invalid variable name syntax '" + sym_name + "'. Variable not defined.\n", false);
675 }
676 }
677
678 void Aprepro::add_variable(const std::string &sym_name, double sym_value, bool immutable,
679 bool internal)
680 {
681 if (check_valid_var(sym_name.c_str())) {
682 SYMBOL_TYPE type = immutable ? SYMBOL_TYPE::IMMUTABLE_VARIABLE : SYMBOL_TYPE::VARIABLE;
683 symrec *var = getsym(sym_name);
684 if (var == nullptr) {
685 var = putsym(sym_name, type, internal);
686 }
687 else {
688 var->type = immutable ? Parser::token::IMMVAR : Parser::token::VAR;
689 }
690 var->value.var = sym_value;
691 }
692 else {
693 warning("Invalid variable name syntax '" + sym_name + "'. Variable not defined.\n", false);
694 }
695 }
696
697 void Aprepro::add_variable(const std::string &sym_name, array *value)
698 {
699 if (check_valid_var(sym_name.c_str())) {
700 SYMBOL_TYPE type = SYMBOL_TYPE::ARRAY_VARIABLE;
701 symrec *var = getsym(sym_name);
702 if (var == nullptr) {
703 var = putsym(sym_name, type, false);
704 }
705 else {
706 var->type = Parser::token::AVAR;
707 }
708 var->value.avar = value;
709 }
710 else {
711 warning("Invalid variable name syntax '" + sym_name + "'. Variable not defined.\n", false);
712 }
713 }
714
715 std::vector<std::string> Aprepro::get_variable_names(bool doInternal)
716 {
717 std::vector<std::string> names;
718
719 for (const auto &sym : sym_table->get()) {
720 const auto &ptr = sym.second;
721 if (ptr->isInternal != doInternal) {
722 continue;
723 }
724
725 switch (ptr->type) {
726 case Parser::token::VAR:
727 case Parser::token::IMMVAR:
728 case Parser::token::SVAR:
729 case Parser::token::IMMSVAR:
730 case Parser::token::AVAR:
731 // Add to our vector
732 names.push_back(ptr->name);
733 break;
734
735 default:
736 // Do nothing
737 break;
738 }
739 }
740 return names;
741 }
742
743 void Aprepro::remove_variable(const std::string &sym_name)
744 {
745 symrec *ptr = getsym(sym_name);
746 bool is_valid_variable =
747 (ptr != nullptr) && (!ptr->isInternal) &&
748 ((ptr->type == Parser::token::VAR) || (ptr->type == Parser::token::SVAR) ||
749 (ptr->type == Parser::token::AVAR) || (ptr->type == Parser::token::IMMVAR) ||
750 (ptr->type == Parser::token::IMMSVAR) || (ptr->type == Parser::token::UNDVAR));
751
752 if (is_valid_variable) {
753 sym_table->erase(sym_name);
754 delete ptr;
755 }
756 else {
757 warning("Variable '" + sym_name + "' not defined.\n", false);
758 }
759 }
760
761 symrec *Aprepro::getsym(const char *sym_name) const { return sym_table->getsym(sym_name); }
762
763 symrec *Aprepro::getsym(const std::string &sym_name) const { return getsym(sym_name.c_str()); }
764
765 void Aprepro::dumpsym(const char *type, bool doInternal) const
766 {
767 if (type[0] == 'v') {
768 dumpsym(Parser::token::VAR, doInternal);
769 }
770 else if (type[0] == 'f') {
771 dumpsym(Parser::token::FNCT, doInternal);
772 }
773 }
774
775 void Aprepro::dumpsym(int type, bool doInternal) const { dumpsym(type, nullptr, doInternal); }
776
777 void Aprepro::dumpsym_json() const
778 {
779 (*infoStream) << "\n{\n";
780 bool first = true;
781
782 for (const auto &ptr : get_sorted_sym_table()) {
783 if (!ptr->isInternal) {
784 if (ptr->type == Parser::token::VAR || ptr->type == Parser::token::IMMVAR) {
785 fmt::print((*infoStream), "{}{}\": {}", (first ? "\"" : ",\n\""), ptr->name,
786 ptr->value.var);
787 first = false;
788 }
789 else if (ptr->type == Parser::token::UNDVAR) {
790 (*infoStream) << (first ? "\"" : ",\n\"") << ptr->name << "\": null";
791 first = false;
792 }
793 else if (ptr->type == Parser::token::SVAR || ptr->type == Parser::token::IMMSVAR) {
794 (*infoStream) << (first ? "\"" : ",\n\"") << ptr->name << "\": \"" << ptr->value.svar
795 << "\"";
796 first = false;
797 }
798 }
799 }
800 (*infoStream) << "\n}\n";
801 }
802
803 void Aprepro::dumpsym(int type, const char *pre, bool doInternal) const
804 {
805 std::string comment = getsym("_C_")->value.svar;
806 std::string spre;
807
808 if (pre) {
809 spre = pre;
810 }
811
812 if (type == Parser::token::VAR || type == Parser::token::SVAR || type == Parser::token::AVAR) {
813 (*infoStream) << "\n" << comment << " Variable = Value" << '\n';
814
815 int width = 10; // controls spacing/padding for the variable names
816 for (const auto &ptr : get_sorted_sym_table()) {
817 if (spre.empty() || ptr->name.find(spre) != std::string::npos) {
818 if (doInternal == ptr->isInternal) {
819 if (ptr->type == Parser::token::VAR) {
820 fmt::print((*infoStream), "{} {{{:<{}}\t= {}}}\n", comment, ptr->name, width,
821 ptr->value.var);
822 }
823 else if (ptr->type == Parser::token::IMMVAR) {
824 fmt::print((*infoStream), "{} {{{:<{}}\t= {}}} (immutable)\n", comment, ptr->name,
825 width, ptr->value.var);
826 }
827 else if (ptr->type == Parser::token::SVAR) {
828 if (strchr(ptr->value.svar.c_str(), '\n') != nullptr ||
829 strchr(ptr->value.svar.c_str(), '"') != nullptr) {
830 (*infoStream) << comment << " {" << std::left << std::setw(width) << ptr->name
831 << "\t= '" << ptr->value.svar << "'}" << '\n';
832 }
833 else {
834 (*infoStream) << comment << " {" << std::left << std::setw(width) << ptr->name
835 << "\t= \"" << ptr->value.svar << "\"}" << '\n';
836 }
837 }
838 else if (ptr->type == Parser::token::IMMSVAR) {
839 if (strchr(ptr->value.svar.c_str(), '\n') != nullptr ||
840 strchr(ptr->value.svar.c_str(), '"') != nullptr) {
841 (*infoStream) << comment << " {" << std::left << std::setw(width) << ptr->name
842 << "\t= '" << ptr->value.svar << "'} (immutable)" << '\n';
843 }
844 else {
845 (*infoStream) << comment << " {" << std::left << std::setw(width) << ptr->name
846 << "\t= \"" << ptr->value.svar << "\"} (immutable)" << '\n';
847 }
848 }
849 else if (ptr->type == Parser::token::AVAR) {
850 array *arr = ptr->value.avar;
851 (*infoStream) << comment << " {" << std::left << std::setw(width) << ptr->name
852 << "\t (array) rows = " << arr->rows << ", cols = " << arr->cols << "} "
853 << '\n';
854 }
855 }
856 }
857 }
858 }
859 else if (type == Parser::token::FNCT || type == Parser::token::SFNCT ||
860 type == Parser::token::AFNCT) {
861 int fwidth = 20; // controls spacing/padding for the function names
862 fmt::print(*infoStream, "{}",
863 fmt::styled("\nFunctions returning double:\n", fmt::fg(fmt::color::cyan)));
864 for (const auto &ptr : get_sorted_sym_table()) {
865 if (spre.empty() || ptr->name.find(spre) != std::string::npos) {
866 if (ptr->type == Parser::token::FNCT) {
867 fmt::print(*infoStream, "{:<{}}: {}\n",
868 fmt::styled(ptr->syntax, fmt::fg(fmt::color::lime)), fwidth, ptr->info);
869 }
870 }
871 }
872
873 fmt::print(*infoStream, "{}",
874 fmt::styled("\nFunctions returning string:\n", fmt::fg(fmt::color::cyan)));
875 for (const auto &ptr : get_sorted_sym_table()) {
876 if (spre.empty() || ptr->name.find(spre) != std::string::npos) {
877 if (ptr->type == Parser::token::SFNCT) {
878 fmt::print(*infoStream, "{:<{}}: {}\n",
879 fmt::styled(ptr->syntax, fmt::fg(fmt::color::lime)), fwidth, ptr->info);
880 }
881 }
882 }
883
884 fmt::print(*infoStream, "{}",
885 fmt::styled("\nFunctions returning array:\n", fmt::fg(fmt::color::cyan)));
886 for (const auto &ptr : get_sorted_sym_table()) {
887 if (spre.empty() || ptr->name.find(spre) != std::string::npos) {
888 if (ptr->type == Parser::token::AFNCT) {
889 fmt::print(*infoStream, "{:<{}}: {}\n",
890 fmt::styled(ptr->syntax, fmt::fg(fmt::color::lime)), fwidth, ptr->info);
891 }
892 }
893 }
894 }
895 }
896
897 #define min(x, y) ((x) < (y) ? (x) : (y))
898 #define max(x, y) ((x) > (y) ? (x) : (y))
899
900 void Aprepro::statistics(std::ostream *out) const
901 {
902 (*out) << "Statistics function no longer supported.\n";
903 }
904
905 void Aprepro::add_history(const std::string &original, const std::string &substitution)
906 {
907 if (!ap_options.keep_history) {
908 return;
909 }
910
911 if (!original.empty()) {
912 history_data hist{};
913 hist.original = original;
914 hist.substitution = substitution;
915 hist.index = outputStream.empty() ? std::streampos(0) : outputStream.top()->tellp();
916
917 history.push_back(hist);
918 }
919 }
920
921 const std::vector<history_data> &Aprepro::get_history() { return history; }
922
923 void Aprepro::clear_history()
924 {
925 if (ap_options.keep_history) {
926 history.clear();
927 }
928 }
929
930 std::vector<SEAMS::symrec *> Aprepro::get_sorted_sym_table() const
931 {
932 // We want the output to be sorted, so move all symbol pointers to a vector...
933 // Could pre-filter the vector, but for now, just copy all and filter afterwards...
934 std::vector<SEAMS::symrec *> vsym_table;
935 vsym_table.reserve(sym_table->get().size());
936 for (const auto &sym : sym_table->get()) {
937 vsym_table.push_back(sym.second);
938 }
939 std::sort(vsym_table.begin(), vsym_table.end(),
940 [](const auto &a, const auto &b) { return a->name < b->name; });
941
942 return vsym_table;
943 }
944
945 } // namespace SEAMS
946
947 namespace {
948 void output_copyright()
949 {
950 std::cerr << "\n\tCopyright (c) 2014-2017 National Technology & Engineering Solutions\n"
951 << "of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with\n"
952 << "NTESS, the U.S. Government retains certain rights in this software.\n"
953 << "\n"
954 << "\tRedistribution and use in source and binary forms, with or without\n"
955 << "\tmodification, are permitted provided that the following conditions\n"
956 << "\tare met:\n"
957 << "\n"
958 << "\t * Redistributions of source code must retain the above copyright\n"
959 << "\t notice, this list of conditions and the following disclaimer.\n"
960 << "\t * Redistributions in binary form must reproduce the above\n"
961 << "\t copyright notice, this list of conditions and the following\n"
962 << "\t disclaimer in the documentation and/or other materials provided\n"
963 << "\t with the distribution.\n"
964 << "\t * Neither the name of NTESS nor the names of its\n"
965 << "\t contributors may be used to endorse or promote products derived\n"
966 << "\t from this software without specific prior written permission.\n"
967 << "\n"
968 << "\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
969 << "\t'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
970 << "\tLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
971 << "\tA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
972 << "\tOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
973 << "\tSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
974 << "\tLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
975 << "\tDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
976 << "\tTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
977 << "\t(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
978 << "\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n";
979 }
980 } // namespace