source: src/ResolvExpr/Resolver.cc @ 1cdfa82

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

Merge remote-tracking branch 'origin/master' into with_gc

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