source: src/main.cc@ 50202fa

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 50202fa was f57faf6f, checked in by Andrew Beach <ajbeach@…>, 5 years ago

Added a new-ast tools for code locations. The fill pass is being used the check pass is catching lots of missing locations when you enable it.

  • Property mode set to 100644
File size: 26.4 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// main.cc --
8//
9// Author : Peter Buhr and Rob Schluntz
10// Created On : Fri May 15 23:12:02 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Dec 7 15:29:00 2020
13// Update Count : 639
14//
15
16#include <cxxabi.h> // for __cxa_demangle
17#include <execinfo.h> // for backtrace, backtrace_symbols
18#include <getopt.h> // for no_argument, optind, geto...
19#include <cassert> // for assertf
20#include <cstdio> // for fopen, FILE, fclose, stdin
21#include <cstdlib> // for exit, free, abort, EXIT_F...
22#include <csignal> // for signal, SIGABRT, SIGSEGV
23#include <cstring> // for index
24#include <fstream> // for ofstream
25#include <iostream> // for operator<<, basic_ostream
26#include <iomanip>
27#include <iterator> // for back_inserter
28#include <list> // for list
29#include <string> // for char_traits, operator<<
30
31using namespace std;
32
33#include "AST/Convert.hpp"
34#include "CompilationState.h"
35#include "../config.h" // for CFA_LIBDIR
36#include "CodeGen/FixMain.h" // for FixMain
37#include "CodeGen/FixNames.h" // for fixNames
38#include "CodeGen/Generate.h" // for generate
39#include "CodeTools/DeclStats.h" // for printDeclStats
40#include "CodeTools/ResolvProtoDump.h" // for dumpAsResolvProto
41#include "CodeTools/TrackLoc.h" // for fillLocations
42#include "Common/CodeLocationTools.hpp" // for forceFillCodeLocations
43#include "Common/CompilerError.h" // for CompilerError
44#include "Common/Stats.h"
45#include "Common/PassVisitor.h"
46#include "Common/SemanticError.h" // for SemanticError
47#include "Common/UnimplementedError.h" // for UnimplementedError
48#include "Common/utility.h" // for deleteAll, filter, printAll
49#include "Concurrency/Waitfor.h" // for generateWaitfor
50#include "ControlStruct/ExceptTranslate.h" // for translateEHM
51#include "ControlStruct/Mutate.h" // for mutate
52#include "GenPoly/Box.h" // for box
53#include "GenPoly/InstantiateGeneric.h" // for instantiateGeneric
54#include "GenPoly/Lvalue.h" // for convertLvalue
55#include "GenPoly/Specialize.h" // for convertSpecializations
56#include "InitTweak/FixInit.h" // for fix
57#include "InitTweak/GenInit.h" // for genInit
58#include "MakeLibCfa.h" // for makeLibCfa
59#include "Parser/ParseNode.h" // for DeclarationNode, buildList
60#include "Parser/TypedefTable.h" // for TypedefTable
61#include "ResolvExpr/AlternativePrinter.h" // for AlternativePrinter
62#include "ResolvExpr/Resolver.h" // for resolve
63#include "SymTab/Validate.h" // for validate
64#include "SynTree/LinkageSpec.h" // for Spec, Cforall, Intrinsic
65#include "SynTree/Declaration.h" // for Declaration
66#include "SynTree/Visitor.h" // for acceptAll
67#include "Tuples/Tuples.h" // for expandMemberTuples, expan...
68#include "Virtual/ExpandCasts.h" // for expandCasts
69
70
71static void NewPass( const char * const name ) {
72 Stats::Heap::newPass( name );
73 using namespace Stats::Counters;
74 {
75 static auto group = build<CounterGroup>( "Pass Visitor" );
76 auto pass = build<CounterGroup>( name, group );
77 pass_visitor_stats.depth = 0;
78 pass_visitor_stats.avg = build<AverageCounter<double>>( "Average Depth", pass );
79 pass_visitor_stats.max = build<MaxCounter<double>>( "Max Depth", pass );
80 }
81 {
82 static auto group = build<CounterGroup>( "Syntax Node" );
83 auto pass = build<CounterGroup>( name, group );
84 BaseSyntaxNode::new_nodes = build<SimpleCounter>( "Allocs", pass );
85 }
86}
87
88#define PASS( name, pass ) \
89 if ( errorp ) { cerr << name << endl; } \
90 NewPass(name); \
91 Stats::Time::StartBlock(name); \
92 pass; \
93 Stats::Time::StopBlock();
94
95LinkageSpec::Spec linkage = LinkageSpec::Cforall;
96TypedefTable typedefTable;
97DeclarationNode * parseTree = nullptr; // program parse tree
98
99static bool waiting_for_gdb = false; // flag to set cfa-cpp to wait for gdb on start
100
101static string PreludeDirector = "";
102
103static void parse_cmdline( int argc, char *argv[] );
104static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
105static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
106
107static void backtrace( int start ) { // skip first N stack frames
108 enum { Frames = 50, }; // maximum number of stack frames
109 void * array[Frames];
110 size_t size = ::backtrace( array, Frames );
111 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
112
113 *index( messages[0], '(' ) = '\0'; // find executable name
114 cerr << "Stack back trace for: " << messages[0] << endl;
115
116 // skip last 2 stack frames after main
117 for ( unsigned int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
118 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
119
120 for ( char * p = messages[i]; *p; p += 1 ) { // find parantheses and +offset
121 if ( *p == '(' ) {
122 mangled_name = p;
123 } else if ( *p == '+' ) {
124 offset_begin = p;
125 } else if ( *p == ')' ) {
126 offset_end = p;
127 break;
128 } // if
129 } // for
130
131 // if line contains symbol, attempt to demangle
132 int frameNo = i - start;
133 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
134 *mangled_name++ = '\0'; // delimit strings
135 *offset_begin++ = '\0';
136 *offset_end++ = '\0';
137
138 int status;
139 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
140 // bug in __cxa_demangle for single-character lower-case non-mangled names
141 if ( status == 0 ) { // demangling successful ?
142 cerr << "(" << frameNo << ") " << messages[i] << " : "
143 << real_name << "+" << offset_begin << offset_end << endl;
144 } else { // otherwise, output mangled name
145 cerr << "(" << frameNo << ") " << messages[i] << " : "
146 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
147 } // if
148
149 free( real_name );
150 } else { // otherwise, print the whole line
151 cerr << "(" << frameNo << ") " << messages[i] << endl;
152 } // if
153 } // for
154
155 free( messages );
156} // backtrace
157
158#define SIGPARMS int sig __attribute__(( unused )), siginfo_t * sfp __attribute__(( unused )), ucontext_t * cxt __attribute__(( unused ))
159
160static void Signal( int sig, void (*handler)(SIGPARMS), int flags ) {
161 struct sigaction act;
162
163 act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
164 act.sa_flags = flags;
165
166 if ( sigaction( sig, &act, nullptr ) == -1 ) {
167 cerr << "*CFA runtime error* problem installing signal handler, error(" << errno << ") " << strerror( errno ) << endl;
168 _exit( EXIT_FAILURE );
169 } // if
170} // Signal
171
172static void sigSegvBusHandler( SIGPARMS ) {
173 if ( sfp->si_addr == nullptr ) {
174 cerr << "Null pointer (nullptr) dereference." << endl;
175 } else {
176 cerr << (sig == SIGSEGV ? "Segment fault" : "Bus error") << " at memory location " << sfp->si_addr << "." << endl
177 << "Possible cause is reading outside the address space or writing to a protected area within the address space with an invalid pointer or subscript." << endl;
178 } // if
179 backtrace( 2 ); // skip first 2 stack frames
180 abort(); // cause core dump for debugging
181} // sigSegvBusHandler
182
183static void sigFpeHandler( SIGPARMS ) {
184 const char * msg;
185
186 switch ( sfp->si_code ) {
187 case FPE_INTDIV: case FPE_FLTDIV: msg = "divide by zero"; break;
188 case FPE_FLTOVF: msg = "overflow"; break;
189 case FPE_FLTUND: msg = "underflow"; break;
190 case FPE_FLTRES: msg = "inexact result"; break;
191 case FPE_FLTINV: msg = "invalid operation"; break;
192 default: msg = "unknown";
193 } // choose
194 cerr << "Computation error " << msg << " at location " << sfp->si_addr << endl
195 << "Possible cause is constant-expression evaluation invalid." << endl;
196 backtrace( 2 ); // skip first 2 stack frames
197 abort(); // cause core dump for debugging
198} // sigFpeHandler
199
200static void sigAbortHandler( SIGPARMS ) {
201 backtrace( 6 ); // skip first 6 stack frames
202 Signal( SIGABRT, (void (*)(SIGPARMS))SIG_DFL, SA_SIGINFO ); // reset default signal handler
203 raise( SIGABRT ); // reraise SIGABRT
204} // sigAbortHandler
205
206int main( int argc, char * argv[] ) {
207 FILE * input; // use FILE rather than istream because yyin is FILE
208 ostream * output = & cout;
209 list< Declaration * > translationUnit;
210
211 Signal( SIGSEGV, sigSegvBusHandler, SA_SIGINFO );
212 Signal( SIGBUS, sigSegvBusHandler, SA_SIGINFO );
213 Signal( SIGFPE, sigFpeHandler, SA_SIGINFO );
214 Signal( SIGABRT, sigAbortHandler, SA_SIGINFO );
215
216 // cout << "main" << endl;
217 // for ( int i = 0; i < argc; i += 1 ) {
218 // cout << '\t' << argv[i] << endl;
219 // } // for
220
221 parse_cmdline( argc, argv ); // process command-line arguments
222 CodeGen::FixMain::setReplaceMain( !nomainp );
223
224 if ( waiting_for_gdb ) {
225 cerr << "Waiting for gdb" << endl;
226 cerr << "run :" << endl;
227 cerr << " gdb attach " << getpid() << endl;
228 raise(SIGSTOP);
229 } // if
230
231 try {
232 // choose to read the program from a file or stdin
233 if ( optind < argc ) { // any commands after the flags ? => input file name
234 input = fopen( argv[ optind ], "r" );
235 assertf( input, "cannot open %s because %s\n", argv[ optind ], strerror( errno ) );
236 optind += 1;
237 } else { // no input file name
238 input = stdin;
239 } // if
240
241 Stats::Time::StartGlobal();
242 NewPass("Parse");
243 Stats::Time::StartBlock("Parse");
244
245 // read in the builtins, extras, and the prelude
246 if ( ! nopreludep ) { // include gcc builtins
247 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
248
249 assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
250
251 // Read to gcc builtins, if not generating the cfa library
252 FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
253 assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
254 parse( gcc_builtins, LinkageSpec::Compiler );
255
256 // read the extra prelude in, if not generating the cfa library
257 FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
258 assertf( extras, "cannot open extras.cf\n" );
259 parse( extras, LinkageSpec::BuiltinC );
260
261 if ( ! libcfap ) {
262 // read the prelude in, if not generating the cfa library
263 FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
264 assertf( prelude, "cannot open prelude.cfa\n" );
265 parse( prelude, LinkageSpec::Intrinsic );
266
267 // Read to cfa builtins, if not generating the cfa library
268 FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
269 assertf( builtins, "cannot open builtins.cf\n" );
270 parse( builtins, LinkageSpec::BuiltinCFA );
271 } // if
272 } // if
273
274 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
275
276 if ( parsep ) {
277 parseTree->printList( cout );
278 delete parseTree;
279 return EXIT_SUCCESS;
280 } // if
281
282 buildList( parseTree, translationUnit );
283 delete parseTree;
284 parseTree = nullptr;
285
286 if ( astp ) {
287 dump( translationUnit );
288 return EXIT_SUCCESS;
289 } // if
290
291 // Temporary: fill locations after parsing so that every node has a location, for early error messages.
292 // Eventually we should pass the locations from the parser to every node, but this quick and dirty solution
293 // works okay for now.
294 CodeTools::fillLocations( translationUnit );
295 Stats::Time::StopBlock();
296
297 // add the assignment statement after the initialization of a type parameter
298 PASS( "Validate", SymTab::validate( translationUnit, symtabp ) );
299 if ( symtabp ) {
300 deleteAll( translationUnit );
301 return EXIT_SUCCESS;
302 } // if
303
304 if ( expraltp ) {
305 PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
306 acceptAll( translationUnit, printer );
307 return EXIT_SUCCESS;
308 } // if
309
310 if ( validp ) {
311 dump( translationUnit );
312 return EXIT_SUCCESS;
313 } // if
314
315 PASS( "Translate Throws", ControlStruct::translateThrows( translationUnit ) );
316 PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
317 PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
318 PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
319 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
320 if ( libcfap ) {
321 // generate the bodies of cfa library functions
322 LibCfa::makeLibCfa( translationUnit );
323 } // if
324
325 if ( declstatsp ) {
326 CodeTools::printDeclStats( translationUnit );
327 deleteAll( translationUnit );
328 return EXIT_SUCCESS;
329 } // if
330
331 if ( bresolvep ) {
332 dump( translationUnit );
333 return EXIT_SUCCESS;
334 } // if
335
336 CodeTools::fillLocations( translationUnit );
337
338 if ( resolvprotop ) {
339 CodeTools::dumpAsResolvProto( translationUnit );
340 return EXIT_SUCCESS;
341 } // if
342
343 if( useNewAST ) {
344 if (Stats::Counters::enabled) {
345 ast::pass_visitor_stats.avg = Stats::Counters::build<Stats::Counters::AverageCounter<double>>("Average Depth - New");
346 ast::pass_visitor_stats.max = Stats::Counters::build<Stats::Counters::MaxCounter<double>>("Max depth - New");
347 }
348 auto transUnit = convert( move( translationUnit ) );
349 PASS( "Resolve", ResolvExpr::resolve( transUnit ) );
350 if ( exprp ) {
351 translationUnit = convert( move( transUnit ) );
352 dump( translationUnit );
353 return EXIT_SUCCESS;
354 } // if
355
356 forceFillCodeLocations( transUnit );
357
358 PASS( "Fix Init", InitTweak::fix(transUnit, buildingLibrary()));
359 translationUnit = convert( move( transUnit ) );
360 } else {
361 PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
362 if ( exprp ) {
363 dump( translationUnit );
364 return EXIT_SUCCESS;
365 }
366
367 PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
368 }
369
370 // fix ObjectDecl - replaces ConstructorInit nodes
371 if ( ctorinitp ) {
372 dump ( translationUnit );
373 return EXIT_SUCCESS;
374 } // if
375
376 PASS( "Expand Unique Expr", Tuples::expandUniqueExpr( translationUnit ) ); // xxx - is this the right place for this? want to expand ASAP so tha, sequent passes don't need to worry about double-visiting a unique expr - needs to go after InitTweak::fix so that copy constructed return declarations are reused
377
378 PASS( "Translate Tries" , ControlStruct::translateTries( translationUnit ) );
379
380 PASS( "Gen Waitfor" , Concurrency::generateWaitFor( translationUnit ) );
381
382 PASS( "Convert Specializations", GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
383
384 PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
385
386 if ( tuplep ) {
387 dump( translationUnit );
388 return EXIT_SUCCESS;
389 } // if
390
391 PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
392
393 PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
394 if ( genericsp ) {
395 dump( translationUnit );
396 return EXIT_SUCCESS;
397 } // if
398
399 PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );
400
401 if ( bboxp ) {
402 dump( translationUnit );
403 return EXIT_SUCCESS;
404 } // if
405 PASS( "Box", GenPoly::box( translationUnit ) );
406
407 if ( bcodegenp ) {
408 dump( translationUnit );
409 return EXIT_SUCCESS;
410 } // if
411
412 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
413 output = new ofstream( argv[ optind ] );
414 } // if
415
416 CodeTools::fillLocations( translationUnit );
417 PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! genproto, prettycodegenp, true, linemarks ) );
418
419 CodeGen::FixMain::fix( *output, (PreludeDirector + "/bootloader.c").c_str() );
420 if ( output != &cout ) {
421 delete output;
422 } // if
423 } catch ( SemanticErrorException &e ) {
424 if ( errorp ) {
425 cerr << "---AST at error:---" << endl;
426 dump( translationUnit, cerr );
427 cerr << endl << "---End of AST, begin error message:---\n" << endl;
428 } // if
429 e.print();
430 if ( output != &cout ) {
431 delete output;
432 } // if
433 return EXIT_FAILURE;
434 } catch ( UnimplementedError &e ) {
435 cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
436 if ( output != &cout ) {
437 delete output;
438 } // if
439 return EXIT_FAILURE;
440 } catch ( CompilerError &e ) {
441 cerr << "Compiler Error: " << e.get_what() << endl;
442 cerr << "(please report bugs to [REDACTED])" << endl;
443 if ( output != &cout ) {
444 delete output;
445 } // if
446 return EXIT_FAILURE;
447 } catch ( ... ) {
448 exception_ptr eptr = current_exception();
449 try {
450 if (eptr) {
451 rethrow_exception(eptr);
452 } else {
453 cerr << "Exception Uncaught and Unknown" << endl;
454 } // if
455 } catch(const exception& e) {
456 cerr << "Uncaught Exception \"" << e.what() << "\"\n";
457 } // try
458 return EXIT_FAILURE;
459 } // try
460
461 deleteAll( translationUnit );
462 Stats::print();
463 return EXIT_SUCCESS;
464} // main
465
466
467static const char optstring[] = ":c:ghlLmNnpdOAP:S:twW:D:";
468
469enum { PreludeDir = 128 };
470static struct option long_opts[] = {
471 { "colors", required_argument, nullptr, 'c' },
472 { "gdb", no_argument, nullptr, 'g' },
473 { "help", no_argument, nullptr, 'h' },
474 { "libcfa", no_argument, nullptr, 'l' },
475 { "linemarks", no_argument, nullptr, 'L' },
476 { "no-main", no_argument, 0, 'm' },
477 { "no-linemarks", no_argument, nullptr, 'N' },
478 { "no-prelude", no_argument, nullptr, 'n' },
479 { "prototypes", no_argument, nullptr, 'p' },
480 { "deterministic-out", no_argument, nullptr, 'd' },
481 { "old-ast", no_argument, nullptr, 'O'},
482 { "new-ast", no_argument, nullptr, 'A'},
483 { "print", required_argument, nullptr, 'P' },
484 { "prelude-dir", required_argument, nullptr, PreludeDir },
485 { "statistics", required_argument, nullptr, 'S' },
486 { "tree", no_argument, nullptr, 't' },
487 { "", no_argument, nullptr, 0 }, // -w
488 { "", no_argument, nullptr, 0 }, // -W
489 { "", no_argument, nullptr, 0 }, // -D
490 { nullptr, 0, nullptr, 0 }
491}; // long_opts
492
493static const char * description[] = {
494 "diagnostic color: never, always, or auto.", // -c
495 "wait for gdb to attach", // -g
496 "print help message", // -h
497 "generate libcfa.c", // -l
498 "generate line marks", // -L
499 "do not replace main", // -m
500 "do not generate line marks", // -N
501 "do not read prelude", // -n
502 "generate prototypes for prelude functions", // -p
503 "only print deterministic output", // -d
504 "Use the old-ast", // -O
505 "Use the new-ast", // -A
506 "print", // -P
507 "<directory> prelude directory for debug/nodebug", // no flag
508 "<option-list> enable profiling information:\n counters,heap,time,all,none", // -S
509 "building cfa standard lib", // -t
510 "", // -w
511 "", // -W
512 "", // -D
513}; // description
514
515static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
516
517static struct Printopts {
518 const char * name;
519 int & flag;
520 int val;
521 const char * descript;
522} printopts[] = {
523 { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
524 { "asterr", errorp, true, "print AST on error" },
525 { "declstats", declstatsp, true, "code property statistics" },
526 { "parse", yydebug, true, "yacc (parsing) debug information" },
527 { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
528 { "rproto", resolvprotop, true, "resolver-proto instance" },
529 { "rsteps", resolvep, true, "print resolver steps" },
530 { "tree", parsep, true, "print parse tree" },
531 // code dumps
532 { "ast", astp, true, "print AST after parsing" },
533 { "symevt", symtabp, true, "print AST after symbol table events" },
534 { "altexpr", expraltp, true, "print alternatives for expressions" },
535 { "astdecl", validp, true, "print AST after declaration validation pass" },
536 { "resolver", bresolvep, true, "print AST before resolver step" },
537 { "astexpr", exprp, true, "print AST after expression analysis" },
538 { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
539 { "tuple", tuplep, true, "print AST after tuple expansion" },
540 { "astgen", genericsp, true, "print AST after instantiate generics" },
541 { "box", bboxp, true, "print AST before box step" },
542 { "codegen", bcodegenp, true, "print AST before code generation" },
543};
544enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
545
546static void usage( char *argv[] ) {
547 cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
548 int i = 0, j = 1; // j skips starting colon
549 for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
550 if ( long_opts[i].name[0] != '\0' ) { // hidden option, internal usage only
551 if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
552 cout << " -" << optstring[j] << ",";
553 } else { // no flag
554 j -= 1; // compensate
555 cout << " ";
556 } // if
557 cout << " --" << left << setw(12) << long_opts[i].name << " ";
558 if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
559 cout << "one of: " << endl;
560 for ( int i = 0; i < printoptsSize; i += 1 ) {
561 cout << setw(10) << " " << left << setw(10) << printopts[i].name << " " << printopts[i].descript << endl;
562 } // for
563 } else {
564 cout << description[i] << endl;
565 } // if
566 } // if
567 if ( optstring[j + 1] == ':' ) j += 1;
568 } // for
569 if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
570 exit( EXIT_FAILURE );
571} // usage
572
573static void parse_cmdline( int argc, char * argv[] ) {
574 opterr = 0; // (global) prevent getopt from printing error messages
575
576 bool Wsuppress = false, Werror = false;
577 int c;
578 while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
579 switch ( c ) {
580 case 'c': // diagnostic colors
581 if ( strcmp( optarg, "always" ) == 0 ) {
582 ErrorHelpers::colors = ErrorHelpers::Colors::Always;
583 } else if ( strcmp( optarg, "never" ) == 0 ) {
584 ErrorHelpers::colors = ErrorHelpers::Colors::Never;
585 } else if ( strcmp( optarg, "auto" ) == 0 ) {
586 ErrorHelpers::colors = ErrorHelpers::Colors::Auto;
587 } // if
588 break;
589 case 'h': // help message
590 usage( argv ); // no return
591 break;
592 case 'l': // generate libcfa.c
593 libcfap = true;
594 break;
595 case 'L': // generate line marks
596 linemarks = true;
597 break;
598 case 'm': // do not replace main
599 nomainp = true;
600 break;
601 case 'N': // do not generate line marks
602 linemarks = false;
603 break;
604 case 'n': // do not read prelude
605 nopreludep = true;
606 break;
607 case 'p': // generate prototypes for prelude functions
608 genproto = true;
609 break;
610 case 'd': // don't print non-deterministic output
611 deterministic_output = true;
612 break;
613 case 'O': // don't print non-deterministic output
614 useNewAST = false;
615 break;
616 case 'A': // don't print non-deterministic output
617 useNewAST = true;
618 break;
619 case 'P': // print options
620 for ( int i = 0;; i += 1 ) {
621 if ( i == printoptsSize ) {
622 cout << "Unknown --print option " << optarg << endl;
623 goto Default;
624 } // if
625 if ( strcmp( optarg, printopts[i].name ) == 0 ) {
626 printopts[i].flag = printopts[i].val;
627 break;
628 } // if
629 } // for
630 break;
631 case PreludeDir: // prelude directory for debug/nodebug, hidden
632 PreludeDirector = optarg;
633 break;
634 case 'S': // enable profiling information, argument comma separated list of names
635 Stats::parse_params( optarg );
636 break;
637 case 't': // building cfa stdlib
638 treep = true;
639 break;
640 case 'g': // wait for gdb
641 waiting_for_gdb = true;
642 break;
643 case 'w': // suppress all warnings, hidden
644 Wsuppress = true;
645 break;
646 case 'W': // coordinate gcc -W with CFA, hidden
647 if ( strcmp( optarg, "all" ) == 0 ) {
648 SemanticWarning_EnableAll();
649 } else if ( strcmp( optarg, "error" ) == 0 ) {
650 Werror = true;
651 } else {
652 char * warning = optarg;
653 Severity s;
654 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
655 warning += 3;
656 s = Severity::Suppress;
657 } else {
658 s = Severity::Warn;
659 } // if
660 SemanticWarning_Set( warning, s );
661 } // if
662 break;
663 case 'D': // ignore -Dxxx, forwarded by cpp, hidden
664 break;
665 case '?': // unknown option
666 if ( optopt ) { // short option ?
667 cout << "Unknown option -" << (char)optopt << endl;
668 } else {
669 cout << "Unknown option " << argv[optind - 1] << endl;
670 } // if
671 goto Default;
672 case ':': // missing option
673 if ( optopt ) { // short option ?
674 cout << "Missing option for -" << (char)optopt << endl;
675 } else {
676 cout << "Missing option for " << argv[optind - 1] << endl;
677 } // if
678 goto Default;
679 Default:
680 default:
681 usage( argv ); // no return
682 } // switch
683 } // while
684
685 if ( Werror ) {
686 SemanticWarning_WarningAsError();
687 } // if
688 if ( Wsuppress ) {
689 SemanticWarning_SuppressAll();
690 } // if
691 // for ( const auto w : WarningFormats ) {
692 // cout << w.name << ' ' << (int)w.severity << endl;
693 // } // for
694} // parse_cmdline
695
696static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
697 extern int yyparse( void );
698 extern FILE * yyin;
699 extern int yylineno;
700
701 ::linkage = linkage; // set globals
702 yyin = input;
703 yylineno = 1;
704 int parseStatus = yyparse();
705
706 fclose( input );
707 if ( shouldExit || parseStatus != 0 ) {
708 exit( parseStatus );
709 } // if
710} // parse
711
712static bool notPrelude( Declaration * decl ) {
713 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
714} // notPrelude
715
716static void dump( list< Declaration * > & translationUnit, ostream & out ) {
717 list< Declaration * > decls;
718
719 if ( genproto ) {
720 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
721 } else {
722 decls = translationUnit;
723 } // if
724
725 // depending on commandline options, either generate code or dump the AST
726 if ( codegenp ) {
727 CodeGen::generate( decls, out, ! genproto, prettycodegenp );
728 } else {
729 printAll( decls, out );
730 } // if
731 deleteAll( translationUnit );
732} // dump
733
734// Local Variables: //
735// tab-width: 4 //
736// mode: c++ //
737// compile-command: "make install" //
738// End: //
Note: See TracBrowser for help on using the repository browser.