source: src/main.cc @ 4f6dda0

ADTast-experimentalenumpthread-emulationqualifiedEnum old-sched
Last change on this file since 4f6dda0 was 4f6dda0, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Converted Implement Concurrent Keywords to the new AST. Includes updates to various helpers, including the virtual table and a lot of examine helpers.

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