source: src/main.cc @ 2b7afbd

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 2b7afbd was 166793b, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

fix tricky build with parser.h

  • Property mode set to 100644
File size: 15.9 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 : Peter A. Buhr
13// Last Modified On : Wed Jun 28 21:56:47 2017
14// Update Count     : 440
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/parser.hh"
28#include "Parser/TypedefTable.h"
29#include "GenPoly/Lvalue.h"
30#include "GenPoly/Specialize.h"
31#include "GenPoly/Box.h"
32#include "GenPoly/CopyParams.h"
33#include "GenPoly/InstantiateGeneric.h"
34#include "Concurrency/Keywords.h"
35#include "CodeGen/Generate.h"
36#include "CodeGen/FixNames.h"
37#include "CodeGen/FixMain.h"
38#include "CodeTools/DeclStats.h"
39#include "CodeTools/TrackLoc.h"
40#include "ControlStruct/Mutate.h"
41#include "SymTab/Validate.h"
42#include "ResolvExpr/AlternativePrinter.h"
43#include "ResolvExpr/Resolver.h"
44#include "MakeLibCfa.h"
45#include "InitTweak/GenInit.h"
46#include "InitTweak/FixInit.h"
47#include "Common/UnimplementedError.h"
48#include "../config.h"
49#include "Tuples/Tuples.h"
50
51using namespace std;
52
53#define OPTPRINT(x) if ( errorp ) cerr << x << endl;
54
55
56LinkageSpec::Spec linkage = LinkageSpec::Cforall;
57TypedefTable typedefTable;
58DeclarationNode * parseTree = nullptr;                                  // program parse tree
59
60extern int yydebug;                                                                             // set for -g flag (Grammar)
61bool
62        astp = false,
63        bresolvep = false,
64        bboxp = false,
65        bcodegenp = 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( __attribute__((unused)) 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
188                        // Read to gcc builtins, if not generating the cfa library
189                        FILE * gcc_builtins = fopen( libcfap | treep ? "../prelude/gcc-builtins.cf" : CFA_LIBDIR "/gcc-builtins.cf", "r" );
190                        assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
191                        parse( gcc_builtins, LinkageSpec::Compiler );
192
193                        // read the extra prelude in, if not generating the cfa library
194                        FILE * extras = fopen( libcfap | treep ? "../prelude/extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
195                        assertf( extras, "cannot open extras.cf\n" );
196                        parse( extras, LinkageSpec::C );
197
198                        if ( ! libcfap ) {
199                                // read the prelude in, if not generating the cfa library
200                                FILE * prelude = fopen( treep ? "../prelude/prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
201                                assertf( prelude, "cannot open prelude.cf\n" );
202                                parse( prelude, LinkageSpec::Intrinsic );
203
204                                // Read to cfa builtins, if not generating the cfa library
205                                FILE * builtins = fopen( libcfap | treep ? "../prelude/builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
206                                assertf( builtins, "cannot open builtins.cf\n" );
207                                parse( builtins, LinkageSpec::Builtin );
208                        } // if
209                } // if
210
211                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
212
213                if ( parsep ) {
214                        parseTree->printList( cout );
215                        delete parseTree;
216                        return 0;
217                } // if
218
219                buildList( parseTree, translationUnit );
220                delete parseTree;
221                parseTree = nullptr;
222
223                if ( astp ) {
224                        dump( translationUnit );
225                        return 0;
226                } // if
227
228                // OPTPRINT( "Concurrency" )
229                // Concurrency::applyKeywords( translationUnit );
230
231                // add the assignment statement after the initialization of a type parameter
232                OPTPRINT( "validate" )
233                SymTab::validate( translationUnit, symtabp );
234                if ( symtabp ) {
235                        deleteAll( translationUnit );
236                        return 0;
237                } // if
238
239                if ( expraltp ) {
240                        ResolvExpr::AlternativePrinter printer( cout );
241                        acceptAll( translationUnit, printer );
242                        return 0;
243                } // if
244
245                if ( validp ) {
246                        dump( translationUnit );
247                        return 0;
248                } // if
249
250                OPTPRINT( "mutate" )
251                ControlStruct::mutate( translationUnit );
252                OPTPRINT( "fixNames" )
253                CodeGen::fixNames( translationUnit );
254                OPTPRINT( "genInit" )
255                InitTweak::genInit( translationUnit );
256                OPTPRINT( "expandMemberTuples" );
257                Tuples::expandMemberTuples( translationUnit );
258                if ( libcfap ) {
259                        // generate the bodies of cfa library functions
260                        LibCfa::makeLibCfa( translationUnit );
261                } // if
262
263                if ( declstatsp ) {
264                        CodeTools::printDeclStats( translationUnit );
265                        deleteAll( translationUnit );
266                        return 0;
267                }
268
269                if ( bresolvep ) {
270                        dump( translationUnit );
271                        return 0;
272                } // if
273
274                OPTPRINT( "resolve" )
275                ResolvExpr::resolve( translationUnit );
276                if ( exprp ) {
277                        dump( translationUnit );
278                        return 0;
279                } // if
280
281                // fix ObjectDecl - replaces ConstructorInit nodes
282                OPTPRINT( "fixInit" )
283                InitTweak::fix( translationUnit, filename, libcfap || treep );
284                if ( ctorinitp ) {
285                        dump ( translationUnit );
286                        return 0;
287                } // if
288
289                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
290                Tuples::expandUniqueExpr( translationUnit );
291
292                OPTPRINT( "convertSpecializations" ) // needs to happen before tuple types are expanded
293                GenPoly::convertSpecializations( translationUnit );
294
295                OPTPRINT( "expandTuples" ); // xxx - is this the right place for this?
296                Tuples::expandTuples( translationUnit );
297                if ( tuplep ) {
298                        dump( translationUnit );
299                        return 0;
300                }
301
302                OPTPRINT("instantiateGenerics")
303                GenPoly::instantiateGeneric( translationUnit );
304                OPTPRINT( "copyParams" );
305                GenPoly::copyParams( translationUnit );
306                OPTPRINT( "convertLvalue" )
307                GenPoly::convertLvalue( translationUnit );
308
309                if ( bboxp ) {
310                        dump( translationUnit );
311                        return 0;
312                } // if
313                OPTPRINT( "box" )
314                GenPoly::box( translationUnit );
315
316                if ( bcodegenp ) {
317                        dump( translationUnit );
318                        return 0;
319                }
320
321                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
322                        output = new ofstream( argv[ optind ] );
323                } // if
324
325                CodeTools::fillLocations( translationUnit );
326                CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, ! nolinemarks );
327
328                CodeGen::FixMain::fix( *output, treep ? "../prelude/bootloader.c" : CFA_LIBDIR "/bootloader.c" );
329
330                if ( output != &cout ) {
331                        delete output;
332                } // if
333        } catch ( SemanticError &e ) {
334                if ( errorp ) {
335                        cerr << "---AST at error:---" << endl;
336                        dump( translationUnit, cerr );
337                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
338                } // if
339                e.print( cerr );
340                if ( output != &cout ) {
341                        delete output;
342                } // if
343                return 1;
344        } catch ( UnimplementedError &e ) {
345                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
346                if ( output != &cout ) {
347                        delete output;
348                } // if
349                return 1;
350        } catch ( CompilerError &e ) {
351                cerr << "Compiler Error: " << e.get_what() << endl;
352                cerr << "(please report bugs to [REDACTED])" << endl;
353                if ( output != &cout ) {
354                        delete output;
355                } // if
356                return 1;
357        } // try
358
359        deleteAll( translationUnit );
360        return 0;
361} // main
362
363void parse_cmdline( int argc, char * argv[], const char *& filename ) {
364        enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, TupleExpansion, Validate, };
365
366        static struct option long_opts[] = {
367                { "ast", no_argument, 0, Ast },
368                { "before-box", no_argument, 0, Bbox },
369                { "before-resolver", no_argument, 0, Bresolver },
370                { "ctorinitfix", no_argument, 0, CtorInitFix },
371                { "decl-stats", no_argument, 0, DeclStats },
372                { "expr", no_argument, 0, Expr },
373                { "expralt", no_argument, 0, ExprAlt },
374                { "grammar", no_argument, 0, Grammar },
375                { "libcfa", no_argument, 0, LibCFA },
376                { "no-preamble", no_argument, 0, Nopreamble },
377                { "parse", no_argument, 0, Parse },
378                { "no-prototypes", no_argument, 0, Prototypes },
379                { "resolver", no_argument, 0, Resolver },
380                { "symbol", no_argument, 0, Symbol },
381                { "tree", no_argument, 0, Tree },
382                { "tuple-expansion", no_argument, 0, TupleExpansion },
383                { "validate", no_argument, 0, Validate },
384                { 0, 0, 0, 0 }
385        }; // long_opts
386        int long_index;
387
388        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
389
390        int c;
391        while ( (c = getopt_long( argc, argv, "abBcCdefglLmnpqrstTvyzZD:F:", long_opts, &long_index )) != -1 ) {
392                switch ( c ) {
393                  case Ast:
394                  case 'a':                                                                             // dump AST
395                        astp = true;
396                        break;
397                  case Bresolver:
398                  case 'b':                                                                             // print before resolver steps
399                        bresolvep = true;
400                        break;
401                  case 'B':                                                                             // print before box steps
402                        bboxp = true;
403                        break;
404                  case CtorInitFix:
405                  case 'c':                                                                             // print after constructors and destructors are replaced
406                        ctorinitp = true;
407                        break;
408                  case 'C':                                                                             // print before code generation
409                        bcodegenp = true;
410                        break;
411                  case DeclStats:
412                  case 'd':
413                    declstatsp = true;
414                        break;
415                  case Expr:
416                  case 'e':                                                                             // dump AST after expression analysis
417                        exprp = true;
418                        break;
419                  case ExprAlt:
420                  case 'f':                                                                             // print alternatives for expressions
421                        expraltp = true;
422                        break;
423                  case Grammar:
424                  case 'g':                                                                             // bison debugging info (grammar rules)
425                        yydebug = true;
426                        break;
427                  case LibCFA:
428                  case 'l':                                                                             // generate libcfa.c
429                        libcfap = true;
430                        break;
431                  case 'L':                                                                             // surpress lines marks
432                        nolinemarks = true;
433                        break;
434                  case Nopreamble:
435                  case 'n':                                                                             // do not read preamble
436                        nopreludep = true;
437                        break;
438                  case Prototypes:
439                  case 'p':                                                                             // generate prototypes for preamble functions
440                        noprotop = true;
441                        break;
442                  case 'm':                                                                             // don't replace the main
443                        nomainp = true;
444                        break;
445                  case Parse:
446                  case 'q':                                                                             // dump parse tree
447                        parsep = true;
448                        break;
449                  case Resolver:
450                  case 'r':                                                                             // print resolver steps
451                        resolvep = true;
452                        break;
453                  case Symbol:
454                  case 's':                                                                             // print symbol table events
455                        symtabp = true;
456                        break;
457                  case Tree:
458                  case 't':                                                                             // build in tree
459                        treep = true;
460                        break;
461                  case TupleExpansion:
462                  case 'T':                                                                             // print after tuple expansion
463                        tuplep = true;
464                        break;
465                  case 'v':                                                                             // dump AST after decl validation pass
466                        validp = true;
467                        break;
468                  case 'y':                                                                             // dump AST on error
469                        errorp = true;
470                        break;
471                  case 'z':                                                                             // dump as codegen rather than AST
472                        codegenp = true;
473                        break;
474                        case 'Z':                                                                       // prettyprint during codegen (i.e. print unmangled names, etc.)
475                        prettycodegenp = true;
476                        break;
477                  case 'D':                                                                             // ignore -Dxxx
478                        break;
479                  case 'F':                                                                             // source file-name without suffix
480                        filename = optarg;
481                        break;
482                  case '?':
483                        assertf( false, "Unknown option: '%c'\n", (char)optopt );
484                  default:
485                        abort();
486                } // switch
487        } // while
488} // parse_cmdline
489
490static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
491        extern int yyparse( void );
492        extern FILE * yyin;
493        extern int yylineno;
494
495        ::linkage = linkage;                                                            // set globals
496        yyin = input;
497        yylineno = 1;
498        typedefTable.enterScope();
499        int parseStatus = yyparse();
500
501        fclose( input );
502        if ( shouldExit || parseStatus != 0 ) {
503                exit( parseStatus );
504        } // if
505} // parse
506
507static bool notPrelude( Declaration * decl ) {
508        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
509} // notPrelude
510
511static void dump( list< Declaration * > & translationUnit, ostream & out ) {
512        list< Declaration * > decls;
513
514        if ( noprotop ) {
515                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
516        } else {
517                decls = translationUnit;
518        } // if
519
520        // depending on commandline options, either generate code or dump the AST
521        if ( codegenp ) {
522                CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
523        } else {
524                printAll( decls, out );
525        }
526        deleteAll( translationUnit );
527} // dump
528
529// Local Variables: //
530// tab-width: 4 //
531// mode: c++ //
532// compile-command: "make install" //
533// End:  //
Note: See TracBrowser for help on using the repository browser.