blob: bf3db1ea03b57d406d431492836f0d8bbe3a92d9 [file] [log] [blame]
Chandler Carruth55fc8732012-12-04 09:13:33 +00001//===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===//
Daniel Jasperbac016b2012-12-03 18:12:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file contains the declaration of the UnwrappedLineParser,
12/// which turns a stream of tokens into UnwrappedLines.
13///
Daniel Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_FORMAT_UNWRAPPED_LINE_PARSER_H
17#define LLVM_CLANG_FORMAT_UNWRAPPED_LINE_PARSER_H
18
Daniel Jasperbac016b2012-12-03 18:12:45 +000019#include "clang/Basic/IdentifierTable.h"
Alexander Kornienko15757312012-12-06 18:03:27 +000020#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000021#include "clang/Lex/Lexer.h"
Daniel Jaspercbb6c412013-01-16 09:10:19 +000022#include <list>
Daniel Jasper26f7e782013-01-08 14:56:18 +000023
Daniel Jasperbac016b2012-12-03 18:12:45 +000024namespace clang {
25namespace format {
26
27/// \brief A wrapper around a \c Token storing information about the
28/// whitespace characters preceeding it.
29struct FormatToken {
Manuel Klimeka080a182013-01-02 16:30:12 +000030 FormatToken()
Manuel Klimekad3094b2013-05-23 10:56:37 +000031 : NewlinesBefore(0), HasUnescapedNewline(false),
Daniel Jasper1eee6c42013-03-04 13:43:19 +000032 LastNewlineOffset(0), TokenLength(0), IsFirst(false),
Alexander Kornienko919398b2013-04-17 17:34:05 +000033 MustBreakBefore(false), TrailingWhiteSpaceLength(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +000034
35 /// \brief The \c Token.
36 Token Tok;
37
38 /// \brief The number of newlines immediately before the \c Token.
39 ///
40 /// This can be used to determine what the user wrote in the original code
41 /// and thereby e.g. leave an empty line between two function definitions.
42 unsigned NewlinesBefore;
43
Manuel Klimeka080a182013-01-02 16:30:12 +000044 /// \brief Whether there is at least one unescaped newline before the \c
45 /// Token.
46 bool HasUnescapedNewline;
47
Manuel Klimekad3094b2013-05-23 10:56:37 +000048 /// \brief The range of the whitespace immediately preceeding the \c Token.
49 SourceRange WhitespaceRange;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +000050
Daniel Jasper1eee6c42013-03-04 13:43:19 +000051 /// \brief The offset just past the last '\n' in this token's leading
52 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
53 unsigned LastNewlineOffset;
54
Manuel Klimek95419382013-01-07 07:56:50 +000055 /// \brief The length of the non-whitespace parts of the token. This is
56 /// necessary because we need to handle escaped newlines that are stored
57 /// with the token.
58 unsigned TokenLength;
59
Manuel Klimekf6fd00b2013-01-05 22:56:06 +000060 /// \brief Indicates that this is the first token.
61 bool IsFirst;
Daniel Jasper26f7e782013-01-08 14:56:18 +000062
Manuel Klimek526ed112013-01-09 15:25:02 +000063 /// \brief Whether there must be a line break before this token.
64 ///
65 /// This happens for example when a preprocessor directive ended directly
66 /// before the token.
67 bool MustBreakBefore;
Alexander Kornienko919398b2013-04-17 17:34:05 +000068
69 /// \brief Number of characters of trailing whitespace.
70 unsigned TrailingWhiteSpaceLength;
71
72 /// \brief Returns actual token start location without leading escaped
73 /// newlines and whitespace.
74 ///
75 /// This can be different to Tok.getLocation(), which includes leading escaped
76 /// newlines.
77 SourceLocation getStartOfNonWhitespace() const {
Manuel Klimekad3094b2013-05-23 10:56:37 +000078 return WhitespaceRange.getEnd();
Alexander Kornienko919398b2013-04-17 17:34:05 +000079 }
Daniel Jasperbac016b2012-12-03 18:12:45 +000080};
81
82/// \brief An unwrapped line is a sequence of \c Token, that we would like to
83/// put on a single line if there was no column limit.
84///
85/// This is used as a main interface between the \c UnwrappedLineParser and the
86/// \c UnwrappedLineFormatter. The key property is that changing the formatting
87/// within an unwrapped line does not affect any other unwrapped lines.
88struct UnwrappedLine {
Manuel Klimek70b03f42013-01-23 09:32:48 +000089 UnwrappedLine() : Level(0), InPPDirective(false), MustBeDeclaration(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +000090 }
91
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +000092 // FIXME: Don't use std::list here.
Daniel Jaspercbb6c412013-01-16 09:10:19 +000093 /// \brief The \c Tokens comprising this \c UnwrappedLine.
94 std::list<FormatToken> Tokens;
Daniel Jasperbac016b2012-12-03 18:12:45 +000095
96 /// \brief The indent level of the \c UnwrappedLine.
97 unsigned Level;
Manuel Klimeka080a182013-01-02 16:30:12 +000098
99 /// \brief Whether this \c UnwrappedLine is part of a preprocessor directive.
100 bool InPPDirective;
Manuel Klimek70b03f42013-01-23 09:32:48 +0000101
102 bool MustBeDeclaration;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000103};
104
105class UnwrappedLineConsumer {
106public:
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000107 virtual ~UnwrappedLineConsumer() {
108 }
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000109 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000110};
111
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000112class FormatTokenSource {
113public:
Matt Beaumont-Gay422daa12012-12-07 22:49:27 +0000114 virtual ~FormatTokenSource() {
115 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000116 virtual FormatToken getNextToken() = 0;
Manuel Klimek80829bd2013-05-23 09:41:43 +0000117
118 // FIXME: This interface will become an implementation detail of
119 // the UnwrappedLineParser once we switch to generate all tokens
120 // up-front.
121 virtual unsigned getPosition() { return 0; }
Manuel Klimeka3e21792013-05-23 10:02:51 +0000122 virtual FormatToken setPosition(unsigned Position) {
123 assert(false);
124 return FormatToken();
125 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000126};
127
Daniel Jasperbac016b2012-12-03 18:12:45 +0000128class UnwrappedLineParser {
129public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000130 UnwrappedLineParser(const FormatStyle &Style, FormatTokenSource &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000131 UnwrappedLineConsumer &Callback);
132
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000133 /// Returns true in case of a structural error.
134 bool parse();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000135
136private:
Manuel Klimek67d080d2013-04-12 14:13:36 +0000137 void parseFile();
138 void parseLevel(bool HasOpeningBrace);
139 void parseBlock(bool MustBeDeclaration, unsigned AddLevels = 1);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000140 void parsePPDirective();
Manuel Klimekd4397b92013-01-04 23:34:14 +0000141 void parsePPDefine();
Alexander Kornienko6fb46b02013-05-24 18:24:24 +0000142 void parsePPIf();
143 void parsePPIfdef();
144 void parsePPElIf();
145 void parsePPElse();
146 void parsePPEndIf();
Manuel Klimekd4397b92013-01-04 23:34:14 +0000147 void parsePPUnknown();
Manuel Klimekf0ab0a32013-01-07 14:56:16 +0000148 void parseStructuralElement();
Manuel Klimek80829bd2013-05-23 09:41:43 +0000149 bool tryToParseBracedList();
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000150 void parseBracedList();
Manuel Klimekc44ee892013-01-21 10:07:49 +0000151 void parseReturn();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000152 void parseParens();
153 void parseIfThenElse();
Alexander Kornienko2e97cfc2012-12-05 15:06:06 +0000154 void parseForOrWhileLoop();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000155 void parseDoWhile();
156 void parseLabel();
157 void parseCaseLabel();
158 void parseSwitch();
Alexander Kornienko15757312012-12-06 18:03:27 +0000159 void parseNamespace();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000160 void parseAccessSpecifier();
161 void parseEnum();
Manuel Klimek47ea7f62013-01-15 13:38:33 +0000162 void parseRecord();
Nico Weber1abe6ea2013-01-09 21:15:03 +0000163 void parseObjCProtocolList();
164 void parseObjCUntilAtEnd();
Nico Weber50767d82013-01-09 23:25:37 +0000165 void parseObjCInterfaceOrImplementation();
Nico Weber1abe6ea2013-01-09 21:15:03 +0000166 void parseObjCProtocol();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000167 void addUnwrappedLine();
168 bool eof() const;
169 void nextToken();
Manuel Klimekd4397b92013-01-04 23:34:14 +0000170 void readToken();
Manuel Klimek86721d22013-01-22 16:31:55 +0000171 void flushComments(bool NewlineBeforeNext);
172 void pushToken(const FormatToken &Tok);
Manuel Klimek80829bd2013-05-23 09:41:43 +0000173 void calculateBraceTypes();
Alexander Kornienko6fb46b02013-05-24 18:24:24 +0000174 void pushPPConditional();
Manuel Klimek80829bd2013-05-23 09:41:43 +0000175
176 // Represents what type of block a left brace opens.
177 enum LBraceState {
178 BS_Unknown,
179 BS_Block,
180 BS_BracedInit
181 };
Daniel Jasperbac016b2012-12-03 18:12:45 +0000182
Manuel Klimekc37b4d62013-01-05 22:14:16 +0000183 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
184 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
185 // and use that everywhere in the Parser.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000186 OwningPtr<UnwrappedLine> Line;
Manuel Klimek86721d22013-01-22 16:31:55 +0000187
188 // Comments are sorted into unwrapped lines by whether they are in the same
189 // line as the previous token, or not. If not, they belong to the next token.
190 // Since the next token might already be in a new unwrapped line, we need to
191 // store the comments belonging to that token.
192 SmallVector<FormatToken, 1> CommentsBeforeNextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000193 FormatToken FormatTok;
Manuel Klimek526ed112013-01-09 15:25:02 +0000194 bool MustBreakBeforeNextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000195
Manuel Klimekba287dc2013-01-18 18:24:28 +0000196 // The parsed lines. Only added to through \c CurrentLines.
Manuel Klimek525fe162013-01-18 14:04:34 +0000197 std::vector<UnwrappedLine> Lines;
198
199 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
200 // Thus, we need to keep a list of preprocessor directives to be reported
201 // after an unwarpped line that has been started was finished.
202 std::vector<UnwrappedLine> PreprocessorDirectives;
203
204 // New unwrapped lines are added via CurrentLines.
205 // Usually points to \c &Lines. While parsing a preprocessor directive when
206 // there is an unfinished previous unwrapped line, will point to
207 // \c &PreprocessorDirectives.
208 std::vector<UnwrappedLine> *CurrentLines;
209
Manuel Klimek70b03f42013-01-23 09:32:48 +0000210 // We store for each line whether it must be a declaration depending on
211 // whether we are in a compound statement or not.
212 std::vector<bool> DeclarationScopeStack;
213
Manuel Klimek67d080d2013-04-12 14:13:36 +0000214 // Will be true if we encounter an error that leads to possibily incorrect
215 // indentation levels.
216 bool StructuralError;
217
Alexander Kornienko15757312012-12-06 18:03:27 +0000218 const FormatStyle &Style;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000219 FormatTokenSource *Tokens;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000220 UnwrappedLineConsumer &Callback;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000221
Manuel Klimek80829bd2013-05-23 09:41:43 +0000222 // FIXME: This is a temporary measure until we have reworked the ownership
223 // of the format tokens. The goal is to have the actual tokens created and
224 // owned outside of and handed into the UnwrappedLineParser.
225 SmallVector<FormatToken, 16> AllTokens;
226
227 // FIXME: Currently we cannot store attributes with tokens, as we treat
228 // them as read-only; thus, we now store the brace state indexed by the
229 // position of the token in the stream (see \c AllTokens).
230 SmallVector<LBraceState, 16> LBraces;
231
Alexander Kornienko6fb46b02013-05-24 18:24:24 +0000232 // Represents preprocessor branch type, so we can find matching
233 // #if/#else/#endif directives.
234 enum PPBranchKind {
235 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
236 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
237 };
238
239 // Keeps a stack of currently active preprocessor branching directives.
240 SmallVector<PPBranchKind, 16> PPStack;
241
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000242 friend class ScopedLineState;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000243};
244
Daniel Jaspercd162382013-01-07 13:26:07 +0000245} // end namespace format
246} // end namespace clang
Daniel Jasperbac016b2012-12-03 18:12:45 +0000247
Daniel Jaspercd162382013-01-07 13:26:07 +0000248#endif // LLVM_CLANG_FORMAT_UNWRAPPED_LINE_PARSER_H