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

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 6a8df56 was a181494, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Adding cost for reference-to-rvalue conversions

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