aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/Parse/ParseTemplate.cpp
AgeCommit message (Collapse)AuthorFilesLines
2017-06-26[Sema] Fix a crash-on-invalid when a template parameter list has a classAkira Hatanaka1-1/+2
definition or non-reference class type. The crash occurs when there is a template parameter list in a class that is missing the closing angle bracket followed by a definition of a struct. For example: class C0 { public: template<typename T, typename T1 = T // missing closing angle bracket struct S0 {}; C0() : m(new S0<int>) {} S0<int> *m; }; This happens because the parsed struct is added to the scope of the enclosing class without having its access specifier set, which results in an assertion failure in SemaAccess.cpp later. This commit fixes the crash by adding the parsed struct to the enclosing file scope and marking structs as invalid if they are defined in template parameter lists. rdar://problem/31783961 rdar://problem/19570630 Differential Revision: https://reviews.llvm.org/D33606 llvm-svn: 306317
2017-05-23[NFC, Refactor] Modernize TemplateIdAnnotation using TrailingObjectsFaisal Vali1-19/+15
A refactoring of TemplateIdAnnotation that uses TrailingObjects to create a variably-sized object on the heap. https://reviews.llvm.org/D31414 Thanks to Aaron B for the review! llvm-svn: 303594
2017-05-20Fix PR25627: constant expressions being odr-used in template arguments.Faisal Vali1-5/+9
This patch ensures that clang processes the expression-nodes that are generated when disambiguating between types and expressions within template arguments as constant-expressions by installing the ConstantEvaluated ExpressionEvaluationContext just before attempting the disambiguation - and then making sure that Context carries through into ParseConstantExpression (by refactoring it out into a function that does not create its own EvaluationContext: ParseConstantExpressionInExprEvalContext) Note, prior to this patch, trunk would correctly disambiguate and identify the expression as an expression - and while it would annotate the token with the expression - it would fail to complete the odr-use processing (specifically, failing to trigger Sema::UpdateMarkingForLValueToRValue as is done for all Constant Expressions, which would remove it from being considered odr-used). By installing the ConstantExpression Evaluation Context prior to disambiguation, and making sure it carries though, we ensure correct processing of the expression-node. For e.g: template<int> struct X { }; void f() { const int N = 10; X<N> x; // should be OK. [] { return X<N>{}; }; // Should be OK - no capture - but clang errors! } See a related bug: https://bugs.llvm.org//show_bug.cgi?id=25627 In summary (and reiteration), the fix is as follows: - Remove the EnteredConstantEvaluatedContext action from ParseTemplateArgumentList (relying on ParseTemplateArgument getting it right) - Add the EnteredConstantEvaluatedContext action just prior to undergoing the disambiguating parse, and if the parse succeeds for an expression, carry the context though into a refactored version of ParseConstantExpression that does not create its own ExpressionEvaluationContext. See https://reviews.llvm.org/D31588 for additional context regarding some of the more fragile and complicated approaches attempted, and Richard's feedback that eventually shaped the simpler and more robust rendition that is being committed. Thanks Richard! llvm-svn: 303492
2017-05-18Fix the location of "missing ';'" suggestions after annotation tokens.Richard Smith1-2/+2
We were incorrectly setting PrevTokLocation to the first token in the annotation token instead of the last when consuming it. To fix this without adding a complex switch to the hot path through ConsumeToken, we now have a ConsumeAnnotationToken function for consuming annotation tokens in addition to the other Consume*Token special case functions. llvm-svn: 303372
2017-05-11Prune unused \param(s) of clang::Parser::ParseTemplateIdAfterTemplateName() ↵NAKAMURA Takumi1-7/+0
in r302737. [-Wdocumentation] llvm-svn: 302758
2017-05-10Changes missed from r302732.Richard Smith1-7/+2
llvm-svn: 302737
2017-04-01[NFC, Scoped Enum] Convert Sema::ExpressionEvaluationContext into a scoped EnumFaisal Vali1-3/+4
- also replace direct equality checks against the ConstantEvaluated enumerator with isConstantEvaluted(), in anticipation of adding finer granularity to the various ConstantEvaluated contexts and reinstating certain restrictions on where lambda expressions can occur in C++17. - update the clang tablegen backend that uses these Enumerators, and add the relevant scope where needed. llvm-svn: 299316
2017-03-23Publish RAIIObjectsForParser.h for external usage.Vassil Vassilev1-1/+1
Some clients (eg the cling interpreter) need to recover their parser from errors. Patch by Axel Naumann (D31190)! llvm-svn: 298606
2017-02-01Fix hole in our enforcement of rule requiring 'typename' prior to a dependentRichard Smith1-2/+9
name. If the dependent name happened to end in a template-id (X<T>::Y<U>), we would fail to notice that the 'typename' keyword is missing when resolving it to a type. It turns out that GCC has a similar bug. If this shows up in much real code, we can easily downgrade this to an ExtWarn. llvm-svn: 293815
2017-01-19PR13403 (+duplicates): implement C++ DR1310 (http://wg21.link/cwg1310).Richard Smith1-6/+7
Under this defect resolution, the injected-class-name of a class or class template cannot be used except in very limited circumstances (when declaring a constructor, in a nested-name-specifier, in a base-specifier, or in an elaborated-type-specifier). This is apparently done to make parsing easier, but it's a pain for us since we don't know whether a template-id using the injected-class-name is valid at the point when we annotate it (we don't yet know whether the template-id will become part of an elaborated-type-specifier). As a tentative resolution to a perceived language defect, mem-initializer-ids are added to the list of exceptions here (they generally follow the same rules as base-specifiers). When the reference to the injected-class-name uses the 'typename' or 'template' keywords, we permit it to be used to name a type or template as an extension; other compilers also accept some cases in this area. There are also a couple of corner cases with dependent template names that we do not yet diagnose, but which will also get this treatment. llvm-svn: 292518
2016-12-16[c++1z] P0195R2: Allow multiple using-declarators in a single using-declaration.Richard Smith1-3/+6
llvm-svn: 289905
2016-07-18[NFC] Header cleanupMehdi Amini1-2/+1
Summary: Removed unused headers, replaced some headers with forward class declarations Patch by: Eugene <claprix@yandex.ru> Differential Revision: https://reviews.llvm.org/D20100 llvm-svn: 275882
2016-06-15Revert accidential "[MSVC] Late parsing of in-class defined member functions ↵Alexey Bataev1-84/+0
in template" This reverts commit 0253605771b8bd9d414aba74fe2742c730d6fd1a. llvm-svn: 272776
2016-06-15[MSVC] Late parsing of in-class defined member functions in templateAlexey Bataev1-0/+84
classes. MSVC actively uses unqualified lookup in dependent bases, lookup at the instantiation point (non-dependent names may be resolved on things declared later) etc. and all this stuff is the main cause of incompatibility between clang and MSVC. Clang tries to emulate MSVC behavior but it may fail in many cases. clang could store lexed tokens for member functions definitions within ClassTemplateDecl for later parsing during template instantiation. It will allow resolving many possible issues with lookup in dependent base classes and removing many already existing MSVC-specific hacks/workarounds from the clang code. llvm-svn: 272774
2016-04-29[Concepts] Pass requires-clause to ActOnTemplateParameterList; NFCHubert Tong1-10/+9
Summary: Prepare to store requires-clause expression for access via TemplateParameterList. Reviewers: aaron.ballman, faisalv, rsmith Subscribers: cfe-commits, nwilson Differential Revision: http://reviews.llvm.org/D19220 llvm-svn: 268081
2016-04-29[Parser] Clear the TemplateParamScope bit of the current scope's flagAkira Hatanaka1-0/+3
if we are parsing a template specialization. This commit makes changes to clear the TemplateParamScope bit and set the TemplateParamParent field of the current scope to null if a template specialization is being parsed. Before this commit, Sema::ActOnStartOfLambdaDefinition would check whether the parent template scope had any decls to determine whether or not a template specialization was being parsed. This wasn't correct since it couldn't distinguish between a real template specialization and a template defintion with an unnamed template parameter (only template parameters with names are added to the scope's decl list). To fix the bug, this commit changes the code to check the pointer to the parent template scope rather than the decl list. rdar://problem/23440346 Differential Revision: http://reviews.llvm.org/D19175 llvm-svn: 267975
2016-02-09Simplify EnterTokenStream API to make it more robust for memory managementDavid Blaikie1-1/+1
While this won't help fix things like the bug that r260219 addressed, it seems like good tidy up to have anyway. (it might be nice if "makeArrayRef" always produced a MutableArrayRef & let it decay to an ArrayRef when needed - then I'd use that for the MutableArrayRefs in this patch) If we had std::dynarray I'd use that instead of unique_ptr+size_t, ideally (but then it'd have to be threaded down through the Preprocessor all the way - no idea how painful that would be) llvm-svn: 260246
2016-02-05[Parser] Perform CachedTokens update dependent on token consumptionBruno Cardoso Lopes1-2/+6
In the context where we break one tok::greatergreater into two tok::greater in order to correctly update the cached tokens; update the CachedTokens with two tok::greater only if ParseGreaterThanInTemplateList clients asks to consume the last token. Otherwise we only need to add one because the second is already added later on, as a not yet cached token. Differential Revision: http://reviews.llvm.org/D16906 rdar://problem/24488367 llvm-svn: 259910
2016-01-31[Parser] Update CachedTokens while parsing ObjectiveC template argument listBruno Cardoso Lopes1-0/+12
Consider the following ObjC++ snippet: -- @protocol PA; @protocol PB; @class NSArray<ObjectType>; typedef int some_t; id<PA> FA(NSArray<id<PB>> *h, some_t group); -- This would hit an assertion in the parser after generating an annotation token while trying to update the token cache: Assertion failed: (CachedTokens[CachedLexPos-1].getLastLoc() == Tok.getAnnotationEndLoc() && "The annotation should be until the most recent cached token") ... 7 clang::Preprocessor::AnnotatePreviousCachedTokens(clang::Token const&) + 494 8 clang::Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool, bool, clang::CXXScopeSpec&, bool) + 1163 9 clang::Parser::TryAnnotateTypeOrScopeToken(bool, bool) + 361 10 clang::Parser::isCXXDeclarationSpecifier(clang::Parser::TPResult, bool*) + 598 ... The cached preprocessor token in this case is: greatergreater '>>' Loc=<testcase.mm:7:24> while the annotation ("NSArray<id<PB>>") ends at "testcase.mm:7:25", hence the assertion. Properly update the CachedTokens during template parsing to contain two greater tokens instead of a greatergreater. Differential Revision: http://reviews.llvm.org/D15173 rdar://problem/23494277 llvm-svn: 259311
2016-01-28Include RecordDecls from anonymous unions in the AST.Nico Weber1-1/+5
For void f() { union { int i; }; } clang used to omit the RecordDecl from the anonymous union from the AST. That's because the code creating it only called PushOnScopeChains(), which adds it to the current DeclContext, which here is the function's DeclContext. But RecursiveASTVisitor doesn't descent into all decls in a FunctionDecl. Instead, for DeclContexts that contain statements, return the RecordDecl so that it can be included in the DeclStmt containing the VarDecl for the union. Interesting bits from the AST before this change: |-FunctionDecl | `-CompoundStmt | |-DeclStmt | | `-VarDecl 0x589cd60 <col:3> col:3 implicit used 'union (anonymous at test.cc:3:3)' callinit After this change: -FunctionDecl | `-CompoundStmt | |-DeclStmt | | |-CXXRecordDecl 0x4612e48 <col:3, col:18> col:3 union definition | | | |-FieldDecl 0x4612f70 <col:11, col:15> col:15 referenced i 'int' | | `-VarDecl 0x4613010 <col:3> col:3 implicit used 'union (anonymous at test.cc:3:3)' callinit This is now closer to how anonymous struct and unions are represented as members of structs. It also enabled deleting some one-off code in the template instantiation code. Finally, it fixes a crash with ASTMatchers, see the included test case (this fixes http://crbug.com/580749). llvm-svn: 259079
2016-01-15OpaquePtr: Use nullptr construction for ParsedType OpaquePtr typedefDavid Blaikie1-15/+12
llvm-svn: 257958
2015-12-24[Sema] ArrayRef-ize ActOnTemplateParameterList. NFCCraig Topper1-6/+4
llvm-svn: 256400
2015-11-19Change the expression evaluation context from Unevaluated to ↵Faisal Vali1-2/+2
ConstantEvaluated while substituting into non-type template argument defaults. Also address a typo from a prior patch that performed a similar fix during Parsing of default non-type template arguments. I left the RAII ExpressionEvaluationContext variable Name as Unevaluated though we had switched the context to ConstantEvaluated. There should be no functionality change here - since when expression evaluation context is popped off, for the most part these two contexts currently behave similarly in regards to lambda diagnostics and odr-use tracking. Like its parsing counterpart, this patch presages the advent of constexpr lambda patches... llvm-svn: 253590
2015-11-18[NFC] Change the evaluation context of a non-type default template argument ↵Faisal Vali1-1/+2
from Unevaluated to ConstantEvaluated. This patch emits a more appropriate (but still noisy) diagnostic stream when a lambda-expression is encountered within a non-type default argument. For e.g. template<int N = ([] { return 5; }())> int f(); As opposed to complaining that a lambda expression is not allowed in an unevaluated operand, the patch complains about the lambda being forbidden in a constant expression context (which will be allowed in C++17 now that they have been accepted by EWG, unless of course CWG or national bodies (that have so far shown no signs of concern) rise in protest) As I start submitting patches for constexpr lambdas (http://wg21.link/P0170R0) under C++1z (OK'd by Richard Smith at Kona), this will be one less change to make. Thanks! llvm-svn: 253431
2015-07-07Parsing, semantic analysis, and AST for Objective-C type parameters.Douglas Gregor1-35/+45
Produce type parameter declarations for Objective-C type parameters, and attach lists of type parameters to Objective-C classes, categories, forward declarations, and extensions as appropriate. Perform semantic analysis of type bounds for type parameters, both in isolation and across classes/categories/extensions to ensure consistency. Also handle (de-)serialization of Objective-C type parameter lists, along with sundry other things one must do to add a new declaration to Clang. Note that Objective-C type parameters are typedef name declarations, like typedefs and C++11 type aliases, in support of type erasure. Part of rdar://problem/6294649. llvm-svn: 241541
2015-06-25[Concepts] Parsing of requires-clause in template-declarationHubert Tong1-1/+12
Summary: This change implements parse-only acceptance of the optional requires-clause in a template-declaration. Diagnostic testing is added for cases where the grammar is ambiguous with the expectation that the longest token sequence which matches the syntax of a constraint-expression is consumed without backtracking. Reviewers: faisalv, fraggamuffin, rsmith Reviewed By: rsmith Subscribers: cfe-commits Differential Revision: http://reviews.llvm.org/D10462 llvm-svn: 240611
2015-06-18[clang] Refactoring of conditions so they use isOneOf() instead of multiple ↵Daniel Marjamaki1-22/+19
is(). llvm-svn: 240008
2015-05-11PR20625: Instantiate static constexpr member function of a local struct in a ↵Richard Smith1-1/+3
function template earlier. This is necessary in order to allow the use of a constexpr member function, or a member function with deduced return type, of a local class within a surrounding instantiated function template specialization. Patch by Michael Park! This re-commits r236063, which was reverted in r236134, along with a fix for a delayed template parsing bug that was exposed by this change. llvm-svn: 237064
2014-12-15Diagnose function template definitions inside functionsReid Kleckner1-0/+10
The parser can only be tricked into parsing a function template definition by inserting a typename keyword before the function template declaration. This used to make us crash, and now it's fixed. While here, remove an unneeded boolean parameter from ParseDeclGroup. This boolean always corresponded to non-typedef declarators at file scope. ParseDeclGroup already has precise diagnostics for the function definition typedef case, so we can let that through. Fixes PR21839. llvm-svn: 224287
2014-12-02Ensure typos in the default values of template parameters get diagnosed.Kaelyn Takata1-1/+1
llvm-svn: 223177
2014-08-19C++1y is now C++14!Aaron Ballman1-1/+1
Changes diagnostic options, language standard options, diagnostic identifiers, diagnostic wording to use c++14 instead of c++1y. It also modifies related test cases to use the updated diagnostic wording. llvm-svn: 215982
2014-08-15Wrap to 80 columns, no behavior change.Nico Weber1-1/+2
llvm-svn: 215776
2014-08-04A static_assert declaration cannot be a template; adding the diagnostic for ↵Aaron Ballman1-0/+8
this instead of silently accepting and producing possibly-unexpected behavior. llvm-svn: 214770
2014-06-20Fix PR20081: Parsing templates in the presence of -x cuda -std=c++11Eli Bendersky1-2/+5
http://reviews.llvm.org/D4222 llvm-svn: 211357
2014-06-16[C++1z] Implement N4051: 'typename' is permitted instead of 'class' when ↵Richard Smith1-10/+22
declaring a template template parameter. llvm-svn: 211031
2014-06-06Remove an unused variableTimur Iskhodzhanov1-2/+0
llvm-svn: 210324
2014-06-06PR11306 - Variadic template fix-it suggestion. Recover from misplaced or ↵Nikola Smiljanic1-3/+40
redundant ellipsis in parameter pack. llvm-svn: 210304
2014-05-29Refactoring. Remove release and take methods from ActionResult. Rename ↵Nikola Smiljanic1-2/+2
takeAs to getAs. llvm-svn: 209800
2014-05-21[C++11] Use 'nullptr'. Parser edition.Craig Topper1-16/+16
llvm-svn: 209275
2014-05-16Replace a fake enum class with the real thing.Richard Smith1-1/+1
llvm-svn: 208943
2014-05-02Handle -fdelayed-template-parsing of out-of-line definitions ofHans Wennborg1-31/+10
class template member classes (PR19613) Also improve this code in general by implementing suggestions from Richard. Differential Revision: http://reviews.llvm.org/D3555?id=9020 llvm-svn: 207822
2014-04-13Improve error recovery around colon.Serge Pavlov1-0/+1
Parse of nested name spacifier is modified so that it properly recovers if colon is mistyped as double colon in case statement. This patch fixes PR15133. Differential Revision: http://llvm-reviews.chandlerc.com/D2870 llvm-svn: 206135
2014-01-22Introduce and use Decl::getAsFunction() to simplify templated function checksAlp Toker1-5/+5
Lift the getFunctionDecl() utility out of the parser into a general Decl::getAsFunction() and use it to simplify other parts of the implementation. Reduce isFunctionOrFunctionTemplate() to a simple type check that works the same was as the other is* functions and move unwrapping of shadowed decls to callers so it doesn't get run twice. Shuffle around canSkipFunctionBody() to reduce virtual dispatch on ASTConsumer. There's no need to query when we already know the body can't be skipped. llvm-svn: 199794
2014-01-05Parse: Token consumption modernization and loop de-nestingAlp Toker1-5/+3
Cleanup only. llvm-svn: 198539
2014-01-01ExpectAndConsume: Diagnose errors automaticallyAlp Toker1-5/+3
1) Teach ExpectAndConsume() to emit expected and expected-after diagnostics using the generic diagnostic descriptions added in r197972, eliminating another set of trivial err_expected_* variations while maintaining existing behaviour. 2) Lift SkipUntil() recovery out of ExpectAndConsume(). The Expect/Consume family of functions are primitive parser operations that now have the well-defined property of operating on single tokens. Factoring out recovery exposes opportunities for more consistent and tailored error recover at the call sites instead of just relying on a bottled SkipUntil formula. llvm-svn: 198270
2013-12-24Support and use token kinds as diagnostic argumentsAlp Toker1-2/+2
Introduce proper facilities to render token spellings using the diagnostic formatter. Replaces most of the hard-coded diagnostic messages related to expected tokens, which all shared the same semantics but had to be multiply defined due to variations in token order or quote marks. The associated parser changes are largely mechanical but they expose commonality in whole chunks of the parser that can now be factored away. This commit uses C++11 typed enums along with a speculative legacy fallback until the transition is complete. Requires corresponding changes in LLVM r197895. llvm-svn: 197972
2013-12-17Refactor and micro-optimize ConsumeToken()Alp Toker1-47/+20
1) Introduce TryConsumeToken() to handle the common test-and-consume pattern. This brings about readability improvements in the parser and optimizes to avoid redundant checks in the common case. 2) Eliminate the ConsumeCodeCompletionTok special case from ConsumeToken(). This was used by only one caller which has been switched over to the more appropriate ConsumeCodeCompletionToken() function. llvm-svn: 197497
2013-12-04Fix PR17637: incorrect calculation of template parameter depthFaisal Vali1-2/+4
In delayed template parsing mode, adjust the template depth counter for each template parameter list associated with an out of line member template specialization. llvm-svn: 196351
2013-11-18Replaced bool parameters in SkipUntil function with single bit-based parameter.Alexey Bataev1-10/+15
llvm-svn: 194994
2013-08-16Parse: Do not 'HandleTopLevelDecl' on templated functions.David Majnemer1-5/+1
Summary: HandleTopLevelDecl on a templated function leads us to try and mangle it. Reviewers: rsmith Reviewed By: rsmith CC: cfe-commits Differential Revision: http://llvm-reviews.chandlerc.com/D1412 llvm-svn: 188536