source: src/main.cc @ efc8f3e

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since efc8f3e was 68fe946e, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Updated DeclStats? for the new ast. Also fixed a bug in the old implementation (apparently it hasn't been used since gcc-builtins were added).

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