source: src/ResolvExpr/Resolver.cc @ d76c588

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since d76c588 was d76c588, checked in by Aaron Moss <a3moss@…>, 5 years ago

Stubs for new resolver, implementation of new indexer, type environment

  • Property mode set to 100644
File size: 39.4 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           : Aaron B. Moss
10// Created On       : Sun May 17 12:17:01 2015
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Wed May 29 11:00:00 2019
13// Update Count     : 241
14//
15
16#include <cassert>                       // for strict_dynamic_cast, assert
17#include <memory>                        // for allocator, allocator_traits<...
18#include <tuple>                         // for get
19#include <vector>                        // for vector
20
21#include "Alternative.h"                 // for Alternative, AltList
22#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
23#include "CurrentObject.h"               // for CurrentObject
24#include "RenameVars.h"                  // for RenameVars, global_renamer
25#include "Resolver.h"
26#include "ResolvMode.h"                  // for ResolvMode
27#include "typeops.h"                     // for extractResultType
28#include "Unify.h"                       // for unify
29#include "AST/Pass.hpp"
30#include "AST/SymbolTable.hpp"
31#include "Common/PassVisitor.h"          // for PassVisitor
32#include "Common/SemanticError.h"        // for SemanticError
33#include "Common/utility.h"              // for ValueGuard, group_iterate
34#include "InitTweak/GenInit.h"
35#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
36#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
37#include "SymTab/Autogen.h"              // for SizeType
38#include "SymTab/Indexer.h"              // for Indexer
39#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
40#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
41#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
42#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
43#include "SynTree/Type.h"                // for Type, BasicType, PointerType
44#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
45#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
46#include "Tuples/Tuples.h"
47
48using namespace std;
49
50namespace ResolvExpr {
51        struct Resolver_old final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver_old>, public WithShortCircuiting, public WithStmtsToAdd {
52                Resolver_old() {}
53                Resolver_old( 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( EnumDecl * enumDecl );
61                void previsit( StaticAssertDecl * assertDecl );
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
80                void previsit( SingleInit * singleInit );
81                void previsit( ListInit * listInit );
82                void previsit( ConstructorInit * ctorInit );
83          private:
84                typedef std::list< Initializer * >::iterator InitIterator;
85
86                template< typename PtrType >
87                void handlePtrType( PtrType * type );
88
89                void fallbackInit( ConstructorInit * ctorInit );
90
91                Type * functionReturn = nullptr;
92                CurrentObject currentObject = nullptr;
93                bool inEnumDecl = false;
94        };
95
96        struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd {
97                void previsit( FunctionDecl * );
98                void previsit( WithStmt * );
99
100                void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
101        };
102
103        void resolve( std::list< Declaration * > translationUnit ) {
104                PassVisitor<Resolver_old> resolver;
105                acceptAll( translationUnit, resolver );
106        }
107
108        void resolveDecl( Declaration * decl, const SymTab::Indexer & indexer ) {
109                PassVisitor<Resolver_old> resolver( indexer );
110                maybeAccept( decl, resolver );
111        }
112
113        namespace {
114                struct DeleteFinder : public WithShortCircuiting        {
115                        DeletedExpr * delExpr = nullptr;
116                        void previsit( DeletedExpr * expr ) {
117                                if ( delExpr ) visit_children = false;
118                                else delExpr = expr;
119                        }
120
121                        void previsit( Expression * ) {
122                                if ( delExpr ) visit_children = false;
123                        }
124                };
125        }
126
127        DeletedExpr * findDeletedExpr( Expression * expr ) {
128                PassVisitor<DeleteFinder> finder;
129                expr->accept( finder );
130                return finder.pass.delExpr;
131        }
132
133        namespace {
134                struct StripCasts {
135                        Expression * postmutate( CastExpr * castExpr ) {
136                                if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
137                                        // generated cast is to the same type as its argument, so it's unnecessary -- remove it
138                                        Expression * expr = castExpr->arg;
139                                        castExpr->arg = nullptr;
140                                        std::swap( expr->env, castExpr->env );
141                                        return expr;
142                                }
143                                return castExpr;
144                        }
145
146                        static void strip( Expression *& expr ) {
147                                PassVisitor<StripCasts> stripper;
148                                expr = expr->acceptMutator( stripper );
149                        }
150                };
151
152                void finishExpr( Expression *& expr, const TypeEnvironment & env, TypeSubstitution * oldenv = nullptr ) {
153                        expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
154                        env.makeSubstitution( *expr->env );
155                        StripCasts::strip( expr ); // remove unnecessary casts that may be buried in an expression
156                }
157
158                void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
159                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
160                                if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
161                                        // cast is to the same type as its argument, so it's unnecessary -- remove it
162                                        expr = castExpr->arg;
163                                        castExpr->arg = nullptr;
164                                        std::swap( expr->env, castExpr->env );
165                                        delete castExpr;
166                                }
167                        }
168                }
169        } // namespace
170
171        namespace {
172                void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
173                        assertf( untyped, "expected a non-null expression." );
174
175                        // xxx - this isn't thread-safe, but should work until we parallelize the resolver
176                        static unsigned recursion_level = 0;
177
178                        ++recursion_level;
179                        TypeEnvironment env;
180                        AlternativeFinder finder( indexer, env );
181                        finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
182                        --recursion_level;
183
184                        #if 0
185                        if ( finder.get_alternatives().size() != 1 ) {
186                                std::cerr << "untyped expr is ";
187                                untyped->print( std::cerr );
188                                std::cerr << std::endl << "alternatives are:";
189                                for ( const Alternative & alt : finder.get_alternatives() ) {
190                                        alt.print( std::cerr );
191                                } // for
192                        } // if
193                        #endif
194
195                        // produce filtered list of alternatives
196                        AltList candidates;
197                        for ( Alternative & alt : finder.get_alternatives() ) {
198                                if ( pred( alt ) ) {
199                                        candidates.push_back( std::move( alt ) );
200                                }
201                        }
202
203                        // produce invalid error if no candidates
204                        if ( candidates.empty() ) {
205                                SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
206                        }
207
208                        // search for cheapest candidate
209                        AltList winners;
210                        bool seen_undeleted = false;
211                        for ( unsigned i = 0; i < candidates.size(); ++i ) {
212                                int c = winners.empty() ? -1 : candidates[i].cost.compare( winners.front().cost );
213
214                                if ( c > 0 ) continue; // skip more expensive than winner
215
216                                if ( c < 0 ) {
217                                        // reset on new cheapest
218                                        seen_undeleted = ! findDeletedExpr( candidates[i].expr );
219                                        winners.clear();
220                                } else /* if ( c == 0 ) */ {
221                                        if ( findDeletedExpr( candidates[i].expr ) ) {
222                                                // skip deleted expression if already seen one equivalent-cost not
223                                                if ( seen_undeleted ) continue;
224                                        } else if ( ! seen_undeleted ) {
225                                                // replace list of equivalent-cost deleted expressions with one non-deleted
226                                                winners.clear();
227                                                seen_undeleted = true;
228                                        }
229                                }
230
231                                winners.emplace_back( std::move( candidates[i] ) );
232                        }
233
234                        // promote alternative.cvtCost to .cost
235                        // xxx - I don't know why this is done, but I'm keeping the behaviour from findMinCost
236                        for ( Alternative& winner : winners ) {
237                                winner.cost = winner.cvtCost;
238                        }
239                       
240                        // produce ambiguous errors, if applicable
241                        if ( winners.size() != 1 ) {
242                                std::ostringstream stream;
243                                stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
244                                untyped->print( stream );
245                                stream << " Alternatives are:\n";
246                                printAlts( winners, stream, 1 );
247                                SemanticError( untyped->location, stream.str() );
248                        }
249
250                        // single selected choice
251                        Alternative& choice = winners.front();
252
253                        // fail on only expression deleted
254                        if ( ! seen_undeleted ) {
255                                SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
256                        }
257
258                        // xxx - check for ambiguous expressions
259                       
260                        // output selected choice
261                        alt = std::move( choice );
262                }
263
264                /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
265                void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
266                        if ( ! untyped ) return;
267                        Alternative choice;
268                        findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
269                        finishExpr( choice.expr, choice.env, untyped->env );
270                        delete untyped;
271                        untyped = choice.expr;
272                        choice.expr = nullptr;
273                }
274
275                bool standardAlternativeFilter( const Alternative & ) {
276                        // currently don't need to filter, under normal circumstances.
277                        // in the future, this may be useful for removing deleted expressions
278                        return true;
279                }
280        } // namespace
281
282        // used in resolveTypeof
283        Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer ) {
284                TypeEnvironment env;
285                return resolveInVoidContext( expr, indexer, env );
286        }
287
288        Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer, TypeEnvironment & env ) {
289                // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
290                // interpretations, an exception has already been thrown.
291                assertf( expr, "expected a non-null expression." );
292
293                CastExpr * untyped = new CastExpr( expr ); // cast to void
294                untyped->location = expr->location;
295
296                // set up and resolve expression cast to void
297                Alternative choice;
298                findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
299                CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
300                assert( castExpr );
301                env = std::move( choice.env );
302
303                // clean up resolved expression
304                Expression * ret = castExpr->arg;
305                castExpr->arg = nullptr;
306
307                // unlink the arg so that it isn't deleted twice at the end of the program
308                untyped->arg = nullptr;
309                return ret;
310        }
311
312        void findVoidExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
313                resetTyVarRenaming();
314                TypeEnvironment env;
315                Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
316                finishExpr( newExpr, env, untyped->env );
317                delete untyped;
318                untyped = newExpr;
319        }
320
321        void findSingleExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
322                findKindExpression( untyped, indexer, "", standardAlternativeFilter );
323        }
324
325        void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
326                assert( untyped && type );
327                // transfer location to generated cast for error purposes
328                CodeLocation location = untyped->location;
329                untyped = new CastExpr( untyped, type );
330                untyped->location = location;
331                findSingleExpression( untyped, indexer );
332                removeExtraneousCast( untyped, indexer );
333        }
334
335        namespace {
336                bool isIntegralType( const Alternative & alt ) {
337                        Type * type = alt.expr->result;
338                        if ( dynamic_cast< EnumInstType * >( type ) ) {
339                                return true;
340                        } else if ( BasicType * bt = dynamic_cast< BasicType * >( type ) ) {
341                                return bt->isInteger();
342                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
343                                return true;
344                        } else {
345                                return false;
346                        } // if
347                }
348
349                void findIntegralExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
350                        findKindExpression( untyped, indexer, "condition", isIntegralType );
351                }
352        }
353
354
355        bool isStructOrUnion( const Alternative & alt ) {
356                Type * t = alt.expr->result->stripReferences();
357                return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
358        }
359
360        void resolveWithExprs( std::list< Declaration * > & translationUnit ) {
361                PassVisitor<ResolveWithExprs> resolver;
362                acceptAll( translationUnit, resolver );
363        }
364
365        void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
366                for ( Expression *& expr : withExprs )  {
367                        // only struct- and union-typed expressions are viable candidates
368                        findKindExpression( expr, indexer, "with statement", isStructOrUnion );
369
370                        // if with expression might be impure, create a temporary so that it is evaluated once
371                        if ( Tuples::maybeImpure( expr ) ) {
372                                static UniqueName tmpNamer( "_with_tmp_" );
373                                ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
374                                expr = new VariableExpr( tmp );
375                                newStmts.push_back( new DeclStmt( tmp ) );
376                                if ( InitTweak::isConstructable( tmp->type ) ) {
377                                        // generate ctor/dtor and resolve them
378                                        tmp->init = InitTweak::genCtorInit( tmp );
379                                        tmp->accept( *visitor );
380                                }
381                        }
382                }
383        }
384
385        void ResolveWithExprs::previsit( WithStmt * withStmt ) {
386                resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
387        }
388
389        void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) {
390                {
391                        // resolve with-exprs with parameters in scope and add any newly generated declarations to the
392                        // front of the function body.
393                        auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
394                        indexer.addFunctionType( functionDecl->type );
395                        std::list< Statement * > newStmts;
396                        resolveWithExprs( functionDecl->withExprs, newStmts );
397                        if ( functionDecl->statements ) {
398                                functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
399                        } else {
400                                assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
401                        }
402                }
403        }
404
405        void Resolver_old::previsit( ObjectDecl * objectDecl ) {
406                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that
407                // class-variable initContext is changed multiple time because the LHS is analysed twice.
408                // The second analysis changes initContext because of a function type can contain object
409                // declarations in the return and parameter types. So each value of initContext is
410                // retained, so the type on the first analysis is preserved and used for selecting the RHS.
411                GuardValue( currentObject );
412                currentObject = CurrentObject( objectDecl->get_type() );
413                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
414                        // enumerator initializers should not use the enum type to initialize, since
415                        // the enum type is still incomplete at this point. Use signed int instead.
416                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
417                }
418        }
419
420        template< typename PtrType >
421        void Resolver_old::handlePtrType( PtrType * type ) {
422                if ( type->get_dimension() ) {
423                        findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
424                }
425        }
426
427        void Resolver_old::previsit( ArrayType * at ) {
428                handlePtrType( at );
429        }
430
431        void Resolver_old::previsit( PointerType * pt ) {
432                handlePtrType( pt );
433        }
434
435        void Resolver_old::previsit( FunctionDecl * functionDecl ) {
436#if 0
437                std::cerr << "resolver visiting functiondecl ";
438                functionDecl->print( std::cerr );
439                std::cerr << std::endl;
440#endif
441                GuardValue( functionReturn );
442                functionReturn = ResolvExpr::extractResultType( functionDecl->type );
443        }
444
445        void Resolver_old::postvisit( FunctionDecl * functionDecl ) {
446                // default value expressions have an environment which shouldn't be there and trips up
447                // later passes.
448                // xxx - it might be necessary to somehow keep the information from this environment, but I
449                // can't currently see how it's useful.
450                for ( Declaration * d : functionDecl->type->parameters ) {
451                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
452                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
453                                        delete init->value->env;
454                                        init->value->env = nullptr;
455                                }
456                        }
457                }
458        }
459
460        void Resolver_old::previsit( EnumDecl * ) {
461                // in case we decide to allow nested enums
462                GuardValue( inEnumDecl );
463                inEnumDecl = true;
464        }
465
466        void Resolver_old::previsit( StaticAssertDecl * assertDecl ) {
467                findIntegralExpression( assertDecl->condition, indexer );
468        }
469
470        void Resolver_old::previsit( ExprStmt * exprStmt ) {
471                visit_children = false;
472                assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
473                findVoidExpression( exprStmt->expr, indexer );
474        }
475
476        void Resolver_old::previsit( AsmExpr * asmExpr ) {
477                visit_children = false;
478                findVoidExpression( asmExpr->operand, indexer );
479                if ( asmExpr->get_inout() ) {
480                        findVoidExpression( asmExpr->inout, indexer );
481                } // if
482        }
483
484        void Resolver_old::previsit( AsmStmt * asmStmt ) {
485                visit_children = false;
486                acceptAll( asmStmt->get_input(), *visitor );
487                acceptAll( asmStmt->get_output(), *visitor );
488        }
489
490        void Resolver_old::previsit( IfStmt * ifStmt ) {
491                findIntegralExpression( ifStmt->condition, indexer );
492        }
493
494        void Resolver_old::previsit( WhileStmt * whileStmt ) {
495                findIntegralExpression( whileStmt->condition, indexer );
496        }
497
498        void Resolver_old::previsit( ForStmt * forStmt ) {
499                if ( forStmt->condition ) {
500                        findIntegralExpression( forStmt->condition, indexer );
501                } // if
502
503                if ( forStmt->increment ) {
504                        findVoidExpression( forStmt->increment, indexer );
505                } // if
506        }
507
508        void Resolver_old::previsit( SwitchStmt * switchStmt ) {
509                GuardValue( currentObject );
510                findIntegralExpression( switchStmt->condition, indexer );
511
512                currentObject = CurrentObject( switchStmt->condition->result );
513        }
514
515        void Resolver_old::previsit( CaseStmt * caseStmt ) {
516                if ( caseStmt->condition ) {
517                        std::list< InitAlternative > initAlts = currentObject.getOptions();
518                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
519                        // must remove cast from case statement because RangeExpr cannot be cast.
520                        Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
521                        findSingleExpression( newExpr, indexer );
522                        // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
523                        // Ideally we would perform the conversion internally here.
524                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
525                                newExpr = castExpr->arg;
526                                castExpr->arg = nullptr;
527                                std::swap( newExpr->env, castExpr->env );
528                                delete castExpr;
529                        }
530                        caseStmt->condition = newExpr;
531                }
532        }
533
534        void Resolver_old::previsit( BranchStmt * branchStmt ) {
535                visit_children = false;
536                // must resolve the argument for a computed goto
537                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
538                        if ( branchStmt->computedTarget ) {
539                                // computed goto argument is void *
540                                findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
541                        } // if
542                } // if
543        }
544
545        void Resolver_old::previsit( ReturnStmt * returnStmt ) {
546                visit_children = false;
547                if ( returnStmt->expr ) {
548                        findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
549                } // if
550        }
551
552        void Resolver_old::previsit( ThrowStmt * throwStmt ) {
553                visit_children = false;
554                // TODO: Replace *exception type with &exception type.
555                if ( throwStmt->get_expr() ) {
556                        StructDecl * exception_decl =
557                                indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
558                        assert( exception_decl );
559                        Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
560                        findSingleExpression( throwStmt->expr, exceptType, indexer );
561                }
562        }
563
564        void Resolver_old::previsit( CatchStmt * catchStmt ) {
565                if ( catchStmt->cond ) {
566                        findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
567                }
568        }
569
570        template< typename iterator_t >
571        inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
572                while( it != end && !(*it)->get_type()->get_mutex() ) {
573                        it++;
574                }
575
576                return it != end;
577        }
578
579        void Resolver_old::previsit( WaitForStmt * stmt ) {
580                visit_children = false;
581
582                // Resolve all clauses first
583                for( auto& clause : stmt->clauses ) {
584
585                        TypeEnvironment env;
586                        AlternativeFinder funcFinder( indexer, env );
587
588                        // Find all alternatives for a function in canonical form
589                        funcFinder.findWithAdjustment( clause.target.function );
590
591                        if ( funcFinder.get_alternatives().empty() ) {
592                                stringstream ss;
593                                ss << "Use of undeclared indentifier '";
594                                ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
595                                ss << "' in call to waitfor";
596                                SemanticError( stmt->location, ss.str() );
597                        }
598
599                        if(clause.target.arguments.empty()) {
600                                SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
601                        }
602
603                        // Find all alternatives for all arguments in canonical form
604                        std::vector< AlternativeFinder > argAlternatives;
605                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
606
607                        // List all combinations of arguments
608                        std::vector< AltList > possibilities;
609                        combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
610
611                        AltList                func_candidates;
612                        std::vector< AltList > args_candidates;
613
614                        // For every possible function :
615                        //      try matching the arguments to the parameters
616                        //      not the other way around because we have more arguments than parameters
617                        SemanticErrorException errors;
618                        for ( Alternative & func : funcFinder.get_alternatives() ) {
619                                try {
620                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
621                                        if( !pointer ) {
622                                                SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
623                                        }
624
625                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
626                                        if( !function ) {
627                                                SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
628                                        }
629
630
631                                        {
632                                                auto param     = function->parameters.begin();
633                                                auto param_end = function->parameters.end();
634
635                                                if( !advance_to_mutex( param, param_end ) ) {
636                                                        SemanticError(function, "candidate function not viable: no mutex parameters\n");
637                                                }
638                                        }
639
640                                        Alternative newFunc( func );
641                                        // Strip reference from function
642                                        referenceToRvalueConversion( newFunc.expr, newFunc.cost );
643
644                                        // For all the set of arguments we have try to match it with the parameter of the current function alternative
645                                        for ( auto & argsList : possibilities ) {
646
647                                                try {
648                                                        // Declare data structures need for resolution
649                                                        OpenVarSet openVars;
650                                                        AssertionSet resultNeed, resultHave;
651                                                        TypeEnvironment resultEnv( func.env );
652                                                        makeUnifiableVars( function, openVars, resultNeed );
653                                                        // add all type variables as open variables now so that those not used in the parameter
654                                                        // list are still considered open.
655                                                        resultEnv.add( function->forall );
656
657                                                        // Load type variables from arguemnts into one shared space
658                                                        simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
659
660                                                        // Make sure we don't widen any existing bindings
661                                                        resultEnv.forbidWidening();
662
663                                                        // Find any unbound type variables
664                                                        resultEnv.extractOpenVars( openVars );
665
666                                                        auto param     = function->parameters.begin();
667                                                        auto param_end = function->parameters.end();
668
669                                                        int n_mutex_param = 0;
670
671                                                        // For every arguments of its set, check if it matches one of the parameter
672                                                        // The order is important
673                                                        for( auto & arg : argsList ) {
674
675                                                                // Ignore non-mutex arguments
676                                                                if( !advance_to_mutex( param, param_end ) ) {
677                                                                        // We ran out of parameters but still have arguments
678                                                                        // this function doesn't match
679                                                                        SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
680                                                                }
681
682                                                                n_mutex_param++;
683
684                                                                // Check if the argument matches the parameter type in the current scope
685                                                                if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
686                                                                        // Type doesn't match
687                                                                        stringstream ss;
688                                                                        ss << "candidate function not viable: no known convertion from '";
689                                                                        (*param)->get_type()->print( ss );
690                                                                        ss << "' to '";
691                                                                        arg.expr->get_result()->print( ss );
692                                                                        ss << "' with env '";
693                                                                        resultEnv.print(ss);
694                                                                        ss << "'\n";
695                                                                        SemanticError( function, ss.str() );
696                                                                }
697
698                                                                param++;
699                                                        }
700
701                                                        // All arguments match !
702
703                                                        // Check if parameters are missing
704                                                        if( advance_to_mutex( param, param_end ) ) {
705                                                                do {
706                                                                        n_mutex_param++;
707                                                                        param++;
708                                                                } while( advance_to_mutex( param, param_end ) );
709
710                                                                // We ran out of arguments but still have parameters left
711                                                                // this function doesn't match
712                                                                SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
713                                                        }
714
715                                                        // All parameters match !
716
717                                                        // Finish the expressions to tie in the proper environments
718                                                        finishExpr( newFunc.expr, resultEnv );
719                                                        for( Alternative & alt : argsList ) {
720                                                                finishExpr( alt.expr, resultEnv );
721                                                        }
722
723                                                        // This is a match store it and save it for later
724                                                        func_candidates.push_back( newFunc );
725                                                        args_candidates.push_back( argsList );
726
727                                                }
728                                                catch( SemanticErrorException & e ) {
729                                                        errors.append( e );
730                                                }
731                                        }
732                                }
733                                catch( SemanticErrorException & e ) {
734                                        errors.append( e );
735                                }
736                        }
737
738                        // Make sure we got the right number of arguments
739                        if( func_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
740                        if( args_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
741                        if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
742                        if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
743                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
744
745                        // Swap the results from the alternative with the unresolved values.
746                        // Alternatives will handle deletion on destruction
747                        std::swap( clause.target.function, func_candidates.front().expr );
748                        for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
749                                std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
750                        }
751
752                        // Resolve the conditions as if it were an IfStmt
753                        // Resolve the statments normally
754                        findSingleExpression( clause.condition, this->indexer );
755                        clause.statement->accept( *visitor );
756                }
757
758
759                if( stmt->timeout.statement ) {
760                        // Resolve the timeout as an size_t for now
761                        // Resolve the conditions as if it were an IfStmt
762                        // Resolve the statments normally
763                        findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
764                        findSingleExpression( stmt->timeout.condition, this->indexer );
765                        stmt->timeout.statement->accept( *visitor );
766                }
767
768                if( stmt->orelse.statement ) {
769                        // Resolve the conditions as if it were an IfStmt
770                        // Resolve the statments normally
771                        findSingleExpression( stmt->orelse.condition, this->indexer );
772                        stmt->orelse.statement->accept( *visitor );
773                }
774        }
775
776        template< typename T >
777        bool isCharType( T t ) {
778                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
779                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
780                                bt->get_kind() == BasicType::UnsignedChar;
781                }
782                return false;
783        }
784
785        void Resolver_old::previsit( SingleInit * singleInit ) {
786                visit_children = false;
787                // resolve initialization using the possibilities as determined by the currentObject cursor
788                Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
789                findSingleExpression( newExpr, indexer );
790                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
791
792                // move cursor to the object that is actually initialized
793                currentObject.setNext( initExpr->get_designation() );
794
795                // discard InitExpr wrapper and retain relevant pieces
796                newExpr = initExpr->expr;
797                initExpr->expr = nullptr;
798                std::swap( initExpr->env, newExpr->env );
799                // InitExpr may have inferParams in the case where the expression specializes a function
800                // pointer, and newExpr may already have inferParams of its own, so a simple swap is not
801                // sufficient.
802                newExpr->spliceInferParams( initExpr );
803                delete initExpr;
804
805                // get the actual object's type (may not exactly match what comes back from the resolver
806                // due to conversions)
807                Type * initContext = currentObject.getCurrentType();
808
809                removeExtraneousCast( newExpr, indexer );
810
811                // check if actual object's type is char[]
812                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
813                        if ( isCharType( at->get_base() ) ) {
814                                // check if the resolved type is char *
815                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
816                                        if ( isCharType( pt->get_base() ) ) {
817                                                if ( CastExpr * ce = dynamic_cast< CastExpr * >( newExpr ) ) {
818                                                        // strip cast if we're initializing a char[] with a char *,
819                                                        // e.g.  char x[] = "hello";
820                                                        newExpr = ce->get_arg();
821                                                        ce->set_arg( nullptr );
822                                                        std::swap( ce->env, newExpr->env );
823                                                        delete ce;
824                                                }
825                                        }
826                                }
827                        }
828                }
829
830                // set initializer expr to resolved express
831                singleInit->value = newExpr;
832
833                // move cursor to next object in preparation for next initializer
834                currentObject.increment();
835        }
836
837        void Resolver_old::previsit( ListInit * listInit ) {
838                visit_children = false;
839                // move cursor into brace-enclosed initializer-list
840                currentObject.enterListInit();
841                // xxx - fix this so that the list isn't copied, iterator should be used to change current
842                // element
843                std::list<Designation *> newDesignations;
844                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
845                        // iterate designations and initializers in pairs, moving the cursor to the current
846                        // designated object and resolving the initializer against that object.
847                        Designation * des = std::get<0>(p);
848                        Initializer * init = std::get<1>(p);
849                        newDesignations.push_back( currentObject.findNext( des ) );
850                        init->accept( *visitor );
851                }
852                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
853                listInit->get_designations() = newDesignations; // xxx - memory management
854                currentObject.exitListInit();
855
856                // xxx - this part has not be folded into CurrentObject yet
857                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
858                //      Type * base = tt->get_baseType()->get_base();
859                //      if ( base ) {
860                //              // know the implementation type, so try using that as the initContext
861                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
862                //              currentObject = &tmpObj;
863                //              visit( listInit );
864                //      } else {
865                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
866                //              Parent::visit( listInit );
867                //      }
868                // } else {
869        }
870
871        // ConstructorInit - fall back on C-style initializer
872        void Resolver_old::fallbackInit( ConstructorInit * ctorInit ) {
873                // could not find valid constructor, or found an intrinsic constructor
874                // fall back on C-style initializer
875                delete ctorInit->get_ctor();
876                ctorInit->set_ctor( nullptr );
877                delete ctorInit->get_dtor();
878                ctorInit->set_dtor( nullptr );
879                maybeAccept( ctorInit->get_init(), *visitor );
880        }
881
882        // needs to be callable from outside the resolver, so this is a standalone function
883        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
884                assert( ctorInit );
885                PassVisitor<Resolver_old> resolver( indexer );
886                ctorInit->accept( resolver );
887        }
888
889        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
890                assert( stmtExpr );
891                PassVisitor<Resolver_old> resolver( indexer );
892                stmtExpr->accept( resolver );
893                stmtExpr->computeResult();
894                // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
895        }
896
897        void Resolver_old::previsit( ConstructorInit * ctorInit ) {
898                visit_children = false;
899                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
900                maybeAccept( ctorInit->ctor, *visitor );
901                maybeAccept( ctorInit->dtor, *visitor );
902
903                // found a constructor - can get rid of C-style initializer
904                delete ctorInit->init;
905                ctorInit->init = nullptr;
906
907                // intrinsic single parameter constructors and destructors do nothing. Since this was
908                // implicitly generated, there's no way for it to have side effects, so get rid of it
909                // to clean up generated code.
910                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
911                        delete ctorInit->ctor;
912                        ctorInit->ctor = nullptr;
913                }
914
915                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
916                        delete ctorInit->dtor;
917                        ctorInit->dtor = nullptr;
918                }
919
920                // xxx - todo -- what about arrays?
921                // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
922                //      // can reduce the constructor down to a SingleInit using the
923                //      // second argument from the ctor call, since
924                //      delete ctorInit->get_ctor();
925                //      ctorInit->set_ctor( nullptr );
926
927                //      Expression * arg =
928                //      ctorInit->set_init( new SingleInit( arg ) );
929                // }
930        }
931
932        ///////////////////////////////////////////////////////////////////////////
933        //
934        // *** NEW RESOLVER ***
935        //
936        ///////////////////////////////////////////////////////////////////////////
937
938        class Resolver_new final 
939        : public ast::WithIndexer, public ast::WithGuards, public ast::WithVisitorRef<Resolver_new>, 
940          public ast::WithShortCircuiting, public ast::WithStmtsToAdd<> {
941                 
942        public: 
943                Resolver_new() = default;
944                Resolver_new( const ast::SymbolTable & syms ) { /*symtab = syms;*/ }
945
946                void previsit( ast::FunctionDecl * functionDecl );
947                ast::DeclWithType * postvisit( ast::FunctionDecl * functionDecl );
948                void previsit( ast::ObjectDecl * objectDecl );
949                void previsit( ast::EnumDecl * enumDecl );
950                void previsit( ast::StaticAssertDecl * assertDecl );
951
952                void previsit( ast::ArrayType * at );
953                void previsit( ast::PointerType * pt );
954
955                void previsit( ast::ExprStmt * exprStmt );
956                void previsit( ast::AsmExpr * asmExpr );
957                void previsit( ast::AsmStmt * asmStmt );
958                void previsit( ast::IfStmt * ifStmt );
959                void previsit( ast::WhileStmt * whileStmt );
960                void previsit( ast::ForStmt * forStmt );
961                void previsit( ast::SwitchStmt * switchStmt );
962                void previsit( ast::CaseStmt * caseStmt );
963                void previsit( ast::BranchStmt * branchStmt );
964                void previsit( ast::ReturnStmt * returnStmt );
965                void previsit( ast::ThrowStmt * throwStmt );
966                void previsit( ast::CatchStmt * catchStmt );
967                void previsit( ast::WaitForStmt * stmt );
968
969                void previsit( ast::SingleInit * singleInit );
970                void previsit( ast::ListInit * listInit );
971                void previsit( ast::ConstructorInit * ctorInit );
972        };
973
974        void resolve( std::list< ast::ptr<ast::Decl> >& translationUnit ) {
975                ast::Pass<Resolver_new> resolver;
976                accept_all( translationUnit, resolver );
977        }
978
979        void previsit( ast::FunctionDecl * functionDecl ) {
980                #warning unimplemented; Resolver port in progress
981                (void)functionDecl;
982                assert(false);
983        }
984
985        ast::DeclWithType * postvisit( ast::FunctionDecl * functionDecl ) {
986                #warning unimplemented; Resolver port in progress
987                (void)functionDecl;
988                assert(false);
989                return nullptr;
990        }
991
992        void previsit( ast::ObjectDecl * objectDecl ) {
993                #warning unimplemented; Resolver port in progress
994                (void)objectDecl;
995                assert(false);
996        }
997
998        void previsit( ast::EnumDecl * enumDecl ) {
999                #warning unimplemented; Resolver port in progress
1000                (void)enumDecl;
1001                assert(false);
1002        }
1003
1004        void previsit( ast::StaticAssertDecl * assertDecl ) {
1005                #warning unimplemented; Resolver port in progress
1006                (void)assertDecl;
1007                assert(false);
1008        }
1009
1010        void previsit( ast::ArrayType * at ) {
1011                #warning unimplemented; Resolver port in progress
1012                (void)at;
1013                assert(false);
1014        }
1015
1016        void previsit( ast::PointerType * pt ) {
1017                #warning unimplemented; Resolver port in progress
1018                (void)pt;
1019                assert(false);
1020        }
1021
1022        void previsit( ast::ExprStmt * exprStmt ) {
1023                #warning unimplemented; Resolver port in progress
1024                (void)exprStmt;
1025                assert(false);
1026        }
1027
1028        void previsit( ast::AsmExpr * asmExpr ) {
1029                #warning unimplemented; Resolver port in progress
1030                (void)asmExpr;
1031                assert(false);
1032        }
1033
1034        void previsit( ast::AsmStmt * asmStmt ) {
1035                #warning unimplemented; Resolver port in progress
1036                (void)asmStmt;
1037                assert(false);
1038        }
1039
1040        void previsit( ast::IfStmt * ifStmt ) {
1041                #warning unimplemented; Resolver port in progress
1042                (void)ifStmt;
1043                assert(false);
1044        }
1045
1046        void previsit( ast::WhileStmt * whileStmt ) {
1047                #warning unimplemented; Resolver port in progress
1048                (void)whileStmt;
1049                assert(false);
1050        }
1051
1052        void previsit( ast::ForStmt * forStmt ) {
1053                #warning unimplemented; Resolver port in progress
1054                (void)forStmt;
1055                assert(false);
1056        }
1057
1058        void previsit( ast::SwitchStmt * switchStmt ) {
1059                #warning unimplemented; Resolver port in progress
1060                (void)switchStmt;
1061                assert(false);
1062        }
1063
1064        void previsit( ast::CaseStmt * caseStmt ) {
1065                #warning unimplemented; Resolver port in progress
1066                (void)caseStmt;
1067                assert(false);
1068        }
1069
1070        void previsit( ast::BranchStmt * branchStmt ) {
1071                #warning unimplemented; Resolver port in progress
1072                (void)branchStmt;
1073                assert(false);
1074        }
1075
1076        void previsit( ast::ReturnStmt * returnStmt ) {
1077                #warning unimplemented; Resolver port in progress
1078                (void)returnStmt;
1079                assert(false);
1080        }
1081
1082        void previsit( ast::ThrowStmt * throwStmt ) {
1083                #warning unimplemented; Resolver port in progress
1084                (void)throwStmt;
1085                assert(false);
1086        }
1087
1088        void previsit( ast::CatchStmt * catchStmt ) {
1089                #warning unimplemented; Resolver port in progress
1090                (void)catchStmt;
1091                assert(false);
1092        }
1093
1094        void previsit( ast::WaitForStmt * stmt ) {
1095                #warning unimplemented; Resolver port in progress
1096                (void)stmt;
1097                assert(false);
1098        }
1099
1100        void previsit( ast::SingleInit * singleInit ) {
1101                #warning unimplemented; Resolver port in progress
1102                (void)singleInit;
1103                assert(false);
1104        }
1105
1106        void previsit( ast::ListInit * listInit ) {
1107                #warning unimplemented; Resolver port in progress
1108                (void)listInit;
1109                assert(false);
1110        }
1111
1112        void previsit( ast::ConstructorInit * ctorInit ) {
1113                #warning unimplemented; Resolver port in progress
1114                (void)ctorInit;
1115                assert(false);
1116        }
1117
1118} // namespace ResolvExpr
1119
1120// Local Variables: //
1121// tab-width: 4 //
1122// mode: c++ //
1123// compile-command: "make install" //
1124// End: //
Note: See TracBrowser for help on using the repository browser.