source: src/main.cc@ 02153feb

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 02153feb was c850687, checked in by Andrew Beach <ajbeach@…>, 8 years ago

Add -L flag to turn of line marks. Updated the keyword list.

  • Property mode set to 100644
File size: 15.3 KB
Line 
1
2//
3// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
4//
5// The contents of this file are covered under the licence agreement in the
6// file "LICENCE" distributed with Cforall.
7//
8// main.cc --
9//
10// Author : Richard C. Bilson
11// Created On : Fri May 15 23:12:02 2015
12// Last Modified By : Andrew Beach
13// Last Modified On : Wed May 10 14:45:00 2017
14// Update Count : 437
15//
16
17#include <iostream>
18#include <fstream>
19#include <signal.h> // signal
20#include <getopt.h> // getopt
21#include <execinfo.h> // backtrace, backtrace_symbols
22#include <cxxabi.h> // __cxa_demangle
23#include <cstring> // index
24
25using namespace std;
26
27#include "Parser/lex.h"
28#include "Parser/parser.h"
29#include "Parser/TypedefTable.h"
30#include "GenPoly/Lvalue.h"
31#include "GenPoly/Specialize.h"
32#include "GenPoly/Box.h"
33#include "GenPoly/CopyParams.h"
34#include "GenPoly/InstantiateGeneric.h"
35#include "Concurrency/Keywords.h"
36#include "CodeGen/Generate.h"
37#include "CodeGen/FixNames.h"
38#include "CodeGen/FixMain.h"
39#include "CodeTools/DeclStats.h"
40#include "CodeTools/TrackLoc.h"
41#include "ControlStruct/Mutate.h"
42#include "SymTab/Validate.h"
43#include "ResolvExpr/AlternativePrinter.h"
44#include "ResolvExpr/Resolver.h"
45#include "MakeLibCfa.h"
46#include "InitTweak/GenInit.h"
47#include "InitTweak/FixInit.h"
48#include "Common/UnimplementedError.h"
49#include "../config.h"
50#include "Tuples/Tuples.h"
51
52using namespace std;
53
54#define OPTPRINT(x) if ( errorp ) cerr << x << endl;
55
56
57LinkageSpec::Spec linkage = LinkageSpec::Cforall;
58TypedefTable typedefTable;
59DeclarationNode * parseTree = nullptr; // program parse tree
60
61extern int yydebug; // set for -g flag (Grammar)
62bool
63 astp = false,
64 bresolvep = false,
65 bboxp = false,
66 ctorinitp = false,
67 declstatsp = false,
68 exprp = false,
69 expraltp = false,
70 libcfap = false,
71 nopreludep = false,
72 noprotop = false,
73 nomainp = false,
74 parsep = false,
75 resolvep = false, // used in AlternativeFinder
76 symtabp = false,
77 treep = false,
78 tuplep = false,
79 validp = false,
80 errorp = false,
81 codegenp = false,
82 prettycodegenp = false,
83 nolinemarks = false;
84
85static void parse_cmdline( int argc, char *argv[], const char *& filename );
86static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
87static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
88
89static void backtrace( int start ) { // skip first N stack frames
90 enum { Frames = 50 };
91 void * array[Frames];
92 int size = ::backtrace( array, Frames );
93 char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
94
95 *index( messages[0], '(' ) = '\0'; // find executable name
96 cerr << "Stack back trace for: " << messages[0] << endl;
97
98 // skip last 2 stack frames after main
99 for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
100 char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
101 for ( char *p = messages[i]; *p; ++p ) { // find parantheses and +offset
102 if ( *p == '(' ) {
103 mangled_name = p;
104 } else if ( *p == '+' ) {
105 offset_begin = p;
106 } else if ( *p == ')' ) {
107 offset_end = p;
108 break;
109 } // if
110 } // for
111
112 // if line contains symbol, attempt to demangle
113 int frameNo = i - start;
114 if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
115 *mangled_name++ = '\0'; // delimit strings
116 *offset_begin++ = '\0';
117 *offset_end++ = '\0';
118
119 int status;
120 char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
121 // bug in __cxa_demangle for single-character lower-case non-mangled names
122 if ( status == 0 ) { // demangling successful ?
123 cerr << "(" << frameNo << ") " << messages[i] << " : "
124 << real_name << "+" << offset_begin << offset_end << endl;
125 } else { // otherwise, output mangled name
126 cerr << "(" << frameNo << ") " << messages[i] << " : "
127 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
128 } // if
129
130 free( real_name );
131 } else { // otherwise, print the whole line
132 cerr << "(" << frameNo << ") " << messages[i] << endl;
133 } // if
134 } // for
135
136 free( messages );
137} // backtrace
138
139void sigSegvBusHandler( int sig_num ) {
140 cerr << "*CFA runtime error* program cfa-cpp terminated with "
141 << (sig_num == SIGSEGV ? "segment fault" : "bus error")
142 << "." << endl;
143 backtrace( 2 ); // skip first 2 stack frames
144 exit( EXIT_FAILURE );
145} // sigSegvBusHandler
146
147void sigAbortHandler( int sig_num ) {
148 backtrace( 6 ); // skip first 6 stack frames
149 signal( SIGABRT, SIG_DFL); // reset default signal handler
150 raise( SIGABRT ); // reraise SIGABRT
151} // sigAbortHandler
152
153
154int main( int argc, char * argv[] ) {
155 FILE * input; // use FILE rather than istream because yyin is FILE
156 ostream *output = & cout;
157 const char *filename = nullptr;
158 list< Declaration * > translationUnit;
159
160 signal( SIGSEGV, sigSegvBusHandler );
161 signal( SIGBUS, sigSegvBusHandler );
162 signal( SIGABRT, sigAbortHandler );
163
164 parse_cmdline( argc, argv, filename ); // process command-line arguments
165 CodeGen::FixMain::setReplaceMain( !nomainp );
166
167 try {
168 // choose to read the program from a file or stdin
169 if ( optind < argc ) { // any commands after the flags ? => input file name
170 input = fopen( argv[ optind ], "r" );
171 assertf( input, "cannot open %s\n", argv[ optind ] );
172 // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
173 if ( filename == nullptr ) filename = argv[ optind ];
174 // prelude filename comes in differently
175 if ( libcfap ) filename = "prelude.cf";
176 optind += 1;
177 } else { // no input file name
178 input = stdin;
179 // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
180 // a fake name along
181 if ( filename == nullptr ) filename = "stdin";
182 } // if
183
184 // read in the builtins, extras, and the prelude
185 if ( ! nopreludep ) { // include gcc builtins
186 // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
187 FILE * builtins = fopen( libcfap | treep ? "../prelude/builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
188 assertf( builtins, "cannot open builtins.cf\n" );
189 parse( builtins, LinkageSpec::Compiler );
190
191 // read the extra prelude in, if not generating the cfa library
192 FILE * extras = fopen( libcfap | treep ? "../prelude/extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
193 assertf( extras, "cannot open extras.cf\n" );
194 parse( extras, LinkageSpec::C );
195
196 if ( ! libcfap ) {
197 // read the prelude in, if not generating the cfa library
198 FILE * prelude = fopen( treep ? "../prelude/prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
199 assertf( prelude, "cannot open prelude.cf\n" );
200 parse( prelude, LinkageSpec::Intrinsic );
201 } // if
202 } // if
203
204 parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
205
206 if ( parsep ) {
207 parseTree->printList( cout );
208 delete parseTree;
209 return 0;
210 } // if
211
212 buildList( parseTree, translationUnit );
213 delete parseTree;
214 parseTree = nullptr;
215
216 if ( astp ) {
217 dump( translationUnit );
218 return 0;
219 } // if
220
221 // OPTPRINT( "Concurrency" )
222 // Concurrency::applyKeywords( translationUnit );
223
224 // add the assignment statement after the initialization of a type parameter
225 OPTPRINT( "validate" )
226 SymTab::validate( translationUnit, symtabp );
227 if ( symtabp ) {
228 deleteAll( translationUnit );
229 return 0;
230 } // if
231
232 if ( expraltp ) {
233 ResolvExpr::AlternativePrinter printer( cout );
234 acceptAll( translationUnit, printer );
235 return 0;
236 } // if
237
238 if ( validp ) {
239 dump( translationUnit );
240 return 0;
241 } // if
242
243 OPTPRINT( "mutate" )
244 ControlStruct::mutate( translationUnit );
245 OPTPRINT( "fixNames" )
246 CodeGen::fixNames( translationUnit );
247 OPTPRINT( "genInit" )
248 InitTweak::genInit( translationUnit );
249 OPTPRINT( "expandMemberTuples" );
250 Tuples::expandMemberTuples( translationUnit );
251 if ( libcfap ) {
252 // generate the bodies of cfa library functions
253 LibCfa::makeLibCfa( translationUnit );
254 } // if
255
256 if ( declstatsp ) {
257 CodeTools::printDeclStats( translationUnit );
258 deleteAll( translationUnit );
259 return 0;
260 }
261
262 if ( bresolvep ) {
263 dump( translationUnit );
264 return 0;
265 } // if
266
267 OPTPRINT( "resolve" )
268 ResolvExpr::resolve( translationUnit );
269 if ( exprp ) {
270 dump( translationUnit );
271 return 0;
272 } // if
273
274 // fix ObjectDecl - replaces ConstructorInit nodes
275 OPTPRINT( "fixInit" )
276 InitTweak::fix( translationUnit, filename, libcfap || treep );
277 if ( ctorinitp ) {
278 dump ( translationUnit );
279 return 0;
280 } // if
281
282 OPTPRINT( "expandUniqueExpr" ); // xxx - is this the right place for this? want to expand ASAP so that subsequent 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
283 Tuples::expandUniqueExpr( translationUnit );
284
285 OPTPRINT( "convertSpecializations" ) // needs to happen before tuple types are expanded
286 GenPoly::convertSpecializations( translationUnit );
287
288 OPTPRINT( "expandTuples" ); // xxx - is this the right place for this?
289 Tuples::expandTuples( translationUnit );
290 if ( tuplep ) {
291 dump( translationUnit );
292 return 0;
293 }
294
295 OPTPRINT("instantiateGenerics")
296 GenPoly::instantiateGeneric( translationUnit );
297 OPTPRINT( "copyParams" );
298 GenPoly::copyParams( translationUnit );
299 OPTPRINT( "convertLvalue" )
300 GenPoly::convertLvalue( translationUnit );
301
302 if ( bboxp ) {
303 dump( translationUnit );
304 return 0;
305 } // if
306 OPTPRINT( "box" )
307 GenPoly::box( translationUnit );
308
309 if ( optind < argc ) { // any commands after the flags and input file ? => output file name
310 output = new ofstream( argv[ optind ] );
311 } // if
312
313 CodeTools::fillLocations( translationUnit );
314 CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, ! nolinemarks );
315
316 CodeGen::FixMain::fix( *output, treep ? "../prelude/bootloader.c" : CFA_LIBDIR "/bootloader.c" );
317
318 if ( output != &cout ) {
319 delete output;
320 } // if
321 } catch ( SemanticError &e ) {
322 if ( errorp ) {
323 cerr << "---AST at error:---" << endl;
324 dump( translationUnit, cerr );
325 cerr << endl << "---End of AST, begin error message:---\n" << endl;
326 } // if
327 e.print( cerr );
328 if ( output != &cout ) {
329 delete output;
330 } // if
331 return 1;
332 } catch ( UnimplementedError &e ) {
333 cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
334 if ( output != &cout ) {
335 delete output;
336 } // if
337 return 1;
338 } catch ( CompilerError &e ) {
339 cerr << "Compiler Error: " << e.get_what() << endl;
340 cerr << "(please report bugs to [REDACTED])" << endl;
341 if ( output != &cout ) {
342 delete output;
343 } // if
344 return 1;
345 } // try
346
347 deleteAll( translationUnit );
348 return 0;
349} // main
350
351void parse_cmdline( int argc, char * argv[], const char *& filename ) {
352 enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
353
354 static struct option long_opts[] = {
355 { "ast", no_argument, 0, Ast },
356 { "before-box", no_argument, 0, Bbox },
357 { "before-resolver", no_argument, 0, Bresolver },
358 { "ctorinitfix", no_argument, 0, CtorInitFix },
359 { "decl-stats", no_argument, 0, DeclStats },
360 { "expr", no_argument, 0, Expr },
361 { "expralt", no_argument, 0, ExprAlt },
362 { "grammar", no_argument, 0, Grammar },
363 { "libcfa", no_argument, 0, LibCFA },
364 { "no-preamble", no_argument, 0, Nopreamble },
365 { "parse", no_argument, 0, Parse },
366 { "no-prototypes", no_argument, 0, Prototypes },
367 { "resolver", no_argument, 0, Resolver },
368 { "symbol", no_argument, 0, Symbol },
369 { "tree", no_argument, 0, Tree },
370 { "tuple-expansion", no_argument, 0, TupleExpansion },
371 { "validate", no_argument, 0, Validate },
372 { 0, 0, 0, 0 }
373 }; // long_opts
374 int long_index;
375
376 opterr = 0; // (global) prevent getopt from printing error messages
377
378 int c;
379 while ( (c = getopt_long( argc, argv, "abBcdefglLmnpqrstTvyzZD:F:", long_opts, &long_index )) != -1 ) {
380 switch ( c ) {
381 case Ast:
382 case 'a': // dump AST
383 astp = true;
384 break;
385 case Bresolver:
386 case 'b': // print before resolver steps
387 bresolvep = true;
388 break;
389 case 'B': // print before box steps
390 bboxp = true;
391 break;
392 case CtorInitFix:
393 case 'c': // print after constructors and destructors are replaced
394 ctorinitp = true;
395 break;
396 case DeclStats:
397 case 'd':
398 declstatsp = true;
399 break;
400 case Expr:
401 case 'e': // dump AST after expression analysis
402 exprp = true;
403 break;
404 case ExprAlt:
405 case 'f': // print alternatives for expressions
406 expraltp = true;
407 break;
408 case Grammar:
409 case 'g': // bison debugging info (grammar rules)
410 yydebug = true;
411 break;
412 case LibCFA:
413 case 'l': // generate libcfa.c
414 libcfap = true;
415 break;
416 case 'L': // surpress lines marks
417 nolinemarks = true;
418 break;
419 case Nopreamble:
420 case 'n': // do not read preamble
421 nopreludep = true;
422 break;
423 case Prototypes:
424 case 'p': // generate prototypes for preamble functions
425 noprotop = true;
426 break;
427 case 'm': // don't replace the main
428 nomainp = true;
429 break;
430 case Parse:
431 case 'q': // dump parse tree
432 parsep = true;
433 break;
434 case Resolver:
435 case 'r': // print resolver steps
436 resolvep = true;
437 break;
438 case Symbol:
439 case 's': // print symbol table events
440 symtabp = true;
441 break;
442 case Tree:
443 case 't': // build in tree
444 treep = true;
445 break;
446 case TupleExpansion:
447 case 'T': // print after tuple expansion
448 tuplep = true;
449 break;
450 case 'v': // dump AST after decl validation pass
451 validp = true;
452 break;
453 case 'y': // dump AST on error
454 errorp = true;
455 break;
456 case 'z': // dump as codegen rather than AST
457 codegenp = true;
458 break;
459 case 'Z': // prettyprint during codegen (i.e. print unmangled names, etc.)
460 prettycodegenp = true;
461 break;
462 case 'D': // ignore -Dxxx
463 break;
464 case 'F': // source file-name without suffix
465 filename = optarg;
466 break;
467 case '?':
468 assertf( false, "Unknown option: '%c'\n", (char)optopt );
469 default:
470 abort();
471 } // switch
472 } // while
473} // parse_cmdline
474
475static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
476 extern int yyparse( void );
477 extern FILE * yyin;
478 extern int yylineno;
479
480 ::linkage = linkage; // set globals
481 yyin = input;
482 yylineno = 1;
483 typedefTable.enterScope();
484 int parseStatus = yyparse();
485
486 fclose( input );
487 if ( shouldExit || parseStatus != 0 ) {
488 exit( parseStatus );
489 } // if
490} // parse
491
492static bool notPrelude( Declaration * decl ) {
493 return ! LinkageSpec::isBuiltin( decl->get_linkage() );
494} // notPrelude
495
496static void dump( list< Declaration * > & translationUnit, ostream & out ) {
497 list< Declaration * > decls;
498
499 if ( noprotop ) {
500 filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
501 } else {
502 decls = translationUnit;
503 } // if
504
505 // depending on commandline options, either generate code or dump the AST
506 if ( codegenp ) {
507 CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
508 } else {
509 printAll( decls, out );
510 }
511 deleteAll( translationUnit );
512} // dump
513
514// Local Variables: //
515// tab-width: 4 //
516// mode: c++ //
517// compile-command: "make install" //
518// End: //
Note: See TracBrowser for help on using the repository browser.