source: src/AST/Expr.cpp @ 6896548

arm-ehenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-expr
Last change on this file since 6896548 was 6896548, checked in by Michael Brooks <mlbrooks@…>, 3 years ago

Fixed convert-convert issues with strings, when conversion happens after resolve. Three specific issues fixed.

  1. String literals were not roundtripping new-old-new with the original type at the constant level, whereas the resolver changes the expression-level type from array to pointer.
  2. String literals were roundtripping with noise on a "--print astexpr" diff, with the char-array's index type coming up signed int (expecting unsigned long long int).
  3. Function calls that pass a foo[] variable as argument to a foo* formal were crashing on copy-constructor generation because convert-convert was changing the arg-expression type from foo* (set by the resolver, as expecteed) back to foo[], taken from the variable (switched to foo* taken from convert-src expression).
  • Property mode set to 100644
File size: 12.3 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// Expr.cpp --
8//
9// Author           : Aaron B. Moss
10// Created On       : Wed May 15 17:00:00 2019
11// Last Modified By : Andrew Beach
12// Created On       : Thr Jun 13 13:38:00 2019
13// Update Count     : 2
14//
15
16#include "Expr.hpp"
17
18#include <cassert>                 // for strict_dynamic_cast
19#include <string>                  // for to_string
20#include <vector>
21
22#include "GenericSubstitution.hpp"
23#include "Stmt.hpp"
24#include "Type.hpp"
25#include "TypeSubstitution.hpp"
26#include "Common/utility.h"
27#include "Common/SemanticError.h"
28#include "GenPoly/Lvalue.h"        // for referencesPermissable
29#include "InitTweak/InitTweak.h"   // for getPointerBase
30#include "ResolvExpr/typeops.h"    // for extractResultType
31#include "Tuples/Tuples.h"         // for makeTupleType
32
33namespace ast {
34
35// --- ApplicationExpr
36
37ApplicationExpr::ApplicationExpr( const CodeLocation & loc, const Expr * f,
38        std::vector<ptr<Expr>> && as )
39: Expr( loc ), func( f ), args( std::move(as) ) {
40        // ensure that `ApplicationExpr` result type is `FuncExpr`
41        const PointerType * pt = strict_dynamic_cast< const PointerType * >( f->result.get() );
42        const FunctionType * fn = strict_dynamic_cast< const FunctionType * >( pt->base.get() );
43
44        result = ResolvExpr::extractResultType( fn );
45        assert( result );
46}
47
48// --- UntypedExpr
49
50UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, Expr * arg ) {
51        assert( arg );
52
53        UntypedExpr * ret = new UntypedExpr{
54                loc, new NameExpr{loc, "*?"}, std::vector<ptr<Expr>>{ ptr<Expr>{ arg } }
55        };
56        if ( const Type * ty = arg->result ) {
57                const Type * base = InitTweak::getPointerBase( ty );
58                assertf( base, "expected pointer type in dereference (type was %s)", toString( ty ).c_str() );
59
60                if ( GenPoly::referencesPermissable() ) {
61                        // if references are still allowed in the AST, dereference returns a reference
62                        ret->result = new ReferenceType{ base };
63                } else {
64                        // references have been removed, in which case dereference returns an lvalue of the
65                        // base type
66                        ret->result = base;
67                        add_qualifiers( ret->result, CV::Lvalue );
68                }
69        }
70        return ret;
71}
72
73UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, Expr * lhs, Expr * rhs ) {
74        assert( lhs && rhs );
75
76        UntypedExpr * ret = new UntypedExpr{
77                loc, new NameExpr{loc, "?=?"}, std::vector<ptr<Expr>>{ ptr<Expr>{ lhs }, ptr<Expr>{ rhs } }
78        };
79        if ( lhs->result && rhs->result ) {
80                // if both expressions are typed, assumes that this assignment is a C bitwise assignment,
81                // so the result is the type of the RHS
82                ret->result = rhs->result;
83        }
84        return ret;
85}
86
87// --- AddressExpr
88
89// Address expressions are typed based on the following inference rules:
90//    E : lvalue T  &..& (n references)
91//   &E :        T *&..& (n references)
92//
93//    E : T  &..&        (m references)
94//   &E : T *&..&        (m-1 references)
95
96namespace {
97        /// The type of the address of a type.
98        /// Caller is responsible for managing returned memory
99        Type * addrType( const Type * type ) {
100                if ( const ReferenceType * refType = dynamic_cast< const ReferenceType * >( type ) ) {
101                        return new ReferenceType{ addrType( refType->base ), refType->qualifiers };
102                } else {
103                        return new PointerType{ type };
104                }
105        }
106}
107
108AddressExpr::AddressExpr( const CodeLocation & loc, const Expr * a ) : Expr( loc ), arg( a ) {
109        if ( arg->result ) {
110                if ( arg->result->is_lvalue() ) {
111                        // lvalue, retains all levels of reference, and gains a pointer inside the references
112                        Type * res = addrType( arg->result );
113                        res->set_lvalue( false ); // result of & is never an lvalue
114                        result = res;
115                } else {
116                        // taking address of non-lvalue, must be a reference, loses one layer of reference
117                        if ( const ReferenceType * refType =
118                                        dynamic_cast< const ReferenceType * >( arg->result.get() ) ) {
119                                Type * res = addrType( refType->base );
120                                res->set_lvalue( false ); // result of & is never an lvalue
121                                result = res;
122                        } else {
123                                SemanticError( loc, arg->result.get(),
124                                        "Attempt to take address of non-lvalue expression: " );
125                        }
126                }
127        }
128}
129
130// --- LabelAddressExpr
131
132// label address always has type `void*`
133LabelAddressExpr::LabelAddressExpr( const CodeLocation & loc, Label && a )
134: Expr( loc, new PointerType{ new VoidType{} } ), arg( a ) {}
135
136// --- CastExpr
137
138CastExpr::CastExpr( const CodeLocation & loc, const Expr * a, GeneratedFlag g )
139: Expr( loc, new VoidType{} ), arg( a ), isGenerated( g ) {}
140
141// --- KeywordCastExpr
142
143const std::string & KeywordCastExpr::targetString() const {
144        static const std::string targetStrs[] = {
145                "coroutine", "thread", "monitor"
146        };
147        static_assert(
148                (sizeof(targetStrs) / sizeof(targetStrs[0])) == ((unsigned long)NUMBER_OF_TARGETS),
149                "Each KeywordCastExpr::Target should have a corresponding string representation"
150        );
151        return targetStrs[(unsigned long)target];
152}
153
154// --- MemberExpr
155
156MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg )
157: Expr( loc ), member( mem ), aggregate( agg ) {
158        assert( member );
159        assert( aggregate );
160        assert( aggregate->result );
161
162        // take ownership of member type
163        result = mem->get_type();
164        // substitute aggregate generic parameters into member type
165        genericSubstitution( aggregate->result ).apply( result );
166        // ensure lvalue and appropriate restrictions from aggregate type
167        add_qualifiers( result, aggregate->result->qualifiers | CV::Lvalue );
168}
169
170// --- VariableExpr
171
172VariableExpr::VariableExpr( const CodeLocation & loc )
173: Expr( loc ), var( nullptr ) {}
174
175VariableExpr::VariableExpr( const CodeLocation & loc, const DeclWithType * v )
176: Expr( loc ), var( v ) {
177        assert( var );
178        assert( var->get_type() );
179        result = var->get_type();
180        add_qualifiers( result, CV::Lvalue );
181}
182
183VariableExpr * VariableExpr::functionPointer(
184                const CodeLocation & loc, const FunctionDecl * decl ) {
185        // wrap usually-determined result type in a pointer
186        VariableExpr * funcExpr = new VariableExpr{ loc, decl };
187        funcExpr->result = new PointerType{ funcExpr->result };
188        return funcExpr;
189}
190
191// --- ConstantExpr
192
193long long int ConstantExpr::intValue() const {
194        if ( const BasicType * bty = result.as< BasicType >() ) {
195                if ( bty->isInteger() ) {
196                        return val.ival;
197                }
198        } else if ( result.as< ZeroType >() ) {
199                return 0;
200        } else if ( result.as< OneType >() ) {
201                return 1;
202        }
203        SemanticError( this, "Constant expression of non-integral type " );
204}
205
206double ConstantExpr::floatValue() const {
207        if ( const BasicType * bty = result.as< BasicType >() ) {
208                if ( ! bty->isInteger() ) {
209                        return val.dval;
210                }
211        }
212        SemanticError( this, "Constant expression of non-floating-point type " );
213}
214
215ConstantExpr * ConstantExpr::from_bool( const CodeLocation & loc, bool b ) {
216        return new ConstantExpr{
217                loc, new BasicType{ BasicType::Bool }, b ? "1" : "0", (unsigned long long)b };
218}
219
220ConstantExpr * ConstantExpr::from_char( const CodeLocation & loc, char c ) {
221        return new ConstantExpr{
222                loc, new BasicType{ BasicType::Char }, std::to_string( c ), (unsigned long long)c };
223}
224
225ConstantExpr * ConstantExpr::from_int( const CodeLocation & loc, int i ) {
226        return new ConstantExpr{
227                loc, new BasicType{ BasicType::SignedInt }, std::to_string( i ), (unsigned long long)i };
228}
229
230ConstantExpr * ConstantExpr::from_ulong( const CodeLocation & loc, unsigned long i ) {
231        return new ConstantExpr{
232                loc, new BasicType{ BasicType::LongUnsignedInt }, std::to_string( i ),
233                (unsigned long long)i };
234}
235
236ConstantExpr * ConstantExpr::from_double( const CodeLocation & loc, double d ) {
237        return new ConstantExpr{ loc, new BasicType{ BasicType::Double }, std::to_string( d ), d };
238}
239
240ConstantExpr * ConstantExpr::null( const CodeLocation & loc, const Type * ptrType ) {
241        return new ConstantExpr{
242                loc, ptrType ? ptrType : new PointerType{ new VoidType{} }, "0", (unsigned long long)0 };
243}
244
245// --- SizeofExpr
246
247SizeofExpr::SizeofExpr( const CodeLocation & loc, const Expr * e )
248: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
249
250SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * t )
251: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
252
253// --- AlignofExpr
254
255AlignofExpr::AlignofExpr( const CodeLocation & loc, const Expr * e )
256: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
257
258AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * t )
259: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
260
261// --- OffsetofExpr
262
263OffsetofExpr::OffsetofExpr( const CodeLocation & loc, const Type * ty, const DeclWithType * mem )
264: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), type( ty ), member( mem ) {
265        assert( type );
266        assert( member );
267}
268
269// --- OffsetPackExpr
270
271OffsetPackExpr::OffsetPackExpr( const CodeLocation & loc, const StructInstType * ty )
272: Expr( loc, new ArrayType{
273        new BasicType{ BasicType::LongUnsignedInt }, nullptr, FixedLen, DynamicDim }
274), type( ty ) {
275        assert( type );
276}
277
278// --- LogicalExpr
279
280LogicalExpr::LogicalExpr(
281        const CodeLocation & loc, const Expr * a1, const Expr * a2, LogicalFlag ia )
282: Expr( loc, new BasicType{ BasicType::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {}
283
284// --- ConstructorExpr
285
286ConstructorExpr::ConstructorExpr( const CodeLocation & loc, const Expr * call )
287: Expr( loc ), callExpr( call ) {
288        // allow resolver to type a constructor used as an expression if it has the same type as its
289        // first argument
290        assert( callExpr );
291        const Expr * arg = InitTweak::getCallArg( callExpr, 0 );
292        assert( arg );
293        result = arg->result;
294}
295
296// --- CompoundLiteralExpr
297
298CompoundLiteralExpr::CompoundLiteralExpr( const CodeLocation & loc, const Type * t, const Init * i )
299: Expr( loc ), init( i ) {
300        assert( t && i );
301        result = t;
302        add_qualifiers( result, CV::Lvalue );
303}
304
305// --- TupleExpr
306
307TupleExpr::TupleExpr( const CodeLocation & loc, std::vector<ptr<Expr>> && xs )
308: Expr( loc, Tuples::makeTupleType( xs ) ), exprs( xs ) {}
309
310// --- TupleIndexExpr
311
312TupleIndexExpr::TupleIndexExpr( const CodeLocation & loc, const Expr * t, unsigned i )
313: Expr( loc ), tuple( t ), index( i ) {
314        const TupleType * type = strict_dynamic_cast< const TupleType * >( tuple->result.get() );
315        assertf( type->size() > index, "TupleIndexExpr index out of bounds: tuple size %d, requested "
316                "index %d in expr %s", type->size(), index, toString( tuple ).c_str() );
317        // like MemberExpr, TupleIndexExpr is always an lvalue
318        result = type->types[ index ];
319        add_qualifiers( result, CV::Lvalue );
320}
321
322// --- TupleAssignExpr
323
324TupleAssignExpr::TupleAssignExpr(
325        const CodeLocation & loc, std::vector<ptr<Expr>> && assigns,
326        std::vector<ptr<ObjectDecl>> && tempDecls )
327: Expr( loc, Tuples::makeTupleType( assigns ) ), stmtExpr() {
328        // convert internally into a StmtExpr which contains the declarations and produces the tuple of
329        // the assignments
330        std::list<ptr<Stmt>> stmts;
331        for ( const ObjectDecl * obj : tempDecls ) {
332                stmts.emplace_back( new DeclStmt{ loc, obj } );
333        }
334        TupleExpr * tupleExpr = new TupleExpr{ loc, std::move(assigns) };
335        assert( tupleExpr->result );
336        stmts.emplace_back( new ExprStmt{ loc, tupleExpr } );
337        stmtExpr = new StmtExpr{ loc, new CompoundStmt{ loc, std::move(stmts) } };
338}
339
340TupleAssignExpr::TupleAssignExpr(
341        const CodeLocation & loc, const Type * result, const StmtExpr * s )
342: Expr( loc, result ), stmtExpr() {
343        stmtExpr = s;
344}
345
346// --- StmtExpr
347
348StmtExpr::StmtExpr( const CodeLocation & loc, const CompoundStmt * ss )
349: Expr( loc ), stmts( ss ), returnDecls(), dtors() { computeResult(); }
350
351void StmtExpr::computeResult() {
352        assert( stmts );
353        const std::list<ptr<Stmt>> & body = stmts->kids;
354        if ( ! returnDecls.empty() ) {
355                // prioritize return decl for result type, since if a return decl exists, then the StmtExpr
356                // is currently in an intermediate state where the body will always give a void result type
357                result = returnDecls.front()->get_type();
358        } else if ( ! body.empty() ) {
359                if ( const ExprStmt * exprStmt = body.back().as< ExprStmt >() ) {
360                        result = exprStmt->expr->result;
361                }
362        }
363        // ensure a result type exists
364        if ( ! result ) { result = new VoidType{}; }
365}
366
367// --- UniqueExpr
368
369unsigned long long UniqueExpr::nextId = 0;
370
371UniqueExpr::UniqueExpr( const CodeLocation & loc, const Expr * e, unsigned long long i )
372: Expr( loc, e->result ), expr( e ), id( i ) {
373        assert( expr );
374        if ( id == -1ull ) {
375                assert( nextId != -1ull );
376                id = nextId++;
377        }
378}
379
380}
381
382// Local Variables: //
383// tab-width: 4 //
384// mode: c++ //
385// compile-command: "make install" //
386// End: //
Note: See TracBrowser for help on using the repository browser.