source: src/ResolvExpr/Resolver.cc @ 6d2f993

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

Merge branch 'master' into with-statement

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