source: src/main.cc @ d0a00a5a

ADTast-experimental
Last change on this file since d0a00a5a was 09f34a84, checked in by Thierry Delisle <tdelisle@…>, 21 months ago

Remove some of the warnings on the new clang

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