1 //===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This file contains the declaration of the UnwrappedLineParser, 11 /// which turns a stream of tokens into UnwrappedLines. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H 16 #define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H 17 18 #include "FormatToken.h" 19 #include "clang/Basic/IdentifierTable.h" 20 #include "clang/Format/Format.h" 21 #include "llvm/ADT/BitVector.h" 22 #include "llvm/Support/Regex.h" 23 #include <stack> 24 #include <vector> 25 26 namespace clang { 27 namespace format { 28 29 struct UnwrappedLineNode; 30 31 /// An unwrapped line is a sequence of \c Token, that we would like to 32 /// put on a single line if there was no column limit. 33 /// 34 /// This is used as a main interface between the \c UnwrappedLineParser and the 35 /// \c UnwrappedLineFormatter. The key property is that changing the formatting 36 /// within an unwrapped line does not affect any other unwrapped lines. 37 struct UnwrappedLine { 38 UnwrappedLine(); 39 40 /// The \c Tokens comprising this \c UnwrappedLine. 41 std::vector<UnwrappedLineNode> Tokens; 42 43 /// The indent level of the \c UnwrappedLine. 44 unsigned Level; 45 46 /// Whether this \c UnwrappedLine is part of a preprocessor directive. 47 bool InPPDirective; 48 49 bool MustBeDeclaration; 50 51 /// If this \c UnwrappedLine closes a block in a sequence of lines, 52 /// \c MatchingOpeningBlockLineIndex stores the index of the corresponding 53 /// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be 54 /// \c kInvalidIndex. 55 size_t MatchingOpeningBlockLineIndex = kInvalidIndex; 56 57 /// If this \c UnwrappedLine opens a block, stores the index of the 58 /// line with the corresponding closing brace. 59 size_t MatchingClosingBlockLineIndex = kInvalidIndex; 60 61 static const size_t kInvalidIndex = -1; 62 63 unsigned FirstStartColumn = 0; 64 }; 65 66 class UnwrappedLineConsumer { 67 public: 68 virtual ~UnwrappedLineConsumer() {} 69 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0; 70 virtual void finishRun() = 0; 71 }; 72 73 class FormatTokenSource; 74 75 class UnwrappedLineParser { 76 public: 77 UnwrappedLineParser(const FormatStyle &Style, 78 const AdditionalKeywords &Keywords, 79 unsigned FirstStartColumn, ArrayRef<FormatToken *> Tokens, 80 UnwrappedLineConsumer &Callback); 81 82 void parse(); 83 84 private: 85 enum class IfStmtKind { 86 NotIf, // Not an if statement. 87 IfOnly, // An if statement without the else clause. 88 IfElse, // An if statement followed by else but not else if. 89 IfElseIf // An if statement followed by else if. 90 }; 91 92 void reset(); 93 void parseFile(); 94 bool precededByCommentOrPPDirective() const; 95 bool parseLevel(const FormatToken *OpeningBrace, bool CanContainBracedList, 96 IfStmtKind *IfKind = nullptr, 97 TokenType NextLBracesType = TT_Unknown); 98 bool mightFitOnOneLine(UnwrappedLine &Line) const; 99 IfStmtKind parseBlock(bool MustBeDeclaration = false, unsigned AddLevels = 1u, 100 bool MunchSemi = true, bool KeepBraces = true, 101 bool UnindentWhitesmithsBraces = false, 102 bool CanContainBracedList = true, 103 TokenType NextLBracesType = TT_Unknown); 104 void parseChildBlock(bool CanContainBracedList = true, 105 TokenType NextLBracesType = TT_Unknown); 106 void parsePPDirective(); 107 void parsePPDefine(); 108 void parsePPIf(bool IfDef); 109 void parsePPElIf(); 110 void parsePPElse(); 111 void parsePPEndIf(); 112 void parsePPUnknown(); 113 void readTokenWithJavaScriptASI(); 114 void parseStructuralElement(IfStmtKind *IfKind = nullptr, 115 bool IsTopLevel = false, 116 TokenType NextLBracesType = TT_Unknown, 117 bool *HasLabel = nullptr); 118 bool tryToParseBracedList(); 119 bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false, 120 tok::TokenKind ClosingBraceKind = tok::r_brace); 121 void parseParens(TokenType AmpAmpTokenType = TT_Unknown); 122 void parseSquare(bool LambdaIntroducer = false); 123 void keepAncestorBraces(); 124 void parseUnbracedBody(bool CheckEOF = false); 125 void handleAttributes(); 126 bool handleCppAttributes(); 127 FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false); 128 void parseTryCatch(); 129 void parseLoopBody(bool KeepBraces, bool WrapRightBrace); 130 void parseForOrWhileLoop(); 131 void parseDoWhile(); 132 void parseLabel(bool LeftAlignLabel = false); 133 void parseCaseLabel(); 134 void parseSwitch(); 135 void parseNamespace(); 136 void parseModuleImport(); 137 void parseNew(); 138 void parseAccessSpecifier(); 139 bool parseEnum(); 140 bool parseStructLike(); 141 void parseConcept(); 142 bool parseRequires(); 143 void parseRequiresClause(FormatToken *RequiresToken); 144 void parseRequiresExpression(FormatToken *RequiresToken); 145 void parseConstraintExpression(); 146 void parseJavaEnumBody(); 147 // Parses a record (aka class) as a top level element. If ParseAsExpr is true, 148 // parses the record as a child block, i.e. if the class declaration is an 149 // expression. 150 void parseRecord(bool ParseAsExpr = false); 151 void parseObjCLightweightGenerics(); 152 void parseObjCMethod(); 153 void parseObjCProtocolList(); 154 void parseObjCUntilAtEnd(); 155 void parseObjCInterfaceOrImplementation(); 156 bool parseObjCProtocol(); 157 void parseJavaScriptEs6ImportExport(); 158 void parseStatementMacro(); 159 void parseCSharpAttribute(); 160 // Parse a C# generic type constraint: `where T : IComparable<T>`. 161 // See: 162 // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint 163 void parseCSharpGenericTypeConstraint(); 164 bool tryToParseLambda(); 165 bool tryToParseChildBlock(); 166 bool tryToParseLambdaIntroducer(); 167 bool tryToParsePropertyAccessor(); 168 void tryToParseJSFunction(); 169 bool tryToParseSimpleAttribute(); 170 171 // Used by addUnwrappedLine to denote whether to keep or remove a level 172 // when resetting the line state. 173 enum class LineLevel { Remove, Keep }; 174 175 void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove); 176 bool eof() const; 177 // LevelDifference is the difference of levels after and before the current 178 // token. For example: 179 // - if the token is '{' and opens a block, LevelDifference is 1. 180 // - if the token is '}' and closes a block, LevelDifference is -1. 181 void nextToken(int LevelDifference = 0); 182 void readToken(int LevelDifference = 0); 183 184 // Decides which comment tokens should be added to the current line and which 185 // should be added as comments before the next token. 186 // 187 // Comments specifies the sequence of comment tokens to analyze. They get 188 // either pushed to the current line or added to the comments before the next 189 // token. 190 // 191 // NextTok specifies the next token. A null pointer NextTok is supported, and 192 // signifies either the absence of a next token, or that the next token 193 // shouldn't be taken into accunt for the analysis. 194 void distributeComments(const SmallVectorImpl<FormatToken *> &Comments, 195 const FormatToken *NextTok); 196 197 // Adds the comment preceding the next token to unwrapped lines. 198 void flushComments(bool NewlineBeforeNext); 199 void pushToken(FormatToken *Tok); 200 void calculateBraceTypes(bool ExpectClassBody = false); 201 202 // Marks a conditional compilation edge (for example, an '#if', '#ifdef', 203 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes 204 // this branch either cannot be taken (for example '#if false'), or should 205 // not be taken in this round. 206 void conditionalCompilationCondition(bool Unreachable); 207 void conditionalCompilationStart(bool Unreachable); 208 void conditionalCompilationAlternative(); 209 void conditionalCompilationEnd(); 210 211 bool isOnNewLine(const FormatToken &FormatTok); 212 213 // Compute hash of the current preprocessor branch. 214 // This is used to identify the different branches, and thus track if block 215 // open and close in the same branch. 216 size_t computePPHash() const; 217 218 // FIXME: We are constantly running into bugs where Line.Level is incorrectly 219 // subtracted from beyond 0. Introduce a method to subtract from Line.Level 220 // and use that everywhere in the Parser. 221 std::unique_ptr<UnwrappedLine> Line; 222 223 // Comments are sorted into unwrapped lines by whether they are in the same 224 // line as the previous token, or not. If not, they belong to the next token. 225 // Since the next token might already be in a new unwrapped line, we need to 226 // store the comments belonging to that token. 227 SmallVector<FormatToken *, 1> CommentsBeforeNextToken; 228 FormatToken *FormatTok; 229 bool MustBreakBeforeNextToken; 230 231 // The parsed lines. Only added to through \c CurrentLines. 232 SmallVector<UnwrappedLine, 8> Lines; 233 234 // Preprocessor directives are parsed out-of-order from other unwrapped lines. 235 // Thus, we need to keep a list of preprocessor directives to be reported 236 // after an unwrapped line that has been started was finished. 237 SmallVector<UnwrappedLine, 4> PreprocessorDirectives; 238 239 // New unwrapped lines are added via CurrentLines. 240 // Usually points to \c &Lines. While parsing a preprocessor directive when 241 // there is an unfinished previous unwrapped line, will point to 242 // \c &PreprocessorDirectives. 243 SmallVectorImpl<UnwrappedLine> *CurrentLines; 244 245 // We store for each line whether it must be a declaration depending on 246 // whether we are in a compound statement or not. 247 llvm::BitVector DeclarationScopeStack; 248 249 const FormatStyle &Style; 250 const AdditionalKeywords &Keywords; 251 252 llvm::Regex CommentPragmasRegex; 253 254 FormatTokenSource *Tokens; 255 UnwrappedLineConsumer &Callback; 256 257 // FIXME: This is a temporary measure until we have reworked the ownership 258 // of the format tokens. The goal is to have the actual tokens created and 259 // owned outside of and handed into the UnwrappedLineParser. 260 ArrayRef<FormatToken *> AllTokens; 261 262 // Keeps a stack of the states of nested control statements (true if the 263 // statement contains more than some predefined number of nested statements). 264 SmallVector<bool, 8> NestedTooDeep; 265 266 // Represents preprocessor branch type, so we can find matching 267 // #if/#else/#endif directives. 268 enum PPBranchKind { 269 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0 270 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0 271 }; 272 273 struct PPBranch { 274 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {} 275 PPBranchKind Kind; 276 size_t Line; 277 }; 278 279 // Keeps a stack of currently active preprocessor branching directives. 280 SmallVector<PPBranch, 16> PPStack; 281 282 // The \c UnwrappedLineParser re-parses the code for each combination 283 // of preprocessor branches that can be taken. 284 // To that end, we take the same branch (#if, #else, or one of the #elif 285 // branches) for each nesting level of preprocessor branches. 286 // \c PPBranchLevel stores the current nesting level of preprocessor 287 // branches during one pass over the code. 288 int PPBranchLevel; 289 290 // Contains the current branch (#if, #else or one of the #elif branches) 291 // for each nesting level. 292 SmallVector<int, 8> PPLevelBranchIndex; 293 294 // Contains the maximum number of branches at each nesting level. 295 SmallVector<int, 8> PPLevelBranchCount; 296 297 // Contains the number of branches per nesting level we are currently 298 // in while parsing a preprocessor branch sequence. 299 // This is used to update PPLevelBranchCount at the end of a branch 300 // sequence. 301 std::stack<int> PPChainBranchIndex; 302 303 // Include guard search state. Used to fixup preprocessor indent levels 304 // so that include guards do not participate in indentation. 305 enum IncludeGuardState { 306 IG_Inited, // Search started, looking for #ifndef. 307 IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition. 308 IG_Defined, // Matching #define found, checking other requirements. 309 IG_Found, // All requirements met, need to fix indents. 310 IG_Rejected, // Search failed or never started. 311 }; 312 313 // Current state of include guard search. 314 IncludeGuardState IncludeGuard; 315 316 // Points to the #ifndef condition for a potential include guard. Null unless 317 // IncludeGuardState == IG_IfNdefed. 318 FormatToken *IncludeGuardToken; 319 320 // Contains the first start column where the source begins. This is zero for 321 // normal source code and may be nonzero when formatting a code fragment that 322 // does not start at the beginning of the file. 323 unsigned FirstStartColumn; 324 325 friend class ScopedLineState; 326 friend class CompoundStatementIndenter; 327 }; 328 329 struct UnwrappedLineNode { 330 UnwrappedLineNode() : Tok(nullptr) {} 331 UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {} 332 333 FormatToken *Tok; 334 SmallVector<UnwrappedLine, 0> Children; 335 }; 336 337 inline UnwrappedLine::UnwrappedLine() 338 : Level(0), InPPDirective(false), MustBeDeclaration(false), 339 MatchingOpeningBlockLineIndex(kInvalidIndex) {} 340 341 } // end namespace format 342 } // end namespace clang 343 344 #endif 345