source: src/main.cc @ 8c91088

ADTast-experimental
Last change on this file since 8c91088 was 7fffb1b, checked in by Andrew Beach <ajbeach@…>, 19 months ago

Translated the convertLvalue pass. It could possibly use some additional clean-up.

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