source: src/main.cc@ 5e180c2

ADT ast-experimental
Last change on this file since 5e180c2 was 64b3cda, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Adjusted -Pasterr so it works while using the new ast. Removed the -Ptree option as it doesn't seem to work and no one uses it.

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