source: src/main.cc @ 365c8dcb

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

Converted validate C, including adding DimensionExpr? to the new ast.

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