source: src/InitTweak/InitTweak.cc @ 9dbf7c8

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

Skip non-constructable types during autogen

  • Property mode set to 100644
File size: 23.5 KB
RevLine 
[d180746]1#include <algorithm>               // for find, all_of
[e3e16bc]2#include <cassert>                 // for assertf, assert, strict_dynamic_cast
[d180746]3#include <iostream>                // for ostream, cerr, endl
4#include <iterator>                // for back_insert_iterator, back_inserter
5#include <memory>                  // for __shared_ptr
6
7#include "Common/SemanticError.h"  // for SemanticError
8#include "Common/UniqueName.h"     // for UniqueName
9#include "Common/utility.h"        // for toString, deleteAll, maybeClone
10#include "GenPoly/GenPoly.h"       // for getFunctionType
[2b46a13]11#include "InitTweak.h"
[d180746]12#include "Parser/LinkageSpec.h"    // for Spec, isBuiltin, Intrinsic
13#include "ResolvExpr/typeops.h"    // for typesCompatibleIgnoreQualifiers
14#include "SymTab/Indexer.h"        // for Indexer
15#include "SynTree/Attribute.h"     // for Attribute
16#include "SynTree/Constant.h"      // for Constant
17#include "SynTree/Declaration.h"   // for ObjectDecl, DeclarationWithType
18#include "SynTree/Expression.h"    // for Expression, UntypedExpr, Applicati...
19#include "SynTree/Initializer.h"   // for Initializer, ListInit, Designation
20#include "SynTree/Label.h"         // for Label, noLabels
21#include "SynTree/Statement.h"     // for CompoundStmt, ExprStmt, BranchStmt
22#include "SynTree/Type.h"          // for FunctionType, ArrayType, PointerType
23#include "SynTree/Visitor.h"       // for Visitor, maybeAccept
[29bc63e]24#include "Tuples/Tuples.h"         // for Tuples::isTtype
[d180746]25
26class UntypedValofExpr;
[2b46a13]27
28namespace InitTweak {
[64071c2]29        namespace {
30                class HasDesignations : public Visitor {
31                public:
32                        bool hasDesignations = false;
[e4d829b]33                        virtual void visit( Designation * des ) {
34                                if ( ! des->get_designators().empty() ) hasDesignations = true;
35                                else Visitor::visit( des );
[64071c2]36                        }
37                };
[2b46a13]38
[dcd73d1]39                class InitDepthChecker : public Visitor {
40                public:
41                        bool depthOkay = true;
42                        Type * type;
43                        int curDepth = 0, maxDepth = 0;
44                        InitDepthChecker( Type * type ) : type( type ) {
45                                Type * t = type;
46                                while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
47                                        maxDepth++;
48                                        t = at->get_base();
49                                }
50                                maxDepth++;
51                        }
52                        virtual void visit( ListInit * listInit ) {
53                                curDepth++;
54                                if ( curDepth > maxDepth ) depthOkay = false;
55                                Visitor::visit( listInit );
56                                curDepth--;
57                        }
58                };
59
[4d2434a]60                class InitFlattener : public Visitor {
[64071c2]61                        public:
62                        virtual void visit( SingleInit * singleInit );
63                        virtual void visit( ListInit * listInit );
64                        std::list< Expression * > argList;
65                };
[2b46a13]66
[4d2434a]67                void InitFlattener::visit( SingleInit * singleInit ) {
[64071c2]68                        argList.push_back( singleInit->get_value()->clone() );
69                }
[2b46a13]70
[4d2434a]71                void InitFlattener::visit( ListInit * listInit ) {
72                        // flatten nested list inits
73                        std::list<Initializer*>::iterator it = listInit->begin();
74                        for ( ; it != listInit->end(); ++it ) {
[64071c2]75                                (*it)->accept( *this );
76                        }
77                }
78        }
[2b46a13]79
[64071c2]80        std::list< Expression * > makeInitList( Initializer * init ) {
[4d2434a]81                InitFlattener flattener;
82                maybeAccept( init, flattener );
83                return flattener.argList;
[64071c2]84        }
[2b46a13]85
[64071c2]86        bool isDesignated( Initializer * init ) {
87                HasDesignations finder;
88                maybeAccept( init, finder );
89                return finder.hasDesignations;
[dcd73d1]90        }
91
92        bool checkInitDepth( ObjectDecl * objDecl ) {
93                InitDepthChecker checker( objDecl->get_type() );
94                maybeAccept( objDecl->get_init(), checker );
95                return checker.depthOkay;
[64071c2]96        }
[2b46a13]97
[39f84a4]98        class InitExpander::ExpanderImpl {
99        public:
100                virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
[4d2434a]101                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
[39f84a4]102        };
103
104        class InitImpl : public InitExpander::ExpanderImpl {
105        public:
[4d2434a]106                InitImpl( Initializer * init ) : init( init ) {}
[39f84a4]107
[7e003011]108                virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
[39f84a4]109                        // this is wrong, but just a placeholder for now
[4d2434a]110                        // if ( ! flattened ) flatten( indices );
111                        // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
112                        return makeInitList( init );
[39f84a4]113                }
[4d2434a]114
115                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]116        private:
[4d2434a]117                Initializer * init;
[39f84a4]118        };
119
120        class ExprImpl : public InitExpander::ExpanderImpl {
121        public:
122                ExprImpl( Expression * expr ) : arg( expr ) {}
123
[9b4c936]124                ~ExprImpl() { delete arg; }
125
[39f84a4]126                virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
127                        std::list< Expression * > ret;
128                        Expression * expr = maybeClone( arg );
129                        if ( expr ) {
130                                for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
131                                        // go through indices and layer on subscript exprs ?[?]
132                                        ++it;
133                                        UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
134                                        subscriptExpr->get_args().push_back( expr );
135                                        subscriptExpr->get_args().push_back( (*it)->clone() );
136                                        expr = subscriptExpr;
137                                }
138                                ret.push_back( expr );
139                        }
140                        return ret;
141                }
[4d2434a]142
143                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]144        private:
145                Expression * arg;
146        };
147
148        InitExpander::InitExpander( Initializer * init ) : expander( new InitImpl( init ) ) {}
149
150        InitExpander::InitExpander( Expression * expr ) : expander( new ExprImpl( expr ) ) {}
151
152        std::list< Expression * > InitExpander::operator*() {
153                return cur;
154        }
155
156        InitExpander & InitExpander::operator++() {
157                cur = expander->next( indices );
158                return *this;
159        }
160
161        // use array indices list to build switch statement
162        void InitExpander::addArrayIndex( Expression * index, Expression * dimension ) {
163                indices.push_back( index );
164                indices.push_back( dimension );
165        }
166
[4d2434a]167        void InitExpander::clearArrayIndices() {
[9b4c936]168                deleteAll( indices );
[4d2434a]169                indices.clear();
170        }
171
172        namespace {
[f9cebb5]173                /// given index i, dimension d, initializer init, and callExpr f, generates
174                ///   if (i < d) f(..., init)
175                ///   ++i;
176                /// so that only elements within the range of the array are constructed
[4d2434a]177                template< typename OutIterator >
[f9cebb5]178                void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
[4d2434a]179                        UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
180                        cond->get_args().push_back( index->clone() );
181                        cond->get_args().push_back( dimension->clone() );
182
183                        std::list< Expression * > args = makeInitList( init );
184                        callExpr->get_args().splice( callExpr->get_args().end(), args );
185
[22bc276]186                        *out++ = new IfStmt( noLabels, cond, new ExprStmt( noLabels, callExpr ), nullptr );
[4d2434a]187
188                        UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
[175ad32]189                        increment->get_args().push_back( index->clone() );
[4d2434a]190                        *out++ = new ExprStmt( noLabels, increment );
191                }
192
193                template< typename OutIterator >
194                void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
195                        if ( idx == idxEnd ) return;
196                        Expression * index = *idx++;
197                        assert( idx != idxEnd );
198                        Expression * dimension = *idx++;
199
[f9cebb5]200                        // xxx - may want to eventually issue a warning here if we can detect
201                        // that the number of elements exceeds to dimension of the array
[4d2434a]202                        if ( idx == idxEnd ) {
203                                if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
204                                        for ( Initializer * init : *listInit ) {
[f9cebb5]205                                                buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]206                                        }
207                                } else {
[f9cebb5]208                                        buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]209                                }
210                        } else {
211                                std::list< Statement * > branches;
212
213                                unsigned long cond = 0;
214                                ListInit * listInit = dynamic_cast< ListInit * >( init );
215                                if ( ! listInit ) {
216                                        // xxx - this shouldn't be an error, but need a way to
217                                        // terminate without creating output, so should catch this error
218                                        throw SemanticError( "unbalanced list initializers" );
219                                }
[f9cebb5]220
221                                static UniqueName targetLabel( "L__autogen__" );
222                                Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
[4d2434a]223                                for ( Initializer * init : *listInit ) {
224                                        Expression * condition;
225                                        // check for designations
226                                        // if ( init-> ) {
227                                                condition = new ConstantExpr( Constant::from_ulong( cond ) );
228                                                ++cond;
229                                        // } else {
230                                        //      condition = // ... take designation
231                                        //      cond = // ... take designation+1
232                                        // }
233                                        std::list< Statement * > stmts;
234                                        build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
[f9cebb5]235                                        stmts.push_back( new BranchStmt( noLabels, switchLabel, BranchStmt::Break ) );
[4d2434a]236                                        CaseStmt * caseStmt = new CaseStmt( noLabels, condition, stmts );
237                                        branches.push_back( caseStmt );
238                                }
239                                *out++ = new SwitchStmt( noLabels, index->clone(), branches );
[f9cebb5]240                                *out++ = new NullStmt( std::list<Label>{ switchLabel } );
[4d2434a]241                        }
242                }
243        }
244
245        // if array came with an initializer list: initialize each element
246        // may have more initializers than elements in the array - need to check at each index that
247        // we haven't exceeded size.
248        // may have fewer initializers than elements in the array - need to default construct
249        // remaining elements.
250        // To accomplish this, generate switch statement, consuming all of expander's elements
251        Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
[22bc276]252                if ( ! init ) return nullptr;
[f9cebb5]253                CompoundStmt * block = new CompoundStmt( noLabels );
254                build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
255                if ( block->get_kids().empty() ) {
256                        delete block;
[22bc276]257                        return nullptr;
[4d2434a]258                } else {
[22bc276]259                        init = nullptr; // init was consumed in creating the list init
[f9cebb5]260                        return block;
[4d2434a]261                }
[39f84a4]262        }
263
[22bc276]264        Statement * ExprImpl::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
265                return nullptr;
[4d2434a]266        }
267
268        Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
269                return expander->buildListInit( dst, indices );
270        }
271
[549c006]272        Type * getTypeofThis( FunctionType * ftype ) {
273                assertf( ftype, "getTypeofThis: nullptr ftype" );
274                ObjectDecl * thisParam = getParamThis( ftype );
[7fc7cdb]275                ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
276                return refType->base;
277        }
278
[549c006]279        ObjectDecl * getParamThis( FunctionType * ftype ) {
280                assertf( ftype, "getParamThis: nullptr ftype" );
[7fc7cdb]281                auto & params = ftype->parameters;
[549c006]282                assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
[7fc7cdb]283                return strict_dynamic_cast< ObjectDecl * >( params.front() );
284        }
285
[22bc276]286        bool tryConstruct( DeclarationWithType * dwt ) {
287                ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
288                if ( ! objDecl ) return false;
[64071c2]289                return ! LinkageSpec::isBuiltin( objDecl->get_linkage() ) &&
[22bc276]290                        (objDecl->get_init() == nullptr ||
291                                ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
292                        && ! objDecl->get_storageClasses().is_extern
[29bc63e]293                        && isConstructable( objDecl->type );
294        }
295
296        bool isConstructable( Type * type ) {
297                return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
[64071c2]298        }
[2b46a13]299
[4d2434a]300        class CallFinder : public Visitor {
301        public:
302                typedef Visitor Parent;
303                CallFinder( const std::list< std::string > & names ) : names( names ) {}
304
305                virtual void visit( ApplicationExpr * appExpr ) {
306                        handleCallExpr( appExpr );
307                }
308
309                virtual void visit( UntypedExpr * untypedExpr ) {
310                        handleCallExpr( untypedExpr );
311                }
312
313                std::list< Expression * > * matches;
314        private:
315                const std::list< std::string > names;
316
317                template< typename CallExpr >
318                void handleCallExpr( CallExpr * expr ) {
319                        Parent::visit( expr );
320                        std::string fname = getFunctionName( expr );
321                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
322                                matches->push_back( expr );
[cad355a]323                        }
[64071c2]324                }
[4d2434a]325        };
326
327        void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
328                static CallFinder finder( std::list< std::string >{ "?{}", "^?{}" } );
329                finder.matches = &matches;
330                maybeAccept( stmt, finder );
[64071c2]331        }
[4d2434a]332
333        Expression * getCtorDtorCall( Statement * stmt ) {
334                std::list< Expression * > matches;
335                collectCtorDtorCalls( stmt, matches );
336                assert( matches.size() <= 1 );
[22bc276]337                return matches.size() == 1 ? matches.front() : nullptr;
[4d2434a]338        }
339
[aedfd91]340        namespace {
[599b386]341                DeclarationWithType * getCalledFunction( Expression * expr );
342
343                template<typename CallExpr>
344                DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
345                        // (*f)(x) => should get "f"
346                        std::string name = getFunctionName( expr );
347                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]348                        assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
[599b386]349                        return getCalledFunction( expr->get_args().front() );
350                }
351
[ee1635c8]352                DeclarationWithType * getCalledFunction( Expression * expr ) {
353                        assert( expr );
354                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
[6fc5c14]355                                return varExpr->var;
[ee1635c8]356                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
[6fc5c14]357                                return memberExpr->member;
[ee1635c8]358                        } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
[6fc5c14]359                                return getCalledFunction( castExpr->arg );
[599b386]360                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
361                                return handleDerefCalledFunction( untypedExpr );
362                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
363                                return handleDerefCalledFunction( appExpr );
[f3b0a07]364                        } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
[6fc5c14]365                                return getCalledFunction( addrExpr->arg );
366                        } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
367                                return getCalledFunction( commaExpr->arg2 );
[ee1635c8]368                        }
369                        return nullptr;
[aedfd91]370                }
371        }
[70f89d00]372
[b7b8674]373        DeclarationWithType * getFunction( Expression * expr ) {
374                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
375                        return getCalledFunction( appExpr->get_function() );
376                } else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * > ( expr ) ) {
377                        return getCalledFunction( untyped->get_function() );
378                }
379                assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
380        }
381
[aedfd91]382        ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
383                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
[22bc276]384                if ( ! appExpr ) return nullptr;
[ee1635c8]385                DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
[f3b0a07]386                assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
[64071c2]387                // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
388                // will call all member dtors, and some members may have a user defined dtor.
[22bc276]389                return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
[aedfd91]390        }
391
[a465caf]392        namespace {
393                template <typename Predicate>
394                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
395                        std::list< Expression * > callExprs;
396                        collectCtorDtorCalls( stmt, callExprs );
397                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
398                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
399                }
400        }
401
[f9cebb5]402        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
[a465caf]403                return allofCtorDtor( stmt, []( Expression * callExpr ){
[4d2434a]404                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
[906e24d]405                                FunctionType *funcType = GenPoly::getFunctionType( appExpr->get_function()->get_result() );
[4d2434a]406                                assert( funcType );
407                                return funcType->get_parameters().size() == 1;
408                        }
409                        return false;
410                });
[64071c2]411        }
[f1b1e4c]412
[a465caf]413        bool isIntrinsicCallStmt( Statement * stmt ) {
414                return allofCtorDtor( stmt, []( Expression * callExpr ) {
415                        return isIntrinsicCallExpr( callExpr );
416                });
417        }
418
[64071c2]419        namespace {
420                template<typename CallExpr>
421                Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
[a61ad31]422                        if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
[64071c2]423                        for ( Expression *& arg : callExpr->get_args() ) {
424                                if ( pos == 0 ) return arg;
425                                pos--;
426                        }
427                        assert( false );
428                }
429        }
[f1b1e4c]430
[64071c2]431        Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
432                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
433                        return callArg( appExpr, pos );
434                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
435                        return callArg( untypedExpr, pos );
[f3b0a07]436                } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
437                        std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
438                        assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
[e3e16bc]439                        ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
440                        TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
[f3b0a07]441                        assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
442                        return getCallArg( tuple->get_exprs().front(), pos );
[62a05d1]443                } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
444                        return getCallArg( copyCtor->callExpr, pos );
[64071c2]445                } else {
[f3b0a07]446                        assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
[64071c2]447                }
448        }
[f1b1e4c]449
[64071c2]450        namespace {
[599b386]451                std::string funcName( Expression * func );
452
453                template<typename CallExpr>
454                std::string handleDerefName( CallExpr * expr ) {
455                        // (*f)(x) => should get name "f"
456                        std::string name = getFunctionName( expr );
457                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]458                        assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
[599b386]459                        return funcName( expr->get_args().front() );
460                }
461
[c738ca4]462                std::string funcName( Expression * func ) {
[64071c2]463                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
464                                return nameExpr->get_name();
465                        } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
466                                return varExpr->get_var()->get_name();
[c738ca4]467                        }       else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
468                                return funcName( castExpr->get_arg() );
[ee1635c8]469                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
470                                return memberExpr->get_member()->get_name();
[96a10cd]471                        } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
[fd782b2]472                                return funcName( memberExpr->get_member() );
[599b386]473                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
474                                return handleDerefName( untypedExpr );
475                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
476                                return handleDerefName( appExpr );
[19a9822]477                        } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
478                                return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
[64071c2]479                        } else {
[19a9822]480                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
[64071c2]481                        }
482                }
483        }
[70f89d00]484
[64071c2]485        std::string getFunctionName( Expression * expr ) {
[599b386]486                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
487                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
488                // can't possibly do anything reasonable.
[64071c2]489                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
[c738ca4]490                        return funcName( appExpr->get_function() );
[64071c2]491                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
[c738ca4]492                        return funcName( untypedExpr->get_function() );
[64071c2]493                } else {
[c738ca4]494                        std::cerr << expr << std::endl;
[d1969a6]495                        assertf( false, "Unexpected expression type passed to getFunctionName" );
[64071c2]496                }
497        }
[10a7775]498
[64071c2]499        Type * getPointerBase( Type * type ) {
500                if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
501                        return ptrType->get_base();
502                } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
503                        return arrayType->get_base();
[ce8c12f]504                } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
505                        return refType->get_base();
[64071c2]506                } else {
[22bc276]507                        return nullptr;
[64071c2]508                }
509        }
[10a7775]510
[64071c2]511        Type * isPointerType( Type * type ) {
512                if ( getPointerBase( type ) ) return type;
[22bc276]513                else return nullptr;
[64071c2]514        }
[40e636a]515
516        class ConstExprChecker : public Visitor {
517        public:
518                ConstExprChecker() : isConstExpr( true ) {}
519
[65dc863]520                using Visitor::visit;
521
[5809461]522                virtual void visit( ApplicationExpr * ) { isConstExpr = false; }
523                virtual void visit( UntypedExpr * ) { isConstExpr = false; }
524                virtual void visit( NameExpr * ) { isConstExpr = false; }
[1ba88a0]525                // virtual void visit( CastExpr *castExpr ) { isConstExpr = false; }
526                virtual void visit( AddressExpr *addressExpr ) {
527                        // address of a variable or member expression is constexpr
528                        Expression * arg = addressExpr->get_arg();
529                        if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
530                }
[5809461]531                virtual void visit( UntypedMemberExpr * ) { isConstExpr = false; }
532                virtual void visit( MemberExpr * ) { isConstExpr = false; }
533                virtual void visit( VariableExpr * ) { isConstExpr = false; }
[40e636a]534                // these might be okay?
535                // virtual void visit( SizeofExpr *sizeofExpr );
536                // virtual void visit( AlignofExpr *alignofExpr );
537                // virtual void visit( UntypedOffsetofExpr *offsetofExpr );
538                // virtual void visit( OffsetofExpr *offsetofExpr );
539                // virtual void visit( OffsetPackExpr *offsetPackExpr );
540                // virtual void visit( AttrExpr *attrExpr );
541                // virtual void visit( CommaExpr *commaExpr );
542                // virtual void visit( LogicalExpr *logicalExpr );
543                // virtual void visit( ConditionalExpr *conditionalExpr );
[5809461]544                virtual void visit( TypeExpr * ) { isConstExpr = false; }
545                virtual void visit( AsmExpr * ) { isConstExpr = false; }
546                virtual void visit( UntypedValofExpr * ) { isConstExpr = false; }
547                virtual void visit( CompoundLiteralExpr * ) { isConstExpr = false; }
548                virtual void visit( UntypedTupleExpr * ) { isConstExpr = false; }
549                virtual void visit( TupleExpr * ) { isConstExpr = false; }
550                virtual void visit( TupleAssignExpr * ) { isConstExpr = false; }
[40e636a]551
552                bool isConstExpr;
553        };
554
555        bool isConstExpr( Expression * expr ) {
556                if ( expr ) {
557                        ConstExprChecker checker;
558                        expr->accept( checker );
559                        return checker.isConstExpr;
560                }
561                return true;
562        }
563
564        bool isConstExpr( Initializer * init ) {
565                if ( init ) {
566                        ConstExprChecker checker;
567                        init->accept( checker );
568                        return checker.isConstExpr;
569                } // if
570                // for all intents and purposes, no initializer means const expr
571                return true;
572        }
573
[79970ed]574        bool isConstructor( const std::string & str ) { return str == "?{}"; }
575        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
[ee1635c8]576        bool isAssignment( const std::string & str ) { return str == "?=?"; }
[79970ed]577        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
[ee1635c8]578        bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
[4d4882a]579
[ee1635c8]580        FunctionDecl * isCopyFunction( Declaration * decl, const std::string & fname ) {
[4d4882a]581                FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl );
[0a267c1]582                if ( ! function ) return nullptr;
583                if ( function->name != fname ) return nullptr;
584                FunctionType * ftype = function->type;
585                if ( ftype->parameters.size() != 2 ) return nullptr;
[4d4882a]586
[ce8c12f]587                Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
[0a267c1]588                Type * t2 = ftype->parameters.back()->get_type();
[ce8c12f]589                assert( t1 );
[4d4882a]590
[ce8c12f]591                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
[4d4882a]592                        return function;
593                } else {
[ee1635c8]594                        return nullptr;
[4d4882a]595                }
596        }
[ee1635c8]597
[207c7e1d]598        FunctionDecl * isAssignment( Declaration * decl ) {
599                return isCopyFunction( decl, "?=?" );
600        }
601        FunctionDecl * isDestructor( Declaration * decl ) {
602                if ( isDestructor( decl->get_name() ) ) {
603                        return dynamic_cast< FunctionDecl * >( decl );
604                }
605                return nullptr;
606        }
607        FunctionDecl * isDefaultConstructor( Declaration * decl ) {
[0a267c1]608                if ( isConstructor( decl->name ) ) {
[207c7e1d]609                        if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
[0a267c1]610                                if ( func->type->parameters.size() == 1 ) {
[207c7e1d]611                                        return func;
612                                }
613                        }
614                }
615                return nullptr;
616        }
[ee1635c8]617        FunctionDecl * isCopyConstructor( Declaration * decl ) {
618                return isCopyFunction( decl, "?{}" );
619        }
[2b46a13]620}
Note: See TracBrowser for help on using the repository browser.