ParseTentative.cpp revision 195099
1193323Sed//===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed//  This file implements the tentative parsing portions of the Parser
11193323Sed//  interfaces, for ambiguity resolution.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#include "clang/Parse/Parser.h"
16193323Sed#include "clang/Parse/ParseDiagnostic.h"
17199481Srdivackyusing namespace clang;
18218893Sdim
19193323Sed/// isCXXDeclarationStatement - C++-specialized function that disambiguates
20193323Sed/// between a declaration or an expression statement, when parsing function
21193323Sed/// bodies. Returns true for declaration, false for expression.
22193323Sed///
23198090Srdivacky///         declaration-statement:
24245431Sdim///           block-declaration
25193323Sed///
26193323Sed///         block-declaration:
27193323Sed///           simple-declaration
28198090Srdivacky///           asm-definition
29218893Sdim///           namespace-alias-definition
30206274Srdivacky///           using-declaration
31245431Sdim///           using-directive
32245431Sdim/// [C++0x]   static_assert-declaration
33193323Sed///
34193323Sed///         asm-definition:
35212904Sdim///           'asm' '(' string-literal ')' ';'
36193323Sed///
37193323Sed///         namespace-alias-definition:
38193323Sed///           'namespace' identifier = qualified-namespace-specifier ';'
39212904Sdim///
40193323Sed///         using-declaration:
41210299Sed///           'using' typename[opt] '::'[opt] nested-name-specifier
42210299Sed///                 unqualified-id ';'
43212904Sdim///           'using' '::' unqualified-id ;
44193323Sed///
45193323Sed///         using-directive:
46193323Sed///           'using' 'namespace' '::'[opt] nested-name-specifier[opt]
47193323Sed///                 namespace-name ';'
48193323Sed///
49193323Sedbool Parser::isCXXDeclarationStatement() {
50193323Sed  switch (Tok.getKind()) {
51193323Sed    // asm-definition
52193323Sed  case tok::kw_asm:
53193323Sed    // namespace-alias-definition
54193323Sed  case tok::kw_namespace:
55193323Sed    // using-declaration
56193323Sed    // using-directive
57193323Sed  case tok::kw_using:
58193323Sed    return true;
59193323Sed  case tok::kw_static_assert:
60193323Sed    // static_assert-declaration
61193323Sed    return true;
62193323Sed  default:
63193323Sed    // simple-declaration
64193323Sed    return isCXXSimpleDeclaration();
65193323Sed  }
66193323Sed}
67193323Sed
68193323Sed/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
69193323Sed/// between a simple-declaration or an expression-statement.
70193323Sed/// If during the disambiguation process a parsing error is encountered,
71193323Sed/// the function returns true to let the declaration parsing code handle it.
72193323Sed/// Returns false if the statement is disambiguated as expression.
73193323Sed///
74193323Sed/// simple-declaration:
75193323Sed///   decl-specifier-seq init-declarator-list[opt] ';'
76193323Sed///
77193323Sedbool Parser::isCXXSimpleDeclaration() {
78193323Sed  // C++ 6.8p1:
79193323Sed  // There is an ambiguity in the grammar involving expression-statements and
80193323Sed  // declarations: An expression-statement with a function-style explicit type
81193323Sed  // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
82193323Sed  // from a declaration where the first declarator starts with a '('. In those
83198396Srdivacky  // cases the statement is a declaration. [Note: To disambiguate, the whole
84198396Srdivacky  // statement might have to be examined to determine if it is an
85198396Srdivacky  // expression-statement or a declaration].
86212904Sdim
87193323Sed  // C++ 6.8p3:
88193323Sed  // The disambiguation is purely syntactic; that is, the meaning of the names
89193323Sed  // occurring in such a statement, beyond whether they are type-names or not,
90193323Sed  // is not generally used in or changed by the disambiguation. Class
91193323Sed  // templates are instantiated as necessary to determine if a qualified name
92193323Sed  // is a type-name. Disambiguation precedes parsing, and a statement
93193323Sed  // disambiguated as a declaration may be an ill-formed declaration.
94193323Sed
95193323Sed  // We don't have to parse all of the decl-specifier-seq part. There's only
96193323Sed  // an ambiguity if the first decl-specifier is
97193323Sed  // simple-type-specifier/typename-specifier followed by a '(', which may
98193323Sed  // indicate a function-style cast expression.
99212904Sdim  // isCXXDeclarationSpecifier will return TPResult::Ambiguous() only in such
100198396Srdivacky  // a case.
101198396Srdivacky
102198396Srdivacky  TPResult TPR = isCXXDeclarationSpecifier();
103212904Sdim  if (TPR != TPResult::Ambiguous())
104212904Sdim    return TPR != TPResult::False(); // Returns true for TPResult::True() or
105212904Sdim                                     // TPResult::Error().
106212904Sdim
107212904Sdim  // FIXME: Add statistics about the number of ambiguous statements encountered
108245431Sdim  // and how they were resolved (number of declarations+number of expressions).
109245431Sdim
110245431Sdim  // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
111245431Sdim  // We need tentative parsing...
112212904Sdim
113212904Sdim  TentativeParsingAction PA(*this);
114212904Sdim
115212904Sdim  TPR = TryParseSimpleDeclaration();
116212904Sdim  SourceLocation TentativeParseLoc = Tok.getLocation();
117245431Sdim
118198396Srdivacky  PA.Revert();
119245431Sdim
120193323Sed  // In case of an error, let the declaration parsing code handle it.
121193323Sed  if (TPR == TPResult::Error())
122193323Sed    return true;
123193323Sed
124193323Sed  // Declarations take precedence over expressions.
125193323Sed  if (TPR == TPResult::Ambiguous())
126193323Sed    TPR = TPResult::True();
127193323Sed
128193323Sed  assert(TPR == TPResult::True() || TPR == TPResult::False());
129193323Sed  return TPR == TPResult::True();
130193323Sed}
131193323Sed
132193323Sed/// simple-declaration:
133193323Sed///   decl-specifier-seq init-declarator-list[opt] ';'
134193323Sed///
135193323SedParser::TPResult Parser::TryParseSimpleDeclaration() {
136193323Sed  // We know that we have a simple-type-specifier/typename-specifier followed
137193323Sed  // by a '('.
138193323Sed  assert(isCXXDeclarationSpecifier() == TPResult::Ambiguous());
139193323Sed
140193323Sed  if (Tok.is(tok::kw_typeof))
141208599Srdivacky    TryParseTypeofSpecifier();
142208599Srdivacky  else
143208599Srdivacky    ConsumeToken();
144208599Srdivacky
145193323Sed  assert(Tok.is(tok::l_paren) && "Expected '('");
146193323Sed
147193323Sed  TPResult TPR = TryParseInitDeclaratorList();
148193323Sed  if (TPR != TPResult::Ambiguous())
149193323Sed    return TPR;
150193323Sed
151212904Sdim  if (Tok.isNot(tok::semi))
152193323Sed    return TPResult::False();
153198090Srdivacky
154198090Srdivacky  return TPResult::Ambiguous();
155198090Srdivacky}
156198090Srdivacky
157198090Srdivacky///       init-declarator-list:
158198090Srdivacky///         init-declarator
159198090Srdivacky///         init-declarator-list ',' init-declarator
160198090Srdivacky///
161193323Sed///       init-declarator:
162212904Sdim///         declarator initializer[opt]
163212904Sdim/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
164193323Sed///
165212904Sdim/// initializer:
166193323Sed///   '=' initializer-clause
167193323Sed///   '(' expression-list ')'
168193323Sed///
169193323Sed/// initializer-clause:
170193323Sed///   assignment-expression
171193323Sed///   '{' initializer-list ','[opt] '}'
172208599Srdivacky///   '{' '}'
173208599Srdivacky///
174208599SrdivackyParser::TPResult Parser::TryParseInitDeclaratorList() {
175208599Srdivacky  // GCC only examines the first declarator for disambiguation:
176208599Srdivacky  // i.e:
177208599Srdivacky  // int(x), ++x; // GCC regards it as ill-formed declaration.
178193323Sed  //
179193323Sed  // Comeau and MSVC will regard the above statement as correct expression.
180193323Sed  // Clang examines all of the declarators and also regards the above statement
181193323Sed  // as correct expression.
182193323Sed
183226890Sdim  while (1) {
184226890Sdim    // declarator
185226890Sdim    TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
186226890Sdim    if (TPR != TPResult::Ambiguous())
187193323Sed      return TPR;
188193323Sed
189193323Sed    // [GNU] simple-asm-expr[opt] attributes[opt]
190193323Sed    if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
191193323Sed      return TPResult::True();
192193323Sed
193193323Sed    // initializer[opt]
194212904Sdim    if (Tok.is(tok::l_paren)) {
195193323Sed      // Parse through the parens.
196193323Sed      ConsumeParen();
197193323Sed      if (!SkipUntil(tok::r_paren))
198193323Sed        return TPResult::Error();
199193323Sed    } else if (Tok.is(tok::equal)) {
200198090Srdivacky      // MSVC won't examine the rest of declarators if '=' is encountered, it
201198090Srdivacky      // will conclude that it is a declaration.
202198090Srdivacky      // Comeau and Clang will examine the rest of declarators.
203198090Srdivacky      // Note that "int(x) = {0}, ++x;" will be interpreted as ill-formed
204218893Sdim      // expression.
205193323Sed      //
206218893Sdim      // Parse through the initializer-clause.
207199481Srdivacky      SkipUntil(tok::comma, true/*StopAtSemi*/, true/*DontConsume*/);
208212904Sdim    }
209212904Sdim
210212904Sdim    if (Tok.isNot(tok::comma))
211212904Sdim      break;
212212904Sdim    ConsumeToken(); // the comma.
213212904Sdim  }
214212904Sdim
215212904Sdim  return TPResult::Ambiguous();
216212904Sdim}
217212904Sdim
218212904Sdim/// isCXXConditionDeclaration - Disambiguates between a declaration or an
219212904Sdim/// expression for a condition of a if/switch/while/for statement.
220212904Sdim/// If during the disambiguation process a parsing error is encountered,
221212904Sdim/// the function returns true to let the declaration parsing code handle it.
222212904Sdim///
223212904Sdim///       condition:
224252723Sdim///         expression
225252723Sdim///         type-specifier-seq declarator '=' assignment-expression
226193323Sed/// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
227252723Sdim///             '=' assignment-expression
228252723Sdim///
229193323Sedbool Parser::isCXXConditionDeclaration() {
230193323Sed  TPResult TPR = isCXXDeclarationSpecifier();
231193323Sed  if (TPR != TPResult::Ambiguous())
232208599Srdivacky    return TPR != TPResult::False(); // Returns true for TPResult::True() or
233208599Srdivacky                                     // TPResult::Error().
234193323Sed
235193323Sed  // FIXME: Add statistics about the number of ambiguous statements encountered
236226890Sdim  // and how they were resolved (number of declarations+number of expressions).
237193323Sed
238198090Srdivacky  // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
239212904Sdim  // We need tentative parsing...
240212904Sdim
241212904Sdim  TentativeParsingAction PA(*this);
242193323Sed
243193323Sed  // type-specifier-seq
244193323Sed  if (Tok.is(tok::kw_typeof))
245193323Sed    TryParseTypeofSpecifier();
246193323Sed  else
247193323Sed    ConsumeToken();
248193323Sed  assert(Tok.is(tok::l_paren) && "Expected '('");
249193323Sed
250193323Sed  // declarator
251193323Sed  TPR = TryParseDeclarator(false/*mayBeAbstract*/);
252193323Sed
253193323Sed  // In case of an error, let the declaration parsing code handle it.
254193323Sed  if (TPR == TPResult::Error())
255193323Sed    TPR = TPResult::True();
256193323Sed
257193323Sed  if (TPR == TPResult::Ambiguous()) {
258193323Sed    // '='
259193323Sed    // [GNU] simple-asm-expr[opt] attributes[opt]
260193323Sed    if (Tok.is(tok::equal)  ||
261226890Sdim        Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
262226890Sdim      TPR = TPResult::True();
263226890Sdim    else
264226890Sdim      TPR = TPResult::False();
265226890Sdim  }
266193323Sed
267193323Sed  PA.Revert();
268193323Sed
269193323Sed  assert(TPR == TPResult::True() || TPR == TPResult::False());
270193323Sed  return TPR == TPResult::True();
271193323Sed}
272212904Sdim
273212904Sdim  /// \brief Determine whether the next set of tokens contains a type-id.
274208599Srdivacky  ///
275208599Srdivacky  /// The context parameter states what context we're parsing right
276208599Srdivacky  /// now, which affects how this routine copes with the token
277208599Srdivacky  /// following the type-id. If the context is TypeIdInParens, we have
278193323Sed  /// already parsed the '(' and we will cease lookahead when we hit
279193323Sed  /// the corresponding ')'. If the context is
280193323Sed  /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
281193323Sed  /// before this template argument, and will cease lookahead when we
282193323Sed  /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
283193323Sed  /// and false for an expression.  If during the disambiguation
284193323Sed  /// process a parsing error is encountered, the function returns
285193323Sed  /// true to let the declaration parsing code handle it.
286212904Sdim  ///
287193323Sed  /// type-id:
288193323Sed  ///   type-specifier-seq abstract-declarator[opt]
289212904Sdim  ///
290193323Sedbool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
291193323Sed
292193323Sed  isAmbiguous = false;
293212904Sdim
294212904Sdim  // C++ 8.2p2:
295212904Sdim  // The ambiguity arising from the similarity between a function-style cast and
296212904Sdim  // a type-id can occur in different contexts. The ambiguity appears as a
297212904Sdim  // choice between a function-style cast expression and a declaration of a
298212904Sdim  // type. The resolution is that any construct that could possibly be a type-id
299212904Sdim  // in its syntactic context shall be considered a type-id.
300212904Sdim
301212904Sdim  TPResult TPR = isCXXDeclarationSpecifier();
302212904Sdim  if (TPR != TPResult::Ambiguous())
303212904Sdim    return TPR != TPResult::False(); // Returns true for TPResult::True() or
304212904Sdim                                     // TPResult::Error().
305212904Sdim
306212904Sdim  // FIXME: Add statistics about the number of ambiguous statements encountered
307212904Sdim  // and how they were resolved (number of declarations+number of expressions).
308212904Sdim
309212904Sdim  // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
310212904Sdim  // We need tentative parsing...
311212904Sdim
312212904Sdim  TentativeParsingAction PA(*this);
313212904Sdim
314212904Sdim  // type-specifier-seq
315212904Sdim  if (Tok.is(tok::kw_typeof))
316212904Sdim    TryParseTypeofSpecifier();
317212904Sdim  else
318212904Sdim    ConsumeToken();
319212904Sdim  assert(Tok.is(tok::l_paren) && "Expected '('");
320212904Sdim
321212904Sdim  // declarator
322212904Sdim  TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
323212904Sdim
324212904Sdim  // In case of an error, let the declaration parsing code handle it.
325212904Sdim  if (TPR == TPResult::Error())
326212904Sdim    TPR = TPResult::True();
327212904Sdim
328212904Sdim  if (TPR == TPResult::Ambiguous()) {
329212904Sdim    // We are supposed to be inside parens, so if after the abstract declarator
330212904Sdim    // we encounter a ')' this is a type-id, otherwise it's an expression.
331212904Sdim    if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
332212904Sdim      TPR = TPResult::True();
333212904Sdim      isAmbiguous = true;
334212904Sdim
335212904Sdim    // We are supposed to be inside a template argument, so if after
336212904Sdim    // the abstract declarator we encounter a '>', '>>' (in C++0x), or
337212904Sdim    // ',', this is a type-id. Otherwise, it's an expression.
338212904Sdim    } else if (Context == TypeIdAsTemplateArgument &&
339212904Sdim               (Tok.is(tok::greater) || Tok.is(tok::comma) ||
340212904Sdim                (getLang().CPlusPlus0x && Tok.is(tok::greatergreater)))) {
341212904Sdim      TPR = TPResult::True();
342212904Sdim      isAmbiguous = true;
343212904Sdim
344193323Sed    } else
345193323Sed      TPR = TPResult::False();
346193323Sed  }
347193323Sed
348193323Sed  PA.Revert();
349193323Sed
350193323Sed  assert(TPR == TPResult::True() || TPR == TPResult::False());
351193323Sed  return TPR == TPResult::True();
352193323Sed}
353193323Sed
354193323Sed///         declarator:
355193323Sed///           direct-declarator
356193323Sed///           ptr-operator declarator
357193323Sed///
358193323Sed///         direct-declarator:
359193323Sed///           declarator-id
360193323Sed///           direct-declarator '(' parameter-declaration-clause ')'
361193323Sed///                 cv-qualifier-seq[opt] exception-specification[opt]
362193323Sed///           direct-declarator '[' constant-expression[opt] ']'
363193323Sed///           '(' declarator ')'
364193323Sed/// [GNU]     '(' attributes declarator ')'
365193323Sed///
366193323Sed///         abstract-declarator:
367193323Sed///           ptr-operator abstract-declarator[opt]
368193323Sed///           direct-abstract-declarator
369193323Sed///
370193323Sed///         direct-abstract-declarator:
371245431Sdim///           direct-abstract-declarator[opt]
372193323Sed///           '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
373193323Sed///                 exception-specification[opt]
374245431Sdim///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
375245431Sdim///           '(' abstract-declarator ')'
376245431Sdim///
377245431Sdim///         ptr-operator:
378245431Sdim///           '*' cv-qualifier-seq[opt]
379245431Sdim///           '&'
380245431Sdim/// [C++0x]   '&&'                                                        [TODO]
381245431Sdim///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
382212904Sdim///
383212904Sdim///         cv-qualifier-seq:
384212904Sdim///           cv-qualifier cv-qualifier-seq[opt]
385212904Sdim///
386212904Sdim///         cv-qualifier:
387212904Sdim///           'const'
388212904Sdim///           'volatile'
389212904Sdim///
390193323Sed///         declarator-id:
391193323Sed///           id-expression
392193323Sed///
393193323Sed///         id-expression:
394193323Sed///           unqualified-id
395193323Sed///           qualified-id                                                [TODO]
396193323Sed///
397193323Sed///         unqualified-id:
398193323Sed///           identifier
399193323Sed///           operator-function-id                                        [TODO]
400193323Sed///           conversion-function-id                                      [TODO]
401193323Sed///           '~' class-name                                              [TODO]
402193323Sed///           template-id                                                 [TODO]
403193323Sed///
404193323SedParser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
405193323Sed                                            bool mayHaveIdentifier) {
406193323Sed  // declarator:
407193323Sed  //   direct-declarator
408193323Sed  //   ptr-operator declarator
409193323Sed
410193323Sed  while (1) {
411193323Sed    if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
412193323Sed      TryAnnotateCXXScopeToken();
413193323Sed
414193323Sed    if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
415193323Sed        (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
416193323Sed      // ptr-operator
417193323Sed      ConsumeToken();
418193323Sed      while (Tok.is(tok::kw_const)    ||
419193323Sed             Tok.is(tok::kw_volatile) ||
420193323Sed             Tok.is(tok::kw_restrict))
421212904Sdim        ConsumeToken();
422252723Sdim    } else {
423252723Sdim      break;
424252723Sdim    }
425193323Sed  }
426193323Sed
427193323Sed  // direct-declarator:
428212904Sdim  // direct-abstract-declarator:
429193323Sed
430193323Sed  if (Tok.is(tok::identifier) && mayHaveIdentifier) {
431193323Sed    // declarator-id
432193323Sed    ConsumeToken();
433212904Sdim  } else if (Tok.is(tok::l_paren)) {
434212904Sdim    ConsumeParen();
435193323Sed    if (mayBeAbstract &&
436193323Sed        (Tok.is(tok::r_paren) ||       // 'int()' is a function.
437193323Sed         Tok.is(tok::ellipsis) ||      // 'int(...)' is a function.
438212904Sdim         isDeclarationSpecifier())) {   // 'int(int)' is a function.
439245431Sdim      // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
440245431Sdim      //        exception-specification[opt]
441252723Sdim      TPResult TPR = TryParseFunctionDeclarator();
442200581Srdivacky      if (TPR != TPResult::Ambiguous())
443208599Srdivacky        return TPR;
444208599Srdivacky    } else {
445208599Srdivacky      // '(' declarator ')'
446208599Srdivacky      // '(' attributes declarator ')'
447208599Srdivacky      // '(' abstract-declarator ')'
448208599Srdivacky      if (Tok.is(tok::kw___attribute))
449208599Srdivacky        return TPResult::True(); // attributes indicate declaration
450193323Sed      TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
451193323Sed      if (TPR != TPResult::Ambiguous())
452193323Sed        return TPR;
453193323Sed      if (Tok.isNot(tok::r_paren))
454193323Sed        return TPResult::False();
455193323Sed      ConsumeParen();
456193323Sed    }
457193323Sed  } else if (!mayBeAbstract) {
458193323Sed    return TPResult::False();
459193323Sed  }
460193323Sed
461193323Sed  while (1) {
462193323Sed    TPResult TPR(TPResult::Ambiguous());
463193323Sed
464193323Sed    if (Tok.is(tok::l_paren)) {
465193323Sed      // Check whether we have a function declarator or a possible ctor-style
466210299Sed      // initializer that follows the declarator. Note that ctor-style
467212904Sdim      // initializers are not possible in contexts where abstract declarators
468212904Sdim      // are allowed.
469193323Sed      if (!mayBeAbstract && !isCXXFunctionDeclarator(false/*warnIfAmbiguous*/))
470193323Sed        break;
471193323Sed
472193323Sed      // direct-declarator '(' parameter-declaration-clause ')'
473193323Sed      //        cv-qualifier-seq[opt] exception-specification[opt]
474193323Sed      ConsumeParen();
475193323Sed      TPR = TryParseFunctionDeclarator();
476193323Sed    } else if (Tok.is(tok::l_square)) {
477193323Sed      // direct-declarator '[' constant-expression[opt] ']'
478193323Sed      // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
479193323Sed      TPR = TryParseBracketDeclarator();
480193323Sed    } else {
481193323Sed      break;
482193323Sed    }
483198396Srdivacky
484198396Srdivacky    if (TPR != TPResult::Ambiguous())
485198396Srdivacky      return TPR;
486198396Srdivacky  }
487198396Srdivacky
488235633Sdim  return TPResult::Ambiguous();
489198396Srdivacky}
490198396Srdivacky
491193323Sed/// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
492193323Sed/// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
493193323Sed/// be either a decl-specifier or a function-style cast, and TPResult::Error()
494193323Sed/// if a parsing error was found and reported.
495193323Sed///
496193323Sed///         decl-specifier:
497193323Sed///           storage-class-specifier
498193323Sed///           type-specifier
499212904Sdim///           function-specifier
500212904Sdim///           'friend'
501193323Sed///           'typedef'
502212904Sdim/// [GNU]     attributes declaration-specifiers[opt]
503252723Sdim///
504193323Sed///         storage-class-specifier:
505212904Sdim///           'register'
506212904Sdim///           'static'
507212904Sdim///           'extern'
508199481Srdivacky///           'mutable'
509252723Sdim///           'auto'
510199481Srdivacky/// [GNU]     '__thread'
511193323Sed///
512193323Sed///         function-specifier:
513193323Sed///           'inline'
514193323Sed///           'virtual'
515193323Sed///           'explicit'
516193323Sed///
517193323Sed///         typedef-name:
518193323Sed///           identifier
519193323Sed///
520193323Sed///         type-specifier:
521193323Sed///           simple-type-specifier
522193323Sed///           class-specifier
523252723Sdim///           enum-specifier
524199481Srdivacky///           elaborated-type-specifier
525193323Sed///           typename-specifier
526193323Sed///           cv-qualifier
527193323Sed///
528193323Sed///         simple-type-specifier:
529193323Sed///           '::'[opt] nested-name-specifier[opt] type-name
530193323Sed///           '::'[opt] nested-name-specifier 'template'
531193323Sed///                 simple-template-id                              [TODO]
532193323Sed///           'char'
533212904Sdim///           'wchar_t'
534193323Sed///           'bool'
535193323Sed///           'short'
536193323Sed///           'int'
537198090Srdivacky///           'long'
538198090Srdivacky///           'signed'
539198090Srdivacky///           'unsigned'
540198090Srdivacky///           'float'
541198090Srdivacky///           'double'
542198090Srdivacky///           'void'
543198090Srdivacky/// [GNU]     typeof-specifier
544198090Srdivacky/// [GNU]     '_Complex'
545198090Srdivacky/// [C++0x]   'auto'                                                [TODO]
546198090Srdivacky/// [C++0x]   'decltype' ( expression )
547198090Srdivacky///
548198090Srdivacky///         type-name:
549198090Srdivacky///           class-name
550198090Srdivacky///           enum-name
551198090Srdivacky///           typedef-name
552198090Srdivacky///
553193323Sed///         elaborated-type-specifier:
554212904Sdim///           class-key '::'[opt] nested-name-specifier[opt] identifier
555193323Sed///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
556198090Srdivacky///               simple-template-id
557193323Sed///           'enum' '::'[opt] nested-name-specifier[opt] identifier
558198090Srdivacky///
559193323Sed///         enum-name:
560193323Sed///           identifier
561193323Sed///
562193323Sed///         enum-specifier:
563193323Sed///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
564193323Sed///           'enum' identifier[opt] '{' enumerator-list ',' '}'
565///
566///         class-specifier:
567///           class-head '{' member-specification[opt] '}'
568///
569///         class-head:
570///           class-key identifier[opt] base-clause[opt]
571///           class-key nested-name-specifier identifier base-clause[opt]
572///           class-key nested-name-specifier[opt] simple-template-id
573///               base-clause[opt]
574///
575///         class-key:
576///           'class'
577///           'struct'
578///           'union'
579///
580///         cv-qualifier:
581///           'const'
582///           'volatile'
583/// [GNU]     restrict
584///
585Parser::TPResult Parser::isCXXDeclarationSpecifier() {
586  switch (Tok.getKind()) {
587  case tok::identifier:   // foo::bar
588  case tok::kw_typename:  // typename T::type
589    // Annotate typenames and C++ scope specifiers.  If we get one, just
590    // recurse to handle whatever we get.
591    if (TryAnnotateTypeOrScopeToken())
592      return isCXXDeclarationSpecifier();
593    // Otherwise, not a typename.
594    return TPResult::False();
595
596  case tok::coloncolon:   // ::foo::bar
597      if (NextToken().is(tok::kw_new) ||    // ::new
598          NextToken().is(tok::kw_delete))   // ::delete
599        return TPResult::False();
600
601    // Annotate typenames and C++ scope specifiers.  If we get one, just
602    // recurse to handle whatever we get.
603    if (TryAnnotateTypeOrScopeToken())
604      return isCXXDeclarationSpecifier();
605    // Otherwise, not a typename.
606    return TPResult::False();
607
608    // decl-specifier:
609    //   storage-class-specifier
610    //   type-specifier
611    //   function-specifier
612    //   'friend'
613    //   'typedef'
614
615  case tok::kw_friend:
616  case tok::kw_typedef:
617    // storage-class-specifier
618  case tok::kw_register:
619  case tok::kw_static:
620  case tok::kw_extern:
621  case tok::kw_mutable:
622  case tok::kw_auto:
623  case tok::kw___thread:
624    // function-specifier
625  case tok::kw_inline:
626  case tok::kw_virtual:
627  case tok::kw_explicit:
628
629    // type-specifier:
630    //   simple-type-specifier
631    //   class-specifier
632    //   enum-specifier
633    //   elaborated-type-specifier
634    //   typename-specifier
635    //   cv-qualifier
636
637    // class-specifier
638    // elaborated-type-specifier
639  case tok::kw_class:
640  case tok::kw_struct:
641  case tok::kw_union:
642    // enum-specifier
643  case tok::kw_enum:
644    // cv-qualifier
645  case tok::kw_const:
646  case tok::kw_volatile:
647
648    // GNU
649  case tok::kw_restrict:
650  case tok::kw__Complex:
651  case tok::kw___attribute:
652    return TPResult::True();
653
654    // Microsoft
655  case tok::kw___declspec:
656  case tok::kw___cdecl:
657  case tok::kw___stdcall:
658  case tok::kw___fastcall:
659  case tok::kw___w64:
660  case tok::kw___ptr64:
661  case tok::kw___forceinline:
662    return TPResult::True();
663
664    // The ambiguity resides in a simple-type-specifier/typename-specifier
665    // followed by a '('. The '(' could either be the start of:
666    //
667    //   direct-declarator:
668    //     '(' declarator ')'
669    //
670    //   direct-abstract-declarator:
671    //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
672    //              exception-specification[opt]
673    //     '(' abstract-declarator ')'
674    //
675    // or part of a function-style cast expression:
676    //
677    //     simple-type-specifier '(' expression-list[opt] ')'
678    //
679
680    // simple-type-specifier:
681
682  case tok::kw_char:
683  case tok::kw_wchar_t:
684  case tok::kw_bool:
685  case tok::kw_short:
686  case tok::kw_int:
687  case tok::kw_long:
688  case tok::kw_signed:
689  case tok::kw_unsigned:
690  case tok::kw_float:
691  case tok::kw_double:
692  case tok::kw_void:
693  case tok::annot_typename:
694    if (NextToken().is(tok::l_paren))
695      return TPResult::Ambiguous();
696
697    return TPResult::True();
698
699  // GNU typeof support.
700  case tok::kw_typeof: {
701    if (NextToken().isNot(tok::l_paren))
702      return TPResult::True();
703
704    TentativeParsingAction PA(*this);
705
706    TPResult TPR = TryParseTypeofSpecifier();
707    bool isFollowedByParen = Tok.is(tok::l_paren);
708
709    PA.Revert();
710
711    if (TPR == TPResult::Error())
712      return TPResult::Error();
713
714    if (isFollowedByParen)
715      return TPResult::Ambiguous();
716
717    return TPResult::True();
718  }
719
720  // C++0x decltype support.
721  case tok::kw_decltype:
722    return TPResult::True();
723
724  default:
725    return TPResult::False();
726  }
727}
728
729/// [GNU] typeof-specifier:
730///         'typeof' '(' expressions ')'
731///         'typeof' '(' type-name ')'
732///
733Parser::TPResult Parser::TryParseTypeofSpecifier() {
734  assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
735  ConsumeToken();
736
737  assert(Tok.is(tok::l_paren) && "Expected '('");
738  // Parse through the parens after 'typeof'.
739  ConsumeParen();
740  if (!SkipUntil(tok::r_paren))
741    return TPResult::Error();
742
743  return TPResult::Ambiguous();
744}
745
746Parser::TPResult Parser::TryParseDeclarationSpecifier() {
747  TPResult TPR = isCXXDeclarationSpecifier();
748  if (TPR != TPResult::Ambiguous())
749    return TPR;
750
751  if (Tok.is(tok::kw_typeof))
752    TryParseTypeofSpecifier();
753  else
754    ConsumeToken();
755
756  assert(Tok.is(tok::l_paren) && "Expected '('!");
757  return TPResult::Ambiguous();
758}
759
760/// isCXXFunctionDeclarator - Disambiguates between a function declarator or
761/// a constructor-style initializer, when parsing declaration statements.
762/// Returns true for function declarator and false for constructor-style
763/// initializer.
764/// If during the disambiguation process a parsing error is encountered,
765/// the function returns true to let the declaration parsing code handle it.
766///
767/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
768///         exception-specification[opt]
769///
770bool Parser::isCXXFunctionDeclarator(bool warnIfAmbiguous) {
771
772  // C++ 8.2p1:
773  // The ambiguity arising from the similarity between a function-style cast and
774  // a declaration mentioned in 6.8 can also occur in the context of a
775  // declaration. In that context, the choice is between a function declaration
776  // with a redundant set of parentheses around a parameter name and an object
777  // declaration with a function-style cast as the initializer. Just as for the
778  // ambiguities mentioned in 6.8, the resolution is to consider any construct
779  // that could possibly be a declaration a declaration.
780
781  TentativeParsingAction PA(*this);
782
783  ConsumeParen();
784  TPResult TPR = TryParseParameterDeclarationClause();
785  if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
786    TPR = TPResult::False();
787
788  SourceLocation TPLoc = Tok.getLocation();
789  PA.Revert();
790
791  // In case of an error, let the declaration parsing code handle it.
792  if (TPR == TPResult::Error())
793    return true;
794
795  if (TPR == TPResult::Ambiguous()) {
796    // Function declarator has precedence over constructor-style initializer.
797    // Emit a warning just in case the author intended a variable definition.
798    if (warnIfAmbiguous)
799      Diag(Tok, diag::warn_parens_disambiguated_as_function_decl)
800        << SourceRange(Tok.getLocation(), TPLoc);
801    return true;
802  }
803
804  return TPR == TPResult::True();
805}
806
807/// parameter-declaration-clause:
808///   parameter-declaration-list[opt] '...'[opt]
809///   parameter-declaration-list ',' '...'
810///
811/// parameter-declaration-list:
812///   parameter-declaration
813///   parameter-declaration-list ',' parameter-declaration
814///
815/// parameter-declaration:
816///   decl-specifier-seq declarator
817///   decl-specifier-seq declarator '=' assignment-expression
818///   decl-specifier-seq abstract-declarator[opt]
819///   decl-specifier-seq abstract-declarator[opt] '=' assignment-expression
820///
821Parser::TPResult Parser::TryParseParameterDeclarationClause() {
822
823  if (Tok.is(tok::r_paren))
824    return TPResult::True();
825
826  //   parameter-declaration-list[opt] '...'[opt]
827  //   parameter-declaration-list ',' '...'
828  //
829  // parameter-declaration-list:
830  //   parameter-declaration
831  //   parameter-declaration-list ',' parameter-declaration
832  //
833  while (1) {
834    // '...'[opt]
835    if (Tok.is(tok::ellipsis)) {
836      ConsumeToken();
837      return TPResult::True(); // '...' is a sign of a function declarator.
838    }
839
840    // decl-specifier-seq
841    TPResult TPR = TryParseDeclarationSpecifier();
842    if (TPR != TPResult::Ambiguous())
843      return TPR;
844
845    // declarator
846    // abstract-declarator[opt]
847    TPR = TryParseDeclarator(true/*mayBeAbstract*/);
848    if (TPR != TPResult::Ambiguous())
849      return TPR;
850
851    if (Tok.is(tok::equal)) {
852      // '=' assignment-expression
853      // Parse through assignment-expression.
854      tok::TokenKind StopToks[3] ={ tok::comma, tok::ellipsis, tok::r_paren };
855      if (!SkipUntil(StopToks, 3, true/*StopAtSemi*/, true/*DontConsume*/))
856        return TPResult::Error();
857    }
858
859    if (Tok.is(tok::ellipsis)) {
860      ConsumeToken();
861      return TPResult::True(); // '...' is a sign of a function declarator.
862    }
863
864    if (Tok.isNot(tok::comma))
865      break;
866    ConsumeToken(); // the comma.
867  }
868
869  return TPResult::Ambiguous();
870}
871
872/// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
873/// parsing as a function declarator.
874/// If TryParseFunctionDeclarator fully parsed the function declarator, it will
875/// return TPResult::Ambiguous(), otherwise it will return either False() or
876/// Error().
877///
878/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
879///         exception-specification[opt]
880///
881/// exception-specification:
882///   'throw' '(' type-id-list[opt] ')'
883///
884Parser::TPResult Parser::TryParseFunctionDeclarator() {
885
886  // The '(' is already parsed.
887
888  TPResult TPR = TryParseParameterDeclarationClause();
889  if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
890    TPR = TPResult::False();
891
892  if (TPR == TPResult::False() || TPR == TPResult::Error())
893    return TPR;
894
895  // Parse through the parens.
896  if (!SkipUntil(tok::r_paren))
897    return TPResult::Error();
898
899  // cv-qualifier-seq
900  while (Tok.is(tok::kw_const)    ||
901         Tok.is(tok::kw_volatile) ||
902         Tok.is(tok::kw_restrict)   )
903    ConsumeToken();
904
905  // exception-specification
906  if (Tok.is(tok::kw_throw)) {
907    ConsumeToken();
908    if (Tok.isNot(tok::l_paren))
909      return TPResult::Error();
910
911    // Parse through the parens after 'throw'.
912    ConsumeParen();
913    if (!SkipUntil(tok::r_paren))
914      return TPResult::Error();
915  }
916
917  return TPResult::Ambiguous();
918}
919
920/// '[' constant-expression[opt] ']'
921///
922Parser::TPResult Parser::TryParseBracketDeclarator() {
923  ConsumeBracket();
924  if (!SkipUntil(tok::r_square))
925    return TPResult::Error();
926
927  return TPResult::Ambiguous();
928}
929