source: src/ResolvExpr/Resolver.cc @ 1d7b0a8

new-env
Last change on this file since 1d7b0a8 was 1d7b0a8, checked in by Aaron Moss <a3moss@…>, 6 years ago

Move AlternativeFinder? find flags to ResolvMode? struct

  • Property mode set to 100644
File size: 32.7 KB
RevLine 
[a32b204]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//
[71f4e4f]7// Resolver.cc --
[a32b204]8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:17:01 2015
[93401f8]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sat Feb 17 11:19:40 2018
13// Update Count     : 213
[a32b204]14//
15
[ea6332d]16#include <stddef.h>                      // for NULL
[e3e16bc]17#include <cassert>                       // for strict_dynamic_cast, assert
[ea6332d]18#include <memory>                        // for allocator, allocator_traits<...
19#include <tuple>                         // for get
[bd4f2e9]20#include <vector>
[ea6332d]21
22#include "Alternative.h"                 // for Alternative, AltList
23#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
[f229fc2]24#include "Common/GC.h"                   // for new_generation, collect_young
[a4ca48c]25#include "Common/PassVisitor.h"          // for PassVisitor
[ea6332d]26#include "Common/SemanticError.h"        // for SemanticError
27#include "Common/utility.h"              // for ValueGuard, group_iterate
28#include "CurrentObject.h"               // for CurrentObject
[0a60c04]29#include "InitTweak/GenInit.h"
[ea6332d]30#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
31#include "RenameVars.h"                  // for RenameVars, global_renamer
32#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
33#include "ResolveTypeof.h"               // for resolveTypeof
[e4d829b]34#include "Resolver.h"
[1d7b0a8]35#include "ResolvMode.h"                  // for ResolvMode
[ea6332d]36#include "SymTab/Autogen.h"              // for SizeType
37#include "SymTab/Indexer.h"              // for Indexer
38#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
39#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
40#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
41#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
42#include "SynTree/Type.h"                // for Type, BasicType, PointerType
43#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
44#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
[0a60c04]45#include "Tuples/Tuples.h"
[ea6332d]46#include "typeops.h"                     // for extractResultType
[1dcd9554]47#include "Unify.h"                       // for unify
[51b7345]48
[d9a0e76]49using namespace std;
[51b7345]50
[d9a0e76]51namespace ResolvExpr {
[0a60c04]52        struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting, public WithStmtsToAdd {
[a4ca48c]53                Resolver() {}
54                Resolver( const SymTab::Indexer & other ) {
55                        indexer = other;
[1d2b64f]56                }
[71f4e4f]57
[a4ca48c]58                void previsit( FunctionDecl *functionDecl );
59                void postvisit( FunctionDecl *functionDecl );
[3c398b6]60                void previsit( ObjectDecl *objectDecll );
[a4ca48c]61                void previsit( TypeDecl *typeDecl );
62                void previsit( EnumDecl * enumDecl );
[bd87b138]63                void previsit( StaticAssertDecl * assertDecl );
[a4ca48c]64
65                void previsit( ArrayType * at );
66                void previsit( PointerType * at );
67
68                void previsit( ExprStmt *exprStmt );
69                void previsit( AsmExpr *asmExpr );
70                void previsit( AsmStmt *asmStmt );
71                void previsit( IfStmt *ifStmt );
72                void previsit( WhileStmt *whileStmt );
73                void previsit( ForStmt *forStmt );
74                void previsit( SwitchStmt *switchStmt );
75                void previsit( CaseStmt *caseStmt );
76                void previsit( BranchStmt *branchStmt );
77                void previsit( ReturnStmt *returnStmt );
78                void previsit( ThrowStmt *throwStmt );
79                void previsit( CatchStmt *catchStmt );
[695e00d]80                void previsit( WaitForStmt * stmt );
[882ad37]81                void previsit( WithStmt * withStmt );
[a4ca48c]82
83                void previsit( SingleInit *singleInit );
84                void previsit( ListInit *listInit );
85                void previsit( ConstructorInit *ctorInit );
[a32b204]86          private:
[c28a038d]87                typedef std::list< Initializer * >::iterator InitIterator;
[94b4364]88
[40e636a]89                template< typename PtrType >
90                void handlePtrType( PtrType * type );
91
[c28a038d]92                void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
93                void fallbackInit( ConstructorInit * ctorInit );
[b726084]94
[77971f6]95                Type * functionReturn = nullptr;
[e4d829b]96                CurrentObject currentObject = nullptr;
[a436947]97                bool inEnumDecl = false;
[a32b204]98        };
[d9a0e76]99
[a32b204]100        void resolve( std::list< Declaration * > translationUnit ) {
[a4ca48c]101                PassVisitor<Resolver> resolver;
[a32b204]102                acceptAll( translationUnit, resolver );
[d9a0e76]103        }
104
[8b11840]105        void resolveDecl( Declaration * decl, const SymTab::Indexer &indexer ) {
106                PassVisitor<Resolver> resolver( indexer );
107                maybeAccept( decl, resolver );
108        }
109
[c71b256]110        namespace {
111                struct DeleteFinder : public WithShortCircuiting        {
112                        DeletedExpr * delExpr = nullptr;
113                        void previsit( DeletedExpr * expr ) {
114                                if ( delExpr ) visit_children = false;
115                                else delExpr = expr;
116                        }
117
118                        void previsit( Expression * ) {
119                                if ( delExpr ) visit_children = false;
120                        }
121                };
122        }
123
124        DeletedExpr * findDeletedExpr( Expression * expr ) {
125                PassVisitor<DeleteFinder> finder;
126                expr->accept( finder );
127                return finder.pass.delExpr;
[d9a0e76]128        }
[a32b204]129
130        namespace {
[cdb990a]131                struct StripCasts {
132                        Expression * postmutate( CastExpr * castExpr ) {
133                                if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
134                                        // generated cast is to the same type as its argument, so it's unnecessary -- remove it
135                                        Expression * expr = castExpr->arg;
136                                        castExpr->arg = nullptr;
137                                        std::swap( expr->env, castExpr->env );
138                                        return expr;
139                                }
140                                return castExpr;
141                        }
142
143                        static void strip( Expression *& expr ) {
144                                PassVisitor<StripCasts> stripper;
145                                expr = expr->acceptMutator( stripper );
146                        }
147                };
148
149                void finishExpr( Expression *&expr, const TypeEnvironment &env, TypeSubstitution * oldenv = nullptr ) {
[7664fad]150                        expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
[cdb990a]151                        env.makeSubstitution( *expr->env );
152                        StripCasts::strip( expr ); // remove unnecessary casts that may be buried in an expression
[a32b204]153                }
[0a22cda]154
155                void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
156                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
157                                if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
158                                        // cast is to the same type as its argument, so it's unnecessary -- remove it
159                                        expr = castExpr->arg;
160                                        castExpr->arg = nullptr;
161                                        std::swap( expr->env, castExpr->env );
162                                }
163                        }
164                }
[db4ecc5]165        } // namespace
[a32b204]166
[8f98b78]167        namespace {
[1d7b0a8]168                void findUnfinishedKindExpression( Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
[c71b256]169                        assertf( untyped, "expected a non-null expression." );
[f229fc2]170
[2efe4b8]171                        auto guard = new_generation();  // set up GC generation for this top-level expression
[f229fc2]172
[8587878e]173                        TypeEnvironment env;
174                        AlternativeFinder finder( indexer, env );
[1d7b0a8]175                        finder.find( untyped, mode );
[c71b256]176
177                        #if 0
178                        if ( finder.get_alternatives().size() != 1 ) {
179                                std::cerr << "untyped expr is ";
180                                untyped->print( std::cerr );
181                                std::cerr << std::endl << "alternatives are:";
182                                for ( const Alternative & alt : finder.get_alternatives() ) {
183                                        alt.print( std::cerr );
184                                } // for
185                        } // if
186                        #endif
[8587878e]187
188                        AltList candidates;
189                        for ( Alternative & alt : finder.get_alternatives() ) {
[c71b256]190                                if ( pred( alt ) ) {
[8587878e]191                                        candidates.push_back( std::move( alt ) );
192                                }
193                        }
194
[c71b256]195                        // xxx - if > 1 alternative with same cost, ignore deleted and pick from remaining
[8587878e]196                        // choose the lowest cost expression among the candidates
197                        AltList winners;
198                        findMinCost( candidates.begin(), candidates.end(), back_inserter( winners ) );
199                        if ( winners.size() == 0 ) {
[a16764a6]200                                SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
[8587878e]201                        } else if ( winners.size() != 1 ) {
202                                std::ostringstream stream;
[c71b256]203                                stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
[8587878e]204                                untyped->print( stream );
[93401f8]205                                stream << " Alternatives are:\n";
[8587878e]206                                printAlts( winners, stream, 1 );
[a16764a6]207                                SemanticError( untyped->location, stream.str() );
[8587878e]208                        }
209
210                        // there is one unambiguous interpretation - move the expression into the with statement
[c71b256]211                        Alternative & choice = winners.front();
212                        if ( findDeletedExpr( choice.expr ) ) {
[2efe4b8]213                                trace( choice.expr );
[a16764a6]214                                SemanticError( choice.expr, "Unique best alternative includes deleted identifier in " );
[c71b256]215                        }
216                        alt = std::move( choice );
[2efe4b8]217                        trace( alt );
[c71b256]218                }
219
220                /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
[1d7b0a8]221                void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
[c71b256]222                        if ( ! untyped ) return;
223                        Alternative choice;
[1d7b0a8]224                        findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
[c71b256]225                        finishExpr( choice.expr, choice.env, untyped->env );
226                        untyped = choice.expr;
227                        choice.expr = nullptr;
[8587878e]228                }
229
[c71b256]230                bool standardAlternativeFilter( const Alternative & ) {
231                        // currently don't need to filter, under normal circumstances.
232                        // in the future, this may be useful for removing deleted expressions
233                        return true;
234                }
235        } // namespace
236
237        // used in resolveTypeof
238        Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
239                TypeEnvironment env;
240                return resolveInVoidContext( expr, indexer, env );
241        }
242
243        Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
244                // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
245                // interpretations, an exception has already been thrown.
246                assertf( expr, "expected a non-null expression." );
247
[bd06384]248                auto untyped = new CastExpr{ expr }; // cast to void
[c71b256]249
250                // set up and resolve expression cast to void
251                Alternative choice;
[1d7b0a8]252                findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
[c71b256]253                CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
254                env = std::move( choice.env );
255
256                // clean up resolved expression
[bd06384]257                return castExpr->arg;
[c71b256]258        }
259
260        void findVoidExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
261                resetTyVarRenaming();
262                TypeEnvironment env;
263                Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
264                finishExpr( newExpr, env, untyped->env );
265                untyped = newExpr;
266        }
267
268        void findSingleExpression( Expression *&untyped, const SymTab::Indexer &indexer ) {
269                findKindExpression( untyped, indexer, "", standardAlternativeFilter );
270        }
271
272        void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
273                assert( untyped && type );
274                untyped = new CastExpr( untyped, type );
275                findSingleExpression( untyped, indexer );
276                removeExtraneousCast( untyped, indexer );
277        }
278
279        namespace {
280                bool isIntegralType( const Alternative & alt ) {
281                        Type * type = alt.expr->result;
[a32b204]282                        if ( dynamic_cast< EnumInstType * >( type ) ) {
283                                return true;
284                        } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
285                                return bt->isInteger();
[89e6ffc]286                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
287                                return true;
[a32b204]288                        } else {
289                                return false;
290                        } // if
291                }
[71f4e4f]292
[08da53d]293                void findIntegralExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
[8587878e]294                        findKindExpression( untyped, indexer, "condition", isIntegralType );
[a32b204]295                }
296        }
[71f4e4f]297
[a4ca48c]298        void Resolver::previsit( ObjectDecl *objectDecl ) {
299                Type *new_type = resolveTypeof( objectDecl->get_type(), indexer );
[a32b204]300                objectDecl->set_type( new_type );
[3cfe27f]301                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
302                // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
303                // initContext because of a function type can contain object declarations in the return and parameter types. So
304                // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
305                // the RHS.
[a4ca48c]306                GuardValue( currentObject );
[e4d829b]307                currentObject = CurrentObject( objectDecl->get_type() );
308                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
[a436947]309                        // enumerator initializers should not use the enum type to initialize, since
310                        // the enum type is still incomplete at this point. Use signed int instead.
[e4d829b]311                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
[a436947]312                }
[bfbf97f]313        }
314
[40e636a]315        template< typename PtrType >
316        void Resolver::handlePtrType( PtrType * type ) {
317                if ( type->get_dimension() ) {
[08da53d]318                        findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
[d1d17f5]319                }
[40e636a]320        }
321
[a4ca48c]322        void Resolver::previsit( ArrayType * at ) {
[40e636a]323                handlePtrType( at );
[a32b204]324        }
[94b4364]325
[a4ca48c]326        void Resolver::previsit( PointerType * pt ) {
[40e636a]327                handlePtrType( pt );
328        }
329
[a4ca48c]330        void Resolver::previsit( TypeDecl *typeDecl ) {
[a32b204]331                if ( typeDecl->get_base() ) {
[a4ca48c]332                        Type *new_type = resolveTypeof( typeDecl->get_base(), indexer );
[a32b204]333                        typeDecl->set_base( new_type );
334                } // if
335        }
[94b4364]336
[a4ca48c]337        void Resolver::previsit( FunctionDecl *functionDecl ) {
[d9a0e76]338#if 0
[a4ca48c]339                std::cerr << "resolver visiting functiondecl ";
340                functionDecl->print( std::cerr );
341                std::cerr << std::endl;
[d9a0e76]342#endif
[c28a038d]343                Type *new_type = resolveTypeof( functionDecl->type, indexer );
[a32b204]344                functionDecl->set_type( new_type );
[a4ca48c]345                GuardValue( functionReturn );
[60914351]346                functionReturn = ResolvExpr::extractResultType( functionDecl->type );
347
348                {
349                        // resolve with-exprs with parameters in scope and add any newly generated declarations to the
350                        // front of the function body.
351                        auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
352                        indexer.addFunctionType( functionDecl->type );
353                        std::list< Statement * > newStmts;
354                        resolveWithExprs( functionDecl->withExprs, newStmts );
[a33fdbe]355                        if ( functionDecl->statements ) {
356                                functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
357                        } else {
358                                assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
359                        }
[60914351]360                }
[a4ca48c]361        }
[88d1066]362
[a4ca48c]363        void Resolver::postvisit( FunctionDecl *functionDecl ) {
[88d1066]364                // default value expressions have an environment which shouldn't be there and trips up later passes.
365                // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
366                // see how it's useful.
[c28a038d]367                for ( Declaration * d : functionDecl->type->parameters ) {
[88d1066]368                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
[c28a038d]369                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
370                                        delete init->value->env;
371                                        init->value->env = nullptr;
[88d1066]372                                }
373                        }
374                }
[a32b204]375        }
[51b7345]376
[a4ca48c]377        void Resolver::previsit( EnumDecl * ) {
[a436947]378                // in case we decide to allow nested enums
[a4ca48c]379                GuardValue( inEnumDecl );
[a436947]380                inEnumDecl = true;
381        }
382
[bd87b138]383        void Resolver::previsit( StaticAssertDecl * assertDecl ) {
384                findIntegralExpression( assertDecl->condition, indexer );
385        }
386
[a4ca48c]387        void Resolver::previsit( ExprStmt *exprStmt ) {
388                visit_children = false;
[08da53d]389                assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
390                findVoidExpression( exprStmt->expr, indexer );
[a32b204]391        }
[51b7345]392
[a4ca48c]393        void Resolver::previsit( AsmExpr *asmExpr ) {
394                visit_children = false;
[08da53d]395                findVoidExpression( asmExpr->operand, indexer );
[7f5566b]396                if ( asmExpr->get_inout() ) {
[08da53d]397                        findVoidExpression( asmExpr->inout, indexer );
[7f5566b]398                } // if
399        }
400
[a4ca48c]401        void Resolver::previsit( AsmStmt *asmStmt ) {
402                visit_children = false;
403                acceptAll( asmStmt->get_input(), *visitor );
404                acceptAll( asmStmt->get_output(), *visitor );
[7f5566b]405        }
406
[a4ca48c]407        void Resolver::previsit( IfStmt *ifStmt ) {
[8587878e]408                findIntegralExpression( ifStmt->condition, indexer );
[a32b204]409        }
[51b7345]410
[a4ca48c]411        void Resolver::previsit( WhileStmt *whileStmt ) {
[8587878e]412                findIntegralExpression( whileStmt->condition, indexer );
[a32b204]413        }
[51b7345]414
[a4ca48c]415        void Resolver::previsit( ForStmt *forStmt ) {
[08da53d]416                if ( forStmt->condition ) {
[8587878e]417                        findIntegralExpression( forStmt->condition, indexer );
[a32b204]418                } // if
[71f4e4f]419
[08da53d]420                if ( forStmt->increment ) {
421                        findVoidExpression( forStmt->increment, indexer );
[a32b204]422                } // if
423        }
[51b7345]424
[a4ca48c]425        void Resolver::previsit( SwitchStmt *switchStmt ) {
426                GuardValue( currentObject );
[08da53d]427                findIntegralExpression( switchStmt->condition, indexer );
[71f4e4f]428
[08da53d]429                currentObject = CurrentObject( switchStmt->condition->result );
[a32b204]430        }
[51b7345]431
[a4ca48c]432        void Resolver::previsit( CaseStmt *caseStmt ) {
[cdb990a]433                if ( caseStmt->condition ) {
[e4d829b]434                        std::list< InitAlternative > initAlts = currentObject.getOptions();
435                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
[08da53d]436                        // must remove cast from case statement because RangeExpr cannot be cast.
437                        Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
438                        findSingleExpression( newExpr, indexer );
[cdb990a]439                        // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
440                        // Ideally we would perform the conversion internally here.
441                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
442                                newExpr = castExpr->arg;
443                                castExpr->arg = nullptr;
444                                std::swap( newExpr->env, castExpr->env );
445                        }
446                        caseStmt->condition = newExpr;
[32b8144]447                }
[a32b204]448        }
[51b7345]449
[a4ca48c]450        void Resolver::previsit( BranchStmt *branchStmt ) {
451                visit_children = false;
[de62360d]452                // must resolve the argument for a computed goto
453                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
[08da53d]454                        if ( branchStmt->computedTarget ) {
455                                // computed goto argument is void *
456                                findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
[de62360d]457                        } // if
458                } // if
459        }
460
[a4ca48c]461        void Resolver::previsit( ReturnStmt *returnStmt ) {
462                visit_children = false;
[08da53d]463                if ( returnStmt->expr ) {
464                        findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
[a32b204]465                } // if
466        }
[51b7345]467
[a4ca48c]468        void Resolver::previsit( ThrowStmt *throwStmt ) {
469                visit_children = false;
[cbce272]470                // TODO: Replace *exception type with &exception type.
[307a732]471                if ( throwStmt->get_expr() ) {
[cbce272]472                        StructDecl * exception_decl =
[36982fc]473                                indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
[cbce272]474                        assert( exception_decl );
[08da53d]475                        Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
476                        findSingleExpression( throwStmt->expr, exceptType, indexer );
[307a732]477                }
478        }
479
[a4ca48c]480        void Resolver::previsit( CatchStmt *catchStmt ) {
[08da53d]481                if ( catchStmt->cond ) {
482                        findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
[cbce272]483                }
484        }
485
[1dcd9554]486        template< typename iterator_t >
487        inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
488                while( it != end && !(*it)->get_type()->get_mutex() ) {
489                        it++;
490                }
491
492                return it != end;
493        }
494
[695e00d]495        void Resolver::previsit( WaitForStmt * stmt ) {
[8f98b78]496                visit_children = false;
[1dcd9554]497
498                // Resolve all clauses first
499                for( auto& clause : stmt->clauses ) {
500
501                        TypeEnvironment env;
[8f98b78]502                        AlternativeFinder funcFinder( indexer, env );
[1dcd9554]503
504                        // Find all alternatives for a function in canonical form
505                        funcFinder.findWithAdjustment( clause.target.function );
506
507                        if ( funcFinder.get_alternatives().empty() ) {
508                                stringstream ss;
509                                ss << "Use of undeclared indentifier '";
510                                ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
511                                ss << "' in call to waitfor";
[a16764a6]512                                SemanticError( stmt->location, ss.str() );
[1dcd9554]513                        }
514
[b9f383f]515                        if(clause.target.arguments.empty()) {
516                                SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
517                        }
518
[1dcd9554]519                        // Find all alternatives for all arguments in canonical form
[bd4f2e9]520                        std::vector< AlternativeFinder > argAlternatives;
[1dcd9554]521                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
522
523                        // List all combinations of arguments
[bd4f2e9]524                        std::vector< AltList > possibilities;
[1dcd9554]525                        combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
526
527                        AltList                func_candidates;
528                        std::vector< AltList > args_candidates;
529
530                        // For every possible function :
531                        //      try matching the arguments to the parameters
532                        //      not the other way around because we have more arguments than parameters
[a16764a6]533                        SemanticErrorException errors;
[1dcd9554]534                        for ( Alternative & func : funcFinder.get_alternatives() ) {
535                                try {
536                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
537                                        if( !pointer ) {
[a16764a6]538                                                SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
[1dcd9554]539                                        }
540
541                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
542                                        if( !function ) {
[a16764a6]543                                                SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
[1dcd9554]544                                        }
545
546
547                                        {
548                                                auto param     = function->parameters.begin();
549                                                auto param_end = function->parameters.end();
550
551                                                if( !advance_to_mutex( param, param_end ) ) {
[a16764a6]552                                                        SemanticError(function, "candidate function not viable: no mutex parameters\n");
[1dcd9554]553                                                }
554                                        }
555
556                                        Alternative newFunc( func );
557                                        // Strip reference from function
[a181494]558                                        referenceToRvalueConversion( newFunc.expr, newFunc.cost );
[1dcd9554]559
560                                        // For all the set of arguments we have try to match it with the parameter of the current function alternative
561                                        for ( auto & argsList : possibilities ) {
562
563                                                try {
564                                                        // Declare data structures need for resolution
565                                                        OpenVarSet openVars;
566                                                        AssertionSet resultNeed, resultHave;
[6f326b1]567                                                        TypeEnvironment resultEnv( func.env );
568                                                        makeUnifiableVars( function, openVars, resultNeed );
569                                                        // add all type variables as open variables now so that those not used in the parameter
570                                                        // list are still considered open.
571                                                        resultEnv.add( function->forall );
[1dcd9554]572
573                                                        // Load type variables from arguemnts into one shared space
574                                                        simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
575
576                                                        // Make sure we don't widen any existing bindings
577                                                        for ( auto & i : resultEnv ) {
578                                                                i.allowWidening = false;
579                                                        }
580
581                                                        // Find any unbound type variables
582                                                        resultEnv.extractOpenVars( openVars );
583
584                                                        auto param     = function->parameters.begin();
585                                                        auto param_end = function->parameters.end();
586
[b9f383f]587                                                        int n_mutex_arg = 0;
588
[1dcd9554]589                                                        // For every arguments of its set, check if it matches one of the parameter
590                                                        // The order is important
591                                                        for( auto & arg : argsList ) {
592
593                                                                // Ignore non-mutex arguments
594                                                                if( !advance_to_mutex( param, param_end ) ) {
595                                                                        // We ran out of parameters but still have arguments
596                                                                        // this function doesn't match
[b9f383f]597                                                                        SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_arg, "\n" ));
[1dcd9554]598                                                                }
599
[b9f383f]600                                                                n_mutex_arg++;
601
[1dcd9554]602                                                                // Check if the argument matches the parameter type in the current scope
[b9f383f]603                                                                if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
[1dcd9554]604                                                                        // Type doesn't match
605                                                                        stringstream ss;
606                                                                        ss << "candidate function not viable: no known convertion from '";
607                                                                        (*param)->get_type()->print( ss );
[b9f383f]608                                                                        ss << "' to '";
609                                                                        arg.expr->get_result()->print( ss );
[5248789]610                                                                        ss << "' with env '";
611                                                                        resultEnv.print(ss);
[1dcd9554]612                                                                        ss << "'\n";
[a16764a6]613                                                                        SemanticError( function, ss.str() );
[1dcd9554]614                                                                }
615
616                                                                param++;
617                                                        }
618
619                                                        // All arguments match !
620
621                                                        // Check if parameters are missing
622                                                        if( advance_to_mutex( param, param_end ) ) {
623                                                                // We ran out of arguments but still have parameters left
624                                                                // this function doesn't match
[b9f383f]625                                                                SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_arg, "\n" ));
[1dcd9554]626                                                        }
627
628                                                        // All parameters match !
629
630                                                        // Finish the expressions to tie in the proper environments
631                                                        finishExpr( newFunc.expr, resultEnv );
632                                                        for( Alternative & alt : argsList ) {
633                                                                finishExpr( alt.expr, resultEnv );
634                                                        }
635
636                                                        // This is a match store it and save it for later
637                                                        func_candidates.push_back( newFunc );
638                                                        args_candidates.push_back( argsList );
639
640                                                }
[a16764a6]641                                                catch( SemanticErrorException &e ) {
[1dcd9554]642                                                        errors.append( e );
643                                                }
644                                        }
645                                }
[a16764a6]646                                catch( SemanticErrorException &e ) {
[1dcd9554]647                                        errors.append( e );
648                                }
649                        }
650
651                        // Make sure we got the right number of arguments
[a16764a6]652                        if( func_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
653                        if( args_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
654                        if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
655                        if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
[c71b256]656                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
[1dcd9554]657
658                        // Swap the results from the alternative with the unresolved values.
659                        // Alternatives will handle deletion on destruction
660                        std::swap( clause.target.function, func_candidates.front().expr );
661                        for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
662                                std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
663                        }
664
665                        // Resolve the conditions as if it were an IfStmt
666                        // Resolve the statments normally
[08da53d]667                        findSingleExpression( clause.condition, this->indexer );
[8f98b78]668                        clause.statement->accept( *visitor );
[1dcd9554]669                }
670
671
672                if( stmt->timeout.statement ) {
673                        // Resolve the timeout as an size_t for now
674                        // Resolve the conditions as if it were an IfStmt
675                        // Resolve the statments normally
[08da53d]676                        findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
677                        findSingleExpression( stmt->timeout.condition, this->indexer );
[8f98b78]678                        stmt->timeout.statement->accept( *visitor );
[1dcd9554]679                }
680
681                if( stmt->orelse.statement ) {
682                        // Resolve the conditions as if it were an IfStmt
683                        // Resolve the statments normally
[08da53d]684                        findSingleExpression( stmt->orelse.condition, this->indexer );
[8f98b78]685                        stmt->orelse.statement->accept( *visitor );
[1dcd9554]686                }
687        }
688
[c71b256]689        bool isStructOrUnion( const Alternative & alt ) {
690                Type * t = alt.expr->result->stripReferences();
[882ad37]691                return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
692        }
693
[c28a038d]694        void Resolver::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
695                for ( Expression *& expr : withExprs )  {
[882ad37]696                        // only struct- and union-typed expressions are viable candidates
[8587878e]697                        findKindExpression( expr, indexer, "with statement", isStructOrUnion );
[0a60c04]698
699                        // if with expression might be impure, create a temporary so that it is evaluated once
700                        if ( Tuples::maybeImpure( expr ) ) {
701                                static UniqueName tmpNamer( "_with_tmp_" );
702                                ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
703                                expr = new VariableExpr( tmp );
[c28a038d]704                                newStmts.push_back( new DeclStmt( tmp ) );
[0a60c04]705                                if ( InitTweak::isConstructable( tmp->type ) ) {
706                                        // generate ctor/dtor and resolve them
707                                        tmp->init = InitTweak::genCtorInit( tmp );
708                                        tmp->accept( *visitor );
709                                }
710                        }
[882ad37]711                }
712        }
713
[c28a038d]714        void Resolver::previsit( WithStmt * withStmt ) {
715                resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
716        }
717
[b5c5684]718        template< typename T >
719        bool isCharType( T t ) {
720                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
[71f4e4f]721                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
[b5c5684]722                                bt->get_kind() == BasicType::UnsignedChar;
723                }
724                return false;
725        }
726
[a4ca48c]727        void Resolver::previsit( SingleInit *singleInit ) {
728                visit_children = false;
[62423350]729                // resolve initialization using the possibilities as determined by the currentObject cursor
[0a22cda]730                Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
[08da53d]731                findSingleExpression( newExpr, indexer );
[e3e16bc]732                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
[62423350]733
734                // move cursor to the object that is actually initialized
[e4d829b]735                currentObject.setNext( initExpr->get_designation() );
[62423350]736
737                // discard InitExpr wrapper and retain relevant pieces
[08da53d]738                newExpr = initExpr->expr;
739                initExpr->expr = nullptr;
740                std::swap( initExpr->env, newExpr->env );
[cdb990a]741                // InitExpr may have inferParams in the case where the expression specializes a function pointer,
742                // and newExpr may already have inferParams of its own, so a simple swap is not sufficient.
743                newExpr->spliceInferParams( initExpr );
[e4d829b]744
[62423350]745                // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
746                Type * initContext = currentObject.getCurrentType();
747
[0a22cda]748                removeExtraneousCast( newExpr, indexer );
749
[62423350]750                // check if actual object's type is char[]
751                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
752                        if ( isCharType( at->get_base() ) ) {
753                                // check if the resolved type is char *
754                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
755                                        if ( isCharType( pt->get_base() ) ) {
[0a22cda]756                                                if ( CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ) ) {
757                                                        // strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
758                                                        newExpr = ce->get_arg();
759                                                        ce->set_arg( nullptr );
760                                                        std::swap( ce->env, newExpr->env );
761                                                }
[62423350]762                                        }
763                                }
764                        }
765                }
[94b4364]766
[62423350]767                // set initializer expr to resolved express
[0a22cda]768                singleInit->value = newExpr;
[62423350]769
770                // move cursor to next object in preparation for next initializer
771                currentObject.increment();
772        }
[94b4364]773
[a4ca48c]774        void Resolver::previsit( ListInit * listInit ) {
775                visit_children = false;
[62423350]776                // move cursor into brace-enclosed initializer-list
[e4d829b]777                currentObject.enterListInit();
778                // xxx - fix this so that the list isn't copied, iterator should be used to change current element
779                std::list<Designation *> newDesignations;
780                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
[62423350]781                        // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
782                        // the initializer against that object.
[e4d829b]783                        Designation * des = std::get<0>(p);
784                        Initializer * init = std::get<1>(p);
785                        newDesignations.push_back( currentObject.findNext( des ) );
[a4ca48c]786                        init->accept( *visitor );
[b5c5684]787                }
[62423350]788                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
[e4d829b]789                listInit->get_designations() = newDesignations; // xxx - memory management
790                currentObject.exitListInit();
791
[62423350]792                // xxx - this part has not be folded into CurrentObject yet
[e4d829b]793                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
794                //      Type * base = tt->get_baseType()->get_base();
795                //      if ( base ) {
796                //              // know the implementation type, so try using that as the initContext
797                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
798                //              currentObject = &tmpObj;
799                //              visit( listInit );
800                //      } else {
801                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
802                //              Parent::visit( listInit );
803                //      }
804                // } else {
[a32b204]805        }
[71f4e4f]806
[f1e012b]807        // ConstructorInit - fall back on C-style initializer
808        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
809                // could not find valid constructor, or found an intrinsic constructor
810                // fall back on C-style initializer
[68f9c43]811                ctorInit->set_ctor( nullptr );
812                ctorInit->set_dtor( nullptr );
[a4ca48c]813                maybeAccept( ctorInit->get_init(), *visitor );
[f1e012b]814        }
815
[1d2b64f]816        // needs to be callable from outside the resolver, so this is a standalone function
817        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
818                assert( ctorInit );
[a4ca48c]819                PassVisitor<Resolver> resolver( indexer );
[1d2b64f]820                ctorInit->accept( resolver );
821        }
822
823        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
824                assert( stmtExpr );
[a4ca48c]825                PassVisitor<Resolver> resolver( indexer );
[1d2b64f]826                stmtExpr->accept( resolver );
[5e2c348]827                stmtExpr->computeResult();
[dd05e12]828                // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
[1d2b64f]829        }
830
[a4ca48c]831        void Resolver::previsit( ConstructorInit *ctorInit ) {
832                visit_children = false;
[1ba88a0]833                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
[dd05e12]834                maybeAccept( ctorInit->ctor, *visitor );
835                maybeAccept( ctorInit->dtor, *visitor );
[071a31a]836
[5b2f5bb]837                // found a constructor - can get rid of C-style initializer
[dd05e12]838                ctorInit->init = nullptr;
[ec79847]839
840                // intrinsic single parameter constructors and destructors do nothing. Since this was
841                // implicitly generated, there's no way for it to have side effects, so get rid of it
842                // to clean up generated code.
[dd05e12]843                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
844                        ctorInit->ctor = nullptr;
[ec79847]845                }
[f9cebb5]846
[dd05e12]847                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
848                        ctorInit->dtor = nullptr;
[ec79847]849                }
[a465caf]850
851                // xxx - todo -- what about arrays?
852                // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
853                //      // can reduce the constructor down to a SingleInit using the
854                //      // second argument from the ctor call, since
855                //      delete ctorInit->get_ctor();
856                //      ctorInit->set_ctor( NULL );
857
858                //      Expression * arg =
859                //      ctorInit->set_init( new SingleInit( arg ) );
860                // }
[71f4e4f]861        }
[51b7345]862} // namespace ResolvExpr
[a32b204]863
864// Local Variables: //
865// tab-width: 4 //
866// mode: c++ //
867// compile-command: "make install" //
868// End: //
Note: See TracBrowser for help on using the repository browser.