source: src/main.cc@ 5f3ba11

ADT ast-experimental enum forall-pointer-decay pthread-emulation qualifiedEnum
Last change on this file since 5f3ba11 was 5f3ba11, checked in by Fangren Yu <f37yu@…>, 4 years ago

TranslateTries pass

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