source: src/main.cc @ 8941b6b

Last change on this file since 8941b6b was 8941b6b, checked in by Andrew Beach <ajbeach@…>, 8 months ago

Direct translation of code generation.

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