source: src/main.cc@ f7c41d4

ADT ast-experimental
Last change on this file since f7c41d4 was f26421f, checked in by Mugilan Ganesan <mganesan@…>, 3 years ago

Removed CompilerError and UnimplementedError

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