source: src/ResolvExpr/Resolver.cc @ c28a038d

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

Refactor resolveWith

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