source: src/main.cc @ 93f74c0f

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 93f74c0f was aff7e86, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Added a new attribute 'cfa_linkonce'.

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