source: src/main.cc@ d40555e

ADT ast-experimental
Last change on this file since d40555e was f2f595d7, checked in by Andrew Beach <ajbeach@…>, 3 years ago

RunParser now uses AST for its interface everywhere. (Works because LinkageSpec::Spec and ast::Linkage::Spec have the same layout.)

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