1 //===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===// 2 // 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 /// 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_CLANG_FORMAT_UNWRAPPED_LINE_PARSER_H 17 #define LLVM_CLANG_FORMAT_UNWRAPPED_LINE_PARSER_H 18 19 #include "FormatToken.h" 20 #include "clang/Basic/IdentifierTable.h" 21 #include "clang/Format/Format.h" 22 #include <list> 23 24 namespace clang { 25 namespace format { 26 27 struct UnwrappedLineNode; 28 29 /// \brief An unwrapped line is a sequence of \c Token, that we would like to 30 /// put on a single line if there was no column limit. 31 /// 32 /// This is used as a main interface between the \c UnwrappedLineParser and the 33 /// \c UnwrappedLineFormatter. The key property is that changing the formatting 34 /// within an unwrapped line does not affect any other unwrapped lines. 35 struct UnwrappedLine { 36 UnwrappedLine(); 37 38 // FIXME: Don't use std::list here. 39 /// \brief The \c Tokens comprising this \c UnwrappedLine. 40 std::list<UnwrappedLineNode> Tokens; 41 42 /// \brief The indent level of the \c UnwrappedLine. 43 unsigned Level; 44 45 /// \brief Whether this \c UnwrappedLine is part of a preprocessor directive. 46 bool InPPDirective; 47 48 bool MustBeDeclaration; 49 }; 50 51 class UnwrappedLineConsumer { 52 public: 53 virtual ~UnwrappedLineConsumer() {} 54 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0; 55 virtual void finishRun() = 0; 56 }; 57 58 class FormatTokenSource; 59 60 class UnwrappedLineParser { 61 public: 62 UnwrappedLineParser(const FormatStyle &Style, ArrayRef<FormatToken *> Tokens, 63 UnwrappedLineConsumer &Callback); 64 65 /// Returns true in case of a structural error. 66 bool parse(); 67 68 private: 69 void reset(); 70 void parseFile(); 71 void parseLevel(bool HasOpeningBrace); 72 void parseBlock(bool MustBeDeclaration, bool AddLevel = true, 73 bool MunchSemi = true); 74 void parseChildBlock(); 75 void parsePPDirective(); 76 void parsePPDefine(); 77 void parsePPIf(bool IfDef); 78 void parsePPElIf(); 79 void parsePPElse(); 80 void parsePPEndIf(); 81 void parsePPUnknown(); 82 void parseStructuralElement(); 83 bool tryToParseBracedList(); 84 bool parseBracedList(bool ContinueOnSemicolons = false); 85 void parseParens(); 86 void parseSquare(); 87 void parseIfThenElse(); 88 void parseForOrWhileLoop(); 89 void parseDoWhile(); 90 void parseLabel(); 91 void parseCaseLabel(); 92 void parseSwitch(); 93 void parseNamespace(); 94 void parseAccessSpecifier(); 95 void parseEnum(); 96 void parseRecord(); 97 void parseObjCProtocolList(); 98 void parseObjCUntilAtEnd(); 99 void parseObjCInterfaceOrImplementation(); 100 void parseObjCProtocol(); 101 bool tryToParseLambda(); 102 bool tryToParseLambdaIntroducer(); 103 void addUnwrappedLine(); 104 bool eof() const; 105 void nextToken(); 106 void readToken(); 107 void flushComments(bool NewlineBeforeNext); 108 void pushToken(FormatToken *Tok); 109 void calculateBraceTypes(); 110 111 // Marks a conditional compilation edge (for example, an '#if', '#ifdef', 112 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes 113 // this branch either cannot be taken (for example '#if false'), or should 114 // not be taken in this round. 115 void conditionalCompilationCondition(bool Unreachable); 116 void conditionalCompilationStart(bool Unreachable); 117 void conditionalCompilationAlternative(); 118 void conditionalCompilationEnd(); 119 120 bool isOnNewLine(const FormatToken& FormatTok); 121 122 // FIXME: We are constantly running into bugs where Line.Level is incorrectly 123 // subtracted from beyond 0. Introduce a method to subtract from Line.Level 124 // and use that everywhere in the Parser. 125 std::unique_ptr<UnwrappedLine> Line; 126 127 // Comments are sorted into unwrapped lines by whether they are in the same 128 // line as the previous token, or not. If not, they belong to the next token. 129 // Since the next token might already be in a new unwrapped line, we need to 130 // store the comments belonging to that token. 131 SmallVector<FormatToken *, 1> CommentsBeforeNextToken; 132 FormatToken *FormatTok; 133 bool MustBreakBeforeNextToken; 134 135 // The parsed lines. Only added to through \c CurrentLines. 136 SmallVector<UnwrappedLine, 8> Lines; 137 138 // Preprocessor directives are parsed out-of-order from other unwrapped lines. 139 // Thus, we need to keep a list of preprocessor directives to be reported 140 // after an unwarpped line that has been started was finished. 141 SmallVector<UnwrappedLine, 4> PreprocessorDirectives; 142 143 // New unwrapped lines are added via CurrentLines. 144 // Usually points to \c &Lines. While parsing a preprocessor directive when 145 // there is an unfinished previous unwrapped line, will point to 146 // \c &PreprocessorDirectives. 147 SmallVectorImpl<UnwrappedLine> *CurrentLines; 148 149 // We store for each line whether it must be a declaration depending on 150 // whether we are in a compound statement or not. 151 std::vector<bool> DeclarationScopeStack; 152 153 // Will be true if we encounter an error that leads to possibily incorrect 154 // indentation levels. 155 bool StructuralError; 156 157 const FormatStyle &Style; 158 FormatTokenSource *Tokens; 159 UnwrappedLineConsumer &Callback; 160 161 // FIXME: This is a temporary measure until we have reworked the ownership 162 // of the format tokens. The goal is to have the actual tokens created and 163 // owned outside of and handed into the UnwrappedLineParser. 164 ArrayRef<FormatToken *> AllTokens; 165 166 // Represents preprocessor branch type, so we can find matching 167 // #if/#else/#endif directives. 168 enum PPBranchKind { 169 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0 170 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0 171 }; 172 173 // Keeps a stack of currently active preprocessor branching directives. 174 SmallVector<PPBranchKind, 16> PPStack; 175 176 // The \c UnwrappedLineParser re-parses the code for each combination 177 // of preprocessor branches that can be taken. 178 // To that end, we take the same branch (#if, #else, or one of the #elif 179 // branches) for each nesting level of preprocessor branches. 180 // \c PPBranchLevel stores the current nesting level of preprocessor 181 // branches during one pass over the code. 182 int PPBranchLevel; 183 184 // Contains the current branch (#if, #else or one of the #elif branches) 185 // for each nesting level. 186 SmallVector<int, 8> PPLevelBranchIndex; 187 188 // Contains the maximum number of branches at each nesting level. 189 SmallVector<int, 8> PPLevelBranchCount; 190 191 // Contains the number of branches per nesting level we are currently 192 // in while parsing a preprocessor branch sequence. 193 // This is used to update PPLevelBranchCount at the end of a branch 194 // sequence. 195 std::stack<int> PPChainBranchIndex; 196 197 friend class ScopedLineState; 198 friend class CompoundStatementIndenter; 199 }; 200 201 struct UnwrappedLineNode { 202 UnwrappedLineNode() : Tok(NULL) {} 203 UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {} 204 205 FormatToken *Tok; 206 SmallVector<UnwrappedLine, 0> Children; 207 }; 208 209 inline UnwrappedLine::UnwrappedLine() 210 : Level(0), InPPDirective(false), MustBeDeclaration(false) {} 211 212 } // end namespace format 213 } // end namespace clang 214 215 #endif // LLVM_CLANG_FORMAT_UNWRAPPED_LINE_PARSER_H 216