1 | //===--- ParseExpr.cpp - Expression Parsing -------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | /// |
9 | /// \file |
10 | /// Provides the Expression parsing implementation. |
11 | /// |
12 | /// Expressions in C99 basically consist of a bunch of binary operators with |
13 | /// unary operators and other random stuff at the leaves. |
14 | /// |
15 | /// In the C99 grammar, these unary operators bind tightest and are represented |
16 | /// as the 'cast-expression' production. Everything else is either a binary |
17 | /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are |
18 | /// handled by ParseCastExpression, the higher level pieces are handled by |
19 | /// ParseBinaryExpression. |
20 | /// |
21 | //===----------------------------------------------------------------------===// |
22 | |
23 | #include "clang/AST/ASTContext.h" |
24 | #include "clang/AST/Availability.h" |
25 | #include "clang/AST/ExprCXX.h" |
26 | #include "clang/AST/LocInfoType.h" |
27 | #include "clang/Basic/PrettyStackTrace.h" |
28 | #include "clang/Lex/LiteralSupport.h" |
29 | #include "clang/Parse/Parser.h" |
30 | #include "clang/Parse/RAIIObjectsForParser.h" |
31 | #include "clang/Sema/DeclSpec.h" |
32 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
33 | #include "clang/Sema/ParsedTemplate.h" |
34 | #include "clang/Sema/Scope.h" |
35 | #include "clang/Sema/SemaCUDA.h" |
36 | #include "clang/Sema/SemaCodeCompletion.h" |
37 | #include "clang/Sema/SemaObjC.h" |
38 | #include "clang/Sema/SemaOpenACC.h" |
39 | #include "clang/Sema/SemaOpenMP.h" |
40 | #include "clang/Sema/SemaSYCL.h" |
41 | #include "clang/Sema/TypoCorrection.h" |
42 | #include "llvm/ADT/SmallVector.h" |
43 | #include <optional> |
44 | using namespace clang; |
45 | |
46 | ExprResult Parser::ParseExpression(TypeCastState isTypeCast) { |
47 | ExprResult LHS(ParseAssignmentExpression(isTypeCast)); |
48 | return ParseRHSOfBinaryExpression(LHS, MinPrec: prec::Comma); |
49 | } |
50 | |
51 | ExprResult |
52 | Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) { |
53 | ExprResult LHS(ParseObjCAtExpression(AtLocation: AtLoc)); |
54 | return ParseRHSOfBinaryExpression(LHS, MinPrec: prec::Comma); |
55 | } |
56 | |
57 | ExprResult |
58 | Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) { |
59 | ExprResult LHS(true); |
60 | { |
61 | // Silence extension warnings in the sub-expression |
62 | ExtensionRAIIObject O(Diags); |
63 | |
64 | LHS = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr); |
65 | } |
66 | |
67 | if (!LHS.isInvalid()) |
68 | LHS = Actions.ActOnUnaryOp(S: getCurScope(), OpLoc: ExtLoc, Op: tok::kw___extension__, |
69 | Input: LHS.get()); |
70 | |
71 | return ParseRHSOfBinaryExpression(LHS, MinPrec: prec::Comma); |
72 | } |
73 | |
74 | ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) { |
75 | if (Tok.is(K: tok::code_completion)) { |
76 | cutOffParsing(); |
77 | Actions.CodeCompletion().CodeCompleteExpression( |
78 | S: getCurScope(), PreferredType: PreferredType.get(Tok: Tok.getLocation())); |
79 | return ExprError(); |
80 | } |
81 | |
82 | if (Tok.is(K: tok::kw_throw)) |
83 | return ParseThrowExpression(); |
84 | if (Tok.is(K: tok::kw_co_yield)) |
85 | return ParseCoyieldExpression(); |
86 | |
87 | ExprResult LHS = |
88 | ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr, |
89 | /*isAddressOfOperand=*/false, isTypeCast); |
90 | return ParseRHSOfBinaryExpression(LHS, MinPrec: prec::Assignment); |
91 | } |
92 | |
93 | ExprResult Parser::ParseConditionalExpression() { |
94 | if (Tok.is(K: tok::code_completion)) { |
95 | cutOffParsing(); |
96 | Actions.CodeCompletion().CodeCompleteExpression( |
97 | S: getCurScope(), PreferredType: PreferredType.get(Tok: Tok.getLocation())); |
98 | return ExprError(); |
99 | } |
100 | |
101 | ExprResult LHS = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr, |
102 | /*isAddressOfOperand=*/false, |
103 | isTypeCast: TypeCastState::NotTypeCast); |
104 | return ParseRHSOfBinaryExpression(LHS, MinPrec: prec::Conditional); |
105 | } |
106 | |
107 | ExprResult |
108 | Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc, |
109 | SourceLocation SuperLoc, |
110 | ParsedType ReceiverType, |
111 | Expr *ReceiverExpr) { |
112 | ExprResult R |
113 | = ParseObjCMessageExpressionBody(LBracloc: LBracLoc, SuperLoc, |
114 | ReceiverType, ReceiverExpr); |
115 | R = ParsePostfixExpressionSuffix(LHS: R); |
116 | return ParseRHSOfBinaryExpression(LHS: R, MinPrec: prec::Assignment); |
117 | } |
118 | |
119 | ExprResult |
120 | Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) { |
121 | assert(Actions.ExprEvalContexts.back().Context == |
122 | Sema::ExpressionEvaluationContext::ConstantEvaluated && |
123 | "Call this function only if your ExpressionEvaluationContext is " |
124 | "already ConstantEvaluated" ); |
125 | ExprResult LHS( |
126 | ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr, isAddressOfOperand: false, isTypeCast)); |
127 | ExprResult Res(ParseRHSOfBinaryExpression(LHS, MinPrec: prec::Conditional)); |
128 | return Actions.ActOnConstantExpression(Res); |
129 | } |
130 | |
131 | ExprResult Parser::ParseConstantExpression() { |
132 | // C++03 [basic.def.odr]p2: |
133 | // An expression is potentially evaluated unless it appears where an |
134 | // integral constant expression is required (see 5.19) [...]. |
135 | // C++98 and C++11 have no such rule, but this is only a defect in C++98. |
136 | EnterExpressionEvaluationContext ConstantEvaluated( |
137 | Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
138 | return ParseConstantExpressionInExprEvalContext(isTypeCast: TypeCastState::NotTypeCast); |
139 | } |
140 | |
141 | ExprResult Parser::ParseArrayBoundExpression() { |
142 | EnterExpressionEvaluationContext ConstantEvaluated( |
143 | Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
144 | // If we parse the bound of a VLA... we parse a non-constant |
145 | // constant-expression! |
146 | Actions.ExprEvalContexts.back().InConditionallyConstantEvaluateContext = true; |
147 | // For a VLA type inside an unevaluated operator like: |
148 | // |
149 | // sizeof(typeof(*(int (*)[N])array)) |
150 | // |
151 | // N and array are supposed to be ODR-used. |
152 | // Initially when encountering `array`, it is deemed unevaluated and non-ODR |
153 | // used because that occurs before parsing the type cast. Therefore we use |
154 | // Sema::TransformToPotentiallyEvaluated() to rebuild the expression to ensure |
155 | // it's actually ODR-used. |
156 | // |
157 | // However, in other unevaluated contexts as in constraint substitution, it |
158 | // would end up rebuilding the type twice which is unnecessary. So we push up |
159 | // a flag to help distinguish these cases. |
160 | for (auto Iter = Actions.ExprEvalContexts.rbegin() + 1; |
161 | Iter != Actions.ExprEvalContexts.rend(); ++Iter) { |
162 | if (!Iter->isUnevaluated()) |
163 | break; |
164 | Iter->InConditionallyConstantEvaluateContext = true; |
165 | } |
166 | return ParseConstantExpressionInExprEvalContext(isTypeCast: TypeCastState::NotTypeCast); |
167 | } |
168 | |
169 | ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) { |
170 | EnterExpressionEvaluationContext ConstantEvaluated( |
171 | Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
172 | Actions.currentEvaluationContext().IsCaseExpr = true; |
173 | |
174 | ExprResult LHS(ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr, isAddressOfOperand: false, |
175 | isTypeCast: TypeCastState::NotTypeCast)); |
176 | ExprResult Res(ParseRHSOfBinaryExpression(LHS, MinPrec: prec::Conditional)); |
177 | return Actions.ActOnCaseExpr(CaseLoc, Val: Res); |
178 | } |
179 | |
180 | ExprResult Parser::ParseConstraintExpression() { |
181 | EnterExpressionEvaluationContext ConstantEvaluated( |
182 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); |
183 | ExprResult LHS(ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr)); |
184 | ExprResult Res(ParseRHSOfBinaryExpression(LHS, MinPrec: prec::LogicalOr)); |
185 | if (Res.isUsable() && !Actions.CheckConstraintExpression(CE: Res.get())) { |
186 | return ExprError(); |
187 | } |
188 | return Res; |
189 | } |
190 | |
191 | ExprResult |
192 | Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) { |
193 | EnterExpressionEvaluationContext ConstantEvaluated( |
194 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); |
195 | bool NotPrimaryExpression = false; |
196 | auto ParsePrimary = [&]() { |
197 | ExprResult E = |
198 | ParseCastExpression(ParseKind: CastParseKind::PrimaryExprOnly, |
199 | /*isAddressOfOperand=*/false, |
200 | /*isTypeCast=*/TypeCastState::NotTypeCast, |
201 | /*isVectorLiteral=*/false, NotPrimaryExpression: &NotPrimaryExpression); |
202 | if (E.isInvalid()) |
203 | return ExprError(); |
204 | auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) { |
205 | E = ParsePostfixExpressionSuffix(LHS: E); |
206 | // Use InclusiveOr, the precedence just after '&&' to not parse the |
207 | // next arguments to the logical and. |
208 | E = ParseRHSOfBinaryExpression(LHS: E, MinPrec: prec::InclusiveOr); |
209 | if (!E.isInvalid()) |
210 | Diag(Loc: E.get()->getExprLoc(), |
211 | DiagID: Note |
212 | ? diag::note_unparenthesized_non_primary_expr_in_requires_clause |
213 | : diag::err_unparenthesized_non_primary_expr_in_requires_clause) |
214 | << FixItHint::CreateInsertion(InsertionLoc: E.get()->getBeginLoc(), Code: "(" ) |
215 | << FixItHint::CreateInsertion( |
216 | InsertionLoc: PP.getLocForEndOfToken(Loc: E.get()->getEndLoc()), Code: ")" ) |
217 | << E.get()->getSourceRange(); |
218 | return E; |
219 | }; |
220 | |
221 | if (NotPrimaryExpression || |
222 | // Check if the following tokens must be a part of a non-primary |
223 | // expression |
224 | getBinOpPrecedence(Kind: Tok.getKind(), GreaterThanIsOperator, |
225 | /*CPlusPlus11=*/true) > prec::LogicalAnd || |
226 | // Postfix operators other than '(' (which will be checked for in |
227 | // CheckConstraintExpression). |
228 | Tok.isOneOf(Ks: tok::period, Ks: tok::plusplus, Ks: tok::minusminus) || |
229 | (Tok.is(K: tok::l_square) && !NextToken().is(K: tok::l_square))) { |
230 | E = RecoverFromNonPrimary(E, /*Note=*/false); |
231 | if (E.isInvalid()) |
232 | return ExprError(); |
233 | NotPrimaryExpression = false; |
234 | } |
235 | bool PossibleNonPrimary; |
236 | bool IsConstraintExpr = |
237 | Actions.CheckConstraintExpression(CE: E.get(), NextToken: Tok, PossibleNonPrimary: &PossibleNonPrimary, |
238 | IsTrailingRequiresClause); |
239 | if (!IsConstraintExpr || PossibleNonPrimary) { |
240 | // Atomic constraint might be an unparenthesized non-primary expression |
241 | // (such as a binary operator), in which case we might get here (e.g. in |
242 | // 'requires 0 + 1 && true' we would now be at '+', and parse and ignore |
243 | // the rest of the addition expression). Try to parse the rest of it here. |
244 | if (PossibleNonPrimary) |
245 | E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr); |
246 | return ExprError(); |
247 | } |
248 | return E; |
249 | }; |
250 | ExprResult LHS = ParsePrimary(); |
251 | if (LHS.isInvalid()) |
252 | return ExprError(); |
253 | while (Tok.is(K: tok::ampamp)) { |
254 | SourceLocation LogicalAndLoc = ConsumeToken(); |
255 | ExprResult RHS = ParsePrimary(); |
256 | if (RHS.isInvalid()) { |
257 | return ExprError(); |
258 | } |
259 | ExprResult Op = Actions.ActOnBinOp(S: getCurScope(), TokLoc: LogicalAndLoc, |
260 | Kind: tok::ampamp, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
261 | if (!Op.isUsable()) { |
262 | return ExprError(); |
263 | } |
264 | LHS = Op; |
265 | } |
266 | return LHS; |
267 | } |
268 | |
269 | ExprResult |
270 | Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) { |
271 | ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause)); |
272 | if (!LHS.isUsable()) |
273 | return ExprError(); |
274 | while (Tok.is(K: tok::pipepipe)) { |
275 | SourceLocation LogicalOrLoc = ConsumeToken(); |
276 | ExprResult RHS = |
277 | ParseConstraintLogicalAndExpression(IsTrailingRequiresClause); |
278 | if (!RHS.isUsable()) { |
279 | return ExprError(); |
280 | } |
281 | ExprResult Op = Actions.ActOnBinOp(S: getCurScope(), TokLoc: LogicalOrLoc, |
282 | Kind: tok::pipepipe, LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
283 | if (!Op.isUsable()) { |
284 | return ExprError(); |
285 | } |
286 | LHS = Op; |
287 | } |
288 | return LHS; |
289 | } |
290 | |
291 | bool Parser::isNotExpressionStart() { |
292 | tok::TokenKind K = Tok.getKind(); |
293 | if (K == tok::l_brace || K == tok::r_brace || |
294 | K == tok::kw_for || K == tok::kw_while || |
295 | K == tok::kw_if || K == tok::kw_else || |
296 | K == tok::kw_goto || K == tok::kw_try) |
297 | return true; |
298 | // If this is a decl-specifier, we can't be at the start of an expression. |
299 | return isKnownToBeDeclarationSpecifier(); |
300 | } |
301 | |
302 | bool Parser::isFoldOperator(prec::Level Level) const { |
303 | return Level > prec::Unknown && Level != prec::Conditional && |
304 | Level != prec::Spaceship; |
305 | } |
306 | |
307 | bool Parser::isFoldOperator(tok::TokenKind Kind) const { |
308 | return isFoldOperator(Level: getBinOpPrecedence(Kind, GreaterThanIsOperator, CPlusPlus11: true)); |
309 | } |
310 | |
311 | ExprResult |
312 | Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { |
313 | prec::Level NextTokPrec = getBinOpPrecedence(Kind: Tok.getKind(), |
314 | GreaterThanIsOperator, |
315 | CPlusPlus11: getLangOpts().CPlusPlus11); |
316 | SourceLocation ColonLoc; |
317 | |
318 | auto SavedType = PreferredType; |
319 | while (true) { |
320 | // Every iteration may rely on a preferred type for the whole expression. |
321 | PreferredType = SavedType; |
322 | // If this token has a lower precedence than we are allowed to parse (e.g. |
323 | // because we are called recursively, or because the token is not a binop), |
324 | // then we are done! |
325 | if (NextTokPrec < MinPrec) |
326 | return LHS; |
327 | |
328 | // Consume the operator, saving the operator token for error reporting. |
329 | Token OpToken = Tok; |
330 | ConsumeToken(); |
331 | |
332 | // If we're potentially in a template-id, we may now be able to determine |
333 | // whether we're actually in one or not. |
334 | if (OpToken.isOneOf(Ks: tok::comma, Ks: tok::greater, Ks: tok::greatergreater, |
335 | Ks: tok::greatergreatergreater) && |
336 | checkPotentialAngleBracketDelimiter(OpToken)) |
337 | return ExprError(); |
338 | |
339 | // Bail out when encountering a comma followed by a token which can't |
340 | // possibly be the start of an expression. For instance: |
341 | // int f() { return 1, } |
342 | // We can't do this before consuming the comma, because |
343 | // isNotExpressionStart() looks at the token stream. |
344 | if (OpToken.is(K: tok::comma) && isNotExpressionStart()) { |
345 | PP.EnterToken(Tok, /*IsReinject*/true); |
346 | Tok = OpToken; |
347 | return LHS; |
348 | } |
349 | |
350 | // If the next token is an ellipsis, then this is a fold-expression. Leave |
351 | // it alone so we can handle it in the paren expression. |
352 | if (isFoldOperator(Level: NextTokPrec) && Tok.is(K: tok::ellipsis)) { |
353 | // FIXME: We can't check this via lookahead before we consume the token |
354 | // because that tickles a lexer bug. |
355 | PP.EnterToken(Tok, /*IsReinject*/true); |
356 | Tok = OpToken; |
357 | return LHS; |
358 | } |
359 | |
360 | // In Objective-C++, alternative operator tokens can be used as keyword args |
361 | // in message expressions. Unconsume the token so that it can reinterpreted |
362 | // as an identifier in ParseObjCMessageExpressionBody. i.e., we support: |
363 | // [foo meth:0 and:0]; |
364 | // [foo not_eq]; |
365 | if (getLangOpts().ObjC && getLangOpts().CPlusPlus && |
366 | Tok.isOneOf(Ks: tok::colon, Ks: tok::r_square) && |
367 | OpToken.getIdentifierInfo() != nullptr) { |
368 | PP.EnterToken(Tok, /*IsReinject*/true); |
369 | Tok = OpToken; |
370 | return LHS; |
371 | } |
372 | |
373 | // Special case handling for the ternary operator. |
374 | ExprResult TernaryMiddle(true); |
375 | if (NextTokPrec == prec::Conditional) { |
376 | if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace)) { |
377 | // Parse a braced-init-list here for error recovery purposes. |
378 | SourceLocation BraceLoc = Tok.getLocation(); |
379 | TernaryMiddle = ParseBraceInitializer(); |
380 | if (!TernaryMiddle.isInvalid()) { |
381 | Diag(Loc: BraceLoc, DiagID: diag::err_init_list_bin_op) |
382 | << /*RHS*/ 1 << PP.getSpelling(Tok: OpToken) |
383 | << Actions.getExprRange(E: TernaryMiddle.get()); |
384 | TernaryMiddle = ExprError(); |
385 | } |
386 | } else if (Tok.isNot(K: tok::colon)) { |
387 | // Don't parse FOO:BAR as if it were a typo for FOO::BAR. |
388 | ColonProtectionRAIIObject X(*this); |
389 | |
390 | // Handle this production specially: |
391 | // logical-OR-expression '?' expression ':' conditional-expression |
392 | // In particular, the RHS of the '?' is 'expression', not |
393 | // 'logical-OR-expression' as we might expect. |
394 | TernaryMiddle = ParseExpression(); |
395 | } else { |
396 | // Special case handling of "X ? Y : Z" where Y is empty: |
397 | // logical-OR-expression '?' ':' conditional-expression [GNU] |
398 | TernaryMiddle = nullptr; |
399 | Diag(Tok, DiagID: diag::ext_gnu_conditional_expr); |
400 | } |
401 | |
402 | if (TernaryMiddle.isInvalid()) { |
403 | LHS = ExprError(); |
404 | TernaryMiddle = nullptr; |
405 | } |
406 | |
407 | if (!TryConsumeToken(Expected: tok::colon, Loc&: ColonLoc)) { |
408 | // Otherwise, we're missing a ':'. Assume that this was a typo that |
409 | // the user forgot. If we're not in a macro expansion, we can suggest |
410 | // a fixit hint. If there were two spaces before the current token, |
411 | // suggest inserting the colon in between them, otherwise insert ": ". |
412 | SourceLocation FILoc = Tok.getLocation(); |
413 | const char *FIText = ": " ; |
414 | const SourceManager &SM = PP.getSourceManager(); |
415 | if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(loc: FILoc, MacroBegin: &FILoc)) { |
416 | assert(FILoc.isFileID()); |
417 | bool IsInvalid = false; |
418 | const char *SourcePtr = |
419 | SM.getCharacterData(SL: FILoc.getLocWithOffset(Offset: -1), Invalid: &IsInvalid); |
420 | if (!IsInvalid && *SourcePtr == ' ') { |
421 | SourcePtr = |
422 | SM.getCharacterData(SL: FILoc.getLocWithOffset(Offset: -2), Invalid: &IsInvalid); |
423 | if (!IsInvalid && *SourcePtr == ' ') { |
424 | FILoc = FILoc.getLocWithOffset(Offset: -1); |
425 | FIText = ":" ; |
426 | } |
427 | } |
428 | } |
429 | |
430 | Diag(Tok, DiagID: diag::err_expected) |
431 | << tok::colon << FixItHint::CreateInsertion(InsertionLoc: FILoc, Code: FIText); |
432 | Diag(Tok: OpToken, DiagID: diag::note_matching) << tok::question; |
433 | ColonLoc = Tok.getLocation(); |
434 | } |
435 | } |
436 | |
437 | PreferredType.enterBinary(S&: Actions, Tok: Tok.getLocation(), LHS: LHS.get(), |
438 | Op: OpToken.getKind()); |
439 | // Parse another leaf here for the RHS of the operator. |
440 | // ParseCastExpression works here because all RHS expressions in C have it |
441 | // as a prefix, at least. However, in C++, an assignment-expression could |
442 | // be a throw-expression, which is not a valid cast-expression. |
443 | // Therefore we need some special-casing here. |
444 | // Also note that the third operand of the conditional operator is |
445 | // an assignment-expression in C++, and in C++11, we can have a |
446 | // braced-init-list on the RHS of an assignment. For better diagnostics, |
447 | // parse as if we were allowed braced-init-lists everywhere, and check that |
448 | // they only appear on the RHS of assignments later. |
449 | ExprResult RHS; |
450 | bool RHSIsInitList = false; |
451 | if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace)) { |
452 | RHS = ParseBraceInitializer(); |
453 | RHSIsInitList = true; |
454 | } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional) |
455 | RHS = ParseAssignmentExpression(); |
456 | else |
457 | RHS = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr); |
458 | |
459 | if (RHS.isInvalid()) { |
460 | LHS = ExprError(); |
461 | } |
462 | |
463 | // Remember the precedence of this operator and get the precedence of the |
464 | // operator immediately to the right of the RHS. |
465 | prec::Level ThisPrec = NextTokPrec; |
466 | NextTokPrec = getBinOpPrecedence(Kind: Tok.getKind(), GreaterThanIsOperator, |
467 | CPlusPlus11: getLangOpts().CPlusPlus11); |
468 | |
469 | // Assignment and conditional expressions are right-associative. |
470 | bool isRightAssoc = ThisPrec == prec::Conditional || |
471 | ThisPrec == prec::Assignment; |
472 | |
473 | // Get the precedence of the operator to the right of the RHS. If it binds |
474 | // more tightly with RHS than we do, evaluate it completely first. |
475 | if (ThisPrec < NextTokPrec || |
476 | (ThisPrec == NextTokPrec && isRightAssoc)) { |
477 | if (!RHS.isInvalid() && RHSIsInitList) { |
478 | Diag(Tok, DiagID: diag::err_init_list_bin_op) |
479 | << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(E: RHS.get()); |
480 | RHS = ExprError(); |
481 | } |
482 | // If this is left-associative, only parse things on the RHS that bind |
483 | // more tightly than the current operator. If it is right-associative, it |
484 | // is okay, to bind exactly as tightly. For example, compile A=B=C=D as |
485 | // A=(B=(C=D)), where each paren is a level of recursion here. |
486 | // The function takes ownership of the RHS. |
487 | RHS = ParseRHSOfBinaryExpression(LHS: RHS, |
488 | MinPrec: static_cast<prec::Level>(ThisPrec + !isRightAssoc)); |
489 | RHSIsInitList = false; |
490 | |
491 | if (RHS.isInvalid()) { |
492 | LHS = ExprError(); |
493 | } |
494 | |
495 | NextTokPrec = getBinOpPrecedence(Kind: Tok.getKind(), GreaterThanIsOperator, |
496 | CPlusPlus11: getLangOpts().CPlusPlus11); |
497 | } |
498 | |
499 | if (!RHS.isInvalid() && RHSIsInitList) { |
500 | if (ThisPrec == prec::Assignment) { |
501 | Diag(Tok: OpToken, DiagID: diag::warn_cxx98_compat_generalized_initializer_lists) |
502 | << Actions.getExprRange(E: RHS.get()); |
503 | } else if (ColonLoc.isValid()) { |
504 | Diag(Loc: ColonLoc, DiagID: diag::err_init_list_bin_op) |
505 | << /*RHS*/1 << ":" |
506 | << Actions.getExprRange(E: RHS.get()); |
507 | LHS = ExprError(); |
508 | } else { |
509 | Diag(Tok: OpToken, DiagID: diag::err_init_list_bin_op) |
510 | << /*RHS*/1 << PP.getSpelling(Tok: OpToken) |
511 | << Actions.getExprRange(E: RHS.get()); |
512 | LHS = ExprError(); |
513 | } |
514 | } |
515 | |
516 | if (!LHS.isInvalid()) { |
517 | // Combine the LHS and RHS into the LHS (e.g. build AST). |
518 | if (TernaryMiddle.isInvalid()) { |
519 | // If we're using '>>' as an operator within a template |
520 | // argument list (in C++98), suggest the addition of |
521 | // parentheses so that the code remains well-formed in C++0x. |
522 | if (!GreaterThanIsOperator && OpToken.is(K: tok::greatergreater)) |
523 | SuggestParentheses(Loc: OpToken.getLocation(), |
524 | DK: diag::warn_cxx11_right_shift_in_template_arg, |
525 | ParenRange: SourceRange(Actions.getExprRange(E: LHS.get()).getBegin(), |
526 | Actions.getExprRange(E: RHS.get()).getEnd())); |
527 | |
528 | ExprResult BinOp = |
529 | Actions.ActOnBinOp(S: getCurScope(), TokLoc: OpToken.getLocation(), |
530 | Kind: OpToken.getKind(), LHSExpr: LHS.get(), RHSExpr: RHS.get()); |
531 | if (BinOp.isInvalid()) |
532 | BinOp = Actions.CreateRecoveryExpr(Begin: LHS.get()->getBeginLoc(), |
533 | End: RHS.get()->getEndLoc(), |
534 | SubExprs: {LHS.get(), RHS.get()}); |
535 | |
536 | LHS = BinOp; |
537 | } else { |
538 | ExprResult CondOp = Actions.ActOnConditionalOp( |
539 | QuestionLoc: OpToken.getLocation(), ColonLoc, CondExpr: LHS.get(), LHSExpr: TernaryMiddle.get(), |
540 | RHSExpr: RHS.get()); |
541 | if (CondOp.isInvalid()) { |
542 | std::vector<clang::Expr *> Args; |
543 | // TernaryMiddle can be null for the GNU conditional expr extension. |
544 | if (TernaryMiddle.get()) |
545 | Args = {LHS.get(), TernaryMiddle.get(), RHS.get()}; |
546 | else |
547 | Args = {LHS.get(), RHS.get()}; |
548 | CondOp = Actions.CreateRecoveryExpr(Begin: LHS.get()->getBeginLoc(), |
549 | End: RHS.get()->getEndLoc(), SubExprs: Args); |
550 | } |
551 | |
552 | LHS = CondOp; |
553 | } |
554 | } |
555 | } |
556 | } |
557 | |
558 | ExprResult Parser::ParseCastExpression(CastParseKind ParseKind, |
559 | bool isAddressOfOperand, |
560 | TypeCastState isTypeCast, |
561 | bool isVectorLiteral, |
562 | bool *NotPrimaryExpression) { |
563 | bool NotCastExpr; |
564 | ExprResult Res = ParseCastExpression(ParseKind, |
565 | isAddressOfOperand, |
566 | NotCastExpr, |
567 | isTypeCast, |
568 | isVectorLiteral, |
569 | NotPrimaryExpression); |
570 | if (NotCastExpr) |
571 | Diag(Tok, DiagID: diag::err_expected_expression); |
572 | return Res; |
573 | } |
574 | |
575 | namespace { |
576 | class CastExpressionIdValidator final : public CorrectionCandidateCallback { |
577 | public: |
578 | CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes) |
579 | : NextToken(Next), AllowNonTypes(AllowNonTypes) { |
580 | WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes; |
581 | } |
582 | |
583 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
584 | NamedDecl *ND = candidate.getCorrectionDecl(); |
585 | if (!ND) |
586 | return candidate.isKeyword(); |
587 | |
588 | if (isa<TypeDecl>(Val: ND)) |
589 | return WantTypeSpecifiers; |
590 | |
591 | if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate)) |
592 | return false; |
593 | |
594 | if (!NextToken.isOneOf(Ks: tok::equal, Ks: tok::arrow, Ks: tok::period)) |
595 | return true; |
596 | |
597 | for (auto *C : candidate) { |
598 | NamedDecl *ND = C->getUnderlyingDecl(); |
599 | if (isa<ValueDecl>(Val: ND) && !isa<FunctionDecl>(Val: ND)) |
600 | return true; |
601 | } |
602 | return false; |
603 | } |
604 | |
605 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
606 | return std::make_unique<CastExpressionIdValidator>(args&: *this); |
607 | } |
608 | |
609 | private: |
610 | Token NextToken; |
611 | bool AllowNonTypes; |
612 | }; |
613 | } |
614 | |
615 | bool Parser::isRevertibleTypeTrait(const IdentifierInfo *II, |
616 | tok::TokenKind *Kind) { |
617 | if (RevertibleTypeTraits.empty()) { |
618 | // Revertible type trait is a feature for backwards compatibility with older |
619 | // standard libraries that declare their own structs with the same name as |
620 | // the builtins listed below. New builtins should NOT be added to this list. |
621 | #define RTT_JOIN(X, Y) X##Y |
622 | #define REVERTIBLE_TYPE_TRAIT(Name) \ |
623 | RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] = RTT_JOIN(tok::kw_, Name) |
624 | |
625 | REVERTIBLE_TYPE_TRAIT(__is_abstract); |
626 | REVERTIBLE_TYPE_TRAIT(__is_aggregate); |
627 | REVERTIBLE_TYPE_TRAIT(__is_arithmetic); |
628 | REVERTIBLE_TYPE_TRAIT(__is_array); |
629 | REVERTIBLE_TYPE_TRAIT(__is_assignable); |
630 | REVERTIBLE_TYPE_TRAIT(__is_base_of); |
631 | REVERTIBLE_TYPE_TRAIT(__is_bounded_array); |
632 | REVERTIBLE_TYPE_TRAIT(__is_class); |
633 | REVERTIBLE_TYPE_TRAIT(__is_complete_type); |
634 | REVERTIBLE_TYPE_TRAIT(__is_compound); |
635 | REVERTIBLE_TYPE_TRAIT(__is_const); |
636 | REVERTIBLE_TYPE_TRAIT(__is_constructible); |
637 | REVERTIBLE_TYPE_TRAIT(__is_convertible); |
638 | REVERTIBLE_TYPE_TRAIT(__is_convertible_to); |
639 | REVERTIBLE_TYPE_TRAIT(__is_destructible); |
640 | REVERTIBLE_TYPE_TRAIT(__is_empty); |
641 | REVERTIBLE_TYPE_TRAIT(__is_enum); |
642 | REVERTIBLE_TYPE_TRAIT(__is_floating_point); |
643 | REVERTIBLE_TYPE_TRAIT(__is_final); |
644 | REVERTIBLE_TYPE_TRAIT(__is_function); |
645 | REVERTIBLE_TYPE_TRAIT(__is_fundamental); |
646 | REVERTIBLE_TYPE_TRAIT(__is_integral); |
647 | REVERTIBLE_TYPE_TRAIT(__is_interface_class); |
648 | REVERTIBLE_TYPE_TRAIT(__is_literal); |
649 | REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr); |
650 | REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference); |
651 | REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer); |
652 | REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer); |
653 | REVERTIBLE_TYPE_TRAIT(__is_member_pointer); |
654 | REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable); |
655 | REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible); |
656 | REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible); |
657 | REVERTIBLE_TYPE_TRAIT(__is_object); |
658 | REVERTIBLE_TYPE_TRAIT(__is_pod); |
659 | REVERTIBLE_TYPE_TRAIT(__is_pointer); |
660 | REVERTIBLE_TYPE_TRAIT(__is_polymorphic); |
661 | REVERTIBLE_TYPE_TRAIT(__is_reference); |
662 | REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr); |
663 | REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference); |
664 | REVERTIBLE_TYPE_TRAIT(__is_same); |
665 | REVERTIBLE_TYPE_TRAIT(__is_scalar); |
666 | REVERTIBLE_TYPE_TRAIT(__is_scoped_enum); |
667 | REVERTIBLE_TYPE_TRAIT(__is_sealed); |
668 | REVERTIBLE_TYPE_TRAIT(__is_signed); |
669 | REVERTIBLE_TYPE_TRAIT(__is_standard_layout); |
670 | REVERTIBLE_TYPE_TRAIT(__is_trivial); |
671 | REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable); |
672 | REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible); |
673 | REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable); |
674 | REVERTIBLE_TYPE_TRAIT(__is_unbounded_array); |
675 | REVERTIBLE_TYPE_TRAIT(__is_union); |
676 | REVERTIBLE_TYPE_TRAIT(__is_unsigned); |
677 | REVERTIBLE_TYPE_TRAIT(__is_void); |
678 | REVERTIBLE_TYPE_TRAIT(__is_volatile); |
679 | REVERTIBLE_TYPE_TRAIT(__reference_binds_to_temporary); |
680 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \ |
681 | REVERTIBLE_TYPE_TRAIT(RTT_JOIN(__, Trait)); |
682 | #include "clang/Basic/TransformTypeTraits.def" |
683 | #undef REVERTIBLE_TYPE_TRAIT |
684 | #undef RTT_JOIN |
685 | } |
686 | llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known = |
687 | RevertibleTypeTraits.find(Val: II); |
688 | if (Known != RevertibleTypeTraits.end()) { |
689 | if (Kind) |
690 | *Kind = Known->second; |
691 | return true; |
692 | } |
693 | return false; |
694 | } |
695 | |
696 | ExprResult Parser::ParseBuiltinPtrauthTypeDiscriminator() { |
697 | SourceLocation Loc = ConsumeToken(); |
698 | |
699 | BalancedDelimiterTracker T(*this, tok::l_paren); |
700 | if (T.expectAndConsume()) |
701 | return ExprError(); |
702 | |
703 | TypeResult Ty = ParseTypeName(); |
704 | if (Ty.isInvalid()) { |
705 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
706 | return ExprError(); |
707 | } |
708 | |
709 | SourceLocation EndLoc = Tok.getLocation(); |
710 | T.consumeClose(); |
711 | return Actions.ActOnUnaryExprOrTypeTraitExpr( |
712 | OpLoc: Loc, ExprKind: UETT_PtrAuthTypeDiscriminator, |
713 | /*isType=*/IsType: true, TyOrEx: Ty.get().getAsOpaquePtr(), ArgRange: SourceRange(Loc, EndLoc)); |
714 | } |
715 | |
716 | ExprResult Parser::ParseCastExpression(CastParseKind ParseKind, |
717 | bool isAddressOfOperand, |
718 | bool &NotCastExpr, |
719 | TypeCastState isTypeCast, |
720 | bool isVectorLiteral, |
721 | bool *NotPrimaryExpression) { |
722 | ExprResult Res; |
723 | tok::TokenKind SavedKind = Tok.getKind(); |
724 | auto SavedType = PreferredType; |
725 | NotCastExpr = false; |
726 | |
727 | // Are postfix-expression suffix operators permitted after this |
728 | // cast-expression? If not, and we find some, we'll parse them anyway and |
729 | // diagnose them. |
730 | bool AllowSuffix = true; |
731 | |
732 | // This handles all of cast-expression, unary-expression, postfix-expression, |
733 | // and primary-expression. We handle them together like this for efficiency |
734 | // and to simplify handling of an expression starting with a '(' token: which |
735 | // may be one of a parenthesized expression, cast-expression, compound literal |
736 | // expression, or statement expression. |
737 | // |
738 | // If the parsed tokens consist of a primary-expression, the cases below |
739 | // break out of the switch; at the end we call ParsePostfixExpressionSuffix |
740 | // to handle the postfix expression suffixes. Cases that cannot be followed |
741 | // by postfix exprs should set AllowSuffix to false. |
742 | switch (SavedKind) { |
743 | case tok::l_paren: { |
744 | // If this expression is limited to being a unary-expression, the paren can |
745 | // not start a cast expression. |
746 | ParenParseOption ParenExprType; |
747 | switch (ParseKind) { |
748 | case CastParseKind::UnaryExprOnly: |
749 | assert(getLangOpts().CPlusPlus && "not possible to get here in C" ); |
750 | [[fallthrough]]; |
751 | case CastParseKind::AnyCastExpr: |
752 | ParenExprType = ParenParseOption::CastExpr; |
753 | break; |
754 | case CastParseKind::PrimaryExprOnly: |
755 | ParenExprType = ParenParseOption::FoldExpr; |
756 | break; |
757 | } |
758 | ParsedType CastTy; |
759 | SourceLocation RParenLoc; |
760 | Res = ParseParenExpression(ExprType&: ParenExprType, stopIfCastExpr: false /*stopIfCastExr*/, |
761 | isTypeCast: isTypeCast == TypeCastState::IsTypeCast, CastTy, |
762 | RParenLoc); |
763 | |
764 | // FIXME: What should we do if a vector literal is followed by a |
765 | // postfix-expression suffix? Usually postfix operators are permitted on |
766 | // literals. |
767 | if (isVectorLiteral) |
768 | return Res; |
769 | |
770 | switch (ParenExprType) { |
771 | case ParenParseOption::SimpleExpr: |
772 | break; // Nothing else to do. |
773 | case ParenParseOption::CompoundStmt: |
774 | break; // Nothing else to do. |
775 | case ParenParseOption::CompoundLiteral: |
776 | // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of |
777 | // postfix-expression exist, parse them now. |
778 | break; |
779 | case ParenParseOption::CastExpr: |
780 | // We have parsed the cast-expression and no postfix-expr pieces are |
781 | // following. |
782 | return Res; |
783 | case ParenParseOption::FoldExpr: |
784 | // We only parsed a fold-expression. There might be postfix-expr pieces |
785 | // afterwards; parse them now. |
786 | break; |
787 | } |
788 | |
789 | break; |
790 | } |
791 | |
792 | // primary-expression |
793 | case tok::numeric_constant: |
794 | case tok::binary_data: |
795 | // constant: integer-constant |
796 | // constant: floating-constant |
797 | |
798 | Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope()); |
799 | ConsumeToken(); |
800 | break; |
801 | |
802 | case tok::kw_true: |
803 | case tok::kw_false: |
804 | Res = ParseCXXBoolLiteral(); |
805 | break; |
806 | |
807 | case tok::kw___objc_yes: |
808 | case tok::kw___objc_no: |
809 | Res = ParseObjCBoolLiteral(); |
810 | break; |
811 | |
812 | case tok::kw_nullptr: |
813 | if (getLangOpts().CPlusPlus) |
814 | Diag(Tok, DiagID: diag::warn_cxx98_compat_nullptr); |
815 | else |
816 | Diag(Tok, DiagID: getLangOpts().C23 ? diag::warn_c23_compat_keyword |
817 | : diag::ext_c_nullptr) << Tok.getName(); |
818 | |
819 | Res = Actions.ActOnCXXNullPtrLiteral(Loc: ConsumeToken()); |
820 | break; |
821 | |
822 | case tok::annot_primary_expr: |
823 | case tok::annot_overload_set: |
824 | Res = getExprAnnotation(Tok); |
825 | if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set) |
826 | Res = Actions.ActOnNameClassifiedAsOverloadSet(S: getCurScope(), OverloadSet: Res.get()); |
827 | ConsumeAnnotationToken(); |
828 | if (!Res.isInvalid() && Tok.is(K: tok::less)) |
829 | checkPotentialAngleBracket(PotentialTemplateName&: Res); |
830 | break; |
831 | |
832 | case tok::annot_non_type: |
833 | case tok::annot_non_type_dependent: |
834 | case tok::annot_non_type_undeclared: { |
835 | CXXScopeSpec SS; |
836 | Token Replacement; |
837 | Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); |
838 | assert(!Res.isUnset() && |
839 | "should not perform typo correction on annotation token" ); |
840 | break; |
841 | } |
842 | |
843 | case tok::annot_embed: { |
844 | injectEmbedTokens(); |
845 | return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast, |
846 | isVectorLiteral, NotPrimaryExpression); |
847 | } |
848 | |
849 | case tok::kw___super: |
850 | case tok::kw_decltype: |
851 | // Annotate the token and tail recurse. |
852 | if (TryAnnotateTypeOrScopeToken()) |
853 | return ExprError(); |
854 | assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super)); |
855 | return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast, |
856 | isVectorLiteral, NotPrimaryExpression); |
857 | |
858 | case tok::identifier: |
859 | ParseIdentifier: { // primary-expression: identifier |
860 | // unqualified-id: identifier |
861 | // constant: enumeration-constant |
862 | // Turn a potentially qualified name into a annot_typename or |
863 | // annot_cxxscope if it would be valid. This handles things like x::y, etc. |
864 | if (getLangOpts().CPlusPlus) { |
865 | // Avoid the unnecessary parse-time lookup in the common case |
866 | // where the syntax forbids a type. |
867 | Token Next = NextToken(); |
868 | |
869 | if (Next.is(K: tok::ellipsis) && Tok.is(K: tok::identifier) && |
870 | GetLookAheadToken(N: 2).is(K: tok::l_square)) { |
871 | // Annotate the token and tail recurse. |
872 | // If the token is not annotated, then it might be an expression pack |
873 | // indexing |
874 | if (!TryAnnotateTypeOrScopeToken() && |
875 | Tok.isOneOf(Ks: tok::annot_pack_indexing_type, Ks: tok::annot_cxxscope)) |
876 | return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast, |
877 | isVectorLiteral, NotPrimaryExpression); |
878 | } |
879 | |
880 | // If this identifier was reverted from a token ID, and the next token |
881 | // is a parenthesis, this is likely to be a use of a type trait. Check |
882 | // those tokens. |
883 | else if (Next.is(K: tok::l_paren) && Tok.is(K: tok::identifier) && |
884 | Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) { |
885 | IdentifierInfo *II = Tok.getIdentifierInfo(); |
886 | tok::TokenKind Kind; |
887 | if (isRevertibleTypeTrait(II, Kind: &Kind)) { |
888 | Tok.setKind(Kind); |
889 | return ParseCastExpression(ParseKind, isAddressOfOperand, |
890 | NotCastExpr, isTypeCast, |
891 | isVectorLiteral, NotPrimaryExpression); |
892 | } |
893 | } |
894 | |
895 | else if ((!ColonIsSacred && Next.is(K: tok::colon)) || |
896 | Next.isOneOf(Ks: tok::coloncolon, Ks: tok::less, Ks: tok::l_paren, |
897 | Ks: tok::l_brace)) { |
898 | // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. |
899 | if (TryAnnotateTypeOrScopeToken()) |
900 | return ExprError(); |
901 | if (!Tok.is(K: tok::identifier)) |
902 | return ParseCastExpression(ParseKind, isAddressOfOperand, |
903 | NotCastExpr, isTypeCast, |
904 | isVectorLiteral, |
905 | NotPrimaryExpression); |
906 | } |
907 | } |
908 | |
909 | // Consume the identifier so that we can see if it is followed by a '(' or |
910 | // '.'. |
911 | IdentifierInfo &II = *Tok.getIdentifierInfo(); |
912 | SourceLocation ILoc = ConsumeToken(); |
913 | |
914 | // Support 'Class.property' and 'super.property' notation. |
915 | if (getLangOpts().ObjC && Tok.is(K: tok::period) && |
916 | (Actions.getTypeName(II, NameLoc: ILoc, S: getCurScope()) || |
917 | // Allow the base to be 'super' if in an objc-method. |
918 | (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) { |
919 | ConsumeToken(); |
920 | |
921 | if (Tok.is(K: tok::code_completion) && &II != Ident_super) { |
922 | cutOffParsing(); |
923 | Actions.CodeCompletion().CodeCompleteObjCClassPropertyRefExpr( |
924 | S: getCurScope(), ClassName: II, ClassNameLoc: ILoc, IsBaseExprStatement: ExprStatementTokLoc == ILoc); |
925 | return ExprError(); |
926 | } |
927 | // Allow either an identifier or the keyword 'class' (in C++). |
928 | if (Tok.isNot(K: tok::identifier) && |
929 | !(getLangOpts().CPlusPlus && Tok.is(K: tok::kw_class))) { |
930 | Diag(Tok, DiagID: diag::err_expected_property_name); |
931 | return ExprError(); |
932 | } |
933 | IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); |
934 | SourceLocation PropertyLoc = ConsumeToken(); |
935 | |
936 | Res = Actions.ObjC().ActOnClassPropertyRefExpr(receiverName: II, propertyName: PropertyName, receiverNameLoc: ILoc, |
937 | propertyNameLoc: PropertyLoc); |
938 | break; |
939 | } |
940 | |
941 | // In an Objective-C method, if we have "super" followed by an identifier, |
942 | // the token sequence is ill-formed. However, if there's a ':' or ']' after |
943 | // that identifier, this is probably a message send with a missing open |
944 | // bracket. Treat it as such. |
945 | if (getLangOpts().ObjC && &II == Ident_super && !InMessageExpression && |
946 | getCurScope()->isInObjcMethodScope() && |
947 | ((Tok.is(K: tok::identifier) && |
948 | (NextToken().is(K: tok::colon) || NextToken().is(K: tok::r_square))) || |
949 | Tok.is(K: tok::code_completion))) { |
950 | Res = ParseObjCMessageExpressionBody(LBracloc: SourceLocation(), SuperLoc: ILoc, ReceiverType: nullptr, |
951 | ReceiverExpr: nullptr); |
952 | break; |
953 | } |
954 | |
955 | // If we have an Objective-C class name followed by an identifier |
956 | // and either ':' or ']', this is an Objective-C class message |
957 | // send that's missing the opening '['. Recovery |
958 | // appropriately. Also take this path if we're performing code |
959 | // completion after an Objective-C class name. |
960 | if (getLangOpts().ObjC && |
961 | ((Tok.is(K: tok::identifier) && !InMessageExpression) || |
962 | Tok.is(K: tok::code_completion))) { |
963 | const Token& Next = NextToken(); |
964 | if (Tok.is(K: tok::code_completion) || |
965 | Next.is(K: tok::colon) || Next.is(K: tok::r_square)) |
966 | if (ParsedType Typ = Actions.getTypeName(II, NameLoc: ILoc, S: getCurScope())) |
967 | if (Typ.get()->isObjCObjectOrInterfaceType()) { |
968 | // Fake up a Declarator to use with ActOnTypeName. |
969 | DeclSpec DS(AttrFactory); |
970 | DS.SetRangeStart(ILoc); |
971 | DS.SetRangeEnd(ILoc); |
972 | const char *PrevSpec = nullptr; |
973 | unsigned DiagID; |
974 | DS.SetTypeSpecType(T: TST_typename, Loc: ILoc, PrevSpec, DiagID, Rep: Typ, |
975 | Policy: Actions.getASTContext().getPrintingPolicy()); |
976 | |
977 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
978 | DeclaratorContext::TypeName); |
979 | TypeResult Ty = Actions.ActOnTypeName(D&: DeclaratorInfo); |
980 | if (Ty.isInvalid()) |
981 | break; |
982 | |
983 | Res = ParseObjCMessageExpressionBody(LBracloc: SourceLocation(), |
984 | SuperLoc: SourceLocation(), |
985 | ReceiverType: Ty.get(), ReceiverExpr: nullptr); |
986 | break; |
987 | } |
988 | } |
989 | |
990 | // Make sure to pass down the right value for isAddressOfOperand. |
991 | if (isAddressOfOperand && isPostfixExpressionSuffixStart()) |
992 | isAddressOfOperand = false; |
993 | |
994 | // Function designators are allowed to be undeclared (C99 6.5.1p2), so we |
995 | // need to know whether or not this identifier is a function designator or |
996 | // not. |
997 | UnqualifiedId Name; |
998 | CXXScopeSpec ScopeSpec; |
999 | SourceLocation TemplateKWLoc; |
1000 | Token Replacement; |
1001 | CastExpressionIdValidator Validator( |
1002 | /*Next=*/Tok, |
1003 | /*AllowTypes=*/isTypeCast != TypeCastState::NotTypeCast, |
1004 | /*AllowNonTypes=*/isTypeCast != TypeCastState::IsTypeCast); |
1005 | Validator.IsAddressOfOperand = isAddressOfOperand; |
1006 | if (Tok.isOneOf(Ks: tok::periodstar, Ks: tok::arrowstar)) { |
1007 | Validator.WantExpressionKeywords = false; |
1008 | Validator.WantRemainingKeywords = false; |
1009 | } else { |
1010 | Validator.WantRemainingKeywords = Tok.isNot(K: tok::r_paren); |
1011 | } |
1012 | Name.setIdentifier(Id: &II, IdLoc: ILoc); |
1013 | Res = Actions.ActOnIdExpression( |
1014 | S: getCurScope(), SS&: ScopeSpec, TemplateKWLoc, Id&: Name, HasTrailingLParen: Tok.is(K: tok::l_paren), |
1015 | IsAddressOfOperand: isAddressOfOperand, CCC: &Validator, |
1016 | /*IsInlineAsmIdentifier=*/false, |
1017 | KeywordReplacement: Tok.is(K: tok::r_paren) ? nullptr : &Replacement); |
1018 | if (!Res.isInvalid() && Res.isUnset()) { |
1019 | UnconsumeToken(Consumed&: Replacement); |
1020 | return ParseCastExpression(ParseKind, isAddressOfOperand, |
1021 | NotCastExpr, isTypeCast, |
1022 | /*isVectorLiteral=*/false, |
1023 | NotPrimaryExpression); |
1024 | } |
1025 | Res = tryParseCXXPackIndexingExpression(PackIdExpression: Res); |
1026 | if (!Res.isInvalid() && Tok.is(K: tok::less)) |
1027 | checkPotentialAngleBracket(PotentialTemplateName&: Res); |
1028 | break; |
1029 | } |
1030 | case tok::char_constant: // constant: character-constant |
1031 | case tok::wide_char_constant: |
1032 | case tok::utf8_char_constant: |
1033 | case tok::utf16_char_constant: |
1034 | case tok::utf32_char_constant: |
1035 | Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope()); |
1036 | ConsumeToken(); |
1037 | break; |
1038 | case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] |
1039 | case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] |
1040 | case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS] |
1041 | case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS] |
1042 | case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS] |
1043 | case tok::kw_L__FUNCSIG__: // primary-expression: L__FUNCSIG__ [MS] |
1044 | case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] |
1045 | // Function local predefined macros are represented by PredefinedExpr except |
1046 | // when Microsoft extensions are enabled and one of these macros is adjacent |
1047 | // to a string literal or another one of these macros. |
1048 | if (!(getLangOpts().MicrosoftExt && |
1049 | tokenIsLikeStringLiteral(Tok, LO: getLangOpts()) && |
1050 | tokenIsLikeStringLiteral(Tok: NextToken(), LO: getLangOpts()))) { |
1051 | Res = Actions.ActOnPredefinedExpr(Loc: Tok.getLocation(), Kind: SavedKind); |
1052 | ConsumeToken(); |
1053 | break; |
1054 | } |
1055 | [[fallthrough]]; // treat MS function local macros as concatenable strings |
1056 | case tok::string_literal: // primary-expression: string-literal |
1057 | case tok::wide_string_literal: |
1058 | case tok::utf8_string_literal: |
1059 | case tok::utf16_string_literal: |
1060 | case tok::utf32_string_literal: |
1061 | Res = ParseStringLiteralExpression(AllowUserDefinedLiteral: true); |
1062 | break; |
1063 | case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1] |
1064 | Res = ParseGenericSelectionExpression(); |
1065 | break; |
1066 | case tok::kw___builtin_available: |
1067 | Res = ParseAvailabilityCheckExpr(StartLoc: Tok.getLocation()); |
1068 | break; |
1069 | case tok::kw___builtin_va_arg: |
1070 | case tok::kw___builtin_offsetof: |
1071 | case tok::kw___builtin_choose_expr: |
1072 | case tok::kw___builtin_astype: // primary-expression: [OCL] as_type() |
1073 | case tok::kw___builtin_convertvector: |
1074 | case tok::kw___builtin_COLUMN: |
1075 | case tok::kw___builtin_FILE: |
1076 | case tok::kw___builtin_FILE_NAME: |
1077 | case tok::kw___builtin_FUNCTION: |
1078 | case tok::kw___builtin_FUNCSIG: |
1079 | case tok::kw___builtin_LINE: |
1080 | case tok::kw___builtin_source_location: |
1081 | if (NotPrimaryExpression) |
1082 | *NotPrimaryExpression = true; |
1083 | // This parses the complete suffix; we can return early. |
1084 | return ParseBuiltinPrimaryExpression(); |
1085 | case tok::kw___null: |
1086 | Res = Actions.ActOnGNUNullExpr(TokenLoc: ConsumeToken()); |
1087 | break; |
1088 | |
1089 | case tok::plusplus: // unary-expression: '++' unary-expression [C99] |
1090 | case tok::minusminus: { // unary-expression: '--' unary-expression [C99] |
1091 | if (NotPrimaryExpression) |
1092 | *NotPrimaryExpression = true; |
1093 | // C++ [expr.unary] has: |
1094 | // unary-expression: |
1095 | // ++ cast-expression |
1096 | // -- cast-expression |
1097 | Token SavedTok = Tok; |
1098 | ConsumeToken(); |
1099 | |
1100 | PreferredType.enterUnary(S&: Actions, Tok: Tok.getLocation(), OpKind: SavedTok.getKind(), |
1101 | OpLoc: SavedTok.getLocation()); |
1102 | // One special case is implicitly handled here: if the preceding tokens are |
1103 | // an ambiguous cast expression, such as "(T())++", then we recurse to |
1104 | // determine whether the '++' is prefix or postfix. |
1105 | Res = ParseCastExpression( |
1106 | ParseKind: getLangOpts().CPlusPlus ? CastParseKind::UnaryExprOnly |
1107 | : CastParseKind::AnyCastExpr, |
1108 | /*isAddressOfOperand*/ false, NotCastExpr, isTypeCast: TypeCastState::NotTypeCast); |
1109 | if (NotCastExpr) { |
1110 | // If we return with NotCastExpr = true, we must not consume any tokens, |
1111 | // so put the token back where we found it. |
1112 | assert(Res.isInvalid()); |
1113 | UnconsumeToken(Consumed&: SavedTok); |
1114 | return ExprError(); |
1115 | } |
1116 | if (!Res.isInvalid()) { |
1117 | Expr *Arg = Res.get(); |
1118 | Res = Actions.ActOnUnaryOp(S: getCurScope(), OpLoc: SavedTok.getLocation(), |
1119 | Op: SavedKind, Input: Arg); |
1120 | if (Res.isInvalid()) |
1121 | Res = Actions.CreateRecoveryExpr(Begin: SavedTok.getLocation(), |
1122 | End: Arg->getEndLoc(), SubExprs: Arg); |
1123 | } |
1124 | return Res; |
1125 | } |
1126 | case tok::amp: { // unary-expression: '&' cast-expression |
1127 | if (NotPrimaryExpression) |
1128 | *NotPrimaryExpression = true; |
1129 | // Special treatment because of member pointers |
1130 | SourceLocation SavedLoc = ConsumeToken(); |
1131 | PreferredType.enterUnary(S&: Actions, Tok: Tok.getLocation(), OpKind: tok::amp, OpLoc: SavedLoc); |
1132 | |
1133 | Res = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr, |
1134 | /*isAddressOfOperand=*/true); |
1135 | if (!Res.isInvalid()) { |
1136 | Expr *Arg = Res.get(); |
1137 | Res = Actions.ActOnUnaryOp(S: getCurScope(), OpLoc: SavedLoc, Op: SavedKind, Input: Arg); |
1138 | if (Res.isInvalid()) |
1139 | Res = Actions.CreateRecoveryExpr(Begin: Tok.getLocation(), End: Arg->getEndLoc(), |
1140 | SubExprs: Arg); |
1141 | } |
1142 | return Res; |
1143 | } |
1144 | |
1145 | case tok::star: // unary-expression: '*' cast-expression |
1146 | case tok::plus: // unary-expression: '+' cast-expression |
1147 | case tok::minus: // unary-expression: '-' cast-expression |
1148 | case tok::tilde: // unary-expression: '~' cast-expression |
1149 | case tok::exclaim: // unary-expression: '!' cast-expression |
1150 | case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] |
1151 | case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] |
1152 | if (NotPrimaryExpression) |
1153 | *NotPrimaryExpression = true; |
1154 | SourceLocation SavedLoc = ConsumeToken(); |
1155 | PreferredType.enterUnary(S&: Actions, Tok: Tok.getLocation(), OpKind: SavedKind, OpLoc: SavedLoc); |
1156 | Res = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr); |
1157 | if (!Res.isInvalid()) { |
1158 | Expr *Arg = Res.get(); |
1159 | Res = Actions.ActOnUnaryOp(S: getCurScope(), OpLoc: SavedLoc, Op: SavedKind, Input: Arg, |
1160 | IsAfterAmp: isAddressOfOperand); |
1161 | if (Res.isInvalid()) |
1162 | Res = Actions.CreateRecoveryExpr(Begin: SavedLoc, End: Arg->getEndLoc(), SubExprs: Arg); |
1163 | } |
1164 | return Res; |
1165 | } |
1166 | |
1167 | case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression |
1168 | if (NotPrimaryExpression) |
1169 | *NotPrimaryExpression = true; |
1170 | SourceLocation CoawaitLoc = ConsumeToken(); |
1171 | Res = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr); |
1172 | if (!Res.isInvalid()) |
1173 | Res = Actions.ActOnCoawaitExpr(S: getCurScope(), KwLoc: CoawaitLoc, E: Res.get()); |
1174 | return Res; |
1175 | } |
1176 | |
1177 | case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] |
1178 | // __extension__ silences extension warnings in the subexpression. |
1179 | if (NotPrimaryExpression) |
1180 | *NotPrimaryExpression = true; |
1181 | ExtensionRAIIObject O(Diags); // Use RAII to do this. |
1182 | SourceLocation SavedLoc = ConsumeToken(); |
1183 | Res = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr); |
1184 | if (!Res.isInvalid()) |
1185 | Res = Actions.ActOnUnaryOp(S: getCurScope(), OpLoc: SavedLoc, Op: SavedKind, Input: Res.get()); |
1186 | return Res; |
1187 | } |
1188 | case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')' |
1189 | diagnoseUseOfC11Keyword(Tok); |
1190 | [[fallthrough]]; |
1191 | case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')' |
1192 | case tok::kw___alignof: // unary-expression: '__alignof' unary-expression |
1193 | // unary-expression: '__alignof' '(' type-name ')' |
1194 | case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression |
1195 | // unary-expression: 'sizeof' '(' type-name ')' |
1196 | // unary-expression: '__datasizeof' unary-expression |
1197 | // unary-expression: '__datasizeof' '(' type-name ')' |
1198 | case tok::kw___datasizeof: |
1199 | case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression |
1200 | // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')' |
1201 | case tok::kw___builtin_omp_required_simd_align: |
1202 | case tok::kw___builtin_vectorelements: |
1203 | case tok::kw__Countof: |
1204 | if (NotPrimaryExpression) |
1205 | *NotPrimaryExpression = true; |
1206 | AllowSuffix = false; |
1207 | Res = ParseUnaryExprOrTypeTraitExpression(); |
1208 | break; |
1209 | case tok::ampamp: { // unary-expression: '&&' identifier |
1210 | if (NotPrimaryExpression) |
1211 | *NotPrimaryExpression = true; |
1212 | SourceLocation AmpAmpLoc = ConsumeToken(); |
1213 | if (Tok.isNot(K: tok::identifier)) |
1214 | return ExprError(Diag(Tok, DiagID: diag::err_expected) << tok::identifier); |
1215 | |
1216 | if (getCurScope()->getFnParent() == nullptr) |
1217 | return ExprError(Diag(Tok, DiagID: diag::err_address_of_label_outside_fn)); |
1218 | |
1219 | Diag(Loc: AmpAmpLoc, DiagID: diag::ext_gnu_address_of_label); |
1220 | LabelDecl *LD = Actions.LookupOrCreateLabel(II: Tok.getIdentifierInfo(), |
1221 | IdentLoc: Tok.getLocation()); |
1222 | Res = Actions.ActOnAddrLabel(OpLoc: AmpAmpLoc, LabLoc: Tok.getLocation(), TheDecl: LD); |
1223 | ConsumeToken(); |
1224 | AllowSuffix = false; |
1225 | break; |
1226 | } |
1227 | case tok::kw_const_cast: |
1228 | case tok::kw_dynamic_cast: |
1229 | case tok::kw_reinterpret_cast: |
1230 | case tok::kw_static_cast: |
1231 | case tok::kw_addrspace_cast: |
1232 | if (NotPrimaryExpression) |
1233 | *NotPrimaryExpression = true; |
1234 | Res = ParseCXXCasts(); |
1235 | break; |
1236 | case tok::kw___builtin_bit_cast: |
1237 | if (NotPrimaryExpression) |
1238 | *NotPrimaryExpression = true; |
1239 | Res = ParseBuiltinBitCast(); |
1240 | break; |
1241 | case tok::kw_typeid: |
1242 | if (NotPrimaryExpression) |
1243 | *NotPrimaryExpression = true; |
1244 | Res = ParseCXXTypeid(); |
1245 | break; |
1246 | case tok::kw___uuidof: |
1247 | if (NotPrimaryExpression) |
1248 | *NotPrimaryExpression = true; |
1249 | Res = ParseCXXUuidof(); |
1250 | break; |
1251 | case tok::kw_this: |
1252 | Res = ParseCXXThis(); |
1253 | break; |
1254 | case tok::kw___builtin_sycl_unique_stable_name: |
1255 | Res = ParseSYCLUniqueStableNameExpression(); |
1256 | break; |
1257 | |
1258 | case tok::annot_typename: |
1259 | if (isStartOfObjCClassMessageMissingOpenBracket()) { |
1260 | TypeResult Type = getTypeAnnotation(Tok); |
1261 | |
1262 | // Fake up a Declarator to use with ActOnTypeName. |
1263 | DeclSpec DS(AttrFactory); |
1264 | DS.SetRangeStart(Tok.getLocation()); |
1265 | DS.SetRangeEnd(Tok.getLastLoc()); |
1266 | |
1267 | const char *PrevSpec = nullptr; |
1268 | unsigned DiagID; |
1269 | DS.SetTypeSpecType(T: TST_typename, Loc: Tok.getAnnotationEndLoc(), |
1270 | PrevSpec, DiagID, Rep: Type, |
1271 | Policy: Actions.getASTContext().getPrintingPolicy()); |
1272 | |
1273 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
1274 | DeclaratorContext::TypeName); |
1275 | TypeResult Ty = Actions.ActOnTypeName(D&: DeclaratorInfo); |
1276 | if (Ty.isInvalid()) |
1277 | break; |
1278 | |
1279 | ConsumeAnnotationToken(); |
1280 | Res = ParseObjCMessageExpressionBody(LBracloc: SourceLocation(), SuperLoc: SourceLocation(), |
1281 | ReceiverType: Ty.get(), ReceiverExpr: nullptr); |
1282 | break; |
1283 | } |
1284 | [[fallthrough]]; |
1285 | |
1286 | case tok::annot_decltype: |
1287 | case tok::annot_pack_indexing_type: |
1288 | case tok::kw_char: |
1289 | case tok::kw_wchar_t: |
1290 | case tok::kw_char8_t: |
1291 | case tok::kw_char16_t: |
1292 | case tok::kw_char32_t: |
1293 | case tok::kw_bool: |
1294 | case tok::kw_short: |
1295 | case tok::kw_int: |
1296 | case tok::kw_long: |
1297 | case tok::kw___int64: |
1298 | case tok::kw___int128: |
1299 | case tok::kw__ExtInt: |
1300 | case tok::kw__BitInt: |
1301 | case tok::kw_signed: |
1302 | case tok::kw_unsigned: |
1303 | case tok::kw_half: |
1304 | case tok::kw_float: |
1305 | case tok::kw_double: |
1306 | case tok::kw___bf16: |
1307 | case tok::kw__Float16: |
1308 | case tok::kw___float128: |
1309 | case tok::kw___ibm128: |
1310 | case tok::kw_void: |
1311 | case tok::kw_auto: |
1312 | case tok::kw_typename: |
1313 | case tok::kw_typeof: |
1314 | case tok::kw___vector: |
1315 | case tok::kw__Accum: |
1316 | case tok::kw__Fract: |
1317 | case tok::kw__Sat: |
1318 | #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: |
1319 | #include "clang/Basic/OpenCLImageTypes.def" |
1320 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name: |
1321 | #include "clang/Basic/HLSLIntangibleTypes.def" |
1322 | { |
1323 | if (!getLangOpts().CPlusPlus) { |
1324 | Diag(Tok, DiagID: diag::err_expected_expression); |
1325 | return ExprError(); |
1326 | } |
1327 | |
1328 | // Everything henceforth is a postfix-expression. |
1329 | if (NotPrimaryExpression) |
1330 | *NotPrimaryExpression = true; |
1331 | |
1332 | if (SavedKind == tok::kw_typename) { |
1333 | // postfix-expression: typename-specifier '(' expression-list[opt] ')' |
1334 | // typename-specifier braced-init-list |
1335 | if (TryAnnotateTypeOrScopeToken()) |
1336 | return ExprError(); |
1337 | |
1338 | if (!Tok.isSimpleTypeSpecifier(LangOpts: getLangOpts())) |
1339 | // We are trying to parse a simple-type-specifier but might not get such |
1340 | // a token after error recovery. |
1341 | return ExprError(); |
1342 | } |
1343 | |
1344 | // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' |
1345 | // simple-type-specifier braced-init-list |
1346 | // |
1347 | DeclSpec DS(AttrFactory); |
1348 | |
1349 | ParseCXXSimpleTypeSpecifier(DS); |
1350 | if (Tok.isNot(K: tok::l_paren) && |
1351 | (!getLangOpts().CPlusPlus11 || Tok.isNot(K: tok::l_brace))) |
1352 | return ExprError(Diag(Tok, DiagID: diag::err_expected_lparen_after_type) |
1353 | << DS.getSourceRange()); |
1354 | |
1355 | if (Tok.is(K: tok::l_brace)) |
1356 | Diag(Tok, DiagID: diag::warn_cxx98_compat_generalized_initializer_lists); |
1357 | |
1358 | Res = ParseCXXTypeConstructExpression(DS); |
1359 | break; |
1360 | } |
1361 | |
1362 | case tok::annot_cxxscope: { // [C++] id-expression: qualified-id |
1363 | // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. |
1364 | // (We can end up in this situation after tentative parsing.) |
1365 | if (TryAnnotateTypeOrScopeToken()) |
1366 | return ExprError(); |
1367 | if (!Tok.is(K: tok::annot_cxxscope)) |
1368 | return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr, |
1369 | isTypeCast, isVectorLiteral, |
1370 | NotPrimaryExpression); |
1371 | |
1372 | Token Next = NextToken(); |
1373 | if (Next.is(K: tok::annot_template_id)) { |
1374 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Next); |
1375 | if (TemplateId->Kind == TNK_Type_template) { |
1376 | // We have a qualified template-id that we know refers to a |
1377 | // type, translate it into a type and continue parsing as a |
1378 | // cast expression. |
1379 | CXXScopeSpec SS; |
1380 | ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, |
1381 | /*ObjectHasErrors=*/false, |
1382 | /*EnteringContext=*/false); |
1383 | AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename: ImplicitTypenameContext::Yes); |
1384 | return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr, |
1385 | isTypeCast, isVectorLiteral, |
1386 | NotPrimaryExpression); |
1387 | } |
1388 | } |
1389 | |
1390 | // Parse as an id-expression. |
1391 | Res = ParseCXXIdExpression(isAddressOfOperand); |
1392 | break; |
1393 | } |
1394 | |
1395 | case tok::annot_template_id: { // [C++] template-id |
1396 | TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok); |
1397 | if (TemplateId->Kind == TNK_Type_template) { |
1398 | // We have a template-id that we know refers to a type, |
1399 | // translate it into a type and continue parsing as a cast |
1400 | // expression. |
1401 | CXXScopeSpec SS; |
1402 | AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename: ImplicitTypenameContext::Yes); |
1403 | return ParseCastExpression(ParseKind, isAddressOfOperand, |
1404 | NotCastExpr, isTypeCast, isVectorLiteral, |
1405 | NotPrimaryExpression); |
1406 | } |
1407 | |
1408 | // Fall through to treat the template-id as an id-expression. |
1409 | [[fallthrough]]; |
1410 | } |
1411 | |
1412 | case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id |
1413 | Res = ParseCXXIdExpression(isAddressOfOperand); |
1414 | break; |
1415 | |
1416 | case tok::coloncolon: { |
1417 | // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken |
1418 | // annotates the token, tail recurse. |
1419 | if (TryAnnotateTypeOrScopeToken()) |
1420 | return ExprError(); |
1421 | if (!Tok.is(K: tok::coloncolon)) |
1422 | return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast, |
1423 | isVectorLiteral, NotPrimaryExpression); |
1424 | |
1425 | // ::new -> [C++] new-expression |
1426 | // ::delete -> [C++] delete-expression |
1427 | SourceLocation CCLoc = ConsumeToken(); |
1428 | if (Tok.is(K: tok::kw_new)) { |
1429 | if (NotPrimaryExpression) |
1430 | *NotPrimaryExpression = true; |
1431 | Res = ParseCXXNewExpression(UseGlobal: true, Start: CCLoc); |
1432 | AllowSuffix = false; |
1433 | break; |
1434 | } |
1435 | if (Tok.is(K: tok::kw_delete)) { |
1436 | if (NotPrimaryExpression) |
1437 | *NotPrimaryExpression = true; |
1438 | Res = ParseCXXDeleteExpression(UseGlobal: true, Start: CCLoc); |
1439 | AllowSuffix = false; |
1440 | break; |
1441 | } |
1442 | |
1443 | // This is not a type name or scope specifier, it is an invalid expression. |
1444 | Diag(Loc: CCLoc, DiagID: diag::err_expected_expression); |
1445 | return ExprError(); |
1446 | } |
1447 | |
1448 | case tok::kw_new: // [C++] new-expression |
1449 | if (NotPrimaryExpression) |
1450 | *NotPrimaryExpression = true; |
1451 | Res = ParseCXXNewExpression(UseGlobal: false, Start: Tok.getLocation()); |
1452 | AllowSuffix = false; |
1453 | break; |
1454 | |
1455 | case tok::kw_delete: // [C++] delete-expression |
1456 | if (NotPrimaryExpression) |
1457 | *NotPrimaryExpression = true; |
1458 | Res = ParseCXXDeleteExpression(UseGlobal: false, Start: Tok.getLocation()); |
1459 | AllowSuffix = false; |
1460 | break; |
1461 | |
1462 | case tok::kw_requires: // [C++2a] requires-expression |
1463 | Res = ParseRequiresExpression(); |
1464 | AllowSuffix = false; |
1465 | break; |
1466 | |
1467 | case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' |
1468 | if (NotPrimaryExpression) |
1469 | *NotPrimaryExpression = true; |
1470 | Diag(Tok, DiagID: diag::warn_cxx98_compat_noexcept_expr); |
1471 | SourceLocation KeyLoc = ConsumeToken(); |
1472 | BalancedDelimiterTracker T(*this, tok::l_paren); |
1473 | |
1474 | if (T.expectAndConsume(DiagID: diag::err_expected_lparen_after, Msg: "noexcept" )) |
1475 | return ExprError(); |
1476 | // C++11 [expr.unary.noexcept]p1: |
1477 | // The noexcept operator determines whether the evaluation of its operand, |
1478 | // which is an unevaluated operand, can throw an exception. |
1479 | EnterExpressionEvaluationContext Unevaluated( |
1480 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); |
1481 | Res = ParseExpression(); |
1482 | |
1483 | T.consumeClose(); |
1484 | |
1485 | if (!Res.isInvalid()) |
1486 | Res = Actions.ActOnNoexceptExpr(KeyLoc, LParen: T.getOpenLocation(), Operand: Res.get(), |
1487 | RParen: T.getCloseLocation()); |
1488 | AllowSuffix = false; |
1489 | break; |
1490 | } |
1491 | |
1492 | #define TYPE_TRAIT(N,Spelling,K) \ |
1493 | case tok::kw_##Spelling: |
1494 | #include "clang/Basic/TokenKinds.def" |
1495 | Res = ParseTypeTrait(); |
1496 | break; |
1497 | |
1498 | case tok::kw___array_rank: |
1499 | case tok::kw___array_extent: |
1500 | if (NotPrimaryExpression) |
1501 | *NotPrimaryExpression = true; |
1502 | Res = ParseArrayTypeTrait(); |
1503 | break; |
1504 | |
1505 | case tok::kw___builtin_ptrauth_type_discriminator: |
1506 | return ParseBuiltinPtrauthTypeDiscriminator(); |
1507 | |
1508 | case tok::kw___is_lvalue_expr: |
1509 | case tok::kw___is_rvalue_expr: |
1510 | if (NotPrimaryExpression) |
1511 | *NotPrimaryExpression = true; |
1512 | Res = ParseExpressionTrait(); |
1513 | break; |
1514 | |
1515 | case tok::at: { |
1516 | if (NotPrimaryExpression) |
1517 | *NotPrimaryExpression = true; |
1518 | SourceLocation AtLoc = ConsumeToken(); |
1519 | return ParseObjCAtExpression(AtLocation: AtLoc); |
1520 | } |
1521 | case tok::caret: |
1522 | Res = ParseBlockLiteralExpression(); |
1523 | break; |
1524 | case tok::code_completion: { |
1525 | cutOffParsing(); |
1526 | Actions.CodeCompletion().CodeCompleteExpression( |
1527 | S: getCurScope(), PreferredType: PreferredType.get(Tok: Tok.getLocation())); |
1528 | return ExprError(); |
1529 | } |
1530 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: |
1531 | #include "clang/Basic/TransformTypeTraits.def" |
1532 | // HACK: libstdc++ uses some of the transform-type-traits as alias |
1533 | // templates, so we need to work around this. |
1534 | if (!NextToken().is(K: tok::l_paren)) { |
1535 | Tok.setKind(tok::identifier); |
1536 | Diag(Tok, DiagID: diag::ext_keyword_as_ident) |
1537 | << Tok.getIdentifierInfo()->getName() << 0; |
1538 | goto ParseIdentifier; |
1539 | } |
1540 | goto ExpectedExpression; |
1541 | case tok::l_square: |
1542 | if (getLangOpts().CPlusPlus) { |
1543 | if (getLangOpts().ObjC) { |
1544 | // C++11 lambda expressions and Objective-C message sends both start with a |
1545 | // square bracket. There are three possibilities here: |
1546 | // we have a valid lambda expression, we have an invalid lambda |
1547 | // expression, or we have something that doesn't appear to be a lambda. |
1548 | // If we're in the last case, we fall back to ParseObjCMessageExpression. |
1549 | Res = TryParseLambdaExpression(); |
1550 | if (!Res.isInvalid() && !Res.get()) { |
1551 | // We assume Objective-C++ message expressions are not |
1552 | // primary-expressions. |
1553 | if (NotPrimaryExpression) |
1554 | *NotPrimaryExpression = true; |
1555 | Res = ParseObjCMessageExpression(); |
1556 | } |
1557 | break; |
1558 | } |
1559 | Res = ParseLambdaExpression(); |
1560 | break; |
1561 | } |
1562 | if (getLangOpts().ObjC) { |
1563 | Res = ParseObjCMessageExpression(); |
1564 | break; |
1565 | } |
1566 | [[fallthrough]]; |
1567 | default: |
1568 | ExpectedExpression: |
1569 | NotCastExpr = true; |
1570 | return ExprError(); |
1571 | } |
1572 | |
1573 | // Check to see whether Res is a function designator only. If it is and we |
1574 | // are compiling for OpenCL, we need to return an error as this implies |
1575 | // that the address of the function is being taken, which is illegal in CL. |
1576 | |
1577 | if (ParseKind == CastParseKind::PrimaryExprOnly) |
1578 | // This is strictly a primary-expression - no postfix-expr pieces should be |
1579 | // parsed. |
1580 | return Res; |
1581 | |
1582 | if (!AllowSuffix) { |
1583 | // FIXME: Don't parse a primary-expression suffix if we encountered a parse |
1584 | // error already. |
1585 | if (Res.isInvalid()) |
1586 | return Res; |
1587 | |
1588 | switch (Tok.getKind()) { |
1589 | case tok::l_square: |
1590 | case tok::l_paren: |
1591 | case tok::plusplus: |
1592 | case tok::minusminus: |
1593 | // "expected ';'" or similar is probably the right diagnostic here. Let |
1594 | // the caller decide what to do. |
1595 | if (Tok.isAtStartOfLine()) |
1596 | return Res; |
1597 | |
1598 | [[fallthrough]]; |
1599 | case tok::period: |
1600 | case tok::arrow: |
1601 | break; |
1602 | |
1603 | default: |
1604 | return Res; |
1605 | } |
1606 | |
1607 | // This was a unary-expression for which a postfix-expression suffix is |
1608 | // not permitted by the grammar (eg, a sizeof expression or |
1609 | // new-expression or similar). Diagnose but parse the suffix anyway. |
1610 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_postfix_after_unary_requires_parens) |
1611 | << Tok.getKind() << Res.get()->getSourceRange() |
1612 | << FixItHint::CreateInsertion(InsertionLoc: Res.get()->getBeginLoc(), Code: "(" ) |
1613 | << FixItHint::CreateInsertion(InsertionLoc: PP.getLocForEndOfToken(Loc: PrevTokLocation), |
1614 | Code: ")" ); |
1615 | } |
1616 | |
1617 | // These can be followed by postfix-expr pieces. |
1618 | PreferredType = SavedType; |
1619 | Res = ParsePostfixExpressionSuffix(LHS: Res); |
1620 | if (getLangOpts().OpenCL && |
1621 | !getActions().getOpenCLOptions().isAvailableOption( |
1622 | Ext: "__cl_clang_function_pointers" , LO: getLangOpts())) |
1623 | if (Expr *PostfixExpr = Res.get()) { |
1624 | QualType Ty = PostfixExpr->getType(); |
1625 | if (!Ty.isNull() && Ty->isFunctionType()) { |
1626 | Diag(Loc: PostfixExpr->getExprLoc(), |
1627 | DiagID: diag::err_opencl_taking_function_address_parser); |
1628 | return ExprError(); |
1629 | } |
1630 | } |
1631 | |
1632 | return Res; |
1633 | } |
1634 | |
1635 | ExprResult |
1636 | Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { |
1637 | // Now that the primary-expression piece of the postfix-expression has been |
1638 | // parsed, see if there are any postfix-expression pieces here. |
1639 | SourceLocation Loc; |
1640 | auto SavedType = PreferredType; |
1641 | while (true) { |
1642 | // Each iteration relies on preferred type for the whole expression. |
1643 | PreferredType = SavedType; |
1644 | switch (Tok.getKind()) { |
1645 | case tok::code_completion: |
1646 | if (InMessageExpression) |
1647 | return LHS; |
1648 | |
1649 | cutOffParsing(); |
1650 | Actions.CodeCompletion().CodeCompletePostfixExpression( |
1651 | S: getCurScope(), LHS, PreferredType: PreferredType.get(Tok: Tok.getLocation())); |
1652 | return ExprError(); |
1653 | |
1654 | case tok::identifier: |
1655 | // If we see identifier: after an expression, and we're not already in a |
1656 | // message send, then this is probably a message send with a missing |
1657 | // opening bracket '['. |
1658 | if (getLangOpts().ObjC && !InMessageExpression && |
1659 | (NextToken().is(K: tok::colon) || NextToken().is(K: tok::r_square))) { |
1660 | LHS = ParseObjCMessageExpressionBody(LBracloc: SourceLocation(), SuperLoc: SourceLocation(), |
1661 | ReceiverType: nullptr, ReceiverExpr: LHS.get()); |
1662 | break; |
1663 | } |
1664 | // Fall through; this isn't a message send. |
1665 | [[fallthrough]]; |
1666 | |
1667 | default: // Not a postfix-expression suffix. |
1668 | return LHS; |
1669 | case tok::l_square: { // postfix-expression: p-e '[' expression ']' |
1670 | // If we have a array postfix expression that starts on a new line and |
1671 | // Objective-C is enabled, it is highly likely that the user forgot a |
1672 | // semicolon after the base expression and that the array postfix-expr is |
1673 | // actually another message send. In this case, do some look-ahead to see |
1674 | // if the contents of the square brackets are obviously not a valid |
1675 | // expression and recover by pretending there is no suffix. |
1676 | if (getLangOpts().ObjC && Tok.isAtStartOfLine() && |
1677 | isSimpleObjCMessageExpression()) |
1678 | return LHS; |
1679 | |
1680 | // Reject array indices starting with a lambda-expression. '[[' is |
1681 | // reserved for attributes. |
1682 | if (CheckProhibitedCXX11Attribute()) { |
1683 | return ExprError(); |
1684 | } |
1685 | BalancedDelimiterTracker T(*this, tok::l_square); |
1686 | T.consumeOpen(); |
1687 | Loc = T.getOpenLocation(); |
1688 | ExprResult Length, Stride; |
1689 | SourceLocation ColonLocFirst, ColonLocSecond; |
1690 | ExprVector ArgExprs; |
1691 | bool HasError = false; |
1692 | PreferredType.enterSubscript(S&: Actions, Tok: Tok.getLocation(), LHS: LHS.get()); |
1693 | |
1694 | // We try to parse a list of indexes in all language mode first |
1695 | // and, in we find 0 or one index, we try to parse an OpenMP/OpenACC array |
1696 | // section. This allow us to support C++23 multi dimensional subscript and |
1697 | // OpenMP/OpenACC sections in the same language mode. |
1698 | if ((!getLangOpts().OpenMP && !AllowOpenACCArraySections) || |
1699 | Tok.isNot(K: tok::colon)) { |
1700 | if (!getLangOpts().CPlusPlus23) { |
1701 | ExprResult Idx; |
1702 | if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace)) { |
1703 | Diag(Tok, DiagID: diag::warn_cxx98_compat_generalized_initializer_lists); |
1704 | Idx = ParseBraceInitializer(); |
1705 | } else { |
1706 | Idx = ParseExpression(); // May be a comma expression |
1707 | } |
1708 | if (Idx.isInvalid()) { |
1709 | HasError = true; |
1710 | } else { |
1711 | ArgExprs.push_back(Elt: Idx.get()); |
1712 | } |
1713 | } else if (Tok.isNot(K: tok::r_square)) { |
1714 | if (ParseExpressionList(Exprs&: ArgExprs)) { |
1715 | HasError = true; |
1716 | } |
1717 | } |
1718 | } |
1719 | |
1720 | // Handle OpenACC first, since 'AllowOpenACCArraySections' is only enabled |
1721 | // when actively parsing a 'var' in a 'var-list' during clause/'cache' |
1722 | // parsing, so it is the most specific, and best allows us to handle |
1723 | // OpenACC and OpenMP at the same time. |
1724 | if (ArgExprs.size() <= 1 && AllowOpenACCArraySections) { |
1725 | ColonProtectionRAIIObject RAII(*this); |
1726 | if (Tok.is(K: tok::colon)) { |
1727 | // Consume ':' |
1728 | ColonLocFirst = ConsumeToken(); |
1729 | if (Tok.isNot(K: tok::r_square)) |
1730 | Length = ParseExpression(); |
1731 | } |
1732 | } else if (ArgExprs.size() <= 1 && getLangOpts().OpenMP) { |
1733 | ColonProtectionRAIIObject RAII(*this); |
1734 | if (Tok.is(K: tok::colon)) { |
1735 | // Consume ':' |
1736 | ColonLocFirst = ConsumeToken(); |
1737 | if (Tok.isNot(K: tok::r_square) && |
1738 | (getLangOpts().OpenMP < 50 || |
1739 | ((Tok.isNot(K: tok::colon) && getLangOpts().OpenMP >= 50)))) { |
1740 | Length = ParseExpression(); |
1741 | } |
1742 | } |
1743 | if (getLangOpts().OpenMP >= 50 && |
1744 | (OMPClauseKind == llvm::omp::Clause::OMPC_to || |
1745 | OMPClauseKind == llvm::omp::Clause::OMPC_from) && |
1746 | Tok.is(K: tok::colon)) { |
1747 | // Consume ':' |
1748 | ColonLocSecond = ConsumeToken(); |
1749 | if (Tok.isNot(K: tok::r_square)) { |
1750 | Stride = ParseExpression(); |
1751 | } |
1752 | } |
1753 | } |
1754 | |
1755 | SourceLocation RLoc = Tok.getLocation(); |
1756 | if (!LHS.isInvalid() && !HasError && !Length.isInvalid() && |
1757 | !Stride.isInvalid() && Tok.is(K: tok::r_square)) { |
1758 | if (ColonLocFirst.isValid() || ColonLocSecond.isValid()) { |
1759 | // Like above, AllowOpenACCArraySections is 'more specific' and only |
1760 | // enabled when actively parsing a 'var' in a 'var-list' during |
1761 | // clause/'cache' construct parsing, so it is more specific. So we |
1762 | // should do it first, so that the correct node gets created. |
1763 | if (AllowOpenACCArraySections) { |
1764 | assert(!Stride.isUsable() && !ColonLocSecond.isValid() && |
1765 | "Stride/second colon not allowed for OpenACC" ); |
1766 | LHS = Actions.OpenACC().ActOnArraySectionExpr( |
1767 | Base: LHS.get(), LBLoc: Loc, LowerBound: ArgExprs.empty() ? nullptr : ArgExprs[0], |
1768 | ColonLocFirst, Length: Length.get(), RBLoc: RLoc); |
1769 | } else { |
1770 | LHS = Actions.OpenMP().ActOnOMPArraySectionExpr( |
1771 | Base: LHS.get(), LBLoc: Loc, LowerBound: ArgExprs.empty() ? nullptr : ArgExprs[0], |
1772 | ColonLocFirst, ColonLocSecond, Length: Length.get(), Stride: Stride.get(), |
1773 | RBLoc: RLoc); |
1774 | } |
1775 | } else { |
1776 | LHS = Actions.ActOnArraySubscriptExpr(S: getCurScope(), Base: LHS.get(), LLoc: Loc, |
1777 | ArgExprs, RLoc); |
1778 | } |
1779 | } else { |
1780 | LHS = ExprError(); |
1781 | } |
1782 | |
1783 | // Match the ']'. |
1784 | T.consumeClose(); |
1785 | break; |
1786 | } |
1787 | |
1788 | case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' |
1789 | case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' |
1790 | // '(' argument-expression-list[opt] ')' |
1791 | tok::TokenKind OpKind = Tok.getKind(); |
1792 | InMessageExpressionRAIIObject InMessage(*this, false); |
1793 | |
1794 | Expr *ExecConfig = nullptr; |
1795 | |
1796 | BalancedDelimiterTracker PT(*this, tok::l_paren); |
1797 | |
1798 | if (OpKind == tok::lesslessless) { |
1799 | ExprVector ExecConfigExprs; |
1800 | SourceLocation OpenLoc = ConsumeToken(); |
1801 | |
1802 | if (ParseSimpleExpressionList(Exprs&: ExecConfigExprs)) { |
1803 | LHS = ExprError(); |
1804 | } |
1805 | |
1806 | SourceLocation CloseLoc; |
1807 | if (TryConsumeToken(Expected: tok::greatergreatergreater, Loc&: CloseLoc)) { |
1808 | } else if (LHS.isInvalid()) { |
1809 | SkipUntil(T: tok::greatergreatergreater, Flags: StopAtSemi); |
1810 | } else { |
1811 | // There was an error closing the brackets |
1812 | Diag(Tok, DiagID: diag::err_expected) << tok::greatergreatergreater; |
1813 | Diag(Loc: OpenLoc, DiagID: diag::note_matching) << tok::lesslessless; |
1814 | SkipUntil(T: tok::greatergreatergreater, Flags: StopAtSemi); |
1815 | LHS = ExprError(); |
1816 | } |
1817 | |
1818 | if (!LHS.isInvalid()) { |
1819 | if (ExpectAndConsume(ExpectedTok: tok::l_paren)) |
1820 | LHS = ExprError(); |
1821 | else |
1822 | Loc = PrevTokLocation; |
1823 | } |
1824 | |
1825 | if (!LHS.isInvalid()) { |
1826 | ExprResult ECResult = Actions.CUDA().ActOnExecConfigExpr( |
1827 | S: getCurScope(), LLLLoc: OpenLoc, ExecConfig: ExecConfigExprs, GGGLoc: CloseLoc); |
1828 | if (ECResult.isInvalid()) |
1829 | LHS = ExprError(); |
1830 | else |
1831 | ExecConfig = ECResult.get(); |
1832 | } |
1833 | } else { |
1834 | PT.consumeOpen(); |
1835 | Loc = PT.getOpenLocation(); |
1836 | } |
1837 | |
1838 | ExprVector ArgExprs; |
1839 | auto RunSignatureHelp = [&]() -> QualType { |
1840 | QualType PreferredType = |
1841 | Actions.CodeCompletion().ProduceCallSignatureHelp( |
1842 | Fn: LHS.get(), Args: ArgExprs, OpenParLoc: PT.getOpenLocation()); |
1843 | CalledSignatureHelp = true; |
1844 | return PreferredType; |
1845 | }; |
1846 | bool ExpressionListIsInvalid = false; |
1847 | if (OpKind == tok::l_paren || !LHS.isInvalid()) { |
1848 | if (Tok.isNot(K: tok::r_paren)) { |
1849 | if ((ExpressionListIsInvalid = ParseExpressionList(Exprs&: ArgExprs, ExpressionStarts: [&] { |
1850 | PreferredType.enterFunctionArgument(Tok: Tok.getLocation(), |
1851 | ComputeType: RunSignatureHelp); |
1852 | }))) { |
1853 | // If we got an error when parsing expression list, we don't call |
1854 | // the CodeCompleteCall handler inside the parser. So call it here |
1855 | // to make sure we get overload suggestions even when we are in the |
1856 | // middle of a parameter. |
1857 | if (PP.isCodeCompletionReached() && !CalledSignatureHelp) |
1858 | RunSignatureHelp(); |
1859 | } |
1860 | } |
1861 | } |
1862 | |
1863 | // Match the ')'. |
1864 | if (LHS.isInvalid()) { |
1865 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
1866 | } else if (ExpressionListIsInvalid) { |
1867 | Expr *Fn = LHS.get(); |
1868 | ArgExprs.insert(I: ArgExprs.begin(), Elt: Fn); |
1869 | LHS = Actions.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: Tok.getLocation(), |
1870 | SubExprs: ArgExprs); |
1871 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
1872 | } else if (Tok.isNot(K: tok::r_paren)) { |
1873 | bool HadErrors = false; |
1874 | if (LHS.get()->containsErrors()) |
1875 | HadErrors = true; |
1876 | for (auto &E : ArgExprs) |
1877 | if (E->containsErrors()) |
1878 | HadErrors = true; |
1879 | // If there were errors in the LHS or ArgExprs, call SkipUntil instead |
1880 | // of PT.consumeClose() to avoid emitting extra diagnostics for the |
1881 | // unmatched l_paren. |
1882 | if (HadErrors) |
1883 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
1884 | else |
1885 | PT.consumeClose(); |
1886 | LHS = ExprError(); |
1887 | } else { |
1888 | Expr *Fn = LHS.get(); |
1889 | SourceLocation RParLoc = Tok.getLocation(); |
1890 | LHS = Actions.ActOnCallExpr(S: getCurScope(), Fn, LParenLoc: Loc, ArgExprs, RParenLoc: RParLoc, |
1891 | ExecConfig); |
1892 | if (LHS.isInvalid()) { |
1893 | ArgExprs.insert(I: ArgExprs.begin(), Elt: Fn); |
1894 | LHS = |
1895 | Actions.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParLoc, SubExprs: ArgExprs); |
1896 | } |
1897 | PT.consumeClose(); |
1898 | } |
1899 | |
1900 | break; |
1901 | } |
1902 | case tok::arrow: |
1903 | case tok::period: { |
1904 | // postfix-expression: p-e '->' template[opt] id-expression |
1905 | // postfix-expression: p-e '.' template[opt] id-expression |
1906 | tok::TokenKind OpKind = Tok.getKind(); |
1907 | SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. |
1908 | |
1909 | CXXScopeSpec SS; |
1910 | ParsedType ObjectType; |
1911 | bool MayBePseudoDestructor = false; |
1912 | Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr; |
1913 | |
1914 | PreferredType.enterMemAccess(S&: Actions, Tok: Tok.getLocation(), Base: OrigLHS); |
1915 | |
1916 | if (getLangOpts().CPlusPlus && !LHS.isInvalid()) { |
1917 | Expr *Base = OrigLHS; |
1918 | const Type* BaseType = Base->getType().getTypePtrOrNull(); |
1919 | if (BaseType && Tok.is(K: tok::l_paren) && |
1920 | (BaseType->isFunctionType() || |
1921 | BaseType->isSpecificPlaceholderType(K: BuiltinType::BoundMember))) { |
1922 | Diag(Loc: OpLoc, DiagID: diag::err_function_is_not_record) |
1923 | << OpKind << Base->getSourceRange() |
1924 | << FixItHint::CreateRemoval(RemoveRange: OpLoc); |
1925 | return ParsePostfixExpressionSuffix(LHS: Base); |
1926 | } |
1927 | |
1928 | LHS = Actions.ActOnStartCXXMemberReference(S: getCurScope(), Base, OpLoc, |
1929 | OpKind, ObjectType, |
1930 | MayBePseudoDestructor); |
1931 | if (LHS.isInvalid()) { |
1932 | // Clang will try to perform expression based completion as a |
1933 | // fallback, which is confusing in case of member references. So we |
1934 | // stop here without any completions. |
1935 | if (Tok.is(K: tok::code_completion)) { |
1936 | cutOffParsing(); |
1937 | return ExprError(); |
1938 | } |
1939 | break; |
1940 | } |
1941 | ParseOptionalCXXScopeSpecifier( |
1942 | SS, ObjectType, ObjectHasErrors: LHS.get() && LHS.get()->containsErrors(), |
1943 | /*EnteringContext=*/false, MayBePseudoDestructor: &MayBePseudoDestructor); |
1944 | if (SS.isNotEmpty()) |
1945 | ObjectType = nullptr; |
1946 | } |
1947 | |
1948 | if (Tok.is(K: tok::code_completion)) { |
1949 | tok::TokenKind CorrectedOpKind = |
1950 | OpKind == tok::arrow ? tok::period : tok::arrow; |
1951 | ExprResult CorrectedLHS(/*Invalid=*/true); |
1952 | if (getLangOpts().CPlusPlus && OrigLHS) { |
1953 | // FIXME: Creating a TentativeAnalysisScope from outside Sema is a |
1954 | // hack. |
1955 | Sema::TentativeAnalysisScope Trap(Actions); |
1956 | CorrectedLHS = Actions.ActOnStartCXXMemberReference( |
1957 | S: getCurScope(), Base: OrigLHS, OpLoc, OpKind: CorrectedOpKind, ObjectType, |
1958 | MayBePseudoDestructor); |
1959 | } |
1960 | |
1961 | Expr *Base = LHS.get(); |
1962 | Expr *CorrectedBase = CorrectedLHS.get(); |
1963 | if (!CorrectedBase && !getLangOpts().CPlusPlus) |
1964 | CorrectedBase = Base; |
1965 | |
1966 | // Code completion for a member access expression. |
1967 | cutOffParsing(); |
1968 | Actions.CodeCompletion().CodeCompleteMemberReferenceExpr( |
1969 | S: getCurScope(), Base, OtherOpBase: CorrectedBase, OpLoc, IsArrow: OpKind == tok::arrow, |
1970 | IsBaseExprStatement: Base && ExprStatementTokLoc == Base->getBeginLoc(), |
1971 | PreferredType: PreferredType.get(Tok: Tok.getLocation())); |
1972 | |
1973 | return ExprError(); |
1974 | } |
1975 | |
1976 | if (MayBePseudoDestructor && !LHS.isInvalid()) { |
1977 | LHS = ParseCXXPseudoDestructor(Base: LHS.get(), OpLoc, OpKind, SS, |
1978 | ObjectType); |
1979 | break; |
1980 | } |
1981 | |
1982 | // Either the action has told us that this cannot be a |
1983 | // pseudo-destructor expression (based on the type of base |
1984 | // expression), or we didn't see a '~' in the right place. We |
1985 | // can still parse a destructor name here, but in that case it |
1986 | // names a real destructor. |
1987 | // Allow explicit constructor calls in Microsoft mode. |
1988 | // FIXME: Add support for explicit call of template constructor. |
1989 | SourceLocation TemplateKWLoc; |
1990 | UnqualifiedId Name; |
1991 | if (getLangOpts().ObjC && OpKind == tok::period && |
1992 | Tok.is(K: tok::kw_class)) { |
1993 | // Objective-C++: |
1994 | // After a '.' in a member access expression, treat the keyword |
1995 | // 'class' as if it were an identifier. |
1996 | // |
1997 | // This hack allows property access to the 'class' method because it is |
1998 | // such a common method name. For other C++ keywords that are |
1999 | // Objective-C method names, one must use the message send syntax. |
2000 | IdentifierInfo *Id = Tok.getIdentifierInfo(); |
2001 | SourceLocation Loc = ConsumeToken(); |
2002 | Name.setIdentifier(Id, IdLoc: Loc); |
2003 | } else if (ParseUnqualifiedId( |
2004 | SS, ObjectType, ObjectHadErrors: LHS.get() && LHS.get()->containsErrors(), |
2005 | /*EnteringContext=*/false, |
2006 | /*AllowDestructorName=*/true, |
2007 | /*AllowConstructorName=*/ |
2008 | getLangOpts().MicrosoftExt && SS.isNotEmpty(), |
2009 | /*AllowDeductionGuide=*/false, TemplateKWLoc: &TemplateKWLoc, Result&: Name)) { |
2010 | LHS = ExprError(); |
2011 | } |
2012 | |
2013 | if (!LHS.isInvalid()) |
2014 | LHS = Actions.ActOnMemberAccessExpr(S: getCurScope(), Base: LHS.get(), OpLoc, |
2015 | OpKind, SS, TemplateKWLoc, Member&: Name, |
2016 | ObjCImpDecl: CurParsedObjCImpl ? CurParsedObjCImpl->Dcl |
2017 | : nullptr); |
2018 | if (!LHS.isInvalid()) { |
2019 | if (Tok.is(K: tok::less)) |
2020 | checkPotentialAngleBracket(PotentialTemplateName&: LHS); |
2021 | } else if (OrigLHS && Name.isValid()) { |
2022 | // Preserve the LHS if the RHS is an invalid member. |
2023 | LHS = Actions.CreateRecoveryExpr(Begin: OrigLHS->getBeginLoc(), |
2024 | End: Name.getEndLoc(), SubExprs: {OrigLHS}); |
2025 | } |
2026 | break; |
2027 | } |
2028 | case tok::plusplus: // postfix-expression: postfix-expression '++' |
2029 | case tok::minusminus: // postfix-expression: postfix-expression '--' |
2030 | if (!LHS.isInvalid()) { |
2031 | Expr *Arg = LHS.get(); |
2032 | LHS = Actions.ActOnPostfixUnaryOp(S: getCurScope(), OpLoc: Tok.getLocation(), |
2033 | Kind: Tok.getKind(), Input: Arg); |
2034 | if (LHS.isInvalid()) |
2035 | LHS = Actions.CreateRecoveryExpr(Begin: Arg->getBeginLoc(), |
2036 | End: Tok.getLocation(), SubExprs: Arg); |
2037 | } |
2038 | ConsumeToken(); |
2039 | break; |
2040 | } |
2041 | } |
2042 | } |
2043 | |
2044 | ExprResult |
2045 | Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, |
2046 | bool &isCastExpr, |
2047 | ParsedType &CastTy, |
2048 | SourceRange &CastRange) { |
2049 | |
2050 | assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual, tok::kw_sizeof, |
2051 | tok::kw___datasizeof, tok::kw___alignof, tok::kw_alignof, |
2052 | tok::kw__Alignof, tok::kw_vec_step, |
2053 | tok::kw___builtin_omp_required_simd_align, |
2054 | tok::kw___builtin_vectorelements, tok::kw__Countof) && |
2055 | "Not a typeof/sizeof/alignof/vec_step expression!" ); |
2056 | |
2057 | ExprResult Operand; |
2058 | |
2059 | // If the operand doesn't start with an '(', it must be an expression. |
2060 | if (Tok.isNot(K: tok::l_paren)) { |
2061 | // If construct allows a form without parenthesis, user may forget to put |
2062 | // pathenthesis around type name. |
2063 | if (OpTok.isOneOf(Ks: tok::kw_sizeof, Ks: tok::kw___datasizeof, Ks: tok::kw___alignof, |
2064 | Ks: tok::kw_alignof, Ks: tok::kw__Alignof)) { |
2065 | if (isTypeIdUnambiguously()) { |
2066 | DeclSpec DS(AttrFactory); |
2067 | ParseSpecifierQualifierList(DS); |
2068 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
2069 | DeclaratorContext::TypeName); |
2070 | ParseDeclarator(D&: DeclaratorInfo); |
2071 | |
2072 | SourceLocation LParenLoc = PP.getLocForEndOfToken(Loc: OpTok.getLocation()); |
2073 | SourceLocation RParenLoc = PP.getLocForEndOfToken(Loc: PrevTokLocation); |
2074 | if (LParenLoc.isInvalid() || RParenLoc.isInvalid()) { |
2075 | Diag(Loc: OpTok.getLocation(), |
2076 | DiagID: diag::err_expected_parentheses_around_typename) |
2077 | << OpTok.getName(); |
2078 | } else { |
2079 | Diag(Loc: LParenLoc, DiagID: diag::err_expected_parentheses_around_typename) |
2080 | << OpTok.getName() << FixItHint::CreateInsertion(InsertionLoc: LParenLoc, Code: "(" ) |
2081 | << FixItHint::CreateInsertion(InsertionLoc: RParenLoc, Code: ")" ); |
2082 | } |
2083 | isCastExpr = true; |
2084 | return ExprEmpty(); |
2085 | } |
2086 | } |
2087 | |
2088 | isCastExpr = false; |
2089 | if (OpTok.isOneOf(Ks: tok::kw_typeof, Ks: tok::kw_typeof_unqual) && |
2090 | !getLangOpts().CPlusPlus) { |
2091 | Diag(Tok, DiagID: diag::err_expected_after) << OpTok.getIdentifierInfo() |
2092 | << tok::l_paren; |
2093 | return ExprError(); |
2094 | } |
2095 | |
2096 | // If we're parsing a chain that consists of keywords that could be |
2097 | // followed by a non-parenthesized expression, BalancedDelimiterTracker |
2098 | // is not going to help when the nesting is too deep. In this corner case |
2099 | // we continue to parse with sufficient stack space to avoid crashing. |
2100 | if (OpTok.isOneOf(Ks: tok::kw_sizeof, Ks: tok::kw___datasizeof, Ks: tok::kw___alignof, |
2101 | Ks: tok::kw_alignof, Ks: tok::kw__Alignof, Ks: tok::kw__Countof) && |
2102 | Tok.isOneOf(Ks: tok::kw_sizeof, Ks: tok::kw___datasizeof, Ks: tok::kw___alignof, |
2103 | Ks: tok::kw_alignof, Ks: tok::kw__Alignof, Ks: tok::kw__Countof)) |
2104 | Actions.runWithSufficientStackSpace(Loc: Tok.getLocation(), Fn: [&] { |
2105 | Operand = ParseCastExpression(ParseKind: CastParseKind::UnaryExprOnly); |
2106 | }); |
2107 | else |
2108 | Operand = ParseCastExpression(ParseKind: CastParseKind::UnaryExprOnly); |
2109 | } else { |
2110 | // If it starts with a '(', we know that it is either a parenthesized |
2111 | // type-name, or it is a unary-expression that starts with a compound |
2112 | // literal, or starts with a primary-expression that is a parenthesized |
2113 | // expression. |
2114 | ParenParseOption ExprType = ParenParseOption::CastExpr; |
2115 | SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; |
2116 | |
2117 | Operand = ParseParenExpression(ExprType, stopIfCastExpr: true/*stopIfCastExpr*/, |
2118 | isTypeCast: false, CastTy, RParenLoc); |
2119 | CastRange = SourceRange(LParenLoc, RParenLoc); |
2120 | |
2121 | // If ParseParenExpression parsed a '(typename)' sequence only, then this is |
2122 | // a type. |
2123 | if (ExprType == ParenParseOption::CastExpr) { |
2124 | isCastExpr = true; |
2125 | return ExprEmpty(); |
2126 | } |
2127 | |
2128 | if (getLangOpts().CPlusPlus || |
2129 | !OpTok.isOneOf(Ks: tok::kw_typeof, Ks: tok::kw_typeof_unqual)) { |
2130 | // GNU typeof in C requires the expression to be parenthesized. Not so for |
2131 | // sizeof/alignof or in C++. Therefore, the parenthesized expression is |
2132 | // the start of a unary-expression, but doesn't include any postfix |
2133 | // pieces. Parse these now if present. |
2134 | if (!Operand.isInvalid()) |
2135 | Operand = ParsePostfixExpressionSuffix(LHS: Operand.get()); |
2136 | } |
2137 | } |
2138 | |
2139 | // If we get here, the operand to the typeof/sizeof/alignof was an expression. |
2140 | isCastExpr = false; |
2141 | return Operand; |
2142 | } |
2143 | |
2144 | ExprResult Parser::ParseSYCLUniqueStableNameExpression() { |
2145 | assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) && |
2146 | "Not __builtin_sycl_unique_stable_name" ); |
2147 | |
2148 | SourceLocation OpLoc = ConsumeToken(); |
2149 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2150 | |
2151 | // __builtin_sycl_unique_stable_name expressions are always parenthesized. |
2152 | if (T.expectAndConsume(DiagID: diag::err_expected_lparen_after, |
2153 | Msg: "__builtin_sycl_unique_stable_name" )) |
2154 | return ExprError(); |
2155 | |
2156 | TypeResult Ty = ParseTypeName(); |
2157 | |
2158 | if (Ty.isInvalid()) { |
2159 | T.skipToEnd(); |
2160 | return ExprError(); |
2161 | } |
2162 | |
2163 | if (T.consumeClose()) |
2164 | return ExprError(); |
2165 | |
2166 | return Actions.SYCL().ActOnUniqueStableNameExpr( |
2167 | OpLoc, LParen: T.getOpenLocation(), RParen: T.getCloseLocation(), ParsedTy: Ty.get()); |
2168 | } |
2169 | |
2170 | ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { |
2171 | assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___datasizeof, tok::kw___alignof, |
2172 | tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step, |
2173 | tok::kw___builtin_omp_required_simd_align, |
2174 | tok::kw___builtin_vectorelements, tok::kw__Countof) && |
2175 | "Not a sizeof/alignof/vec_step expression!" ); |
2176 | Token OpTok = Tok; |
2177 | ConsumeToken(); |
2178 | |
2179 | // [C++11] 'sizeof' '...' '(' identifier ')' |
2180 | if (Tok.is(K: tok::ellipsis) && OpTok.is(K: tok::kw_sizeof)) { |
2181 | SourceLocation EllipsisLoc = ConsumeToken(); |
2182 | SourceLocation LParenLoc, RParenLoc; |
2183 | IdentifierInfo *Name = nullptr; |
2184 | SourceLocation NameLoc; |
2185 | if (Tok.is(K: tok::l_paren)) { |
2186 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2187 | T.consumeOpen(); |
2188 | LParenLoc = T.getOpenLocation(); |
2189 | if (Tok.is(K: tok::identifier)) { |
2190 | Name = Tok.getIdentifierInfo(); |
2191 | NameLoc = ConsumeToken(); |
2192 | T.consumeClose(); |
2193 | RParenLoc = T.getCloseLocation(); |
2194 | if (RParenLoc.isInvalid()) |
2195 | RParenLoc = PP.getLocForEndOfToken(Loc: NameLoc); |
2196 | } else { |
2197 | Diag(Tok, DiagID: diag::err_expected_parameter_pack); |
2198 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2199 | } |
2200 | } else if (Tok.is(K: tok::identifier)) { |
2201 | Name = Tok.getIdentifierInfo(); |
2202 | NameLoc = ConsumeToken(); |
2203 | LParenLoc = PP.getLocForEndOfToken(Loc: EllipsisLoc); |
2204 | RParenLoc = PP.getLocForEndOfToken(Loc: NameLoc); |
2205 | Diag(Loc: LParenLoc, DiagID: diag::err_paren_sizeof_parameter_pack) |
2206 | << Name |
2207 | << FixItHint::CreateInsertion(InsertionLoc: LParenLoc, Code: "(" ) |
2208 | << FixItHint::CreateInsertion(InsertionLoc: RParenLoc, Code: ")" ); |
2209 | } else { |
2210 | Diag(Tok, DiagID: diag::err_sizeof_parameter_pack); |
2211 | } |
2212 | |
2213 | if (!Name) |
2214 | return ExprError(); |
2215 | |
2216 | EnterExpressionEvaluationContext Unevaluated( |
2217 | Actions, Sema::ExpressionEvaluationContext::Unevaluated, |
2218 | Sema::ReuseLambdaContextDecl); |
2219 | |
2220 | return Actions.ActOnSizeofParameterPackExpr(S: getCurScope(), |
2221 | OpLoc: OpTok.getLocation(), |
2222 | Name&: *Name, NameLoc, |
2223 | RParenLoc); |
2224 | } |
2225 | |
2226 | if (getLangOpts().CPlusPlus && |
2227 | OpTok.isOneOf(Ks: tok::kw_alignof, Ks: tok::kw__Alignof)) |
2228 | Diag(Tok: OpTok, DiagID: diag::warn_cxx98_compat_alignof); |
2229 | else if (getLangOpts().C23 && OpTok.is(K: tok::kw_alignof)) |
2230 | Diag(Tok: OpTok, DiagID: diag::warn_c23_compat_keyword) << OpTok.getName(); |
2231 | else if (getLangOpts().C2y && OpTok.is(K: tok::kw__Countof)) |
2232 | Diag(Tok: OpTok, DiagID: diag::warn_c2y_compat_keyword) << OpTok.getName(); |
2233 | |
2234 | EnterExpressionEvaluationContext Unevaluated( |
2235 | Actions, Sema::ExpressionEvaluationContext::Unevaluated, |
2236 | Sema::ReuseLambdaContextDecl); |
2237 | |
2238 | bool isCastExpr; |
2239 | ParsedType CastTy; |
2240 | SourceRange CastRange; |
2241 | ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, |
2242 | isCastExpr, |
2243 | CastTy, |
2244 | CastRange); |
2245 | |
2246 | UnaryExprOrTypeTrait ExprKind = UETT_SizeOf; |
2247 | switch (OpTok.getKind()) { |
2248 | case tok::kw_alignof: |
2249 | case tok::kw__Alignof: |
2250 | ExprKind = UETT_AlignOf; |
2251 | break; |
2252 | case tok::kw___alignof: |
2253 | ExprKind = UETT_PreferredAlignOf; |
2254 | break; |
2255 | case tok::kw_vec_step: |
2256 | ExprKind = UETT_VecStep; |
2257 | break; |
2258 | case tok::kw___builtin_omp_required_simd_align: |
2259 | ExprKind = UETT_OpenMPRequiredSimdAlign; |
2260 | break; |
2261 | case tok::kw___datasizeof: |
2262 | ExprKind = UETT_DataSizeOf; |
2263 | break; |
2264 | case tok::kw___builtin_vectorelements: |
2265 | ExprKind = UETT_VectorElements; |
2266 | break; |
2267 | case tok::kw__Countof: |
2268 | ExprKind = UETT_CountOf; |
2269 | assert(!getLangOpts().CPlusPlus && "_Countof in C++ mode?" ); |
2270 | if (!getLangOpts().C2y) |
2271 | Diag(Tok: OpTok, DiagID: diag::ext_c2y_feature) << OpTok.getName(); |
2272 | break; |
2273 | default: |
2274 | break; |
2275 | } |
2276 | |
2277 | if (isCastExpr) |
2278 | return Actions.ActOnUnaryExprOrTypeTraitExpr(OpLoc: OpTok.getLocation(), |
2279 | ExprKind, |
2280 | /*IsType=*/true, |
2281 | TyOrEx: CastTy.getAsOpaquePtr(), |
2282 | ArgRange: CastRange); |
2283 | |
2284 | if (OpTok.isOneOf(Ks: tok::kw_alignof, Ks: tok::kw__Alignof)) |
2285 | Diag(Tok: OpTok, DiagID: diag::ext_alignof_expr) << OpTok.getIdentifierInfo(); |
2286 | |
2287 | // If we get here, the operand to the sizeof/alignof was an expression. |
2288 | if (!Operand.isInvalid()) |
2289 | Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpLoc: OpTok.getLocation(), |
2290 | ExprKind, |
2291 | /*IsType=*/false, |
2292 | TyOrEx: Operand.get(), |
2293 | ArgRange: CastRange); |
2294 | return Operand; |
2295 | } |
2296 | |
2297 | ExprResult Parser::ParseBuiltinPrimaryExpression() { |
2298 | ExprResult Res; |
2299 | const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); |
2300 | |
2301 | tok::TokenKind T = Tok.getKind(); |
2302 | SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. |
2303 | |
2304 | // All of these start with an open paren. |
2305 | if (Tok.isNot(K: tok::l_paren)) |
2306 | return ExprError(Diag(Tok, DiagID: diag::err_expected_after) << BuiltinII |
2307 | << tok::l_paren); |
2308 | |
2309 | BalancedDelimiterTracker PT(*this, tok::l_paren); |
2310 | PT.consumeOpen(); |
2311 | |
2312 | // TODO: Build AST. |
2313 | |
2314 | switch (T) { |
2315 | default: llvm_unreachable("Not a builtin primary expression!" ); |
2316 | case tok::kw___builtin_va_arg: { |
2317 | ExprResult Expr(ParseAssignmentExpression()); |
2318 | |
2319 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
2320 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2321 | Expr = ExprError(); |
2322 | } |
2323 | |
2324 | TypeResult Ty = ParseTypeName(); |
2325 | |
2326 | if (Tok.isNot(K: tok::r_paren)) { |
2327 | Diag(Tok, DiagID: diag::err_expected) << tok::r_paren; |
2328 | Expr = ExprError(); |
2329 | } |
2330 | |
2331 | if (Expr.isInvalid() || Ty.isInvalid()) |
2332 | Res = ExprError(); |
2333 | else |
2334 | Res = Actions.ActOnVAArg(BuiltinLoc: StartLoc, E: Expr.get(), Ty: Ty.get(), RPLoc: ConsumeParen()); |
2335 | break; |
2336 | } |
2337 | case tok::kw___builtin_offsetof: { |
2338 | SourceLocation TypeLoc = Tok.getLocation(); |
2339 | auto OOK = OffsetOfKind::Builtin; |
2340 | if (Tok.getLocation().isMacroID()) { |
2341 | StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( |
2342 | Loc: Tok.getLocation(), SM: PP.getSourceManager(), LangOpts: getLangOpts()); |
2343 | if (MacroName == "offsetof" ) |
2344 | OOK = OffsetOfKind::Macro; |
2345 | } |
2346 | TypeResult Ty; |
2347 | { |
2348 | OffsetOfStateRAIIObject InOffsetof(*this, OOK); |
2349 | Ty = ParseTypeName(); |
2350 | if (Ty.isInvalid()) { |
2351 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2352 | return ExprError(); |
2353 | } |
2354 | } |
2355 | |
2356 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
2357 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2358 | return ExprError(); |
2359 | } |
2360 | |
2361 | // We must have at least one identifier here. |
2362 | if (Tok.isNot(K: tok::identifier)) { |
2363 | Diag(Tok, DiagID: diag::err_expected) << tok::identifier; |
2364 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2365 | return ExprError(); |
2366 | } |
2367 | |
2368 | // Keep track of the various subcomponents we see. |
2369 | SmallVector<Sema::OffsetOfComponent, 4> Comps; |
2370 | |
2371 | Comps.push_back(Elt: Sema::OffsetOfComponent()); |
2372 | Comps.back().isBrackets = false; |
2373 | Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); |
2374 | Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); |
2375 | |
2376 | // FIXME: This loop leaks the index expressions on error. |
2377 | while (true) { |
2378 | if (Tok.is(K: tok::period)) { |
2379 | // offsetof-member-designator: offsetof-member-designator '.' identifier |
2380 | Comps.push_back(Elt: Sema::OffsetOfComponent()); |
2381 | Comps.back().isBrackets = false; |
2382 | Comps.back().LocStart = ConsumeToken(); |
2383 | |
2384 | if (Tok.isNot(K: tok::identifier)) { |
2385 | Diag(Tok, DiagID: diag::err_expected) << tok::identifier; |
2386 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2387 | return ExprError(); |
2388 | } |
2389 | Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); |
2390 | Comps.back().LocEnd = ConsumeToken(); |
2391 | } else if (Tok.is(K: tok::l_square)) { |
2392 | if (CheckProhibitedCXX11Attribute()) |
2393 | return ExprError(); |
2394 | |
2395 | // offsetof-member-designator: offsetof-member-design '[' expression ']' |
2396 | Comps.push_back(Elt: Sema::OffsetOfComponent()); |
2397 | Comps.back().isBrackets = true; |
2398 | BalancedDelimiterTracker ST(*this, tok::l_square); |
2399 | ST.consumeOpen(); |
2400 | Comps.back().LocStart = ST.getOpenLocation(); |
2401 | Res = ParseExpression(); |
2402 | if (Res.isInvalid()) { |
2403 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2404 | return Res; |
2405 | } |
2406 | Comps.back().U.E = Res.get(); |
2407 | |
2408 | ST.consumeClose(); |
2409 | Comps.back().LocEnd = ST.getCloseLocation(); |
2410 | } else { |
2411 | if (Tok.isNot(K: tok::r_paren)) { |
2412 | PT.consumeClose(); |
2413 | Res = ExprError(); |
2414 | } else if (Ty.isInvalid()) { |
2415 | Res = ExprError(); |
2416 | } else { |
2417 | PT.consumeClose(); |
2418 | Res = Actions.ActOnBuiltinOffsetOf(S: getCurScope(), BuiltinLoc: StartLoc, TypeLoc, |
2419 | ParsedArgTy: Ty.get(), Components: Comps, |
2420 | RParenLoc: PT.getCloseLocation()); |
2421 | } |
2422 | break; |
2423 | } |
2424 | } |
2425 | break; |
2426 | } |
2427 | case tok::kw___builtin_choose_expr: { |
2428 | ExprResult Cond(ParseAssignmentExpression()); |
2429 | if (Cond.isInvalid()) { |
2430 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2431 | return Cond; |
2432 | } |
2433 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
2434 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2435 | return ExprError(); |
2436 | } |
2437 | |
2438 | ExprResult Expr1(ParseAssignmentExpression()); |
2439 | if (Expr1.isInvalid()) { |
2440 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2441 | return Expr1; |
2442 | } |
2443 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
2444 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2445 | return ExprError(); |
2446 | } |
2447 | |
2448 | ExprResult Expr2(ParseAssignmentExpression()); |
2449 | if (Expr2.isInvalid()) { |
2450 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2451 | return Expr2; |
2452 | } |
2453 | if (Tok.isNot(K: tok::r_paren)) { |
2454 | Diag(Tok, DiagID: diag::err_expected) << tok::r_paren; |
2455 | return ExprError(); |
2456 | } |
2457 | Res = Actions.ActOnChooseExpr(BuiltinLoc: StartLoc, CondExpr: Cond.get(), LHSExpr: Expr1.get(), |
2458 | RHSExpr: Expr2.get(), RPLoc: ConsumeParen()); |
2459 | break; |
2460 | } |
2461 | case tok::kw___builtin_astype: { |
2462 | // The first argument is an expression to be converted, followed by a comma. |
2463 | ExprResult Expr(ParseAssignmentExpression()); |
2464 | if (Expr.isInvalid()) { |
2465 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2466 | return ExprError(); |
2467 | } |
2468 | |
2469 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
2470 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2471 | return ExprError(); |
2472 | } |
2473 | |
2474 | // Second argument is the type to bitcast to. |
2475 | TypeResult DestTy = ParseTypeName(); |
2476 | if (DestTy.isInvalid()) |
2477 | return ExprError(); |
2478 | |
2479 | // Attempt to consume the r-paren. |
2480 | if (Tok.isNot(K: tok::r_paren)) { |
2481 | Diag(Tok, DiagID: diag::err_expected) << tok::r_paren; |
2482 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2483 | return ExprError(); |
2484 | } |
2485 | |
2486 | Res = Actions.ActOnAsTypeExpr(E: Expr.get(), ParsedDestTy: DestTy.get(), BuiltinLoc: StartLoc, |
2487 | RParenLoc: ConsumeParen()); |
2488 | break; |
2489 | } |
2490 | case tok::kw___builtin_convertvector: { |
2491 | // The first argument is an expression to be converted, followed by a comma. |
2492 | ExprResult Expr(ParseAssignmentExpression()); |
2493 | if (Expr.isInvalid()) { |
2494 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2495 | return ExprError(); |
2496 | } |
2497 | |
2498 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
2499 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2500 | return ExprError(); |
2501 | } |
2502 | |
2503 | // Second argument is the type to bitcast to. |
2504 | TypeResult DestTy = ParseTypeName(); |
2505 | if (DestTy.isInvalid()) |
2506 | return ExprError(); |
2507 | |
2508 | // Attempt to consume the r-paren. |
2509 | if (Tok.isNot(K: tok::r_paren)) { |
2510 | Diag(Tok, DiagID: diag::err_expected) << tok::r_paren; |
2511 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2512 | return ExprError(); |
2513 | } |
2514 | |
2515 | Res = Actions.ActOnConvertVectorExpr(E: Expr.get(), ParsedDestTy: DestTy.get(), BuiltinLoc: StartLoc, |
2516 | RParenLoc: ConsumeParen()); |
2517 | break; |
2518 | } |
2519 | case tok::kw___builtin_COLUMN: |
2520 | case tok::kw___builtin_FILE: |
2521 | case tok::kw___builtin_FILE_NAME: |
2522 | case tok::kw___builtin_FUNCTION: |
2523 | case tok::kw___builtin_FUNCSIG: |
2524 | case tok::kw___builtin_LINE: |
2525 | case tok::kw___builtin_source_location: { |
2526 | // Attempt to consume the r-paren. |
2527 | if (Tok.isNot(K: tok::r_paren)) { |
2528 | Diag(Tok, DiagID: diag::err_expected) << tok::r_paren; |
2529 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2530 | return ExprError(); |
2531 | } |
2532 | SourceLocIdentKind Kind = [&] { |
2533 | switch (T) { |
2534 | case tok::kw___builtin_FILE: |
2535 | return SourceLocIdentKind::File; |
2536 | case tok::kw___builtin_FILE_NAME: |
2537 | return SourceLocIdentKind::FileName; |
2538 | case tok::kw___builtin_FUNCTION: |
2539 | return SourceLocIdentKind::Function; |
2540 | case tok::kw___builtin_FUNCSIG: |
2541 | return SourceLocIdentKind::FuncSig; |
2542 | case tok::kw___builtin_LINE: |
2543 | return SourceLocIdentKind::Line; |
2544 | case tok::kw___builtin_COLUMN: |
2545 | return SourceLocIdentKind::Column; |
2546 | case tok::kw___builtin_source_location: |
2547 | return SourceLocIdentKind::SourceLocStruct; |
2548 | default: |
2549 | llvm_unreachable("invalid keyword" ); |
2550 | } |
2551 | }(); |
2552 | Res = Actions.ActOnSourceLocExpr(Kind, BuiltinLoc: StartLoc, RPLoc: ConsumeParen()); |
2553 | break; |
2554 | } |
2555 | } |
2556 | |
2557 | if (Res.isInvalid()) |
2558 | return ExprError(); |
2559 | |
2560 | // These can be followed by postfix-expr pieces because they are |
2561 | // primary-expressions. |
2562 | return ParsePostfixExpressionSuffix(LHS: Res.get()); |
2563 | } |
2564 | |
2565 | bool Parser::tryParseOpenMPArrayShapingCastPart() { |
2566 | assert(Tok.is(tok::l_square) && "Expected open bracket" ); |
2567 | bool ErrorFound = true; |
2568 | TentativeParsingAction TPA(*this); |
2569 | do { |
2570 | if (Tok.isNot(K: tok::l_square)) |
2571 | break; |
2572 | // Consume '[' |
2573 | ConsumeBracket(); |
2574 | // Skip inner expression. |
2575 | while (!SkipUntil(T1: tok::r_square, T2: tok::annot_pragma_openmp_end, |
2576 | Flags: StopAtSemi | StopBeforeMatch)) |
2577 | ; |
2578 | if (Tok.isNot(K: tok::r_square)) |
2579 | break; |
2580 | // Consume ']' |
2581 | ConsumeBracket(); |
2582 | // Found ')' - done. |
2583 | if (Tok.is(K: tok::r_paren)) { |
2584 | ErrorFound = false; |
2585 | break; |
2586 | } |
2587 | } while (Tok.isNot(K: tok::annot_pragma_openmp_end)); |
2588 | TPA.Revert(); |
2589 | return !ErrorFound; |
2590 | } |
2591 | |
2592 | ExprResult |
2593 | Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, |
2594 | bool isTypeCast, ParsedType &CastTy, |
2595 | SourceLocation &RParenLoc) { |
2596 | assert(Tok.is(tok::l_paren) && "Not a paren expr!" ); |
2597 | ColonProtectionRAIIObject ColonProtection(*this, false); |
2598 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2599 | if (T.consumeOpen()) |
2600 | return ExprError(); |
2601 | SourceLocation OpenLoc = T.getOpenLocation(); |
2602 | |
2603 | PreferredType.enterParenExpr(Tok: Tok.getLocation(), LParLoc: OpenLoc); |
2604 | |
2605 | ExprResult Result(true); |
2606 | bool isAmbiguousTypeId; |
2607 | CastTy = nullptr; |
2608 | |
2609 | if (Tok.is(K: tok::code_completion)) { |
2610 | cutOffParsing(); |
2611 | Actions.CodeCompletion().CodeCompleteExpression( |
2612 | S: getCurScope(), PreferredType: PreferredType.get(Tok: Tok.getLocation()), |
2613 | /*IsParenthesized=*/ExprType >= ParenParseOption::CompoundLiteral); |
2614 | return ExprError(); |
2615 | } |
2616 | |
2617 | // Diagnose use of bridge casts in non-arc mode. |
2618 | bool BridgeCast = (getLangOpts().ObjC && |
2619 | Tok.isOneOf(Ks: tok::kw___bridge, |
2620 | Ks: tok::kw___bridge_transfer, |
2621 | Ks: tok::kw___bridge_retained, |
2622 | Ks: tok::kw___bridge_retain)); |
2623 | if (BridgeCast && !getLangOpts().ObjCAutoRefCount) { |
2624 | if (!TryConsumeToken(Expected: tok::kw___bridge)) { |
2625 | StringRef BridgeCastName = Tok.getName(); |
2626 | SourceLocation BridgeKeywordLoc = ConsumeToken(); |
2627 | if (!PP.getSourceManager().isInSystemHeader(Loc: BridgeKeywordLoc)) |
2628 | Diag(Loc: BridgeKeywordLoc, DiagID: diag::warn_arc_bridge_cast_nonarc) |
2629 | << BridgeCastName |
2630 | << FixItHint::CreateReplacement(RemoveRange: BridgeKeywordLoc, Code: "" ); |
2631 | } |
2632 | BridgeCast = false; |
2633 | } |
2634 | |
2635 | // None of these cases should fall through with an invalid Result |
2636 | // unless they've already reported an error. |
2637 | if (ExprType >= ParenParseOption::CompoundStmt && Tok.is(K: tok::l_brace)) { |
2638 | Diag(Tok, DiagID: OpenLoc.isMacroID() ? diag::ext_gnu_statement_expr_macro |
2639 | : diag::ext_gnu_statement_expr); |
2640 | |
2641 | checkCompoundToken(FirstTokLoc: OpenLoc, FirstTokKind: tok::l_paren, Op: CompoundToken::StmtExprBegin); |
2642 | |
2643 | if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) { |
2644 | Result = ExprError(Diag(Loc: OpenLoc, DiagID: diag::err_stmtexpr_file_scope)); |
2645 | } else { |
2646 | // Find the nearest non-record decl context. Variables declared in a |
2647 | // statement expression behave as if they were declared in the enclosing |
2648 | // function, block, or other code construct. |
2649 | DeclContext *CodeDC = Actions.CurContext; |
2650 | while (CodeDC->isRecord() || isa<EnumDecl>(Val: CodeDC)) { |
2651 | CodeDC = CodeDC->getParent(); |
2652 | assert(CodeDC && !CodeDC->isFileContext() && |
2653 | "statement expr not in code context" ); |
2654 | } |
2655 | Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false); |
2656 | |
2657 | Actions.ActOnStartStmtExpr(); |
2658 | |
2659 | StmtResult Stmt(ParseCompoundStatement(isStmtExpr: true)); |
2660 | ExprType = ParenParseOption::CompoundStmt; |
2661 | |
2662 | // If the substmt parsed correctly, build the AST node. |
2663 | if (!Stmt.isInvalid()) { |
2664 | Result = Actions.ActOnStmtExpr(S: getCurScope(), LPLoc: OpenLoc, SubStmt: Stmt.get(), |
2665 | RPLoc: Tok.getLocation()); |
2666 | } else { |
2667 | Actions.ActOnStmtExprError(); |
2668 | } |
2669 | } |
2670 | } else if (ExprType >= ParenParseOption::CompoundLiteral && BridgeCast) { |
2671 | tok::TokenKind tokenKind = Tok.getKind(); |
2672 | SourceLocation BridgeKeywordLoc = ConsumeToken(); |
2673 | |
2674 | // Parse an Objective-C ARC ownership cast expression. |
2675 | ObjCBridgeCastKind Kind; |
2676 | if (tokenKind == tok::kw___bridge) |
2677 | Kind = OBC_Bridge; |
2678 | else if (tokenKind == tok::kw___bridge_transfer) |
2679 | Kind = OBC_BridgeTransfer; |
2680 | else if (tokenKind == tok::kw___bridge_retained) |
2681 | Kind = OBC_BridgeRetained; |
2682 | else { |
2683 | // As a hopefully temporary workaround, allow __bridge_retain as |
2684 | // a synonym for __bridge_retained, but only in system headers. |
2685 | assert(tokenKind == tok::kw___bridge_retain); |
2686 | Kind = OBC_BridgeRetained; |
2687 | if (!PP.getSourceManager().isInSystemHeader(Loc: BridgeKeywordLoc)) |
2688 | Diag(Loc: BridgeKeywordLoc, DiagID: diag::err_arc_bridge_retain) |
2689 | << FixItHint::CreateReplacement(RemoveRange: BridgeKeywordLoc, |
2690 | Code: "__bridge_retained" ); |
2691 | } |
2692 | |
2693 | TypeResult Ty = ParseTypeName(); |
2694 | T.consumeClose(); |
2695 | ColonProtection.restore(); |
2696 | RParenLoc = T.getCloseLocation(); |
2697 | |
2698 | PreferredType.enterTypeCast(Tok: Tok.getLocation(), CastType: Ty.get().get()); |
2699 | ExprResult SubExpr = ParseCastExpression(ParseKind: CastParseKind::AnyCastExpr); |
2700 | |
2701 | if (Ty.isInvalid() || SubExpr.isInvalid()) |
2702 | return ExprError(); |
2703 | |
2704 | return Actions.ObjC().ActOnObjCBridgedCast(S: getCurScope(), LParenLoc: OpenLoc, Kind, |
2705 | BridgeKeywordLoc, Type: Ty.get(), |
2706 | RParenLoc, SubExpr: SubExpr.get()); |
2707 | } else if (ExprType >= ParenParseOption::CompoundLiteral && |
2708 | isTypeIdInParens(isAmbiguous&: isAmbiguousTypeId)) { |
2709 | |
2710 | // Otherwise, this is a compound literal expression or cast expression. |
2711 | |
2712 | // In C++, if the type-id is ambiguous we disambiguate based on context. |
2713 | // If stopIfCastExpr is true the context is a typeof/sizeof/alignof |
2714 | // in which case we should treat it as type-id. |
2715 | // if stopIfCastExpr is false, we need to determine the context past the |
2716 | // parens, so we defer to ParseCXXAmbiguousParenExpression for that. |
2717 | if (isAmbiguousTypeId && !stopIfCastExpr) { |
2718 | ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, Tracker&: T, |
2719 | ColonProt&: ColonProtection); |
2720 | RParenLoc = T.getCloseLocation(); |
2721 | return res; |
2722 | } |
2723 | |
2724 | // Parse the type declarator. |
2725 | DeclSpec DS(AttrFactory); |
2726 | ParseSpecifierQualifierList(DS); |
2727 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
2728 | DeclaratorContext::TypeName); |
2729 | ParseDeclarator(D&: DeclaratorInfo); |
2730 | |
2731 | // If our type is followed by an identifier and either ':' or ']', then |
2732 | // this is probably an Objective-C message send where the leading '[' is |
2733 | // missing. Recover as if that were the case. |
2734 | if (!DeclaratorInfo.isInvalidType() && Tok.is(K: tok::identifier) && |
2735 | !InMessageExpression && getLangOpts().ObjC && |
2736 | (NextToken().is(K: tok::colon) || NextToken().is(K: tok::r_square))) { |
2737 | TypeResult Ty; |
2738 | { |
2739 | InMessageExpressionRAIIObject InMessage(*this, false); |
2740 | Ty = Actions.ActOnTypeName(D&: DeclaratorInfo); |
2741 | } |
2742 | Result = ParseObjCMessageExpressionBody(LBracloc: SourceLocation(), |
2743 | SuperLoc: SourceLocation(), |
2744 | ReceiverType: Ty.get(), ReceiverExpr: nullptr); |
2745 | } else { |
2746 | // Match the ')'. |
2747 | T.consumeClose(); |
2748 | ColonProtection.restore(); |
2749 | RParenLoc = T.getCloseLocation(); |
2750 | if (Tok.is(K: tok::l_brace)) { |
2751 | ExprType = ParenParseOption::CompoundLiteral; |
2752 | TypeResult Ty; |
2753 | { |
2754 | InMessageExpressionRAIIObject InMessage(*this, false); |
2755 | Ty = Actions.ActOnTypeName(D&: DeclaratorInfo); |
2756 | } |
2757 | return ParseCompoundLiteralExpression(Ty: Ty.get(), LParenLoc: OpenLoc, RParenLoc); |
2758 | } |
2759 | |
2760 | if (Tok.is(K: tok::l_paren)) { |
2761 | // This could be OpenCL vector Literals |
2762 | if (getLangOpts().OpenCL) |
2763 | { |
2764 | TypeResult Ty; |
2765 | { |
2766 | InMessageExpressionRAIIObject InMessage(*this, false); |
2767 | Ty = Actions.ActOnTypeName(D&: DeclaratorInfo); |
2768 | } |
2769 | if(Ty.isInvalid()) |
2770 | { |
2771 | return ExprError(); |
2772 | } |
2773 | QualType QT = Ty.get().get().getCanonicalType(); |
2774 | if (QT->isVectorType()) |
2775 | { |
2776 | // We parsed '(' vector-type-name ')' followed by '(' |
2777 | |
2778 | // Parse the cast-expression that follows it next. |
2779 | // isVectorLiteral = true will make sure we don't parse any |
2780 | // Postfix expression yet |
2781 | Result = ParseCastExpression( |
2782 | /*isUnaryExpression=*/ParseKind: CastParseKind::AnyCastExpr, |
2783 | /*isAddressOfOperand=*/false, |
2784 | /*isTypeCast=*/TypeCastState::IsTypeCast, |
2785 | /*isVectorLiteral=*/true); |
2786 | |
2787 | if (!Result.isInvalid()) { |
2788 | Result = Actions.ActOnCastExpr(S: getCurScope(), LParenLoc: OpenLoc, |
2789 | D&: DeclaratorInfo, Ty&: CastTy, |
2790 | RParenLoc, CastExpr: Result.get()); |
2791 | } |
2792 | |
2793 | // After we performed the cast we can check for postfix-expr pieces. |
2794 | if (!Result.isInvalid()) { |
2795 | Result = ParsePostfixExpressionSuffix(LHS: Result); |
2796 | } |
2797 | |
2798 | return Result; |
2799 | } |
2800 | } |
2801 | } |
2802 | |
2803 | if (ExprType == ParenParseOption::CastExpr) { |
2804 | // We parsed '(' type-name ')' and the thing after it wasn't a '{'. |
2805 | |
2806 | if (DeclaratorInfo.isInvalidType()) |
2807 | return ExprError(); |
2808 | |
2809 | // Note that this doesn't parse the subsequent cast-expression, it just |
2810 | // returns the parsed type to the callee. |
2811 | if (stopIfCastExpr) { |
2812 | TypeResult Ty; |
2813 | { |
2814 | InMessageExpressionRAIIObject InMessage(*this, false); |
2815 | Ty = Actions.ActOnTypeName(D&: DeclaratorInfo); |
2816 | } |
2817 | CastTy = Ty.get(); |
2818 | return ExprResult(); |
2819 | } |
2820 | |
2821 | // Reject the cast of super idiom in ObjC. |
2822 | if (Tok.is(K: tok::identifier) && getLangOpts().ObjC && |
2823 | Tok.getIdentifierInfo() == Ident_super && |
2824 | getCurScope()->isInObjcMethodScope() && |
2825 | GetLookAheadToken(N: 1).isNot(K: tok::period)) { |
2826 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_illegal_super_cast) |
2827 | << SourceRange(OpenLoc, RParenLoc); |
2828 | return ExprError(); |
2829 | } |
2830 | |
2831 | PreferredType.enterTypeCast(Tok: Tok.getLocation(), CastType: CastTy.get()); |
2832 | // Parse the cast-expression that follows it next. |
2833 | // TODO: For cast expression with CastTy. |
2834 | Result = ParseCastExpression( |
2835 | /*isUnaryExpression=*/ParseKind: CastParseKind::AnyCastExpr, |
2836 | /*isAddressOfOperand=*/false, |
2837 | /*isTypeCast=*/TypeCastState::IsTypeCast); |
2838 | if (!Result.isInvalid()) { |
2839 | Result = Actions.ActOnCastExpr(S: getCurScope(), LParenLoc: OpenLoc, |
2840 | D&: DeclaratorInfo, Ty&: CastTy, |
2841 | RParenLoc, CastExpr: Result.get()); |
2842 | } |
2843 | return Result; |
2844 | } |
2845 | |
2846 | Diag(Tok, DiagID: diag::err_expected_lbrace_in_compound_literal); |
2847 | return ExprError(); |
2848 | } |
2849 | } else if (ExprType >= ParenParseOption::FoldExpr && Tok.is(K: tok::ellipsis) && |
2850 | isFoldOperator(Kind: NextToken().getKind())) { |
2851 | ExprType = ParenParseOption::FoldExpr; |
2852 | return ParseFoldExpression(LHS: ExprResult(), T); |
2853 | } else if (isTypeCast) { |
2854 | // Parse the expression-list. |
2855 | InMessageExpressionRAIIObject InMessage(*this, false); |
2856 | ExprVector ArgExprs; |
2857 | |
2858 | if (!ParseSimpleExpressionList(Exprs&: ArgExprs)) { |
2859 | // FIXME: If we ever support comma expressions as operands to |
2860 | // fold-expressions, we'll need to allow multiple ArgExprs here. |
2861 | if (ExprType >= ParenParseOption::FoldExpr && ArgExprs.size() == 1 && |
2862 | isFoldOperator(Kind: Tok.getKind()) && NextToken().is(K: tok::ellipsis)) { |
2863 | ExprType = ParenParseOption::FoldExpr; |
2864 | return ParseFoldExpression(LHS: ArgExprs[0], T); |
2865 | } |
2866 | |
2867 | ExprType = ParenParseOption::SimpleExpr; |
2868 | Result = Actions.ActOnParenListExpr(L: OpenLoc, R: Tok.getLocation(), |
2869 | Val: ArgExprs); |
2870 | } |
2871 | } else if (getLangOpts().OpenMP >= 50 && OpenMPDirectiveParsing && |
2872 | ExprType == ParenParseOption::CastExpr && Tok.is(K: tok::l_square) && |
2873 | tryParseOpenMPArrayShapingCastPart()) { |
2874 | bool ErrorFound = false; |
2875 | SmallVector<Expr *, 4> OMPDimensions; |
2876 | SmallVector<SourceRange, 4> OMPBracketsRanges; |
2877 | do { |
2878 | BalancedDelimiterTracker TS(*this, tok::l_square); |
2879 | TS.consumeOpen(); |
2880 | ExprResult NumElements = ParseExpression(); |
2881 | if (!NumElements.isUsable()) { |
2882 | ErrorFound = true; |
2883 | while (!SkipUntil(T1: tok::r_square, T2: tok::r_paren, |
2884 | Flags: StopAtSemi | StopBeforeMatch)) |
2885 | ; |
2886 | } |
2887 | TS.consumeClose(); |
2888 | OMPDimensions.push_back(Elt: NumElements.get()); |
2889 | OMPBracketsRanges.push_back(Elt: TS.getRange()); |
2890 | } while (Tok.isNot(K: tok::r_paren)); |
2891 | // Match the ')'. |
2892 | T.consumeClose(); |
2893 | RParenLoc = T.getCloseLocation(); |
2894 | Result = ParseAssignmentExpression(); |
2895 | if (ErrorFound) { |
2896 | Result = ExprError(); |
2897 | } else if (!Result.isInvalid()) { |
2898 | Result = Actions.OpenMP().ActOnOMPArrayShapingExpr( |
2899 | Base: Result.get(), LParenLoc: OpenLoc, RParenLoc, Dims: OMPDimensions, Brackets: OMPBracketsRanges); |
2900 | } |
2901 | return Result; |
2902 | } else { |
2903 | InMessageExpressionRAIIObject InMessage(*this, false); |
2904 | |
2905 | Result = ParseExpression(isTypeCast: TypeCastState::MaybeTypeCast); |
2906 | if (ExprType >= ParenParseOption::FoldExpr && |
2907 | isFoldOperator(Kind: Tok.getKind()) && NextToken().is(K: tok::ellipsis)) { |
2908 | ExprType = ParenParseOption::FoldExpr; |
2909 | return ParseFoldExpression(LHS: Result, T); |
2910 | } |
2911 | ExprType = ParenParseOption::SimpleExpr; |
2912 | |
2913 | // Don't build a paren expression unless we actually match a ')'. |
2914 | if (!Result.isInvalid() && Tok.is(K: tok::r_paren)) |
2915 | Result = |
2916 | Actions.ActOnParenExpr(L: OpenLoc, R: Tok.getLocation(), E: Result.get()); |
2917 | } |
2918 | |
2919 | // Match the ')'. |
2920 | if (Result.isInvalid()) { |
2921 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2922 | return ExprError(); |
2923 | } |
2924 | |
2925 | T.consumeClose(); |
2926 | RParenLoc = T.getCloseLocation(); |
2927 | return Result; |
2928 | } |
2929 | |
2930 | ExprResult |
2931 | Parser::ParseCompoundLiteralExpression(ParsedType Ty, |
2932 | SourceLocation LParenLoc, |
2933 | SourceLocation RParenLoc) { |
2934 | assert(Tok.is(tok::l_brace) && "Not a compound literal!" ); |
2935 | if (!getLangOpts().C99) // Compound literals don't exist in C90. |
2936 | Diag(Loc: LParenLoc, DiagID: diag::ext_c99_compound_literal); |
2937 | PreferredType.enterTypeCast(Tok: Tok.getLocation(), CastType: Ty.get()); |
2938 | ExprResult Result = ParseInitializer(); |
2939 | if (!Result.isInvalid() && Ty) |
2940 | return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, InitExpr: Result.get()); |
2941 | return Result; |
2942 | } |
2943 | |
2944 | ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) { |
2945 | return ParseStringLiteralExpression(AllowUserDefinedLiteral, |
2946 | /*Unevaluated=*/false); |
2947 | } |
2948 | |
2949 | ExprResult Parser::ParseUnevaluatedStringLiteralExpression() { |
2950 | return ParseStringLiteralExpression(/*AllowUserDefinedLiteral=*/false, |
2951 | /*Unevaluated=*/true); |
2952 | } |
2953 | |
2954 | ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral, |
2955 | bool Unevaluated) { |
2956 | assert(tokenIsLikeStringLiteral(Tok, getLangOpts()) && |
2957 | "Not a string-literal-like token!" ); |
2958 | |
2959 | // String concatenation. |
2960 | // Note: some keywords like __FUNCTION__ are not considered to be strings |
2961 | // for concatenation purposes, unless Microsoft extensions are enabled. |
2962 | SmallVector<Token, 4> StringToks; |
2963 | |
2964 | do { |
2965 | StringToks.push_back(Elt: Tok); |
2966 | ConsumeAnyToken(); |
2967 | } while (tokenIsLikeStringLiteral(Tok, LO: getLangOpts())); |
2968 | |
2969 | if (Unevaluated) { |
2970 | assert(!AllowUserDefinedLiteral && "UDL are always evaluated" ); |
2971 | return Actions.ActOnUnevaluatedStringLiteral(StringToks); |
2972 | } |
2973 | |
2974 | // Pass the set of string tokens, ready for concatenation, to the actions. |
2975 | return Actions.ActOnStringLiteral(StringToks, |
2976 | UDLScope: AllowUserDefinedLiteral ? getCurScope() |
2977 | : nullptr); |
2978 | } |
2979 | |
2980 | ExprResult Parser::ParseGenericSelectionExpression() { |
2981 | assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected" ); |
2982 | |
2983 | diagnoseUseOfC11Keyword(Tok); |
2984 | |
2985 | SourceLocation KeyLoc = ConsumeToken(); |
2986 | BalancedDelimiterTracker T(*this, tok::l_paren); |
2987 | if (T.expectAndConsume()) |
2988 | return ExprError(); |
2989 | |
2990 | // We either have a controlling expression or we have a controlling type, and |
2991 | // we need to figure out which it is. |
2992 | TypeResult ControllingType; |
2993 | ExprResult ControllingExpr; |
2994 | if (isTypeIdForGenericSelection()) { |
2995 | ControllingType = ParseTypeName(); |
2996 | if (ControllingType.isInvalid()) { |
2997 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
2998 | return ExprError(); |
2999 | } |
3000 | const auto *LIT = cast<LocInfoType>(Val: ControllingType.get().get()); |
3001 | SourceLocation Loc = LIT->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); |
3002 | Diag(Loc, DiagID: getLangOpts().C2y ? diag::warn_c2y_compat_generic_with_type_arg |
3003 | : diag::ext_c2y_generic_with_type_arg); |
3004 | } else { |
3005 | // C11 6.5.1.1p3 "The controlling expression of a generic selection is |
3006 | // not evaluated." |
3007 | EnterExpressionEvaluationContext Unevaluated( |
3008 | Actions, Sema::ExpressionEvaluationContext::Unevaluated); |
3009 | ControllingExpr = ParseAssignmentExpression(); |
3010 | if (ControllingExpr.isInvalid()) { |
3011 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3012 | return ExprError(); |
3013 | } |
3014 | } |
3015 | |
3016 | if (ExpectAndConsume(ExpectedTok: tok::comma)) { |
3017 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3018 | return ExprError(); |
3019 | } |
3020 | |
3021 | SourceLocation DefaultLoc; |
3022 | SmallVector<ParsedType, 12> Types; |
3023 | ExprVector Exprs; |
3024 | do { |
3025 | ParsedType Ty; |
3026 | if (Tok.is(K: tok::kw_default)) { |
3027 | // C11 6.5.1.1p2 "A generic selection shall have no more than one default |
3028 | // generic association." |
3029 | if (!DefaultLoc.isInvalid()) { |
3030 | Diag(Tok, DiagID: diag::err_duplicate_default_assoc); |
3031 | Diag(Loc: DefaultLoc, DiagID: diag::note_previous_default_assoc); |
3032 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3033 | return ExprError(); |
3034 | } |
3035 | DefaultLoc = ConsumeToken(); |
3036 | Ty = nullptr; |
3037 | } else { |
3038 | ColonProtectionRAIIObject X(*this); |
3039 | TypeResult TR = ParseTypeName(Range: nullptr, Context: DeclaratorContext::Association); |
3040 | if (TR.isInvalid()) { |
3041 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3042 | return ExprError(); |
3043 | } |
3044 | Ty = TR.get(); |
3045 | } |
3046 | Types.push_back(Elt: Ty); |
3047 | |
3048 | if (ExpectAndConsume(ExpectedTok: tok::colon)) { |
3049 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3050 | return ExprError(); |
3051 | } |
3052 | |
3053 | // FIXME: These expressions should be parsed in a potentially potentially |
3054 | // evaluated context. |
3055 | ExprResult ER = ParseAssignmentExpression(); |
3056 | if (ER.isInvalid()) { |
3057 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3058 | return ExprError(); |
3059 | } |
3060 | Exprs.push_back(Elt: ER.get()); |
3061 | } while (TryConsumeToken(Expected: tok::comma)); |
3062 | |
3063 | T.consumeClose(); |
3064 | if (T.getCloseLocation().isInvalid()) |
3065 | return ExprError(); |
3066 | |
3067 | void *ExprOrTy = ControllingExpr.isUsable() |
3068 | ? ControllingExpr.get() |
3069 | : ControllingType.get().getAsOpaquePtr(); |
3070 | |
3071 | return Actions.ActOnGenericSelectionExpr( |
3072 | KeyLoc, DefaultLoc, RParenLoc: T.getCloseLocation(), PredicateIsExpr: ControllingExpr.isUsable(), |
3073 | ControllingExprOrType: ExprOrTy, ArgTypes: Types, ArgExprs: Exprs); |
3074 | } |
3075 | |
3076 | ExprResult Parser::ParseFoldExpression(ExprResult LHS, |
3077 | BalancedDelimiterTracker &T) { |
3078 | if (LHS.isInvalid()) { |
3079 | T.skipToEnd(); |
3080 | return true; |
3081 | } |
3082 | |
3083 | tok::TokenKind Kind = tok::unknown; |
3084 | SourceLocation FirstOpLoc; |
3085 | if (LHS.isUsable()) { |
3086 | Kind = Tok.getKind(); |
3087 | assert(isFoldOperator(Kind) && "missing fold-operator" ); |
3088 | FirstOpLoc = ConsumeToken(); |
3089 | } |
3090 | |
3091 | assert(Tok.is(tok::ellipsis) && "not a fold-expression" ); |
3092 | SourceLocation EllipsisLoc = ConsumeToken(); |
3093 | |
3094 | ExprResult RHS; |
3095 | if (Tok.isNot(K: tok::r_paren)) { |
3096 | if (!isFoldOperator(Kind: Tok.getKind())) |
3097 | return Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_fold_operator); |
3098 | |
3099 | if (Kind != tok::unknown && Tok.getKind() != Kind) |
3100 | Diag(Loc: Tok.getLocation(), DiagID: diag::err_fold_operator_mismatch) |
3101 | << SourceRange(FirstOpLoc); |
3102 | Kind = Tok.getKind(); |
3103 | ConsumeToken(); |
3104 | |
3105 | RHS = ParseExpression(); |
3106 | if (RHS.isInvalid()) { |
3107 | T.skipToEnd(); |
3108 | return true; |
3109 | } |
3110 | } |
3111 | |
3112 | Diag(Loc: EllipsisLoc, DiagID: getLangOpts().CPlusPlus17 |
3113 | ? diag::warn_cxx14_compat_fold_expression |
3114 | : diag::ext_fold_expression); |
3115 | |
3116 | T.consumeClose(); |
3117 | return Actions.ActOnCXXFoldExpr(S: getCurScope(), LParenLoc: T.getOpenLocation(), LHS: LHS.get(), |
3118 | Operator: Kind, EllipsisLoc, RHS: RHS.get(), |
3119 | RParenLoc: T.getCloseLocation()); |
3120 | } |
3121 | |
3122 | void Parser::injectEmbedTokens() { |
3123 | EmbedAnnotationData *Data = |
3124 | reinterpret_cast<EmbedAnnotationData *>(Tok.getAnnotationValue()); |
3125 | MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>( |
3126 | Num: Data->BinaryData.size() * 2 - 1), |
3127 | Data->BinaryData.size() * 2 - 1); |
3128 | unsigned I = 0; |
3129 | for (auto &Byte : Data->BinaryData) { |
3130 | Toks[I].startToken(); |
3131 | Toks[I].setKind(tok::binary_data); |
3132 | Toks[I].setLocation(Tok.getLocation()); |
3133 | Toks[I].setLength(1); |
3134 | Toks[I].setLiteralData(&Byte); |
3135 | if (I != ((Data->BinaryData.size() - 1) * 2)) { |
3136 | Toks[I + 1].startToken(); |
3137 | Toks[I + 1].setKind(tok::comma); |
3138 | Toks[I + 1].setLocation(Tok.getLocation()); |
3139 | } |
3140 | I += 2; |
3141 | } |
3142 | PP.EnterTokenStream(Toks: std::move(Toks), /*DisableMacroExpansion=*/true, |
3143 | /*IsReinject=*/true); |
3144 | ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); |
3145 | } |
3146 | |
3147 | bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, |
3148 | llvm::function_ref<void()> ExpressionStarts, |
3149 | bool FailImmediatelyOnInvalidExpr) { |
3150 | bool SawError = false; |
3151 | while (true) { |
3152 | if (ExpressionStarts) |
3153 | ExpressionStarts(); |
3154 | |
3155 | ExprResult Expr; |
3156 | if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace)) { |
3157 | Diag(Tok, DiagID: diag::warn_cxx98_compat_generalized_initializer_lists); |
3158 | Expr = ParseBraceInitializer(); |
3159 | } else |
3160 | Expr = ParseAssignmentExpression(); |
3161 | |
3162 | if (Tok.is(K: tok::ellipsis)) |
3163 | Expr = Actions.ActOnPackExpansion(Pattern: Expr.get(), EllipsisLoc: ConsumeToken()); |
3164 | else if (Tok.is(K: tok::code_completion)) { |
3165 | // There's nothing to suggest in here as we parsed a full expression. |
3166 | // Instead fail and propagate the error since caller might have something |
3167 | // the suggest, e.g. signature help in function call. Note that this is |
3168 | // performed before pushing the \p Expr, so that signature help can report |
3169 | // current argument correctly. |
3170 | SawError = true; |
3171 | cutOffParsing(); |
3172 | break; |
3173 | } |
3174 | if (Expr.isInvalid()) { |
3175 | SawError = true; |
3176 | if (FailImmediatelyOnInvalidExpr) |
3177 | break; |
3178 | SkipUntil(T1: tok::comma, T2: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch); |
3179 | } else { |
3180 | Exprs.push_back(Elt: Expr.get()); |
3181 | } |
3182 | |
3183 | if (Tok.isNot(K: tok::comma)) |
3184 | break; |
3185 | // Move to the next argument, remember where the comma was. |
3186 | Token Comma = Tok; |
3187 | ConsumeToken(); |
3188 | checkPotentialAngleBracketDelimiter(OpToken: Comma); |
3189 | } |
3190 | return SawError; |
3191 | } |
3192 | |
3193 | bool Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs) { |
3194 | while (true) { |
3195 | ExprResult Expr = ParseAssignmentExpression(); |
3196 | if (Expr.isInvalid()) |
3197 | return true; |
3198 | |
3199 | Exprs.push_back(Elt: Expr.get()); |
3200 | |
3201 | // We might be parsing the LHS of a fold-expression. If we reached the fold |
3202 | // operator, stop. |
3203 | if (Tok.isNot(K: tok::comma) || NextToken().is(K: tok::ellipsis)) |
3204 | return false; |
3205 | |
3206 | // Move to the next argument, remember where the comma was. |
3207 | Token Comma = Tok; |
3208 | ConsumeToken(); |
3209 | checkPotentialAngleBracketDelimiter(OpToken: Comma); |
3210 | } |
3211 | } |
3212 | |
3213 | void Parser::ParseBlockId(SourceLocation CaretLoc) { |
3214 | if (Tok.is(K: tok::code_completion)) { |
3215 | cutOffParsing(); |
3216 | Actions.CodeCompletion().CodeCompleteOrdinaryName( |
3217 | S: getCurScope(), CompletionContext: SemaCodeCompletion::PCC_Type); |
3218 | return; |
3219 | } |
3220 | |
3221 | // Parse the specifier-qualifier-list piece. |
3222 | DeclSpec DS(AttrFactory); |
3223 | ParseSpecifierQualifierList(DS); |
3224 | |
3225 | // Parse the block-declarator. |
3226 | Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), |
3227 | DeclaratorContext::BlockLiteral); |
3228 | DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); |
3229 | ParseDeclarator(D&: DeclaratorInfo); |
3230 | |
3231 | MaybeParseGNUAttributes(D&: DeclaratorInfo); |
3232 | |
3233 | // Inform sema that we are starting a block. |
3234 | Actions.ActOnBlockArguments(CaretLoc, ParamInfo&: DeclaratorInfo, CurScope: getCurScope()); |
3235 | } |
3236 | |
3237 | ExprResult Parser::ParseBlockLiteralExpression() { |
3238 | assert(Tok.is(tok::caret) && "block literal starts with ^" ); |
3239 | SourceLocation CaretLoc = ConsumeToken(); |
3240 | |
3241 | PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, |
3242 | "block literal parsing" ); |
3243 | |
3244 | // Enter a scope to hold everything within the block. This includes the |
3245 | // argument decls, decls within the compound expression, etc. This also |
3246 | // allows determining whether a variable reference inside the block is |
3247 | // within or outside of the block. |
3248 | ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | |
3249 | Scope::CompoundStmtScope | Scope::DeclScope); |
3250 | |
3251 | // Inform sema that we are starting a block. |
3252 | Actions.ActOnBlockStart(CaretLoc, CurScope: getCurScope()); |
3253 | |
3254 | // Parse the return type if present. |
3255 | DeclSpec DS(AttrFactory); |
3256 | Declarator ParamInfo(DS, ParsedAttributesView::none(), |
3257 | DeclaratorContext::BlockLiteral); |
3258 | ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); |
3259 | // FIXME: Since the return type isn't actually parsed, it can't be used to |
3260 | // fill ParamInfo with an initial valid range, so do it manually. |
3261 | ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); |
3262 | |
3263 | // If this block has arguments, parse them. There is no ambiguity here with |
3264 | // the expression case, because the expression case requires a parameter list. |
3265 | if (Tok.is(K: tok::l_paren)) { |
3266 | ParseParenDeclarator(D&: ParamInfo); |
3267 | // Parse the pieces after the identifier as if we had "int(...)". |
3268 | // SetIdentifier sets the source range end, but in this case we're past |
3269 | // that location. |
3270 | SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); |
3271 | ParamInfo.SetIdentifier(Id: nullptr, IdLoc: CaretLoc); |
3272 | ParamInfo.SetRangeEnd(Tmp); |
3273 | if (ParamInfo.isInvalidType()) { |
3274 | // If there was an error parsing the arguments, they may have |
3275 | // tried to use ^(x+y) which requires an argument list. Just |
3276 | // skip the whole block literal. |
3277 | Actions.ActOnBlockError(CaretLoc, CurScope: getCurScope()); |
3278 | return ExprError(); |
3279 | } |
3280 | |
3281 | MaybeParseGNUAttributes(D&: ParamInfo); |
3282 | |
3283 | // Inform sema that we are starting a block. |
3284 | Actions.ActOnBlockArguments(CaretLoc, ParamInfo, CurScope: getCurScope()); |
3285 | } else if (!Tok.is(K: tok::l_brace)) { |
3286 | ParseBlockId(CaretLoc); |
3287 | } else { |
3288 | // Otherwise, pretend we saw (void). |
3289 | SourceLocation NoLoc; |
3290 | ParamInfo.AddTypeInfo( |
3291 | TI: DeclaratorChunk::getFunction(/*HasProto=*/true, |
3292 | /*IsAmbiguous=*/false, |
3293 | /*RParenLoc=*/LParenLoc: NoLoc, |
3294 | /*ArgInfo=*/Params: nullptr, |
3295 | /*NumParams=*/0, |
3296 | /*EllipsisLoc=*/NoLoc, |
3297 | /*RParenLoc=*/NoLoc, |
3298 | /*RefQualifierIsLvalueRef=*/true, |
3299 | /*RefQualifierLoc=*/NoLoc, |
3300 | /*MutableLoc=*/NoLoc, ESpecType: EST_None, |
3301 | /*ESpecRange=*/SourceRange(), |
3302 | /*Exceptions=*/nullptr, |
3303 | /*ExceptionRanges=*/nullptr, |
3304 | /*NumExceptions=*/0, |
3305 | /*NoexceptExpr=*/nullptr, |
3306 | /*ExceptionSpecTokens=*/nullptr, |
3307 | /*DeclsInPrototype=*/{}, LocalRangeBegin: CaretLoc, |
3308 | LocalRangeEnd: CaretLoc, TheDeclarator&: ParamInfo), |
3309 | EndLoc: CaretLoc); |
3310 | |
3311 | MaybeParseGNUAttributes(D&: ParamInfo); |
3312 | |
3313 | // Inform sema that we are starting a block. |
3314 | Actions.ActOnBlockArguments(CaretLoc, ParamInfo, CurScope: getCurScope()); |
3315 | } |
3316 | |
3317 | |
3318 | ExprResult Result(true); |
3319 | if (!Tok.is(K: tok::l_brace)) { |
3320 | // Saw something like: ^expr |
3321 | Diag(Tok, DiagID: diag::err_expected_expression); |
3322 | Actions.ActOnBlockError(CaretLoc, CurScope: getCurScope()); |
3323 | return ExprError(); |
3324 | } |
3325 | |
3326 | StmtResult Stmt(ParseCompoundStatementBody()); |
3327 | BlockScope.Exit(); |
3328 | if (!Stmt.isInvalid()) |
3329 | Result = Actions.ActOnBlockStmtExpr(CaretLoc, Body: Stmt.get(), CurScope: getCurScope()); |
3330 | else |
3331 | Actions.ActOnBlockError(CaretLoc, CurScope: getCurScope()); |
3332 | return Result; |
3333 | } |
3334 | |
3335 | ExprResult Parser::ParseObjCBoolLiteral() { |
3336 | tok::TokenKind Kind = Tok.getKind(); |
3337 | return Actions.ObjC().ActOnObjCBoolLiteral(OpLoc: ConsumeToken(), Kind); |
3338 | } |
3339 | |
3340 | /// Validate availability spec list, emitting diagnostics if necessary. Returns |
3341 | /// true if invalid. |
3342 | static bool CheckAvailabilitySpecList(Parser &P, |
3343 | ArrayRef<AvailabilitySpec> AvailSpecs) { |
3344 | llvm::SmallSet<StringRef, 4> Platforms; |
3345 | bool HasOtherPlatformSpec = false; |
3346 | bool Valid = true; |
3347 | for (const auto &Spec : AvailSpecs) { |
3348 | if (Spec.isOtherPlatformSpec()) { |
3349 | if (HasOtherPlatformSpec) { |
3350 | P.Diag(Loc: Spec.getBeginLoc(), DiagID: diag::err_availability_query_repeated_star); |
3351 | Valid = false; |
3352 | } |
3353 | |
3354 | HasOtherPlatformSpec = true; |
3355 | continue; |
3356 | } |
3357 | |
3358 | bool Inserted = Platforms.insert(V: Spec.getPlatform()).second; |
3359 | if (!Inserted) { |
3360 | // Rule out multiple version specs referring to the same platform. |
3361 | // For example, we emit an error for: |
3362 | // @available(macos 10.10, macos 10.11, *) |
3363 | StringRef Platform = Spec.getPlatform(); |
3364 | P.Diag(Loc: Spec.getBeginLoc(), DiagID: diag::err_availability_query_repeated_platform) |
3365 | << Spec.getEndLoc() << Platform; |
3366 | Valid = false; |
3367 | } |
3368 | } |
3369 | |
3370 | if (!HasOtherPlatformSpec) { |
3371 | SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc(); |
3372 | P.Diag(Loc: InsertWildcardLoc, DiagID: diag::err_availability_query_wildcard_required) |
3373 | << FixItHint::CreateInsertion(InsertionLoc: InsertWildcardLoc, Code: ", *" ); |
3374 | return true; |
3375 | } |
3376 | |
3377 | return !Valid; |
3378 | } |
3379 | |
3380 | std::optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() { |
3381 | if (Tok.is(K: tok::star)) { |
3382 | return AvailabilitySpec(ConsumeToken()); |
3383 | } else { |
3384 | // Parse the platform name. |
3385 | if (Tok.is(K: tok::code_completion)) { |
3386 | cutOffParsing(); |
3387 | Actions.CodeCompletion().CodeCompleteAvailabilityPlatformName(); |
3388 | return std::nullopt; |
3389 | } |
3390 | if (Tok.isNot(K: tok::identifier)) { |
3391 | Diag(Tok, DiagID: diag::err_avail_query_expected_platform_name); |
3392 | return std::nullopt; |
3393 | } |
3394 | |
3395 | IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc(); |
3396 | SourceRange VersionRange; |
3397 | VersionTuple Version = ParseVersionTuple(Range&: VersionRange); |
3398 | |
3399 | if (Version.empty()) |
3400 | return std::nullopt; |
3401 | |
3402 | StringRef GivenPlatform = |
3403 | PlatformIdentifier->getIdentifierInfo()->getName(); |
3404 | StringRef Platform = |
3405 | AvailabilityAttr::canonicalizePlatformName(Platform: GivenPlatform); |
3406 | |
3407 | if (AvailabilityAttr::getPrettyPlatformName(Platform).empty() || |
3408 | (GivenPlatform.contains(Other: "xros" ) || GivenPlatform.contains(Other: "xrOS" ))) { |
3409 | Diag(Loc: PlatformIdentifier->getLoc(), |
3410 | DiagID: diag::err_avail_query_unrecognized_platform_name) |
3411 | << GivenPlatform; |
3412 | return std::nullopt; |
3413 | } |
3414 | |
3415 | return AvailabilitySpec(Version, Platform, PlatformIdentifier->getLoc(), |
3416 | VersionRange.getEnd()); |
3417 | } |
3418 | } |
3419 | |
3420 | ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) { |
3421 | assert(Tok.is(tok::kw___builtin_available) || |
3422 | Tok.isObjCAtKeyword(tok::objc_available)); |
3423 | |
3424 | // Eat the available or __builtin_available. |
3425 | ConsumeToken(); |
3426 | |
3427 | BalancedDelimiterTracker Parens(*this, tok::l_paren); |
3428 | if (Parens.expectAndConsume()) |
3429 | return ExprError(); |
3430 | |
3431 | SmallVector<AvailabilitySpec, 4> AvailSpecs; |
3432 | bool HasError = false; |
3433 | while (true) { |
3434 | std::optional<AvailabilitySpec> Spec = ParseAvailabilitySpec(); |
3435 | if (!Spec) |
3436 | HasError = true; |
3437 | else |
3438 | AvailSpecs.push_back(Elt: *Spec); |
3439 | |
3440 | if (!TryConsumeToken(Expected: tok::comma)) |
3441 | break; |
3442 | } |
3443 | |
3444 | if (HasError) { |
3445 | SkipUntil(T: tok::r_paren, Flags: StopAtSemi); |
3446 | return ExprError(); |
3447 | } |
3448 | |
3449 | CheckAvailabilitySpecList(P&: *this, AvailSpecs); |
3450 | |
3451 | if (Parens.consumeClose()) |
3452 | return ExprError(); |
3453 | |
3454 | return Actions.ObjC().ActOnObjCAvailabilityCheckExpr( |
3455 | AvailSpecs, AtLoc: BeginLoc, RParen: Parens.getCloseLocation()); |
3456 | } |
3457 | |