source: src/main.cc @ 4c51aca

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 4c51aca was dee1f89, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Libcfa make can now stop cfa-cpp when starting so a gdb session will be attached to it.
Use make ... gdbwaittarget=FILENAME where the filename is the same as the one printed when building with the silent rules.
cfa-cpp will print the gdb command to attach to it.
You may need to change linux permissions for gdb attach, just Google it.

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