source: src/ResolvExpr/Resolver.cc @ ded5f07

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 ded5f07 was 7664fad, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Update finishExpr so environment is not lost on multiple resolutions

  • Property mode set to 100644
File size: 27.4 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// Resolver.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:17:01 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Tus Aug  8 16:06:00 2017
13// Update Count     : 212
14//
15
16#include <stddef.h>                      // for NULL
17#include <cassert>                       // for strict_dynamic_cast, assert
18#include <memory>                        // for allocator, allocator_traits<...
19#include <tuple>                         // for get
20
21#include "Alternative.h"                 // for Alternative, AltList
22#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
23#include "Common/PassVisitor.h"          // for PassVisitor
24#include "Common/SemanticError.h"        // for SemanticError
25#include "Common/utility.h"              // for ValueGuard, group_iterate
26#include "CurrentObject.h"               // for CurrentObject
27#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
28#include "RenameVars.h"                  // for RenameVars, global_renamer
29#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
30#include "ResolveTypeof.h"               // for resolveTypeof
31#include "Resolver.h"
32#include "SymTab/Autogen.h"              // for SizeType
33#include "SymTab/Indexer.h"              // for Indexer
34#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
35#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
36#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
37#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
38#include "SynTree/Type.h"                // for Type, BasicType, PointerType
39#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
40#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
41#include "typeops.h"                     // for extractResultType
42#include "Unify.h"                       // for unify
43
44using namespace std;
45
46namespace ResolvExpr {
47        struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting {
48                Resolver() {}
49                Resolver( const SymTab::Indexer & other ) {
50                        indexer = other;
51                }
52
53                void previsit( FunctionDecl *functionDecl );
54                void postvisit( FunctionDecl *functionDecl );
55                void previsit( ObjectDecl *objectDecll );
56                void previsit( TypeDecl *typeDecl );
57                void previsit( EnumDecl * enumDecl );
58
59                void previsit( ArrayType * at );
60                void previsit( PointerType * at );
61
62                void previsit( ExprStmt *exprStmt );
63                void previsit( AsmExpr *asmExpr );
64                void previsit( AsmStmt *asmStmt );
65                void previsit( IfStmt *ifStmt );
66                void previsit( WhileStmt *whileStmt );
67                void previsit( ForStmt *forStmt );
68                void previsit( SwitchStmt *switchStmt );
69                void previsit( CaseStmt *caseStmt );
70                void previsit( BranchStmt *branchStmt );
71                void previsit( ReturnStmt *returnStmt );
72                void previsit( ThrowStmt *throwStmt );
73                void previsit( CatchStmt *catchStmt );
74                void previsit( WaitForStmt * stmt );
75
76                void previsit( SingleInit *singleInit );
77                void previsit( ListInit *listInit );
78                void previsit( ConstructorInit *ctorInit );
79          private:
80        typedef std::list< Initializer * >::iterator InitIterator;
81
82                template< typename PtrType >
83                void handlePtrType( PtrType * type );
84
85          void resolveAggrInit( ReferenceToType *, InitIterator &, InitIterator & );
86          void resolveSingleAggrInit( Declaration *, InitIterator &, InitIterator &, TypeSubstitution sub );
87          void fallbackInit( ConstructorInit * ctorInit );
88
89                Type * functionReturn = nullptr;
90                CurrentObject currentObject = nullptr;
91                bool inEnumDecl = false;
92        };
93
94        void resolve( std::list< Declaration * > translationUnit ) {
95                PassVisitor<Resolver> resolver;
96                acceptAll( translationUnit, resolver );
97        }
98
99        void resolveDecl( Declaration * decl, const SymTab::Indexer &indexer ) {
100                PassVisitor<Resolver> resolver( indexer );
101                maybeAccept( decl, resolver );
102        }
103
104        // used in resolveTypeof
105        Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
106                TypeEnvironment env;
107                return resolveInVoidContext( expr, indexer, env );
108        }
109
110        namespace {
111                void finishExpr( Expression *expr, const TypeEnvironment &env, TypeSubstitution * oldenv = nullptr ) {
112                        expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
113                        env.makeSubstitution( *expr->get_env() );
114                }
115        } // namespace
116
117        Expression *findVoidExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
118                global_renamer.reset();
119                TypeEnvironment env;
120                Expression *newExpr = resolveInVoidContext( untyped, indexer, env );
121                finishExpr( newExpr, env, untyped->env );
122                return newExpr;
123        }
124
125        Expression * findSingleExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
126                TypeEnvironment env;
127                AlternativeFinder finder( indexer, env );
128                finder.find( untyped );
129                #if 0
130                if ( finder.get_alternatives().size() != 1 ) {
131                        std::cerr << "untyped expr is ";
132                        untyped->print( std::cerr );
133                        std::cerr << std::endl << "alternatives are:";
134                        for ( const Alternative & alt : finder.get_alternatives() ) {
135                                alt.print( std::cerr );
136                        } // for
137                } // if
138                #endif
139                assertf( finder.get_alternatives().size() == 1, "findSingleExpression: must have exactly one alternative at the end." );
140                Alternative &choice = finder.get_alternatives().front();
141                Expression *newExpr = choice.expr->clone();
142                finishExpr( newExpr, choice.env, untyped->env );
143                return newExpr;
144        }
145
146        namespace {
147                bool isIntegralType( Type *type ) {
148                        if ( dynamic_cast< EnumInstType * >( type ) ) {
149                                return true;
150                        } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
151                                return bt->isInteger();
152                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
153                                return true;
154                        } else {
155                                return false;
156                        } // if
157                }
158
159                Expression *findIntegralExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
160                        TypeEnvironment env;
161                        AlternativeFinder finder( indexer, env );
162                        finder.find( untyped );
163#if 0
164                        if ( finder.get_alternatives().size() != 1 ) {
165                                std::cout << "untyped expr is ";
166                                untyped->print( std::cout );
167                                std::cout << std::endl << "alternatives are:";
168                                for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
169                                        i->print( std::cout );
170                                } // for
171                        } // if
172#endif
173                        Expression *newExpr = 0;
174                        const TypeEnvironment *newEnv = 0;
175                        for ( AltList::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
176                                if ( i->expr->get_result()->size() == 1 && isIntegralType( i->expr->get_result() ) ) {
177                                        if ( newExpr ) {
178                                                throw SemanticError( "Too many interpretations for case control expression", untyped );
179                                        } else {
180                                                newExpr = i->expr->clone();
181                                                newEnv = &i->env;
182                                        } // if
183                                } // if
184                        } // for
185                        if ( ! newExpr ) {
186                                throw SemanticError( "No interpretations for case control expression", untyped );
187                        } // if
188                        finishExpr( newExpr, *newEnv, untyped->env );
189                        return newExpr;
190                }
191
192        }
193
194        void Resolver::previsit( ObjectDecl *objectDecl ) {
195                Type *new_type = resolveTypeof( objectDecl->get_type(), indexer );
196                objectDecl->set_type( new_type );
197                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
198                // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
199                // initContext because of a function type can contain object declarations in the return and parameter types. So
200                // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
201                // the RHS.
202                GuardValue( currentObject );
203                currentObject = CurrentObject( objectDecl->get_type() );
204                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
205                        // enumerator initializers should not use the enum type to initialize, since
206                        // the enum type is still incomplete at this point. Use signed int instead.
207                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
208                }
209        }
210
211        template< typename PtrType >
212        void Resolver::handlePtrType( PtrType * type ) {
213                if ( type->get_dimension() ) {
214                        CastExpr *castExpr = new CastExpr( type->get_dimension(), SymTab::SizeType->clone() );
215                        Expression *newExpr = findSingleExpression( castExpr, indexer );
216                        delete type->get_dimension();
217                        type->set_dimension( newExpr );
218                }
219        }
220
221        void Resolver::previsit( ArrayType * at ) {
222                handlePtrType( at );
223        }
224
225        void Resolver::previsit( PointerType * pt ) {
226                handlePtrType( pt );
227        }
228
229        void Resolver::previsit( TypeDecl *typeDecl ) {
230                if ( typeDecl->get_base() ) {
231                        Type *new_type = resolveTypeof( typeDecl->get_base(), indexer );
232                        typeDecl->set_base( new_type );
233                } // if
234        }
235
236        void Resolver::previsit( FunctionDecl *functionDecl ) {
237#if 0
238                std::cerr << "resolver visiting functiondecl ";
239                functionDecl->print( std::cerr );
240                std::cerr << std::endl;
241#endif
242                Type *new_type = resolveTypeof( functionDecl->get_type(), indexer );
243                functionDecl->set_type( new_type );
244                GuardValue( functionReturn );
245                functionReturn = ResolvExpr::extractResultType( functionDecl->get_functionType() );
246        }
247
248        void Resolver::postvisit( FunctionDecl *functionDecl ) {
249                // default value expressions have an environment which shouldn't be there and trips up later passes.
250                // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
251                // see how it's useful.
252                for ( Declaration * d : functionDecl->get_functionType()->get_parameters() ) {
253                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
254                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->get_init() ) ) {
255                                        delete init->get_value()->get_env();
256                                        init->get_value()->set_env( nullptr );
257                                }
258                        }
259                }
260        }
261
262        void Resolver::previsit( EnumDecl * ) {
263                // in case we decide to allow nested enums
264                GuardValue( inEnumDecl );
265                inEnumDecl = true;
266        }
267
268        void Resolver::previsit( ExprStmt *exprStmt ) {
269                visit_children = false;
270                assertf( exprStmt->get_expr(), "ExprStmt has null Expression in resolver" );
271                Expression *newExpr = findVoidExpression( exprStmt->get_expr(), indexer );
272                delete exprStmt->get_expr();
273                exprStmt->set_expr( newExpr );
274        }
275
276        void Resolver::previsit( AsmExpr *asmExpr ) {
277                visit_children = false;
278                Expression *newExpr = findVoidExpression( asmExpr->get_operand(), indexer );
279                delete asmExpr->get_operand();
280                asmExpr->set_operand( newExpr );
281                if ( asmExpr->get_inout() ) {
282                        newExpr = findVoidExpression( asmExpr->get_inout(), indexer );
283                        delete asmExpr->get_inout();
284                        asmExpr->set_inout( newExpr );
285                } // if
286        }
287
288        void Resolver::previsit( AsmStmt *asmStmt ) {
289                visit_children = false;
290                acceptAll( asmStmt->get_input(), *visitor );
291                acceptAll( asmStmt->get_output(), *visitor );
292        }
293
294        void Resolver::previsit( IfStmt *ifStmt ) {
295                Expression *newExpr = findSingleExpression( ifStmt->get_condition(), indexer );
296                delete ifStmt->get_condition();
297                ifStmt->set_condition( newExpr );
298        }
299
300        void Resolver::previsit( WhileStmt *whileStmt ) {
301                Expression *newExpr = findSingleExpression( whileStmt->get_condition(), indexer );
302                delete whileStmt->get_condition();
303                whileStmt->set_condition( newExpr );
304        }
305
306        void Resolver::previsit( ForStmt *forStmt ) {
307                if ( forStmt->get_condition() ) {
308                        Expression * newExpr = findSingleExpression( forStmt->get_condition(), indexer );
309                        delete forStmt->get_condition();
310                        forStmt->set_condition( newExpr );
311                } // if
312
313                if ( forStmt->get_increment() ) {
314                        Expression * newExpr = findVoidExpression( forStmt->get_increment(), indexer );
315                        delete forStmt->get_increment();
316                        forStmt->set_increment( newExpr );
317                } // if
318        }
319
320        void Resolver::previsit( SwitchStmt *switchStmt ) {
321                GuardValue( currentObject );
322                Expression *newExpr;
323                newExpr = findIntegralExpression( switchStmt->get_condition(), indexer );
324                delete switchStmt->get_condition();
325                switchStmt->set_condition( newExpr );
326
327                currentObject = CurrentObject( newExpr->get_result() );
328        }
329
330        void Resolver::previsit( CaseStmt *caseStmt ) {
331                if ( caseStmt->get_condition() ) {
332                        std::list< InitAlternative > initAlts = currentObject.getOptions();
333                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
334                        CastExpr * castExpr = new CastExpr( caseStmt->get_condition(), initAlts.front().type->clone() );
335                        Expression * newExpr = findSingleExpression( castExpr, indexer );
336                        castExpr = strict_dynamic_cast< CastExpr * >( newExpr );
337                        caseStmt->set_condition( castExpr->get_arg() );
338                        castExpr->set_arg( nullptr );
339                        delete castExpr;
340                }
341        }
342
343        void Resolver::previsit( BranchStmt *branchStmt ) {
344                visit_children = false;
345                // must resolve the argument for a computed goto
346                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
347                        if ( Expression * arg = branchStmt->get_computedTarget() ) {
348                                VoidType v = Type::Qualifiers();                // cast to void * for the alternative finder
349                                PointerType pt( Type::Qualifiers(), v.clone() );
350                                CastExpr * castExpr = new CastExpr( arg, pt.clone() );
351                                Expression * newExpr = findSingleExpression( castExpr, indexer ); // find best expression
352                                branchStmt->set_target( newExpr );
353                        } // if
354                } // if
355        }
356
357        void Resolver::previsit( ReturnStmt *returnStmt ) {
358                visit_children = false;
359                if ( returnStmt->get_expr() ) {
360                        CastExpr *castExpr = new CastExpr( returnStmt->get_expr(), functionReturn->clone() );
361                        Expression *newExpr = findSingleExpression( castExpr, indexer );
362                        delete castExpr;
363                        returnStmt->set_expr( newExpr );
364                } // if
365        }
366
367        void Resolver::previsit( ThrowStmt *throwStmt ) {
368                visit_children = false;
369                // TODO: Replace *exception type with &exception type.
370                if ( throwStmt->get_expr() ) {
371                        StructDecl * exception_decl =
372                                indexer.lookupStruct( "__cfaehm__base_exception_t" );
373                        assert( exception_decl );
374                        Expression * wrapped = new CastExpr(
375                                throwStmt->get_expr(),
376                                new PointerType(
377                                        noQualifiers,
378                                        new StructInstType(
379                                                noQualifiers,
380                                                exception_decl
381                                                )
382                                        )
383                                );
384                        Expression * newExpr = findSingleExpression( wrapped, indexer );
385                        throwStmt->set_expr( newExpr );
386                }
387        }
388
389        void Resolver::previsit( CatchStmt *catchStmt ) {
390                if ( catchStmt->get_cond() ) {
391                        Expression * wrapped = new CastExpr(
392                                catchStmt->get_cond(),
393                                new BasicType( noQualifiers, BasicType::Bool )
394                                );
395                        catchStmt->set_cond( findSingleExpression( wrapped, indexer ) );
396                }
397        }
398
399        inline void resolveAsIf( Expression *& expr, SymTab::Indexer & indexer ) {
400                if( !expr ) return;
401                Expression * newExpr = findSingleExpression( expr, indexer );
402                delete expr;
403                expr = newExpr;
404        }
405
406        inline void resolveAsType( Expression *& expr, Type * type, SymTab::Indexer & indexer ) {
407                if( !expr ) return;
408                Expression * newExpr = findSingleExpression( new CastExpr( expr, type ), indexer );
409                delete expr;
410                expr = newExpr;
411        }
412
413        template< typename iterator_t >
414        inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
415                while( it != end && !(*it)->get_type()->get_mutex() ) {
416                        it++;
417                }
418
419                return it != end;
420        }
421
422        void Resolver::previsit( WaitForStmt * stmt ) {
423                visit_children = false;
424
425                // Resolve all clauses first
426                for( auto& clause : stmt->clauses ) {
427
428                        TypeEnvironment env;
429                        AlternativeFinder funcFinder( indexer, env );
430
431                        // Find all alternatives for a function in canonical form
432                        funcFinder.findWithAdjustment( clause.target.function );
433
434                        if ( funcFinder.get_alternatives().empty() ) {
435                                stringstream ss;
436                                ss << "Use of undeclared indentifier '";
437                                ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
438                                ss << "' in call to waitfor";
439                                throw SemanticError( ss.str() );
440                        }
441
442                        // Find all alternatives for all arguments in canonical form
443                        std::list< AlternativeFinder > argAlternatives;
444                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
445
446                        // List all combinations of arguments
447                        std::list< AltList > possibilities;
448                        combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
449
450                        AltList                func_candidates;
451                        std::vector< AltList > args_candidates;
452
453                        // For every possible function :
454                        //      try matching the arguments to the parameters
455                        //      not the other way around because we have more arguments than parameters
456                        SemanticError errors;
457                        for ( Alternative & func : funcFinder.get_alternatives() ) {
458                                try {
459                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
460                                        if( !pointer ) {
461                                                throw SemanticError( "candidate not viable: not a pointer type\n", func.expr->get_result() );
462                                        }
463
464                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
465                                        if( !function ) {
466                                                throw SemanticError( "candidate not viable: not a function type\n", pointer->get_base() );
467                                        }
468
469
470                                        {
471                                                auto param     = function->parameters.begin();
472                                                auto param_end = function->parameters.end();
473
474                                                if( !advance_to_mutex( param, param_end ) ) {
475                                                        throw SemanticError("candidate function not viable: no mutex parameters\n", function);
476                                                }
477                                        }
478
479                                        Alternative newFunc( func );
480                                        // Strip reference from function
481                                        referenceToRvalueConversion( newFunc.expr );
482
483                                        // For all the set of arguments we have try to match it with the parameter of the current function alternative
484                                        for ( auto & argsList : possibilities ) {
485
486                                                try {
487                                                        // Declare data structures need for resolution
488                                                        OpenVarSet openVars;
489                                                        AssertionSet resultNeed, resultHave;
490                                                        TypeEnvironment resultEnv;
491
492                                                        // Load type variables from arguemnts into one shared space
493                                                        simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
494
495                                                        // Make sure we don't widen any existing bindings
496                                                        for ( auto & i : resultEnv ) {
497                                                                i.allowWidening = false;
498                                                        }
499
500                                                        // Find any unbound type variables
501                                                        resultEnv.extractOpenVars( openVars );
502
503                                                        auto param     = function->parameters.begin();
504                                                        auto param_end = function->parameters.end();
505
506                                                        // For every arguments of its set, check if it matches one of the parameter
507                                                        // The order is important
508                                                        for( auto & arg : argsList ) {
509
510                                                                // Ignore non-mutex arguments
511                                                                if( !advance_to_mutex( param, param_end ) ) {
512                                                                        // We ran out of parameters but still have arguments
513                                                                        // this function doesn't match
514                                                                        throw SemanticError("candidate function not viable: too many mutex arguments\n", function);
515                                                                }
516
517                                                                // Check if the argument matches the parameter type in the current scope
518                                                                if( ! unify( (*param)->get_type(), arg.expr->get_result(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
519                                                                        // Type doesn't match
520                                                                        stringstream ss;
521                                                                        ss << "candidate function not viable: no known convertion from '";
522                                                                        arg.expr->get_result()->print( ss );
523                                                                        ss << "' to '";
524                                                                        (*param)->get_type()->print( ss );
525                                                                        ss << "'\n";
526                                                                        throw SemanticError(ss.str(), function);
527                                                                }
528
529                                                                param++;
530                                                        }
531
532                                                        // All arguments match !
533
534                                                        // Check if parameters are missing
535                                                        if( advance_to_mutex( param, param_end ) ) {
536                                                                // We ran out of arguments but still have parameters left
537                                                                // this function doesn't match
538                                                                throw SemanticError("candidate function not viable: too few mutex arguments\n", function);
539                                                        }
540
541                                                        // All parameters match !
542
543                                                        // Finish the expressions to tie in the proper environments
544                                                        finishExpr( newFunc.expr, resultEnv );
545                                                        for( Alternative & alt : argsList ) {
546                                                                finishExpr( alt.expr, resultEnv );
547                                                        }
548
549                                                        // This is a match store it and save it for later
550                                                        func_candidates.push_back( newFunc );
551                                                        args_candidates.push_back( argsList );
552
553                                                }
554                                                catch( SemanticError &e ) {
555                                                        errors.append( e );
556                                                }
557                                        }
558                                }
559                                catch( SemanticError &e ) {
560                                        errors.append( e );
561                                }
562                        }
563
564                        // Make sure we got the right number of arguments
565                        if( func_candidates.empty() )    { SemanticError top( "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
566                        if( args_candidates.empty() )    { SemanticError top( "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
567                        if( func_candidates.size() > 1 ) { SemanticError top( "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
568                        if( args_candidates.size() > 1 ) { SemanticError top( "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
569
570
571                        // Swap the results from the alternative with the unresolved values.
572                        // Alternatives will handle deletion on destruction
573                        std::swap( clause.target.function, func_candidates.front().expr );
574                        for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
575                                std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
576                        }
577
578                        // Resolve the conditions as if it were an IfStmt
579                        // Resolve the statments normally
580                        resolveAsIf( clause.condition, this->indexer );
581                        clause.statement->accept( *visitor );
582                }
583
584
585                if( stmt->timeout.statement ) {
586                        // Resolve the timeout as an size_t for now
587                        // Resolve the conditions as if it were an IfStmt
588                        // Resolve the statments normally
589                        resolveAsType( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
590                        resolveAsIf  ( stmt->timeout.condition, this->indexer );
591                        stmt->timeout.statement->accept( *visitor );
592                }
593
594                if( stmt->orelse.statement ) {
595                        // Resolve the conditions as if it were an IfStmt
596                        // Resolve the statments normally
597                        resolveAsIf( stmt->orelse.condition, this->indexer );
598                        stmt->orelse.statement->accept( *visitor );
599                }
600        }
601
602        template< typename T >
603        bool isCharType( T t ) {
604                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
605                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
606                                bt->get_kind() == BasicType::UnsignedChar;
607                }
608                return false;
609        }
610
611        void Resolver::previsit( SingleInit *singleInit ) {
612                visit_children = false;
613                // resolve initialization using the possibilities as determined by the currentObject cursor
614                UntypedInitExpr * untyped = new UntypedInitExpr( singleInit->get_value(), currentObject.getOptions() );
615                Expression * newExpr = findSingleExpression( untyped, indexer );
616                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
617
618                // move cursor to the object that is actually initialized
619                currentObject.setNext( initExpr->get_designation() );
620
621                // discard InitExpr wrapper and retain relevant pieces
622                newExpr = initExpr->get_expr();
623                newExpr->set_env( initExpr->get_env() );
624                initExpr->set_expr( nullptr );
625                initExpr->set_env( nullptr );
626                delete initExpr;
627
628                // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
629                Type * initContext = currentObject.getCurrentType();
630
631                // check if actual object's type is char[]
632                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
633                        if ( isCharType( at->get_base() ) ) {
634                                // check if the resolved type is char *
635                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
636                                        if ( isCharType( pt->get_base() ) ) {
637                                                // strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
638                                                CastExpr *ce = strict_dynamic_cast< CastExpr * >( newExpr );
639                                                newExpr = ce->get_arg();
640                                                ce->set_arg( nullptr );
641                                                delete ce;
642                                        }
643                                }
644                        }
645                }
646
647                // set initializer expr to resolved express
648                singleInit->set_value( newExpr );
649
650                // move cursor to next object in preparation for next initializer
651                currentObject.increment();
652        }
653
654        void Resolver::previsit( ListInit * listInit ) {
655                visit_children = false;
656                // move cursor into brace-enclosed initializer-list
657                currentObject.enterListInit();
658                // xxx - fix this so that the list isn't copied, iterator should be used to change current element
659                std::list<Designation *> newDesignations;
660                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
661                        // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
662                        // the initializer against that object.
663                        Designation * des = std::get<0>(p);
664                        Initializer * init = std::get<1>(p);
665                        newDesignations.push_back( currentObject.findNext( des ) );
666                        init->accept( *visitor );
667                }
668                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
669                listInit->get_designations() = newDesignations; // xxx - memory management
670                currentObject.exitListInit();
671
672                // xxx - this part has not be folded into CurrentObject yet
673                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
674                //      Type * base = tt->get_baseType()->get_base();
675                //      if ( base ) {
676                //              // know the implementation type, so try using that as the initContext
677                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
678                //              currentObject = &tmpObj;
679                //              visit( listInit );
680                //      } else {
681                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
682                //              Parent::visit( listInit );
683                //      }
684                // } else {
685        }
686
687        // ConstructorInit - fall back on C-style initializer
688        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
689                // could not find valid constructor, or found an intrinsic constructor
690                // fall back on C-style initializer
691                delete ctorInit->get_ctor();
692                ctorInit->set_ctor( NULL );
693                delete ctorInit->get_dtor();
694                ctorInit->set_dtor( NULL );
695                maybeAccept( ctorInit->get_init(), *visitor );
696        }
697
698        // needs to be callable from outside the resolver, so this is a standalone function
699        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
700                assert( ctorInit );
701                PassVisitor<Resolver> resolver( indexer );
702                ctorInit->accept( resolver );
703        }
704
705        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
706                assert( stmtExpr );
707                PassVisitor<Resolver> resolver( indexer );
708                stmtExpr->accept( resolver );
709        }
710
711        void Resolver::previsit( ConstructorInit *ctorInit ) {
712                visit_children = false;
713                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
714                maybeAccept( ctorInit->get_ctor(), *visitor );
715                maybeAccept( ctorInit->get_dtor(), *visitor );
716
717                // found a constructor - can get rid of C-style initializer
718                delete ctorInit->get_init();
719                ctorInit->set_init( NULL );
720
721                // intrinsic single parameter constructors and destructors do nothing. Since this was
722                // implicitly generated, there's no way for it to have side effects, so get rid of it
723                // to clean up generated code.
724                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
725                        delete ctorInit->get_ctor();
726                        ctorInit->set_ctor( NULL );
727                }
728
729                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_dtor() ) ) {
730                        delete ctorInit->get_dtor();
731                        ctorInit->set_dtor( NULL );
732                }
733
734                // xxx - todo -- what about arrays?
735                // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
736                //      // can reduce the constructor down to a SingleInit using the
737                //      // second argument from the ctor call, since
738                //      delete ctorInit->get_ctor();
739                //      ctorInit->set_ctor( NULL );
740
741                //      Expression * arg =
742                //      ctorInit->set_init( new SingleInit( arg ) );
743                // }
744        }
745} // namespace ResolvExpr
746
747// Local Variables: //
748// tab-width: 4 //
749// mode: c++ //
750// compile-command: "make install" //
751// End: //
Note: See TracBrowser for help on using the repository browser.