source: src/ResolvExpr/Resolver.cc @ 721cd19f

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 721cd19f was 8587878e, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Refactor findIntegralExpression and use it to resolve if/for/while conditions [fixes #76]

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