source: src/main.cc@ a73c16e

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

Updated DeclStats for the new ast. Also fixed a bug in the old implementation (apparently it hasn't been used since gcc-builtins were added).

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