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