source: src/main.cc @ 48a91e2

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 48a91e2 was 33b7d49, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Added another check to checkInvariants for code locations. I also went through and made sure you can put it every after every new AST pass not followed by a forceFillCodeLocations.

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