source: src/main.cc @ d912bed

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

harmonize signal handling in main.cc with interpose.cfa, consider refactoring all signal code into a separate module

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