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_LIB_FORMAT_UNWRAPPEDLINEPARSER_H 17 #define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H 18 19 #include "FormatToken.h" 20 #include "clang/Basic/IdentifierTable.h" 21 #include "clang/Format/Format.h" 22 #include "llvm/Support/Regex.h" 23 #include <list> 24 #include <stack> 25 26 namespace clang { 27 namespace format { 28 29 struct UnwrappedLineNode; 30 31 /// \brief 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 // FIXME: Don't use std::list here. 41 /// \brief The \c Tokens comprising this \c UnwrappedLine. 42 std::list<UnwrappedLineNode> Tokens; 43 44 /// \brief The indent level of the \c UnwrappedLine. 45 unsigned Level; 46 47 /// \brief Whether this \c UnwrappedLine is part of a preprocessor directive. 48 bool InPPDirective; 49 50 bool MustBeDeclaration; 51 52 /// \brief If this \c UnwrappedLine closes a block in a sequence of lines, 53 /// \c MatchingOpeningBlockLineIndex stores the index of the corresponding 54 /// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be 55 /// \c kInvalidIndex. 56 size_t MatchingOpeningBlockLineIndex; 57 58 static const size_t kInvalidIndex = -1; 59 }; 60 61 class UnwrappedLineConsumer { 62 public: 63 virtual ~UnwrappedLineConsumer() {} 64 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0; 65 virtual void finishRun() = 0; 66 }; 67 68 class FormatTokenSource; 69 70 class UnwrappedLineParser { 71 public: 72 UnwrappedLineParser(const FormatStyle &Style, 73 const AdditionalKeywords &Keywords, 74 ArrayRef<FormatToken *> Tokens, 75 UnwrappedLineConsumer &Callback); 76 77 void parse(); 78 79 private: 80 void reset(); 81 void parseFile(); 82 void parseLevel(bool HasOpeningBrace); 83 void parseBlock(bool MustBeDeclaration, bool AddLevel = true, 84 bool MunchSemi = true); 85 void parseChildBlock(); 86 void parsePPDirective(); 87 void parsePPDefine(); 88 void parsePPIf(bool IfDef); 89 void parsePPElIf(); 90 void parsePPElse(); 91 void parsePPEndIf(); 92 void parsePPUnknown(); 93 void readTokenWithJavaScriptASI(); 94 void parseStructuralElement(); 95 bool tryToParseBracedList(); 96 bool parseBracedList(bool ContinueOnSemicolons = false); 97 void parseParens(); 98 void parseSquare(); 99 void parseIfThenElse(); 100 void parseTryCatch(); 101 void parseForOrWhileLoop(); 102 void parseDoWhile(); 103 void parseLabel(); 104 void parseCaseLabel(); 105 void parseSwitch(); 106 void parseNamespace(); 107 void parseNew(); 108 void parseAccessSpecifier(); 109 bool parseEnum(); 110 void parseJavaEnumBody(); 111 // Parses a record (aka class) as a top level element. If ParseAsExpr is true, 112 // parses the record as a child block, i.e. if the class declaration is an 113 // expression. 114 void parseRecord(bool ParseAsExpr = false); 115 void parseObjCProtocolList(); 116 void parseObjCUntilAtEnd(); 117 void parseObjCInterfaceOrImplementation(); 118 void parseObjCProtocol(); 119 void parseJavaScriptEs6ImportExport(); 120 bool tryToParseLambda(); 121 bool tryToParseLambdaIntroducer(); 122 void tryToParseJSFunction(); 123 void addUnwrappedLine(); 124 bool eof() const; 125 void nextToken(); 126 const FormatToken *getPreviousToken(); 127 void readToken(); 128 129 // Decides which comment tokens should be added to the current line and which 130 // should be added as comments before the next token. 131 // 132 // Comments specifies the sequence of comment tokens to analyze. They get 133 // either pushed to the current line or added to the comments before the next 134 // token. 135 // 136 // NextTok specifies the next token. A null pointer NextTok is supported, and 137 // signifies either the absense of a next token, or that the next token 138 // shouldn't be taken into accunt for the analysis. 139 void distributeComments(const SmallVectorImpl<FormatToken *> &Comments, 140 const FormatToken *NextTok); 141 142 // Adds the comment preceding the next token to unwrapped lines. 143 void flushComments(bool NewlineBeforeNext); 144 void pushToken(FormatToken *Tok); 145 void calculateBraceTypes(bool ExpectClassBody = false); 146 147 // Marks a conditional compilation edge (for example, an '#if', '#ifdef', 148 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes 149 // this branch either cannot be taken (for example '#if false'), or should 150 // not be taken in this round. 151 void conditionalCompilationCondition(bool Unreachable); 152 void conditionalCompilationStart(bool Unreachable); 153 void conditionalCompilationAlternative(); 154 void conditionalCompilationEnd(); 155 156 bool isOnNewLine(const FormatToken &FormatTok); 157 158 // FIXME: We are constantly running into bugs where Line.Level is incorrectly 159 // subtracted from beyond 0. Introduce a method to subtract from Line.Level 160 // and use that everywhere in the Parser. 161 std::unique_ptr<UnwrappedLine> Line; 162 163 // Comments are sorted into unwrapped lines by whether they are in the same 164 // line as the previous token, or not. If not, they belong to the next token. 165 // Since the next token might already be in a new unwrapped line, we need to 166 // store the comments belonging to that token. 167 SmallVector<FormatToken *, 1> CommentsBeforeNextToken; 168 FormatToken *FormatTok; 169 bool MustBreakBeforeNextToken; 170 171 // The parsed lines. Only added to through \c CurrentLines. 172 SmallVector<UnwrappedLine, 8> Lines; 173 174 // Preprocessor directives are parsed out-of-order from other unwrapped lines. 175 // Thus, we need to keep a list of preprocessor directives to be reported 176 // after an unwarpped line that has been started was finished. 177 SmallVector<UnwrappedLine, 4> PreprocessorDirectives; 178 179 // New unwrapped lines are added via CurrentLines. 180 // Usually points to \c &Lines. While parsing a preprocessor directive when 181 // there is an unfinished previous unwrapped line, will point to 182 // \c &PreprocessorDirectives. 183 SmallVectorImpl<UnwrappedLine> *CurrentLines; 184 185 // We store for each line whether it must be a declaration depending on 186 // whether we are in a compound statement or not. 187 std::vector<bool> DeclarationScopeStack; 188 189 const FormatStyle &Style; 190 const AdditionalKeywords &Keywords; 191 192 llvm::Regex CommentPragmasRegex; 193 194 FormatTokenSource *Tokens; 195 UnwrappedLineConsumer &Callback; 196 197 // FIXME: This is a temporary measure until we have reworked the ownership 198 // of the format tokens. The goal is to have the actual tokens created and 199 // owned outside of and handed into the UnwrappedLineParser. 200 ArrayRef<FormatToken *> AllTokens; 201 202 // Represents preprocessor branch type, so we can find matching 203 // #if/#else/#endif directives. 204 enum PPBranchKind { 205 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0 206 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0 207 }; 208 209 // Keeps a stack of currently active preprocessor branching directives. 210 SmallVector<PPBranchKind, 16> PPStack; 211 212 // The \c UnwrappedLineParser re-parses the code for each combination 213 // of preprocessor branches that can be taken. 214 // To that end, we take the same branch (#if, #else, or one of the #elif 215 // branches) for each nesting level of preprocessor branches. 216 // \c PPBranchLevel stores the current nesting level of preprocessor 217 // branches during one pass over the code. 218 int PPBranchLevel; 219 220 // Contains the current branch (#if, #else or one of the #elif branches) 221 // for each nesting level. 222 SmallVector<int, 8> PPLevelBranchIndex; 223 224 // Contains the maximum number of branches at each nesting level. 225 SmallVector<int, 8> PPLevelBranchCount; 226 227 // Contains the number of branches per nesting level we are currently 228 // in while parsing a preprocessor branch sequence. 229 // This is used to update PPLevelBranchCount at the end of a branch 230 // sequence. 231 std::stack<int> PPChainBranchIndex; 232 233 friend class ScopedLineState; 234 friend class CompoundStatementIndenter; 235 }; 236 237 struct UnwrappedLineNode { 238 UnwrappedLineNode() : Tok(nullptr) {} 239 UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {} 240 241 FormatToken *Tok; 242 SmallVector<UnwrappedLine, 0> Children; 243 }; 244 245 inline UnwrappedLine::UnwrappedLine() : Level(0), InPPDirective(false), 246 MustBeDeclaration(false), MatchingOpeningBlockLineIndex(kInvalidIndex) {} 247 248 } // end namespace format 249 } // end namespace clang 250 251 #endif 252