source: src/main.cc @ 4c51aca

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

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

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