source: src/main.cc @ 7e13b11

Last change on this file since 7e13b11 was dacd2c19, checked in by Andrew Beach <ajbeach@…>, 5 months ago

Added Peter's fix to ensure syscall argument is initialized. I did check it against valgrind.

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