source: src/ResolvExpr/Resolver.cc @ 954c954

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

Move function argument and return variable declarations from FunctionType? to FunctionDecl?

  • Property mode set to 100644
File size: 68.0 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                /// Establish post-resolver invariants for expressions
1108                void finishExpr(
1109                        ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env,
1110                        const ast::TypeSubstitution * oldenv = nullptr
1111                ) {
1112                        // set up new type substitution for expression
1113                        ast::ptr< ast::TypeSubstitution > newenv =
1114                                 oldenv ? oldenv : new ast::TypeSubstitution{};
1115                        env.writeToSubstitution( *newenv.get_and_mutate() );
1116                        expr.get_and_mutate()->env = std::move( newenv );
1117                        // remove unncecessary casts
1118                        StripCasts_new::strip( expr );
1119                }
1120        } // anonymous namespace
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        namespace {
1142                /// Resolve `untyped` to the expression whose candidate is the best match for a `void`
1143                /// context.
1144                ast::ptr< ast::Expr > findVoidExpression(
1145                        const ast::Expr * untyped, const ast::SymbolTable & symtab
1146                ) {
1147                        resetTyVarRenaming();
1148                        ast::TypeEnvironment env;
1149                        ast::ptr< ast::Expr > newExpr = resolveInVoidContext( untyped, symtab, env );
1150                        finishExpr( newExpr, env, untyped->env );
1151                        return newExpr;
1152                }
1153
1154                /// resolve `untyped` to the expression whose candidate satisfies `pred` with the
1155                /// lowest cost, returning the resolved version
1156                ast::ptr< ast::Expr > findKindExpression(
1157                        const ast::Expr * untyped, const ast::SymbolTable & symtab,
1158                        std::function<bool(const Candidate &)> pred = anyCandidate,
1159                        const std::string & kind = "", ResolvMode mode = {}
1160                ) {
1161                        if ( ! untyped ) return {};
1162                        CandidateRef choice =
1163                                findUnfinishedKindExpression( untyped, symtab, kind, pred, mode );
1164                        finishExpr( choice->expr, choice->env, untyped->env );
1165                        return std::move( choice->expr );
1166                }
1167
1168                /// Resolve `untyped` to the single expression whose candidate is the best match
1169                ast::ptr< ast::Expr > findSingleExpression(
1170                        const ast::Expr * untyped, const ast::SymbolTable & symtab
1171                ) {
1172                        Stats::ResolveTime::start( untyped );
1173                        auto res = findKindExpression( untyped, symtab );
1174                        Stats::ResolveTime::stop();
1175                        return res;
1176                }
1177        } // anonymous namespace
1178
1179                ast::ptr< ast::Expr > findSingleExpression(
1180                        const ast::Expr * untyped, const ast::Type * type, const ast::SymbolTable & symtab
1181                ) {
1182                        assert( untyped && type );
1183                        ast::ptr< ast::Expr > castExpr = new ast::CastExpr{ untyped, type };
1184                        ast::ptr< ast::Expr > newExpr = findSingleExpression( castExpr, symtab );
1185                        removeExtraneousCast( newExpr, symtab );
1186                        return newExpr;
1187                }
1188
1189        namespace {
1190                /// Predicate for "Candidate has integral type"
1191                bool hasIntegralType( const Candidate & i ) {
1192                        const ast::Type * type = i.expr->result;
1193
1194                        if ( auto bt = dynamic_cast< const ast::BasicType * >( type ) ) {
1195                                return bt->isInteger();
1196                        } else if (
1197                                dynamic_cast< const ast::EnumInstType * >( type )
1198                                || dynamic_cast< const ast::ZeroType * >( type )
1199                                || dynamic_cast< const ast::OneType * >( type )
1200                        ) {
1201                                return true;
1202                        } else return false;
1203                }
1204
1205                /// Resolve `untyped` as an integral expression, returning the resolved version
1206                ast::ptr< ast::Expr > findIntegralExpression(
1207                        const ast::Expr * untyped, const ast::SymbolTable & symtab
1208                ) {
1209                        return findKindExpression( untyped, symtab, hasIntegralType, "condition" );
1210                }
1211
1212                /// check if a type is a character type
1213                bool isCharType( const ast::Type * t ) {
1214                        if ( auto bt = dynamic_cast< const ast::BasicType * >( t ) ) {
1215                                return bt->kind == ast::BasicType::Char
1216                                        || bt->kind == ast::BasicType::SignedChar
1217                                        || bt->kind == ast::BasicType::UnsignedChar;
1218                        }
1219                        return false;
1220                }
1221
1222                /// Advance a type itertor to the next mutex parameter
1223                template<typename Iter>
1224                inline bool nextMutex( Iter & it, const Iter & end ) {
1225                        while ( it != end && ! (*it)->is_mutex() ) { ++it; }
1226                        return it != end;
1227                }
1228        }
1229
1230        class Resolver_new final
1231        : public ast::WithSymbolTable, public ast::WithGuards,
1232          public ast::WithVisitorRef<Resolver_new>, public ast::WithShortCircuiting,
1233          public ast::WithStmtsToAdd<> {
1234
1235                ast::ptr< ast::Type > functionReturn = nullptr;
1236                ast::CurrentObject currentObject;
1237                bool inEnumDecl = false;
1238
1239        public:
1240                static size_t traceId;
1241                Resolver_new() = default;
1242                Resolver_new( const ast::SymbolTable & syms ) { symtab = syms; }
1243
1244                void previsit( const ast::FunctionDecl * );
1245                const ast::FunctionDecl * postvisit( const ast::FunctionDecl * );
1246                void previsit( const ast::ObjectDecl * );
1247                void previsit( const ast::EnumDecl * );
1248                const ast::StaticAssertDecl * previsit( const ast::StaticAssertDecl * );
1249
1250                const ast::ArrayType * previsit( const ast::ArrayType * );
1251                const ast::PointerType * previsit( const ast::PointerType * );
1252
1253                const ast::ExprStmt *        previsit( const ast::ExprStmt * );
1254                const ast::AsmExpr *         previsit( const ast::AsmExpr * );
1255                const ast::AsmStmt *         previsit( const ast::AsmStmt * );
1256                const ast::IfStmt *          previsit( const ast::IfStmt * );
1257                const ast::WhileStmt *       previsit( const ast::WhileStmt * );
1258                const ast::ForStmt *         previsit( const ast::ForStmt * );
1259                const ast::SwitchStmt *      previsit( const ast::SwitchStmt * );
1260                const ast::CaseStmt *        previsit( const ast::CaseStmt * );
1261                const ast::BranchStmt *      previsit( const ast::BranchStmt * );
1262                const ast::ReturnStmt *      previsit( const ast::ReturnStmt * );
1263                const ast::ThrowStmt *       previsit( const ast::ThrowStmt * );
1264                const ast::CatchStmt *       previsit( const ast::CatchStmt * );
1265                const ast::CatchStmt *       postvisit( const ast::CatchStmt * );
1266                const ast::WaitForStmt *     previsit( const ast::WaitForStmt * );
1267
1268                const ast::SingleInit *      previsit( const ast::SingleInit * );
1269                const ast::ListInit *        previsit( const ast::ListInit * );
1270                const ast::ConstructorInit * previsit( const ast::ConstructorInit * );
1271        };
1272        // size_t Resolver_new::traceId = Stats::Heap::new_stacktrace_id("Resolver");
1273
1274        void resolve( std::list< ast::ptr< ast::Decl > >& translationUnit ) {
1275                ast::Pass< Resolver_new >::run( translationUnit );
1276        }
1277
1278        ast::ptr< ast::Init > resolveCtorInit(
1279                const ast::ConstructorInit * ctorInit, const ast::SymbolTable & symtab
1280        ) {
1281                assert( ctorInit );
1282                ast::Pass< Resolver_new > resolver{ symtab };
1283                return ctorInit->accept( resolver );
1284        }
1285
1286        ast::ptr< ast::Expr > resolveStmtExpr(
1287                const ast::StmtExpr * stmtExpr, const ast::SymbolTable & symtab
1288        ) {
1289                assert( stmtExpr );
1290                ast::Pass< Resolver_new > resolver{ symtab };
1291                ast::ptr< ast::Expr > ret = stmtExpr;
1292                ret = ret->accept( resolver );
1293                strict_dynamic_cast< ast::StmtExpr * >( ret.get_and_mutate() )->computeResult();
1294                return ret;
1295        }
1296
1297        void Resolver_new::previsit( const ast::FunctionDecl * functionDecl ) {
1298                GuardValue( functionReturn );
1299                functionReturn = extractResultType( functionDecl->type );
1300        }
1301
1302        const ast::FunctionDecl * Resolver_new::postvisit( const ast::FunctionDecl * functionDecl ) {
1303                // default value expressions have an environment which shouldn't be there and trips up
1304                // later passes.
1305                assert( functionDecl->unique() );
1306                ast::FunctionType * mutType = mutate( functionDecl->type.get() );
1307
1308                for ( unsigned i = 0 ; i < mutType->params.size() ; ++i ) {
1309                        if ( const ast::ObjectDecl * obj = mutType->params[i].as< ast::ObjectDecl >() ) {
1310                                if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) {
1311                                        if ( init->value->env == nullptr ) continue;
1312                                        // clone initializer minus the initializer environment
1313                                        auto mutParam = mutate( mutType->params[i].strict_as< ast::ObjectDecl >() );
1314                                        auto mutInit = mutate( mutParam->init.strict_as< ast::SingleInit >() );
1315                                        auto mutValue = mutate( mutInit->value.get() );
1316
1317                                        mutValue->env = nullptr;
1318                                        mutInit->value = mutValue;
1319                                        mutParam->init = mutInit;
1320                                        mutType->params[i] = mutParam;
1321
1322                                        assert( ! mutType->params[i].strict_as< ast::ObjectDecl >()->init.strict_as< ast::SingleInit >()->value->env);
1323                                }
1324                        }
1325                }
1326                mutate_field(functionDecl, &ast::FunctionDecl::type, mutType);
1327                return functionDecl;
1328        }
1329
1330        void Resolver_new::previsit( const ast::ObjectDecl * objectDecl ) {
1331                // To handle initialization of routine pointers [e.g. int (*fp)(int) = foo()],
1332                // class-variable `initContext` is changed multiple times because the LHS is analyzed
1333                // twice. The second analysis changes `initContext` because a function type can contain
1334                // object declarations in the return and parameter types. Therefore each value of
1335                // `initContext` is retained so the type on the first analysis is preserved and used for
1336                // selecting the RHS.
1337                GuardValue( currentObject );
1338                currentObject = ast::CurrentObject{ objectDecl->location, objectDecl->get_type() };
1339                if ( inEnumDecl && dynamic_cast< const ast::EnumInstType * >( objectDecl->get_type() ) ) {
1340                        // enumerator initializers should not use the enum type to initialize, since the
1341                        // enum type is still incomplete at this point. Use `int` instead.
1342                        currentObject = ast::CurrentObject{
1343                                objectDecl->location, new ast::BasicType{ ast::BasicType::SignedInt } };
1344                }
1345        }
1346
1347        void Resolver_new::previsit( const ast::EnumDecl * ) {
1348                // in case we decide to allow nested enums
1349                GuardValue( inEnumDecl );
1350                inEnumDecl = true;
1351        }
1352
1353        const ast::StaticAssertDecl * Resolver_new::previsit(
1354                const ast::StaticAssertDecl * assertDecl
1355        ) {
1356                return ast::mutate_field(
1357                        assertDecl, &ast::StaticAssertDecl::cond,
1358                        findIntegralExpression( assertDecl->cond, symtab ) );
1359        }
1360
1361        template< typename PtrType >
1362        const PtrType * handlePtrType( const PtrType * type, const ast::SymbolTable & symtab ) {
1363                if ( type->dimension ) {
1364                        #warning should use new equivalent to Validate::SizeType rather than sizeType here
1365                        ast::ptr< ast::Type > sizeType = new ast::BasicType{ ast::BasicType::LongUnsignedInt };
1366                        ast::mutate_field(
1367                                type, &PtrType::dimension,
1368                                findSingleExpression( type->dimension, sizeType, symtab ) );
1369                }
1370                return type;
1371        }
1372
1373        const ast::ArrayType * Resolver_new::previsit( const ast::ArrayType * at ) {
1374                return handlePtrType( at, symtab );
1375        }
1376
1377        const ast::PointerType * Resolver_new::previsit( const ast::PointerType * pt ) {
1378                return handlePtrType( pt, symtab );
1379        }
1380
1381        const ast::ExprStmt * Resolver_new::previsit( const ast::ExprStmt * exprStmt ) {
1382                visit_children = false;
1383                assertf( exprStmt->expr, "ExprStmt has null expression in resolver" );
1384
1385                return ast::mutate_field(
1386                        exprStmt, &ast::ExprStmt::expr, findVoidExpression( exprStmt->expr, symtab ) );
1387        }
1388
1389        const ast::AsmExpr * Resolver_new::previsit( const ast::AsmExpr * asmExpr ) {
1390                visit_children = false;
1391
1392                asmExpr = ast::mutate_field(
1393                        asmExpr, &ast::AsmExpr::operand, findVoidExpression( asmExpr->operand, symtab ) );
1394
1395                return asmExpr;
1396        }
1397
1398        const ast::AsmStmt * Resolver_new::previsit( const ast::AsmStmt * asmStmt ) {
1399                visitor->maybe_accept( asmStmt, &ast::AsmStmt::input );
1400                visitor->maybe_accept( asmStmt, &ast::AsmStmt::output );
1401                visit_children = false;
1402                return asmStmt;
1403        }
1404
1405        const ast::IfStmt * Resolver_new::previsit( const ast::IfStmt * ifStmt ) {
1406                return ast::mutate_field(
1407                        ifStmt, &ast::IfStmt::cond, findIntegralExpression( ifStmt->cond, symtab ) );
1408        }
1409
1410        const ast::WhileStmt * Resolver_new::previsit( const ast::WhileStmt * whileStmt ) {
1411                return ast::mutate_field(
1412                        whileStmt, &ast::WhileStmt::cond, findIntegralExpression( whileStmt->cond, symtab ) );
1413        }
1414
1415        const ast::ForStmt * Resolver_new::previsit( const ast::ForStmt * forStmt ) {
1416                if ( forStmt->cond ) {
1417                        forStmt = ast::mutate_field(
1418                                forStmt, &ast::ForStmt::cond, findIntegralExpression( forStmt->cond, symtab ) );
1419                }
1420
1421                if ( forStmt->inc ) {
1422                        forStmt = ast::mutate_field(
1423                                forStmt, &ast::ForStmt::inc, findVoidExpression( forStmt->inc, symtab ) );
1424                }
1425
1426                return forStmt;
1427        }
1428
1429        const ast::SwitchStmt * Resolver_new::previsit( const ast::SwitchStmt * switchStmt ) {
1430                GuardValue( currentObject );
1431                switchStmt = ast::mutate_field(
1432                        switchStmt, &ast::SwitchStmt::cond,
1433                        findIntegralExpression( switchStmt->cond, symtab ) );
1434                currentObject = ast::CurrentObject{ switchStmt->location, switchStmt->cond->result };
1435                return switchStmt;
1436        }
1437
1438        const ast::CaseStmt * Resolver_new::previsit( const ast::CaseStmt * caseStmt ) {
1439                if ( caseStmt->cond ) {
1440                        std::deque< ast::InitAlternative > initAlts = currentObject.getOptions();
1441                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral "
1442                                "expression." );
1443
1444                        ast::ptr< ast::Expr > untyped =
1445                                new ast::CastExpr{ caseStmt->location, caseStmt->cond, initAlts.front().type };
1446                        ast::ptr< ast::Expr > newExpr = findSingleExpression( untyped, symtab );
1447
1448                        // case condition cannot have a cast in C, so it must be removed here, regardless of
1449                        // whether it would perform a conversion.
1450                        if ( const ast::CastExpr * castExpr = newExpr.as< ast::CastExpr >() ) {
1451                                swap_and_save_env( newExpr, castExpr->arg );
1452                        }
1453
1454                        caseStmt = ast::mutate_field( caseStmt, &ast::CaseStmt::cond, newExpr );
1455                }
1456                return caseStmt;
1457        }
1458
1459        const ast::BranchStmt * Resolver_new::previsit( const ast::BranchStmt * branchStmt ) {
1460                visit_children = false;
1461                // must resolve the argument of a computed goto
1462                if ( branchStmt->kind == ast::BranchStmt::Goto && branchStmt->computedTarget ) {
1463                        // computed goto argument is void*
1464                        ast::ptr< ast::Type > target = new ast::PointerType{ new ast::VoidType{} };
1465                        branchStmt = ast::mutate_field(
1466                                branchStmt, &ast::BranchStmt::computedTarget,
1467                                findSingleExpression( branchStmt->computedTarget, target, symtab ) );
1468                }
1469                return branchStmt;
1470        }
1471
1472        const ast::ReturnStmt * Resolver_new::previsit( const ast::ReturnStmt * returnStmt ) {
1473                visit_children = false;
1474                if ( returnStmt->expr ) {
1475                        returnStmt = ast::mutate_field(
1476                                returnStmt, &ast::ReturnStmt::expr,
1477                                findSingleExpression( returnStmt->expr, functionReturn, symtab ) );
1478                }
1479                return returnStmt;
1480        }
1481
1482        const ast::ThrowStmt * Resolver_new::previsit( const ast::ThrowStmt * throwStmt ) {
1483                visit_children = false;
1484                if ( throwStmt->expr ) {
1485                        const ast::StructDecl * exceptionDecl =
1486                                symtab.lookupStruct( "__cfaehm_base_exception_t" );
1487                        assert( exceptionDecl );
1488                        ast::ptr< ast::Type > exceptType =
1489                                new ast::PointerType{ new ast::StructInstType{ exceptionDecl } };
1490                        throwStmt = ast::mutate_field(
1491                                throwStmt, &ast::ThrowStmt::expr,
1492                                findSingleExpression( throwStmt->expr, exceptType, symtab ) );
1493                }
1494                return throwStmt;
1495        }
1496
1497        const ast::CatchStmt * Resolver_new::previsit( const ast::CatchStmt * catchStmt ) {
1498                // Until we are very sure this invarent (ifs that move between passes have thenPart)
1499                // holds, check it. This allows a check for when to decode the mangling.
1500                if ( auto ifStmt = catchStmt->body.as<ast::IfStmt>() ) {
1501                        assert( ifStmt->thenPart );
1502                }
1503                // Encode the catchStmt so the condition can see the declaration.
1504                if ( catchStmt->cond ) {
1505                        ast::CatchStmt * stmt = mutate( catchStmt );
1506                        stmt->body = new ast::IfStmt( stmt->location, stmt->cond, nullptr, stmt->body );
1507                        stmt->cond = nullptr;
1508                        return stmt;
1509                }
1510                return catchStmt;
1511        }
1512
1513        const ast::CatchStmt * Resolver_new::postvisit( const ast::CatchStmt * catchStmt ) {
1514                // Decode the catchStmt so everything is stored properly.
1515                const ast::IfStmt * ifStmt = catchStmt->body.as<ast::IfStmt>();
1516                if ( nullptr != ifStmt && nullptr == ifStmt->thenPart ) {
1517                        assert( ifStmt->cond );
1518                        assert( ifStmt->elsePart );
1519                        ast::CatchStmt * stmt = ast::mutate( catchStmt );
1520                        stmt->cond = ifStmt->cond;
1521                        stmt->body = ifStmt->elsePart;
1522                        // ifStmt should be implicately deleted here.
1523                        return stmt;
1524                }
1525                return catchStmt;
1526        }
1527
1528        const ast::WaitForStmt * Resolver_new::previsit( const ast::WaitForStmt * stmt ) {
1529                visit_children = false;
1530
1531                // Resolve all clauses first
1532                for ( unsigned i = 0; i < stmt->clauses.size(); ++i ) {
1533                        const ast::WaitForStmt::Clause & clause = stmt->clauses[i];
1534
1535                        ast::TypeEnvironment env;
1536                        CandidateFinder funcFinder{ symtab, env };
1537
1538                        // Find all candidates for a function in canonical form
1539                        funcFinder.find( clause.target.func, ResolvMode::withAdjustment() );
1540
1541                        if ( funcFinder.candidates.empty() ) {
1542                                stringstream ss;
1543                                ss << "Use of undeclared indentifier '";
1544                                ss << clause.target.func.strict_as< ast::NameExpr >()->name;
1545                                ss << "' in call to waitfor";
1546                                SemanticError( stmt->location, ss.str() );
1547                        }
1548
1549                        if ( clause.target.args.empty() ) {
1550                                SemanticError( stmt->location,
1551                                        "Waitfor clause must have at least one mutex parameter");
1552                        }
1553
1554                        // Find all alternatives for all arguments in canonical form
1555                        std::vector< CandidateFinder > argFinders =
1556                                funcFinder.findSubExprs( clause.target.args );
1557
1558                        // List all combinations of arguments
1559                        std::vector< CandidateList > possibilities;
1560                        combos( argFinders.begin(), argFinders.end(), back_inserter( possibilities ) );
1561
1562                        // For every possible function:
1563                        // * try matching the arguments to the parameters, not the other way around because
1564                        //   more arguments than parameters
1565                        CandidateList funcCandidates;
1566                        std::vector< CandidateList > argsCandidates;
1567                        SemanticErrorException errors;
1568                        for ( CandidateRef & func : funcFinder.candidates ) {
1569                                try {
1570                                        auto pointerType = dynamic_cast< const ast::PointerType * >(
1571                                                func->expr->result->stripReferences() );
1572                                        if ( ! pointerType ) {
1573                                                SemanticError( stmt->location, func->expr->result.get(),
1574                                                        "candidate not viable: not a pointer type\n" );
1575                                        }
1576
1577                                        auto funcType = pointerType->base.as< ast::FunctionType >();
1578                                        if ( ! funcType ) {
1579                                                SemanticError( stmt->location, func->expr->result.get(),
1580                                                        "candidate not viable: not a function type\n" );
1581                                        }
1582
1583                                        {
1584                                                auto param    = funcType->params.begin();
1585                                                auto paramEnd = funcType->params.end();
1586
1587                                                if( ! nextMutex( param, paramEnd ) ) {
1588                                                        SemanticError( stmt->location, funcType,
1589                                                                "candidate function not viable: no mutex parameters\n");
1590                                                }
1591                                        }
1592
1593                                        CandidateRef func2{ new Candidate{ *func } };
1594                                        // strip reference from function
1595                                        func2->expr = referenceToRvalueConversion( func->expr, func2->cost );
1596
1597                                        // Each argument must be matched with a parameter of the current candidate
1598                                        for ( auto & argsList : possibilities ) {
1599                                                try {
1600                                                        // Declare data structures needed for resolution
1601                                                        ast::OpenVarSet open;
1602                                                        ast::AssertionSet need, have;
1603                                                        ast::TypeEnvironment resultEnv{ func->env };
1604                                                        // Add all type variables as open so that those not used in the
1605                                                        // parameter list are still considered open
1606                                                        resultEnv.add( funcType->forall );
1607
1608                                                        // load type variables from arguments into one shared space
1609                                                        for ( auto & arg : argsList ) {
1610                                                                resultEnv.simpleCombine( arg->env );
1611                                                        }
1612
1613                                                        // Make sure we don't widen any existing bindings
1614                                                        resultEnv.forbidWidening();
1615
1616                                                        // Find any unbound type variables
1617                                                        resultEnv.extractOpenVars( open );
1618
1619                                                        auto param = funcType->params.begin();
1620                                                        auto paramEnd = funcType->params.end();
1621
1622                                                        unsigned n_mutex_param = 0;
1623
1624                                                        // For every argument of its set, check if it matches one of the
1625                                                        // parameters. The order is important
1626                                                        for ( auto & arg : argsList ) {
1627                                                                // Ignore non-mutex arguments
1628                                                                if ( ! nextMutex( param, paramEnd ) ) {
1629                                                                        // We ran out of parameters but still have arguments.
1630                                                                        // This function doesn't match
1631                                                                        SemanticError( stmt->location, funcType,
1632                                                                                toString("candidate function not viable: too many mutex "
1633                                                                                "arguments, expected ", n_mutex_param, "\n" ) );
1634                                                                }
1635
1636                                                                ++n_mutex_param;
1637
1638                                                                // Check if the argument matches the parameter type in the current
1639                                                                // scope
1640                                                                // ast::ptr< ast::Type > paramType = (*param)->get_type();
1641                                                                if (
1642                                                                        ! unify(
1643                                                                                arg->expr->result, *param, resultEnv, need, have, open,
1644                                                                                symtab )
1645                                                                ) {
1646                                                                        // Type doesn't match
1647                                                                        stringstream ss;
1648                                                                        ss << "candidate function not viable: no known conversion "
1649                                                                                "from '";
1650                                                                        ast::print( ss, *param );
1651                                                                        ss << "' to '";
1652                                                                        ast::print( ss, arg->expr->result );
1653                                                                        ss << "' with env '";
1654                                                                        ast::print( ss, resultEnv );
1655                                                                        ss << "'\n";
1656                                                                        SemanticError( stmt->location, funcType, ss.str() );
1657                                                                }
1658
1659                                                                ++param;
1660                                                        }
1661
1662                                                        // All arguments match!
1663
1664                                                        // Check if parameters are missing
1665                                                        if ( nextMutex( param, paramEnd ) ) {
1666                                                                do {
1667                                                                        ++n_mutex_param;
1668                                                                        ++param;
1669                                                                } while ( nextMutex( param, paramEnd ) );
1670
1671                                                                // We ran out of arguments but still have parameters left; this
1672                                                                // function doesn't match
1673                                                                SemanticError( stmt->location, funcType,
1674                                                                        toString( "candidate function not viable: too few mutex "
1675                                                                        "arguments, expected ", n_mutex_param, "\n" ) );
1676                                                        }
1677
1678                                                        // All parameters match!
1679
1680                                                        // Finish the expressions to tie in proper environments
1681                                                        finishExpr( func2->expr, resultEnv );
1682                                                        for ( CandidateRef & arg : argsList ) {
1683                                                                finishExpr( arg->expr, resultEnv );
1684                                                        }
1685
1686                                                        // This is a match, store it and save it for later
1687                                                        funcCandidates.emplace_back( std::move( func2 ) );
1688                                                        argsCandidates.emplace_back( std::move( argsList ) );
1689
1690                                                } catch ( SemanticErrorException & e ) {
1691                                                        errors.append( e );
1692                                                }
1693                                        }
1694                                } catch ( SemanticErrorException & e ) {
1695                                        errors.append( e );
1696                                }
1697                        }
1698
1699                        // Make sure correct number of arguments
1700                        if( funcCandidates.empty() ) {
1701                                SemanticErrorException top( stmt->location,
1702                                        "No alternatives for function in call to waitfor" );
1703                                top.append( errors );
1704                                throw top;
1705                        }
1706
1707                        if( argsCandidates.empty() ) {
1708                                SemanticErrorException top( stmt->location,
1709                                        "No alternatives for arguments in call to waitfor" );
1710                                top.append( errors );
1711                                throw top;
1712                        }
1713
1714                        if( funcCandidates.size() > 1 ) {
1715                                SemanticErrorException top( stmt->location,
1716                                        "Ambiguous function in call to waitfor" );
1717                                top.append( errors );
1718                                throw top;
1719                        }
1720                        if( argsCandidates.size() > 1 ) {
1721                                SemanticErrorException top( stmt->location,
1722                                        "Ambiguous arguments in call to waitfor" );
1723                                top.append( errors );
1724                                throw top;
1725                        }
1726                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
1727
1728                        // build new clause
1729                        ast::WaitForStmt::Clause clause2;
1730
1731                        clause2.target.func = funcCandidates.front()->expr;
1732
1733                        clause2.target.args.reserve( clause.target.args.size() );
1734                        for ( auto arg : argsCandidates.front() ) {
1735                                clause2.target.args.emplace_back( std::move( arg->expr ) );
1736                        }
1737
1738                        // Resolve the conditions as if it were an IfStmt, statements normally
1739                        clause2.cond = findSingleExpression( clause.cond, symtab );
1740                        clause2.stmt = clause.stmt->accept( *visitor );
1741
1742                        // set results into stmt
1743                        auto n = mutate( stmt );
1744                        n->clauses[i] = std::move( clause2 );
1745                        stmt = n;
1746                }
1747
1748                if ( stmt->timeout.stmt ) {
1749                        // resolve the timeout as a size_t, the conditions like IfStmt, and stmts normally
1750                        ast::WaitForStmt::Timeout timeout2;
1751
1752                        ast::ptr< ast::Type > target =
1753                                new ast::BasicType{ ast::BasicType::LongLongUnsignedInt };
1754                        timeout2.time = findSingleExpression( stmt->timeout.time, target, symtab );
1755                        timeout2.cond = findSingleExpression( stmt->timeout.cond, symtab );
1756                        timeout2.stmt = stmt->timeout.stmt->accept( *visitor );
1757
1758                        // set results into stmt
1759                        auto n = mutate( stmt );
1760                        n->timeout = std::move( timeout2 );
1761                        stmt = n;
1762                }
1763
1764                if ( stmt->orElse.stmt ) {
1765                        // resolve the condition like IfStmt, stmts normally
1766                        ast::WaitForStmt::OrElse orElse2;
1767
1768                        orElse2.cond = findSingleExpression( stmt->orElse.cond, symtab );
1769                        orElse2.stmt = stmt->orElse.stmt->accept( *visitor );
1770
1771                        // set results into stmt
1772                        auto n = mutate( stmt );
1773                        n->orElse = std::move( orElse2 );
1774                        stmt = n;
1775                }
1776
1777                return stmt;
1778        }
1779
1780
1781
1782        const ast::SingleInit * Resolver_new::previsit( const ast::SingleInit * singleInit ) {
1783                visit_children = false;
1784                // resolve initialization using the possibilities as determined by the `currentObject`
1785                // cursor.
1786                ast::ptr< ast::Expr > untyped = new ast::UntypedInitExpr{
1787                        singleInit->location, singleInit->value, currentObject.getOptions() };
1788                ast::ptr<ast::Expr> newExpr = findSingleExpression( untyped, symtab );
1789                const ast::InitExpr * initExpr = newExpr.strict_as< ast::InitExpr >();
1790
1791                // move cursor to the object that is actually initialized
1792                currentObject.setNext( initExpr->designation );
1793
1794                // discard InitExpr wrapper and retain relevant pieces.
1795                // `initExpr` may have inferred params in the case where the expression specialized a
1796                // function pointer, and newExpr may already have inferParams of its own, so a simple
1797                // swap is not sufficient
1798                ast::Expr::InferUnion inferred = initExpr->inferred;
1799                swap_and_save_env( newExpr, initExpr->expr );
1800                newExpr.get_and_mutate()->inferred.splice( std::move(inferred) );
1801
1802                // get the actual object's type (may not exactly match what comes back from the resolver
1803                // due to conversions)
1804                const ast::Type * initContext = currentObject.getCurrentType();
1805
1806                removeExtraneousCast( newExpr, symtab );
1807
1808                // check if actual object's type is char[]
1809                if ( auto at = dynamic_cast< const ast::ArrayType * >( initContext ) ) {
1810                        if ( isCharType( at->base ) ) {
1811                                // check if the resolved type is char*
1812                                if ( auto pt = newExpr->result.as< ast::PointerType >() ) {
1813                                        if ( isCharType( pt->base ) ) {
1814                                                // strip cast if we're initializing a char[] with a char*
1815                                                // e.g. char x[] = "hello"
1816                                                if ( auto ce = newExpr.as< ast::CastExpr >() ) {
1817                                                        swap_and_save_env( newExpr, ce->arg );
1818                                                }
1819                                        }
1820                                }
1821                        }
1822                }
1823
1824                // move cursor to next object in preparation for next initializer
1825                currentObject.increment();
1826
1827                // set initializer expression to resolved expression
1828                return ast::mutate_field( singleInit, &ast::SingleInit::value, std::move(newExpr) );
1829        }
1830
1831        const ast::ListInit * Resolver_new::previsit( const ast::ListInit * listInit ) {
1832                // move cursor into brace-enclosed initializer-list
1833                currentObject.enterListInit( listInit->location );
1834
1835                assert( listInit->designations.size() == listInit->initializers.size() );
1836                for ( unsigned i = 0; i < listInit->designations.size(); ++i ) {
1837                        // iterate designations and initializers in pairs, moving the cursor to the current
1838                        // designated object and resolving the initializer against that object
1839                        listInit = ast::mutate_field_index(
1840                                listInit, &ast::ListInit::designations, i,
1841                                currentObject.findNext( listInit->designations[i] ) );
1842                        listInit = ast::mutate_field_index(
1843                                listInit, &ast::ListInit::initializers, i,
1844                                listInit->initializers[i]->accept( *visitor ) );
1845                }
1846
1847                // move cursor out of brace-enclosed initializer-list
1848                currentObject.exitListInit();
1849
1850                visit_children = false;
1851                return listInit;
1852        }
1853
1854        const ast::ConstructorInit * Resolver_new::previsit( const ast::ConstructorInit * ctorInit ) {
1855                visitor->maybe_accept( ctorInit, &ast::ConstructorInit::ctor );
1856                visitor->maybe_accept( ctorInit, &ast::ConstructorInit::dtor );
1857
1858                // found a constructor - can get rid of C-style initializer
1859                // xxx - Rob suggests this field is dead code
1860                ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::init, nullptr );
1861
1862                // intrinsic single-parameter constructors and destructors do nothing. Since this was
1863                // implicitly generated, there's no way for it to have side effects, so get rid of it to
1864                // clean up generated code
1865                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
1866                        ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::ctor, nullptr );
1867                }
1868                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
1869                        ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::dtor, nullptr );
1870                }
1871
1872                return ctorInit;
1873        }
1874
1875} // namespace ResolvExpr
1876
1877// Local Variables: //
1878// tab-width: 4 //
1879// mode: c++ //
1880// compile-command: "make install" //
1881// End: //
Note: See TracBrowser for help on using the repository browser.