source: src/main.cc @ 63f42a8

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 63f42a8 was aff7e86, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Added a new attribute 'cfa_linkonce'.

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