source: src/main.cc @ 3b8e52c

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 3b8e52c was 3b8e52c, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

more refactoring of parser code

  • Property mode set to 100644
File size: 11.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           : Richard C. Bilson
10// Created On       : Fri May 15 23:12:02 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Wed Aug 17 22:13:38 2016
13// Update Count     : 341
14//
15
16#include <iostream>
17#include <fstream>
18#include <getopt.h>
19#include "Parser/lex.h"
20#include "Parser/parser.h"
21#include "Parser/TypedefTable.h"
22#include "GenPoly/Lvalue.h"
23#include "GenPoly/Specialize.h"
24#include "GenPoly/Box.h"
25#include "GenPoly/CopyParams.h"
26#include "GenPoly/InstantiateGeneric.h"
27#include "CodeGen/Generate.h"
28#include "CodeGen/FixNames.h"
29#include "ControlStruct/Mutate.h"
30#include "SymTab/Validate.h"
31#include "ResolvExpr/AlternativePrinter.h"
32#include "ResolvExpr/Resolver.h"
33#include "MakeLibCfa.h"
34#include "InitTweak/GenInit.h"
35#include "InitTweak/FixInit.h"
36#include "Common/UnimplementedError.h"
37
38#include "../config.h"
39
40using namespace std;
41
42#define OPTPRINT(x) if ( errorp ) std::cerr << x << std::endl;
43
44
45LinkageSpec::Type linkage = LinkageSpec::Cforall;
46TypedefTable typedefTable;
47DeclarationNode * parseTree = nullptr;                                  // program parse tree
48
49extern int yydebug;                                                                             // set for -g flag (Grammar)
50bool
51        astp = false,
52        bresolvep = false,
53        bboxp = false,
54        ctorinitp = false,
55        exprp = false,
56        expraltp = false,
57        libcfap = false,
58        nopreludep = false,
59        noprotop = false,
60        parsep = false,
61        resolvep = false,                                                                       // used in AlternativeFinder
62        symtabp = false,
63        treep = false,
64        validp = false,
65        errorp = false,
66        codegenp = false;
67
68static void parse_cmdline( int argc, char *argv[], const char *& filename );
69static void parse( FILE * input, LinkageSpec::Type t, bool shouldExit = false );
70static void dump( std::list< Declaration * > & translationUnit, std::ostream & out = std::cout );
71
72//************************************************
73
74#define __STRINGIFY__(str) #str
75#define __VSTRINGIFY__(str) __STRINGIFY__(str)
76#define assertf(expr, fmt, ...) ((expr) ? static_cast<void>(0) : __assert_fail_f(__VSTRINGIFY__(expr), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, ## __VA_ARGS__ ))
77#define CFA_ASSERT_FMT "*CFA assertion error* from program \"%s\" in \"%s\" at line %d in file \"%s\": "
78
79extern const char * __progname;                                                 // global name of running executable (argv[0])
80// called by macro assert in assert.h
81void __assert_fail( const char *assertion, const char *file, unsigned int line, const char *function ) {
82        fprintf( stderr, CFA_ASSERT_FMT, __progname, function, line, file );
83        exit( EXIT_FAILURE );
84}
85
86#include <cstdarg>
87// called by macro assertf
88void __assert_fail_f( const char *assertion, const char *file, unsigned int line, const char *function, const char *fmt, ... ) {
89        fprintf( stderr, CFA_ASSERT_FMT, __progname, function, line, file );
90        va_list args;
91        va_start( args, fmt );
92        vfprintf( stderr, fmt, args );
93        exit( EXIT_FAILURE );
94}
95
96//************************************************
97
98int main( int argc, char * argv[] ) {
99        FILE * input;                                                                           // use FILE rather than istream because yyin is FILE
100        std::ostream *output = & std::cout;
101        std::list< Declaration * > translationUnit;
102        const char *filename = nullptr;
103
104        parse_cmdline( argc, argv, filename );                          // process command-line arguments
105
106        try {
107                // choose to read the program from a file or stdin
108                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
109                        input = fopen( argv[ optind ], "r" );
110                        assertf( input, "cannot open %s\n", argv[ optind ] );
111                        // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
112                        if ( filename == nullptr ) filename = argv[ optind ];
113                        // prelude filename comes in differently
114                        if ( libcfap ) filename = "prelude.cf";
115                        optind += 1;
116                } else {                                                                                // no input file name
117                        input = stdin;
118                        // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
119                        // a fake name along
120                        if ( filename == nullptr ) filename = "stdin";
121                } // if
122
123                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
124                        output = new ofstream( argv[ optind ] );
125                } // if
126
127                // read in the builtins, extras, and the prelude
128                if ( ! nopreludep ) {                                                   // include gcc builtins
129                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
130                        FILE * builtins = fopen( libcfap | treep ? "builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
131                        assertf( builtins, "cannot open builtins.cf\n" );
132                        parse( builtins, LinkageSpec::Compiler );
133
134                        // read the extra prelude in, if not generating the cfa library
135                        FILE * extras = fopen( libcfap | treep ? "extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
136                        assertf( extras, "cannot open extras.cf\n" );
137                        parse( extras, LinkageSpec::C );
138
139                        if ( ! libcfap ) {
140                                // read the prelude in, if not generating the cfa library
141                                FILE * prelude = fopen( treep ? "prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
142                                assertf( prelude, "cannot open prelude.cf\n" );
143                                parse( prelude, LinkageSpec::Intrinsic );
144                        } // if
145                } // if
146
147                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
148
149                if ( parsep ) {
150                        parseTree->printList( std::cout );
151                        delete parseTree;
152                        return 0;
153                } // if
154
155                buildList( parseTree, translationUnit );
156                delete parseTree;
157                parseTree = nullptr;
158
159                if ( astp ) {
160                        dump( translationUnit );
161                        return 0;
162                } // if
163
164                // add the assignment statement after the initialization of a type parameter
165                OPTPRINT( "validate" )
166                SymTab::validate( translationUnit, symtabp );
167                if ( symtabp ) {
168                        return 0;
169                } // if
170
171                if ( expraltp ) {
172                        ResolvExpr::AlternativePrinter printer( std::cout );
173                        acceptAll( translationUnit, printer );
174                        return 0;
175                } // if
176
177                if ( validp ) {
178                        dump( translationUnit );
179                        return 0;
180                } // if
181
182                OPTPRINT( "mutate" )
183                ControlStruct::mutate( translationUnit );
184                OPTPRINT( "fixNames" )
185                CodeGen::fixNames( translationUnit );
186                OPTPRINT( "tweakInit" )
187                InitTweak::genInit( translationUnit );
188
189                if ( libcfap ) {
190                        // generate the bodies of cfa library functions
191                        LibCfa::makeLibCfa( translationUnit );
192                } // if
193
194                if ( bresolvep ) {
195                        dump( translationUnit );
196                        return 0;
197                } // if
198
199                OPTPRINT( "resolve" )
200                ResolvExpr::resolve( translationUnit );
201                if ( exprp ) {
202                        dump( translationUnit );
203                        return 0;
204                } // if
205
206                // fix ObjectDecl - replaces ConstructorInit nodes
207                OPTPRINT( "fixInit" )
208                InitTweak::fix( translationUnit, filename, libcfap || treep );
209                if ( ctorinitp ) {
210                        dump ( translationUnit );
211                        return 0;
212                } // if
213
214                OPTPRINT("instantiateGenerics")
215                GenPoly::instantiateGeneric( translationUnit );
216                OPTPRINT( "copyParams" );
217                GenPoly::copyParams( translationUnit );
218                OPTPRINT( "convertSpecializations" )
219                GenPoly::convertSpecializations( translationUnit );
220                OPTPRINT( "convertLvalue" )
221                GenPoly::convertLvalue( translationUnit );
222
223                if ( bboxp ) {
224                        dump( translationUnit );
225                        return 0;
226                } // if
227                OPTPRINT( "box" )
228                GenPoly::box( translationUnit );
229
230                // print tree right before code generation
231                if ( codegenp ) {
232                        dump( translationUnit );
233                        return 0;
234                } // if
235
236                CodeGen::generate( translationUnit, *output, ! noprotop );
237
238                if ( output != &std::cout ) {
239                        delete output;
240                } // if
241        } catch ( SemanticError &e ) {
242                if ( errorp ) {
243                        std::cerr << "---AST at error:---" << std::endl;
244                        dump( translationUnit, std::cerr );
245                        std::cerr << std::endl << "---End of AST, begin error message:---\n" << std::endl;
246                } // if
247                e.print( std::cerr );
248                if ( output != &std::cout ) {
249                        delete output;
250                } // if
251                return 1;
252        } catch ( UnimplementedError &e ) {
253                std::cout << "Sorry, " << e.get_what() << " is not currently implemented" << std::endl;
254                if ( output != &std::cout ) {
255                        delete output;
256                } // if
257                return 1;
258        } catch ( CompilerError &e ) {
259                std::cerr << "Compiler Error: " << e.get_what() << std::endl;
260                std::cerr << "(please report bugs to " << std::endl;
261                if ( output != &std::cout ) {
262                        delete output;
263                } // if
264                return 1;
265        } // try
266
267        deleteAll( translationUnit );
268        return 0;
269} // main
270
271void parse_cmdline( int argc, char * argv[], const char *& filename ) {
272        enum { Ast, Bbox, Bresolver, CtorInitFix, Expr, ExprAlt, Grammar, LibCFA, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, Validate, };
273
274        static struct option long_opts[] = {
275                { "ast", no_argument, 0, Ast },
276                { "before-box", no_argument, 0, Bbox },
277                { "before-resolver", no_argument, 0, Bresolver },
278                { "ctorinitfix", no_argument, 0, CtorInitFix },
279                { "expr", no_argument, 0, Expr },
280                { "expralt", no_argument, 0, ExprAlt },
281                { "grammar", no_argument, 0, Grammar },
282                { "libcfa", no_argument, 0, LibCFA },
283                { "no-preamble", no_argument, 0, Nopreamble },
284                { "parse", no_argument, 0, Parse },
285                { "no-prototypes", no_argument, 0, Prototypes },
286                { "resolver", no_argument, 0, Resolver },
287                { "symbol", no_argument, 0, Symbol },
288                { "tree", no_argument, 0, Tree },
289                { "validate", no_argument, 0, Validate },
290                { 0, 0, 0, 0 }
291        }; // long_opts
292        int long_index;
293
294        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
295
296        int c;
297        while ( (c = getopt_long( argc, argv, "abBcefglnpqrstvyzD:F:", long_opts, &long_index )) != -1 ) {
298                switch ( c ) {
299                  case Ast:
300                  case 'a':                                                                             // dump AST
301                        astp = true;
302                        break;
303                  case Bresolver:
304                  case 'b':                                                                             // print before resolver steps
305                        bresolvep = true;
306                        break;
307                  case 'B':                                                                             // print before resolver steps
308                        bboxp = true;
309                        break;
310                  case CtorInitFix:
311                  case 'c':
312                        ctorinitp = true;
313                        break;
314                  case Expr:
315                  case 'e':                                                                             // dump AST after expression analysis
316                        exprp = true;
317                        break;
318                  case ExprAlt:
319                  case 'f':                                                                             // print alternatives for expressions
320                        expraltp = true;
321                        break;
322                  case Grammar:
323                  case 'g':                                                                             // bison debugging info (grammar rules)
324                        yydebug = true;
325                        break;
326                  case LibCFA:
327                  case 'l':                                                                             // generate libcfa.c
328                        libcfap = true;
329                        break;
330                  case Nopreamble:
331                  case 'n':                                                                             // do not read preamble
332                        nopreludep = true;
333                        break;
334                  case Prototypes:
335                  case 'p':                                                                             // generate prototypes for preamble functions
336                        noprotop = true;
337                        break;
338                  case Parse:
339                  case 'q':                                                                             // dump parse tree
340                        parsep = true;
341                        break;
342                  case Resolver:
343                  case 'r':                                                                             // print resolver steps
344                        resolvep = true;
345                        break;
346                  case Symbol:
347                  case 's':                                                                             // print symbol table events
348                        symtabp = true;
349                        break;
350                  case Tree:
351                  case 't':                                                                             // build in tree
352                        treep = true;
353                        break;
354                  case 'v':                                                                             // dump AST after decl validation pass
355                        validp = true;
356                        break;
357                  case 'y':
358                        errorp = true;
359                        break;
360                  case 'z':
361                        codegenp = true;
362                        break;
363                  case 'D':                                                                             // ignore -Dxxx
364                        break;
365                  case 'F':                                                                             // source file-name without suffix
366                        filename = optarg;
367                        break;
368                  case '?':
369                        assertf( false, "Unknown option: '%c'\n", (char)optopt );
370                  default:
371                        abort();
372                } // switch
373        } // while
374} // parse_cmdline
375
376static void parse( FILE * input, LinkageSpec::Type link, bool shouldExit ) {
377        extern int yyparse( void );
378        extern FILE * yyin;
379        extern int yylineno;
380
381        linkage = link;                                                                         // set globals
382        yyin = input;
383        yylineno = 1;
384        typedefTable.enterScope();
385        int parseStatus = yyparse();
386
387        fclose( input );
388        if ( shouldExit || parseStatus != 0 ) {
389                exit( parseStatus );
390        } // if
391} // parse
392
393static bool notPrelude( Declaration * decl ) {
394        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
395} // notPrelude
396
397static void dump( std::list< Declaration * > & translationUnit, std::ostream & out ) {
398        std::list< Declaration * > decls;
399
400        if ( noprotop ) {
401                filter( translationUnit.begin(), translationUnit.end(), std::back_inserter( decls ), notPrelude );
402        } else {
403                decls = translationUnit;
404        } // if
405
406        printAll( decls, out );
407        deleteAll( translationUnit );
408} // dump
409
410
411
412// Local Variables: //
413// tab-width: 4 //
414// mode: c++ //
415// compile-command: "make install" //
416// End:  //
Note: See TracBrowser for help on using the repository browser.