From 3f8da5d0910772dc1f6198916a9141bf1d5be885 Mon Sep 17 00:00:00 2001 From: Sam McCall Date: Wed, 11 Dec 2019 15:40:23 +0100 Subject: [Tooling/Syntax] Helpers to find spelled tokens touching a location. Summary: Useful when positions are used to target nodes, with before/after ambiguity. Reviewers: ilya-biryukov, kbobyrev Subscribers: cfe-commits Tags: #clang Differential Revision: https://reviews.llvm.org/D71356 --- clang/lib/Tooling/Syntax/Tokens.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'clang/lib/Tooling/Syntax/Tokens.cpp') diff --git a/clang/lib/Tooling/Syntax/Tokens.cpp b/clang/lib/Tooling/Syntax/Tokens.cpp index 5941507e086..7c7a442dff0 100644 --- a/clang/lib/Tooling/Syntax/Tokens.cpp +++ b/clang/lib/Tooling/Syntax/Tokens.cpp @@ -248,6 +248,31 @@ TokenBuffer::expansionStartingAt(const syntax::Token *Spelled) const { return E; } +llvm::ArrayRef +syntax::spelledTokensTouching(SourceLocation Loc, + const syntax::TokenBuffer &Tokens) { + assert(Loc.isFileID()); + llvm::ArrayRef All = + Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc)); + // Comparing SourceLocations is well-defined within a FileID. + auto *Right = llvm::partition_point( + All, [&](const syntax::Token &Tok) { return Tok.location() < Loc; }); + bool AcceptRight = Right != All.end() && Right->location() <= Loc; + bool AcceptLeft = Right != All.begin() && (Right - 1)->endLocation() >= Loc; + return llvm::makeArrayRef(Right - (AcceptLeft ? 1 : 0), + Right + (AcceptRight ? 1 : 0)); +} + +const syntax::Token * +syntax::spelledIdentifierTouching(SourceLocation Loc, + const syntax::TokenBuffer &Tokens) { + for (const syntax::Token &Tok : spelledTokensTouching(Loc, Tokens)) { + if (Tok.kind() == tok::identifier) + return &Tok; + } + return nullptr; +} + std::vector TokenBuffer::macroExpansions(FileID FID) const { auto FileIt = Files.find(FID); -- cgit v1.2.3