source: src/main.cc@ 890f67a

ADT ast-experimental
Last change on this file since 890f67a was 09f34a84, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Remove some of the warnings on the new clang

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