source: src/main.cc@ 22226e4

ADT ast-experimental enum pthread-emulation qualifiedEnum
Last change on this file since 22226e4 was 33b7d49, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Added another check to checkInvariants for code locations. I also went through and made sure you can put it every after every new AST pass not followed by a forceFillCodeLocations.

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