clang-tools  15.0.0git
SemanticSelection.cpp
Go to the documentation of this file.
1 //===--- SemanticSelection.cpp -----------------------------------*- 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 #include "SemanticSelection.h"
10 #include "ParsedAST.h"
11 #include "Protocol.h"
12 #include "Selection.h"
13 #include "SourceCode.h"
14 #include "clang/AST/DeclBase.h"
15 #include "clang/Basic/SourceLocation.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Tooling/Syntax/BuildTree.h"
18 #include "clang/Tooling/Syntax/Nodes.h"
19 #include "clang/Tooling/Syntax/Tree.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Error.h"
23 #include <queue>
24 #include <vector>
25 
26 namespace clang {
27 namespace clangd {
28 namespace {
29 
30 // Adds Range \p R to the Result if it is distinct from the last added Range.
31 // Assumes that only consecutive ranges can coincide.
32 void addIfDistinct(const Range &R, std::vector<Range> &Result) {
33  if (Result.empty() || Result.back() != R) {
34  Result.push_back(R);
35  }
36 }
37 
38 llvm::Optional<FoldingRange> toFoldingRange(SourceRange SR,
39  const SourceManager &SM) {
40  const auto Begin = SM.getDecomposedLoc(SR.getBegin()),
41  End = SM.getDecomposedLoc(SR.getEnd());
42  // Do not produce folding ranges if either range ends is not within the main
43  // file. Macros have their own FileID so this also checks if locations are not
44  // within the macros.
45  if ((Begin.first != SM.getMainFileID()) || (End.first != SM.getMainFileID()))
46  return llvm::None;
47  FoldingRange Range;
48  Range.startCharacter = SM.getColumnNumber(Begin.first, Begin.second) - 1;
49  Range.startLine = SM.getLineNumber(Begin.first, Begin.second) - 1;
50  Range.endCharacter = SM.getColumnNumber(End.first, End.second) - 1;
51  Range.endLine = SM.getLineNumber(End.first, End.second) - 1;
52  return Range;
53 }
54 
55 llvm::Optional<FoldingRange> extractFoldingRange(const syntax::Node *Node,
56  const SourceManager &SM) {
57  if (const auto *Stmt = dyn_cast<syntax::CompoundStatement>(Node)) {
58  const auto *LBrace = cast_or_null<syntax::Leaf>(
59  Stmt->findChild(syntax::NodeRole::OpenParen));
60  // FIXME(kirillbobyrev): This should find the last child. Compound
61  // statements have only one pair of braces so this is valid but for other
62  // node kinds it might not be correct.
63  const auto *RBrace = cast_or_null<syntax::Leaf>(
64  Stmt->findChild(syntax::NodeRole::CloseParen));
65  if (!LBrace || !RBrace)
66  return llvm::None;
67  // Fold the entire range within braces, including whitespace.
68  const SourceLocation LBraceLocInfo = LBrace->getToken()->endLocation(),
69  RBraceLocInfo = RBrace->getToken()->location();
70  auto Range = toFoldingRange(SourceRange(LBraceLocInfo, RBraceLocInfo), SM);
71  // Do not generate folding range for compound statements without any
72  // nodes and newlines.
73  if (Range && Range->startLine != Range->endLine)
74  return Range;
75  }
76  return llvm::None;
77 }
78 
79 // Traverse the tree and collect folding ranges along the way.
80 std::vector<FoldingRange> collectFoldingRanges(const syntax::Node *Root,
81  const SourceManager &SM) {
82  std::queue<const syntax::Node *> Nodes;
83  Nodes.push(Root);
84  std::vector<FoldingRange> Result;
85  while (!Nodes.empty()) {
86  const syntax::Node *Node = Nodes.front();
87  Nodes.pop();
88  const auto Range = extractFoldingRange(Node, SM);
89  if (Range)
90  Result.push_back(*Range);
91  if (const auto *T = dyn_cast<syntax::Tree>(Node))
92  for (const auto *NextNode = T->getFirstChild(); NextNode;
93  NextNode = NextNode->getNextSibling())
94  Nodes.push(NextNode);
95  }
96  return Result;
97 }
98 
99 } // namespace
100 
101 llvm::Expected<SelectionRange> getSemanticRanges(ParsedAST &AST, Position Pos) {
102  std::vector<Range> Ranges;
103  const auto &SM = AST.getSourceManager();
104  const auto &LangOpts = AST.getLangOpts();
105 
106  auto FID = SM.getMainFileID();
107  auto Offset = positionToOffset(SM.getBufferData(FID), Pos);
108  if (!Offset) {
109  return Offset.takeError();
110  }
111 
112  // Get node under the cursor.
114  AST.getASTContext(), AST.getTokens(), *Offset, *Offset);
115  for (const auto *Node = ST.commonAncestor(); Node != nullptr;
116  Node = Node->Parent) {
117  if (const Decl *D = Node->ASTNode.get<Decl>()) {
118  if (llvm::isa<TranslationUnitDecl>(D)) {
119  break;
120  }
121  }
122 
123  auto SR = toHalfOpenFileRange(SM, LangOpts, Node->ASTNode.getSourceRange());
124  if (!SR || SM.getFileID(SR->getBegin()) != SM.getMainFileID()) {
125  continue;
126  }
127  Range R;
128  R.start = sourceLocToPosition(SM, SR->getBegin());
129  R.end = sourceLocToPosition(SM, SR->getEnd());
130  addIfDistinct(R, Ranges);
131  }
132 
133  if (Ranges.empty()) {
134  // LSP provides no way to signal "the point is not within a semantic range".
135  // Return an empty range at the point.
137  Empty.range.start = Empty.range.end = Pos;
138  return std::move(Empty);
139  }
140 
141  // Convert to the LSP linked-list representation.
143  Head.range = std::move(Ranges.front());
145  for (auto &Range :
146  llvm::makeMutableArrayRef(Ranges.data(), Ranges.size()).drop_front()) {
147  Tail->parent = std::make_unique<SelectionRange>();
148  Tail = Tail->parent.get();
149  Tail->range = std::move(Range);
150  }
151 
152  return std::move(Head);
153 }
154 
155 // FIXME(kirillbobyrev): Collect comments, PP conditional regions, includes and
156 // other code regions (e.g. public/private/protected sections of classes,
157 // control flow statement bodies).
158 // Related issue: https://github.com/clangd/clangd/issues/310
159 llvm::Expected<std::vector<FoldingRange>> getFoldingRanges(ParsedAST &AST) {
161  const auto *SyntaxTree = syntax::buildSyntaxTree(A, AST.getASTContext());
162  return collectFoldingRanges(SyntaxTree, AST.getSourceManager());
163 }
164 
165 } // namespace clangd
166 } // namespace clang
Range
CharSourceRange Range
SourceRange for the file name.
Definition: IncludeOrderCheck.cpp:38
clang::clangd::Head
@ Head
Definition: FuzzyMatch.h:58
clang::clangd::getFoldingRanges
llvm::Expected< std::vector< FoldingRange > > getFoldingRanges(ParsedAST &AST)
Returns a list of ranges whose contents might be collapsible in an editor.
Definition: SemanticSelection.cpp:159
Selection.h
clang::clangd::toHalfOpenFileRange
llvm::Optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
Definition: SourceCode.cpp:421
clang::clangd::ParsedAST::getASTContext
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ParsedAST.cpp:697
Root
ASTNode Root
Definition: DumpAST.cpp:332
clang::clangd::Range::start
Position start
The range's start position.
Definition: Protocol.h:184
clang::clangd::getSemanticRanges
llvm::Expected< SelectionRange > getSemanticRanges(ParsedAST &AST, Position Pos)
Returns the list of all interesting ranges around the Position Pos.
Definition: SemanticSelection.cpp:101
clang::clangd::sourceLocToPosition
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
Definition: SourceCode.cpp:213
clang::clangd::Tail
@ Tail
Definition: FuzzyMatch.h:57
clang::clangd::ParsedAST::getLangOpts
const LangOptions & getLangOpts() const
Definition: ParsedAST.h:80
Pos
size_t Pos
Definition: NoLintDirectiveHandler.cpp:97
Protocol.h
Offset
size_t Offset
Definition: CodeComplete.cpp:1203
ns1::ns2::A
@ A
Definition: CategoricalFeature.h:3
clang::clangd::Position
Definition: Protocol.h:153
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
Decl
const FunctionDecl * Decl
Definition: AvoidBindCheck.cpp:100
clang::clangd::SelectionTree::createRight
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
Definition: Selection.cpp:1039
SemanticSelection.h
clang::clangd::positionToOffset
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
Definition: SourceCode.cpp:172
clang::clangd::Range::end
Position end
The range's end position.
Definition: Protocol.h:187
clang::clangd::SelectionTree
Definition: Selection.h:76
clang::clangd::SelectionRange
Definition: Protocol.h:1714
clang::clangd::SelectionTree::commonAncestor
const Node * commonAncestor() const
Definition: Selection.cpp:1069
SourceCode.h
clang::clangd::Empty
@ Empty
Definition: FuzzyMatch.h:42
clang::clangd::Range
Definition: Protocol.h:182
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::ParsedAST::getTokens
const syntax::TokenBuffer & getTokens() const
Tokens recorded while parsing the main file.
Definition: ParsedAST.h:106
Arena
llvm::BumpPtrAllocator Arena
Definition: Serialization.cpp:212
LangOpts
const LangOptions * LangOpts
Definition: ExtractFunction.cpp:366
clang::clangd::ParsedAST
Stores and provides access to parsed AST.
Definition: ParsedAST.h:45
clang::clangd::ParsedAST::getSourceManager
SourceManager & getSourceManager()
Definition: ParsedAST.h:73
ParsedAST.h