source: src/main.cc @ 21a2a7d

ADTast-experimental
Last change on this file since 21a2a7d was 3dd8f42, checked in by caparsons <caparson@…>, 15 months ago

added actor support to the compiler

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