source: src/main.cc@ fe293bf

Last change on this file since fe293bf was be3f163, checked in by Peter A. Buhr <pabuhr@…>, 23 months ago

rename files gcc-builtins.cf builtins.cf extras.cf bootloader.cf and sync-builtins.cf with suffix .cfa

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