source: src/AST/Expr.cpp@ a750c71b

Last change on this file since a750c71b was 5cc53b2, checked in by Andrew Beach <ajbeach@…>, 8 months ago

Updated documenation in VariableExpr::get_lvalue. This accounts for the code update that did not update the documentation and the rather sparse original documentation.

  • Property mode set to 100644
File size: 13.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 : Peter A. Buhr
12// Created On : Wed May 18 13:56:00 2022
13// Update Count : 12
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 "Copy.hpp" // for shallowCopy
23#include "GenericSubstitution.hpp"
24#include "Inspect.hpp"
25#include "LinkageSpec.hpp"
26#include "Stmt.hpp"
27#include "Type.hpp"
28#include "TypeSubstitution.hpp"
29#include "Common/Utility.hpp"
30#include "Common/SemanticError.hpp"
31#include "GenPoly/Lvalue.hpp" // for referencesPermissable
32#include "ResolvExpr/Unify.hpp" // for extractResultType
33#include "Tuples/Tuples.hpp" // for makeTupleType
34
35namespace ast {
36
37namespace {
38 std::set<std::string> const lvalueFunctionNames = {"*?", "?[?]"};
39}
40
41// --- Expr
42bool Expr::get_lvalue() const {
43 return false;
44}
45
46// --- ApplicationExpr
47
48ApplicationExpr::ApplicationExpr( const CodeLocation & loc, const Expr * f,
49 std::vector<ptr<Expr>> && as )
50: Expr( loc ), func( f ), args( std::move(as) ) {
51 // ensure that `ApplicationExpr` result type is `FuncExpr`
52 const PointerType * pt = strict_dynamic_cast< const PointerType * >( f->result.get() );
53 const FunctionType * fn = strict_dynamic_cast< const FunctionType * >( pt->base.get() );
54
55 result = ResolvExpr::extractResultType( fn );
56 assert( result );
57}
58
59bool ApplicationExpr::get_lvalue() const {
60 if ( const DeclWithType * func = getFunction( this ) ) {
61 return func->linkage == Linkage::Intrinsic && lvalueFunctionNames.count( func->name );
62 }
63 return false;
64}
65
66// --- UntypedExpr
67
68bool UntypedExpr::get_lvalue() const {
69 std::string fname = getFunctionName( this );
70 return lvalueFunctionNames.count( fname );
71}
72
73UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, const Expr * arg ) {
74 assert( arg );
75
76 UntypedExpr * ret = createCall( loc, "*?", { arg } );
77 if ( const Type * ty = arg->result ) {
78 const Type * base = getPointerBase( ty );
79 assertf( base, "expected pointer type in dereference (type was %s)", toString( ty ).c_str() );
80
81 if ( GenPoly::referencesPermissable() ) {
82 // if references are still allowed in the AST, dereference returns a reference
83 ret->result = new ReferenceType{ base };
84 } else {
85 // references have been removed, in which case dereference returns an lvalue of the
86 // base type
87 ret->result = base;
88 }
89 }
90 return ret;
91}
92
93UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, const Expr * lhs, const Expr * rhs ) {
94 assert( lhs && rhs );
95
96 UntypedExpr * ret = createCall( loc, "?=?", { lhs, rhs } );
97 if ( lhs->result && rhs->result ) {
98 // if both expressions are typed, assumes that this assignment is a C bitwise assignment,
99 // so the result is the type of the RHS
100 ret->result = rhs->result;
101 }
102 return ret;
103}
104
105UntypedExpr * UntypedExpr::createCall( const CodeLocation & loc,
106 const std::string & name, std::vector<ptr<Expr>> && args ) {
107 return new UntypedExpr( loc,
108 new NameExpr( loc, name ), std::move( args ) );
109}
110
111// --- VariableExpr
112
113VariableExpr::VariableExpr( const CodeLocation & loc )
114: Expr( loc ), var( nullptr ) {}
115
116VariableExpr::VariableExpr( const CodeLocation & loc, const DeclWithType * v )
117: Expr( loc ), var( v ) {
118 assert( var );
119 assert( var->get_type() );
120 result = shallowCopy( var->get_type() );
121}
122
123bool VariableExpr::get_lvalue() const {
124 // Special case for enumeration labels (more literals than variables):
125 if(dynamic_cast<const ast::EnumInstType *>(var->get_type())) return !var->isMember;
126 // The remaining uses are either actual variables (lvalues) or function
127 // names which are a special value catagory that can be treated as
128 // lvalues in the places we are worried about.
129 return true;
130}
131
132VariableExpr * VariableExpr::functionPointer(
133 const CodeLocation & loc, const FunctionDecl * decl ) {
134 // wrap usually-determined result type in a pointer
135 VariableExpr * funcExpr = new VariableExpr{ loc, decl };
136 funcExpr->result = new PointerType{ funcExpr->result };
137 return funcExpr;
138}
139
140// --- AddressExpr
141
142// Address expressions are typed based on the following inference rules:
143// E : lvalue T &..& (n references)
144// &E : T *&..& (n references)
145//
146// E : T &..& (m references)
147// &E : T *&..& (m-1 references)
148
149namespace {
150 /// The type of the address of a type.
151 /// Caller is responsible for managing returned memory
152 Type * addrType( const ptr<Type> & type ) {
153 if ( auto refType = type.as< ReferenceType >() ) {
154 return new ReferenceType( addrType( refType->base ), refType->qualifiers );
155 } else {
156 return new PointerType( type );
157 }
158 }
159
160 /// The type of the address of an expression.
161 /// Caller is responsible for managing returned memory
162 Type * addrExprType( const CodeLocation & loc, const Expr * arg ) {
163 assert( arg );
164 // If the expression's type is unknown, the address type is unknown.
165 if ( nullptr == arg->result ) {
166 return nullptr;
167 // An lvalue is transformed directly.
168 } else if ( arg->get_lvalue() ) {
169 return addrType( arg->result );
170 // Strip a layer of reference to "create" an lvalue expression.
171 } else if ( auto refType = arg->result.as< ReferenceType >() ) {
172 return addrType( refType->base );
173 } else {
174 SemanticError( loc, "Attempt to take address of non-lvalue expression %s",
175 toString( arg->result.get() ).c_str() );
176 }
177 }
178}
179
180AddressExpr::AddressExpr( const CodeLocation & loc, const Expr * a ) :
181 Expr( loc, addrExprType( loc, a ) ), arg( a )
182{}
183
184// --- LabelAddressExpr
185
186// label address always has type `void*`
187LabelAddressExpr::LabelAddressExpr( const CodeLocation & loc, Label && a )
188: Expr( loc, new PointerType{ new VoidType{} } ), arg( a ) {}
189
190// --- CastExpr
191
192CastExpr::CastExpr( const CodeLocation & loc, const Expr * a, GeneratedFlag g, CastKind kind )
193: Expr( loc, new VoidType{} ), arg( a ), isGenerated( g ), kind( kind ) {}
194
195bool CastExpr::get_lvalue() const {
196 // This is actually wrong by C, but it works with our current set-up.
197 return arg->get_lvalue();
198}
199
200// --- KeywordCastExpr
201
202const char * KeywordCastExpr::targetString() const {
203 return AggregateDecl::aggrString( target );
204}
205
206// --- UntypedMemberExpr
207
208bool UntypedMemberExpr::get_lvalue() const {
209 return aggregate->get_lvalue();
210}
211
212// --- MemberExpr
213
214MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg )
215: Expr( loc ), member( mem ), aggregate( agg ) {
216 assert( member );
217 assert( aggregate );
218 assert( aggregate->result );
219
220 result = mem->get_type();
221
222 // substitute aggregate generic parameters into member type
223 genericSubstitution( aggregate->result ).apply( result );
224 // ensure appropriate restrictions from aggregate type
225 add_qualifiers( result, aggregate->result->qualifiers );
226}
227
228bool MemberExpr::get_lvalue() const {
229 // This is actually wrong by C, but it works with our current set-up.
230 return true;
231}
232
233// --- ConstantExpr
234
235long long int ConstantExpr::intValue() const {
236 if ( const BasicType * bty = result.as< BasicType >() ) {
237 if ( bty->isInteger() ) {
238 assert(ival);
239 return ival.value();
240 }
241 } else if ( result.as< ZeroType >() ) {
242 return 0;
243 } else if ( result.as< OneType >() ) {
244 return 1;
245 }
246 SemanticError( this->location, "Constant expression of non-integral type %s",
247 toString( this ).c_str() );
248}
249
250ConstantExpr * ConstantExpr::from_bool( const CodeLocation & loc, bool b ) {
251 return new ConstantExpr{
252 loc, new BasicType{ BasicKind::Bool }, b ? "1" : "0", (unsigned long long)b };
253}
254
255ConstantExpr * ConstantExpr::from_int( const CodeLocation & loc, int i ) {
256 return new ConstantExpr{
257 loc, new BasicType{ BasicKind::SignedInt }, std::to_string( i ), (unsigned long long)i };
258}
259
260ConstantExpr * ConstantExpr::from_ulong( const CodeLocation & loc, unsigned long i ) {
261 return new ConstantExpr{
262 loc, new BasicType{ BasicKind::LongUnsignedInt }, std::to_string( i ),
263 (unsigned long long)i };
264}
265
266ConstantExpr * ConstantExpr::from_string( const CodeLocation & loc, const std::string & str ) {
267 const Type * charType = new BasicType( BasicKind::Char, ast::CV::Const );
268 // Adjust the length of the string for the terminator.
269 const Expr * strSize = from_ulong( loc, str.size() + 1 );
270 const Type * strType = new ArrayType( charType, strSize, FixedLen, DynamicDim );
271 const std::string strValue = "\"" + str + "\"";
272 return new ConstantExpr( loc, strType, strValue, std::nullopt );
273}
274
275ConstantExpr * ConstantExpr::null( const CodeLocation & loc, const Type * ptrType ) {
276 return new ConstantExpr{
277 loc, ptrType ? ptrType : new PointerType{ new VoidType{} }, "0", (unsigned long long)0 };
278}
279
280// --- SizeofExpr
281
282SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * t )
283: Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), type( t ) {}
284
285// --- CountExpr
286
287CountExpr::CountExpr( const CodeLocation & loc, const Expr * e )
288: Expr( loc, new BasicType( BasicKind::LongUnsignedInt) ), expr(e), type( nullptr ) {}
289
290CountExpr::CountExpr( const CodeLocation & loc, const Type * t )
291: Expr( loc, new BasicType( BasicKind::LongUnsignedInt) ), expr(nullptr), type( t ) {}
292
293// --- AlignofExpr
294
295AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * t )
296: Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), type( t ) {}
297
298// --- OffsetofExpr
299
300OffsetofExpr::OffsetofExpr( const CodeLocation & loc, const Type * ty, const DeclWithType * mem )
301: Expr( loc, new BasicType{ BasicKind::LongUnsignedInt } ), type( ty ), member( mem ) {
302 assert( type );
303 assert( member );
304}
305
306// --- OffsetPackExpr
307
308OffsetPackExpr::OffsetPackExpr( const CodeLocation & loc, const StructInstType * ty )
309: Expr( loc, new ArrayType{
310 new BasicType{ BasicKind::LongUnsignedInt }, nullptr, FixedLen, DynamicDim }
311), type( ty ) {
312 assert( type );
313}
314
315// --- LogicalExpr
316
317LogicalExpr::LogicalExpr(
318 const CodeLocation & loc, const Expr * a1, const Expr * a2, LogicalFlag ia )
319: Expr( loc, new BasicType{ BasicKind::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {}
320
321// --- CommaExpr
322bool CommaExpr::get_lvalue() const {
323 // This is wrong by C, but the current implementation uses it.
324 // (ex: Specialize, Lvalue and Box)
325 return arg2->get_lvalue();
326}
327
328// --- ConstructorExpr
329
330ConstructorExpr::ConstructorExpr( const CodeLocation & loc, const Expr * call )
331: Expr( loc ), callExpr( call ) {
332 // allow resolver to type a constructor used as an expression if it has the same type as its
333 // first argument
334 assert( callExpr );
335 const Expr * arg = getCallArg( callExpr, 0 );
336 assert( arg );
337 result = arg->result;
338}
339
340// --- CompoundLiteralExpr
341
342CompoundLiteralExpr::CompoundLiteralExpr( const CodeLocation & loc, const Type * t, const Init * i )
343: Expr( loc ), init( i ) {
344 assert( t && i );
345 result = t;
346}
347
348bool CompoundLiteralExpr::get_lvalue() const {
349 return true;
350}
351
352// --- TupleExpr
353
354TupleExpr::TupleExpr( const CodeLocation & loc, std::vector<ptr<Expr>> && xs )
355: Expr( loc, Tuples::makeTupleType( xs ) ), exprs( xs ) {}
356
357// --- TupleIndexExpr
358
359TupleIndexExpr::TupleIndexExpr( const CodeLocation & loc, const Expr * t, unsigned i )
360: Expr( loc ), tuple( t ), index( i ) {
361 const TupleType * type = strict_dynamic_cast< const TupleType * >( tuple->result.get() );
362 assertf( type->size() > index, "TupleIndexExpr index out of bounds: tuple size %d, requested "
363 "index %d in expr %s", type->size(), index, toString( tuple ).c_str() );
364 // like MemberExpr, TupleIndexExpr is always an lvalue
365 result = type->types[ index ];
366}
367
368bool TupleIndexExpr::get_lvalue() const {
369 return tuple->get_lvalue();
370}
371
372// --- TupleAssignExpr
373
374TupleAssignExpr::TupleAssignExpr(
375 const CodeLocation & loc, std::vector<ptr<Expr>> && assigns,
376 std::vector<ptr<ObjectDecl>> && tempDecls )
377: Expr( loc, Tuples::makeTupleType( assigns ) ), stmtExpr() {
378 // convert internally into a StmtExpr which contains the declarations and produces the tuple of
379 // the assignments
380 std::list<ptr<Stmt>> stmts;
381 for ( const ObjectDecl * obj : tempDecls ) {
382 stmts.emplace_back( new DeclStmt{ loc, obj } );
383 }
384 TupleExpr * tupleExpr = new TupleExpr{ loc, std::move(assigns) };
385 assert( tupleExpr->result );
386 stmts.emplace_back( new ExprStmt{ loc, tupleExpr } );
387 stmtExpr = new StmtExpr{ loc, new CompoundStmt{ loc, std::move(stmts) } };
388}
389
390// --- StmtExpr
391
392StmtExpr::StmtExpr( const CodeLocation & loc, const CompoundStmt * ss )
393: Expr( loc ), stmts( ss ), returnDecls(), dtors() { computeResult(); }
394
395void StmtExpr::computeResult() {
396 assert( stmts );
397 const std::list<ptr<Stmt>> & body = stmts->kids;
398 if ( ! returnDecls.empty() ) {
399 // prioritize return decl for result type, since if a return decl exists, then the StmtExpr
400 // is currently in an intermediate state where the body will always give a void result type
401 result = returnDecls.front()->get_type();
402 } else if ( ! body.empty() ) {
403 if ( const ExprStmt * exprStmt = body.back().as< ExprStmt >() ) {
404 result = exprStmt->expr->result;
405 }
406 }
407 // ensure a result type exists
408 if ( ! result ) { result = new VoidType{}; }
409}
410
411// --- UniqueExpr
412
413unsigned long long UniqueExpr::nextId = 0;
414
415UniqueExpr::UniqueExpr( const CodeLocation & loc, const Expr * e, unsigned long long i )
416: Expr( loc, e->result ), expr( e ), id( i ) {
417 assert( expr );
418 if ( id == -1ull ) {
419 assert( nextId != -1ull );
420 id = nextId++;
421 }
422}
423
424}
425
426// Local Variables: //
427// tab-width: 4 //
428// mode: c++ //
429// compile-command: "make install" //
430// End: //
Note: See TracBrowser for help on using the repository browser.