source: src/ResolvExpr/Resolver.cc @ 0a60c04

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

Introduce a temporary for with expressions that may contain side-effects and evaluate the expression once

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