source: src/main.cc @ 0c730d9

ADTast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 0c730d9 was 0c730d9, checked in by Henry Xue <y58xue@…>, 3 years ago

Translate exception declarations

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