source: src/ResolvExpr/Resolver.cc @ 55acc3a

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 55acc3a was 490fb92e, checked in by Fangren Yu <f37yu@…>, 3 years ago

move FixInit? to new ast

  • Property mode set to 100644
File size: 68.1 KB
Line 
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//
7// Resolver.cc --
8//
9// Author           : Aaron B. Moss
10// Created On       : Sun May 17 12:17:01 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Mar 27 11:58:00 2020
13// Update Count     : 242
14//
15
16#include <cassert>                       // for strict_dynamic_cast, assert
17#include <memory>                        // for allocator, allocator_traits<...
18#include <tuple>                         // for get
19#include <vector>                        // for vector
20
21#include "Alternative.h"                 // for Alternative, AltList
22#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
23#include "Candidate.hpp"
24#include "CandidateFinder.hpp"
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
31#include "AST/Chain.hpp"
32#include "AST/Decl.hpp"
33#include "AST/Init.hpp"
34#include "AST/Pass.hpp"
35#include "AST/Print.hpp"
36#include "AST/SymbolTable.hpp"
37#include "AST/Type.hpp"
38#include "Common/PassVisitor.h"          // for PassVisitor
39#include "Common/SemanticError.h"        // for SemanticError
40#include "Common/Stats/ResolveTime.h"    // for ResolveTime::start(), ResolveTime::stop()
41#include "Common/utility.h"              // for ValueGuard, group_iterate
42#include "InitTweak/GenInit.h"
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
54#include "Tuples/Tuples.h"
55#include "Validate/FindSpecialDecls.h"   // for SizeType
56
57using namespace std;
58
59namespace ResolvExpr {
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 ) {
63                        indexer = other;
64                }
65
66                void previsit( FunctionDecl * functionDecl );
67                void postvisit( FunctionDecl * functionDecl );
68                void previsit( ObjectDecl * objectDecll );
69                void previsit( EnumDecl * enumDecl );
70                void previsit( StaticAssertDecl * assertDecl );
71
72                void previsit( ArrayType * at );
73                void previsit( PointerType * at );
74
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 );
87                void postvisit( CatchStmt * catchStmt );
88                void previsit( WaitForStmt * stmt );
89
90                void previsit( SingleInit * singleInit );
91                void previsit( ListInit * listInit );
92                void previsit( ConstructorInit * ctorInit );
93          private:
94                typedef std::list< Initializer * >::iterator InitIterator;
95
96                template< typename PtrType >
97                void handlePtrType( PtrType * type );
98
99                void fallbackInit( ConstructorInit * ctorInit );
100
101                Type * functionReturn = nullptr;
102                CurrentObject currentObject = nullptr;
103                bool inEnumDecl = false;
104        };
105
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
113        void resolve( std::list< Declaration * > translationUnit ) {
114                PassVisitor<Resolver_old> resolver;
115                acceptAll( translationUnit, resolver );
116        }
117
118        void resolveDecl( Declaration * decl, const SymTab::Indexer & indexer ) {
119                PassVisitor<Resolver_old> resolver( indexer );
120                maybeAccept( decl, resolver );
121        }
122
123        namespace {
124                struct DeleteFinder_old : public WithShortCircuiting    {
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 ) {
138                PassVisitor<DeleteFinder_old> finder;
139                expr->accept( finder );
140                return finder.pass.delExpr;
141        }
142
143        namespace {
144                struct StripCasts_old {
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 ) {
157                                PassVisitor<StripCasts_old> stripper;
158                                expr = expr->acceptMutator( stripper );
159                        }
160                };
161
162                void finishExpr( Expression *& expr, const TypeEnvironment & env, TypeSubstitution * oldenv = nullptr ) {
163                        expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
164                        env.makeSubstitution( *expr->env );
165                        StripCasts_old::strip( expr ); // remove unnecessary casts that may be buried in an expression
166                }
167
168                void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
169                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
170                                if ( typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
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                }
179        } // namespace
180
181        namespace {
182                void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
183                        assertf( untyped, "expected a non-null expression." );
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;
189                        TypeEnvironment env;
190                        AlternativeFinder finder( indexer, env );
191                        finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
192                        --recursion_level;
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
204
205                        // produce filtered list of alternatives
206                        AltList candidates;
207                        for ( Alternative & alt : finder.get_alternatives() ) {
208                                if ( pred( alt ) ) {
209                                        candidates.push_back( std::move( alt ) );
210                                }
211                        }
212
213                        // produce invalid error if no candidates
214                        if ( candidates.empty() ) {
215                                SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
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
241                                winners.emplace_back( std::move( candidates[i] ) );
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                        }
249
250                        // produce ambiguous errors, if applicable
251                        if ( winners.size() != 1 ) {
252                                std::ostringstream stream;
253                                stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
254                                untyped->print( stream );
255                                stream << " Alternatives are:\n";
256                                printAlts( winners, stream, 1 );
257                                SemanticError( untyped->location, stream.str() );
258                        }
259
260                        // single selected choice
261                        Alternative& choice = winners.front();
262
263                        // fail on only expression deleted
264                        if ( ! seen_undeleted ) {
265                                SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
266                        }
267
268                        // xxx - check for ambiguous expressions
269
270                        // output selected choice
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
275                void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
276                        if ( ! untyped ) return;
277                        Alternative choice;
278                        findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
279                        finishExpr( choice.expr, choice.env, untyped->env );
280                        delete untyped;
281                        untyped = choice.expr;
282                        choice.expr = nullptr;
283                }
284
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
293        Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer ) {
294                TypeEnvironment env;
295                return resolveInVoidContext( expr, indexer, env );
296        }
297
298        Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer, TypeEnvironment & env ) {
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
303                CastExpr * untyped = new CastExpr( expr ); // cast to void
304                untyped->location = expr->location;
305
306                // set up and resolve expression cast to void
307                Alternative choice;
308                findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
309                CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
310                assert( castExpr );
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
318                untyped->arg = nullptr;
319                return ret;
320        }
321
322        void findVoidExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
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
331        void findSingleExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
332                findKindExpression( untyped, indexer, "", standardAlternativeFilter );
333        }
334
335        void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
336                assert( untyped && type );
337                // transfer location to generated cast for error purposes
338                CodeLocation location = untyped->location;
339                untyped = new CastExpr( untyped, type );
340                untyped->location = location;
341                findSingleExpression( untyped, indexer );
342                removeExtraneousCast( untyped, indexer );
343        }
344
345        namespace {
346                bool isIntegralType( const Alternative & alt ) {
347                        Type * type = alt.expr->result;
348                        if ( dynamic_cast< EnumInstType * >( type ) ) {
349                                return true;
350                        } else if ( BasicType * bt = dynamic_cast< BasicType * >( type ) ) {
351                                return bt->isInteger();
352                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
353                                return true;
354                        } else {
355                                return false;
356                        } // if
357                }
358
359                void findIntegralExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
360                        findKindExpression( untyped, indexer, "condition", isIntegralType );
361                }
362        }
363
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
415        void Resolver_old::previsit( ObjectDecl * objectDecl ) {
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
420                // retained, so the type on the first analysis is preserved and used for selecting the RHS.
421                GuardValue( currentObject );
422                currentObject = CurrentObject( objectDecl->get_type() );
423                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
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.
426                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
427                }
428        }
429
430        template< typename PtrType >
431        void Resolver_old::handlePtrType( PtrType * type ) {
432                if ( type->get_dimension() ) {
433                        findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
434                }
435        }
436
437        void Resolver_old::previsit( ArrayType * at ) {
438                handlePtrType( at );
439        }
440
441        void Resolver_old::previsit( PointerType * pt ) {
442                handlePtrType( pt );
443        }
444
445        void Resolver_old::previsit( FunctionDecl * functionDecl ) {
446#if 0
447                std::cerr << "resolver visiting functiondecl ";
448                functionDecl->print( std::cerr );
449                std::cerr << std::endl;
450#endif
451                GuardValue( functionReturn );
452                functionReturn = ResolvExpr::extractResultType( functionDecl->type );
453        }
454
455        void Resolver_old::postvisit( FunctionDecl * functionDecl ) {
456                // default value expressions have an environment which shouldn't be there and trips up
457                // later passes.
458                // xxx - it might be necessary to somehow keep the information from this environment, but I
459                // can't currently see how it's useful.
460                for ( Declaration * d : functionDecl->type->parameters ) {
461                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
462                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
463                                        delete init->value->env;
464                                        init->value->env = nullptr;
465                                }
466                        }
467                }
468        }
469
470        void Resolver_old::previsit( EnumDecl * ) {
471                // in case we decide to allow nested enums
472                GuardValue( inEnumDecl );
473                inEnumDecl = true;
474        }
475
476        void Resolver_old::previsit( StaticAssertDecl * assertDecl ) {
477                findIntegralExpression( assertDecl->condition, indexer );
478        }
479
480        void Resolver_old::previsit( ExprStmt * exprStmt ) {
481                visit_children = false;
482                assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
483                findVoidExpression( exprStmt->expr, indexer );
484        }
485
486        void Resolver_old::previsit( AsmExpr * asmExpr ) {
487                visit_children = false;
488                findVoidExpression( asmExpr->operand, indexer );
489        }
490
491        void Resolver_old::previsit( AsmStmt * asmStmt ) {
492                visit_children = false;
493                acceptAll( asmStmt->get_input(), *visitor );
494                acceptAll( asmStmt->get_output(), *visitor );
495        }
496
497        void Resolver_old::previsit( IfStmt * ifStmt ) {
498                findIntegralExpression( ifStmt->condition, indexer );
499        }
500
501        void Resolver_old::previsit( WhileStmt * whileStmt ) {
502                findIntegralExpression( whileStmt->condition, indexer );
503        }
504
505        void Resolver_old::previsit( ForStmt * forStmt ) {
506                if ( forStmt->condition ) {
507                        findIntegralExpression( forStmt->condition, indexer );
508                } // if
509
510                if ( forStmt->increment ) {
511                        findVoidExpression( forStmt->increment, indexer );
512                } // if
513        }
514
515        void Resolver_old::previsit( SwitchStmt * switchStmt ) {
516                GuardValue( currentObject );
517                findIntegralExpression( switchStmt->condition, indexer );
518
519                currentObject = CurrentObject( switchStmt->condition->result );
520        }
521
522        void Resolver_old::previsit( CaseStmt * caseStmt ) {
523                if ( caseStmt->condition ) {
524                        std::list< InitAlternative > initAlts = currentObject.getOptions();
525                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
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 );
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;
538                }
539        }
540
541        void Resolver_old::previsit( BranchStmt * branchStmt ) {
542                visit_children = false;
543                // must resolve the argument for a computed goto
544                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
545                        if ( branchStmt->computedTarget ) {
546                                // computed goto argument is void *
547                                findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
548                        } // if
549                } // if
550        }
551
552        void Resolver_old::previsit( ReturnStmt * returnStmt ) {
553                visit_children = false;
554                if ( returnStmt->expr ) {
555                        findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
556                } // if
557        }
558
559        void Resolver_old::previsit( ThrowStmt * throwStmt ) {
560                visit_children = false;
561                // TODO: Replace *exception type with &exception type.
562                if ( throwStmt->get_expr() ) {
563                        const StructDecl * exception_decl = indexer.lookupStruct( "__cfaehm_base_exception_t" );
564                        assert( exception_decl );
565                        Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, const_cast<StructDecl *>(exception_decl) ) );
566                        findSingleExpression( throwStmt->expr, exceptType, indexer );
567                }
568        }
569
570        void Resolver_old::previsit( CatchStmt * catchStmt ) {
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.
577                if ( catchStmt->cond ) {
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;
595                }
596        }
597
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
607        void Resolver_old::previsit( WaitForStmt * stmt ) {
608                visit_children = false;
609
610                // Resolve all clauses first
611                for( auto& clause : stmt->clauses ) {
612
613                        TypeEnvironment env;
614                        AlternativeFinder funcFinder( indexer, env );
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";
624                                SemanticError( stmt->location, ss.str() );
625                        }
626
627                        if(clause.target.arguments.empty()) {
628                                SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
629                        }
630
631                        // Find all alternatives for all arguments in canonical form
632                        std::vector< AlternativeFinder > argAlternatives;
633                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
634
635                        // List all combinations of arguments
636                        std::vector< AltList > possibilities;
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
645                        SemanticErrorException errors;
646                        for ( Alternative & func : funcFinder.get_alternatives() ) {
647                                try {
648                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
649                                        if( !pointer ) {
650                                                SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
651                                        }
652
653                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
654                                        if( !function ) {
655                                                SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
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 ) ) {
664                                                        SemanticError(function, "candidate function not viable: no mutex parameters\n");
665                                                }
666                                        }
667
668                                        Alternative newFunc( func );
669                                        // Strip reference from function
670                                        referenceToRvalueConversion( newFunc.expr, newFunc.cost );
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;
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 );
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
689                                                        resultEnv.forbidWidening();
690
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
697                                                        int n_mutex_param = 0;
698
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
707                                                                        SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
708                                                                }
709
710                                                                n_mutex_param++;
711
712                                                                // Check if the argument matches the parameter type in the current scope
713                                                                if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
714                                                                        // Type doesn't match
715                                                                        stringstream ss;
716                                                                        ss << "candidate function not viable: no known convertion from '";
717                                                                        (*param)->get_type()->print( ss );
718                                                                        ss << "' to '";
719                                                                        arg.expr->get_result()->print( ss );
720                                                                        ss << "' with env '";
721                                                                        resultEnv.print(ss);
722                                                                        ss << "'\n";
723                                                                        SemanticError( function, ss.str() );
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 ) ) {
733                                                                do {
734                                                                        n_mutex_param++;
735                                                                        param++;
736                                                                } while( advance_to_mutex( param, param_end ) );
737
738                                                                // We ran out of arguments but still have parameters left
739                                                                // this function doesn't match
740                                                                SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
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                                                }
756                                                catch( SemanticErrorException & e ) {
757                                                        errors.append( e );
758                                                }
759                                        }
760                                }
761                                catch( SemanticErrorException & e ) {
762                                        errors.append( e );
763                                }
764                        }
765
766                        // Make sure we got the right number of arguments
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; }
771                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
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
782                        findSingleExpression( clause.condition, this->indexer );
783                        clause.statement->accept( *visitor );
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
791                        findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
792                        findSingleExpression( stmt->timeout.condition, this->indexer );
793                        stmt->timeout.statement->accept( *visitor );
794                }
795
796                if( stmt->orelse.statement ) {
797                        // Resolve the conditions as if it were an IfStmt
798                        // Resolve the statments normally
799                        findSingleExpression( stmt->orelse.condition, this->indexer );
800                        stmt->orelse.statement->accept( *visitor );
801                }
802        }
803
804        bool isCharType( Type * t ) {
805                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
806                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
807                                bt->get_kind() == BasicType::UnsignedChar;
808                }
809                return false;
810        }
811
812        void Resolver_old::previsit( SingleInit * singleInit ) {
813                visit_children = false;
814                // resolve initialization using the possibilities as determined by the currentObject cursor
815                Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
816                findSingleExpression( newExpr, indexer );
817                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
818
819                // move cursor to the object that is actually initialized
820                currentObject.setNext( initExpr->get_designation() );
821
822                // discard InitExpr wrapper and retain relevant pieces
823                newExpr = initExpr->expr;
824                initExpr->expr = nullptr;
825                std::swap( initExpr->env, newExpr->env );
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
828                // sufficient.
829                newExpr->spliceInferParams( initExpr );
830                delete initExpr;
831
832                // get the actual object's type (may not exactly match what comes back from the resolver
833                // due to conversions)
834                Type * initContext = currentObject.getCurrentType();
835
836                removeExtraneousCast( newExpr, indexer );
837
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() ) ) {
844                                                if ( CastExpr * ce = dynamic_cast< CastExpr * >( newExpr ) ) {
845                                                        // strip cast if we're initializing a char[] with a char *,
846                                                        // e.g.  char x[] = "hello";
847                                                        newExpr = ce->get_arg();
848                                                        ce->set_arg( nullptr );
849                                                        std::swap( ce->env, newExpr->env );
850                                                        delete ce;
851                                                }
852                                        }
853                                }
854                        }
855                }
856
857                // set initializer expr to resolved express
858                singleInit->value = newExpr;
859
860                // move cursor to next object in preparation for next initializer
861                currentObject.increment();
862        }
863
864        void Resolver_old::previsit( ListInit * listInit ) {
865                visit_children = false;
866                // move cursor into brace-enclosed initializer-list
867                currentObject.enterListInit();
868                // xxx - fix this so that the list isn't copied, iterator should be used to change current
869                // element
870                std::list<Designation *> newDesignations;
871                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
872                        // iterate designations and initializers in pairs, moving the cursor to the current
873                        // designated object and resolving the initializer against that object.
874                        Designation * des = std::get<0>(p);
875                        Initializer * init = std::get<1>(p);
876                        newDesignations.push_back( currentObject.findNext( des ) );
877                        init->accept( *visitor );
878                }
879                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
880                listInit->get_designations() = newDesignations; // xxx - memory management
881                currentObject.exitListInit();
882
883                // xxx - this part has not be folded into CurrentObject yet
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 {
896        }
897
898        // ConstructorInit - fall back on C-style initializer
899        void Resolver_old::fallbackInit( ConstructorInit * ctorInit ) {
900                // could not find valid constructor, or found an intrinsic constructor
901                // fall back on C-style initializer
902                delete ctorInit->get_ctor();
903                ctorInit->set_ctor( nullptr );
904                delete ctorInit->get_dtor();
905                ctorInit->set_dtor( nullptr );
906                maybeAccept( ctorInit->get_init(), *visitor );
907        }
908
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 );
912                PassVisitor<Resolver_old> resolver( indexer );
913                ctorInit->accept( resolver );
914        }
915
916        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
917                assert( stmtExpr );
918                PassVisitor<Resolver_old> resolver( indexer );
919                stmtExpr->accept( resolver );
920                stmtExpr->computeResult();
921                // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
922        }
923
924        void Resolver_old::previsit( ConstructorInit * ctorInit ) {
925                visit_children = false;
926                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
927                maybeAccept( ctorInit->ctor, *visitor );
928                maybeAccept( ctorInit->dtor, *visitor );
929
930                // found a constructor - can get rid of C-style initializer
931                delete ctorInit->init;
932                ctorInit->init = nullptr;
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.
937                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
938                        delete ctorInit->ctor;
939                        ctorInit->ctor = nullptr;
940                }
941
942                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
943                        delete ctorInit->dtor;
944                        ctorInit->dtor = nullptr;
945                }
946
947                // xxx - todo -- what about arrays?
948                // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
949                //      // can reduce the constructor down to a SingleInit using the
950                //      // second argument from the ctor call, since
951                //      delete ctorInit->get_ctor();
952                //      ctorInit->set_ctor( nullptr );
953
954                //      Expression * arg =
955                //      ctorInit->set_init( new SingleInit( arg ) );
956                // }
957        }
958
959        ///////////////////////////////////////////////////////////////////////////
960        //
961        // *** NEW RESOLVER ***
962        //
963        ///////////////////////////////////////////////////////////////////////////
964
965        namespace {
966                /// Finds deleted expressions in an expression tree
967                struct DeleteFinder_new final : public ast::WithShortCircuiting {
968                        const ast::DeletedExpr * result = nullptr;
969
970                        void previsit( const ast::DeletedExpr * expr ) {
971                                if ( result ) { visit_children = false; }
972                                else { result = expr; }
973                        }
974
975                        void previsit( const ast::Expr * ) {
976                                if ( result ) { visit_children = false; }
977                        }
978                };
979        } // anonymous namespace
980
981        /// Check if this expression is or includes a deleted expression
982        const ast::DeletedExpr * findDeletedExpr( const ast::Expr * expr ) {
983                return ast::Pass<DeleteFinder_new>::read( expr );
984        }
985
986        namespace {
987                /// always-accept candidate filter
988                bool anyCandidate( const Candidate & ) { return true; }
989
990                /// Calls the CandidateFinder and finds the single best candidate
991                CandidateRef findUnfinishedKindExpression(
992                        const ast::Expr * untyped, const ast::SymbolTable & symtab, const std::string & kind,
993                        std::function<bool(const Candidate &)> pred = anyCandidate, ResolvMode mode = {}
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() ) {
1014                                SemanticError( untyped,
1015                                        toString( "No reasonable alternatives for ", kind, (kind != "" ? " " : ""),
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
1046                        promoteCvtCost( winners );
1047
1048                        // produce ambiguous errors, if applicable
1049                        if ( winners.size() != 1 ) {
1050                                std::ostringstream stream;
1051                                stream << "Cannot choose between " << winners.size() << " alternatives for "
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 {
1073                        const ast::Expr * postvisit( const ast::CastExpr * castExpr ) {
1074                                if (
1075                                        castExpr->isGenerated == ast::GeneratedCast
1076                                        && typesCompatible( castExpr->arg->result, castExpr->result )
1077                                ) {
1078                                        // generated cast is the same type as its argument, remove it after keeping env
1079                                        return ast::mutate_field(
1080                                                castExpr->arg.get(), &ast::Expr::env, castExpr->env );
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
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
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
1102                                        swap_and_save_env( expr, castExpr->arg );
1103                                }
1104                        }
1105                }
1106
1107               
1108        } // anonymous namespace
1109/// Establish post-resolver invariants for expressions
1110                void finishExpr(
1111                        ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env,
1112                        const ast::TypeSubstitution * oldenv = nullptr
1113                ) {
1114                        // set up new type substitution for expression
1115                        ast::ptr< ast::TypeSubstitution > newenv =
1116                                 oldenv ? oldenv : new ast::TypeSubstitution{};
1117                        env.writeToSubstitution( *newenv.get_and_mutate() );
1118                        expr.get_and_mutate()->env = std::move( newenv );
1119                        // remove unncecessary casts
1120                        StripCasts_new::strip( expr );
1121                }
1122
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" );
1127
1128                // set up and resolve expression cast to void
1129                ast::ptr< ast::CastExpr > untyped = new ast::CastExpr{ expr };
1130                CandidateRef choice = findUnfinishedKindExpression(
1131                        untyped, symtab, "", anyCandidate, ResolvMode::withAdjustment() );
1132
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        }
1140
1141        /// Resolve `untyped` to the expression whose candidate is the best match for a `void`
1142                /// context.
1143                ast::ptr< ast::Expr > findVoidExpression(
1144                        const ast::Expr * untyped, const ast::SymbolTable & symtab
1145                ) {
1146                        resetTyVarRenaming();
1147                        ast::TypeEnvironment env;
1148                        ast::ptr< ast::Expr > newExpr = resolveInVoidContext( untyped, symtab, env );
1149                        finishExpr( newExpr, env, untyped->env );
1150                        return newExpr;
1151                }
1152
1153        namespace {
1154               
1155
1156                /// resolve `untyped` to the expression whose candidate satisfies `pred` with the
1157                /// lowest cost, returning the resolved version
1158                ast::ptr< ast::Expr > findKindExpression(
1159                        const ast::Expr * untyped, const ast::SymbolTable & symtab,
1160                        std::function<bool(const Candidate &)> pred = anyCandidate,
1161                        const std::string & kind = "", ResolvMode mode = {}
1162                ) {
1163                        if ( ! untyped ) return {};
1164                        CandidateRef choice =
1165                                findUnfinishedKindExpression( untyped, symtab, kind, pred, mode );
1166                        ResolvExpr::finishExpr( choice->expr, choice->env, untyped->env );
1167                        return std::move( choice->expr );
1168                }
1169
1170                /// Resolve `untyped` to the single expression whose candidate is the best match
1171                ast::ptr< ast::Expr > findSingleExpression(
1172                        const ast::Expr * untyped, const ast::SymbolTable & symtab
1173                ) {
1174                        Stats::ResolveTime::start( untyped );
1175                        auto res = findKindExpression( untyped, symtab );
1176                        Stats::ResolveTime::stop();
1177                        return res;
1178                }
1179        } // anonymous namespace
1180
1181                ast::ptr< ast::Expr > findSingleExpression(
1182                        const ast::Expr * untyped, const ast::Type * type, const ast::SymbolTable & symtab
1183                ) {
1184                        assert( untyped && type );
1185                        ast::ptr< ast::Expr > castExpr = new ast::CastExpr{ untyped, type };
1186                        ast::ptr< ast::Expr > newExpr = findSingleExpression( castExpr, symtab );
1187                        removeExtraneousCast( newExpr, symtab );
1188                        return newExpr;
1189                }
1190
1191        namespace {
1192                /// Predicate for "Candidate has integral type"
1193                bool hasIntegralType( const Candidate & i ) {
1194                        const ast::Type * type = i.expr->result;
1195
1196                        if ( auto bt = dynamic_cast< const ast::BasicType * >( type ) ) {
1197                                return bt->isInteger();
1198                        } else if (
1199                                dynamic_cast< const ast::EnumInstType * >( type )
1200                                || dynamic_cast< const ast::ZeroType * >( type )
1201                                || dynamic_cast< const ast::OneType * >( type )
1202                        ) {
1203                                return true;
1204                        } else return false;
1205                }
1206
1207                /// Resolve `untyped` as an integral expression, returning the resolved version
1208                ast::ptr< ast::Expr > findIntegralExpression(
1209                        const ast::Expr * untyped, const ast::SymbolTable & symtab
1210                ) {
1211                        return findKindExpression( untyped, symtab, hasIntegralType, "condition" );
1212                }
1213
1214                /// check if a type is a character type
1215                bool isCharType( const ast::Type * t ) {
1216                        if ( auto bt = dynamic_cast< const ast::BasicType * >( t ) ) {
1217                                return bt->kind == ast::BasicType::Char
1218                                        || bt->kind == ast::BasicType::SignedChar
1219                                        || bt->kind == ast::BasicType::UnsignedChar;
1220                        }
1221                        return false;
1222                }
1223
1224                /// Advance a type itertor to the next mutex parameter
1225                template<typename Iter>
1226                inline bool nextMutex( Iter & it, const Iter & end ) {
1227                        while ( it != end && ! (*it)->is_mutex() ) { ++it; }
1228                        return it != end;
1229                }
1230        }
1231
1232        class Resolver_new final
1233        : public ast::WithSymbolTable, public ast::WithGuards,
1234          public ast::WithVisitorRef<Resolver_new>, public ast::WithShortCircuiting,
1235          public ast::WithStmtsToAdd<> {
1236
1237                ast::ptr< ast::Type > functionReturn = nullptr;
1238                ast::CurrentObject currentObject;
1239                bool inEnumDecl = false;
1240
1241        public:
1242                static size_t traceId;
1243                Resolver_new() = default;
1244                Resolver_new( const ast::SymbolTable & syms ) { symtab = syms; }
1245
1246                void previsit( const ast::FunctionDecl * );
1247                const ast::FunctionDecl * postvisit( const ast::FunctionDecl * );
1248                void previsit( const ast::ObjectDecl * );
1249                void previsit( const ast::EnumDecl * );
1250                const ast::StaticAssertDecl * previsit( const ast::StaticAssertDecl * );
1251
1252                const ast::ArrayType * previsit( const ast::ArrayType * );
1253                const ast::PointerType * previsit( const ast::PointerType * );
1254
1255                const ast::ExprStmt *        previsit( const ast::ExprStmt * );
1256                const ast::AsmExpr *         previsit( const ast::AsmExpr * );
1257                const ast::AsmStmt *         previsit( const ast::AsmStmt * );
1258                const ast::IfStmt *          previsit( const ast::IfStmt * );
1259                const ast::WhileStmt *       previsit( const ast::WhileStmt * );
1260                const ast::ForStmt *         previsit( const ast::ForStmt * );
1261                const ast::SwitchStmt *      previsit( const ast::SwitchStmt * );
1262                const ast::CaseStmt *        previsit( const ast::CaseStmt * );
1263                const ast::BranchStmt *      previsit( const ast::BranchStmt * );
1264                const ast::ReturnStmt *      previsit( const ast::ReturnStmt * );
1265                const ast::ThrowStmt *       previsit( const ast::ThrowStmt * );
1266                const ast::CatchStmt *       previsit( const ast::CatchStmt * );
1267                const ast::CatchStmt *       postvisit( const ast::CatchStmt * );
1268                const ast::WaitForStmt *     previsit( const ast::WaitForStmt * );
1269
1270                const ast::SingleInit *      previsit( const ast::SingleInit * );
1271                const ast::ListInit *        previsit( const ast::ListInit * );
1272                const ast::ConstructorInit * previsit( const ast::ConstructorInit * );
1273        };
1274        // size_t Resolver_new::traceId = Stats::Heap::new_stacktrace_id("Resolver");
1275
1276        void resolve( std::list< ast::ptr< ast::Decl > >& translationUnit ) {
1277                ast::Pass< Resolver_new >::run( translationUnit );
1278        }
1279
1280        ast::ptr< ast::Init > resolveCtorInit(
1281                const ast::ConstructorInit * ctorInit, const ast::SymbolTable & symtab
1282        ) {
1283                assert( ctorInit );
1284                ast::Pass< Resolver_new > resolver{ symtab };
1285                return ctorInit->accept( resolver );
1286        }
1287
1288        ast::ptr< ast::Expr > resolveStmtExpr(
1289                const ast::StmtExpr * stmtExpr, const ast::SymbolTable & symtab
1290        ) {
1291                assert( stmtExpr );
1292                ast::Pass< Resolver_new > resolver{ symtab };
1293                ast::ptr< ast::Expr > ret = stmtExpr;
1294                ret = ret->accept( resolver );
1295                strict_dynamic_cast< ast::StmtExpr * >( ret.get_and_mutate() )->computeResult();
1296                return ret;
1297        }
1298
1299        void Resolver_new::previsit( const ast::FunctionDecl * functionDecl ) {
1300                GuardValue( functionReturn );
1301                functionReturn = extractResultType( functionDecl->type );
1302        }
1303
1304        const ast::FunctionDecl * Resolver_new::postvisit( const ast::FunctionDecl * functionDecl ) {
1305                // default value expressions have an environment which shouldn't be there and trips up
1306                // later passes.
1307                assert( functionDecl->unique() );
1308                ast::FunctionType * mutType = mutate( functionDecl->type.get() );
1309
1310                for ( unsigned i = 0 ; i < mutType->params.size() ; ++i ) {
1311                        if ( const ast::ObjectDecl * obj = mutType->params[i].as< ast::ObjectDecl >() ) {
1312                                if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) {
1313                                        if ( init->value->env == nullptr ) continue;
1314                                        // clone initializer minus the initializer environment
1315                                        auto mutParam = mutate( mutType->params[i].strict_as< ast::ObjectDecl >() );
1316                                        auto mutInit = mutate( mutParam->init.strict_as< ast::SingleInit >() );
1317                                        auto mutValue = mutate( mutInit->value.get() );
1318
1319                                        mutValue->env = nullptr;
1320                                        mutInit->value = mutValue;
1321                                        mutParam->init = mutInit;
1322                                        mutType->params[i] = mutParam;
1323
1324                                        assert( ! mutType->params[i].strict_as< ast::ObjectDecl >()->init.strict_as< ast::SingleInit >()->value->env);
1325                                }
1326                        }
1327                }
1328                mutate_field(functionDecl, &ast::FunctionDecl::type, mutType);
1329                return functionDecl;
1330        }
1331
1332        void Resolver_new::previsit( const ast::ObjectDecl * objectDecl ) {
1333                // To handle initialization of routine pointers [e.g. int (*fp)(int) = foo()],
1334                // class-variable `initContext` is changed multiple times because the LHS is analyzed
1335                // twice. The second analysis changes `initContext` because a function type can contain
1336                // object declarations in the return and parameter types. Therefore each value of
1337                // `initContext` is retained so the type on the first analysis is preserved and used for
1338                // selecting the RHS.
1339                GuardValue( currentObject );
1340                currentObject = ast::CurrentObject{ objectDecl->location, objectDecl->get_type() };
1341                if ( inEnumDecl && dynamic_cast< const ast::EnumInstType * >( objectDecl->get_type() ) ) {
1342                        // enumerator initializers should not use the enum type to initialize, since the
1343                        // enum type is still incomplete at this point. Use `int` instead.
1344                        currentObject = ast::CurrentObject{
1345                                objectDecl->location, new ast::BasicType{ ast::BasicType::SignedInt } };
1346                }
1347        }
1348
1349        void Resolver_new::previsit( const ast::EnumDecl * ) {
1350                // in case we decide to allow nested enums
1351                GuardValue( inEnumDecl );
1352                inEnumDecl = true;
1353        }
1354
1355        const ast::StaticAssertDecl * Resolver_new::previsit(
1356                const ast::StaticAssertDecl * assertDecl
1357        ) {
1358                return ast::mutate_field(
1359                        assertDecl, &ast::StaticAssertDecl::cond,
1360                        findIntegralExpression( assertDecl->cond, symtab ) );
1361        }
1362
1363        template< typename PtrType >
1364        const PtrType * handlePtrType( const PtrType * type, const ast::SymbolTable & symtab ) {
1365                if ( type->dimension ) {
1366                        #warning should use new equivalent to Validate::SizeType rather than sizeType here
1367                        ast::ptr< ast::Type > sizeType = new ast::BasicType{ ast::BasicType::LongUnsignedInt };
1368                        ast::mutate_field(
1369                                type, &PtrType::dimension,
1370                                findSingleExpression( type->dimension, sizeType, symtab ) );
1371                }
1372                return type;
1373        }
1374
1375        const ast::ArrayType * Resolver_new::previsit( const ast::ArrayType * at ) {
1376                return handlePtrType( at, symtab );
1377        }
1378
1379        const ast::PointerType * Resolver_new::previsit( const ast::PointerType * pt ) {
1380                return handlePtrType( pt, symtab );
1381        }
1382
1383        const ast::ExprStmt * Resolver_new::previsit( const ast::ExprStmt * exprStmt ) {
1384                visit_children = false;
1385                assertf( exprStmt->expr, "ExprStmt has null expression in resolver" );
1386
1387                return ast::mutate_field(
1388                        exprStmt, &ast::ExprStmt::expr, findVoidExpression( exprStmt->expr, symtab ) );
1389        }
1390
1391        const ast::AsmExpr * Resolver_new::previsit( const ast::AsmExpr * asmExpr ) {
1392                visit_children = false;
1393
1394                asmExpr = ast::mutate_field(
1395                        asmExpr, &ast::AsmExpr::operand, findVoidExpression( asmExpr->operand, symtab ) );
1396
1397                return asmExpr;
1398        }
1399
1400        const ast::AsmStmt * Resolver_new::previsit( const ast::AsmStmt * asmStmt ) {
1401                visitor->maybe_accept( asmStmt, &ast::AsmStmt::input );
1402                visitor->maybe_accept( asmStmt, &ast::AsmStmt::output );
1403                visit_children = false;
1404                return asmStmt;
1405        }
1406
1407        const ast::IfStmt * Resolver_new::previsit( const ast::IfStmt * ifStmt ) {
1408                return ast::mutate_field(
1409                        ifStmt, &ast::IfStmt::cond, findIntegralExpression( ifStmt->cond, symtab ) );
1410        }
1411
1412        const ast::WhileStmt * Resolver_new::previsit( const ast::WhileStmt * whileStmt ) {
1413                return ast::mutate_field(
1414                        whileStmt, &ast::WhileStmt::cond, findIntegralExpression( whileStmt->cond, symtab ) );
1415        }
1416
1417        const ast::ForStmt * Resolver_new::previsit( const ast::ForStmt * forStmt ) {
1418                if ( forStmt->cond ) {
1419                        forStmt = ast::mutate_field(
1420                                forStmt, &ast::ForStmt::cond, findIntegralExpression( forStmt->cond, symtab ) );
1421                }
1422
1423                if ( forStmt->inc ) {
1424                        forStmt = ast::mutate_field(
1425                                forStmt, &ast::ForStmt::inc, findVoidExpression( forStmt->inc, symtab ) );
1426                }
1427
1428                return forStmt;
1429        }
1430
1431        const ast::SwitchStmt * Resolver_new::previsit( const ast::SwitchStmt * switchStmt ) {
1432                GuardValue( currentObject );
1433                switchStmt = ast::mutate_field(
1434                        switchStmt, &ast::SwitchStmt::cond,
1435                        findIntegralExpression( switchStmt->cond, symtab ) );
1436                currentObject = ast::CurrentObject{ switchStmt->location, switchStmt->cond->result };
1437                return switchStmt;
1438        }
1439
1440        const ast::CaseStmt * Resolver_new::previsit( const ast::CaseStmt * caseStmt ) {
1441                if ( caseStmt->cond ) {
1442                        std::deque< ast::InitAlternative > initAlts = currentObject.getOptions();
1443                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral "
1444                                "expression." );
1445
1446                        ast::ptr< ast::Expr > untyped =
1447                                new ast::CastExpr{ caseStmt->location, caseStmt->cond, initAlts.front().type };
1448                        ast::ptr< ast::Expr > newExpr = findSingleExpression( untyped, symtab );
1449
1450                        // case condition cannot have a cast in C, so it must be removed here, regardless of
1451                        // whether it would perform a conversion.
1452                        if ( const ast::CastExpr * castExpr = newExpr.as< ast::CastExpr >() ) {
1453                                swap_and_save_env( newExpr, castExpr->arg );
1454                        }
1455
1456                        caseStmt = ast::mutate_field( caseStmt, &ast::CaseStmt::cond, newExpr );
1457                }
1458                return caseStmt;
1459        }
1460
1461        const ast::BranchStmt * Resolver_new::previsit( const ast::BranchStmt * branchStmt ) {
1462                visit_children = false;
1463                // must resolve the argument of a computed goto
1464                if ( branchStmt->kind == ast::BranchStmt::Goto && branchStmt->computedTarget ) {
1465                        // computed goto argument is void*
1466                        ast::ptr< ast::Type > target = new ast::PointerType{ new ast::VoidType{} };
1467                        branchStmt = ast::mutate_field(
1468                                branchStmt, &ast::BranchStmt::computedTarget,
1469                                findSingleExpression( branchStmt->computedTarget, target, symtab ) );
1470                }
1471                return branchStmt;
1472        }
1473
1474        const ast::ReturnStmt * Resolver_new::previsit( const ast::ReturnStmt * returnStmt ) {
1475                visit_children = false;
1476                if ( returnStmt->expr ) {
1477                        returnStmt = ast::mutate_field(
1478                                returnStmt, &ast::ReturnStmt::expr,
1479                                findSingleExpression( returnStmt->expr, functionReturn, symtab ) );
1480                }
1481                return returnStmt;
1482        }
1483
1484        const ast::ThrowStmt * Resolver_new::previsit( const ast::ThrowStmt * throwStmt ) {
1485                visit_children = false;
1486                if ( throwStmt->expr ) {
1487                        const ast::StructDecl * exceptionDecl =
1488                                symtab.lookupStruct( "__cfaehm_base_exception_t" );
1489                        assert( exceptionDecl );
1490                        ast::ptr< ast::Type > exceptType =
1491                                new ast::PointerType{ new ast::StructInstType{ exceptionDecl } };
1492                        throwStmt = ast::mutate_field(
1493                                throwStmt, &ast::ThrowStmt::expr,
1494                                findSingleExpression( throwStmt->expr, exceptType, symtab ) );
1495                }
1496                return throwStmt;
1497        }
1498
1499        const ast::CatchStmt * Resolver_new::previsit( const ast::CatchStmt * catchStmt ) {
1500                // Until we are very sure this invarent (ifs that move between passes have thenPart)
1501                // holds, check it. This allows a check for when to decode the mangling.
1502                if ( auto ifStmt = catchStmt->body.as<ast::IfStmt>() ) {
1503                        assert( ifStmt->thenPart );
1504                }
1505                // Encode the catchStmt so the condition can see the declaration.
1506                if ( catchStmt->cond ) {
1507                        ast::CatchStmt * stmt = mutate( catchStmt );
1508                        stmt->body = new ast::IfStmt( stmt->location, stmt->cond, nullptr, stmt->body );
1509                        stmt->cond = nullptr;
1510                        return stmt;
1511                }
1512                return catchStmt;
1513        }
1514
1515        const ast::CatchStmt * Resolver_new::postvisit( const ast::CatchStmt * catchStmt ) {
1516                // Decode the catchStmt so everything is stored properly.
1517                const ast::IfStmt * ifStmt = catchStmt->body.as<ast::IfStmt>();
1518                if ( nullptr != ifStmt && nullptr == ifStmt->thenPart ) {
1519                        assert( ifStmt->cond );
1520                        assert( ifStmt->elsePart );
1521                        ast::CatchStmt * stmt = ast::mutate( catchStmt );
1522                        stmt->cond = ifStmt->cond;
1523                        stmt->body = ifStmt->elsePart;
1524                        // ifStmt should be implicately deleted here.
1525                        return stmt;
1526                }
1527                return catchStmt;
1528        }
1529
1530        const ast::WaitForStmt * Resolver_new::previsit( const ast::WaitForStmt * stmt ) {
1531                visit_children = false;
1532
1533                // Resolve all clauses first
1534                for ( unsigned i = 0; i < stmt->clauses.size(); ++i ) {
1535                        const ast::WaitForStmt::Clause & clause = stmt->clauses[i];
1536
1537                        ast::TypeEnvironment env;
1538                        CandidateFinder funcFinder{ symtab, env };
1539
1540                        // Find all candidates for a function in canonical form
1541                        funcFinder.find( clause.target.func, ResolvMode::withAdjustment() );
1542
1543                        if ( funcFinder.candidates.empty() ) {
1544                                stringstream ss;
1545                                ss << "Use of undeclared indentifier '";
1546                                ss << clause.target.func.strict_as< ast::NameExpr >()->name;
1547                                ss << "' in call to waitfor";
1548                                SemanticError( stmt->location, ss.str() );
1549                        }
1550
1551                        if ( clause.target.args.empty() ) {
1552                                SemanticError( stmt->location,
1553                                        "Waitfor clause must have at least one mutex parameter");
1554                        }
1555
1556                        // Find all alternatives for all arguments in canonical form
1557                        std::vector< CandidateFinder > argFinders =
1558                                funcFinder.findSubExprs( clause.target.args );
1559
1560                        // List all combinations of arguments
1561                        std::vector< CandidateList > possibilities;
1562                        combos( argFinders.begin(), argFinders.end(), back_inserter( possibilities ) );
1563
1564                        // For every possible function:
1565                        // * try matching the arguments to the parameters, not the other way around because
1566                        //   more arguments than parameters
1567                        CandidateList funcCandidates;
1568                        std::vector< CandidateList > argsCandidates;
1569                        SemanticErrorException errors;
1570                        for ( CandidateRef & func : funcFinder.candidates ) {
1571                                try {
1572                                        auto pointerType = dynamic_cast< const ast::PointerType * >(
1573                                                func->expr->result->stripReferences() );
1574                                        if ( ! pointerType ) {
1575                                                SemanticError( stmt->location, func->expr->result.get(),
1576                                                        "candidate not viable: not a pointer type\n" );
1577                                        }
1578
1579                                        auto funcType = pointerType->base.as< ast::FunctionType >();
1580                                        if ( ! funcType ) {
1581                                                SemanticError( stmt->location, func->expr->result.get(),
1582                                                        "candidate not viable: not a function type\n" );
1583                                        }
1584
1585                                        {
1586                                                auto param    = funcType->params.begin();
1587                                                auto paramEnd = funcType->params.end();
1588
1589                                                if( ! nextMutex( param, paramEnd ) ) {
1590                                                        SemanticError( stmt->location, funcType,
1591                                                                "candidate function not viable: no mutex parameters\n");
1592                                                }
1593                                        }
1594
1595                                        CandidateRef func2{ new Candidate{ *func } };
1596                                        // strip reference from function
1597                                        func2->expr = referenceToRvalueConversion( func->expr, func2->cost );
1598
1599                                        // Each argument must be matched with a parameter of the current candidate
1600                                        for ( auto & argsList : possibilities ) {
1601                                                try {
1602                                                        // Declare data structures needed for resolution
1603                                                        ast::OpenVarSet open;
1604                                                        ast::AssertionSet need, have;
1605                                                        ast::TypeEnvironment resultEnv{ func->env };
1606                                                        // Add all type variables as open so that those not used in the
1607                                                        // parameter list are still considered open
1608                                                        resultEnv.add( funcType->forall );
1609
1610                                                        // load type variables from arguments into one shared space
1611                                                        for ( auto & arg : argsList ) {
1612                                                                resultEnv.simpleCombine( arg->env );
1613                                                        }
1614
1615                                                        // Make sure we don't widen any existing bindings
1616                                                        resultEnv.forbidWidening();
1617
1618                                                        // Find any unbound type variables
1619                                                        resultEnv.extractOpenVars( open );
1620
1621                                                        auto param = funcType->params.begin();
1622                                                        auto paramEnd = funcType->params.end();
1623
1624                                                        unsigned n_mutex_param = 0;
1625
1626                                                        // For every argument of its set, check if it matches one of the
1627                                                        // parameters. The order is important
1628                                                        for ( auto & arg : argsList ) {
1629                                                                // Ignore non-mutex arguments
1630                                                                if ( ! nextMutex( param, paramEnd ) ) {
1631                                                                        // We ran out of parameters but still have arguments.
1632                                                                        // This function doesn't match
1633                                                                        SemanticError( stmt->location, funcType,
1634                                                                                toString("candidate function not viable: too many mutex "
1635                                                                                "arguments, expected ", n_mutex_param, "\n" ) );
1636                                                                }
1637
1638                                                                ++n_mutex_param;
1639
1640                                                                // Check if the argument matches the parameter type in the current
1641                                                                // scope
1642                                                                // ast::ptr< ast::Type > paramType = (*param)->get_type();
1643                                                                if (
1644                                                                        ! unify(
1645                                                                                arg->expr->result, *param, resultEnv, need, have, open,
1646                                                                                symtab )
1647                                                                ) {
1648                                                                        // Type doesn't match
1649                                                                        stringstream ss;
1650                                                                        ss << "candidate function not viable: no known conversion "
1651                                                                                "from '";
1652                                                                        ast::print( ss, *param );
1653                                                                        ss << "' to '";
1654                                                                        ast::print( ss, arg->expr->result );
1655                                                                        ss << "' with env '";
1656                                                                        ast::print( ss, resultEnv );
1657                                                                        ss << "'\n";
1658                                                                        SemanticError( stmt->location, funcType, ss.str() );
1659                                                                }
1660
1661                                                                ++param;
1662                                                        }
1663
1664                                                        // All arguments match!
1665
1666                                                        // Check if parameters are missing
1667                                                        if ( nextMutex( param, paramEnd ) ) {
1668                                                                do {
1669                                                                        ++n_mutex_param;
1670                                                                        ++param;
1671                                                                } while ( nextMutex( param, paramEnd ) );
1672
1673                                                                // We ran out of arguments but still have parameters left; this
1674                                                                // function doesn't match
1675                                                                SemanticError( stmt->location, funcType,
1676                                                                        toString( "candidate function not viable: too few mutex "
1677                                                                        "arguments, expected ", n_mutex_param, "\n" ) );
1678                                                        }
1679
1680                                                        // All parameters match!
1681
1682                                                        // Finish the expressions to tie in proper environments
1683                                                        finishExpr( func2->expr, resultEnv );
1684                                                        for ( CandidateRef & arg : argsList ) {
1685                                                                finishExpr( arg->expr, resultEnv );
1686                                                        }
1687
1688                                                        // This is a match, store it and save it for later
1689                                                        funcCandidates.emplace_back( std::move( func2 ) );
1690                                                        argsCandidates.emplace_back( std::move( argsList ) );
1691
1692                                                } catch ( SemanticErrorException & e ) {
1693                                                        errors.append( e );
1694                                                }
1695                                        }
1696                                } catch ( SemanticErrorException & e ) {
1697                                        errors.append( e );
1698                                }
1699                        }
1700
1701                        // Make sure correct number of arguments
1702                        if( funcCandidates.empty() ) {
1703                                SemanticErrorException top( stmt->location,
1704                                        "No alternatives for function in call to waitfor" );
1705                                top.append( errors );
1706                                throw top;
1707                        }
1708
1709                        if( argsCandidates.empty() ) {
1710                                SemanticErrorException top( stmt->location,
1711                                        "No alternatives for arguments in call to waitfor" );
1712                                top.append( errors );
1713                                throw top;
1714                        }
1715
1716                        if( funcCandidates.size() > 1 ) {
1717                                SemanticErrorException top( stmt->location,
1718                                        "Ambiguous function in call to waitfor" );
1719                                top.append( errors );
1720                                throw top;
1721                        }
1722                        if( argsCandidates.size() > 1 ) {
1723                                SemanticErrorException top( stmt->location,
1724                                        "Ambiguous arguments in call to waitfor" );
1725                                top.append( errors );
1726                                throw top;
1727                        }
1728                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
1729
1730                        // build new clause
1731                        ast::WaitForStmt::Clause clause2;
1732
1733                        clause2.target.func = funcCandidates.front()->expr;
1734
1735                        clause2.target.args.reserve( clause.target.args.size() );
1736                        for ( auto arg : argsCandidates.front() ) {
1737                                clause2.target.args.emplace_back( std::move( arg->expr ) );
1738                        }
1739
1740                        // Resolve the conditions as if it were an IfStmt, statements normally
1741                        clause2.cond = findSingleExpression( clause.cond, symtab );
1742                        clause2.stmt = clause.stmt->accept( *visitor );
1743
1744                        // set results into stmt
1745                        auto n = mutate( stmt );
1746                        n->clauses[i] = std::move( clause2 );
1747                        stmt = n;
1748                }
1749
1750                if ( stmt->timeout.stmt ) {
1751                        // resolve the timeout as a size_t, the conditions like IfStmt, and stmts normally
1752                        ast::WaitForStmt::Timeout timeout2;
1753
1754                        ast::ptr< ast::Type > target =
1755                                new ast::BasicType{ ast::BasicType::LongLongUnsignedInt };
1756                        timeout2.time = findSingleExpression( stmt->timeout.time, target, symtab );
1757                        timeout2.cond = findSingleExpression( stmt->timeout.cond, symtab );
1758                        timeout2.stmt = stmt->timeout.stmt->accept( *visitor );
1759
1760                        // set results into stmt
1761                        auto n = mutate( stmt );
1762                        n->timeout = std::move( timeout2 );
1763                        stmt = n;
1764                }
1765
1766                if ( stmt->orElse.stmt ) {
1767                        // resolve the condition like IfStmt, stmts normally
1768                        ast::WaitForStmt::OrElse orElse2;
1769
1770                        orElse2.cond = findSingleExpression( stmt->orElse.cond, symtab );
1771                        orElse2.stmt = stmt->orElse.stmt->accept( *visitor );
1772
1773                        // set results into stmt
1774                        auto n = mutate( stmt );
1775                        n->orElse = std::move( orElse2 );
1776                        stmt = n;
1777                }
1778
1779                return stmt;
1780        }
1781
1782
1783
1784        const ast::SingleInit * Resolver_new::previsit( const ast::SingleInit * singleInit ) {
1785                visit_children = false;
1786                // resolve initialization using the possibilities as determined by the `currentObject`
1787                // cursor.
1788                ast::ptr< ast::Expr > untyped = new ast::UntypedInitExpr{
1789                        singleInit->location, singleInit->value, currentObject.getOptions() };
1790                ast::ptr<ast::Expr> newExpr = findSingleExpression( untyped, symtab );
1791                const ast::InitExpr * initExpr = newExpr.strict_as< ast::InitExpr >();
1792
1793                // move cursor to the object that is actually initialized
1794                currentObject.setNext( initExpr->designation );
1795
1796                // discard InitExpr wrapper and retain relevant pieces.
1797                // `initExpr` may have inferred params in the case where the expression specialized a
1798                // function pointer, and newExpr may already have inferParams of its own, so a simple
1799                // swap is not sufficient
1800                ast::Expr::InferUnion inferred = initExpr->inferred;
1801                swap_and_save_env( newExpr, initExpr->expr );
1802                newExpr.get_and_mutate()->inferred.splice( std::move(inferred) );
1803
1804                // get the actual object's type (may not exactly match what comes back from the resolver
1805                // due to conversions)
1806                const ast::Type * initContext = currentObject.getCurrentType();
1807
1808                removeExtraneousCast( newExpr, symtab );
1809
1810                // check if actual object's type is char[]
1811                if ( auto at = dynamic_cast< const ast::ArrayType * >( initContext ) ) {
1812                        if ( isCharType( at->base ) ) {
1813                                // check if the resolved type is char*
1814                                if ( auto pt = newExpr->result.as< ast::PointerType >() ) {
1815                                        if ( isCharType( pt->base ) ) {
1816                                                // strip cast if we're initializing a char[] with a char*
1817                                                // e.g. char x[] = "hello"
1818                                                if ( auto ce = newExpr.as< ast::CastExpr >() ) {
1819                                                        swap_and_save_env( newExpr, ce->arg );
1820                                                }
1821                                        }
1822                                }
1823                        }
1824                }
1825
1826                // move cursor to next object in preparation for next initializer
1827                currentObject.increment();
1828
1829                // set initializer expression to resolved expression
1830                return ast::mutate_field( singleInit, &ast::SingleInit::value, std::move(newExpr) );
1831        }
1832
1833        const ast::ListInit * Resolver_new::previsit( const ast::ListInit * listInit ) {
1834                // move cursor into brace-enclosed initializer-list
1835                currentObject.enterListInit( listInit->location );
1836
1837                assert( listInit->designations.size() == listInit->initializers.size() );
1838                for ( unsigned i = 0; i < listInit->designations.size(); ++i ) {
1839                        // iterate designations and initializers in pairs, moving the cursor to the current
1840                        // designated object and resolving the initializer against that object
1841                        listInit = ast::mutate_field_index(
1842                                listInit, &ast::ListInit::designations, i,
1843                                currentObject.findNext( listInit->designations[i] ) );
1844                        listInit = ast::mutate_field_index(
1845                                listInit, &ast::ListInit::initializers, i,
1846                                listInit->initializers[i]->accept( *visitor ) );
1847                }
1848
1849                // move cursor out of brace-enclosed initializer-list
1850                currentObject.exitListInit();
1851
1852                visit_children = false;
1853                return listInit;
1854        }
1855
1856        const ast::ConstructorInit * Resolver_new::previsit( const ast::ConstructorInit * ctorInit ) {
1857                visitor->maybe_accept( ctorInit, &ast::ConstructorInit::ctor );
1858                visitor->maybe_accept( ctorInit, &ast::ConstructorInit::dtor );
1859
1860                // found a constructor - can get rid of C-style initializer
1861                // xxx - Rob suggests this field is dead code
1862                ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::init, nullptr );
1863
1864                // intrinsic single-parameter constructors and destructors do nothing. Since this was
1865                // implicitly generated, there's no way for it to have side effects, so get rid of it to
1866                // clean up generated code
1867                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
1868                        ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::ctor, nullptr );
1869                }
1870                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
1871                        ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::dtor, nullptr );
1872                }
1873
1874                return ctorInit;
1875        }
1876
1877} // namespace ResolvExpr
1878
1879// Local Variables: //
1880// tab-width: 4 //
1881// mode: c++ //
1882// compile-command: "make install" //
1883// End: //
Note: See TracBrowser for help on using the repository browser.