source: src/ResolvExpr/Resolver.cc @ 08da53d

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

Refactor findSingleExpr and remove unnecessary resolver-generated casts

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