source: src/main.cc@ 40a64f78

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

First translation of the Gen Init pass. Passed the tests.

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