source: src/ResolvExpr/Resolver.cc @ 875a72f

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 875a72f was 36982fc, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Renamed internal stuff to cfaabi_...

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