source: src/ResolvExpr/Resolver.cc @ 8573729

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

Start new assertion resolution branch

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