source: src/main.cc@ 148ba7d

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

First translation of the Gen Init pass. Passed the tests.

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