1259701Sdim//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
2259701Sdim//
3259701Sdim//                     The LLVM Compiler Infrastructure
4259701Sdim//
5259701Sdim// This file is distributed under the University of Illinois Open Source
6259701Sdim// License. See LICENSE.TXT for details.
7259701Sdim//
8259701Sdim//===----------------------------------------------------------------------===//
9259701Sdim///
10259701Sdim/// \file
11259701Sdim/// \brief This file contains the declaration of the FormatToken, a wrapper
12259701Sdim/// around Token with additional information related to formatting.
13259701Sdim///
14259701Sdim//===----------------------------------------------------------------------===//
15259701Sdim
16259701Sdim#ifndef LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
17259701Sdim#define LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
18259701Sdim
19259701Sdim#include "clang/Basic/OperatorPrecedence.h"
20259701Sdim#include "clang/Format/Format.h"
21259701Sdim#include "clang/Lex/Lexer.h"
22259701Sdim#include "llvm/ADT/OwningPtr.h"
23259701Sdim
24259701Sdimnamespace clang {
25259701Sdimnamespace format {
26259701Sdim
27259701Sdimenum TokenType {
28259701Sdim  TT_ArrayInitializerLSquare,
29259701Sdim  TT_ArraySubscriptLSquare,
30259701Sdim  TT_BinaryOperator,
31259701Sdim  TT_BitFieldColon,
32259701Sdim  TT_BlockComment,
33259701Sdim  TT_CastRParen,
34259701Sdim  TT_ConditionalExpr,
35259701Sdim  TT_CtorInitializerColon,
36259701Sdim  TT_CtorInitializerComma,
37259701Sdim  TT_DesignatedInitializerPeriod,
38259701Sdim  TT_DictLiteral,
39259701Sdim  TT_ImplicitStringLiteral,
40259701Sdim  TT_InlineASMColon,
41259701Sdim  TT_InheritanceColon,
42259701Sdim  TT_FunctionTypeLParen,
43259701Sdim  TT_LambdaLSquare,
44259701Sdim  TT_LineComment,
45259701Sdim  TT_ObjCBlockLParen,
46259701Sdim  TT_ObjCDecl,
47259701Sdim  TT_ObjCForIn,
48259701Sdim  TT_ObjCMethodExpr,
49259701Sdim  TT_ObjCMethodSpecifier,
50259701Sdim  TT_ObjCProperty,
51259701Sdim  TT_ObjCSelectorName,
52259701Sdim  TT_OverloadedOperator,
53259701Sdim  TT_OverloadedOperatorLParen,
54259701Sdim  TT_PointerOrReference,
55259701Sdim  TT_PureVirtualSpecifier,
56259701Sdim  TT_RangeBasedForLoopColon,
57259701Sdim  TT_StartOfName,
58259701Sdim  TT_TemplateCloser,
59259701Sdim  TT_TemplateOpener,
60259701Sdim  TT_TrailingReturnArrow,
61259701Sdim  TT_TrailingUnaryOperator,
62259701Sdim  TT_UnaryOperator,
63259701Sdim  TT_Unknown
64259701Sdim};
65259701Sdim
66259701Sdim// Represents what type of block a set of braces open.
67259701Sdimenum BraceBlockKind {
68259701Sdim  BK_Unknown,
69259701Sdim  BK_Block,
70259701Sdim  BK_BracedInit
71259701Sdim};
72259701Sdim
73259701Sdim// The packing kind of a function's parameters.
74259701Sdimenum ParameterPackingKind {
75259701Sdim  PPK_BinPacked,
76259701Sdim  PPK_OnePerLine,
77259701Sdim  PPK_Inconclusive
78259701Sdim};
79259701Sdim
80259701Sdimenum FormatDecision {
81259701Sdim  FD_Unformatted,
82259701Sdim  FD_Continue,
83259701Sdim  FD_Break
84259701Sdim};
85259701Sdim
86259701Sdimclass TokenRole;
87259701Sdimclass AnnotatedLine;
88259701Sdim
89259701Sdim/// \brief A wrapper around a \c Token storing information about the
90259701Sdim/// whitespace characters preceeding it.
91259701Sdimstruct FormatToken {
92259701Sdim  FormatToken()
93259701Sdim      : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
94259701Sdim        ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
95259701Sdim        IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
96259701Sdim        BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
97259701Sdim        CanBreakBefore(false), ClosesTemplateDeclaration(false),
98259701Sdim        ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
99259701Sdim        UnbreakableTailLength(0), BindingStrength(0), SplitPenalty(0),
100259701Sdim        LongestObjCSelectorName(0), FakeRParens(0),
101259701Sdim        StartsBinaryExpression(false), EndsBinaryExpression(false),
102259701Sdim        LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
103259701Sdim        MatchingParen(NULL), Previous(NULL), Next(NULL),
104259701Sdim        Decision(FD_Unformatted), Finalized(false) {}
105259701Sdim
106259701Sdim  /// \brief The \c Token.
107259701Sdim  Token Tok;
108259701Sdim
109259701Sdim  /// \brief The number of newlines immediately before the \c Token.
110259701Sdim  ///
111259701Sdim  /// This can be used to determine what the user wrote in the original code
112259701Sdim  /// and thereby e.g. leave an empty line between two function definitions.
113259701Sdim  unsigned NewlinesBefore;
114259701Sdim
115259701Sdim  /// \brief Whether there is at least one unescaped newline before the \c
116259701Sdim  /// Token.
117259701Sdim  bool HasUnescapedNewline;
118259701Sdim
119259701Sdim  /// \brief The range of the whitespace immediately preceeding the \c Token.
120259701Sdim  SourceRange WhitespaceRange;
121259701Sdim
122259701Sdim  /// \brief The offset just past the last '\n' in this token's leading
123259701Sdim  /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
124259701Sdim  unsigned LastNewlineOffset;
125259701Sdim
126259701Sdim  /// \brief The width of the non-whitespace parts of the token (or its first
127259701Sdim  /// line for multi-line tokens) in columns.
128259701Sdim  /// We need this to correctly measure number of columns a token spans.
129259701Sdim  unsigned ColumnWidth;
130259701Sdim
131259701Sdim  /// \brief Contains the width in columns of the last line of a multi-line
132259701Sdim  /// token.
133259701Sdim  unsigned LastLineColumnWidth;
134259701Sdim
135259701Sdim  /// \brief Whether the token text contains newlines (escaped or not).
136259701Sdim  bool IsMultiline;
137259701Sdim
138259701Sdim  /// \brief Indicates that this is the first token.
139259701Sdim  bool IsFirst;
140259701Sdim
141259701Sdim  /// \brief Whether there must be a line break before this token.
142259701Sdim  ///
143259701Sdim  /// This happens for example when a preprocessor directive ended directly
144259701Sdim  /// before the token.
145259701Sdim  bool MustBreakBefore;
146259701Sdim
147259701Sdim  /// \brief Returns actual token start location without leading escaped
148259701Sdim  /// newlines and whitespace.
149259701Sdim  ///
150259701Sdim  /// This can be different to Tok.getLocation(), which includes leading escaped
151259701Sdim  /// newlines.
152259701Sdim  SourceLocation getStartOfNonWhitespace() const {
153259701Sdim    return WhitespaceRange.getEnd();
154259701Sdim  }
155259701Sdim
156259701Sdim  /// \brief The raw text of the token.
157259701Sdim  ///
158259701Sdim  /// Contains the raw token text without leading whitespace and without leading
159259701Sdim  /// escaped newlines.
160259701Sdim  StringRef TokenText;
161259701Sdim
162259701Sdim  /// \brief Set to \c true if this token is an unterminated literal.
163259701Sdim  bool IsUnterminatedLiteral;
164259701Sdim
165259701Sdim  /// \brief Contains the kind of block if this token is a brace.
166259701Sdim  BraceBlockKind BlockKind;
167259701Sdim
168259701Sdim  TokenType Type;
169259701Sdim
170259701Sdim  /// \brief The number of spaces that should be inserted before this token.
171259701Sdim  unsigned SpacesRequiredBefore;
172259701Sdim
173259701Sdim  /// \brief \c true if it is allowed to break before this token.
174259701Sdim  bool CanBreakBefore;
175259701Sdim
176259701Sdim  bool ClosesTemplateDeclaration;
177259701Sdim
178259701Sdim  /// \brief Number of parameters, if this is "(", "[" or "<".
179259701Sdim  ///
180259701Sdim  /// This is initialized to 1 as we don't need to distinguish functions with
181259701Sdim  /// 0 parameters from functions with 1 parameter. Thus, we can simply count
182259701Sdim  /// the number of commas.
183259701Sdim  unsigned ParameterCount;
184259701Sdim
185259701Sdim  /// \brief A token can have a special role that can carry extra information
186259701Sdim  /// about the token's formatting.
187259701Sdim  llvm::OwningPtr<TokenRole> Role;
188259701Sdim
189259701Sdim  /// \brief If this is an opening parenthesis, how are the parameters packed?
190259701Sdim  ParameterPackingKind PackingKind;
191259701Sdim
192259701Sdim  /// \brief The total length of the unwrapped line up to and including this
193259701Sdim  /// token.
194259701Sdim  unsigned TotalLength;
195259701Sdim
196259701Sdim  /// \brief The original 0-based column of this token, including expanded tabs.
197259701Sdim  /// The configured TabWidth is used as tab width.
198259701Sdim  unsigned OriginalColumn;
199259701Sdim
200259701Sdim  /// \brief The length of following tokens until the next natural split point,
201259701Sdim  /// or the next token that can be broken.
202259701Sdim  unsigned UnbreakableTailLength;
203259701Sdim
204259701Sdim  // FIXME: Come up with a 'cleaner' concept.
205259701Sdim  /// \brief The binding strength of a token. This is a combined value of
206259701Sdim  /// operator precedence, parenthesis nesting, etc.
207259701Sdim  unsigned BindingStrength;
208259701Sdim
209259701Sdim  /// \brief Penalty for inserting a line break before this token.
210259701Sdim  unsigned SplitPenalty;
211259701Sdim
212259701Sdim  /// \brief If this is the first ObjC selector name in an ObjC method
213259701Sdim  /// definition or call, this contains the length of the longest name.
214259701Sdim  unsigned LongestObjCSelectorName;
215259701Sdim
216259701Sdim  /// \brief Stores the number of required fake parentheses and the
217259701Sdim  /// corresponding operator precedence.
218259701Sdim  ///
219259701Sdim  /// If multiple fake parentheses start at a token, this vector stores them in
220259701Sdim  /// reverse order, i.e. inner fake parenthesis first.
221259701Sdim  SmallVector<prec::Level, 4> FakeLParens;
222259701Sdim  /// \brief Insert this many fake ) after this token for correct indentation.
223259701Sdim  unsigned FakeRParens;
224259701Sdim
225259701Sdim  /// \brief \c true if this token starts a binary expression, i.e. has at least
226259701Sdim  /// one fake l_paren with a precedence greater than prec::Unknown.
227259701Sdim  bool StartsBinaryExpression;
228259701Sdim  /// \brief \c true if this token ends a binary expression.
229259701Sdim  bool EndsBinaryExpression;
230259701Sdim
231259701Sdim  /// \brief Is this the last "." or "->" in a builder-type call?
232259701Sdim  bool LastInChainOfCalls;
233259701Sdim
234259701Sdim  /// \brief Is this token part of a \c DeclStmt defining multiple variables?
235259701Sdim  ///
236259701Sdim  /// Only set if \c Type == \c TT_StartOfName.
237259701Sdim  bool PartOfMultiVariableDeclStmt;
238259701Sdim
239259701Sdim  bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
240259701Sdim
241259701Sdim  bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
242259701Sdim    return is(K1) || is(K2);
243259701Sdim  }
244259701Sdim
245259701Sdim  bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
246259701Sdim    return is(K1) || is(K2) || is(K3);
247259701Sdim  }
248259701Sdim
249259701Sdim  bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
250259701Sdim               tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
251259701Sdim               tok::TokenKind K6 = tok::NUM_TOKENS,
252259701Sdim               tok::TokenKind K7 = tok::NUM_TOKENS,
253259701Sdim               tok::TokenKind K8 = tok::NUM_TOKENS,
254259701Sdim               tok::TokenKind K9 = tok::NUM_TOKENS,
255259701Sdim               tok::TokenKind K10 = tok::NUM_TOKENS,
256259701Sdim               tok::TokenKind K11 = tok::NUM_TOKENS,
257259701Sdim               tok::TokenKind K12 = tok::NUM_TOKENS) const {
258259701Sdim    return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
259259701Sdim           is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
260259701Sdim  }
261259701Sdim
262259701Sdim  bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
263259701Sdim
264259701Sdim  bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
265259701Sdim    return Tok.isObjCAtKeyword(Kind);
266259701Sdim  }
267259701Sdim
268259701Sdim  bool isAccessSpecifier(bool ColonRequired = true) const {
269259701Sdim    return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
270259701Sdim           (!ColonRequired || (Next && Next->is(tok::colon)));
271259701Sdim  }
272259701Sdim
273259701Sdim  bool isObjCAccessSpecifier() const {
274259701Sdim    return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
275259701Sdim                                   Next->isObjCAtKeyword(tok::objc_protected) ||
276259701Sdim                                   Next->isObjCAtKeyword(tok::objc_package) ||
277259701Sdim                                   Next->isObjCAtKeyword(tok::objc_private));
278259701Sdim  }
279259701Sdim
280259701Sdim  /// \brief Returns whether \p Tok is ([{ or a template opening <.
281259701Sdim  bool opensScope() const {
282259701Sdim    return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
283259701Sdim           Type == TT_TemplateOpener;
284259701Sdim  }
285259701Sdim  /// \brief Returns whether \p Tok is )]} or a template closing >.
286259701Sdim  bool closesScope() const {
287259701Sdim    return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
288259701Sdim           Type == TT_TemplateCloser;
289259701Sdim  }
290259701Sdim
291259701Sdim  /// \brief Returns \c true if this is a "." or "->" accessing a member.
292259701Sdim  bool isMemberAccess() const {
293259701Sdim    return isOneOf(tok::arrow, tok::period) &&
294259701Sdim           Type != TT_DesignatedInitializerPeriod;
295259701Sdim  }
296259701Sdim
297259701Sdim  bool isUnaryOperator() const {
298259701Sdim    switch (Tok.getKind()) {
299259701Sdim    case tok::plus:
300259701Sdim    case tok::plusplus:
301259701Sdim    case tok::minus:
302259701Sdim    case tok::minusminus:
303259701Sdim    case tok::exclaim:
304259701Sdim    case tok::tilde:
305259701Sdim    case tok::kw_sizeof:
306259701Sdim    case tok::kw_alignof:
307259701Sdim      return true;
308259701Sdim    default:
309259701Sdim      return false;
310259701Sdim    }
311259701Sdim  }
312259701Sdim
313259701Sdim  bool isBinaryOperator() const {
314259701Sdim    // Comma is a binary operator, but does not behave as such wrt. formatting.
315259701Sdim    return getPrecedence() > prec::Comma;
316259701Sdim  }
317259701Sdim
318259701Sdim  bool isTrailingComment() const {
319259701Sdim    return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
320259701Sdim  }
321259701Sdim
322259701Sdim  prec::Level getPrecedence() const {
323259701Sdim    return getBinOpPrecedence(Tok.getKind(), true, true);
324259701Sdim  }
325259701Sdim
326259701Sdim  /// \brief Returns the previous token ignoring comments.
327259701Sdim  FormatToken *getPreviousNonComment() const {
328259701Sdim    FormatToken *Tok = Previous;
329259701Sdim    while (Tok != NULL && Tok->is(tok::comment))
330259701Sdim      Tok = Tok->Previous;
331259701Sdim    return Tok;
332259701Sdim  }
333259701Sdim
334259701Sdim  /// \brief Returns the next token ignoring comments.
335259701Sdim  const FormatToken *getNextNonComment() const {
336259701Sdim    const FormatToken *Tok = Next;
337259701Sdim    while (Tok != NULL && Tok->is(tok::comment))
338259701Sdim      Tok = Tok->Next;
339259701Sdim    return Tok;
340259701Sdim  }
341259701Sdim
342259701Sdim  /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
343259701Sdim  /// list that should be indented with a block indent.
344259701Sdim  bool opensBlockTypeList(const FormatStyle &Style) const {
345259701Sdim    return Type == TT_ArrayInitializerLSquare ||
346259701Sdim           (is(tok::l_brace) &&
347259701Sdim            (BlockKind == BK_Block || Type == TT_DictLiteral ||
348259701Sdim             !Style.Cpp11BracedListStyle));
349259701Sdim  }
350259701Sdim
351259701Sdim  /// \brief Same as opensBlockTypeList, but for the closing token.
352259701Sdim  bool closesBlockTypeList(const FormatStyle &Style) const {
353259701Sdim    return MatchingParen && MatchingParen->opensBlockTypeList(Style);
354259701Sdim  }
355259701Sdim
356259701Sdim  FormatToken *MatchingParen;
357259701Sdim
358259701Sdim  FormatToken *Previous;
359259701Sdim  FormatToken *Next;
360259701Sdim
361259701Sdim  SmallVector<AnnotatedLine *, 1> Children;
362259701Sdim
363259701Sdim  /// \brief Stores the formatting decision for the token once it was made.
364259701Sdim  FormatDecision Decision;
365259701Sdim
366259701Sdim  /// \brief If \c true, this token has been fully formatted (indented and
367259701Sdim  /// potentially re-formatted inside), and we do not allow further formatting
368259701Sdim  /// changes.
369259701Sdim  bool Finalized;
370259701Sdim
371259701Sdimprivate:
372259701Sdim  // Disallow copying.
373259701Sdim  FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
374259701Sdim  void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
375259701Sdim};
376259701Sdim
377259701Sdimclass ContinuationIndenter;
378259701Sdimstruct LineState;
379259701Sdim
380259701Sdimclass TokenRole {
381259701Sdimpublic:
382259701Sdim  TokenRole(const FormatStyle &Style) : Style(Style) {}
383259701Sdim  virtual ~TokenRole();
384259701Sdim
385259701Sdim  /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
386259701Sdim  /// this function precomputes required information for formatting.
387259701Sdim  virtual void precomputeFormattingInfos(const FormatToken *Token);
388259701Sdim
389259701Sdim  /// \brief Apply the special formatting that the given role demands.
390259701Sdim  ///
391259701Sdim  /// Continues formatting from \p State leaving indentation to \p Indenter and
392259701Sdim  /// returns the total penalty that this formatting incurs.
393259701Sdim  virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
394259701Sdim                          bool DryRun) {
395259701Sdim    return 0;
396259701Sdim  }
397259701Sdim
398259701Sdim  /// \brief Notifies the \c Role that a comma was found.
399259701Sdim  virtual void CommaFound(const FormatToken *Token) {}
400259701Sdim
401259701Sdimprotected:
402259701Sdim  const FormatStyle &Style;
403259701Sdim};
404259701Sdim
405259701Sdimclass CommaSeparatedList : public TokenRole {
406259701Sdimpublic:
407259701Sdim  CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
408259701Sdim
409259701Sdim  virtual void precomputeFormattingInfos(const FormatToken *Token);
410259701Sdim
411259701Sdim  virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
412259701Sdim                          bool DryRun);
413259701Sdim
414259701Sdim  /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
415259701Sdim  virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
416259701Sdim
417259701Sdimprivate:
418259701Sdim  /// \brief A struct that holds information on how to format a given list with
419259701Sdim  /// a specific number of columns.
420259701Sdim  struct ColumnFormat {
421259701Sdim    /// \brief The number of columns to use.
422259701Sdim    unsigned Columns;
423259701Sdim
424259701Sdim    /// \brief The total width in characters.
425259701Sdim    unsigned TotalWidth;
426259701Sdim
427259701Sdim    /// \brief The number of lines required for this format.
428259701Sdim    unsigned LineCount;
429259701Sdim
430259701Sdim    /// \brief The size of each column in characters.
431259701Sdim    SmallVector<unsigned, 8> ColumnSizes;
432259701Sdim  };
433259701Sdim
434259701Sdim  /// \brief Calculate which \c ColumnFormat fits best into
435259701Sdim  /// \p RemainingCharacters.
436259701Sdim  const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
437259701Sdim
438259701Sdim  /// \brief The ordered \c FormatTokens making up the commas of this list.
439259701Sdim  SmallVector<const FormatToken *, 8> Commas;
440259701Sdim
441259701Sdim  /// \brief The length of each of the list's items in characters including the
442259701Sdim  /// trailing comma.
443259701Sdim  SmallVector<unsigned, 8> ItemLengths;
444259701Sdim
445259701Sdim  /// \brief Precomputed formats that can be used for this list.
446259701Sdim  SmallVector<ColumnFormat, 4> Formats;
447259701Sdim};
448259701Sdim
449259701Sdim} // namespace format
450259701Sdim} // namespace clang
451259701Sdim
452259701Sdim#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
453