source: src/AST/Expr.cpp @ 893e106

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 893e106 was 893e106, checked in by Aaron Moss <a3moss@…>, 6 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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