source: src/main.cc @ 474d610

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 474d610 was 77d601f, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

dump core for cfa-cpp bad_alloc exception

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