source: src/ResolvExpr/Resolver.cc @ 6d53e779

new-env
Last change on this file since 6d53e779 was 1d7b0a8, checked in by Aaron Moss <a3moss@…>, 6 years ago

Move AlternativeFinder? find flags to ResolvMode? struct

  • Property mode set to 100644
File size: 32.7 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           : Richard C. Bilson
10// Created On       : Sun May 17 12:17:01 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sat Feb 17 11:19:40 2018
13// Update Count     : 213
14//
15
16#include <stddef.h>                      // for NULL
17#include <cassert>                       // for strict_dynamic_cast, assert
18#include <memory>                        // for allocator, allocator_traits<...
19#include <tuple>                         // for get
20#include <vector>
21
22#include "Alternative.h"                 // for Alternative, AltList
23#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
24#include "Common/GC.h"                   // for new_generation, collect_young
25#include "Common/PassVisitor.h"          // for PassVisitor
26#include "Common/SemanticError.h"        // for SemanticError
27#include "Common/utility.h"              // for ValueGuard, group_iterate
28#include "CurrentObject.h"               // for CurrentObject
29#include "InitTweak/GenInit.h"
30#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
31#include "RenameVars.h"                  // for RenameVars, global_renamer
32#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
33#include "ResolveTypeof.h"               // for resolveTypeof
34#include "Resolver.h"
35#include "ResolvMode.h"                  // for ResolvMode
36#include "SymTab/Autogen.h"              // for SizeType
37#include "SymTab/Indexer.h"              // for Indexer
38#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
39#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
40#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
41#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
42#include "SynTree/Type.h"                // for Type, BasicType, PointerType
43#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
44#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
45#include "Tuples/Tuples.h"
46#include "typeops.h"                     // for extractResultType
47#include "Unify.h"                       // for unify
48
49using namespace std;
50
51namespace ResolvExpr {
52        struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting, public WithStmtsToAdd {
53                Resolver() {}
54                Resolver( const SymTab::Indexer & other ) {
55                        indexer = other;
56                }
57
58                void previsit( FunctionDecl *functionDecl );
59                void postvisit( FunctionDecl *functionDecl );
60                void previsit( ObjectDecl *objectDecll );
61                void previsit( TypeDecl *typeDecl );
62                void previsit( EnumDecl * enumDecl );
63                void previsit( StaticAssertDecl * assertDecl );
64
65                void previsit( ArrayType * at );
66                void previsit( PointerType * at );
67
68                void previsit( ExprStmt *exprStmt );
69                void previsit( AsmExpr *asmExpr );
70                void previsit( AsmStmt *asmStmt );
71                void previsit( IfStmt *ifStmt );
72                void previsit( WhileStmt *whileStmt );
73                void previsit( ForStmt *forStmt );
74                void previsit( SwitchStmt *switchStmt );
75                void previsit( CaseStmt *caseStmt );
76                void previsit( BranchStmt *branchStmt );
77                void previsit( ReturnStmt *returnStmt );
78                void previsit( ThrowStmt *throwStmt );
79                void previsit( CatchStmt *catchStmt );
80                void previsit( WaitForStmt * stmt );
81                void previsit( WithStmt * withStmt );
82
83                void previsit( SingleInit *singleInit );
84                void previsit( ListInit *listInit );
85                void previsit( ConstructorInit *ctorInit );
86          private:
87                typedef std::list< Initializer * >::iterator InitIterator;
88
89                template< typename PtrType >
90                void handlePtrType( PtrType * type );
91
92                void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
93                void fallbackInit( ConstructorInit * ctorInit );
94
95                Type * functionReturn = nullptr;
96                CurrentObject currentObject = nullptr;
97                bool inEnumDecl = false;
98        };
99
100        void resolve( std::list< Declaration * > translationUnit ) {
101                PassVisitor<Resolver> resolver;
102                acceptAll( translationUnit, resolver );
103        }
104
105        void resolveDecl( Declaration * decl, const SymTab::Indexer &indexer ) {
106                PassVisitor<Resolver> resolver( indexer );
107                maybeAccept( decl, resolver );
108        }
109
110        namespace {
111                struct DeleteFinder : public WithShortCircuiting        {
112                        DeletedExpr * delExpr = nullptr;
113                        void previsit( DeletedExpr * expr ) {
114                                if ( delExpr ) visit_children = false;
115                                else delExpr = expr;
116                        }
117
118                        void previsit( Expression * ) {
119                                if ( delExpr ) visit_children = false;
120                        }
121                };
122        }
123
124        DeletedExpr * findDeletedExpr( Expression * expr ) {
125                PassVisitor<DeleteFinder> finder;
126                expr->accept( finder );
127                return finder.pass.delExpr;
128        }
129
130        namespace {
131                struct StripCasts {
132                        Expression * postmutate( CastExpr * castExpr ) {
133                                if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
134                                        // generated cast is to the same type as its argument, so it's unnecessary -- remove it
135                                        Expression * expr = castExpr->arg;
136                                        castExpr->arg = nullptr;
137                                        std::swap( expr->env, castExpr->env );
138                                        return expr;
139                                }
140                                return castExpr;
141                        }
142
143                        static void strip( Expression *& expr ) {
144                                PassVisitor<StripCasts> stripper;
145                                expr = expr->acceptMutator( stripper );
146                        }
147                };
148
149                void finishExpr( Expression *&expr, const TypeEnvironment &env, TypeSubstitution * oldenv = nullptr ) {
150                        expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
151                        env.makeSubstitution( *expr->env );
152                        StripCasts::strip( expr ); // remove unnecessary casts that may be buried in an expression
153                }
154
155                void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
156                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
157                                if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
158                                        // cast is to the same type as its argument, so it's unnecessary -- remove it
159                                        expr = castExpr->arg;
160                                        castExpr->arg = nullptr;
161                                        std::swap( expr->env, castExpr->env );
162                                }
163                        }
164                }
165        } // namespace
166
167        namespace {
168                void findUnfinishedKindExpression( Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
169                        assertf( untyped, "expected a non-null expression." );
170
171                        auto guard = new_generation();  // set up GC generation for this top-level expression
172
173                        TypeEnvironment env;
174                        AlternativeFinder finder( indexer, env );
175                        finder.find( untyped, mode );
176
177                        #if 0
178                        if ( finder.get_alternatives().size() != 1 ) {
179                                std::cerr << "untyped expr is ";
180                                untyped->print( std::cerr );
181                                std::cerr << std::endl << "alternatives are:";
182                                for ( const Alternative & alt : finder.get_alternatives() ) {
183                                        alt.print( std::cerr );
184                                } // for
185                        } // if
186                        #endif
187
188                        AltList candidates;
189                        for ( Alternative & alt : finder.get_alternatives() ) {
190                                if ( pred( alt ) ) {
191                                        candidates.push_back( std::move( alt ) );
192                                }
193                        }
194
195                        // xxx - if > 1 alternative with same cost, ignore deleted and pick from remaining
196                        // choose the lowest cost expression among the candidates
197                        AltList winners;
198                        findMinCost( candidates.begin(), candidates.end(), back_inserter( winners ) );
199                        if ( winners.size() == 0 ) {
200                                SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
201                        } else if ( winners.size() != 1 ) {
202                                std::ostringstream stream;
203                                stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
204                                untyped->print( stream );
205                                stream << " Alternatives are:\n";
206                                printAlts( winners, stream, 1 );
207                                SemanticError( untyped->location, stream.str() );
208                        }
209
210                        // there is one unambiguous interpretation - move the expression into the with statement
211                        Alternative & choice = winners.front();
212                        if ( findDeletedExpr( choice.expr ) ) {
213                                trace( choice.expr );
214                                SemanticError( choice.expr, "Unique best alternative includes deleted identifier in " );
215                        }
216                        alt = std::move( choice );
217                        trace( alt );
218                }
219
220                /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
221                void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
222                        if ( ! untyped ) return;
223                        Alternative choice;
224                        findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
225                        finishExpr( choice.expr, choice.env, untyped->env );
226                        untyped = choice.expr;
227                        choice.expr = nullptr;
228                }
229
230                bool standardAlternativeFilter( const Alternative & ) {
231                        // currently don't need to filter, under normal circumstances.
232                        // in the future, this may be useful for removing deleted expressions
233                        return true;
234                }
235        } // namespace
236
237        // used in resolveTypeof
238        Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
239                TypeEnvironment env;
240                return resolveInVoidContext( expr, indexer, env );
241        }
242
243        Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
244                // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
245                // interpretations, an exception has already been thrown.
246                assertf( expr, "expected a non-null expression." );
247
248                auto untyped = new CastExpr{ expr }; // cast to void
249
250                // set up and resolve expression cast to void
251                Alternative choice;
252                findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
253                CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
254                env = std::move( choice.env );
255
256                // clean up resolved expression
257                return castExpr->arg;
258        }
259
260        void findVoidExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
261                resetTyVarRenaming();
262                TypeEnvironment env;
263                Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
264                finishExpr( newExpr, env, untyped->env );
265                untyped = newExpr;
266        }
267
268        void findSingleExpression( Expression *&untyped, const SymTab::Indexer &indexer ) {
269                findKindExpression( untyped, indexer, "", standardAlternativeFilter );
270        }
271
272        void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
273                assert( untyped && type );
274                untyped = new CastExpr( untyped, type );
275                findSingleExpression( untyped, indexer );
276                removeExtraneousCast( untyped, indexer );
277        }
278
279        namespace {
280                bool isIntegralType( const Alternative & alt ) {
281                        Type * type = alt.expr->result;
282                        if ( dynamic_cast< EnumInstType * >( type ) ) {
283                                return true;
284                        } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
285                                return bt->isInteger();
286                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
287                                return true;
288                        } else {
289                                return false;
290                        } // if
291                }
292
293                void findIntegralExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
294                        findKindExpression( untyped, indexer, "condition", isIntegralType );
295                }
296        }
297
298        void Resolver::previsit( ObjectDecl *objectDecl ) {
299                Type *new_type = resolveTypeof( objectDecl->get_type(), indexer );
300                objectDecl->set_type( new_type );
301                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
302                // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
303                // initContext because of a function type can contain object declarations in the return and parameter types. So
304                // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
305                // the RHS.
306                GuardValue( currentObject );
307                currentObject = CurrentObject( objectDecl->get_type() );
308                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
309                        // enumerator initializers should not use the enum type to initialize, since
310                        // the enum type is still incomplete at this point. Use signed int instead.
311                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
312                }
313        }
314
315        template< typename PtrType >
316        void Resolver::handlePtrType( PtrType * type ) {
317                if ( type->get_dimension() ) {
318                        findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
319                }
320        }
321
322        void Resolver::previsit( ArrayType * at ) {
323                handlePtrType( at );
324        }
325
326        void Resolver::previsit( PointerType * pt ) {
327                handlePtrType( pt );
328        }
329
330        void Resolver::previsit( TypeDecl *typeDecl ) {
331                if ( typeDecl->get_base() ) {
332                        Type *new_type = resolveTypeof( typeDecl->get_base(), indexer );
333                        typeDecl->set_base( new_type );
334                } // if
335        }
336
337        void Resolver::previsit( FunctionDecl *functionDecl ) {
338#if 0
339                std::cerr << "resolver visiting functiondecl ";
340                functionDecl->print( std::cerr );
341                std::cerr << std::endl;
342#endif
343                Type *new_type = resolveTypeof( functionDecl->type, indexer );
344                functionDecl->set_type( new_type );
345                GuardValue( functionReturn );
346                functionReturn = ResolvExpr::extractResultType( functionDecl->type );
347
348                {
349                        // resolve with-exprs with parameters in scope and add any newly generated declarations to the
350                        // front of the function body.
351                        auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
352                        indexer.addFunctionType( functionDecl->type );
353                        std::list< Statement * > newStmts;
354                        resolveWithExprs( functionDecl->withExprs, newStmts );
355                        if ( functionDecl->statements ) {
356                                functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
357                        } else {
358                                assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
359                        }
360                }
361        }
362
363        void Resolver::postvisit( FunctionDecl *functionDecl ) {
364                // default value expressions have an environment which shouldn't be there and trips up later passes.
365                // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
366                // see how it's useful.
367                for ( Declaration * d : functionDecl->type->parameters ) {
368                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
369                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
370                                        delete init->value->env;
371                                        init->value->env = nullptr;
372                                }
373                        }
374                }
375        }
376
377        void Resolver::previsit( EnumDecl * ) {
378                // in case we decide to allow nested enums
379                GuardValue( inEnumDecl );
380                inEnumDecl = true;
381        }
382
383        void Resolver::previsit( StaticAssertDecl * assertDecl ) {
384                findIntegralExpression( assertDecl->condition, indexer );
385        }
386
387        void Resolver::previsit( ExprStmt *exprStmt ) {
388                visit_children = false;
389                assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
390                findVoidExpression( exprStmt->expr, indexer );
391        }
392
393        void Resolver::previsit( AsmExpr *asmExpr ) {
394                visit_children = false;
395                findVoidExpression( asmExpr->operand, indexer );
396                if ( asmExpr->get_inout() ) {
397                        findVoidExpression( asmExpr->inout, indexer );
398                } // if
399        }
400
401        void Resolver::previsit( AsmStmt *asmStmt ) {
402                visit_children = false;
403                acceptAll( asmStmt->get_input(), *visitor );
404                acceptAll( asmStmt->get_output(), *visitor );
405        }
406
407        void Resolver::previsit( IfStmt *ifStmt ) {
408                findIntegralExpression( ifStmt->condition, indexer );
409        }
410
411        void Resolver::previsit( WhileStmt *whileStmt ) {
412                findIntegralExpression( whileStmt->condition, indexer );
413        }
414
415        void Resolver::previsit( ForStmt *forStmt ) {
416                if ( forStmt->condition ) {
417                        findIntegralExpression( forStmt->condition, indexer );
418                } // if
419
420                if ( forStmt->increment ) {
421                        findVoidExpression( forStmt->increment, indexer );
422                } // if
423        }
424
425        void Resolver::previsit( SwitchStmt *switchStmt ) {
426                GuardValue( currentObject );
427                findIntegralExpression( switchStmt->condition, indexer );
428
429                currentObject = CurrentObject( switchStmt->condition->result );
430        }
431
432        void Resolver::previsit( CaseStmt *caseStmt ) {
433                if ( caseStmt->condition ) {
434                        std::list< InitAlternative > initAlts = currentObject.getOptions();
435                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
436                        // must remove cast from case statement because RangeExpr cannot be cast.
437                        Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
438                        findSingleExpression( newExpr, indexer );
439                        // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
440                        // Ideally we would perform the conversion internally here.
441                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
442                                newExpr = castExpr->arg;
443                                castExpr->arg = nullptr;
444                                std::swap( newExpr->env, castExpr->env );
445                        }
446                        caseStmt->condition = newExpr;
447                }
448        }
449
450        void Resolver::previsit( BranchStmt *branchStmt ) {
451                visit_children = false;
452                // must resolve the argument for a computed goto
453                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
454                        if ( branchStmt->computedTarget ) {
455                                // computed goto argument is void *
456                                findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
457                        } // if
458                } // if
459        }
460
461        void Resolver::previsit( ReturnStmt *returnStmt ) {
462                visit_children = false;
463                if ( returnStmt->expr ) {
464                        findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
465                } // if
466        }
467
468        void Resolver::previsit( ThrowStmt *throwStmt ) {
469                visit_children = false;
470                // TODO: Replace *exception type with &exception type.
471                if ( throwStmt->get_expr() ) {
472                        StructDecl * exception_decl =
473                                indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
474                        assert( exception_decl );
475                        Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
476                        findSingleExpression( throwStmt->expr, exceptType, indexer );
477                }
478        }
479
480        void Resolver::previsit( CatchStmt *catchStmt ) {
481                if ( catchStmt->cond ) {
482                        findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
483                }
484        }
485
486        template< typename iterator_t >
487        inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
488                while( it != end && !(*it)->get_type()->get_mutex() ) {
489                        it++;
490                }
491
492                return it != end;
493        }
494
495        void Resolver::previsit( WaitForStmt * stmt ) {
496                visit_children = false;
497
498                // Resolve all clauses first
499                for( auto& clause : stmt->clauses ) {
500
501                        TypeEnvironment env;
502                        AlternativeFinder funcFinder( indexer, env );
503
504                        // Find all alternatives for a function in canonical form
505                        funcFinder.findWithAdjustment( clause.target.function );
506
507                        if ( funcFinder.get_alternatives().empty() ) {
508                                stringstream ss;
509                                ss << "Use of undeclared indentifier '";
510                                ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
511                                ss << "' in call to waitfor";
512                                SemanticError( stmt->location, ss.str() );
513                        }
514
515                        if(clause.target.arguments.empty()) {
516                                SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
517                        }
518
519                        // Find all alternatives for all arguments in canonical form
520                        std::vector< AlternativeFinder > argAlternatives;
521                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
522
523                        // List all combinations of arguments
524                        std::vector< AltList > possibilities;
525                        combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
526
527                        AltList                func_candidates;
528                        std::vector< AltList > args_candidates;
529
530                        // For every possible function :
531                        //      try matching the arguments to the parameters
532                        //      not the other way around because we have more arguments than parameters
533                        SemanticErrorException errors;
534                        for ( Alternative & func : funcFinder.get_alternatives() ) {
535                                try {
536                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
537                                        if( !pointer ) {
538                                                SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
539                                        }
540
541                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
542                                        if( !function ) {
543                                                SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
544                                        }
545
546
547                                        {
548                                                auto param     = function->parameters.begin();
549                                                auto param_end = function->parameters.end();
550
551                                                if( !advance_to_mutex( param, param_end ) ) {
552                                                        SemanticError(function, "candidate function not viable: no mutex parameters\n");
553                                                }
554                                        }
555
556                                        Alternative newFunc( func );
557                                        // Strip reference from function
558                                        referenceToRvalueConversion( newFunc.expr, newFunc.cost );
559
560                                        // For all the set of arguments we have try to match it with the parameter of the current function alternative
561                                        for ( auto & argsList : possibilities ) {
562
563                                                try {
564                                                        // Declare data structures need for resolution
565                                                        OpenVarSet openVars;
566                                                        AssertionSet resultNeed, resultHave;
567                                                        TypeEnvironment resultEnv( func.env );
568                                                        makeUnifiableVars( function, openVars, resultNeed );
569                                                        // add all type variables as open variables now so that those not used in the parameter
570                                                        // list are still considered open.
571                                                        resultEnv.add( function->forall );
572
573                                                        // Load type variables from arguemnts into one shared space
574                                                        simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
575
576                                                        // Make sure we don't widen any existing bindings
577                                                        for ( auto & i : resultEnv ) {
578                                                                i.allowWidening = false;
579                                                        }
580
581                                                        // Find any unbound type variables
582                                                        resultEnv.extractOpenVars( openVars );
583
584                                                        auto param     = function->parameters.begin();
585                                                        auto param_end = function->parameters.end();
586
587                                                        int n_mutex_arg = 0;
588
589                                                        // For every arguments of its set, check if it matches one of the parameter
590                                                        // The order is important
591                                                        for( auto & arg : argsList ) {
592
593                                                                // Ignore non-mutex arguments
594                                                                if( !advance_to_mutex( param, param_end ) ) {
595                                                                        // We ran out of parameters but still have arguments
596                                                                        // this function doesn't match
597                                                                        SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_arg, "\n" ));
598                                                                }
599
600                                                                n_mutex_arg++;
601
602                                                                // Check if the argument matches the parameter type in the current scope
603                                                                if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
604                                                                        // Type doesn't match
605                                                                        stringstream ss;
606                                                                        ss << "candidate function not viable: no known convertion from '";
607                                                                        (*param)->get_type()->print( ss );
608                                                                        ss << "' to '";
609                                                                        arg.expr->get_result()->print( ss );
610                                                                        ss << "' with env '";
611                                                                        resultEnv.print(ss);
612                                                                        ss << "'\n";
613                                                                        SemanticError( function, ss.str() );
614                                                                }
615
616                                                                param++;
617                                                        }
618
619                                                        // All arguments match !
620
621                                                        // Check if parameters are missing
622                                                        if( advance_to_mutex( param, param_end ) ) {
623                                                                // We ran out of arguments but still have parameters left
624                                                                // this function doesn't match
625                                                                SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_arg, "\n" ));
626                                                        }
627
628                                                        // All parameters match !
629
630                                                        // Finish the expressions to tie in the proper environments
631                                                        finishExpr( newFunc.expr, resultEnv );
632                                                        for( Alternative & alt : argsList ) {
633                                                                finishExpr( alt.expr, resultEnv );
634                                                        }
635
636                                                        // This is a match store it and save it for later
637                                                        func_candidates.push_back( newFunc );
638                                                        args_candidates.push_back( argsList );
639
640                                                }
641                                                catch( SemanticErrorException &e ) {
642                                                        errors.append( e );
643                                                }
644                                        }
645                                }
646                                catch( SemanticErrorException &e ) {
647                                        errors.append( e );
648                                }
649                        }
650
651                        // Make sure we got the right number of arguments
652                        if( func_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
653                        if( args_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
654                        if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
655                        if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
656                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
657
658                        // Swap the results from the alternative with the unresolved values.
659                        // Alternatives will handle deletion on destruction
660                        std::swap( clause.target.function, func_candidates.front().expr );
661                        for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
662                                std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
663                        }
664
665                        // Resolve the conditions as if it were an IfStmt
666                        // Resolve the statments normally
667                        findSingleExpression( clause.condition, this->indexer );
668                        clause.statement->accept( *visitor );
669                }
670
671
672                if( stmt->timeout.statement ) {
673                        // Resolve the timeout as an size_t for now
674                        // Resolve the conditions as if it were an IfStmt
675                        // Resolve the statments normally
676                        findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
677                        findSingleExpression( stmt->timeout.condition, this->indexer );
678                        stmt->timeout.statement->accept( *visitor );
679                }
680
681                if( stmt->orelse.statement ) {
682                        // Resolve the conditions as if it were an IfStmt
683                        // Resolve the statments normally
684                        findSingleExpression( stmt->orelse.condition, this->indexer );
685                        stmt->orelse.statement->accept( *visitor );
686                }
687        }
688
689        bool isStructOrUnion( const Alternative & alt ) {
690                Type * t = alt.expr->result->stripReferences();
691                return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
692        }
693
694        void Resolver::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
695                for ( Expression *& expr : withExprs )  {
696                        // only struct- and union-typed expressions are viable candidates
697                        findKindExpression( expr, indexer, "with statement", isStructOrUnion );
698
699                        // if with expression might be impure, create a temporary so that it is evaluated once
700                        if ( Tuples::maybeImpure( expr ) ) {
701                                static UniqueName tmpNamer( "_with_tmp_" );
702                                ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
703                                expr = new VariableExpr( tmp );
704                                newStmts.push_back( new DeclStmt( tmp ) );
705                                if ( InitTweak::isConstructable( tmp->type ) ) {
706                                        // generate ctor/dtor and resolve them
707                                        tmp->init = InitTweak::genCtorInit( tmp );
708                                        tmp->accept( *visitor );
709                                }
710                        }
711                }
712        }
713
714        void Resolver::previsit( WithStmt * withStmt ) {
715                resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
716        }
717
718        template< typename T >
719        bool isCharType( T t ) {
720                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
721                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
722                                bt->get_kind() == BasicType::UnsignedChar;
723                }
724                return false;
725        }
726
727        void Resolver::previsit( SingleInit *singleInit ) {
728                visit_children = false;
729                // resolve initialization using the possibilities as determined by the currentObject cursor
730                Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
731                findSingleExpression( newExpr, indexer );
732                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
733
734                // move cursor to the object that is actually initialized
735                currentObject.setNext( initExpr->get_designation() );
736
737                // discard InitExpr wrapper and retain relevant pieces
738                newExpr = initExpr->expr;
739                initExpr->expr = nullptr;
740                std::swap( initExpr->env, newExpr->env );
741                // InitExpr may have inferParams in the case where the expression specializes a function pointer,
742                // and newExpr may already have inferParams of its own, so a simple swap is not sufficient.
743                newExpr->spliceInferParams( initExpr );
744
745                // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
746                Type * initContext = currentObject.getCurrentType();
747
748                removeExtraneousCast( newExpr, indexer );
749
750                // check if actual object's type is char[]
751                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
752                        if ( isCharType( at->get_base() ) ) {
753                                // check if the resolved type is char *
754                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
755                                        if ( isCharType( pt->get_base() ) ) {
756                                                if ( CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ) ) {
757                                                        // strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
758                                                        newExpr = ce->get_arg();
759                                                        ce->set_arg( nullptr );
760                                                        std::swap( ce->env, newExpr->env );
761                                                }
762                                        }
763                                }
764                        }
765                }
766
767                // set initializer expr to resolved express
768                singleInit->value = newExpr;
769
770                // move cursor to next object in preparation for next initializer
771                currentObject.increment();
772        }
773
774        void Resolver::previsit( ListInit * listInit ) {
775                visit_children = false;
776                // move cursor into brace-enclosed initializer-list
777                currentObject.enterListInit();
778                // xxx - fix this so that the list isn't copied, iterator should be used to change current element
779                std::list<Designation *> newDesignations;
780                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
781                        // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
782                        // the initializer against that object.
783                        Designation * des = std::get<0>(p);
784                        Initializer * init = std::get<1>(p);
785                        newDesignations.push_back( currentObject.findNext( des ) );
786                        init->accept( *visitor );
787                }
788                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
789                listInit->get_designations() = newDesignations; // xxx - memory management
790                currentObject.exitListInit();
791
792                // xxx - this part has not be folded into CurrentObject yet
793                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
794                //      Type * base = tt->get_baseType()->get_base();
795                //      if ( base ) {
796                //              // know the implementation type, so try using that as the initContext
797                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
798                //              currentObject = &tmpObj;
799                //              visit( listInit );
800                //      } else {
801                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
802                //              Parent::visit( listInit );
803                //      }
804                // } else {
805        }
806
807        // ConstructorInit - fall back on C-style initializer
808        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
809                // could not find valid constructor, or found an intrinsic constructor
810                // fall back on C-style initializer
811                ctorInit->set_ctor( nullptr );
812                ctorInit->set_dtor( nullptr );
813                maybeAccept( ctorInit->get_init(), *visitor );
814        }
815
816        // needs to be callable from outside the resolver, so this is a standalone function
817        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
818                assert( ctorInit );
819                PassVisitor<Resolver> resolver( indexer );
820                ctorInit->accept( resolver );
821        }
822
823        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
824                assert( stmtExpr );
825                PassVisitor<Resolver> resolver( indexer );
826                stmtExpr->accept( resolver );
827                stmtExpr->computeResult();
828                // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
829        }
830
831        void Resolver::previsit( ConstructorInit *ctorInit ) {
832                visit_children = false;
833                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
834                maybeAccept( ctorInit->ctor, *visitor );
835                maybeAccept( ctorInit->dtor, *visitor );
836
837                // found a constructor - can get rid of C-style initializer
838                ctorInit->init = nullptr;
839
840                // intrinsic single parameter constructors and destructors do nothing. Since this was
841                // implicitly generated, there's no way for it to have side effects, so get rid of it
842                // to clean up generated code.
843                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
844                        ctorInit->ctor = nullptr;
845                }
846
847                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
848                        ctorInit->dtor = nullptr;
849                }
850
851                // xxx - todo -- what about arrays?
852                // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
853                //      // can reduce the constructor down to a SingleInit using the
854                //      // second argument from the ctor call, since
855                //      delete ctorInit->get_ctor();
856                //      ctorInit->set_ctor( NULL );
857
858                //      Expression * arg =
859                //      ctorInit->set_init( new SingleInit( arg ) );
860                // }
861        }
862} // namespace ResolvExpr
863
864// Local Variables: //
865// tab-width: 4 //
866// mode: c++ //
867// compile-command: "make install" //
868// End: //
Note: See TracBrowser for help on using the repository browser.