source: src/main.cc@ 4d35bc6

ADT ast-experimental
Last change on this file since 4d35bc6 was f26421f, checked in by Mugilan Ganesan <mganesan@…>, 3 years ago

Removed CompilerError and UnimplementedError

  • 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
[7fffb1b]12// Last Modified On : Wed Oct 5 12:06:00 2022
13// Update Count : 679
[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" );
274 parse( gcc_builtins, LinkageSpec::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" );
[f0994a1]279 parse( extras, LinkageSpec::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" );
[35304009]285 parse( prelude, LinkageSpec::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" );
[54d714e]290 parse( builtins, LinkageSpec::BuiltinCFA );
[b87a5ed]291 } // if
292 } // if
[81419b5]293
[926af74]294 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::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
[3dd8f42]342 PASS( "Implement Actors", Concurrency::implementActors( transUnit ) );
343
[09366b8]344 PASS( "Implement Mutex", Concurrency::implementMutex( transUnit ) );
345 PASS( "Implement Thread Start", Concurrency::implementThreadStarter( transUnit ) );
346 PASS( "Compound Literal", Validate::handleCompoundLiterals( transUnit ) );
347 PASS( "Set Length From Initializer", Validate::setLengthFromInitializer( transUnit ) );
348 PASS( "Find Global Decls", Validate::findGlobalDecls( transUnit ) );
349 PASS( "Fix Label Address", Validate::fixLabelAddresses( transUnit ) );
350
351 if ( symtabp ) {
352 return EXIT_SUCCESS;
353 } // if
[ccbc65c]354
[09366b8]355 if ( expraltp ) {
356 ResolvExpr::printCandidates( transUnit );
357 return EXIT_SUCCESS;
358 } // if
[3606fe4]359
[09366b8]360 if ( validp ) {
[09f34a84]361 dump( std::move( transUnit ) );
[09366b8]362 return EXIT_SUCCESS;
363 } // if
[6a896b0]364
[09366b8]365 PASS( "Translate Throws", ControlStruct::translateThrows( transUnit ) );
366 PASS( "Fix Labels", ControlStruct::fixLabels( transUnit ) );
367 PASS( "Fix Names", CodeGen::fixNames( transUnit ) );
368 PASS( "Gen Init", InitTweak::genInit( transUnit ) );
369 PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( transUnit ) );
[ce36b55]370
[09366b8]371 if ( libcfap ) {
372 // Generate the bodies of cfa library functions.
373 LibCfa::makeLibCfa( transUnit );
374 } // if
[1622af5]375
[09366b8]376 if ( declstatsp ) {
377 printDeclStats( transUnit );
378 return EXIT_SUCCESS;
379 } // if
[1622af5]380
[09366b8]381 if ( bresolvep ) {
[09f34a84]382 dump( std::move( transUnit ) );
[09366b8]383 return EXIT_SUCCESS;
384 } // if
[1622af5]385
[09366b8]386 if ( resolvprotop ) {
387 dumpAsResolverProto( transUnit );
388 return EXIT_SUCCESS;
389 } // if
[9f5a19fa]390
[09366b8]391 PASS( "Resolve", ResolvExpr::resolve( transUnit ) );
392 if ( exprp ) {
[09f34a84]393 dump( std::move( transUnit ) );
[09366b8]394 return EXIT_SUCCESS;
395 } // if
[68fe946e]396
[09366b8]397 forceFillCodeLocations( transUnit );
[68fe946e]398
[09366b8]399 PASS( "Fix Init", InitTweak::fix(transUnit, buildingLibrary()));
[68fe946e]400
[09366b8]401 // fix ObjectDecl - replaces ConstructorInit nodes
402 if ( ctorinitp ) {
[09f34a84]403 dump( std::move( transUnit ) );
[09366b8]404 return EXIT_SUCCESS;
405 } // if
[68fe946e]406
[09366b8]407 // Currently not working due to unresolved issues with UniqueExpr
408 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]409
[09366b8]410 PASS( "Translate Tries", ControlStruct::translateTries( transUnit ) );
411 PASS( "Gen Waitfor", Concurrency::generateWaitFor( transUnit ) );
[4615ac8]412
[09366b8]413 // Needs to happen before tuple types are expanded.
414 PASS( "Convert Specializations", GenPoly::convertSpecializations( transUnit ) );
[81419b5]415
[09366b8]416 PASS( "Expand Tuples", Tuples::expandTuples( transUnit ) );
[71f4e4f]417
[09366b8]418 if ( tuplep ) {
[09f34a84]419 dump( std::move( transUnit ) );
[09366b8]420 return EXIT_SUCCESS;
421 } // if
[626dbc10]422
[09366b8]423 // Must come after Translate Tries.
424 PASS( "Virtual Expand Casts", Virtual::expandCasts( transUnit ) );
[141b786]425
[09366b8]426 PASS( "Instantiate Generics", GenPoly::instantiateGeneric( transUnit ) );
[53d3ab4b]427 if ( genericsp ) {
[7fffb1b]428 dump( std::move( transUnit ) );
[3e96559]429 return EXIT_SUCCESS;
430 } // if
[b4f8808]431
[7fffb1b]432 PASS( "Convert L-Value", GenPoly::convertLvalue( transUnit ) );
433
434 translationUnit = convert( std::move( transUnit ) );
[53d3ab4b]435
[fea7ca7]436 if ( bboxp ) {
437 dump( translationUnit );
[3e96559]438 return EXIT_SUCCESS;
[926af74]439 } // if
[675716e]440 PASS( "Box", GenPoly::box( translationUnit ) );
[81419b5]441
[aff7e86]442 PASS( "Link-Once", CodeGen::translateLinkOnce( translationUnit ) );
443
444 // Code has been lowered to C, now we can start generation.
445
[8905f56]446 if ( bcodegenp ) {
447 dump( translationUnit );
[3e96559]448 return EXIT_SUCCESS;
449 } // if
[8905f56]450
[13de47bc]451 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
452 output = new ofstream( argv[ optind ] );
453 } // if
[0270824]454
[7b15d7a]455 CodeTools::fillLocations( translationUnit );
[62ce290]456 PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! genproto, prettycodegenp, true, linemarks ) );
[0270824]457
[8e48fca4]458 CodeGen::FixMain::fix( translationUnit, *output,
459 (PreludeDirector + "/bootloader.c").c_str() );
[e6955b1]460 if ( output != &cout ) {
[b87a5ed]461 delete output;
462 } // if
[77d601f]463 } catch ( SemanticErrorException & e ) {
[b87a5ed]464 if ( errorp ) {
[e6955b1]465 cerr << "---AST at error:---" << endl;
[64b3cda]466 // We check which section the errors came from without looking at
467 // transUnit because std::move means it could look like anything.
468 if ( !translationUnit.empty() ) {
469 dump( translationUnit, cerr );
470 } else {
471 dump( std::move( transUnit ), cerr );
472 }
[e6955b1]473 cerr << endl << "---End of AST, begin error message:---\n" << endl;
[926af74]474 } // if
[d55d7a6]475 e.print();
[e6955b1]476 if ( output != &cout ) {
[b87a5ed]477 delete output;
478 } // if
[3e96559]479 return EXIT_FAILURE;
[77d601f]480 } catch ( std::bad_alloc & ) {
481 cerr << "*cfa-cpp compilation error* std::bad_alloc" << endl;
482 backtrace( 1 );
483 abort();
[3e96559]484 } catch ( ... ) {
[bffcd66]485 exception_ptr eptr = current_exception();
[4990812]486 try {
487 if (eptr) {
[bffcd66]488 rethrow_exception(eptr);
[3e96559]489 } else {
[77d601f]490 cerr << "*cfa-cpp compilation error* exception uncaught and unknown" << endl;
[3e96559]491 } // if
[77d601f]492 } catch( const exception & e ) {
493 cerr << "*cfa-cpp compilation error* uncaught exception \"" << e.what() << "\"\n";
[3e96559]494 } // try
495 return EXIT_FAILURE;
496 } // try
[b87a5ed]497
[39786813]498 deleteAll( translationUnit );
[1cb7fab2]499 Stats::print();
[3e96559]500 return EXIT_SUCCESS;
[d9a0e76]501} // main
[51b73452]502
[0da3e2c]503
[ce31925]504static const char optstring[] = ":c:ghlLmNnpdP:S:twW:D:";
[3e96559]505
[62ce290]506enum { PreludeDir = 128 };
[3e96559]507static struct option long_opts[] = {
[1a69a90]508 { "colors", required_argument, nullptr, 'c' },
509 { "gdb", no_argument, nullptr, 'g' },
[3e96559]510 { "help", no_argument, nullptr, 'h' },
511 { "libcfa", no_argument, nullptr, 'l' },
[62ce290]512 { "linemarks", no_argument, nullptr, 'L' },
[3e96559]513 { "no-main", no_argument, 0, 'm' },
[62ce290]514 { "no-linemarks", no_argument, nullptr, 'N' },
515 { "no-prelude", no_argument, nullptr, 'n' },
[3e96559]516 { "prototypes", no_argument, nullptr, 'p' },
[7215000]517 { "deterministic-out", no_argument, nullptr, 'd' },
[62ce290]518 { "print", required_argument, nullptr, 'P' },
519 { "prelude-dir", required_argument, nullptr, PreludeDir },
520 { "statistics", required_argument, nullptr, 'S' },
[3e96559]521 { "tree", no_argument, nullptr, 't' },
522 { "", no_argument, nullptr, 0 }, // -w
523 { "", no_argument, nullptr, 0 }, // -W
524 { "", no_argument, nullptr, 0 }, // -D
525 { nullptr, 0, nullptr, 0 }
526}; // long_opts
527
528static const char * description[] = {
[aa88cb9a]529 "diagnostic color: never, always, auto", // -c
[3e9de01]530 "wait for gdb to attach", // -g
[aa88cb9a]531 "print translator help message", // -h
[3e9de01]532 "generate libcfa.c", // -l
533 "generate line marks", // -L
534 "do not replace main", // -m
535 "do not generate line marks", // -N
536 "do not read prelude", // -n
[aa88cb9a]537 "do not generate prelude prototypes => prelude not printed", // -p
[3e9de01]538 "only print deterministic output", // -d
539 "print", // -P
[62ce290]540 "<directory> prelude directory for debug/nodebug", // no flag
[aa88cb9a]541 "<option-list> enable profiling information: counters, heap, time, all, none", // -S
[3e9de01]542 "building cfa standard lib", // -t
543 "", // -w
544 "", // -W
545 "", // -D
[3e96559]546}; // description
547
[0c0f548]548static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
[62ce290]549
550static struct Printopts {
551 const char * name;
552 int & flag;
553 int val;
554 const char * descript;
555} printopts[] = {
[0e464f6]556 { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
557 { "asterr", errorp, true, "print AST on error" },
[62ce290]558 { "declstats", declstatsp, true, "code property statistics" },
559 { "parse", yydebug, true, "yacc (parsing) debug information" },
560 { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
561 { "rproto", resolvprotop, true, "resolver-proto instance" },
[0e464f6]562 { "rsteps", resolvep, true, "print resolver steps" },
563 // code dumps
564 { "ast", astp, true, "print AST after parsing" },
[00da199]565 { "exdecl", exdeclp, true, "print AST after translating exception decls" },
[0e464f6]566 { "symevt", symtabp, true, "print AST after symbol table events" },
567 { "altexpr", expraltp, true, "print alternatives for expressions" },
568 { "astdecl", validp, true, "print AST after declaration validation pass" },
569 { "resolver", bresolvep, true, "print AST before resolver step" },
570 { "astexpr", exprp, true, "print AST after expression analysis" },
571 { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
572 { "tuple", tuplep, true, "print AST after tuple expansion" },
573 { "astgen", genericsp, true, "print AST after instantiate generics" },
574 { "box", bboxp, true, "print AST before box step" },
575 { "codegen", bcodegenp, true, "print AST before code generation" },
[62ce290]576};
577enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
578
[77d601f]579static void usage( char * argv[] ) {
[e0bd0f9]580 cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
[3e96559]581 int i = 0, j = 1; // j skips starting colon
582 for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
583 if ( long_opts[i].name[0] != '\0' ) { // hidden option, internal usage only
[62ce290]584 if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
585 cout << " -" << optstring[j] << ",";
586 } else { // no flag
587 j -= 1; // compensate
588 cout << " ";
589 } // if
590 cout << " --" << left << setw(12) << long_opts[i].name << " ";
591 if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
592 cout << "one of: " << endl;
593 for ( int i = 0; i < printoptsSize; i += 1 ) {
594 cout << setw(10) << " " << left << setw(10) << printopts[i].name << " " << printopts[i].descript << endl;
595 } // for
596 } else {
597 cout << description[i] << endl;
598 } // if
[3e96559]599 } // if
[62ce290]600 if ( optstring[j + 1] == ':' ) j += 1;
[3e96559]601 } // for
602 if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
603 exit( EXIT_FAILURE );
604} // usage
605
[e0bd0f9]606static void parse_cmdline( int argc, char * argv[] ) {
[0da3e2c]607 opterr = 0; // (global) prevent getopt from printing error messages
608
[c5e5109]609 bool Wsuppress = false, Werror = false;
[0da3e2c]610 int c;
[3e96559]611 while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
[0da3e2c]612 switch ( c ) {
[1a69a90]613 case 'c': // diagnostic colors
614 if ( strcmp( optarg, "always" ) == 0 ) {
615 ErrorHelpers::colors = ErrorHelpers::Colors::Always;
616 } else if ( strcmp( optarg, "never" ) == 0 ) {
617 ErrorHelpers::colors = ErrorHelpers::Colors::Never;
618 } else if ( strcmp( optarg, "auto" ) == 0 ) {
619 ErrorHelpers::colors = ErrorHelpers::Colors::Auto;
620 } // if
621 break;
[3e96559]622 case 'h': // help message
623 usage( argv ); // no return
[53d3ab4b]624 break;
[3e96559]625 case 'l': // generate libcfa.c
[0da3e2c]626 libcfap = true;
627 break;
[62ce290]628 case 'L': // generate line marks
[6de43b6]629 linemarks = true;
[c850687]630 break;
[3e96559]631 case 'm': // do not replace main
632 nomainp = true;
[0da3e2c]633 break;
[62ce290]634 case 'N': // do not generate line marks
[6de43b6]635 linemarks = false;
[c59bde6]636 break;
[62ce290]637 case 'n': // do not read prelude
[3e96559]638 nopreludep = true;
[0da3e2c]639 break;
[62ce290]640 case 'p': // generate prototypes for prelude functions
641 genproto = true;
[0da3e2c]642 break;
[7215000]643 case 'd': // don't print non-deterministic output
[a77257be]644 deterministic_output = true;
645 break;
[62ce290]646 case 'P': // print options
647 for ( int i = 0;; i += 1 ) {
648 if ( i == printoptsSize ) {
649 cout << "Unknown --print option " << optarg << endl;
650 goto Default;
651 } // if
652 if ( strcmp( optarg, printopts[i].name ) == 0 ) {
653 printopts[i].flag = printopts[i].val;
654 break;
655 } // if
656 } // for
[0da3e2c]657 break;
[62ce290]658 case PreludeDir: // prelude directory for debug/nodebug, hidden
659 PreludeDirector = optarg;
[3b3491b6]660 break;
[3e96559]661 case 'S': // enable profiling information, argument comma separated list of names
662 Stats::parse_params( optarg );
[ebcc940]663 break;
[dee1f89]664 case 't': // building cfa stdlib
[0da3e2c]665 treep = true;
666 break;
[dee1f89]667 case 'g': // wait for gdb
668 waiting_for_gdb = true;
669 break;
[3e96559]670 case 'w': // suppress all warnings, hidden
[c5e5109]671 Wsuppress = true;
[44bca7f]672 break;
[3e96559]673 case 'W': // coordinate gcc -W with CFA, hidden
[44bca7f]674 if ( strcmp( optarg, "all" ) == 0 ) {
[68e9ace]675 SemanticWarning_EnableAll();
[44bca7f]676 } else if ( strcmp( optarg, "error" ) == 0 ) {
677 Werror = true;
678 } else {
679 char * warning = optarg;
680 Severity s;
681 if ( strncmp( optarg, "no-", 3 ) == 0 ) {
682 warning += 3;
683 s = Severity::Suppress;
684 } else {
685 s = Severity::Warn;
686 } // if
[68e9ace]687 SemanticWarning_Set( warning, s );
[44bca7f]688 } // if
689 break;
[3e96559]690 case 'D': // ignore -Dxxx, forwarded by cpp, hidden
[0da3e2c]691 break;
[3e96559]692 case '?': // unknown option
693 if ( optopt ) { // short option ?
694 cout << "Unknown option -" << (char)optopt << endl;
695 } else {
696 cout << "Unknown option " << argv[optind - 1] << endl;
697 } // if
698 goto Default;
699 case ':': // missing option
[ae47a23]700 if ( optopt ) { // short option ?
[3e96559]701 cout << "Missing option for -" << (char)optopt << endl;
[ae47a23]702 } else {
[3e96559]703 cout << "Missing option for " << argv[optind - 1] << endl;
[ae47a23]704 } // if
[3e96559]705 goto Default;
706 Default:
707 default:
708 usage( argv ); // no return
[0da3e2c]709 } // switch
710 } // while
[44bca7f]711
712 if ( Werror ) {
[68e9ace]713 SemanticWarning_WarningAsError();
[44bca7f]714 } // if
[c5e5109]715 if ( Wsuppress ) {
716 SemanticWarning_SuppressAll();
717 } // if
[44bca7f]718 // for ( const auto w : WarningFormats ) {
719 // cout << w.name << ' ' << (int)w.severity << endl;
720 // } // for
[0da3e2c]721} // parse_cmdline
722
[1ab4ce2]723static bool notPrelude( Declaration * decl ) {
724 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
[0da3e2c]725} // notPrelude
[1ab4ce2]726
[e6955b1]727static void dump( list< Declaration * > & translationUnit, ostream & out ) {
728 list< Declaration * > decls;
[926af74]729
[62ce290]730 if ( genproto ) {
[e6955b1]731 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
[1ab4ce2]732 } else {
733 decls = translationUnit;
[926af74]734 } // if
[1ab4ce2]735
[e39241b]736 // depending on commandline options, either generate code or dump the AST
737 if ( codegenp ) {
[62ce290]738 CodeGen::generate( decls, out, ! genproto, prettycodegenp );
[e39241b]739 } else {
740 printAll( decls, out );
[3e96559]741 } // if
[7f5566b]742 deleteAll( translationUnit );
[0da3e2c]743} // dump
[1ab4ce2]744
[e499381]745static void dump( ast::TranslationUnit && transUnit, ostream & out ) {
[09f34a84]746 std::list< Declaration * > translationUnit = convert( std::move( transUnit ) );
[e499381]747 dump( translationUnit, out );
748}
749
[51b73452]750// Local Variables: //
[b87a5ed]751// tab-width: 4 //
752// mode: c++ //
753// compile-command: "make install" //
[51b73452]754// End: //
Note: See TracBrowser for help on using the repository browser.