source: src/main.cc@ 5dcb881

ADT ast-experimental enum forall-pointer-decay pthread-emulation qualifiedEnum
Last change on this file since 5dcb881 was 5dcb881, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Split up the validate pass. (Some statistics code is repeated, but this does not effect regular runs.)

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