source: src/main.cc @ 36a05d7

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since 36a05d7 was 5ee153d, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Translated the Translate Throws pass to the new ast.

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