source: src/main.cc @ 45040b61

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

Translated the first half of validate-D. HoistControlStruct? is pretty much the same, Autogen has changed a lot due to the changes in the AST.

  • Property mode set to 100644
File size: 31.2 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                        translationUnit = convert( move( transUnit ) );
418                } else {
419                        PASS( "Validate-D", SymTab::validate_D( translationUnit ) );
420                        PASS( "Validate-E", SymTab::validate_E( translationUnit ) );
421                        PASS( "Validate-F", SymTab::validate_F( translationUnit ) );
422
423                        if ( symtabp ) {
424                                deleteAll( translationUnit );
425                                return EXIT_SUCCESS;
426                        } // if
427
428                        if ( expraltp ) {
429                                PassVisitor<ResolvExpr::AlternativePrinter> printer( cout );
430                                acceptAll( translationUnit, printer );
431                                return EXIT_SUCCESS;
432                        } // if
433
434                        if ( validp ) {
435                                dump( translationUnit );
436                                return EXIT_SUCCESS;
437                        } // if
438
439                        PASS( "Translate Throws", ControlStruct::translateThrows( translationUnit ) );
440                        PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
441                        PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
442                        PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
443                        PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
444
445                        if ( libcfap ) {
446                                // Generate the bodies of cfa library functions.
447                                LibCfa::makeLibCfa( translationUnit );
448                        } // if
449
450                        if ( declstatsp ) {
451                                CodeTools::printDeclStats( translationUnit );
452                                deleteAll( translationUnit );
453                                return EXIT_SUCCESS;
454                        } // if
455
456                        if ( bresolvep ) {
457                                dump( translationUnit );
458                                return EXIT_SUCCESS;
459                        } // if
460
461                        CodeTools::fillLocations( translationUnit );
462
463                        if ( resolvprotop ) {
464                                CodeTools::dumpAsResolvProto( translationUnit );
465                                return EXIT_SUCCESS;
466                        } // if
467
468                        PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
469                        if ( exprp ) {
470                                dump( translationUnit );
471                                return EXIT_SUCCESS;
472                        }
473
474                        PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
475
476                        // fix ObjectDecl - replaces ConstructorInit nodes
477                        if ( ctorinitp ) {
478                                dump ( translationUnit );
479                                return EXIT_SUCCESS;
480                        } // if
481
482                        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
483                }
484
485                PASS( "Translate Tries" , ControlStruct::translateTries( translationUnit ) );
486
487                PASS( "Gen Waitfor" , Concurrency::generateWaitFor( translationUnit ) );
488
489                PASS( "Convert Specializations",  GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded
490
491                PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?
492
493                if ( tuplep ) {
494                        dump( translationUnit );
495                        return EXIT_SUCCESS;
496                } // if
497
498                PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM
499
500                PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
501                if ( genericsp ) {
502                        dump( translationUnit );
503                        return EXIT_SUCCESS;
504                } // if
505
506                PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );
507
508                if ( bboxp ) {
509                        dump( translationUnit );
510                        return EXIT_SUCCESS;
511                } // if
512                PASS( "Box", GenPoly::box( translationUnit ) );
513
514                PASS( "Link-Once", CodeGen::translateLinkOnce( translationUnit ) );
515
516                // Code has been lowered to C, now we can start generation.
517
518                if ( bcodegenp ) {
519                        dump( translationUnit );
520                        return EXIT_SUCCESS;
521                } // if
522
523                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
524                        output = new ofstream( argv[ optind ] );
525                } // if
526
527                CodeTools::fillLocations( translationUnit );
528                PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! genproto, prettycodegenp, true, linemarks ) );
529
530                CodeGen::FixMain::fix( translationUnit, *output,
531                                (PreludeDirector + "/bootloader.c").c_str() );
532                if ( output != &cout ) {
533                        delete output;
534                } // if
535        } catch ( SemanticErrorException & e ) {
536                if ( errorp ) {
537                        cerr << "---AST at error:---" << endl;
538                        dump( translationUnit, cerr );
539                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
540                } // if
541                e.print();
542                if ( output != &cout ) {
543                        delete output;
544                } // if
545                return EXIT_FAILURE;
546        } catch ( UnimplementedError & e ) {
547                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
548                if ( output != &cout ) {
549                        delete output;
550                } // if
551                return EXIT_FAILURE;
552        } catch ( CompilerError & e ) {
553                cerr << "Compiler Error: " << e.get_what() << endl;
554                cerr << "(please report bugs to [REDACTED])" << endl;
555                if ( output != &cout ) {
556                        delete output;
557                } // if
558                return EXIT_FAILURE;
559        } catch ( std::bad_alloc & ) {
560                cerr << "*cfa-cpp compilation error* std::bad_alloc" << endl;
561                backtrace( 1 );
562                abort();
563        } catch ( ... ) {
564                exception_ptr eptr = current_exception();
565                try {
566                        if (eptr) {
567                                rethrow_exception(eptr);
568                        } else {
569                                cerr << "*cfa-cpp compilation error* exception uncaught and unknown" << endl;
570                        } // if
571                } catch( const exception & e ) {
572                        cerr << "*cfa-cpp compilation error* uncaught exception \"" << e.what() << "\"\n";
573                } // try
574                return EXIT_FAILURE;
575        } // try
576
577        deleteAll( translationUnit );
578        Stats::print();
579        return EXIT_SUCCESS;
580} // main
581
582
583static const char optstring[] = ":c:ghlLmNnpdOAP:S:twW:D:";
584
585enum { PreludeDir = 128 };
586static struct option long_opts[] = {
587        { "colors", required_argument, nullptr, 'c' },
588        { "gdb", no_argument, nullptr, 'g' },
589        { "help", no_argument, nullptr, 'h' },
590        { "libcfa", no_argument, nullptr, 'l' },
591        { "linemarks", no_argument, nullptr, 'L' },
592        { "no-main", no_argument, 0, 'm' },
593        { "no-linemarks", no_argument, nullptr, 'N' },
594        { "no-prelude", no_argument, nullptr, 'n' },
595        { "prototypes", no_argument, nullptr, 'p' },
596        { "deterministic-out", no_argument, nullptr, 'd' },
597        { "old-ast", no_argument, nullptr, 'O'},
598        { "new-ast", no_argument, nullptr, 'A'},
599        { "print", required_argument, nullptr, 'P' },
600        { "prelude-dir", required_argument, nullptr, PreludeDir },
601        { "statistics", required_argument, nullptr, 'S' },
602        { "tree", no_argument, nullptr, 't' },
603        { "", no_argument, nullptr, 0 },                                        // -w
604        { "", no_argument, nullptr, 0 },                                        // -W
605        { "", no_argument, nullptr, 0 },                                        // -D
606        { nullptr, 0, nullptr, 0 }
607}; // long_opts
608
609static const char * description[] = {
610        "diagnostic color: never, always, auto",                        // -c
611        "wait for gdb to attach",                                                       // -g
612        "print translator help message",                                        // -h
613        "generate libcfa.c",                                                            // -l
614        "generate line marks",                                                          // -L
615        "do not replace main",                                                          // -m
616        "do not generate line marks",                                           // -N
617        "do not read prelude",                                                          // -n
618        "do not generate prelude prototypes => prelude not printed", // -p
619        "only print deterministic output",                  // -d
620        "Use the old-ast",                                                                      // -O
621        "Use the new-ast",                                                                      // -A
622        "print",                                                                                        // -P
623        "<directory> prelude directory for debug/nodebug",      // no flag
624        "<option-list> enable profiling information: counters, heap, time, all, none", // -S
625        "building cfa standard lib",                                            // -t
626        "",                                                                                                     // -w
627        "",                                                                                                     // -W
628        "",                                                                                                     // -D
629}; // description
630
631static_assert( sizeof( long_opts ) / sizeof( long_opts[0] ) - 1 == sizeof( description ) / sizeof( description[0] ), "Long opts and description must match" );
632
633static struct Printopts {
634        const char * name;
635        int & flag;
636        int val;
637        const char * descript;
638} printopts[] = {
639        { "ascodegen", codegenp, true, "print AST as codegen rather than AST" },
640        { "asterr", errorp, true, "print AST on error" },
641        { "declstats", declstatsp, true, "code property statistics" },
642        { "parse", yydebug, true, "yacc (parsing) debug information" },
643        { "pretty", prettycodegenp, true, "prettyprint for ascodegen flag" },
644        { "rproto", resolvprotop, true, "resolver-proto instance" },
645        { "rsteps", resolvep, true, "print resolver steps" },
646        { "tree", parsep, true, "print parse tree" },
647        // code dumps
648        { "ast", astp, true, "print AST after parsing" },
649        { "exdecl", exdeclp, true, "print AST after translating exception decls" },
650        { "symevt", symtabp, true, "print AST after symbol table events" },
651        { "altexpr", expraltp, true, "print alternatives for expressions" },
652        { "astdecl", validp, true, "print AST after declaration validation pass" },
653        { "resolver", bresolvep, true, "print AST before resolver step" },
654        { "astexpr", exprp, true, "print AST after expression analysis" },
655        { "ctordtor", ctorinitp, true, "print AST after ctor/dtor are replaced" },
656        { "tuple", tuplep, true, "print AST after tuple expansion" },
657        { "astgen", genericsp, true, "print AST after instantiate generics" },
658        { "box", bboxp, true, "print AST before box step" },
659        { "codegen", bcodegenp, true, "print AST before code generation" },
660};
661enum { printoptsSize = sizeof( printopts ) / sizeof( printopts[0] ) };
662
663static void usage( char * argv[] ) {
664    cout << "Usage: " << argv[0] << " [options] [input-file (default stdin)] [output-file (default stdout)], where options are:" << endl;
665        int i = 0, j = 1;                                                                       // j skips starting colon
666        for ( ; long_opts[i].name != 0 && optstring[j] != '\0'; i += 1, j += 1 ) {
667                if ( long_opts[i].name[0] != '\0' ) {                   // hidden option, internal usage only
668                        if ( strcmp( long_opts[i].name, "prelude-dir" ) != 0 ) { // flag
669                                cout << "  -" << optstring[j] << ",";
670                        } else {                                                                        // no flag
671                                j -= 1;                                                                 // compensate
672                                cout << "     ";
673                        } // if
674                        cout << " --" << left << setw(12) << long_opts[i].name << "  ";
675                        if ( strcmp( long_opts[i].name, "print" ) == 0 ) {
676                                cout << "one of: " << endl;
677                                for ( int i = 0; i < printoptsSize; i += 1 ) {
678                                        cout << setw(10) << " " << left << setw(10) << printopts[i].name << "  " << printopts[i].descript << endl;
679                                } // for
680                        } else {
681                                cout << description[i] << endl;
682                        } // if
683                } // if
684                if ( optstring[j + 1] == ':' ) j += 1;
685        } // for
686        if ( long_opts[i].name != 0 || optstring[j] != '\0' ) assertf( false, "internal error, mismatch of option flags and names\n" );
687    exit( EXIT_FAILURE );
688} // usage
689
690static void parse_cmdline( int argc, char * argv[] ) {
691        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
692
693        bool Wsuppress = false, Werror = false;
694        int c;
695        while ( (c = getopt_long( argc, argv, optstring, long_opts, nullptr )) != -1 ) {
696                switch ( c ) {
697                  case 'c':                                                                             // diagnostic colors
698                        if ( strcmp( optarg, "always" ) == 0 ) {
699                                ErrorHelpers::colors = ErrorHelpers::Colors::Always;
700                        } else if ( strcmp( optarg, "never" ) == 0 ) {
701                                ErrorHelpers::colors = ErrorHelpers::Colors::Never;
702                        } else if ( strcmp( optarg, "auto" ) == 0 ) {
703                                ErrorHelpers::colors = ErrorHelpers::Colors::Auto;
704                        } // if
705                        break;
706                  case 'h':                                                                             // help message
707                        usage( argv );                                                          // no return
708                        break;
709                  case 'l':                                                                             // generate libcfa.c
710                        libcfap = true;
711                        break;
712                  case 'L':                                                                             // generate line marks
713                        linemarks = true;
714                        break;
715                  case 'm':                                                                             // do not replace main
716                        nomainp = true;
717                        break;
718                  case 'N':                                                                             // do not generate line marks
719                        linemarks = false;
720                        break;
721                  case 'n':                                                                             // do not read prelude
722                        nopreludep = true;
723                        break;
724                  case 'p':                                                                             // generate prototypes for prelude functions
725                        genproto = true;
726                        break;
727                  case 'd':                                     // don't print non-deterministic output
728                        deterministic_output = true;
729                        break;
730                  case 'O':                                     // don't print non-deterministic output
731                        useNewAST = false;
732                        break;
733                  case 'A':                                     // don't print non-deterministic output
734                        useNewAST = true;
735                        break;
736                  case 'P':                                                                             // print options
737                        for ( int i = 0;; i += 1 ) {
738                                if ( i == printoptsSize ) {
739                                        cout << "Unknown --print option " << optarg << endl;
740                                        goto Default;
741                                } // if
742                                if ( strcmp( optarg, printopts[i].name ) == 0 ) {
743                                        printopts[i].flag = printopts[i].val;
744                                        break;
745                                } // if
746                        } // for
747                        break;
748                  case PreludeDir:                                                              // prelude directory for debug/nodebug, hidden
749                        PreludeDirector = optarg;
750                        break;
751                  case 'S':                                                                             // enable profiling information, argument comma separated list of names
752                        Stats::parse_params( optarg );
753                        break;
754                  case 't':                                                                             // building cfa stdlib
755                        treep = true;
756                        break;
757                  case 'g':                                                                             // wait for gdb
758                        waiting_for_gdb = true;
759                        break;
760                  case 'w':                                                                             // suppress all warnings, hidden
761                        Wsuppress = true;
762                        break;
763                  case 'W':                                                                             // coordinate gcc -W with CFA, hidden
764                        if ( strcmp( optarg, "all" ) == 0 ) {
765                                SemanticWarning_EnableAll();
766                        } else if ( strcmp( optarg, "error" ) == 0 ) {
767                                Werror = true;
768                        } else {
769                                char * warning = optarg;
770                                Severity s;
771                                if ( strncmp( optarg, "no-", 3 ) == 0 ) {
772                                        warning += 3;
773                                        s = Severity::Suppress;
774                                } else {
775                                        s = Severity::Warn;
776                                } // if
777                                SemanticWarning_Set( warning, s );
778                        } // if
779                        break;
780                  case 'D':                                                                             // ignore -Dxxx, forwarded by cpp, hidden
781                        break;
782                  case '?':                                                                             // unknown option
783                        if ( optopt ) {                                                         // short option ?
784                                cout << "Unknown option -" << (char)optopt << endl;
785                        } else {
786                                cout << "Unknown option " << argv[optind - 1] << endl;
787                        } // if
788                        goto Default;
789                  case ':':                                                                             // missing option
790                        if ( optopt ) {                                                         // short option ?
791                                cout << "Missing option for -" << (char)optopt << endl;
792                        } else {
793                                cout << "Missing option for " << argv[optind - 1] << endl;
794                        } // if
795                        goto Default;
796                  Default:
797                  default:
798                        usage( argv );                                                          // no return
799                } // switch
800        } // while
801
802        if ( Werror ) {
803                SemanticWarning_WarningAsError();
804        } // if
805        if ( Wsuppress ) {
806                SemanticWarning_SuppressAll();
807        } // if
808        // for ( const auto w : WarningFormats ) {
809        //      cout << w.name << ' ' << (int)w.severity << endl;
810        // } // for
811} // parse_cmdline
812
813static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
814        extern int yyparse( void );
815        extern FILE * yyin;
816        extern int yylineno;
817
818        ::linkage = linkage;                                                            // set globals
819        yyin = input;
820        yylineno = 1;
821        int parseStatus = yyparse();
822
823        fclose( input );
824        if ( shouldExit || parseStatus != 0 ) {
825                exit( parseStatus );
826        } // if
827} // parse
828
829static bool notPrelude( Declaration * decl ) {
830        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
831} // notPrelude
832
833static void dump( list< Declaration * > & translationUnit, ostream & out ) {
834        list< Declaration * > decls;
835
836        if ( genproto ) {
837                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
838        } else {
839                decls = translationUnit;
840        } // if
841
842        // depending on commandline options, either generate code or dump the AST
843        if ( codegenp ) {
844                CodeGen::generate( decls, out, ! genproto, prettycodegenp );
845        } else {
846                printAll( decls, out );
847        } // if
848        deleteAll( translationUnit );
849} // dump
850
851static void dump( ast::TranslationUnit && transUnit, ostream & out ) {
852        std::list< Declaration * > translationUnit = convert( move( transUnit ) );
853        dump( translationUnit, out );
854}
855
856// Local Variables: //
857// tab-width: 4 //
858// mode: c++ //
859// compile-command: "make install" //
860// End:  //
Note: See TracBrowser for help on using the repository browser.