source: src/main.cc@ ee56a4f

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

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

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