source: src/ResolvExpr/Resolver.cc @ 57e0289

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 57e0289 was 57e0289, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Added stats option to print stats per expression in new-ast resolution

  • Property mode set to 100644
File size: 68.1 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//
[d76c588]9// Author           : Aaron B. Moss
[a32b204]10// Created On       : Sun May 17 12:17:01 2015
[3090127]11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Mar 27 11:58:00 2020
13// Update Count     : 242
[a32b204]14//
15
[e3e16bc]16#include <cassert>                       // for strict_dynamic_cast, assert
[ea6332d]17#include <memory>                        // for allocator, allocator_traits<...
18#include <tuple>                         // for get
[6d6e829]19#include <vector>                        // for vector
[ea6332d]20
21#include "Alternative.h"                 // for Alternative, AltList
22#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
[99d4584]23#include "Candidate.hpp"
24#include "CandidateFinder.hpp"
[d76c588]25#include "CurrentObject.h"               // for CurrentObject
26#include "RenameVars.h"                  // for RenameVars, global_renamer
27#include "Resolver.h"
28#include "ResolvMode.h"                  // for ResolvMode
29#include "typeops.h"                     // for extractResultType
30#include "Unify.h"                       // for unify
[4864a73]31#include "AST/Chain.hpp"
[2a8f0c1]32#include "AST/Decl.hpp"
33#include "AST/Init.hpp"
[d76c588]34#include "AST/Pass.hpp"
[99d4584]35#include "AST/Print.hpp"
[d76c588]36#include "AST/SymbolTable.hpp"
[2773ab8]37#include "AST/Type.hpp"
[a4ca48c]38#include "Common/PassVisitor.h"          // for PassVisitor
[ea6332d]39#include "Common/SemanticError.h"        // for SemanticError
[57e0289]40#include "Common/Stats/ResolveTime.h"    // for ResolveTime::start(), ResolveTime::stop()
[ea6332d]41#include "Common/utility.h"              // for ValueGuard, group_iterate
[0a60c04]42#include "InitTweak/GenInit.h"
[ea6332d]43#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
44#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
45#include "SymTab/Autogen.h"              // for SizeType
46#include "SymTab/Indexer.h"              // for Indexer
47#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
48#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
49#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
50#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
51#include "SynTree/Type.h"                // for Type, BasicType, PointerType
52#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
53#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
[0a60c04]54#include "Tuples/Tuples.h"
[2bfc6b2]55#include "Validate/FindSpecialDecls.h"   // for SizeType
[51b7345]56
[d9a0e76]57using namespace std;
[51b7345]58
[d9a0e76]59namespace ResolvExpr {
[d76c588]60        struct Resolver_old final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver_old>, public WithShortCircuiting, public WithStmtsToAdd {
61                Resolver_old() {}
62                Resolver_old( const SymTab::Indexer & other ) {
[a4ca48c]63                        indexer = other;
[1d2b64f]64                }
[71f4e4f]65
[5170d95]66                void previsit( FunctionDecl * functionDecl );
67                void postvisit( FunctionDecl * functionDecl );
68                void previsit( ObjectDecl * objectDecll );
[a4ca48c]69                void previsit( EnumDecl * enumDecl );
[bd87b138]70                void previsit( StaticAssertDecl * assertDecl );
[a4ca48c]71
72                void previsit( ArrayType * at );
73                void previsit( PointerType * at );
74
[5170d95]75                void previsit( ExprStmt * exprStmt );
76                void previsit( AsmExpr * asmExpr );
77                void previsit( AsmStmt * asmStmt );
78                void previsit( IfStmt * ifStmt );
79                void previsit( WhileStmt * whileStmt );
80                void previsit( ForStmt * forStmt );
81                void previsit( SwitchStmt * switchStmt );
82                void previsit( CaseStmt * caseStmt );
83                void previsit( BranchStmt * branchStmt );
84                void previsit( ReturnStmt * returnStmt );
85                void previsit( ThrowStmt * throwStmt );
86                void previsit( CatchStmt * catchStmt );
[3b9c674]87                void postvisit( CatchStmt * catchStmt );
[695e00d]88                void previsit( WaitForStmt * stmt );
[a4ca48c]89
[5170d95]90                void previsit( SingleInit * singleInit );
91                void previsit( ListInit * listInit );
92                void previsit( ConstructorInit * ctorInit );
[a32b204]93          private:
[c28a038d]94                typedef std::list< Initializer * >::iterator InitIterator;
[94b4364]95
[40e636a]96                template< typename PtrType >
97                void handlePtrType( PtrType * type );
98
[c28a038d]99                void fallbackInit( ConstructorInit * ctorInit );
[b726084]100
[77971f6]101                Type * functionReturn = nullptr;
[e4d829b]102                CurrentObject currentObject = nullptr;
[a436947]103                bool inEnumDecl = false;
[a32b204]104        };
[d9a0e76]105
[2a6292d]106        struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd {
107                void previsit( FunctionDecl * );
108                void previsit( WithStmt * );
109
110                void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
111        };
112
[a32b204]113        void resolve( std::list< Declaration * > translationUnit ) {
[d76c588]114                PassVisitor<Resolver_old> resolver;
[a32b204]115                acceptAll( translationUnit, resolver );
[d9a0e76]116        }
117
[5170d95]118        void resolveDecl( Declaration * decl, const SymTab::Indexer & indexer ) {
[d76c588]119                PassVisitor<Resolver_old> resolver( indexer );
[8b11840]120                maybeAccept( decl, resolver );
121        }
122
[c71b256]123        namespace {
[99d4584]124                struct DeleteFinder_old : public WithShortCircuiting    {
[c71b256]125                        DeletedExpr * delExpr = nullptr;
126                        void previsit( DeletedExpr * expr ) {
127                                if ( delExpr ) visit_children = false;
128                                else delExpr = expr;
129                        }
130
131                        void previsit( Expression * ) {
132                                if ( delExpr ) visit_children = false;
133                        }
134                };
135        }
136
137        DeletedExpr * findDeletedExpr( Expression * expr ) {
[99d4584]138                PassVisitor<DeleteFinder_old> finder;
[c71b256]139                expr->accept( finder );
140                return finder.pass.delExpr;
[d9a0e76]141        }
[a32b204]142
143        namespace {
[99d4584]144                struct StripCasts_old {
[cdb990a]145                        Expression * postmutate( CastExpr * castExpr ) {
146                                if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
147                                        // generated cast is to the same type as its argument, so it's unnecessary -- remove it
148                                        Expression * expr = castExpr->arg;
149                                        castExpr->arg = nullptr;
150                                        std::swap( expr->env, castExpr->env );
151                                        return expr;
152                                }
153                                return castExpr;
154                        }
155
156                        static void strip( Expression *& expr ) {
[99d4584]157                                PassVisitor<StripCasts_old> stripper;
[cdb990a]158                                expr = expr->acceptMutator( stripper );
159                        }
160                };
161
[5170d95]162                void finishExpr( Expression *& expr, const TypeEnvironment & env, TypeSubstitution * oldenv = nullptr ) {
[7664fad]163                        expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
[cdb990a]164                        env.makeSubstitution( *expr->env );
[99d4584]165                        StripCasts_old::strip( expr ); // remove unnecessary casts that may be buried in an expression
[a32b204]166                }
[0a22cda]167
168                void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
169                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
[b7d92b96]170                                if ( typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
[0a22cda]171                                        // cast is to the same type as its argument, so it's unnecessary -- remove it
172                                        expr = castExpr->arg;
173                                        castExpr->arg = nullptr;
174                                        std::swap( expr->env, castExpr->env );
175                                        delete castExpr;
176                                }
177                        }
178                }
[db4ecc5]179        } // namespace
[a32b204]180
[8f98b78]181        namespace {
[59cf83b]182                void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
[c71b256]183                        assertf( untyped, "expected a non-null expression." );
[6d6e829]184
185                        // xxx - this isn't thread-safe, but should work until we parallelize the resolver
186                        static unsigned recursion_level = 0;
187
188                        ++recursion_level;
[8587878e]189                        TypeEnvironment env;
190                        AlternativeFinder finder( indexer, env );
[6d6e829]191                        finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
192                        --recursion_level;
[c71b256]193
194                        #if 0
195                        if ( finder.get_alternatives().size() != 1 ) {
196                                std::cerr << "untyped expr is ";
197                                untyped->print( std::cerr );
198                                std::cerr << std::endl << "alternatives are:";
199                                for ( const Alternative & alt : finder.get_alternatives() ) {
200                                        alt.print( std::cerr );
201                                } // for
202                        } // if
203                        #endif
[8587878e]204
[6d6e829]205                        // produce filtered list of alternatives
[8587878e]206                        AltList candidates;
207                        for ( Alternative & alt : finder.get_alternatives() ) {
[c71b256]208                                if ( pred( alt ) ) {
[8587878e]209                                        candidates.push_back( std::move( alt ) );
210                                }
211                        }
212
[6d6e829]213                        // produce invalid error if no candidates
214                        if ( candidates.empty() ) {
[a16764a6]215                                SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
[6d6e829]216                        }
217
218                        // search for cheapest candidate
219                        AltList winners;
220                        bool seen_undeleted = false;
221                        for ( unsigned i = 0; i < candidates.size(); ++i ) {
222                                int c = winners.empty() ? -1 : candidates[i].cost.compare( winners.front().cost );
223
224                                if ( c > 0 ) continue; // skip more expensive than winner
225
226                                if ( c < 0 ) {
227                                        // reset on new cheapest
228                                        seen_undeleted = ! findDeletedExpr( candidates[i].expr );
229                                        winners.clear();
230                                } else /* if ( c == 0 ) */ {
231                                        if ( findDeletedExpr( candidates[i].expr ) ) {
232                                                // skip deleted expression if already seen one equivalent-cost not
233                                                if ( seen_undeleted ) continue;
234                                        } else if ( ! seen_undeleted ) {
235                                                // replace list of equivalent-cost deleted expressions with one non-deleted
236                                                winners.clear();
237                                                seen_undeleted = true;
238                                        }
239                                }
240
[2fd9f24]241                                winners.emplace_back( std::move( candidates[i] ) );
[6d6e829]242                        }
243
244                        // promote alternative.cvtCost to .cost
245                        // xxx - I don't know why this is done, but I'm keeping the behaviour from findMinCost
246                        for ( Alternative& winner : winners ) {
247                                winner.cost = winner.cvtCost;
248                        }
[cde3891]249
[6d6e829]250                        // produce ambiguous errors, if applicable
251                        if ( winners.size() != 1 ) {
[8587878e]252                                std::ostringstream stream;
[c71b256]253                                stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
[8587878e]254                                untyped->print( stream );
[93401f8]255                                stream << " Alternatives are:\n";
[8587878e]256                                printAlts( winners, stream, 1 );
[a16764a6]257                                SemanticError( untyped->location, stream.str() );
[8587878e]258                        }
259
[6d6e829]260                        // single selected choice
261                        Alternative& choice = winners.front();
262
263                        // fail on only expression deleted
264                        if ( ! seen_undeleted ) {
[2a08c25]265                                SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
[c71b256]266                        }
[6d6e829]267
268                        // xxx - check for ambiguous expressions
[cde3891]269
[6d6e829]270                        // output selected choice
[c71b256]271                        alt = std::move( choice );
272                }
273
274                /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
[59cf83b]275                void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
[c71b256]276                        if ( ! untyped ) return;
277                        Alternative choice;
[59cf83b]278                        findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
[c71b256]279                        finishExpr( choice.expr, choice.env, untyped->env );
[8587878e]280                        delete untyped;
[c71b256]281                        untyped = choice.expr;
282                        choice.expr = nullptr;
[8587878e]283                }
284
[c71b256]285                bool standardAlternativeFilter( const Alternative & ) {
286                        // currently don't need to filter, under normal circumstances.
287                        // in the future, this may be useful for removing deleted expressions
288                        return true;
289                }
290        } // namespace
291
292        // used in resolveTypeof
[5170d95]293        Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer ) {
[c71b256]294                TypeEnvironment env;
295                return resolveInVoidContext( expr, indexer, env );
296        }
297
[5170d95]298        Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer, TypeEnvironment & env ) {
[c71b256]299                // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
300                // interpretations, an exception has already been thrown.
301                assertf( expr, "expected a non-null expression." );
302
[5170d95]303                CastExpr * untyped = new CastExpr( expr ); // cast to void
304                untyped->location = expr->location;
[c71b256]305
306                // set up and resolve expression cast to void
307                Alternative choice;
[5170d95]308                findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
[c71b256]309                CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
[5170d95]310                assert( castExpr );
[c71b256]311                env = std::move( choice.env );
312
313                // clean up resolved expression
314                Expression * ret = castExpr->arg;
315                castExpr->arg = nullptr;
316
317                // unlink the arg so that it isn't deleted twice at the end of the program
[5170d95]318                untyped->arg = nullptr;
[c71b256]319                return ret;
320        }
321
[5170d95]322        void findVoidExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
[c71b256]323                resetTyVarRenaming();
324                TypeEnvironment env;
325                Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
326                finishExpr( newExpr, env, untyped->env );
327                delete untyped;
328                untyped = newExpr;
329        }
330
[5170d95]331        void findSingleExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
[c71b256]332                findKindExpression( untyped, indexer, "", standardAlternativeFilter );
333        }
334
335        void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
336                assert( untyped && type );
[2a08c25]337                // transfer location to generated cast for error purposes
338                CodeLocation location = untyped->location;
[c71b256]339                untyped = new CastExpr( untyped, type );
[2a08c25]340                untyped->location = location;
[c71b256]341                findSingleExpression( untyped, indexer );
342                removeExtraneousCast( untyped, indexer );
343        }
344
345        namespace {
346                bool isIntegralType( const Alternative & alt ) {
347                        Type * type = alt.expr->result;
[a32b204]348                        if ( dynamic_cast< EnumInstType * >( type ) ) {
349                                return true;
[5170d95]350                        } else if ( BasicType * bt = dynamic_cast< BasicType * >( type ) ) {
[a32b204]351                                return bt->isInteger();
[89e6ffc]352                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
353                                return true;
[a32b204]354                        } else {
355                                return false;
356                        } // if
357                }
[71f4e4f]358
[5170d95]359                void findIntegralExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
[8587878e]360                        findKindExpression( untyped, indexer, "condition", isIntegralType );
[a32b204]361                }
362        }
[71f4e4f]363
[2a6292d]364
365        bool isStructOrUnion( const Alternative & alt ) {
366                Type * t = alt.expr->result->stripReferences();
367                return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
368        }
369
370        void resolveWithExprs( std::list< Declaration * > & translationUnit ) {
371                PassVisitor<ResolveWithExprs> resolver;
372                acceptAll( translationUnit, resolver );
373        }
374
375        void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
376                for ( Expression *& expr : withExprs )  {
377                        // only struct- and union-typed expressions are viable candidates
378                        findKindExpression( expr, indexer, "with statement", isStructOrUnion );
379
380                        // if with expression might be impure, create a temporary so that it is evaluated once
381                        if ( Tuples::maybeImpure( expr ) ) {
382                                static UniqueName tmpNamer( "_with_tmp_" );
383                                ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
384                                expr = new VariableExpr( tmp );
385                                newStmts.push_back( new DeclStmt( tmp ) );
386                                if ( InitTweak::isConstructable( tmp->type ) ) {
387                                        // generate ctor/dtor and resolve them
388                                        tmp->init = InitTweak::genCtorInit( tmp );
389                                        tmp->accept( *visitor );
390                                }
391                        }
392                }
393        }
394
395        void ResolveWithExprs::previsit( WithStmt * withStmt ) {
396                resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
397        }
398
399        void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) {
400                {
401                        // resolve with-exprs with parameters in scope and add any newly generated declarations to the
402                        // front of the function body.
403                        auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
404                        indexer.addFunctionType( functionDecl->type );
405                        std::list< Statement * > newStmts;
406                        resolveWithExprs( functionDecl->withExprs, newStmts );
407                        if ( functionDecl->statements ) {
408                                functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
409                        } else {
410                                assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
411                        }
412                }
413        }
414
[d76c588]415        void Resolver_old::previsit( ObjectDecl * objectDecl ) {
[4864a73]416                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that
417                // class-variable initContext is changed multiple time because the LHS is analysed twice.
418                // The second analysis changes initContext because of a function type can contain object
419                // declarations in the return and parameter types. So each value of initContext is
[6d6e829]420                // retained, so the type on the first analysis is preserved and used for selecting the RHS.
[a4ca48c]421                GuardValue( currentObject );
[e4d829b]422                currentObject = CurrentObject( objectDecl->get_type() );
423                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
[a436947]424                        // enumerator initializers should not use the enum type to initialize, since
425                        // the enum type is still incomplete at this point. Use signed int instead.
[e4d829b]426                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
[a436947]427                }
[bfbf97f]428        }
429
[40e636a]430        template< typename PtrType >
[d76c588]431        void Resolver_old::handlePtrType( PtrType * type ) {
[40e636a]432                if ( type->get_dimension() ) {
[2bfc6b2]433                        findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
[d1d17f5]434                }
[40e636a]435        }
436
[d76c588]437        void Resolver_old::previsit( ArrayType * at ) {
[40e636a]438                handlePtrType( at );
[a32b204]439        }
[94b4364]440
[d76c588]441        void Resolver_old::previsit( PointerType * pt ) {
[40e636a]442                handlePtrType( pt );
443        }
444
[d76c588]445        void Resolver_old::previsit( FunctionDecl * functionDecl ) {
[d9a0e76]446#if 0
[a4ca48c]447                std::cerr << "resolver visiting functiondecl ";
448                functionDecl->print( std::cerr );
449                std::cerr << std::endl;
[d9a0e76]450#endif
[a4ca48c]451                GuardValue( functionReturn );
[60914351]452                functionReturn = ResolvExpr::extractResultType( functionDecl->type );
[a4ca48c]453        }
[88d1066]454
[d76c588]455        void Resolver_old::postvisit( FunctionDecl * functionDecl ) {
[4864a73]456                // default value expressions have an environment which shouldn't be there and trips up
[6d6e829]457                // later passes.
[cde3891]458                // xxx - it might be necessary to somehow keep the information from this environment, but I
[6d6e829]459                // can't currently see how it's useful.
[c28a038d]460                for ( Declaration * d : functionDecl->type->parameters ) {
[88d1066]461                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
[c28a038d]462                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
463                                        delete init->value->env;
464                                        init->value->env = nullptr;
[88d1066]465                                }
466                        }
467                }
[a32b204]468        }
[51b7345]469
[d76c588]470        void Resolver_old::previsit( EnumDecl * ) {
[a436947]471                // in case we decide to allow nested enums
[a4ca48c]472                GuardValue( inEnumDecl );
[a436947]473                inEnumDecl = true;
474        }
475
[d76c588]476        void Resolver_old::previsit( StaticAssertDecl * assertDecl ) {
[bd87b138]477                findIntegralExpression( assertDecl->condition, indexer );
478        }
479
[d76c588]480        void Resolver_old::previsit( ExprStmt * exprStmt ) {
[a4ca48c]481                visit_children = false;
[08da53d]482                assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
483                findVoidExpression( exprStmt->expr, indexer );
[a32b204]484        }
[51b7345]485
[d76c588]486        void Resolver_old::previsit( AsmExpr * asmExpr ) {
[a4ca48c]487                visit_children = false;
[08da53d]488                findVoidExpression( asmExpr->operand, indexer );
[7f5566b]489        }
490
[d76c588]491        void Resolver_old::previsit( AsmStmt * asmStmt ) {
[a4ca48c]492                visit_children = false;
493                acceptAll( asmStmt->get_input(), *visitor );
494                acceptAll( asmStmt->get_output(), *visitor );
[7f5566b]495        }
496
[d76c588]497        void Resolver_old::previsit( IfStmt * ifStmt ) {
[8587878e]498                findIntegralExpression( ifStmt->condition, indexer );
[a32b204]499        }
[51b7345]500
[d76c588]501        void Resolver_old::previsit( WhileStmt * whileStmt ) {
[8587878e]502                findIntegralExpression( whileStmt->condition, indexer );
[a32b204]503        }
[51b7345]504
[d76c588]505        void Resolver_old::previsit( ForStmt * forStmt ) {
[08da53d]506                if ( forStmt->condition ) {
[8587878e]507                        findIntegralExpression( forStmt->condition, indexer );
[a32b204]508                } // if
[71f4e4f]509
[08da53d]510                if ( forStmt->increment ) {
511                        findVoidExpression( forStmt->increment, indexer );
[a32b204]512                } // if
513        }
[51b7345]514
[d76c588]515        void Resolver_old::previsit( SwitchStmt * switchStmt ) {
[a4ca48c]516                GuardValue( currentObject );
[08da53d]517                findIntegralExpression( switchStmt->condition, indexer );
[71f4e4f]518
[08da53d]519                currentObject = CurrentObject( switchStmt->condition->result );
[a32b204]520        }
[51b7345]521
[d76c588]522        void Resolver_old::previsit( CaseStmt * caseStmt ) {
[cdb990a]523                if ( caseStmt->condition ) {
[e4d829b]524                        std::list< InitAlternative > initAlts = currentObject.getOptions();
525                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
[08da53d]526                        // must remove cast from case statement because RangeExpr cannot be cast.
527                        Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
528                        findSingleExpression( newExpr, indexer );
[cdb990a]529                        // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
530                        // Ideally we would perform the conversion internally here.
531                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
532                                newExpr = castExpr->arg;
533                                castExpr->arg = nullptr;
534                                std::swap( newExpr->env, castExpr->env );
535                                delete castExpr;
536                        }
537                        caseStmt->condition = newExpr;
[32b8144]538                }
[a32b204]539        }
[51b7345]540
[d76c588]541        void Resolver_old::previsit( BranchStmt * branchStmt ) {
[a4ca48c]542                visit_children = false;
[de62360d]543                // must resolve the argument for a computed goto
544                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
[08da53d]545                        if ( branchStmt->computedTarget ) {
546                                // computed goto argument is void *
547                                findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
[de62360d]548                        } // if
549                } // if
550        }
551
[d76c588]552        void Resolver_old::previsit( ReturnStmt * returnStmt ) {
[a4ca48c]553                visit_children = false;
[08da53d]554                if ( returnStmt->expr ) {
555                        findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
[a32b204]556                } // if
557        }
[51b7345]558
[d76c588]559        void Resolver_old::previsit( ThrowStmt * throwStmt ) {
[a4ca48c]560                visit_children = false;
[cbce272]561                // TODO: Replace *exception type with &exception type.
[307a732]562                if ( throwStmt->get_expr() ) {
[3090127]563                        const StructDecl * exception_decl = indexer.lookupStruct( "__cfaehm_base_exception_t" );
[cbce272]564                        assert( exception_decl );
[8fd52e90]565                        Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, const_cast<StructDecl *>(exception_decl) ) );
[08da53d]566                        findSingleExpression( throwStmt->expr, exceptType, indexer );
[307a732]567                }
568        }
569
[d76c588]570        void Resolver_old::previsit( CatchStmt * catchStmt ) {
[3b9c674]571                // Until we are very sure this invarent (ifs that move between passes have thenPart)
572                // holds, check it. This allows a check for when to decode the mangling.
573                if ( IfStmt * ifStmt = dynamic_cast<IfStmt *>( catchStmt->body ) ) {
574                        assert( ifStmt->thenPart );
575                }
576                // Encode the catchStmt so the condition can see the declaration.
[08da53d]577                if ( catchStmt->cond ) {
[3b9c674]578                        IfStmt * ifStmt = new IfStmt( catchStmt->cond, nullptr, catchStmt->body );
579                        catchStmt->cond = nullptr;
580                        catchStmt->body = ifStmt;
581                }
582        }
583
584        void Resolver_old::postvisit( CatchStmt * catchStmt ) {
585                // Decode the catchStmt so everything is stored properly.
586                IfStmt * ifStmt = dynamic_cast<IfStmt *>( catchStmt->body );
587                if ( nullptr != ifStmt && nullptr == ifStmt->thenPart ) {
588                        assert( ifStmt->condition );
589                        assert( ifStmt->elsePart );
590                        catchStmt->cond = ifStmt->condition;
591                        catchStmt->body = ifStmt->elsePart;
592                        ifStmt->condition = nullptr;
593                        ifStmt->elsePart = nullptr;
594                        delete ifStmt;
[cbce272]595                }
596        }
597
[1dcd9554]598        template< typename iterator_t >
599        inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
600                while( it != end && !(*it)->get_type()->get_mutex() ) {
601                        it++;
602                }
603
604                return it != end;
605        }
606
[d76c588]607        void Resolver_old::previsit( WaitForStmt * stmt ) {
[8f98b78]608                visit_children = false;
[1dcd9554]609
610                // Resolve all clauses first
611                for( auto& clause : stmt->clauses ) {
612
613                        TypeEnvironment env;
[8f98b78]614                        AlternativeFinder funcFinder( indexer, env );
[1dcd9554]615
616                        // Find all alternatives for a function in canonical form
617                        funcFinder.findWithAdjustment( clause.target.function );
618
619                        if ( funcFinder.get_alternatives().empty() ) {
620                                stringstream ss;
621                                ss << "Use of undeclared indentifier '";
622                                ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
623                                ss << "' in call to waitfor";
[a16764a6]624                                SemanticError( stmt->location, ss.str() );
[1dcd9554]625                        }
626
[b9f383f]627                        if(clause.target.arguments.empty()) {
628                                SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
629                        }
630
[1dcd9554]631                        // Find all alternatives for all arguments in canonical form
[bd4f2e9]632                        std::vector< AlternativeFinder > argAlternatives;
[1dcd9554]633                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
634
635                        // List all combinations of arguments
[bd4f2e9]636                        std::vector< AltList > possibilities;
[1dcd9554]637                        combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
638
639                        AltList                func_candidates;
640                        std::vector< AltList > args_candidates;
641
642                        // For every possible function :
643                        //      try matching the arguments to the parameters
644                        //      not the other way around because we have more arguments than parameters
[a16764a6]645                        SemanticErrorException errors;
[1dcd9554]646                        for ( Alternative & func : funcFinder.get_alternatives() ) {
647                                try {
648                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
649                                        if( !pointer ) {
[a16764a6]650                                                SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
[1dcd9554]651                                        }
652
653                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
654                                        if( !function ) {
[a16764a6]655                                                SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
[1dcd9554]656                                        }
657
658
659                                        {
660                                                auto param     = function->parameters.begin();
661                                                auto param_end = function->parameters.end();
662
663                                                if( !advance_to_mutex( param, param_end ) ) {
[a16764a6]664                                                        SemanticError(function, "candidate function not viable: no mutex parameters\n");
[1dcd9554]665                                                }
666                                        }
667
668                                        Alternative newFunc( func );
669                                        // Strip reference from function
[a181494]670                                        referenceToRvalueConversion( newFunc.expr, newFunc.cost );
[1dcd9554]671
672                                        // For all the set of arguments we have try to match it with the parameter of the current function alternative
673                                        for ( auto & argsList : possibilities ) {
674
675                                                try {
676                                                        // Declare data structures need for resolution
677                                                        OpenVarSet openVars;
678                                                        AssertionSet resultNeed, resultHave;
[6f326b1]679                                                        TypeEnvironment resultEnv( func.env );
680                                                        makeUnifiableVars( function, openVars, resultNeed );
681                                                        // add all type variables as open variables now so that those not used in the parameter
682                                                        // list are still considered open.
683                                                        resultEnv.add( function->forall );
[1dcd9554]684
685                                                        // Load type variables from arguemnts into one shared space
686                                                        simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
687
688                                                        // Make sure we don't widen any existing bindings
[d286cf68]689                                                        resultEnv.forbidWidening();
[c5283ba]690
[1dcd9554]691                                                        // Find any unbound type variables
692                                                        resultEnv.extractOpenVars( openVars );
693
694                                                        auto param     = function->parameters.begin();
695                                                        auto param_end = function->parameters.end();
696
[c5283ba]697                                                        int n_mutex_param = 0;
[b9f383f]698
[1dcd9554]699                                                        // For every arguments of its set, check if it matches one of the parameter
700                                                        // The order is important
701                                                        for( auto & arg : argsList ) {
702
703                                                                // Ignore non-mutex arguments
704                                                                if( !advance_to_mutex( param, param_end ) ) {
705                                                                        // We ran out of parameters but still have arguments
706                                                                        // this function doesn't match
[c5283ba]707                                                                        SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
[1dcd9554]708                                                                }
709
[c5283ba]710                                                                n_mutex_param++;
[b9f383f]711
[1dcd9554]712                                                                // Check if the argument matches the parameter type in the current scope
[b9f383f]713                                                                if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
[1dcd9554]714                                                                        // Type doesn't match
715                                                                        stringstream ss;
716                                                                        ss << "candidate function not viable: no known convertion from '";
717                                                                        (*param)->get_type()->print( ss );
[b9f383f]718                                                                        ss << "' to '";
719                                                                        arg.expr->get_result()->print( ss );
[5248789]720                                                                        ss << "' with env '";
721                                                                        resultEnv.print(ss);
[1dcd9554]722                                                                        ss << "'\n";
[a16764a6]723                                                                        SemanticError( function, ss.str() );
[1dcd9554]724                                                                }
725
726                                                                param++;
727                                                        }
728
729                                                        // All arguments match !
730
731                                                        // Check if parameters are missing
732                                                        if( advance_to_mutex( param, param_end ) ) {
[c5283ba]733                                                                do {
734                                                                        n_mutex_param++;
735                                                                        param++;
736                                                                } while( advance_to_mutex( param, param_end ) );
737
[1dcd9554]738                                                                // We ran out of arguments but still have parameters left
739                                                                // this function doesn't match
[c5283ba]740                                                                SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
[1dcd9554]741                                                        }
742
743                                                        // All parameters match !
744
745                                                        // Finish the expressions to tie in the proper environments
746                                                        finishExpr( newFunc.expr, resultEnv );
747                                                        for( Alternative & alt : argsList ) {
748                                                                finishExpr( alt.expr, resultEnv );
749                                                        }
750
751                                                        // This is a match store it and save it for later
752                                                        func_candidates.push_back( newFunc );
753                                                        args_candidates.push_back( argsList );
754
755                                                }
[5170d95]756                                                catch( SemanticErrorException & e ) {
[1dcd9554]757                                                        errors.append( e );
758                                                }
759                                        }
760                                }
[5170d95]761                                catch( SemanticErrorException & e ) {
[1dcd9554]762                                        errors.append( e );
763                                }
764                        }
765
766                        // Make sure we got the right number of arguments
[a16764a6]767                        if( func_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
768                        if( args_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
769                        if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
770                        if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
[c71b256]771                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
[1dcd9554]772
773                        // Swap the results from the alternative with the unresolved values.
774                        // Alternatives will handle deletion on destruction
775                        std::swap( clause.target.function, func_candidates.front().expr );
776                        for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
777                                std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
778                        }
779
780                        // Resolve the conditions as if it were an IfStmt
781                        // Resolve the statments normally
[08da53d]782                        findSingleExpression( clause.condition, this->indexer );
[8f98b78]783                        clause.statement->accept( *visitor );
[1dcd9554]784                }
785
786
787                if( stmt->timeout.statement ) {
788                        // Resolve the timeout as an size_t for now
789                        // Resolve the conditions as if it were an IfStmt
790                        // Resolve the statments normally
[08da53d]791                        findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
792                        findSingleExpression( stmt->timeout.condition, this->indexer );
[8f98b78]793                        stmt->timeout.statement->accept( *visitor );
[1dcd9554]794                }
795
796                if( stmt->orelse.statement ) {
797                        // Resolve the conditions as if it were an IfStmt
798                        // Resolve the statments normally
[08da53d]799                        findSingleExpression( stmt->orelse.condition, this->indexer );
[8f98b78]800                        stmt->orelse.statement->accept( *visitor );
[1dcd9554]801                }
802        }
803
[60aaa51d]804        bool isCharType( Type * t ) {
[b5c5684]805                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
[71f4e4f]806                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
[b5c5684]807                                bt->get_kind() == BasicType::UnsignedChar;
808                }
809                return false;
810        }
811
[d76c588]812        void Resolver_old::previsit( SingleInit * singleInit ) {
[a4ca48c]813                visit_children = false;
[62423350]814                // resolve initialization using the possibilities as determined by the currentObject cursor
[0a22cda]815                Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
[08da53d]816                findSingleExpression( newExpr, indexer );
[e3e16bc]817                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
[62423350]818
819                // move cursor to the object that is actually initialized
[e4d829b]820                currentObject.setNext( initExpr->get_designation() );
[62423350]821
822                // discard InitExpr wrapper and retain relevant pieces
[08da53d]823                newExpr = initExpr->expr;
824                initExpr->expr = nullptr;
825                std::swap( initExpr->env, newExpr->env );
[cde3891]826                // InitExpr may have inferParams in the case where the expression specializes a function
827                // pointer, and newExpr may already have inferParams of its own, so a simple swap is not
[6d6e829]828                // sufficient.
[cdb990a]829                newExpr->spliceInferParams( initExpr );
[e4d829b]830                delete initExpr;
831
[cde3891]832                // get the actual object's type (may not exactly match what comes back from the resolver
[6d6e829]833                // due to conversions)
[62423350]834                Type * initContext = currentObject.getCurrentType();
835
[0a22cda]836                removeExtraneousCast( newExpr, indexer );
837
[62423350]838                // check if actual object's type is char[]
839                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
840                        if ( isCharType( at->get_base() ) ) {
841                                // check if the resolved type is char *
842                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
843                                        if ( isCharType( pt->get_base() ) ) {
[5170d95]844                                                if ( CastExpr * ce = dynamic_cast< CastExpr * >( newExpr ) ) {
[cde3891]845                                                        // strip cast if we're initializing a char[] with a char *,
[6d6e829]846                                                        // e.g.  char x[] = "hello";
[0a22cda]847                                                        newExpr = ce->get_arg();
848                                                        ce->set_arg( nullptr );
849                                                        std::swap( ce->env, newExpr->env );
850                                                        delete ce;
851                                                }
[62423350]852                                        }
853                                }
854                        }
855                }
[94b4364]856
[62423350]857                // set initializer expr to resolved express
[0a22cda]858                singleInit->value = newExpr;
[62423350]859
860                // move cursor to next object in preparation for next initializer
861                currentObject.increment();
862        }
[94b4364]863
[d76c588]864        void Resolver_old::previsit( ListInit * listInit ) {
[a4ca48c]865                visit_children = false;
[62423350]866                // move cursor into brace-enclosed initializer-list
[e4d829b]867                currentObject.enterListInit();
[cde3891]868                // xxx - fix this so that the list isn't copied, iterator should be used to change current
[6d6e829]869                // element
[e4d829b]870                std::list<Designation *> newDesignations;
871                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
[cde3891]872                        // iterate designations and initializers in pairs, moving the cursor to the current
[6d6e829]873                        // designated object and resolving the initializer against that object.
[e4d829b]874                        Designation * des = std::get<0>(p);
875                        Initializer * init = std::get<1>(p);
876                        newDesignations.push_back( currentObject.findNext( des ) );
[a4ca48c]877                        init->accept( *visitor );
[b5c5684]878                }
[62423350]879                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
[e4d829b]880                listInit->get_designations() = newDesignations; // xxx - memory management
881                currentObject.exitListInit();
882
[62423350]883                // xxx - this part has not be folded into CurrentObject yet
[e4d829b]884                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
885                //      Type * base = tt->get_baseType()->get_base();
886                //      if ( base ) {
887                //              // know the implementation type, so try using that as the initContext
888                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
889                //              currentObject = &tmpObj;
890                //              visit( listInit );
891                //      } else {
892                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
893                //              Parent::visit( listInit );
894                //      }
895                // } else {
[a32b204]896        }
[71f4e4f]897
[f1e012b]898        // ConstructorInit - fall back on C-style initializer
[d76c588]899        void Resolver_old::fallbackInit( ConstructorInit * ctorInit ) {
[f1e012b]900                // could not find valid constructor, or found an intrinsic constructor
901                // fall back on C-style initializer
902                delete ctorInit->get_ctor();
[6d6e829]903                ctorInit->set_ctor( nullptr );
[71a145de]904                delete ctorInit->get_dtor();
[6d6e829]905                ctorInit->set_dtor( nullptr );
[a4ca48c]906                maybeAccept( ctorInit->get_init(), *visitor );
[f1e012b]907        }
908
[1d2b64f]909        // needs to be callable from outside the resolver, so this is a standalone function
910        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
911                assert( ctorInit );
[d76c588]912                PassVisitor<Resolver_old> resolver( indexer );
[1d2b64f]913                ctorInit->accept( resolver );
914        }
915
916        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
917                assert( stmtExpr );
[d76c588]918                PassVisitor<Resolver_old> resolver( indexer );
[1d2b64f]919                stmtExpr->accept( resolver );
[5e2c348]920                stmtExpr->computeResult();
[dd05e12]921                // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
[1d2b64f]922        }
923
[d76c588]924        void Resolver_old::previsit( ConstructorInit * ctorInit ) {
[a4ca48c]925                visit_children = false;
[1ba88a0]926                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
[dd05e12]927                maybeAccept( ctorInit->ctor, *visitor );
928                maybeAccept( ctorInit->dtor, *visitor );
[071a31a]929
[5b2f5bb]930                // found a constructor - can get rid of C-style initializer
[dd05e12]931                delete ctorInit->init;
932                ctorInit->init = nullptr;
[ec79847]933
934                // intrinsic single parameter constructors and destructors do nothing. Since this was
935                // implicitly generated, there's no way for it to have side effects, so get rid of it
936                // to clean up generated code.
[dd05e12]937                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
938                        delete ctorInit->ctor;
939                        ctorInit->ctor = nullptr;
[ec79847]940                }
[f9cebb5]941
[dd05e12]942                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
943                        delete ctorInit->dtor;
944                        ctorInit->dtor = nullptr;
[ec79847]945                }
[a465caf]946
947                // xxx - todo -- what about arrays?
[6d6e829]948                // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
[a465caf]949                //      // can reduce the constructor down to a SingleInit using the
950                //      // second argument from the ctor call, since
951                //      delete ctorInit->get_ctor();
[6d6e829]952                //      ctorInit->set_ctor( nullptr );
[a465caf]953
954                //      Expression * arg =
955                //      ctorInit->set_init( new SingleInit( arg ) );
956                // }
[71f4e4f]957        }
[d76c588]958
959        ///////////////////////////////////////////////////////////////////////////
960        //
961        // *** NEW RESOLVER ***
962        //
963        ///////////////////////////////////////////////////////////////////////////
964
[99d4584]965        namespace {
966                /// Finds deleted expressions in an expression tree
967                struct DeleteFinder_new final : public ast::WithShortCircuiting {
[e6b42e7]968                        const ast::DeletedExpr * result = nullptr;
[99d4584]969
970                        void previsit( const ast::DeletedExpr * expr ) {
[e6b42e7]971                                if ( result ) { visit_children = false; }
972                                else { result = expr; }
[99d4584]973                        }
974
975                        void previsit( const ast::Expr * ) {
[e6b42e7]976                                if ( result ) { visit_children = false; }
[99d4584]977                        }
978                };
[d57e349]979        } // anonymous namespace
[99d4584]980
[d57e349]981        /// Check if this expression is or includes a deleted expression
982        const ast::DeletedExpr * findDeletedExpr( const ast::Expr * expr ) {
[e6b42e7]983                return ast::Pass<DeleteFinder_new>::read( expr );
[d57e349]984        }
[99d4584]985
[d57e349]986        namespace {
[b7d92b96]987                /// always-accept candidate filter
988                bool anyCandidate( const Candidate & ) { return true; }
989
[99d4584]990                /// Calls the CandidateFinder and finds the single best candidate
991                CandidateRef findUnfinishedKindExpression(
[ef5b828]992                        const ast::Expr * untyped, const ast::SymbolTable & symtab, const std::string & kind,
[b7d92b96]993                        std::function<bool(const Candidate &)> pred = anyCandidate, ResolvMode mode = {}
[99d4584]994                ) {
995                        if ( ! untyped ) return nullptr;
996
997                        // xxx - this isn't thread-safe, but should work until we parallelize the resolver
998                        static unsigned recursion_level = 0;
999
1000                        ++recursion_level;
1001                        ast::TypeEnvironment env;
1002                        CandidateFinder finder{ symtab, env };
1003                        finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
1004                        --recursion_level;
1005
1006                        // produce a filtered list of candidates
1007                        CandidateList candidates;
1008                        for ( auto & cand : finder.candidates ) {
1009                                if ( pred( *cand ) ) { candidates.emplace_back( cand ); }
1010                        }
1011
1012                        // produce invalid error if no candidates
1013                        if ( candidates.empty() ) {
[ef5b828]1014                                SemanticError( untyped,
1015                                        toString( "No reasonable alternatives for ", kind, (kind != "" ? " " : ""),
[99d4584]1016                                        "expression: ") );
1017                        }
1018
1019                        // search for cheapest candidate
1020                        CandidateList winners;
1021                        bool seen_undeleted = false;
1022                        for ( CandidateRef & cand : candidates ) {
1023                                int c = winners.empty() ? -1 : cand->cost.compare( winners.front()->cost );
1024
1025                                if ( c > 0 ) continue;  // skip more expensive than winner
1026
1027                                if ( c < 0 ) {
1028                                        // reset on new cheapest
1029                                        seen_undeleted = ! findDeletedExpr( cand->expr );
1030                                        winners.clear();
1031                                } else /* if ( c == 0 ) */ {
1032                                        if ( findDeletedExpr( cand->expr ) ) {
1033                                                // skip deleted expression if already seen one equivalent-cost not
1034                                                if ( seen_undeleted ) continue;
1035                                        } else if ( ! seen_undeleted ) {
1036                                                // replace list of equivalent-cost deleted expressions with one non-deleted
1037                                                winners.clear();
1038                                                seen_undeleted = true;
1039                                        }
1040                                }
1041
1042                                winners.emplace_back( std::move( cand ) );
1043                        }
1044
1045                        // promote candidate.cvtCost to .cost
[d57e349]1046                        promoteCvtCost( winners );
[99d4584]1047
1048                        // produce ambiguous errors, if applicable
1049                        if ( winners.size() != 1 ) {
1050                                std::ostringstream stream;
[ef5b828]1051                                stream << "Cannot choose between " << winners.size() << " alternatives for "
[99d4584]1052                                        << kind << (kind != "" ? " " : "") << "expression\n";
1053                                ast::print( stream, untyped );
1054                                stream << " Alternatives are:\n";
1055                                print( stream, winners, 1 );
1056                                SemanticError( untyped->location, stream.str() );
1057                        }
1058
1059                        // single selected choice
1060                        CandidateRef & choice = winners.front();
1061
1062                        // fail on only expression deleted
1063                        if ( ! seen_undeleted ) {
1064                                SemanticError( untyped->location, choice->expr.get(), "Unique best alternative "
1065                                "includes deleted identifier in " );
1066                        }
1067
1068                        return std::move( choice );
1069                }
1070
1071                /// Strips extraneous casts out of an expression
1072                struct StripCasts_new final {
[c408483]1073                        const ast::Expr * postvisit( const ast::CastExpr * castExpr ) {
[ef5b828]1074                                if (
[2890212]1075                                        castExpr->isGenerated == ast::GeneratedCast
[ef5b828]1076                                        && typesCompatible( castExpr->arg->result, castExpr->result )
[99d4584]1077                                ) {
1078                                        // generated cast is the same type as its argument, remove it after keeping env
[ef5b828]1079                                        return ast::mutate_field(
[b7d92b96]1080                                                castExpr->arg.get(), &ast::Expr::env, castExpr->env );
[99d4584]1081                                }
1082                                return castExpr;
1083                        }
1084
1085                        static void strip( ast::ptr< ast::Expr > & expr ) {
1086                                ast::Pass< StripCasts_new > stripper;
1087                                expr = expr->accept( stripper );
1088                        }
1089                };
1090
[60aaa51d]1091                /// Swaps argument into expression pointer, saving original environment
1092                void swap_and_save_env( ast::ptr< ast::Expr > & expr, const ast::Expr * newExpr ) {
1093                        ast::ptr< ast::TypeSubstitution > env = expr->env;
1094                        expr.set_and_mutate( newExpr )->env = env;
1095                }
1096
[b7d92b96]1097                /// Removes cast to type of argument (unlike StripCasts, also handles non-generated casts)
1098                void removeExtraneousCast( ast::ptr<ast::Expr> & expr, const ast::SymbolTable & symtab ) {
1099                        if ( const ast::CastExpr * castExpr = expr.as< ast::CastExpr >() ) {
1100                                if ( typesCompatible( castExpr->arg->result, castExpr->result, symtab ) ) {
1101                                        // cast is to the same type as its argument, remove it
[60aaa51d]1102                                        swap_and_save_env( expr, castExpr->arg );
[b7d92b96]1103                                }
1104                        }
1105                }
1106
[99d4584]1107                /// Establish post-resolver invariants for expressions
[ef5b828]1108                void finishExpr(
1109                        ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env,
[99d4584]1110                        const ast::TypeSubstitution * oldenv = nullptr
1111                ) {
1112                        // set up new type substitution for expression
[ef5b828]1113                        ast::ptr< ast::TypeSubstitution > newenv =
[99d4584]1114                                 oldenv ? oldenv : new ast::TypeSubstitution{};
1115                        env.writeToSubstitution( *newenv.get_and_mutate() );
1116                        expr.get_and_mutate()->env = std::move( newenv );
1117                        // remove unncecessary casts
1118                        StripCasts_new::strip( expr );
1119                }
[4b7cce6]1120        } // anonymous namespace
[b7d92b96]1121
[ef5b828]1122
[4b7cce6]1123        ast::ptr< ast::Expr > resolveInVoidContext(
1124                const ast::Expr * expr, const ast::SymbolTable & symtab, ast::TypeEnvironment & env
1125        ) {
1126                assertf( expr, "expected a non-null expression" );
[ef5b828]1127
[4b7cce6]1128                // set up and resolve expression cast to void
[417117e]1129                ast::ptr< ast::CastExpr > untyped = new ast::CastExpr{ expr };
[ef5b828]1130                CandidateRef choice = findUnfinishedKindExpression(
[4b7cce6]1131                        untyped, symtab, "", anyCandidate, ResolvMode::withAdjustment() );
[ef5b828]1132
[4b7cce6]1133                // a cast expression has either 0 or 1 interpretations (by language rules);
1134                // if 0, an exception has already been thrown, and this code will not run
1135                const ast::CastExpr * castExpr = choice->expr.strict_as< ast::CastExpr >();
1136                env = std::move( choice->env );
1137
1138                return castExpr->arg;
1139        }
[b7d92b96]1140
[4b7cce6]1141        namespace {
[ef5b828]1142                /// Resolve `untyped` to the expression whose candidate is the best match for a `void`
[b7d92b96]1143                /// context.
[ef5b828]1144                ast::ptr< ast::Expr > findVoidExpression(
[b7d92b96]1145                        const ast::Expr * untyped, const ast::SymbolTable & symtab
1146                ) {
1147                        resetTyVarRenaming();
1148                        ast::TypeEnvironment env;
1149                        ast::ptr< ast::Expr > newExpr = resolveInVoidContext( untyped, symtab, env );
1150                        finishExpr( newExpr, env, untyped->env );
1151                        return newExpr;
1152                }
1153
[ef5b828]1154                /// resolve `untyped` to the expression whose candidate satisfies `pred` with the
[99d4584]1155                /// lowest cost, returning the resolved version
1156                ast::ptr< ast::Expr > findKindExpression(
[ef5b828]1157                        const ast::Expr * untyped, const ast::SymbolTable & symtab,
1158                        std::function<bool(const Candidate &)> pred = anyCandidate,
[2b59f55]1159                        const std::string & kind = "", ResolvMode mode = {}
[99d4584]1160                ) {
1161                        if ( ! untyped ) return {};
[ef5b828]1162                        CandidateRef choice =
[99d4584]1163                                findUnfinishedKindExpression( untyped, symtab, kind, pred, mode );
1164                        finishExpr( choice->expr, choice->env, untyped->env );
1165                        return std::move( choice->expr );
1166                }
1167
[2773ab8]1168                /// Resolve `untyped` to the single expression whose candidate is the best match
[ef5b828]1169                ast::ptr< ast::Expr > findSingleExpression(
1170                        const ast::Expr * untyped, const ast::SymbolTable & symtab
[2773ab8]1171                ) {
[57e0289]1172                        Stats::ResolveTime::start( untyped );
1173                        auto res = findKindExpression( untyped, symtab );
1174                        Stats::ResolveTime::stop();
1175                        return res;
[2773ab8]1176                }
[18e683b]1177        } // anonymous namespace
[2773ab8]1178
[b7d92b96]1179                ast::ptr< ast::Expr > findSingleExpression(
1180                        const ast::Expr * untyped, const ast::Type * type, const ast::SymbolTable & symtab
1181                ) {
1182                        assert( untyped && type );
[b8524ca]1183                        ast::ptr< ast::Expr > castExpr = new ast::CastExpr{ untyped, type };
[2773ab8]1184                        ast::ptr< ast::Expr > newExpr = findSingleExpression( castExpr, symtab );
[b7d92b96]1185                        removeExtraneousCast( newExpr, symtab );
1186                        return newExpr;
1187                }
1188
[18e683b]1189        namespace {
[99d4584]1190                /// Predicate for "Candidate has integral type"
1191                bool hasIntegralType( const Candidate & i ) {
1192                        const ast::Type * type = i.expr->result;
[ef5b828]1193
[99d4584]1194                        if ( auto bt = dynamic_cast< const ast::BasicType * >( type ) ) {
1195                                return bt->isInteger();
[ef5b828]1196                        } else if (
1197                                dynamic_cast< const ast::EnumInstType * >( type )
[99d4584]1198                                || dynamic_cast< const ast::ZeroType * >( type )
1199                                || dynamic_cast< const ast::OneType * >( type )
1200                        ) {
1201                                return true;
1202                        } else return false;
1203                }
1204
1205                /// Resolve `untyped` as an integral expression, returning the resolved version
[ef5b828]1206                ast::ptr< ast::Expr > findIntegralExpression(
1207                        const ast::Expr * untyped, const ast::SymbolTable & symtab
[99d4584]1208                ) {
[2b59f55]1209                        return findKindExpression( untyped, symtab, hasIntegralType, "condition" );
[99d4584]1210                }
[60aaa51d]1211
1212                /// check if a type is a character type
1213                bool isCharType( const ast::Type * t ) {
1214                        if ( auto bt = dynamic_cast< const ast::BasicType * >( t ) ) {
[ef5b828]1215                                return bt->kind == ast::BasicType::Char
1216                                        || bt->kind == ast::BasicType::SignedChar
[60aaa51d]1217                                        || bt->kind == ast::BasicType::UnsignedChar;
1218                        }
1219                        return false;
1220                }
[2773ab8]1221
1222                /// Advance a type itertor to the next mutex parameter
1223                template<typename Iter>
1224                inline bool nextMutex( Iter & it, const Iter & end ) {
1225                        while ( it != end && ! (*it)->get_type()->is_mutex() ) { ++it; }
1226                        return it != end;
1227                }
[99d4584]1228        }
1229
[4864a73]1230        class Resolver_new final
1231        : public ast::WithSymbolTable, public ast::WithGuards,
1232          public ast::WithVisitorRef<Resolver_new>, public ast::WithShortCircuiting,
[0e42794]1233          public ast::WithStmtsToAdd<> {
[4864a73]1234
[2a8f0c1]1235                ast::ptr< ast::Type > functionReturn = nullptr;
[2b59f55]1236                ast::CurrentObject currentObject;
[99d4584]1237                bool inEnumDecl = false;
[2a8f0c1]1238
[4864a73]1239        public:
[c15085d]1240                static size_t traceId;
[d76c588]1241                Resolver_new() = default;
[0e42794]1242                Resolver_new( const ast::SymbolTable & syms ) { symtab = syms; }
[d76c588]1243
[99d4584]1244                void previsit( const ast::FunctionDecl * );
1245                const ast::FunctionDecl * postvisit( const ast::FunctionDecl * );
1246                void previsit( const ast::ObjectDecl * );
1247                void previsit( const ast::EnumDecl * );
1248                const ast::StaticAssertDecl * previsit( const ast::StaticAssertDecl * );
1249
[0f6a7752]1250                const ast::ArrayType * previsit( const ast::ArrayType * );
1251                const ast::PointerType * previsit( const ast::PointerType * );
[99d4584]1252
[2773ab8]1253                const ast::ExprStmt *        previsit( const ast::ExprStmt * );
1254                const ast::AsmExpr *         previsit( const ast::AsmExpr * );
1255                const ast::AsmStmt *         previsit( const ast::AsmStmt * );
1256                const ast::IfStmt *          previsit( const ast::IfStmt * );
1257                const ast::WhileStmt *       previsit( const ast::WhileStmt * );
1258                const ast::ForStmt *         previsit( const ast::ForStmt * );
1259                const ast::SwitchStmt *      previsit( const ast::SwitchStmt * );
1260                const ast::CaseStmt *        previsit( const ast::CaseStmt * );
1261                const ast::BranchStmt *      previsit( const ast::BranchStmt * );
1262                const ast::ReturnStmt *      previsit( const ast::ReturnStmt * );
1263                const ast::ThrowStmt *       previsit( const ast::ThrowStmt * );
1264                const ast::CatchStmt *       previsit( const ast::CatchStmt * );
[b9fa85b]1265                const ast::CatchStmt *       postvisit( const ast::CatchStmt * );
[2773ab8]1266                const ast::WaitForStmt *     previsit( const ast::WaitForStmt * );
[99d4584]1267
[2d11663]1268                const ast::SingleInit *      previsit( const ast::SingleInit * );
1269                const ast::ListInit *        previsit( const ast::ListInit * );
1270                const ast::ConstructorInit * previsit( const ast::ConstructorInit * );
[d76c588]1271        };
[0d070ca]1272        // size_t Resolver_new::traceId = Stats::Heap::new_stacktrace_id("Resolver");
[d76c588]1273
[417117e]1274        void resolve( std::list< ast::ptr< ast::Decl > >& translationUnit ) {
[a86b2ca6]1275                ast::Pass< Resolver_new >::run( translationUnit );
[d76c588]1276        }
1277
[ef5b828]1278        ast::ptr< ast::Init > resolveCtorInit(
1279                const ast::ConstructorInit * ctorInit, const ast::SymbolTable & symtab
[234b1cb]1280        ) {
1281                assert( ctorInit );
1282                ast::Pass< Resolver_new > resolver{ symtab };
1283                return ctorInit->accept( resolver );
1284        }
1285
[ef5b828]1286        ast::ptr< ast::Expr > resolveStmtExpr(
1287                const ast::StmtExpr * stmtExpr, const ast::SymbolTable & symtab
[17a0ede2]1288        ) {
1289                assert( stmtExpr );
1290                ast::Pass< Resolver_new > resolver{ symtab };
1291                ast::ptr< ast::Expr > ret = stmtExpr;
1292                ret = ret->accept( resolver );
1293                strict_dynamic_cast< ast::StmtExpr * >( ret.get_and_mutate() )->computeResult();
1294                return ret;
1295        }
1296
[2a8f0c1]1297        void Resolver_new::previsit( const ast::FunctionDecl * functionDecl ) {
1298                GuardValue( functionReturn );
1299                functionReturn = extractResultType( functionDecl->type );
[d76c588]1300        }
1301
[2a8f0c1]1302        const ast::FunctionDecl * Resolver_new::postvisit( const ast::FunctionDecl * functionDecl ) {
[4864a73]1303                // default value expressions have an environment which shouldn't be there and trips up
[2a8f0c1]1304                // later passes.
[e068c8a]1305                assert( functionDecl->unique() );
1306                ast::FunctionType * mutType = mutate( functionDecl->type.get() );
1307
1308                for ( unsigned i = 0 ; i < mutType->params.size() ; ++i ) {
1309                        if ( const ast::ObjectDecl * obj = mutType->params[i].as< ast::ObjectDecl >() ) {
1310                                if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) {
1311                                        if ( init->value->env == nullptr ) continue;
1312                                        // clone initializer minus the initializer environment
1313                                        auto mutParam = mutate( mutType->params[i].strict_as< ast::ObjectDecl >() );
1314                                        auto mutInit = mutate( mutParam->init.strict_as< ast::SingleInit >() );
1315                                        auto mutValue = mutate( mutInit->value.get() );
1316
1317                                        mutValue->env = nullptr;
1318                                        mutInit->value = mutValue;
1319                                        mutParam->init = mutInit;
1320                                        mutType->params[i] = mutParam;
1321
1322                                        assert( ! mutType->params[i].strict_as< ast::ObjectDecl >()->init.strict_as< ast::SingleInit >()->value->env);
1323                                }
1324                        }
[2a8f0c1]1325                }
[73973b6]1326                mutate_field(functionDecl, &ast::FunctionDecl::type, mutType);
1327                return functionDecl;
[d76c588]1328        }
1329
[2a8f0c1]1330        void Resolver_new::previsit( const ast::ObjectDecl * objectDecl ) {
[ef5b828]1331                // To handle initialization of routine pointers [e.g. int (*fp)(int) = foo()],
1332                // class-variable `initContext` is changed multiple times because the LHS is analyzed
1333                // twice. The second analysis changes `initContext` because a function type can contain
1334                // object declarations in the return and parameter types. Therefore each value of
1335                // `initContext` is retained so the type on the first analysis is preserved and used for
[b7d92b96]1336                // selecting the RHS.
1337                GuardValue( currentObject );
[2b59f55]1338                currentObject = ast::CurrentObject{ objectDecl->location, objectDecl->get_type() };
[b7d92b96]1339                if ( inEnumDecl && dynamic_cast< const ast::EnumInstType * >( objectDecl->get_type() ) ) {
[ef5b828]1340                        // enumerator initializers should not use the enum type to initialize, since the
[b7d92b96]1341                        // enum type is still incomplete at this point. Use `int` instead.
[ef5b828]1342                        currentObject = ast::CurrentObject{
[2b59f55]1343                                objectDecl->location, new ast::BasicType{ ast::BasicType::SignedInt } };
[b7d92b96]1344                }
[d76c588]1345        }
1346
[99d4584]1347        void Resolver_new::previsit( const ast::EnumDecl * ) {
1348                // in case we decide to allow nested enums
1349                GuardValue( inEnumDecl );
[2890212]1350                inEnumDecl = true;
[d76c588]1351        }
1352
[ef5b828]1353        const ast::StaticAssertDecl * Resolver_new::previsit(
1354                const ast::StaticAssertDecl * assertDecl
[99d4584]1355        ) {
[ef5b828]1356                return ast::mutate_field(
1357                        assertDecl, &ast::StaticAssertDecl::cond,
[b7d92b96]1358                        findIntegralExpression( assertDecl->cond, symtab ) );
1359        }
1360
1361        template< typename PtrType >
[0f6a7752]1362        const PtrType * handlePtrType( const PtrType * type, const ast::SymbolTable & symtab ) {
1363                if ( type->dimension ) {
1364                        #warning should use new equivalent to Validate::SizeType rather than sizeType here
[3c89751]1365                        ast::ptr< ast::Type > sizeType = new ast::BasicType{ ast::BasicType::LongUnsignedInt };
[ef5b828]1366                        ast::mutate_field(
1367                                type, &PtrType::dimension,
[0f6a7752]1368                                findSingleExpression( type->dimension, sizeType, symtab ) );
1369                }
1370                return type;
[d76c588]1371        }
1372
[0f6a7752]1373        const ast::ArrayType * Resolver_new::previsit( const ast::ArrayType * at ) {
1374                return handlePtrType( at, symtab );
[d76c588]1375        }
1376
[0f6a7752]1377        const ast::PointerType * Resolver_new::previsit( const ast::PointerType * pt ) {
1378                return handlePtrType( pt, symtab );
[d76c588]1379        }
1380
[b7d92b96]1381        const ast::ExprStmt * Resolver_new::previsit( const ast::ExprStmt * exprStmt ) {
1382                visit_children = false;
1383                assertf( exprStmt->expr, "ExprStmt has null expression in resolver" );
[ef5b828]1384
1385                return ast::mutate_field(
[b7d92b96]1386                        exprStmt, &ast::ExprStmt::expr, findVoidExpression( exprStmt->expr, symtab ) );
[d76c588]1387        }
1388
[b7d92b96]1389        const ast::AsmExpr * Resolver_new::previsit( const ast::AsmExpr * asmExpr ) {
1390                visit_children = false;
1391
[ef5b828]1392                asmExpr = ast::mutate_field(
[b7d92b96]1393                        asmExpr, &ast::AsmExpr::operand, findVoidExpression( asmExpr->operand, symtab ) );
[ef5b828]1394
[b7d92b96]1395                return asmExpr;
[d76c588]1396        }
1397
[2b59f55]1398        const ast::AsmStmt * Resolver_new::previsit( const ast::AsmStmt * asmStmt ) {
1399                visitor->maybe_accept( asmStmt, &ast::AsmStmt::input );
1400                visitor->maybe_accept( asmStmt, &ast::AsmStmt::output );
1401                visit_children = false;
1402                return asmStmt;
[d76c588]1403        }
1404
[b7d92b96]1405        const ast::IfStmt * Resolver_new::previsit( const ast::IfStmt * ifStmt ) {
1406                return ast::mutate_field(
1407                        ifStmt, &ast::IfStmt::cond, findIntegralExpression( ifStmt->cond, symtab ) );
[d76c588]1408        }
1409
[b7d92b96]1410        const ast::WhileStmt * Resolver_new::previsit( const ast::WhileStmt * whileStmt ) {
[ef5b828]1411                return ast::mutate_field(
[b7d92b96]1412                        whileStmt, &ast::WhileStmt::cond, findIntegralExpression( whileStmt->cond, symtab ) );
[d76c588]1413        }
1414
[b7d92b96]1415        const ast::ForStmt * Resolver_new::previsit( const ast::ForStmt * forStmt ) {
1416                if ( forStmt->cond ) {
1417                        forStmt = ast::mutate_field(
1418                                forStmt, &ast::ForStmt::cond, findIntegralExpression( forStmt->cond, symtab ) );
1419                }
1420
1421                if ( forStmt->inc ) {
1422                        forStmt = ast::mutate_field(
1423                                forStmt, &ast::ForStmt::inc, findVoidExpression( forStmt->inc, symtab ) );
1424                }
1425
1426                return forStmt;
[d76c588]1427        }
1428
[b7d92b96]1429        const ast::SwitchStmt * Resolver_new::previsit( const ast::SwitchStmt * switchStmt ) {
1430                GuardValue( currentObject );
1431                switchStmt = ast::mutate_field(
[ef5b828]1432                        switchStmt, &ast::SwitchStmt::cond,
[b7d92b96]1433                        findIntegralExpression( switchStmt->cond, symtab ) );
[2b59f55]1434                currentObject = ast::CurrentObject{ switchStmt->location, switchStmt->cond->result };
[b7d92b96]1435                return switchStmt;
[d76c588]1436        }
1437
[b7d92b96]1438        const ast::CaseStmt * Resolver_new::previsit( const ast::CaseStmt * caseStmt ) {
1439                if ( caseStmt->cond ) {
[60aaa51d]1440                        std::deque< ast::InitAlternative > initAlts = currentObject.getOptions();
[2b59f55]1441                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral "
1442                                "expression." );
[ef5b828]1443
1444                        ast::ptr< ast::Expr > untyped =
[2b59f55]1445                                new ast::CastExpr{ caseStmt->location, caseStmt->cond, initAlts.front().type };
[2773ab8]1446                        ast::ptr< ast::Expr > newExpr = findSingleExpression( untyped, symtab );
[ef5b828]1447
1448                        // case condition cannot have a cast in C, so it must be removed here, regardless of
[2b59f55]1449                        // whether it would perform a conversion.
1450                        if ( const ast::CastExpr * castExpr = newExpr.as< ast::CastExpr >() ) {
[60aaa51d]1451                                swap_and_save_env( newExpr, castExpr->arg );
[2b59f55]1452                        }
[ef5b828]1453
[2b59f55]1454                        caseStmt = ast::mutate_field( caseStmt, &ast::CaseStmt::cond, newExpr );
[b7d92b96]1455                }
1456                return caseStmt;
[d76c588]1457        }
1458
[b7d92b96]1459        const ast::BranchStmt * Resolver_new::previsit( const ast::BranchStmt * branchStmt ) {
1460                visit_children = false;
1461                // must resolve the argument of a computed goto
1462                if ( branchStmt->kind == ast::BranchStmt::Goto && branchStmt->computedTarget ) {
1463                        // computed goto argument is void*
[2773ab8]1464                        ast::ptr< ast::Type > target = new ast::PointerType{ new ast::VoidType{} };
[b7d92b96]1465                        branchStmt = ast::mutate_field(
[ef5b828]1466                                branchStmt, &ast::BranchStmt::computedTarget,
[2773ab8]1467                                findSingleExpression( branchStmt->computedTarget, target, symtab ) );
[b7d92b96]1468                }
1469                return branchStmt;
[d76c588]1470        }
1471
[2b59f55]1472        const ast::ReturnStmt * Resolver_new::previsit( const ast::ReturnStmt * returnStmt ) {
1473                visit_children = false;
1474                if ( returnStmt->expr ) {
1475                        returnStmt = ast::mutate_field(
[ef5b828]1476                                returnStmt, &ast::ReturnStmt::expr,
[2b59f55]1477                                findSingleExpression( returnStmt->expr, functionReturn, symtab ) );
1478                }
1479                return returnStmt;
[d76c588]1480        }
1481
[2b59f55]1482        const ast::ThrowStmt * Resolver_new::previsit( const ast::ThrowStmt * throwStmt ) {
1483                visit_children = false;
1484                if ( throwStmt->expr ) {
[ef5b828]1485                        const ast::StructDecl * exceptionDecl =
[3090127]1486                                symtab.lookupStruct( "__cfaehm_base_exception_t" );
[2b59f55]1487                        assert( exceptionDecl );
[ef5b828]1488                        ast::ptr< ast::Type > exceptType =
[2b59f55]1489                                new ast::PointerType{ new ast::StructInstType{ exceptionDecl } };
1490                        throwStmt = ast::mutate_field(
[ef5b828]1491                                throwStmt, &ast::ThrowStmt::expr,
[2b59f55]1492                                findSingleExpression( throwStmt->expr, exceptType, symtab ) );
1493                }
1494                return throwStmt;
[d76c588]1495        }
1496
[2b59f55]1497        const ast::CatchStmt * Resolver_new::previsit( const ast::CatchStmt * catchStmt ) {
[b9fa85b]1498                // Until we are very sure this invarent (ifs that move between passes have thenPart)
1499                // holds, check it. This allows a check for when to decode the mangling.
1500                if ( auto ifStmt = catchStmt->body.as<ast::IfStmt>() ) {
1501                        assert( ifStmt->thenPart );
1502                }
1503                // Encode the catchStmt so the condition can see the declaration.
[2b59f55]1504                if ( catchStmt->cond ) {
[b9fa85b]1505                        ast::CatchStmt * stmt = mutate( catchStmt );
1506                        stmt->body = new ast::IfStmt( stmt->location, stmt->cond, nullptr, stmt->body );
1507                        stmt->cond = nullptr;
1508                        return stmt;
1509                }
1510                return catchStmt;
1511        }
1512
1513        const ast::CatchStmt * Resolver_new::postvisit( const ast::CatchStmt * catchStmt ) {
1514                // Decode the catchStmt so everything is stored properly.
1515                const ast::IfStmt * ifStmt = catchStmt->body.as<ast::IfStmt>();
1516                if ( nullptr != ifStmt && nullptr == ifStmt->thenPart ) {
1517                        assert( ifStmt->cond );
1518                        assert( ifStmt->elsePart );
1519                        ast::CatchStmt * stmt = ast::mutate( catchStmt );
1520                        stmt->cond = ifStmt->cond;
1521                        stmt->body = ifStmt->elsePart;
1522                        // ifStmt should be implicately deleted here.
1523                        return stmt;
[2b59f55]1524                }
1525                return catchStmt;
[d76c588]1526        }
1527
[2773ab8]1528        const ast::WaitForStmt * Resolver_new::previsit( const ast::WaitForStmt * stmt ) {
1529                visit_children = false;
1530
1531                // Resolve all clauses first
1532                for ( unsigned i = 0; i < stmt->clauses.size(); ++i ) {
1533                        const ast::WaitForStmt::Clause & clause = stmt->clauses[i];
1534
1535                        ast::TypeEnvironment env;
1536                        CandidateFinder funcFinder{ symtab, env };
1537
1538                        // Find all candidates for a function in canonical form
1539                        funcFinder.find( clause.target.func, ResolvMode::withAdjustment() );
1540
1541                        if ( funcFinder.candidates.empty() ) {
1542                                stringstream ss;
1543                                ss << "Use of undeclared indentifier '";
1544                                ss << clause.target.func.strict_as< ast::NameExpr >()->name;
1545                                ss << "' in call to waitfor";
1546                                SemanticError( stmt->location, ss.str() );
1547                        }
1548
1549                        if ( clause.target.args.empty() ) {
[ef5b828]1550                                SemanticError( stmt->location,
[2773ab8]1551                                        "Waitfor clause must have at least one mutex parameter");
1552                        }
1553
1554                        // Find all alternatives for all arguments in canonical form
[ef5b828]1555                        std::vector< CandidateFinder > argFinders =
[2773ab8]1556                                funcFinder.findSubExprs( clause.target.args );
[ef5b828]1557
[2773ab8]1558                        // List all combinations of arguments
1559                        std::vector< CandidateList > possibilities;
1560                        combos( argFinders.begin(), argFinders.end(), back_inserter( possibilities ) );
1561
1562                        // For every possible function:
[ef5b828]1563                        // * try matching the arguments to the parameters, not the other way around because
[2773ab8]1564                        //   more arguments than parameters
1565                        CandidateList funcCandidates;
1566                        std::vector< CandidateList > argsCandidates;
1567                        SemanticErrorException errors;
1568                        for ( CandidateRef & func : funcFinder.candidates ) {
1569                                try {
[ef5b828]1570                                        auto pointerType = dynamic_cast< const ast::PointerType * >(
[2773ab8]1571                                                func->expr->result->stripReferences() );
1572                                        if ( ! pointerType ) {
[ef5b828]1573                                                SemanticError( stmt->location, func->expr->result.get(),
[2773ab8]1574                                                        "candidate not viable: not a pointer type\n" );
1575                                        }
1576
1577                                        auto funcType = pointerType->base.as< ast::FunctionType >();
1578                                        if ( ! funcType ) {
[ef5b828]1579                                                SemanticError( stmt->location, func->expr->result.get(),
[2773ab8]1580                                                        "candidate not viable: not a function type\n" );
1581                                        }
1582
1583                                        {
1584                                                auto param    = funcType->params.begin();
1585                                                auto paramEnd = funcType->params.end();
1586
1587                                                if( ! nextMutex( param, paramEnd ) ) {
[ef5b828]1588                                                        SemanticError( stmt->location, funcType,
[2773ab8]1589                                                                "candidate function not viable: no mutex parameters\n");
1590                                                }
1591                                        }
1592
1593                                        CandidateRef func2{ new Candidate{ *func } };
1594                                        // strip reference from function
1595                                        func2->expr = referenceToRvalueConversion( func->expr, func2->cost );
1596
1597                                        // Each argument must be matched with a parameter of the current candidate
1598                                        for ( auto & argsList : possibilities ) {
1599                                                try {
1600                                                        // Declare data structures needed for resolution
1601                                                        ast::OpenVarSet open;
1602                                                        ast::AssertionSet need, have;
1603                                                        ast::TypeEnvironment resultEnv{ func->env };
[ef5b828]1604                                                        // Add all type variables as open so that those not used in the
[2773ab8]1605                                                        // parameter list are still considered open
1606                                                        resultEnv.add( funcType->forall );
1607
1608                                                        // load type variables from arguments into one shared space
1609                                                        for ( auto & arg : argsList ) {
1610                                                                resultEnv.simpleCombine( arg->env );
1611                                                        }
1612
1613                                                        // Make sure we don't widen any existing bindings
1614                                                        resultEnv.forbidWidening();
1615
1616                                                        // Find any unbound type variables
1617                                                        resultEnv.extractOpenVars( open );
1618
1619                                                        auto param = funcType->params.begin();
1620                                                        auto paramEnd = funcType->params.end();
1621
1622                                                        unsigned n_mutex_param = 0;
1623
[ef5b828]1624                                                        // For every argument of its set, check if it matches one of the
[2773ab8]1625                                                        // parameters. The order is important
1626                                                        for ( auto & arg : argsList ) {
1627                                                                // Ignore non-mutex arguments
1628                                                                if ( ! nextMutex( param, paramEnd ) ) {
1629                                                                        // We ran out of parameters but still have arguments.
1630                                                                        // This function doesn't match
[ef5b828]1631                                                                        SemanticError( stmt->location, funcType,
[2773ab8]1632                                                                                toString("candidate function not viable: too many mutex "
1633                                                                                "arguments, expected ", n_mutex_param, "\n" ) );
1634                                                                }
1635
1636                                                                ++n_mutex_param;
1637
[ef5b828]1638                                                                // Check if the argument matches the parameter type in the current
[2773ab8]1639                                                                // scope
1640                                                                ast::ptr< ast::Type > paramType = (*param)->get_type();
[ef5b828]1641                                                                if (
1642                                                                        ! unify(
1643                                                                                arg->expr->result, paramType, resultEnv, need, have, open,
1644                                                                                symtab )
[2773ab8]1645                                                                ) {
1646                                                                        // Type doesn't match
1647                                                                        stringstream ss;
1648                                                                        ss << "candidate function not viable: no known conversion "
1649                                                                                "from '";
1650                                                                        ast::print( ss, (*param)->get_type() );
1651                                                                        ss << "' to '";
1652                                                                        ast::print( ss, arg->expr->result );
1653                                                                        ss << "' with env '";
1654                                                                        ast::print( ss, resultEnv );
1655                                                                        ss << "'\n";
1656                                                                        SemanticError( stmt->location, funcType, ss.str() );
1657                                                                }
1658
1659                                                                ++param;
1660                                                        }
1661
1662                                                        // All arguments match!
1663
1664                                                        // Check if parameters are missing
1665                                                        if ( nextMutex( param, paramEnd ) ) {
1666                                                                do {
1667                                                                        ++n_mutex_param;
1668                                                                        ++param;
1669                                                                } while ( nextMutex( param, paramEnd ) );
1670
[ef5b828]1671                                                                // We ran out of arguments but still have parameters left; this
[2773ab8]1672                                                                // function doesn't match
[ef5b828]1673                                                                SemanticError( stmt->location, funcType,
[2773ab8]1674                                                                        toString( "candidate function not viable: too few mutex "
1675                                                                        "arguments, expected ", n_mutex_param, "\n" ) );
1676                                                        }
1677
1678                                                        // All parameters match!
1679
1680                                                        // Finish the expressions to tie in proper environments
1681                                                        finishExpr( func2->expr, resultEnv );
1682                                                        for ( CandidateRef & arg : argsList ) {
1683                                                                finishExpr( arg->expr, resultEnv );
1684                                                        }
1685
1686                                                        // This is a match, store it and save it for later
1687                                                        funcCandidates.emplace_back( std::move( func2 ) );
1688                                                        argsCandidates.emplace_back( std::move( argsList ) );
1689
1690                                                } catch ( SemanticErrorException & e ) {
1691                                                        errors.append( e );
1692                                                }
1693                                        }
1694                                } catch ( SemanticErrorException & e ) {
1695                                        errors.append( e );
1696                                }
1697                        }
1698
1699                        // Make sure correct number of arguments
1700                        if( funcCandidates.empty() ) {
[ef5b828]1701                                SemanticErrorException top( stmt->location,
[2773ab8]1702                                        "No alternatives for function in call to waitfor" );
1703                                top.append( errors );
1704                                throw top;
1705                        }
1706
1707                        if( argsCandidates.empty() ) {
[ef5b828]1708                                SemanticErrorException top( stmt->location,
1709                                        "No alternatives for arguments in call to waitfor" );
[2773ab8]1710                                top.append( errors );
1711                                throw top;
1712                        }
1713
1714                        if( funcCandidates.size() > 1 ) {
[ef5b828]1715                                SemanticErrorException top( stmt->location,
[2773ab8]1716                                        "Ambiguous function in call to waitfor" );
1717                                top.append( errors );
1718                                throw top;
1719                        }
1720                        if( argsCandidates.size() > 1 ) {
1721                                SemanticErrorException top( stmt->location,
1722                                        "Ambiguous arguments in call to waitfor" );
1723                                top.append( errors );
1724                                throw top;
1725                        }
1726                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
1727
1728                        // build new clause
1729                        ast::WaitForStmt::Clause clause2;
[ef5b828]1730
[2773ab8]1731                        clause2.target.func = funcCandidates.front()->expr;
[ef5b828]1732
[2773ab8]1733                        clause2.target.args.reserve( clause.target.args.size() );
1734                        for ( auto arg : argsCandidates.front() ) {
1735                                clause2.target.args.emplace_back( std::move( arg->expr ) );
1736                        }
1737
1738                        // Resolve the conditions as if it were an IfStmt, statements normally
1739                        clause2.cond = findSingleExpression( clause.cond, symtab );
1740                        clause2.stmt = clause.stmt->accept( *visitor );
1741
1742                        // set results into stmt
1743                        auto n = mutate( stmt );
1744                        n->clauses[i] = std::move( clause2 );
1745                        stmt = n;
1746                }
1747
1748                if ( stmt->timeout.stmt ) {
1749                        // resolve the timeout as a size_t, the conditions like IfStmt, and stmts normally
1750                        ast::WaitForStmt::Timeout timeout2;
1751
[ef5b828]1752                        ast::ptr< ast::Type > target =
[2773ab8]1753                                new ast::BasicType{ ast::BasicType::LongLongUnsignedInt };
1754                        timeout2.time = findSingleExpression( stmt->timeout.time, target, symtab );
1755                        timeout2.cond = findSingleExpression( stmt->timeout.cond, symtab );
1756                        timeout2.stmt = stmt->timeout.stmt->accept( *visitor );
1757
1758                        // set results into stmt
1759                        auto n = mutate( stmt );
1760                        n->timeout = std::move( timeout2 );
1761                        stmt = n;
1762                }
1763
1764                if ( stmt->orElse.stmt ) {
1765                        // resolve the condition like IfStmt, stmts normally
1766                        ast::WaitForStmt::OrElse orElse2;
1767
1768                        orElse2.cond = findSingleExpression( stmt->orElse.cond, symtab );
1769                        orElse2.stmt = stmt->orElse.stmt->accept( *visitor );
1770
1771                        // set results into stmt
1772                        auto n = mutate( stmt );
1773                        n->orElse = std::move( orElse2 );
1774                        stmt = n;
1775                }
1776
1777                return stmt;
[d76c588]1778        }
1779
[60aaa51d]1780
1781
1782        const ast::SingleInit * Resolver_new::previsit( const ast::SingleInit * singleInit ) {
1783                visit_children = false;
[ef5b828]1784                // resolve initialization using the possibilities as determined by the `currentObject`
[60aaa51d]1785                // cursor.
[ef5b828]1786                ast::ptr< ast::Expr > untyped = new ast::UntypedInitExpr{
[60aaa51d]1787                        singleInit->location, singleInit->value, currentObject.getOptions() };
[2773ab8]1788                ast::ptr<ast::Expr> newExpr = findSingleExpression( untyped, symtab );
[60aaa51d]1789                const ast::InitExpr * initExpr = newExpr.strict_as< ast::InitExpr >();
1790
1791                // move cursor to the object that is actually initialized
1792                currentObject.setNext( initExpr->designation );
1793
1794                // discard InitExpr wrapper and retain relevant pieces.
[ef5b828]1795                // `initExpr` may have inferred params in the case where the expression specialized a
1796                // function pointer, and newExpr may already have inferParams of its own, so a simple
[60aaa51d]1797                // swap is not sufficient
1798                ast::Expr::InferUnion inferred = initExpr->inferred;
1799                swap_and_save_env( newExpr, initExpr->expr );
1800                newExpr.get_and_mutate()->inferred.splice( std::move(inferred) );
1801
[ef5b828]1802                // get the actual object's type (may not exactly match what comes back from the resolver
[60aaa51d]1803                // due to conversions)
1804                const ast::Type * initContext = currentObject.getCurrentType();
1805
1806                removeExtraneousCast( newExpr, symtab );
1807
1808                // check if actual object's type is char[]
1809                if ( auto at = dynamic_cast< const ast::ArrayType * >( initContext ) ) {
1810                        if ( isCharType( at->base ) ) {
1811                                // check if the resolved type is char*
1812                                if ( auto pt = newExpr->result.as< ast::PointerType >() ) {
1813                                        if ( isCharType( pt->base ) ) {
[ef5b828]1814                                                // strip cast if we're initializing a char[] with a char*
[60aaa51d]1815                                                // e.g. char x[] = "hello"
1816                                                if ( auto ce = newExpr.as< ast::CastExpr >() ) {
1817                                                        swap_and_save_env( newExpr, ce->arg );
1818                                                }
1819                                        }
1820                                }
1821                        }
1822                }
1823
1824                // move cursor to next object in preparation for next initializer
1825                currentObject.increment();
1826
1827                // set initializer expression to resolved expression
1828                return ast::mutate_field( singleInit, &ast::SingleInit::value, std::move(newExpr) );
[d76c588]1829        }
1830
[60aaa51d]1831        const ast::ListInit * Resolver_new::previsit( const ast::ListInit * listInit ) {
1832                // move cursor into brace-enclosed initializer-list
1833                currentObject.enterListInit( listInit->location );
1834
1835                assert( listInit->designations.size() == listInit->initializers.size() );
1836                for ( unsigned i = 0; i < listInit->designations.size(); ++i ) {
[ef5b828]1837                        // iterate designations and initializers in pairs, moving the cursor to the current
[60aaa51d]1838                        // designated object and resolving the initializer against that object
[2d11663]1839                        listInit = ast::mutate_field_index(
[ef5b828]1840                                listInit, &ast::ListInit::designations, i,
[2d11663]1841                                currentObject.findNext( listInit->designations[i] ) );
1842                        listInit = ast::mutate_field_index(
1843                                listInit, &ast::ListInit::initializers, i,
1844                                listInit->initializers[i]->accept( *visitor ) );
[60aaa51d]1845                }
1846
[2d11663]1847                // move cursor out of brace-enclosed initializer-list
1848                currentObject.exitListInit();
1849
[60aaa51d]1850                visit_children = false;
1851                return listInit;
[d76c588]1852        }
1853
[2d11663]1854        const ast::ConstructorInit * Resolver_new::previsit( const ast::ConstructorInit * ctorInit ) {
1855                visitor->maybe_accept( ctorInit, &ast::ConstructorInit::ctor );
1856                visitor->maybe_accept( ctorInit, &ast::ConstructorInit::dtor );
1857
1858                // found a constructor - can get rid of C-style initializer
1859                // xxx - Rob suggests this field is dead code
1860                ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::init, nullptr );
1861
[ef5b828]1862                // intrinsic single-parameter constructors and destructors do nothing. Since this was
1863                // implicitly generated, there's no way for it to have side effects, so get rid of it to
[2d11663]1864                // clean up generated code
1865                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
1866                        ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::ctor, nullptr );
1867                }
1868                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
1869                        ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::dtor, nullptr );
1870                }
1871
1872                return ctorInit;
[d76c588]1873        }
1874
[51b7345]1875} // namespace ResolvExpr
[a32b204]1876
1877// Local Variables: //
1878// tab-width: 4 //
1879// mode: c++ //
1880// compile-command: "make install" //
1881// End: //
Note: See TracBrowser for help on using the repository browser.