source: src/main.cc@ b9cd3b5

ADT ast-experimental
Last change on this file since b9cd3b5 was c86b08d, checked in by caparsons <caparson@…>, 2 years ago

added support for the waituntil statement in the compiler

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