source: src/main.cc@ a1f3d93

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

Translation of Validate F; and some improvements in some helpers.

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