source: src/main.cc @ a5294af

ast-experimental
Last change on this file since a5294af was bccd70a, checked in by Andrew Beach <ajbeach@…>, 13 months ago

Removed internal code from TypeSubstitution? header. It caused a chain of include problems, which have been corrected.

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