source: src/main.cc@ 637240f

ADT ast-experimental enum forall-pointer-decay pthread-emulation qualifiedEnum
Last change on this file since 637240f was 8e48fca4, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Combined the code in FixMain so it is all done with one pass.

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