source: src/main.cc @ bf20567

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

RunParser? now uses AST for its interface everywhere. (Works because LinkageSpec::Spec and ast::Linkage::Spec have the same layout.)

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