source: src/ResolvExpr/Resolver.cc @ 60914351

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

Add support for resolving function with clause [fixes #80]

  • Property mode set to 100644
File size: 28.5 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->type );
274
275                {
276                        // resolve with-exprs with parameters in scope and add any newly generated declarations to the
277                        // front of the function body.
278                        auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
279                        indexer.addFunctionType( functionDecl->type );
280                        std::list< Statement * > newStmts;
281                        resolveWithExprs( functionDecl->withExprs, newStmts );
282                        functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
283                }
284        }
285
286        void Resolver::postvisit( FunctionDecl *functionDecl ) {
287                // default value expressions have an environment which shouldn't be there and trips up later passes.
288                // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
289                // see how it's useful.
290                for ( Declaration * d : functionDecl->type->parameters ) {
291                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
292                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
293                                        delete init->value->env;
294                                        init->value->env = nullptr;
295                                }
296                        }
297                }
298        }
299
300        void Resolver::previsit( EnumDecl * ) {
301                // in case we decide to allow nested enums
302                GuardValue( inEnumDecl );
303                inEnumDecl = true;
304        }
305
306        void Resolver::previsit( ExprStmt *exprStmt ) {
307                visit_children = false;
308                assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
309                findVoidExpression( exprStmt->expr, indexer );
310        }
311
312        void Resolver::previsit( AsmExpr *asmExpr ) {
313                visit_children = false;
314                findVoidExpression( asmExpr->operand, indexer );
315                if ( asmExpr->get_inout() ) {
316                        findVoidExpression( asmExpr->inout, indexer );
317                } // if
318        }
319
320        void Resolver::previsit( AsmStmt *asmStmt ) {
321                visit_children = false;
322                acceptAll( asmStmt->get_input(), *visitor );
323                acceptAll( asmStmt->get_output(), *visitor );
324        }
325
326        void Resolver::previsit( IfStmt *ifStmt ) {
327                findIntegralExpression( ifStmt->condition, indexer );
328        }
329
330        void Resolver::previsit( WhileStmt *whileStmt ) {
331                findIntegralExpression( whileStmt->condition, indexer );
332        }
333
334        void Resolver::previsit( ForStmt *forStmt ) {
335                if ( forStmt->condition ) {
336                        findIntegralExpression( forStmt->condition, indexer );
337                } // if
338
339                if ( forStmt->increment ) {
340                        findVoidExpression( forStmt->increment, indexer );
341                } // if
342        }
343
344        void Resolver::previsit( SwitchStmt *switchStmt ) {
345                GuardValue( currentObject );
346                findIntegralExpression( switchStmt->condition, indexer );
347
348                currentObject = CurrentObject( switchStmt->condition->result );
349        }
350
351        void Resolver::previsit( CaseStmt *caseStmt ) {
352                if ( caseStmt->get_condition() ) {
353                        std::list< InitAlternative > initAlts = currentObject.getOptions();
354                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
355                        // must remove cast from case statement because RangeExpr cannot be cast.
356                        Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
357                        findSingleExpression( newExpr, indexer );
358                        CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( newExpr );
359                        caseStmt->condition = castExpr->arg;
360                        castExpr->arg = nullptr;
361                        delete castExpr;
362                }
363        }
364
365        void Resolver::previsit( BranchStmt *branchStmt ) {
366                visit_children = false;
367                // must resolve the argument for a computed goto
368                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
369                        if ( branchStmt->computedTarget ) {
370                                // computed goto argument is void *
371                                findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
372                        } // if
373                } // if
374        }
375
376        void Resolver::previsit( ReturnStmt *returnStmt ) {
377                visit_children = false;
378                if ( returnStmt->expr ) {
379                        findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
380                } // if
381        }
382
383        void Resolver::previsit( ThrowStmt *throwStmt ) {
384                visit_children = false;
385                // TODO: Replace *exception type with &exception type.
386                if ( throwStmt->get_expr() ) {
387                        StructDecl * exception_decl =
388                                indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
389                        assert( exception_decl );
390                        Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
391                        findSingleExpression( throwStmt->expr, exceptType, indexer );
392                }
393        }
394
395        void Resolver::previsit( CatchStmt *catchStmt ) {
396                if ( catchStmt->cond ) {
397                        findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
398                }
399        }
400
401        template< typename iterator_t >
402        inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
403                while( it != end && !(*it)->get_type()->get_mutex() ) {
404                        it++;
405                }
406
407                return it != end;
408        }
409
410        void Resolver::previsit( WaitForStmt * stmt ) {
411                visit_children = false;
412
413                // Resolve all clauses first
414                for( auto& clause : stmt->clauses ) {
415
416                        TypeEnvironment env;
417                        AlternativeFinder funcFinder( indexer, env );
418
419                        // Find all alternatives for a function in canonical form
420                        funcFinder.findWithAdjustment( clause.target.function );
421
422                        if ( funcFinder.get_alternatives().empty() ) {
423                                stringstream ss;
424                                ss << "Use of undeclared indentifier '";
425                                ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
426                                ss << "' in call to waitfor";
427                                throw SemanticError( ss.str() );
428                        }
429
430                        // Find all alternatives for all arguments in canonical form
431                        std::vector< AlternativeFinder > argAlternatives;
432                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
433
434                        // List all combinations of arguments
435                        std::vector< AltList > possibilities;
436                        combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
437
438                        AltList                func_candidates;
439                        std::vector< AltList > args_candidates;
440
441                        // For every possible function :
442                        //      try matching the arguments to the parameters
443                        //      not the other way around because we have more arguments than parameters
444                        SemanticError errors;
445                        for ( Alternative & func : funcFinder.get_alternatives() ) {
446                                try {
447                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
448                                        if( !pointer ) {
449                                                throw SemanticError( "candidate not viable: not a pointer type\n", func.expr->get_result() );
450                                        }
451
452                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
453                                        if( !function ) {
454                                                throw SemanticError( "candidate not viable: not a function type\n", pointer->get_base() );
455                                        }
456
457
458                                        {
459                                                auto param     = function->parameters.begin();
460                                                auto param_end = function->parameters.end();
461
462                                                if( !advance_to_mutex( param, param_end ) ) {
463                                                        throw SemanticError("candidate function not viable: no mutex parameters\n", function);
464                                                }
465                                        }
466
467                                        Alternative newFunc( func );
468                                        // Strip reference from function
469                                        referenceToRvalueConversion( newFunc.expr );
470
471                                        // For all the set of arguments we have try to match it with the parameter of the current function alternative
472                                        for ( auto & argsList : possibilities ) {
473
474                                                try {
475                                                        // Declare data structures need for resolution
476                                                        OpenVarSet openVars;
477                                                        AssertionSet resultNeed, resultHave;
478                                                        TypeEnvironment resultEnv;
479
480                                                        // Load type variables from arguemnts into one shared space
481                                                        simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
482
483                                                        // Make sure we don't widen any existing bindings
484                                                        for ( auto & i : resultEnv ) {
485                                                                i.allowWidening = false;
486                                                        }
487
488                                                        // Find any unbound type variables
489                                                        resultEnv.extractOpenVars( openVars );
490
491                                                        auto param     = function->parameters.begin();
492                                                        auto param_end = function->parameters.end();
493
494                                                        // For every arguments of its set, check if it matches one of the parameter
495                                                        // The order is important
496                                                        for( auto & arg : argsList ) {
497
498                                                                // Ignore non-mutex arguments
499                                                                if( !advance_to_mutex( param, param_end ) ) {
500                                                                        // We ran out of parameters but still have arguments
501                                                                        // this function doesn't match
502                                                                        throw SemanticError("candidate function not viable: too many mutex arguments\n", function);
503                                                                }
504
505                                                                // Check if the argument matches the parameter type in the current scope
506                                                                if( ! unify( (*param)->get_type(), arg.expr->get_result(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
507                                                                        // Type doesn't match
508                                                                        stringstream ss;
509                                                                        ss << "candidate function not viable: no known convertion from '";
510                                                                        arg.expr->get_result()->print( ss );
511                                                                        ss << "' to '";
512                                                                        (*param)->get_type()->print( ss );
513                                                                        ss << "'\n";
514                                                                        throw SemanticError(ss.str(), function);
515                                                                }
516
517                                                                param++;
518                                                        }
519
520                                                        // All arguments match !
521
522                                                        // Check if parameters are missing
523                                                        if( advance_to_mutex( param, param_end ) ) {
524                                                                // We ran out of arguments but still have parameters left
525                                                                // this function doesn't match
526                                                                throw SemanticError("candidate function not viable: too few mutex arguments\n", function);
527                                                        }
528
529                                                        // All parameters match !
530
531                                                        // Finish the expressions to tie in the proper environments
532                                                        finishExpr( newFunc.expr, resultEnv );
533                                                        for( Alternative & alt : argsList ) {
534                                                                finishExpr( alt.expr, resultEnv );
535                                                        }
536
537                                                        // This is a match store it and save it for later
538                                                        func_candidates.push_back( newFunc );
539                                                        args_candidates.push_back( argsList );
540
541                                                }
542                                                catch( SemanticError &e ) {
543                                                        errors.append( e );
544                                                }
545                                        }
546                                }
547                                catch( SemanticError &e ) {
548                                        errors.append( e );
549                                }
550                        }
551
552                        // Make sure we got the right number of arguments
553                        if( func_candidates.empty() )    { SemanticError top( "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
554                        if( args_candidates.empty() )    { SemanticError top( "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
555                        if( func_candidates.size() > 1 ) { SemanticError top( "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
556                        if( args_candidates.size() > 1 ) { SemanticError top( "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
557
558
559                        // Swap the results from the alternative with the unresolved values.
560                        // Alternatives will handle deletion on destruction
561                        std::swap( clause.target.function, func_candidates.front().expr );
562                        for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
563                                std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
564                        }
565
566                        // Resolve the conditions as if it were an IfStmt
567                        // Resolve the statments normally
568                        findSingleExpression( clause.condition, this->indexer );
569                        clause.statement->accept( *visitor );
570                }
571
572
573                if( stmt->timeout.statement ) {
574                        // Resolve the timeout as an size_t for now
575                        // Resolve the conditions as if it were an IfStmt
576                        // Resolve the statments normally
577                        findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
578                        findSingleExpression( stmt->timeout.condition, this->indexer );
579                        stmt->timeout.statement->accept( *visitor );
580                }
581
582                if( stmt->orelse.statement ) {
583                        // Resolve the conditions as if it were an IfStmt
584                        // Resolve the statments normally
585                        findSingleExpression( stmt->orelse.condition, this->indexer );
586                        stmt->orelse.statement->accept( *visitor );
587                }
588        }
589
590        bool isStructOrUnion( Type * t ) {
591                t = t->stripReferences();
592                return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
593        }
594
595        void Resolver::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
596                for ( Expression *& expr : withExprs )  {
597                        // only struct- and union-typed expressions are viable candidates
598                        findKindExpression( expr, indexer, "with statement", isStructOrUnion );
599
600                        // if with expression might be impure, create a temporary so that it is evaluated once
601                        if ( Tuples::maybeImpure( expr ) ) {
602                                static UniqueName tmpNamer( "_with_tmp_" );
603                                ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
604                                expr = new VariableExpr( tmp );
605                                newStmts.push_back( new DeclStmt( tmp ) );
606                                if ( InitTweak::isConstructable( tmp->type ) ) {
607                                        // generate ctor/dtor and resolve them
608                                        tmp->init = InitTweak::genCtorInit( tmp );
609                                        tmp->accept( *visitor );
610                                }
611                        }
612                }
613        }
614
615        void Resolver::previsit( WithStmt * withStmt ) {
616                resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
617        }
618
619        template< typename T >
620        bool isCharType( T t ) {
621                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
622                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
623                                bt->get_kind() == BasicType::UnsignedChar;
624                }
625                return false;
626        }
627
628        void Resolver::previsit( SingleInit *singleInit ) {
629                visit_children = false;
630                // resolve initialization using the possibilities as determined by the currentObject cursor
631                Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
632                findSingleExpression( newExpr, indexer );
633                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
634
635                // move cursor to the object that is actually initialized
636                currentObject.setNext( initExpr->get_designation() );
637
638                // discard InitExpr wrapper and retain relevant pieces
639                newExpr = initExpr->expr;
640                initExpr->expr = nullptr;
641                std::swap( initExpr->env, newExpr->env );
642                std::swap( initExpr->inferParams, newExpr->inferParams ) ;
643                delete initExpr;
644
645                // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
646                Type * initContext = currentObject.getCurrentType();
647
648                removeExtraneousCast( newExpr, indexer );
649
650                // check if actual object's type is char[]
651                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
652                        if ( isCharType( at->get_base() ) ) {
653                                // check if the resolved type is char *
654                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
655                                        if ( isCharType( pt->get_base() ) ) {
656                                                if ( CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ) ) {
657                                                        // strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
658                                                        newExpr = ce->get_arg();
659                                                        ce->set_arg( nullptr );
660                                                        std::swap( ce->env, newExpr->env );
661                                                        delete ce;
662                                                }
663                                        }
664                                }
665                        }
666                }
667
668                // set initializer expr to resolved express
669                singleInit->value = newExpr;
670
671                // move cursor to next object in preparation for next initializer
672                currentObject.increment();
673        }
674
675        void Resolver::previsit( ListInit * listInit ) {
676                visit_children = false;
677                // move cursor into brace-enclosed initializer-list
678                currentObject.enterListInit();
679                // xxx - fix this so that the list isn't copied, iterator should be used to change current element
680                std::list<Designation *> newDesignations;
681                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
682                        // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
683                        // the initializer against that object.
684                        Designation * des = std::get<0>(p);
685                        Initializer * init = std::get<1>(p);
686                        newDesignations.push_back( currentObject.findNext( des ) );
687                        init->accept( *visitor );
688                }
689                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
690                listInit->get_designations() = newDesignations; // xxx - memory management
691                currentObject.exitListInit();
692
693                // xxx - this part has not be folded into CurrentObject yet
694                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
695                //      Type * base = tt->get_baseType()->get_base();
696                //      if ( base ) {
697                //              // know the implementation type, so try using that as the initContext
698                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
699                //              currentObject = &tmpObj;
700                //              visit( listInit );
701                //      } else {
702                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
703                //              Parent::visit( listInit );
704                //      }
705                // } else {
706        }
707
708        // ConstructorInit - fall back on C-style initializer
709        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
710                // could not find valid constructor, or found an intrinsic constructor
711                // fall back on C-style initializer
712                delete ctorInit->get_ctor();
713                ctorInit->set_ctor( NULL );
714                delete ctorInit->get_dtor();
715                ctorInit->set_dtor( NULL );
716                maybeAccept( ctorInit->get_init(), *visitor );
717        }
718
719        // needs to be callable from outside the resolver, so this is a standalone function
720        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
721                assert( ctorInit );
722                PassVisitor<Resolver> resolver( indexer );
723                ctorInit->accept( resolver );
724        }
725
726        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
727                assert( stmtExpr );
728                PassVisitor<Resolver> resolver( indexer );
729                stmtExpr->accept( resolver );
730                stmtExpr->computeResult();
731        }
732
733        void Resolver::previsit( ConstructorInit *ctorInit ) {
734                visit_children = false;
735                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
736                maybeAccept( ctorInit->get_ctor(), *visitor );
737                maybeAccept( ctorInit->get_dtor(), *visitor );
738
739                // found a constructor - can get rid of C-style initializer
740                delete ctorInit->get_init();
741                ctorInit->set_init( NULL );
742
743                // intrinsic single parameter constructors and destructors do nothing. Since this was
744                // implicitly generated, there's no way for it to have side effects, so get rid of it
745                // to clean up generated code.
746                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
747                        delete ctorInit->get_ctor();
748                        ctorInit->set_ctor( NULL );
749                }
750
751                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_dtor() ) ) {
752                        delete ctorInit->get_dtor();
753                        ctorInit->set_dtor( NULL );
754                }
755
756                // xxx - todo -- what about arrays?
757                // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
758                //      // can reduce the constructor down to a SingleInit using the
759                //      // second argument from the ctor call, since
760                //      delete ctorInit->get_ctor();
761                //      ctorInit->set_ctor( NULL );
762
763                //      Expression * arg =
764                //      ctorInit->set_init( new SingleInit( arg ) );
765                // }
766        }
767} // namespace ResolvExpr
768
769// Local Variables: //
770// tab-width: 4 //
771// mode: c++ //
772// compile-command: "make install" //
773// End: //
Note: See TracBrowser for help on using the repository browser.