source: src/main.cpp @ d3b33d5

Last change on this file since d3b33d5 was 82a5ea2, checked in by Andrew Beach <ajbeach@…>, 6 days ago

Added checks for (and a test to check the checks) assertions we will not be able to adapt. Using an adapted version of Mike's error message.

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