source: src/main.cc @ eb8d791

ADTast-experimental
Last change on this file since eb8d791 was eb8d791, checked in by Andrew Beach <ajbeach@…>, 13 months ago

CandidateFinder? fills in the CodeLocation? on a generated expression. With that and recent changes, the fills seem to be redundent now, so I removed them.

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