source: src/main.cc @ a5a6a1a8

ADTast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since a5a6a1a8 was 00da199, checked in by Henry Xue <y58xue@…>, 3 years ago

Add a switch to print AST after exdecl pass

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