source: src/main.cc @ b7fd9daf

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since b7fd9daf was b7fd9daf, checked in by Fangren Yu <f37yu@…>, 2 years ago

Merge branch 'new-ast-unique-expr'

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