source: src/main.cc @ 7350330f

Last change on this file since 7350330f was 14c0f7b, checked in by Andrew Beach <ajbeach@…>, 11 months ago

Added invariant to check that referenced declarations are in scope. This one took a while, I don't remember why forall pointer decay is involved.

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