Path: blob/main/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.h
35233 views
//===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// This file contains the declaration of the UnwrappedLineParser,10/// which turns a stream of tokens into UnwrappedLines.11///12//===----------------------------------------------------------------------===//1314#ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H15#define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H1617#include "Macros.h"18#include <stack>1920namespace clang {21namespace format {2223struct UnwrappedLineNode;2425/// An unwrapped line is a sequence of \c Token, that we would like to26/// put on a single line if there was no column limit.27///28/// This is used as a main interface between the \c UnwrappedLineParser and the29/// \c UnwrappedLineFormatter. The key property is that changing the formatting30/// within an unwrapped line does not affect any other unwrapped lines.31struct UnwrappedLine {32UnwrappedLine() = default;3334/// The \c Tokens comprising this \c UnwrappedLine.35std::list<UnwrappedLineNode> Tokens;3637/// The indent level of the \c UnwrappedLine.38unsigned Level = 0;3940/// The \c PPBranchLevel (adjusted for header guards) if this line is a41/// \c InMacroBody line, and 0 otherwise.42unsigned PPLevel = 0;4344/// Whether this \c UnwrappedLine is part of a preprocessor directive.45bool InPPDirective = false;46/// Whether this \c UnwrappedLine is part of a pramga directive.47bool InPragmaDirective = false;48/// Whether it is part of a macro body.49bool InMacroBody = false;5051/// Nesting level of unbraced body of a control statement.52unsigned UnbracedBodyLevel = 0;5354bool MustBeDeclaration = false;5556/// Whether the parser has seen \c decltype(auto) in this line.57bool SeenDecltypeAuto = false;5859/// \c True if this line should be indented by ContinuationIndent in60/// addition to the normal indention level.61bool IsContinuation = false;6263/// If this \c UnwrappedLine closes a block in a sequence of lines,64/// \c MatchingOpeningBlockLineIndex stores the index of the corresponding65/// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be66/// \c kInvalidIndex.67size_t MatchingOpeningBlockLineIndex = kInvalidIndex;6869/// If this \c UnwrappedLine opens a block, stores the index of the70/// line with the corresponding closing brace.71size_t MatchingClosingBlockLineIndex = kInvalidIndex;7273static const size_t kInvalidIndex = -1;7475unsigned FirstStartColumn = 0;76};7778/// Interface for users of the UnwrappedLineParser to receive the parsed lines.79/// Parsing a single snippet of code can lead to multiple runs, where each80/// run is a coherent view of the file.81///82/// For example, different runs are generated:83/// - for different combinations of #if blocks84/// - when macros are involved, for the expanded code and the as-written code85///86/// Some tokens will only be visible in a subset of the runs.87/// For each run, \c UnwrappedLineParser will call \c consumeUnwrappedLine88/// for each parsed unwrapped line, and then \c finishRun to indicate89/// that the set of unwrapped lines before is one coherent view of the90/// code snippet to be formatted.91class UnwrappedLineConsumer {92public:93virtual ~UnwrappedLineConsumer() {}94virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;95virtual void finishRun() = 0;96};9798class FormatTokenSource;99100class UnwrappedLineParser {101public:102UnwrappedLineParser(SourceManager &SourceMgr, const FormatStyle &Style,103const AdditionalKeywords &Keywords,104unsigned FirstStartColumn, ArrayRef<FormatToken *> Tokens,105UnwrappedLineConsumer &Callback,106llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,107IdentifierTable &IdentTable);108109void parse();110111private:112enum class IfStmtKind {113NotIf, // Not an if statement.114IfOnly, // An if statement without the else clause.115IfElse, // An if statement followed by else but not else if.116IfElseIf // An if statement followed by else if.117};118119void reset();120void parseFile();121bool precededByCommentOrPPDirective() const;122bool parseLevel(const FormatToken *OpeningBrace = nullptr,123IfStmtKind *IfKind = nullptr,124FormatToken **IfLeftBrace = nullptr);125bool mightFitOnOneLine(UnwrappedLine &Line,126const FormatToken *OpeningBrace = nullptr) const;127FormatToken *parseBlock(bool MustBeDeclaration = false,128unsigned AddLevels = 1u, bool MunchSemi = true,129bool KeepBraces = true, IfStmtKind *IfKind = nullptr,130bool UnindentWhitesmithsBraces = false);131void parseChildBlock();132void parsePPDirective();133void parsePPDefine();134void parsePPIf(bool IfDef);135void parsePPElse();136void parsePPEndIf();137void parsePPPragma();138void parsePPUnknown();139void readTokenWithJavaScriptASI();140void parseStructuralElement(const FormatToken *OpeningBrace = nullptr,141IfStmtKind *IfKind = nullptr,142FormatToken **IfLeftBrace = nullptr,143bool *HasDoWhile = nullptr,144bool *HasLabel = nullptr);145bool tryToParseBracedList();146bool parseBracedList(bool IsAngleBracket = false, bool IsEnum = false);147bool parseParens(TokenType AmpAmpTokenType = TT_Unknown);148void parseSquare(bool LambdaIntroducer = false);149void keepAncestorBraces();150void parseUnbracedBody(bool CheckEOF = false);151void handleAttributes();152bool handleCppAttributes();153bool isBlockBegin(const FormatToken &Tok) const;154FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false,155bool IsVerilogAssert = false);156void parseTryCatch();157void parseLoopBody(bool KeepBraces, bool WrapRightBrace);158void parseForOrWhileLoop(bool HasParens = true);159void parseDoWhile();160void parseLabel(bool LeftAlignLabel = false);161void parseCaseLabel();162void parseSwitch(bool IsExpr);163void parseNamespace();164bool parseModuleImport();165void parseNew();166void parseAccessSpecifier();167bool parseEnum();168bool parseStructLike();169bool parseRequires();170void parseRequiresClause(FormatToken *RequiresToken);171void parseRequiresExpression(FormatToken *RequiresToken);172void parseConstraintExpression();173void parseJavaEnumBody();174// Parses a record (aka class) as a top level element. If ParseAsExpr is true,175// parses the record as a child block, i.e. if the class declaration is an176// expression.177void parseRecord(bool ParseAsExpr = false);178void parseObjCLightweightGenerics();179void parseObjCMethod();180void parseObjCProtocolList();181void parseObjCUntilAtEnd();182void parseObjCInterfaceOrImplementation();183bool parseObjCProtocol();184void parseJavaScriptEs6ImportExport();185void parseStatementMacro();186void parseCSharpAttribute();187// Parse a C# generic type constraint: `where T : IComparable<T>`.188// See:189// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint190void parseCSharpGenericTypeConstraint();191bool tryToParseLambda();192bool tryToParseChildBlock();193bool tryToParseLambdaIntroducer();194bool tryToParsePropertyAccessor();195void tryToParseJSFunction();196bool tryToParseSimpleAttribute();197void parseVerilogHierarchyIdentifier();198void parseVerilogSensitivityList();199// Returns the number of levels of indentation in addition to the normal 1200// level for a block, used for indenting case labels.201unsigned parseVerilogHierarchyHeader();202void parseVerilogTable();203void parseVerilogCaseLabel();204std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>205parseMacroCall();206207// Used by addUnwrappedLine to denote whether to keep or remove a level208// when resetting the line state.209enum class LineLevel { Remove, Keep };210211void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove);212bool eof() const;213// LevelDifference is the difference of levels after and before the current214// token. For example:215// - if the token is '{' and opens a block, LevelDifference is 1.216// - if the token is '}' and closes a block, LevelDifference is -1.217void nextToken(int LevelDifference = 0);218void readToken(int LevelDifference = 0);219220// Decides which comment tokens should be added to the current line and which221// should be added as comments before the next token.222//223// Comments specifies the sequence of comment tokens to analyze. They get224// either pushed to the current line or added to the comments before the next225// token.226//227// NextTok specifies the next token. A null pointer NextTok is supported, and228// signifies either the absence of a next token, or that the next token229// shouldn't be taken into account for the analysis.230void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,231const FormatToken *NextTok);232233// Adds the comment preceding the next token to unwrapped lines.234void flushComments(bool NewlineBeforeNext);235void pushToken(FormatToken *Tok);236void calculateBraceTypes(bool ExpectClassBody = false);237void setPreviousRBraceType(TokenType Type);238239// Marks a conditional compilation edge (for example, an '#if', '#ifdef',240// '#else' or merge conflict marker). If 'Unreachable' is true, assumes241// this branch either cannot be taken (for example '#if false'), or should242// not be taken in this round.243void conditionalCompilationCondition(bool Unreachable);244void conditionalCompilationStart(bool Unreachable);245void conditionalCompilationAlternative();246void conditionalCompilationEnd();247248bool isOnNewLine(const FormatToken &FormatTok);249250// Returns whether there is a macro expansion in the line, i.e. a token that251// was expanded from a macro call.252bool containsExpansion(const UnwrappedLine &Line) const;253254// Compute hash of the current preprocessor branch.255// This is used to identify the different branches, and thus track if block256// open and close in the same branch.257size_t computePPHash() const;258259bool parsingPPDirective() const { return CurrentLines != &Lines; }260261// FIXME: We are constantly running into bugs where Line.Level is incorrectly262// subtracted from beyond 0. Introduce a method to subtract from Line.Level263// and use that everywhere in the Parser.264std::unique_ptr<UnwrappedLine> Line;265266// Lines that are created by macro expansion.267// When formatting code containing macro calls, we first format the expanded268// lines to set the token types correctly. Afterwards, we format the269// reconstructed macro calls, re-using the token types determined in the first270// step.271// ExpandedLines will be reset every time we create a new LineAndExpansion272// instance once a line containing macro calls has been parsed.273SmallVector<UnwrappedLine, 8> CurrentExpandedLines;274275// Maps from the first token of a top-level UnwrappedLine that contains276// a macro call to the replacement UnwrappedLines expanded from the macro277// call.278llvm::DenseMap<FormatToken *, SmallVector<UnwrappedLine, 8>> ExpandedLines;279280// Map from the macro identifier to a line containing the full unexpanded281// macro call.282llvm::DenseMap<FormatToken *, std::unique_ptr<UnwrappedLine>> Unexpanded;283284// For recursive macro expansions, trigger reconstruction only on the285// outermost expansion.286bool InExpansion = false;287288// Set while we reconstruct a macro call.289// For reconstruction, we feed the expanded lines into the reconstructor290// until it is finished.291std::optional<MacroCallReconstructor> Reconstruct;292293// Comments are sorted into unwrapped lines by whether they are in the same294// line as the previous token, or not. If not, they belong to the next token.295// Since the next token might already be in a new unwrapped line, we need to296// store the comments belonging to that token.297SmallVector<FormatToken *, 1> CommentsBeforeNextToken;298FormatToken *FormatTok = nullptr;299bool MustBreakBeforeNextToken;300301// The parsed lines. Only added to through \c CurrentLines.302SmallVector<UnwrappedLine, 8> Lines;303304// Preprocessor directives are parsed out-of-order from other unwrapped lines.305// Thus, we need to keep a list of preprocessor directives to be reported306// after an unwrapped line that has been started was finished.307SmallVector<UnwrappedLine, 4> PreprocessorDirectives;308309// New unwrapped lines are added via CurrentLines.310// Usually points to \c &Lines. While parsing a preprocessor directive when311// there is an unfinished previous unwrapped line, will point to312// \c &PreprocessorDirectives.313SmallVectorImpl<UnwrappedLine> *CurrentLines;314315// We store for each line whether it must be a declaration depending on316// whether we are in a compound statement or not.317llvm::BitVector DeclarationScopeStack;318319const FormatStyle &Style;320bool IsCpp;321LangOptions LangOpts;322const AdditionalKeywords &Keywords;323324llvm::Regex CommentPragmasRegex;325326FormatTokenSource *Tokens;327UnwrappedLineConsumer &Callback;328329ArrayRef<FormatToken *> AllTokens;330331// Keeps a stack of the states of nested control statements (true if the332// statement contains more than some predefined number of nested statements).333SmallVector<bool, 8> NestedTooDeep;334335// Keeps a stack of the states of nested lambdas (true if the return type of336// the lambda is `decltype(auto)`).337SmallVector<bool, 4> NestedLambdas;338339// Whether the parser is parsing the body of a function whose return type is340// `decltype(auto)`.341bool IsDecltypeAutoFunction = false;342343// Represents preprocessor branch type, so we can find matching344// #if/#else/#endif directives.345enum PPBranchKind {346PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0347PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0348};349350struct PPBranch {351PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}352PPBranchKind Kind;353size_t Line;354};355356// Keeps a stack of currently active preprocessor branching directives.357SmallVector<PPBranch, 16> PPStack;358359// The \c UnwrappedLineParser re-parses the code for each combination360// of preprocessor branches that can be taken.361// To that end, we take the same branch (#if, #else, or one of the #elif362// branches) for each nesting level of preprocessor branches.363// \c PPBranchLevel stores the current nesting level of preprocessor364// branches during one pass over the code.365int PPBranchLevel;366367// Contains the current branch (#if, #else or one of the #elif branches)368// for each nesting level.369SmallVector<int, 8> PPLevelBranchIndex;370371// Contains the maximum number of branches at each nesting level.372SmallVector<int, 8> PPLevelBranchCount;373374// Contains the number of branches per nesting level we are currently375// in while parsing a preprocessor branch sequence.376// This is used to update PPLevelBranchCount at the end of a branch377// sequence.378std::stack<int> PPChainBranchIndex;379380// Include guard search state. Used to fixup preprocessor indent levels381// so that include guards do not participate in indentation.382enum IncludeGuardState {383IG_Inited, // Search started, looking for #ifndef.384IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.385IG_Defined, // Matching #define found, checking other requirements.386IG_Found, // All requirements met, need to fix indents.387IG_Rejected, // Search failed or never started.388};389390// Current state of include guard search.391IncludeGuardState IncludeGuard;392393// Points to the #ifndef condition for a potential include guard. Null unless394// IncludeGuardState == IG_IfNdefed.395FormatToken *IncludeGuardToken;396397// Contains the first start column where the source begins. This is zero for398// normal source code and may be nonzero when formatting a code fragment that399// does not start at the beginning of the file.400unsigned FirstStartColumn;401402MacroExpander Macros;403404friend class ScopedLineState;405friend class CompoundStatementIndenter;406};407408struct UnwrappedLineNode {409UnwrappedLineNode() : Tok(nullptr) {}410UnwrappedLineNode(FormatToken *Tok,411llvm::ArrayRef<UnwrappedLine> Children = {})412: Tok(Tok), Children(Children.begin(), Children.end()) {}413414FormatToken *Tok;415SmallVector<UnwrappedLine, 0> Children;416};417418std::ostream &operator<<(std::ostream &Stream, const UnwrappedLine &Line);419420} // end namespace format421} // end namespace clang422423#endif424425426