source: src/ResolvExpr/Resolver.cc @ 36a2367

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 36a2367 was ad51cc2, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Convert RenameVars? to PassVisitor?

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