source: src/main.cc @ 353aaba

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 353aaba was 77d601f, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

dump core for cfa-cpp bad_alloc exception

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