source: src/main.cc @ 0e6cadf

ast-experimental
Last change on this file since 0e6cadf was 6e1e2d0, checked in by caparsons <caparson@…>, 14 months ago

resolved merge conflicts

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