source: src/main.cc @ 1894e03

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since 1894e03 was 2cf3b87, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Translated valitate-E after much bug hunting.

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