source: src/main.cc @ 4ac402d

Last change on this file since 4ac402d was 0b5e780, checked in by Andrew Beach <ajbeach@…>, 7 months ago

Code dumps (under the -P flag) no longer convert to the old ast to print.

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