source: src/main.cc @ 5ee153d

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since 5ee153d was 5ee153d, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Translated the Translate Throws pass to the new ast.

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