source: src/main.cc @ eb211bf

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since eb211bf was b56ad5e, checked in by Fangren Yu <f37yu@…>, 2 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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