source: src/main.cc @ 28f8f15

ADT
Last change on this file since 28f8f15 was 52f9804, checked in by Andrew Beach <ajbeach@…>, 15 months ago

Update macros in main. DUMP is now a macro to save space/noise and the PASS macro now runs checkInvariants afterwards if --invariant is on.

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