source: src/main.cc @ 1e24d13

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 1e24d13 was ef22ad6, checked in by Peter A. Buhr <pabuhr@…>, 5 years ago

deal with conflicts

  • Property mode set to 100644
File size: 24.1 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
[ef22ad6]12// Last Modified On : Fri Aug 23 06:50:08 2019
13// Update Count     : 607
[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
[ef22ad6]98static bool waiting_for_gdb = false;                                    // flag to set cfa-cpp to wait for gdb on start
[dee1f89]99
[3e96559]100static std::string PreludeDirector = "";
[4dcaed2]101
[e0bd0f9]102static void parse_cmdline( int argc, char *argv[] );
[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;
[e6955b1]174        list< Declaration * > translationUnit;
175
176        signal( SIGSEGV, sigSegvBusHandler );
177        signal( SIGBUS, sigSegvBusHandler );
[b542bfb]178        signal( SIGABRT, sigAbortHandler );
[b87a5ed]179
[44bca7f]180        // std::cout << "main" << std::endl;
181        // for ( int i = 0; i < argc; i += 1 ) {
182        //      std::cout << '\t' << argv[i] << std::endl;
183        // } // for
184
[e0bd0f9]185        parse_cmdline( argc, argv );                                            // process command-line arguments
[13de47bc]186        CodeGen::FixMain::setReplaceMain( !nomainp );
[b87a5ed]187
[ef22ad6]188        if ( waiting_for_gdb ) {
[dee1f89]189                std::cerr << "Waiting for gdb" << std::endl;
190                std::cerr << "run :" << std::endl;
191                std::cerr << "  gdb attach " << getpid() << std::endl;
192                raise(SIGSTOP);
[ef22ad6]193        } // if
[dee1f89]194
[b87a5ed]195        try {
[81419b5]196                // choose to read the program from a file or stdin
[3b8e52c]197                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
[b87a5ed]198                        input = fopen( argv[ optind ], "r" );
[e0bd0f9]199                        assertf( input, "cannot open %s because %s\n", argv[ optind ], strerror( errno ) );
[b87a5ed]200                        optind += 1;
[3b8e52c]201                } else {                                                                                // no input file name
[b87a5ed]202                        input = stdin;
203                } // if
204
[79eaeb7]205                Stats::Time::StartGlobal();
[3c0d4cd]206                NewPass("Parse");
207                Stats::Time::StartBlock("Parse");
[675716e]208
[159c62e]209                // read in the builtins, extras, and the prelude
[de62360d]210                if ( ! nopreludep ) {                                                   // include gcc builtins
[faf8857]211                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
[807ce84]212
[37fe352]213                        assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );
[4dcaed2]214
[807ce84]215                        // Read to gcc builtins, if not generating the cfa library
[37fe352]216                        FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
[6ce3ae9]217                        assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
218                        parse( gcc_builtins, LinkageSpec::Compiler );
[81419b5]219
[159c62e]220                        // read the extra prelude in, if not generating the cfa library
[37fe352]221                        FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
[3b8e52c]222                        assertf( extras, "cannot open extras.cf\n" );
[f0994a1]223                        parse( extras, LinkageSpec::BuiltinC );
[159c62e]224
[81419b5]225                        if ( ! libcfap ) {
[faf8857]226                                // read the prelude in, if not generating the cfa library
[e523b07]227                                FILE * prelude = fopen( (PreludeDirector + "/prelude.cfa").c_str(), "r" );
228                                assertf( prelude, "cannot open prelude.cfa\n" );
[35304009]229                                parse( prelude, LinkageSpec::Intrinsic );
[fa4805f]230
231                                // Read to cfa builtins, if not generating the cfa library
[37fe352]232                                FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
[fa4805f]233                                assertf( builtins, "cannot open builtins.cf\n" );
[54d714e]234                                parse( builtins, LinkageSpec::BuiltinCFA );
[b87a5ed]235                        } // if
236                } // if
[81419b5]237
[926af74]238                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
[71f4e4f]239
[b87a5ed]240                if ( parsep ) {
[e6955b1]241                        parseTree->printList( cout );
[0da3e2c]242                        delete parseTree;
[3e96559]243                        return EXIT_SUCCESS;
[b87a5ed]244                } // if
245
[0da3e2c]246                buildList( parseTree, translationUnit );
247                delete parseTree;
[cbaee0d]248                parseTree = nullptr;
[b87a5ed]249
250                if ( astp ) {
[1ab4ce2]251                        dump( translationUnit );
[3e96559]252                        return EXIT_SUCCESS;
[b87a5ed]253                } // if
254
[036dd5f]255                // Temporary: fill locations after parsing so that every node has a location, for early error messages.
256                // Eventually we should pass the locations from the parser to every node, but this quick and dirty solution
257                // works okay for now.
258                CodeTools::fillLocations( translationUnit );
[3c0d4cd]259                Stats::Time::StopBlock();
[036dd5f]260
[4615ac8]261                //std::cerr << "Post-Parse Check" << std::endl;
262                clearInnerLvalue( translationUnit );
263                assertTopLvalue( translationUnit );
264
[839ccbb]265                // add the assignment statement after the initialization of a type parameter
[675716e]266                PASS( "Validate", SymTab::validate( translationUnit, symtabp ) );
[81419b5]267                if ( symtabp ) {
[46f6134]268                        deleteAll( translationUnit );
[3e96559]269                        return EXIT_SUCCESS;
[b87a5ed]270                } // if
271
[81419b5]272                if ( expraltp ) {
[bff09c8]273                        PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
[81419b5]274                        acceptAll( translationUnit, printer );
[3e96559]275                        return EXIT_SUCCESS;
[b87a5ed]276                } // if
277
278                if ( validp ) {
[1ab4ce2]279                        dump( translationUnit );
[3e96559]280                        return EXIT_SUCCESS;
[b87a5ed]281                } // if
282
[4615ac8]283                assertTopLvalue( translationUnit );
[675716e]284                PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
[4615ac8]285                assertTopLvalue( translationUnit );
[675716e]286                PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
[4615ac8]287                assertTopLvalue( translationUnit );
[675716e]288                PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
[4615ac8]289                assertTopLvalue( translationUnit );
[675716e]290                PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
[4615ac8]291                assertTopLvalue( translationUnit );
[81419b5]292                if ( libcfap ) {
293                        // generate the bodies of cfa library functions
294                        LibCfa::makeLibCfa( translationUnit );
[b87a5ed]295                } // if
296
[fa2de95]297                if ( declstatsp ) {
298                        CodeTools::printDeclStats( translationUnit );
299                        deleteAll( translationUnit );
[3e96559]300                        return EXIT_SUCCESS;
301                } // if
[fa2de95]302
[de62360d]303                if ( bresolvep ) {
[1ab4ce2]304                        dump( translationUnit );
[3e96559]305                        return EXIT_SUCCESS;
[de62360d]306                } // if
307
[76b378d]308                CodeTools::fillLocations( translationUnit );
309
[3b3491b]310                if ( resolvprotop ) {
311                        CodeTools::dumpAsResolvProto( translationUnit );
[3e96559]312                        return EXIT_SUCCESS;
313                } // if
[3b3491b]314
[4615ac8]315                assertTopLvalue( translationUnit );
316
[675716e]317                PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
[81419b5]318                if ( exprp ) {
[1ab4ce2]319                        dump( translationUnit );
[3e96559]320                        return EXIT_SUCCESS;
[926af74]321                } // if
[81419b5]322
[4615ac8]323                clearInnerLvalue( translationUnit );
324                assertTopLvalue( translationUnit );
325
[71f4e4f]326                // fix ObjectDecl - replaces ConstructorInit nodes
[675716e]327                PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
[4615ac8]328                clearInnerLvalue( translationUnit );
329                assertTopLvalue( translationUnit );
[ca1c11f]330                if ( ctorinitp ) {
331                        dump ( translationUnit );
[3e96559]332                        return EXIT_SUCCESS;
[926af74]333                } // if
[71f4e4f]334
[675716e]335                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]336                assertTopLvalue( translationUnit );
[626dbc10]337
[675716e]338                PASS( "Translate EHM" , ControlStruct::translateEHM( translationUnit ) );
[4615ac8]339                assertTopLvalue( translationUnit );
[6edd210]340
[675716e]341                PASS( "Gen Waitfor" , Concurrency::generateWaitFor( translationUnit ) );
[4615ac8]342                clearInnerLvalue( translationUnit );
343                assertTopLvalue( translationUnit );
[307a732]344
[675716e]345                PASS( "Convert Specializations",  GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
[4615ac8]346                clearInnerLvalue( translationUnit );
347                assertTopLvalue( translationUnit );
[9f5ecf5]348
[675716e]349                PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
[4615ac8]350                assertTopLvalue( translationUnit );
[626dbc10]351
352                if ( tuplep ) {
353                        dump( translationUnit );
[3e96559]354                        return EXIT_SUCCESS;
355                } // if
[141b786]356
[675716e]357                PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
[4615ac8]358                assertTopLvalue( translationUnit );
[a5f0529]359
[675716e]360                PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
[53d3ab4b]361                if ( genericsp ) {
362                        dump( translationUnit );
[3e96559]363                        return EXIT_SUCCESS;
364                } // if
[4615ac8]365                clearInnerLvalue( translationUnit );
366                assertTopLvalue( translationUnit );
[675716e]367                PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );
[4615ac8]368                clearInnerLvalue( translationUnit );
369                assertTopLvalue( translationUnit );
[53d3ab4b]370
[fea7ca7]371                if ( bboxp ) {
372                        dump( translationUnit );
[3e96559]373                        return EXIT_SUCCESS;
[926af74]374                } // if
[675716e]375                PASS( "Box", GenPoly::box( translationUnit ) );
[4615ac8]376                clearInnerLvalue( translationUnit );
377                assertTopLvalue( translationUnit );
[81419b5]378
[8905f56]379                if ( bcodegenp ) {
380                        dump( translationUnit );
[3e96559]381                        return EXIT_SUCCESS;
382                } // if
[8905f56]383
[13de47bc]384                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
385                        output = new ofstream( argv[ optind ] );
386                } // if
[0270824]387
[7b15d7a]388                CodeTools::fillLocations( translationUnit );
[4615ac8]389                assertTopLvalue( translationUnit );
[62ce290]390                PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! genproto, prettycodegenp, true, linemarks ) );
[0270824]391
[37fe352]392                CodeGen::FixMain::fix( *output, (PreludeDirector + "/bootloader.c").c_str() );
[e6955b1]393                if ( output != &cout ) {
[b87a5ed]394                        delete output;
395                } // if
[a16764a6]396        } catch ( SemanticErrorException &e ) {
[b87a5ed]397                if ( errorp ) {
[e6955b1]398                        cerr << "---AST at error:---" << endl;
399                        dump( translationUnit, cerr );
400                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
[926af74]401                } // if
[d55d7a6]402                e.print();
[e6955b1]403                if ( output != &cout ) {
[b87a5ed]404                        delete output;
405                } // if
[3e96559]406                return EXIT_FAILURE;
[b87a5ed]407        } catch ( UnimplementedError &e ) {
[e6955b1]408                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
409                if ( output != &cout ) {
[b87a5ed]410                        delete output;
411                } // if
[3e96559]412                return EXIT_FAILURE;
[b87a5ed]413        } catch ( CompilerError &e ) {
[e6955b1]414                cerr << "Compiler Error: " << e.get_what() << endl;
[c850687]415                cerr << "(please report bugs to [REDACTED])" << endl;
[e6955b1]416                if ( output != &cout ) {
[b87a5ed]417                        delete output;
418                } // if
[3e96559]419                return EXIT_FAILURE;
420        } catch ( ... ) {
[4990812]421                std::exception_ptr eptr = std::current_exception();
422                try {
423                        if (eptr) {
424                                std::rethrow_exception(eptr);
[3e96559]425                        } else {
426                                std::cerr << "Exception Uncaught and Unknown" << std::endl;
427                        } // if
[4990812]428                } catch(const std::exception& e) {
[0689cd9]429                        std::cerr << "Uncaught Exception \"" << e.what() << "\"\n";
[3e96559]430                } // try
431                return EXIT_FAILURE;
432        } // try
[b87a5ed]433
[39786813]434        deleteAll( translationUnit );
[1cb7fab2]435        Stats::print();
[3e96559]436        return EXIT_SUCCESS;
[d9a0e76]437} // main
[51b7345]438
[0da3e2c]439
[e0bd0f9]440static const char optstring[] = ":hlLmNnpP:S:twW:D:";
[3e96559]441
[62ce290]442enum { PreludeDir = 128 };
[3e96559]443static struct option long_opts[] = {
444        { "help", no_argument, nullptr, 'h' },
445        { "libcfa", no_argument, nullptr, 'l' },
[62ce290]446        { "linemarks", no_argument, nullptr, 'L' },
[3e96559]447        { "no-main", no_argument, 0, 'm' },
[62ce290]448        { "no-linemarks", no_argument, nullptr, 'N' },
449        { "no-prelude", no_argument, nullptr, 'n' },
[3e96559]450        { "prototypes", no_argument, nullptr, 'p' },
[62ce290]451        { "print", required_argument, nullptr, 'P' },
452        { "prelude-dir", required_argument, nullptr, PreludeDir },
453        { "statistics", required_argument, nullptr, 'S' },
[3e96559]454        { "tree", no_argument, nullptr, 't' },
[dee1f89]455        { "gdb", no_argument, nullptr, 'g' },
[3e96559]456        { "", no_argument, nullptr, 0 },                                        // -w
457        { "", no_argument, nullptr, 0 },                                        // -W
458        { "", no_argument, nullptr, 0 },                                        // -D
459        { nullptr, 0, nullptr, 0 }
460}; // long_opts
461
462static const char * description[] = {
[62ce290]463        "print help message",                                                           // -h
[3e96559]464        "generate libcfa.c",                                                            // -l
[62ce290]465        "generate line marks",                                                          // -L
[3e96559]466        "do not replace main",                                                          // -m
[62ce290]467        "do not generate line marks",                                           // -N
468        "do not read prelude",                                                          // -n
469        "generate prototypes for prelude functions",            // -p
470        "print",                                                                                        // -P
471        "<directory> prelude directory for debug/nodebug",      // no flag
472        "<option-list> enable profiling information:\n          counters,heap,time,all,none", // -S
[dee1f89]473        "building cfa standard lib",                                                                    // -t
474        "wait for gdb to attach",                                                                       // -g
[3e96559]475        "",                                                                                                     // -w
476        "",                                                                                                     // -W
477        "",                                                                                                     // -D
478}; // description
479
[0c0f548]480static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
[62ce290]481
482static struct Printopts {
483        const char * name;
484        int & flag;
485        int val;
486        const char * descript;
487} printopts[] = {
[0e464f6]488        { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
489        { "asterr", errorp, true, "print AST on error" },
[62ce290]490        { "declstats", declstatsp, true, "code property statistics" },
491        { "parse", yydebug, true, "yacc (parsing) debug information" },
492        { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
493        { "rproto", resolvprotop, true, "resolver-proto instance" },
[0e464f6]494        { "rsteps", resolvep, true, "print resolver steps" },
495        { "tree", parsep, true, "print parse tree" },
496        // code dumps
497        { "ast", astp, true, "print AST after parsing" },
498        { "symevt", symtabp, true, "print AST after symbol table events" },
499        { "altexpr", expraltp, true, "print alternatives for expressions" },
500        { "astdecl", validp, true, "print AST after declaration validation pass" },
501        { "resolver", bresolvep, true, "print AST before resolver step" },
502        { "astexpr", exprp, true, "print AST after expression analysis" },
503        { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
504        { "tuple", tuplep, true, "print AST after tuple expansion" },
505        { "astgen", genericsp, true, "print AST after instantiate generics" },
506        { "box", bboxp, true, "print AST before box step" },
507        { "codegen", bcodegenp, true, "print AST before code generation" },
[62ce290]508};
509enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
510
[3e96559]511static void usage( char *argv[] ) {
[e0bd0f9]512    cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
[3e96559]513        int i = 0, j = 1;                                                                       // j skips starting colon
514        for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
515                if ( long_opts[i].name[0] != '\0' ) {                   // hidden option, internal usage only
[62ce290]516                        if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
517                                cout << "  -" << optstring[j] << ",";
518                        } else {                                                                        // no flag
519                                j -= 1;                                                                 // compensate
520                                cout << "     ";
521                        } // if
522                        cout << " --" << left << setw(12) << long_opts[i].name << "  ";
523                        if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
524                                cout << "one of: " << endl;
525                                for ( int i = 0; i < printoptsSize; i += 1 ) {
526                                        cout << setw(10) << " " << left << setw(10) << printopts[i].name << "  " << printopts[i].descript << endl;
527                                } // for
528                        } else {
529                                cout << description[i] << endl;
530                        } // if
[3e96559]531                } // if
[62ce290]532                if ( optstring[j + 1] == ':' ) j += 1;
[3e96559]533        } // for
534        if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
535    exit( EXIT_FAILURE );
536} // usage
537
[e0bd0f9]538static void parse_cmdline( int argc, char * argv[] ) {
[0da3e2c]539        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
540
[c5e5109]541        bool Wsuppress = false, Werror = false;
[0da3e2c]542        int c;
[3e96559]543        while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
[0da3e2c]544                switch ( c ) {
[3e96559]545                  case 'h':                                                                             // help message
546                        usage( argv );                                                          // no return
[53d3ab4b]547                        break;
[3e96559]548                  case 'l':                                                                             // generate libcfa.c
[0da3e2c]549                        libcfap = true;
550                        break;
[62ce290]551                  case 'L':                                                                             // generate line marks
[6de43b6]552                        linemarks = true;
[c850687]553                        break;
[3e96559]554                  case 'm':                                                                             // do not replace main
555                        nomainp = true;
[0da3e2c]556                        break;
[62ce290]557                  case 'N':                                                                             // do not generate line marks
[6de43b6]558                        linemarks = false;
[c59bde6]559                        break;
[62ce290]560                  case 'n':                                                                             // do not read prelude
[3e96559]561                        nopreludep = true;
[0da3e2c]562                        break;
[62ce290]563                  case 'p':                                                                             // generate prototypes for prelude functions
564                        genproto = true;
[0da3e2c]565                        break;
[62ce290]566                  case 'P':                                                                             // print options
567                        for ( int i = 0;; i += 1 ) {
568                                if ( i == printoptsSize ) {
569                                        cout << "Unknown --print option " << optarg << endl;
570                                        goto Default;
571                                } // if
572                                if ( strcmp( optarg, printopts[i].name ) == 0 ) {
573                                        printopts[i].flag = printopts[i].val;
574                                        break;
575                                } // if
576                        } // for
[0da3e2c]577                        break;
[62ce290]578                  case PreludeDir:                                                              // prelude directory for debug/nodebug, hidden
579                        PreludeDirector = optarg;
[3b3491b]580                        break;
[3e96559]581                  case 'S':                                                                             // enable profiling information, argument comma separated list of names
582                        Stats::parse_params( optarg );
[ebcc940]583                        break;
[dee1f89]584                  case 't':                                                                             // building cfa stdlib
[0da3e2c]585                        treep = true;
586                        break;
[dee1f89]587                  case 'g':                                                                             // wait for gdb
588                        waiting_for_gdb = true;
589                        break;
[3e96559]590                  case 'w':                                                                             // suppress all warnings, hidden
[c5e5109]591                        Wsuppress = true;
[44bca7f]592                        break;
[3e96559]593                  case 'W':                                                                             // coordinate gcc -W with CFA, hidden
[44bca7f]594                        if ( strcmp( optarg, "all" ) == 0 ) {
[68e9ace]595                                SemanticWarning_EnableAll();
[44bca7f]596                        } else if ( strcmp( optarg, "error" ) == 0 ) {
597                                Werror = true;
598                        } else {
599                                char * warning = optarg;
600                                Severity s;
601                                if ( strncmp( optarg, "no-", 3 ) == 0 ) {
602                                        warning += 3;
603                                        s = Severity::Suppress;
604                                } else {
605                                        s = Severity::Warn;
606                                } // if
[68e9ace]607                                SemanticWarning_Set( warning, s );
[44bca7f]608                        } // if
609                        break;
[3e96559]610                  case 'D':                                                                             // ignore -Dxxx, forwarded by cpp, hidden
[0da3e2c]611                        break;
[3e96559]612                  case '?':                                                                             // unknown option
613                        if ( optopt ) {                                                         // short option ?
614                                cout << "Unknown option -" << (char)optopt << endl;
615                        } else {
616                                cout << "Unknown option " << argv[optind - 1] << endl;
617                        } // if
618                        goto Default;
619                  case ':':                                                                             // missing option
[ae47a23]620                        if ( optopt ) {                                                         // short option ?
[3e96559]621                                cout << "Missing option for -" << (char)optopt << endl;
[ae47a23]622                        } else {
[3e96559]623                                cout << "Missing option for " << argv[optind - 1] << endl;
[ae47a23]624                        } // if
[3e96559]625                        goto Default;
626                  Default:
627                  default:
628                        usage( argv );                                                          // no return
[0da3e2c]629                } // switch
630        } // while
[44bca7f]631
632        if ( Werror ) {
[68e9ace]633                SemanticWarning_WarningAsError();
[44bca7f]634        } // if
[c5e5109]635        if ( Wsuppress ) {
636                SemanticWarning_SuppressAll();
637        } // if
[44bca7f]638        // for ( const auto w : WarningFormats ) {
639        //      cout << w.name << ' ' << (int)w.severity << endl;
640        // } // for
[0da3e2c]641} // parse_cmdline
642
[8b7ee09]643static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
[0da3e2c]644        extern int yyparse( void );
[cbaee0d]645        extern FILE * yyin;
[0da3e2c]646        extern int yylineno;
647
[8b7ee09]648        ::linkage = linkage;                                                            // set globals
[0da3e2c]649        yyin = input;
650        yylineno = 1;
651        int parseStatus = yyparse();
[81419b5]652
653        fclose( input );
[0da3e2c]654        if ( shouldExit || parseStatus != 0 ) {
655                exit( parseStatus );
[81419b5]656        } // if
[0da3e2c]657} // parse
[81419b5]658
[1ab4ce2]659static bool notPrelude( Declaration * decl ) {
660        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
[0da3e2c]661} // notPrelude
[1ab4ce2]662
[e6955b1]663static void dump( list< Declaration * > & translationUnit, ostream & out ) {
664        list< Declaration * > decls;
[926af74]665
[62ce290]666        if ( genproto ) {
[e6955b1]667                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
[1ab4ce2]668        } else {
669                decls = translationUnit;
[926af74]670        } // if
[1ab4ce2]671
[e39241b]672        // depending on commandline options, either generate code or dump the AST
673        if ( codegenp ) {
[62ce290]674                CodeGen::generate( decls, out, ! genproto, prettycodegenp );
[e39241b]675        } else {
676                printAll( decls, out );
[3e96559]677        } // if
[7f5566b]678        deleteAll( translationUnit );
[0da3e2c]679} // dump
[1ab4ce2]680
[51b7345]681// Local Variables: //
[b87a5ed]682// tab-width: 4 //
683// mode: c++ //
684// compile-command: "make install" //
[51b7345]685// End:  //
Note: See TracBrowser for help on using the repository browser.