source: src/ResolvExpr/Resolver.cc @ 04570c7

new-envwith_gc
Last change on this file since 04570c7 was f229fc2, checked in by Aaron Moss <a3moss@…>, 6 years ago

Modify resolver to use young-generation collection per-top-level expression

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