source: src/main.cc @ bae0d35

ADTast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since bae0d35 was 1f68d5d, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Changed signal handling to avoid incompatible pointer cast

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