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.
113   SelectionTree ST = SelectionTree::createRight(
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.
136     SelectionRange Empty;
137     Empty.range.start = Empty.range.end = Pos;
138     return std::move(Empty);
139   }
140 
141   // Convert to the LSP linked-list representation.
142   SelectionRange Head;
143   Head.range = std::move(Ranges.front());
144   SelectionRange *Tail = &Head;
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) {
160   syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(), AST.getTokens());
161   const auto *SyntaxTree = syntax::buildSyntaxTree(A, AST.getASTContext());
162   return collectFoldingRanges(SyntaxTree, AST.getSourceManager());
163 }
164 
165 } // namespace clangd
166 } // namespace clang
167