source: src/main.cc@ c5af4f9

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

My work in progress implementation of ForallPointerDecay for Fangren.

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