source: src/ResolvExpr/Resolver.cc @ c3d048c

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

Fix polymorphic-to-monomorphic function specialization for casts and initializers [fixes #27]

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