source: src/main.cc@ bdc8591

Last change on this file since bdc8591 was 5b25c49, checked in by Andrew Beach <ajbeach@…>, 18 months ago

Removed some code from main that supported the old ast.

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