blob: 7bc54550f166a277493b150a1b767c25f0e9962b [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000015#include "clang/AST/ASTContext.h"
Chris Lattner17ed4872006-11-20 04:58:19 +000016#include "clang/AST/Decl.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000017#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
Steve Naroff09ef4742007-03-09 23:16:33 +000019#include "clang/Lex/LiteralSupport.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000022#include "clang/Basic/LangOptions.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000023#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000025using namespace llvm;
26using namespace clang;
27
Steve Naroffdf7855b2007-02-21 23:46:25 +000028/// ParseStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Naroffdf7855b2007-02-21 23:46:25 +000035Sema::ParseStringLiteral(const LexerToken *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +000036 assert(NumStringToks && "Must have at least one string!");
37
Steve Naroff4f88b312007-03-13 22:37:02 +000038 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
Chris Lattner5b183d82006-11-10 05:03:26 +000041
Chris Lattner5b183d82006-11-10 05:03:26 +000042 SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
Steve Naroff4f88b312007-03-13 22:37:02 +000045
Chris Lattner5b183d82006-11-10 05:03:26 +000046 // FIXME: use factory.
Chris Lattner5b183d82006-11-10 05:03:26 +000047 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Steve Naroff4f88b312007-03-13 22:37:02 +000048 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
49 Literal.AnyWide);
Chris Lattner5b183d82006-11-10 05:03:26 +000050}
51
Chris Lattnere168f762006-11-10 05:29:30 +000052
Chris Lattnerac18be92006-11-20 06:49:47 +000053/// ParseIdentifierExpr - The parser read an identifier in expression context,
54/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
55/// identifier is used in an function call context.
56Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
57 IdentifierInfo &II,
58 bool HasTrailingLParen) {
Chris Lattner17ed4872006-11-20 04:58:19 +000059 // Could be enum-constant or decl.
Chris Lattner9561a0b2007-01-28 08:20:04 +000060 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner17ed4872006-11-20 04:58:19 +000061 if (D == 0) {
Bill Wendling4073ed52007-02-13 01:51:42 +000062 // Otherwise, this could be an implicitly declared function reference (legal
Chris Lattner9561a0b2007-01-28 08:20:04 +000063 // in C90, extension in C99).
Chris Lattnerac18be92006-11-20 06:49:47 +000064 if (HasTrailingLParen &&
65 // Not in C++.
66 !getLangOptions().CPlusPlus) {
67 D = ImplicitlyDefineFunction(Loc, II, S);
68 } else {
69 // If this name wasn't predeclared and if this is not a function call,
70 // diagnose the problem.
71 Diag(Loc, diag::err_undeclared_var_use, II.getName());
72 return true;
73 }
Chris Lattner17ed4872006-11-20 04:58:19 +000074 }
75
Chris Lattner32d920b2007-01-26 02:01:53 +000076 if (isa<TypedefDecl>(D)) {
Chris Lattner17ed4872006-11-20 04:58:19 +000077 Diag(Loc, diag::err_unexpected_typedef, II.getName());
78 return true;
79 }
80
Chris Lattner5efbb332006-11-20 05:01:40 +000081 return new DeclRefExpr(D);
Chris Lattner17ed4872006-11-20 04:58:19 +000082}
Chris Lattnere168f762006-11-10 05:29:30 +000083
Chris Lattner17ed4872006-11-20 04:58:19 +000084Sema::ExprResult Sema::ParseSimplePrimaryExpr(SourceLocation Loc,
85 tok::TokenKind Kind) {
Chris Lattnere168f762006-11-10 05:29:30 +000086 switch (Kind) {
87 default:
88 assert(0 && "Unknown simple primary expr!");
Chris Lattnere168f762006-11-10 05:29:30 +000089 case tok::char_constant: // constant: character-constant
Chris Lattner17ed4872006-11-20 04:58:19 +000090 // TODO: MOVE this to be some other callback.
Chris Lattnere168f762006-11-10 05:29:30 +000091 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
92 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
93 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattner17ed4872006-11-20 04:58:19 +000094 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000095 }
96}
97
Steve Naroff8160ea22007-03-06 01:09:46 +000098Action::ExprResult Sema::ParseNumericConstant(const LexerToken &Tok) {
Steve Narofff2fb89e2007-03-13 20:29:44 +000099 // fast path for a single digit (which is quite common). A single digit
100 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
101 if (Tok.getLength() == 1) {
102 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
103 return ExprResult(new IntegerLiteral(*t-'0', Context.IntTy));
104 }
Steve Naroff8160ea22007-03-06 01:09:46 +0000105 SmallString<512> IntegerBuffer;
106 IntegerBuffer.resize(Tok.getLength());
107 const char *ThisTokBegin = &IntegerBuffer[0];
108
109 // Get the spelling of the token, which eliminates trigraphs, etc. Notes:
110 // - We know that ThisTokBuf points to a buffer that is big enough for the
111 // whole token and 'spelled' tokens can only shrink.
112 // - In practice, the local buffer is only used when the spelling doesn't
113 // match the original token (which is rare). The common case simply returns
114 // a pointer to a *constant* buffer (avoiding a copy).
115
116 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Steve Naroff09ef4742007-03-09 23:16:33 +0000117 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +0000118 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +0000119 if (Literal.hadError)
120 return ExprResult(true);
121
Steve Naroff09ef4742007-03-09 23:16:33 +0000122 if (Literal.isIntegerLiteral()) {
123 TypeRef t;
124 if (Literal.hasSuffix()) {
125 if (Literal.isLong)
126 t = Literal.isUnsigned ? Context.UnsignedLongTy : Context.LongTy;
127 else if (Literal.isLongLong)
128 t = Literal.isUnsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
129 else
130 t = Context.UnsignedIntTy;
131 } else {
132 t = Context.IntTy; // implicit type is "int"
133 }
Steve Naroff451d8f162007-03-12 23:22:38 +0000134 uintmax_t val;
135 if (Literal.GetIntegerValue(val)) {
Steve Narofff2fb89e2007-03-13 20:29:44 +0000136 return new IntegerLiteral(val, t);
Steve Naroff09ef4742007-03-09 23:16:33 +0000137 }
138 } else if (Literal.isFloatingLiteral()) {
139 // TODO: add floating point processing...
140 }
Steve Narofff2fb89e2007-03-13 20:29:44 +0000141 return ExprResult(true);
Chris Lattnere168f762006-11-10 05:29:30 +0000142}
143
144Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
145 ExprTy *Val) {
146 return Val;
147}
148
149
150// Unary Operators. 'Tok' is the token for the operator.
151Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
152 ExprTy *Input) {
153 UnaryOperator::Opcode Opc;
154 switch (Op) {
155 default: assert(0 && "Unknown unary op!");
156 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
157 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
158 case tok::amp: Opc = UnaryOperator::AddrOf; break;
159 case tok::star: Opc = UnaryOperator::Deref; break;
160 case tok::plus: Opc = UnaryOperator::Plus; break;
161 case tok::minus: Opc = UnaryOperator::Minus; break;
162 case tok::tilde: Opc = UnaryOperator::Not; break;
163 case tok::exclaim: Opc = UnaryOperator::LNot; break;
164 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
165 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
166 case tok::kw___real: Opc = UnaryOperator::Real; break;
167 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
168 case tok::ampamp: Opc = UnaryOperator::AddrLabel; break;
169 case tok::kw___extension__:
170 return Input;
171 //Opc = UnaryOperator::Extension;
172 //break;
173 }
174
175 return new UnaryOperator((Expr*)Input, Opc);
176}
177
178Action::ExprResult Sema::
179ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
180 SourceLocation LParenLoc, TypeTy *Ty,
181 SourceLocation RParenLoc) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000182 // If error parsing type, ignore.
183 if (Ty == 0) return true;
Chris Lattner6531c102007-01-23 22:29:49 +0000184
185 // Verify that this is a valid expression.
186 TypeRef ArgTy = TypeRef::getFromOpaquePtr(Ty);
187
188 if (isa<FunctionType>(ArgTy) && isSizeof) {
189 // alignof(function) is allowed.
190 Diag(OpLoc, diag::ext_sizeof_function_type);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000191 return new IntegerLiteral(1, Context.IntTy);
Chris Lattner6531c102007-01-23 22:29:49 +0000192 } else if (ArgTy->isVoidType()) {
193 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
194 } else if (ArgTy->isIncompleteType()) {
195 std::string TypeName;
196 ArgTy->getAsString(TypeName);
197 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
198 diag::err_alignof_incomplete_type, TypeName);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000199 return new IntegerLiteral(0, Context.IntTy);
Chris Lattner6531c102007-01-23 22:29:49 +0000200 }
201
202 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy);
Chris Lattnere168f762006-11-10 05:29:30 +0000203}
204
205
206Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
207 tok::TokenKind Kind,
208 ExprTy *Input) {
209 UnaryOperator::Opcode Opc;
210 switch (Kind) {
211 default: assert(0 && "Unknown unary op!");
212 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
213 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
214 }
215
216 return new UnaryOperator((Expr*)Input, Opc);
217}
218
219Action::ExprResult Sema::
220ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
221 ExprTy *Idx, SourceLocation RLoc) {
222 return new ArraySubscriptExpr((Expr*)Base, (Expr*)Idx);
223}
224
225Action::ExprResult Sema::
226ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
227 tok::TokenKind OpKind, SourceLocation MemberLoc,
228 IdentifierInfo &Member) {
229 Decl *MemberDecl = 0;
230 // TODO: Look up MemberDecl.
231 return new MemberExpr((Expr*)Base, OpKind == tok::arrow, MemberDecl);
232}
233
234/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
235/// This provides the location of the left/right parens and a list of comma
236/// locations.
237Action::ExprResult Sema::
238ParseCallExpr(ExprTy *Fn, SourceLocation LParenLoc,
239 ExprTy **Args, unsigned NumArgs,
240 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
241 return new CallExpr((Expr*)Fn, (Expr**)Args, NumArgs);
242}
243
244Action::ExprResult Sema::
245ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
246 SourceLocation RParenLoc, ExprTy *Op) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000247 // If error parsing type, ignore.
248 if (Ty == 0) return true;
249 return new CastExpr(TypeRef::getFromOpaquePtr(Ty), (Expr*)Op);
Chris Lattnere168f762006-11-10 05:29:30 +0000250}
251
252
253
254// Binary Operators. 'Tok' is the token for the operator.
255Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
256 ExprTy *LHS, ExprTy *RHS) {
257 BinaryOperator::Opcode Opc;
258 switch (Kind) {
259 default: assert(0 && "Unknown binop!");
260 case tok::star: Opc = BinaryOperator::Mul; break;
261 case tok::slash: Opc = BinaryOperator::Div; break;
262 case tok::percent: Opc = BinaryOperator::Rem; break;
263 case tok::plus: Opc = BinaryOperator::Add; break;
264 case tok::minus: Opc = BinaryOperator::Sub; break;
265 case tok::lessless: Opc = BinaryOperator::Shl; break;
266 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
267 case tok::lessequal: Opc = BinaryOperator::LE; break;
268 case tok::less: Opc = BinaryOperator::LT; break;
269 case tok::greaterequal: Opc = BinaryOperator::GE; break;
270 case tok::greater: Opc = BinaryOperator::GT; break;
271 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
272 case tok::equalequal: Opc = BinaryOperator::EQ; break;
273 case tok::amp: Opc = BinaryOperator::And; break;
274 case tok::caret: Opc = BinaryOperator::Xor; break;
275 case tok::pipe: Opc = BinaryOperator::Or; break;
276 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
277 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
278 case tok::equal: Opc = BinaryOperator::Assign; break;
279 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
280 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
281 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
282 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
283 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
284 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
285 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
286 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
287 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
288 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
289 case tok::comma: Opc = BinaryOperator::Comma; break;
290 }
291
Steve Naroff26c8ea52007-03-21 21:08:52 +0000292 if (BinaryOperator::isMultiplicativeOp(Opc))
293 CheckMultiplicativeOperands((Expr*)LHS, (Expr*)RHS);
294 else if (BinaryOperator::isAdditiveOp(Opc))
295 CheckAdditiveOperands((Expr*)LHS, (Expr*)RHS);
296 else if (BinaryOperator::isShiftOp(Opc))
297 CheckShiftOperands((Expr*)LHS, (Expr*)RHS);
298 else if (BinaryOperator::isRelationalOp(Opc))
299 CheckRelationalOperands((Expr*)LHS, (Expr*)RHS);
300 else if (BinaryOperator::isEqualityOp(Opc))
301 CheckEqualityOperands((Expr*)LHS, (Expr*)RHS);
302 else if (BinaryOperator::isBitwiseOp(Opc))
303 CheckBitwiseOperands((Expr*)LHS, (Expr*)RHS);
304 else if (BinaryOperator::isLogicalOp(Opc))
305 CheckLogicalOperands((Expr*)LHS, (Expr*)RHS);
306
Chris Lattnere168f762006-11-10 05:29:30 +0000307 return new BinaryOperator((Expr*)LHS, (Expr*)RHS, Opc);
308}
309
310/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
311/// in the case of a the GNU conditional expr extension.
312Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
313 SourceLocation ColonLoc,
314 ExprTy *Cond, ExprTy *LHS,
315 ExprTy *RHS) {
316 return new ConditionalOperator((Expr*)Cond, (Expr*)LHS, (Expr*)RHS);
317}
318
Steve Naroff26c8ea52007-03-21 21:08:52 +0000319void Sema::CheckMultiplicativeOperands(Expr *op1, Expr *op2) {
320}
321
322void Sema::CheckAdditiveOperands(Expr *op1, Expr *op2) {
323}
324
325void Sema::CheckShiftOperands(Expr *op1, Expr *op2) {
326}
327
328void Sema::CheckRelationalOperands(Expr *op1, Expr *op2) {
329}
330
331void Sema::CheckEqualityOperands(Expr *op1, Expr *op2) {
332}
333
334void Sema::CheckBitwiseOperands(Expr *op1, Expr *op2) {
335}
336
337void Sema::CheckLogicalOperands(Expr *op1, Expr *op2) {
338}
339