14#include "llvm/ADT/IntervalMap.h"
15#include "llvm/ADT/PointerUnion.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/Support/LSP/Logging.h"
18#include "llvm/Support/LSP/Protocol.h"
19#include "llvm/Support/Path.h"
20#include "llvm/Support/VirtualFileSystem.h"
21#include "llvm/TableGen/Parser.h"
22#include "llvm/TableGen/Record.h"
27using llvm::RecordKeeper;
40static llvm::lsp::URIForFile
42 const llvm::lsp::URIForFile &mainFileURI) {
43 int bufferId = mgr.FindBufferContainingLoc(loc);
44 if (bufferId == 0 || bufferId ==
static_cast<int>(mgr.getMainFileID()))
47 llvm::lsp::URIForFile::fromFile(
48 mgr.getBufferInfo(bufferId).Buffer->getBufferIdentifier());
51 llvm::lsp::Logger::error(
"Failed to create URI for include file: {0}",
52 llvm::toString(fileForLoc.takeError()));
57static llvm::lsp::Location
59 const llvm::lsp::URIForFile &uri) {
60 return llvm::lsp::Location(
getURIFromLoc(mgr, loc.Start, uri),
61 llvm::lsp::Range(mgr, loc));
63static llvm::lsp::Location
65 const llvm::lsp::URIForFile &uri) {
70static std::optional<llvm::lsp::Diagnostic>
72 const llvm::lsp::URIForFile &uri) {
73 auto *sourceMgr =
const_cast<SourceMgr *
>(
diag.getSourceMgr());
74 if (!sourceMgr || !
diag.getLoc().isValid())
77 llvm::lsp::Diagnostic lspDiag;
78 lspDiag.source =
"tablegen";
79 lspDiag.category =
"Parse Error";
83 lspDiag.range = loc.range;
90 switch (
diag.getKind()) {
91 case SourceMgr::DK_Warning:
92 lspDiag.severity = llvm::lsp::DiagnosticSeverity::Warning;
94 case SourceMgr::DK_Error:
95 lspDiag.severity = llvm::lsp::DiagnosticSeverity::Error;
97 case SourceMgr::DK_Note:
101 case SourceMgr::DK_Remark:
102 lspDiag.severity = llvm::lsp::DiagnosticSeverity::Information;
105 lspDiag.message =
diag.getMessage().str();
112static std::pair<const Record *, const RecordVal *>
114 if (value->isTemplateArg())
115 return {
nullptr,
nullptr};
119 StringRef valueName = value->getName();
120 auto findValueInSupers = [&](
const Record *&record) ->
const RecordVal * {
121 for (
const Record *parentRecord : record->getSuperClasses()) {
122 if (
auto *newBase = parentRecord->getValue(valueName)) {
123 record = parentRecord;
131 std::pair<const Record *, const RecordVal *> baseValue = {};
132 while (
const RecordVal *newBase = findValueInSupers(record))
133 baseValue = {record, newBase};
137 if (!baseValue.second || baseValue.second->getLoc() == value->getLoc())
138 return {
nullptr,
nullptr};
150struct TableGenIndexSymbol {
151 TableGenIndexSymbol(
const Record *record)
152 : definition(record),
154 TableGenIndexSymbol(
const RecordVal *value)
156 virtual ~TableGenIndexSymbol() =
default;
159 PointerUnion<const Record *, const RecordVal *> definition;
165 SmallVector<SMRange> references;
168struct TableGenRecordSymbol :
public TableGenIndexSymbol {
169 TableGenRecordSymbol(
const Record *record) : TableGenIndexSymbol(record) {}
170 ~TableGenRecordSymbol()
override =
default;
172 static bool classof(
const TableGenIndexSymbol *symbol) {
173 return isa<const Record *>(symbol->definition);
177 const Record *getValue()
const {
return cast<const Record *>(definition); }
180struct TableGenRecordValSymbol :
public TableGenIndexSymbol {
181 TableGenRecordValSymbol(
const Record *record,
const RecordVal *value)
182 : TableGenIndexSymbol(value), record(record) {}
183 ~TableGenRecordValSymbol()
override =
default;
185 static bool classof(
const TableGenIndexSymbol *symbol) {
186 return isa<const RecordVal *>(symbol->definition);
190 const RecordVal *getValue()
const {
191 return cast<const RecordVal *>(definition);
195 const Record *record;
203 TableGenIndex() : intervalMap(allocator) {}
211 const TableGenIndexSymbol *lookup(SMLoc loc,
212 SMRange *overlappedRange =
nullptr)
const;
217 using MapT = llvm::IntervalMap<
218 const char *,
const TableGenIndexSymbol *,
219 llvm::IntervalMapImpl::NodeSizer<
const char *,
220 const TableGenIndexSymbol *>::LeafSize,
221 llvm::IntervalMapHalfOpenInfo<const char *>>;
224 TableGenIndexSymbol *getOrInsertDef(
const Record *record) {
225 auto it = defToSymbol.try_emplace(record,
nullptr);
227 it.first->second = std::make_unique<TableGenRecordSymbol>(record);
228 return &*it.first->second;
231 TableGenIndexSymbol *getOrInsertDef(
const Record *record,
232 const RecordVal *value) {
233 auto it = defToSymbol.try_emplace(value,
nullptr);
236 std::make_unique<TableGenRecordValSymbol>(record, value);
238 return &*it.first->second;
242 MapT::Allocator allocator;
253void TableGenIndex::initialize(
const RecordKeeper &records) {
257 auto insertRef = [&](TableGenIndexSymbol *sym, SMRange refLoc,
258 bool isDef =
false) {
259 const char *startLoc = refLoc.Start.getPointer();
260 const char *endLoc = refLoc.End.getPointer();
264 if (startLoc == endLoc) {
266 startLoc = refLoc.Start.getPointer();
267 endLoc = refLoc.End.getPointer();
271 if (startLoc == endLoc)
279 if (!intervalMap.overlaps(startLoc, endLoc))
280 intervalMap.insert(startLoc, endLoc, sym);
283 sym->references.push_back(refLoc);
285 auto classes = llvm::make_pointee_range(records.getClasses());
286 auto defs = llvm::make_pointee_range(records.getDefs());
287 for (
const Record &def : llvm::concat<const Record>(classes, defs)) {
288 auto *sym = getOrInsertDef(&def);
289 insertRef(sym, sym->defLoc,
true);
292 for (SMLoc loc : def.getLoc().drop_front())
294 for (SMRange loc : def.getReferenceLocs())
298 for (
const RecordVal &value : def.getValues()) {
299 auto *sym = getOrInsertDef(&def, &value);
300 insertRef(sym, sym->defLoc,
true);
301 for (SMRange refLoc : def.getValueReferenceLocs(value.getNameInit()))
302 insertRef(sym, refLoc);
307const TableGenIndexSymbol *
308TableGenIndex::lookup(SMLoc loc, SMRange *overlappedRange)
const {
309 auto it = intervalMap.find(loc.getPointer());
310 if (!it.valid() || loc.getPointer() < it.start())
313 if (overlappedRange) {
314 *overlappedRange = SMRange(SMLoc::getFromPointer(it.start()),
315 SMLoc::getFromPointer(it.stop()));
326class TableGenTextFile {
328 TableGenTextFile(
const llvm::lsp::URIForFile &uri, StringRef fileContents,
330 const std::vector<std::string> &extraIncludeDirs,
331 std::vector<llvm::lsp::Diagnostic> &diagnostics);
334 int64_t getVersion()
const {
return version; }
339 update(
const llvm::lsp::URIForFile &uri, int64_t newVersion,
340 ArrayRef<llvm::lsp::TextDocumentContentChangeEvent> changes,
341 std::vector<llvm::lsp::Diagnostic> &diagnostics);
347 void getLocationsOf(
const llvm::lsp::URIForFile &uri,
348 const llvm::lsp::Position &defPos,
349 std::vector<llvm::lsp::Location> &locations);
350 void findReferencesOf(
const llvm::lsp::URIForFile &uri,
351 const llvm::lsp::Position &pos,
352 std::vector<llvm::lsp::Location> &references);
358 void getDocumentLinks(
const llvm::lsp::URIForFile &uri,
359 std::vector<llvm::lsp::DocumentLink> &links);
365 std::optional<llvm::lsp::Hover>
366 findHover(
const llvm::lsp::URIForFile &uri,
367 const llvm::lsp::Position &hoverPos);
368 llvm::lsp::Hover buildHoverForRecord(
const Record *record,
369 const SMRange &hoverRange);
370 llvm::lsp::Hover buildHoverForTemplateArg(
const Record *record,
371 const RecordVal *value,
372 const SMRange &hoverRange);
373 llvm::lsp::Hover buildHoverForField(
const Record *record,
374 const RecordVal *value,
375 const SMRange &hoverRange);
379 void initialize(
const llvm::lsp::URIForFile &uri, int64_t newVersion,
380 std::vector<llvm::lsp::Diagnostic> &diagnostics);
383 std::string contents;
389 std::vector<std::string> includeDirs;
395 std::unique_ptr<RecordKeeper> recordKeeper;
401 SmallVector<lsp::SourceMgrInclude> parsedIncludes;
405TableGenTextFile::TableGenTextFile(
406 const llvm::lsp::URIForFile &uri, StringRef fileContents, int64_t version,
407 const std::vector<std::string> &extraIncludeDirs,
408 std::vector<llvm::lsp::Diagnostic> &diagnostics)
409 : contents(fileContents.str()), version(version) {
412 llvm::sys::path::remove_filename(uriDirectory);
413 includeDirs.push_back(uriDirectory.str().str());
414 llvm::append_range(includeDirs, extraIncludeDirs);
420LogicalResult TableGenTextFile::update(
421 const llvm::lsp::URIForFile &uri,
int64_t newVersion,
423 std::vector<llvm::lsp::Diagnostic> &diagnostics) {
424 if (
failed(llvm::lsp::TextDocumentContentChangeEvent::applyTo(changes,
426 llvm::lsp::Logger::error(
"Failed to update contents of {0}", uri.file());
435void TableGenTextFile::initialize(
436 const llvm::lsp::URIForFile &uri, int64_t newVersion,
437 std::vector<llvm::lsp::Diagnostic> &diagnostics) {
438 version = newVersion;
439 sourceMgr = SourceMgr();
440 recordKeeper = std::make_unique<RecordKeeper>();
443 auto memBuffer = llvm::MemoryBuffer::getMemBuffer(contents, uri.file());
445 llvm::lsp::Logger::error(
"Failed to create memory buffer for file",
449 sourceMgr.setIncludeDirs(includeDirs);
450 sourceMgr.setVirtualFileSystem(llvm::vfs::getRealFileSystem());
451 sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
455 struct DiagHandlerContext {
456 std::vector<llvm::lsp::Diagnostic> &diagnostics;
457 const llvm::lsp::URIForFile &uri;
458 } handlerContext{diagnostics, uri};
461 sourceMgr.setDiagHandler(
462 [](
const llvm::SMDiagnostic &diag,
void *rawHandlerContext) {
463 auto *ctx =
reinterpret_cast<DiagHandlerContext *
>(rawHandlerContext);
465 ctx->diagnostics.push_back(*lspDiag);
468 bool failedToParse = llvm::TableGenParseFile(sourceMgr, *recordKeeper);
476 index.initialize(*recordKeeper);
483void TableGenTextFile::getLocationsOf(
484 const llvm::lsp::URIForFile &uri,
const llvm::lsp::Position &defPos,
485 std::vector<llvm::lsp::Location> &locations) {
486 SMLoc posLoc = defPos.getAsSMLoc(sourceMgr);
487 const TableGenIndexSymbol *symbol = index.lookup(posLoc);
494 auto *valSym = dyn_cast<TableGenRecordValSymbol>(symbol);
496 if (
auto *val =
getBaseValue(valSym->record, valSym->getValue()).second) {
505void TableGenTextFile::findReferencesOf(
506 const llvm::lsp::URIForFile &uri,
const llvm::lsp::Position &pos,
507 std::vector<llvm::lsp::Location> &references) {
508 SMLoc posLoc = pos.getAsSMLoc(sourceMgr);
509 const TableGenIndexSymbol *symbol = index.lookup(posLoc);
514 for (SMRange refLoc : symbol->references)
522void TableGenTextFile::getDocumentLinks(
523 const llvm::lsp::URIForFile &uri,
524 std::vector<llvm::lsp::DocumentLink> &links) {
525 for (
const lsp::SourceMgrInclude &include : parsedIncludes)
526 links.emplace_back(include.range, include.uri);
533std::optional<llvm::lsp::Hover>
534TableGenTextFile::findHover(
const llvm::lsp::URIForFile &uri,
535 const llvm::lsp::Position &hoverPos) {
537 for (
const lsp::SourceMgrInclude &include : parsedIncludes)
538 if (include.range.contains(hoverPos))
539 return include.buildHover();
543 SMLoc posLoc = hoverPos.getAsSMLoc(sourceMgr);
544 const TableGenIndexSymbol *symbol = index.lookup(posLoc, &hoverRange);
549 if (
auto *record = dyn_cast<TableGenRecordSymbol>(symbol))
550 return buildHoverForRecord(record->getValue(), hoverRange);
554 auto *recordVal = cast<TableGenRecordValSymbol>(symbol);
555 const RecordVal *value = recordVal->getValue();
556 if (value->isTemplateArg())
557 return buildHoverForTemplateArg(recordVal->record, value, hoverRange);
558 return buildHoverForField(recordVal->record, value, hoverRange);
562TableGenTextFile::buildHoverForRecord(
const Record *record,
563 const SMRange &hoverRange) {
564 llvm::lsp::Hover hover(llvm::lsp::Range(sourceMgr, hoverRange));
566 llvm::raw_string_ostream hoverOS(hover.contents.value);
569 if (record->isClass()) {
570 hoverOS <<
"**class** `" << record->getName() <<
"`";
571 }
else if (record->isAnonymous()) {
572 hoverOS <<
"**anonymous class**";
574 hoverOS <<
"**def** `" << record->getName() <<
"`";
576 hoverOS <<
"\n***\n";
580 auto printAndFormatField = [&](StringRef fieldName) {
583 const RecordVal *value = record->getValue(fieldName);
584 if (!value || !value->getValue())
586 auto *stringValue = dyn_cast<llvm::StringInit>(value->getValue());
590 raw_indented_ostream ros(hoverOS);
591 ros.printReindented(stringValue->getValue().rtrim(
" \t"));
592 hoverOS <<
"\n***\n";
594 printAndFormatField(
"summary");
595 printAndFormatField(
"description");
598 if (std::optional<std::string> doc =
600 hoverOS <<
"\n" << *doc <<
"\n";
606llvm::lsp::Hover TableGenTextFile::buildHoverForTemplateArg(
607 const Record *record,
const RecordVal *value,
const SMRange &hoverRange) {
608 llvm::lsp::Hover hover(llvm::lsp::Range(sourceMgr, hoverRange));
610 llvm::raw_string_ostream hoverOS(hover.contents.value);
611 StringRef name = value->getName().rsplit(
':').second;
613 hoverOS <<
"**template arg** `" << name <<
"`\n***\nType: `";
614 value->getType()->print(hoverOS);
620llvm::lsp::Hover TableGenTextFile::buildHoverForField(
621 const Record *record,
const RecordVal *value,
const SMRange &hoverRange) {
622 llvm::lsp::Hover hover(llvm::lsp::Range(sourceMgr, hoverRange));
624 llvm::raw_string_ostream hoverOS(hover.contents.value);
625 hoverOS <<
"**field** `" << value->getName() <<
"`\n***\nType: `";
626 value->getType()->print(hoverOS);
627 hoverOS <<
"`\n***\n";
630 if (std::optional<std::string> doc =
632 hoverOS <<
"\n" << *doc <<
"\n";
633 hoverOS <<
"\n***\n";
638 auto [baseRecord, baseValue] =
getBaseValue(record, value);
640 if (std::optional<std::string> doc =
642 hoverOS <<
"\n *From `" << baseRecord->getName() <<
"`*:\n\n"
666 llvm::StringMap<std::unique_ptr<TableGenTextFile>>
files;
679 std::vector<Diagnostic> &diagnostics) {
681 std::vector<std::string> additionalIncludeDirs =
impl->options.extraDirs;
682 const auto &fileInfo =
impl->compilationDatabase.getFileInfo(uri.file());
683 llvm::append_range(additionalIncludeDirs, fileInfo.includeDirs);
685 impl->files[uri.file()] = std::make_unique<TableGenTextFile>(
686 uri, contents, version, additionalIncludeDirs, diagnostics);
691 int64_t version, std::vector<Diagnostic> &diagnostics) {
693 auto it =
impl->files.find(uri.file());
694 if (it ==
impl->files.end())
699 if (failed(it->second->update(uri, version, changes, diagnostics)))
700 impl->files.erase(it);
703std::optional<int64_t>
705 auto it =
impl->files.find(uri.file());
706 if (it ==
impl->files.end())
709 int64_t version = it->second->getVersion();
710 impl->files.erase(it);
715 const Position &defPos,
716 std::vector<Location> &locations) {
717 auto fileIt =
impl->files.find(uri.file());
718 if (fileIt !=
impl->files.end())
719 fileIt->second->getLocationsOf(uri, defPos, locations);
724 std::vector<Location> &references) {
725 auto fileIt =
impl->files.find(uri.file());
726 if (fileIt !=
impl->files.end())
727 fileIt->second->findReferencesOf(uri, pos, references);
731 const URIForFile &uri, std::vector<DocumentLink> &documentLinks) {
732 auto fileIt =
impl->files.find(uri.file());
733 if (fileIt !=
impl->files.end())
734 return fileIt->second->getDocumentLinks(uri, documentLinks);
737std::optional<llvm::lsp::Hover>
739 const Position &hoverPos) {
740 auto fileIt =
impl->files.find(uri.file());
741 if (fileIt !=
impl->files.end())
742 return fileIt->second->findHover(uri, hoverPos);
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
static std::optional< lsp::Location > getLocationFromLoc(StringRef uriScheme, FileLineColLoc loc, StringRef workspaceRoot)
Returns a language server location from the given MLIR file location.
static lsp::Diagnostic getLspDiagnoticFromDiag(llvm::SourceMgr &sourceMgr, Diagnostic &diag, const lsp::URIForFile &uri, StringRef workspaceRoot)
Convert the given MLIR diagnostic to the LSP form.
static SMRange convertTokenLocToRange(SMLoc loc)
Returns the range of a lexical token given a SMLoc corresponding to the start of an token location.
static llvm::ManagedStatic< PassManagerOptions > options
static llvm::lsp::URIForFile getURIFromLoc(const SourceMgr &mgr, SMLoc loc, const llvm::lsp::URIForFile &mainFileURI)
Returns a language server uri for the given source location.
static llvm::lsp::Location getLocationFromLoc(SourceMgr &mgr, SMRange loc, const llvm::lsp::URIForFile &uri)
Returns a language server location from the given source range.
static std::pair< const Record *, const RecordVal * > getBaseValue(const Record *record, const RecordVal *value)
Get the base definition of the given record value, or nullptr if one couldn't be found.
static std::optional< llvm::lsp::Diagnostic > getLspDiagnoticFromDiag(const llvm::SMDiagnostic &diag, const llvm::lsp::URIForFile &uri)
Convert the given TableGen diagnostic to the LSP form.
static SMRange convertTokenLocToRange(SMLoc loc)
Returns the range of a lexical token given a SMLoc corresponding to the start of an token location.
This class contains a collection of compilation information for files provided to the language server...
std::optional< int64_t > removeDocument(const URIForFile &uri)
Remove the document with the given uri.
void updateDocument(const URIForFile &uri, ArrayRef< TextDocumentContentChangeEvent > changes, int64_t version, std::vector< Diagnostic > &diagnostics)
Update the document, with the provided version, at the given URI.
std::optional< Hover > findHover(const URIForFile &uri, const Position &hoverPos)
Find a hover description for the given hover position, or std::nullopt if one couldn't be found.
void getDocumentLinks(const URIForFile &uri, std::vector< DocumentLink > &documentLinks)
Return the document links referenced by the given file.
void addDocument(const URIForFile &uri, StringRef contents, int64_t version, std::vector< Diagnostic > &diagnostics)
Add the document, with the provided version, at the given URI.
void getLocationsOf(const URIForFile &uri, const Position &defPos, std::vector< Location > &locations)
Return the locations of the object pointed at by the given position.
TableGenServer(const Options &options)
void findReferencesOf(const URIForFile &uri, const Position &pos, std::vector< Location > &references)
Find all references of the object pointed at by the given position.
void gatherIncludeFiles(llvm::SourceMgr &sourceMgr, SmallVectorImpl< SourceMgrInclude > &includes)
Given a source manager, gather all of the processed include files.
bool contains(SMRange range, SMLoc loc)
Returns true if the given range contains the given source location.
std::optional< std::string > extractSourceDocComment(llvm::SourceMgr &sourceMgr, SMLoc loc)
Extract a documentation comment for the given location within the source manager.
SMRange convertTokenLocToRange(SMLoc loc, StringRef identifierChars="")
Returns the range of a lexical token given a SMLoc corresponding to the start of an token location.
Include the generated interface declarations.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Impl(const Options &options)
lsp::CompilationDatabase compilationDatabase
The compilation database containing additional information for files passed to the server.
const Options & options
TableGen LSP options.
llvm::StringMap< std::unique_ptr< TableGenTextFile > > files
The files held by the server, mapped by their URI file name.