17#include "clang/AST/DeclBase.h"
18#include "clang/Basic/SourceLocation.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/TokenKinds.h"
21#include "clang/Tooling/Syntax/BuildTree.h"
22#include "clang/Tooling/Syntax/Nodes.h"
23#include "clang/Tooling/Syntax/TokenBufferTokenManager.h"
24#include "clang/Tooling/Syntax/Tree.h"
25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/Casting.h"
28#include "llvm/Support/Error.h"
39void addIfDistinct(
const Range &R, std::vector<Range> &Result) {
40 if (Result.empty() || Result.back() != R) {
45std::optional<FoldingRange> toFoldingRange(SourceRange SR,
46 const SourceManager &SM) {
47 const auto Begin = SM.getDecomposedLoc(SR.getBegin()),
48 End = SM.getDecomposedLoc(SR.getEnd());
52 if ((Begin.first != SM.getMainFileID()) || (End.first != SM.getMainFileID()))
55 Range.startCharacter = SM.getColumnNumber(Begin.first, Begin.second) - 1;
56 Range.startLine = SM.getLineNumber(Begin.first, Begin.second) - 1;
57 Range.endCharacter = SM.getColumnNumber(End.first, End.second) - 1;
58 Range.endLine = SM.getLineNumber(End.first, End.second) - 1;
62std::optional<FoldingRange>
63extractFoldingRange(
const syntax::Node *Node,
64 const syntax::TokenBufferTokenManager &TM) {
65 if (
const auto *Stmt = dyn_cast<syntax::CompoundStatement>(Node)) {
66 const auto *LBrace = cast_or_null<syntax::Leaf>(
67 Stmt->findChild(syntax::NodeRole::OpenParen));
71 const auto *RBrace = cast_or_null<syntax::Leaf>(
72 Stmt->findChild(syntax::NodeRole::CloseParen));
73 if (!LBrace || !RBrace)
76 const SourceLocation LBraceLocInfo =
77 TM.getToken(LBrace->getTokenKey())->endLocation(),
79 TM.getToken(RBrace->getTokenKey())->location();
80 auto Range = toFoldingRange(SourceRange(LBraceLocInfo, RBraceLocInfo),
91std::vector<FoldingRange>
92collectFoldingRanges(
const syntax::Node *Root,
93 const syntax::TokenBufferTokenManager &TM) {
94 std::queue<const syntax::Node *> Nodes;
96 std::vector<FoldingRange> Result;
97 while (!Nodes.empty()) {
98 const syntax::Node *Node = Nodes.front();
100 const auto Range = extractFoldingRange(Node, TM);
102 Result.push_back(*
Range);
103 if (
const auto *T = dyn_cast<syntax::Tree>(Node))
104 for (
const auto *NextNode =
T->getFirstChild(); NextNode;
105 NextNode = NextNode->getNextSibling())
106 Nodes.push(NextNode);
114 std::vector<Range> Ranges;
115 const auto &SM =
AST.getSourceManager();
116 const auto &LangOpts =
AST.getLangOpts();
118 auto FID = SM.getMainFileID();
121 return Offset.takeError();
126 AST.getASTContext(),
AST.getTokens(), *Offset, *Offset);
129 if (
const Decl *D = Node->ASTNode.get<Decl>()) {
130 if (llvm::isa<TranslationUnitDecl>(D)) {
136 if (!SR || SM.getFileID(SR->getBegin()) != SM.getMainFileID()) {
142 addIfDistinct(R, Ranges);
145 if (Ranges.empty()) {
150 return std::move(
Empty);
155 Head.range = std::move(Ranges.front());
158 llvm::MutableArrayRef(Ranges.data(), Ranges.size()).drop_front()) {
159 Tail->parent = std::make_unique<SelectionRange>();
164 return std::move(
Head);
173 std::vector<Token::Range> &Ranges;
177 std::vector<unsigned> Stack;
181 : Ranges(Ranges), Code(Code) {}
183 void walk(
const DirectiveTree &T) {
184 for (
const auto &C : T.Chunks)
185 std::visit(*
this, C);
192 auto Tokens = Code.tokens(D.Tokens);
195 const Token &HashToken = Tokens.front();
196 assert(HashToken.
Kind == tok::hash);
198 if (Pragma.
text() !=
"pragma")
203 if (
Value.text() ==
"region") {
206 while (T < Tokens.end() && T->Line == Pragma.
Line)
209 Stack.push_back(T->OriginalIndex);
214 if (
Value.text() ==
"endregion") {
218 unsigned StartIdx = Stack.back();
227 [[maybe_unused]] DirectiveTree Dummy;
228 for (
const auto &[_, SubTree] : C.Branches)
239 syntax::TokenBufferTokenManager TM(
AST.getTokens(),
AST.getLangOpts(),
240 AST.getSourceManager());
241 const auto *SyntaxTree = syntax::buildSyntaxTree(A, TM,
AST.getASTContext());
242 return collectFoldingRanges(SyntaxTree, TM);
248llvm::Expected<std::vector<FoldingRange>>
252 auto DirectiveStructure = DirectiveTree::parse(OrigStream);
255 std::vector<FoldingRange> Result;
257 llvm::StringLiteral Kind) {
258 if (Start.
line >= End.line)
265 FR.
kind = Kind.str();
266 Result.push_back(FR);
268 auto OriginalToken = [&](
const Token &T) {
269 return OrigStream.tokens()[T.OriginalIndex];
271 auto StartOffset = [&](
const Token &T) {
272 return OriginalToken(T).text().data() - Code.data();
274 auto StartPosition = [&](
const Token &T) {
277 auto EndOffset = [&](
const Token &T) {
278 return StartOffset(T) + OriginalToken(T).Length;
280 auto EndPosition = [&](
const Token &T) {
286 for (
const auto &R : PPRanges) {
287 auto BTok = OrigStream.tokens()[R.Begin];
288 auto ETok = OrigStream.tokens()[R.End];
289 if (ETok.Kind == tok::eof)
291 if (BTok.Line >= ETok.Line)
302 auto Preprocessed = DirectiveStructure.stripDirectives(OrigStream);
307 auto Tokens = ParseableStream.tokens();
310 for (
const auto &Tok : Tokens) {
311 if (
auto *Paired = Tok.pair()) {
314 if (Tok.Line < Paired->Line) {
316 Position End = StartPosition(*Paired);
323 auto IsBlockComment = [&](
const Token &T) {
324 assert(T.Kind == tok::comment);
325 return OriginalToken(T).Length >= 2 &&
326 Code.substr(StartOffset(T), 2) ==
"/*";
330 for (
auto *T = Tokens.begin(); T != Tokens.end();) {
331 if (T->Kind != tok::comment) {
335 Token *FirstComment = T;
338 Token *LastComment = T;
340 while (T != Tokens.end() && T->Kind == tok::comment &&
341 StartPosition(*T).line <= End.
line + 1) {
342 End = EndPosition(*T);
346 if (IsBlockComment(*FirstComment)) {
350 if (IsBlockComment(*LastComment))
358 std::vector<Token::Range> Ranges;
360 auto Ts = OrigStream.tokens();
361 for (
const auto &R : Ranges) {
362 auto End = StartPosition(Ts[R.End]);
Stores and provides access to parsed AST.
PragmaRegionFinder(std::vector< Token::Range > &Ranges, const TokenStream &Code)
void walk(const DirectiveTree &T)
void operator()(const DirectiveTree::Directive &D)
void operator()(const DirectiveTree::Code &C)
void operator()(const DirectiveTree::Conditional &C)
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
const Node * commonAncestor() const
A complete sequence of Tokens representing a source file.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
std::optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
static void lex(llvm::StringRef Code, const LangOptions &LangOpts, llvm::function_ref< void(const syntax::Token &, const SourceManager &SM)> Action)
llvm::Expected< std::vector< FoldingRange > > getFoldingRanges(ParsedAST &AST)
Returns a list of ranges whose contents might be collapsible in an editor.
std::vector< Token::Range > pairDirectiveRanges(const DirectiveTree &Tree, const TokenStream &Code)
Pairs preprocessor conditional directives and computes their token ranges.
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
llvm::Expected< SelectionRange > getSemanticRanges(ParsedAST &AST, Position Pos)
Returns the list of all interesting ranges around the Position Pos.
clang::LangOptions genericLangOpts(clang::Language Lang, clang::LangStandard::Kind Standard)
A generic lang options suitable for lexing/parsing a langage.
void chooseConditionalBranches(DirectiveTree &Tree, const TokenStream &Code)
Describes the structure of a source file, as seen by the preprocessor.
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
TokenStream cook(const TokenStream &Code, const LangOptions &LangOpts)
void pairBrackets(TokenStream &Stream)
Identifies bracket token in the stream which should be paired.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Stores information about a region of code that can be folded.
static const llvm::StringLiteral REGION_KIND
static const llvm::StringLiteral COMMENT_KIND
int line
Line position in a document (zero-based).
int character
Character offset on a line in a document (zero-based).
Position start
The range's start position.
Position end
The range's end position.
A half-open range of tokens within a stream.
A single C++ or preprocessor token.
Index OriginalIndex
Index into the original token stream (as raw-lexed from the source code).
StringRef text() const
The token text.
uint32_t Line
Zero-based line number for the start of the token.
clang::tok::TokenKind Kind
The type of token as determined by clang's lexer.
const Token & nextNC() const
Returns the next token in the stream, skipping over comments.