source: src/ResolvExpr/Resolver.cc @ 4edf753

resolv-new
Last change on this file since 4edf753 was 4edf753, checked in by Aaron Moss <a3moss@…>, 7 years ago

Added deleted expression support to waitfor

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