MLIR 24.0.0git
TableGenServer.cpp
Go to the documentation of this file.
1//===- TableGenServer.cpp - TableGen Language Server ----------------------===//
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 "TableGenServer.h"
10
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"
23#include <optional>
24
25using namespace mlir;
26using llvm::Record;
27using llvm::RecordKeeper;
28using llvm::RecordVal;
29using llvm::SourceMgr;
30
31/// Returns the range of a lexical token given a SMLoc corresponding to the
32/// start of an token location. The range is computed heuristically, and
33/// supports identifier-like tokens, strings, etc.
34static SMRange convertTokenLocToRange(SMLoc loc) {
35 return lsp::convertTokenLocToRange(loc, "$");
36}
37
38/// Returns a language server uri for the given source location. `mainFileURI`
39/// corresponds to the uri for the main file of the source manager.
40static llvm::lsp::URIForFile
41getURIFromLoc(const SourceMgr &mgr, SMLoc loc,
42 const llvm::lsp::URIForFile &mainFileURI) {
43 int bufferId = mgr.FindBufferContainingLoc(loc);
44 if (bufferId == 0 || bufferId == static_cast<int>(mgr.getMainFileID()))
45 return mainFileURI;
47 llvm::lsp::URIForFile::fromFile(
48 mgr.getBufferInfo(bufferId).Buffer->getBufferIdentifier());
49 if (fileForLoc)
50 return *fileForLoc;
51 llvm::lsp::Logger::error("Failed to create URI for include file: {0}",
52 llvm::toString(fileForLoc.takeError()));
53 return mainFileURI;
54}
55
56/// Returns a language server location from the given source range.
57static llvm::lsp::Location
58getLocationFromLoc(SourceMgr &mgr, SMRange loc,
59 const llvm::lsp::URIForFile &uri) {
60 return llvm::lsp::Location(getURIFromLoc(mgr, loc.Start, uri),
61 llvm::lsp::Range(mgr, loc));
62}
63static llvm::lsp::Location
64getLocationFromLoc(SourceMgr &mgr, SMLoc loc,
65 const llvm::lsp::URIForFile &uri) {
66 return getLocationFromLoc(mgr, convertTokenLocToRange(loc), uri);
67}
68
69/// Convert the given TableGen diagnostic to the LSP form.
70static std::optional<llvm::lsp::Diagnostic>
71getLspDiagnoticFromDiag(const llvm::SMDiagnostic &diag,
72 const llvm::lsp::URIForFile &uri) {
73 auto *sourceMgr = const_cast<SourceMgr *>(diag.getSourceMgr());
74 if (!sourceMgr || !diag.getLoc().isValid())
75 return std::nullopt;
76
77 llvm::lsp::Diagnostic lspDiag;
78 lspDiag.source = "tablegen";
79 lspDiag.category = "Parse Error";
80
81 // Try to grab a file location for this diagnostic.
82 llvm::lsp::Location loc = getLocationFromLoc(*sourceMgr, diag.getLoc(), uri);
83 lspDiag.range = loc.range;
84
85 // Skip diagnostics that weren't emitted within the main file.
86 if (loc.uri != uri)
87 return std::nullopt;
88
89 // Convert the severity for the diagnostic.
90 switch (diag.getKind()) {
91 case SourceMgr::DK_Warning:
92 lspDiag.severity = llvm::lsp::DiagnosticSeverity::Warning;
93 break;
94 case SourceMgr::DK_Error:
95 lspDiag.severity = llvm::lsp::DiagnosticSeverity::Error;
96 break;
97 case SourceMgr::DK_Note:
98 // Notes are emitted separately from the main diagnostic, so we just treat
99 // them as remarks given that we can't determine the diagnostic to relate
100 // them to.
101 case SourceMgr::DK_Remark:
102 lspDiag.severity = llvm::lsp::DiagnosticSeverity::Information;
103 break;
104 }
105 lspDiag.message = diag.getMessage().str();
106
107 return lspDiag;
108}
109
110/// Get the base definition of the given record value, or nullptr if one
111/// couldn't be found.
112static std::pair<const Record *, const RecordVal *>
113getBaseValue(const Record *record, const RecordVal *value) {
114 if (value->isTemplateArg())
115 return {nullptr, nullptr};
116
117 // Find a base value for the field in the super classes of the given record.
118 // On success, `record` is updated to the new parent record.
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;
124 return newBase;
125 }
126 }
127 return nullptr;
128 };
129
130 // Try to find the lowest definition of the record value.
131 std::pair<const Record *, const RecordVal *> baseValue = {};
132 while (const RecordVal *newBase = findValueInSupers(record))
133 baseValue = {record, newBase};
134
135 // Check that the base isn't the same as the current value (e.g. if the value
136 // wasn't overridden).
137 if (!baseValue.second || baseValue.second->getLoc() == value->getLoc())
138 return {nullptr, nullptr};
139 return baseValue;
140}
141
142//===----------------------------------------------------------------------===//
143// TableGenIndex
144//===----------------------------------------------------------------------===//
145
146namespace {
147/// This class represents a single symbol definition within a TableGen index. It
148/// contains the definition of the symbol, the location of the symbol, and any
149/// recorded references.
150struct TableGenIndexSymbol {
151 TableGenIndexSymbol(const Record *record)
152 : definition(record),
153 defLoc(convertTokenLocToRange(record->getLoc().front())) {}
154 TableGenIndexSymbol(const RecordVal *value)
155 : definition(value), defLoc(convertTokenLocToRange(value->getLoc())) {}
156 virtual ~TableGenIndexSymbol() = default;
157
158 // The main definition of the symbol.
159 PointerUnion<const Record *, const RecordVal *> definition;
160
161 /// The source location of the definition.
162 SMRange defLoc;
163
164 /// The source location of the references of the definition.
165 SmallVector<SMRange> references;
166};
167/// This class represents a single record symbol.
168struct TableGenRecordSymbol : public TableGenIndexSymbol {
169 TableGenRecordSymbol(const Record *record) : TableGenIndexSymbol(record) {}
170 ~TableGenRecordSymbol() override = default;
171
172 static bool classof(const TableGenIndexSymbol *symbol) {
173 return isa<const Record *>(symbol->definition);
174 }
175
176 /// Return the value of this symbol.
177 const Record *getValue() const { return cast<const Record *>(definition); }
178};
179/// This class represents a single record value symbol.
180struct TableGenRecordValSymbol : public TableGenIndexSymbol {
181 TableGenRecordValSymbol(const Record *record, const RecordVal *value)
182 : TableGenIndexSymbol(value), record(record) {}
183 ~TableGenRecordValSymbol() override = default;
184
185 static bool classof(const TableGenIndexSymbol *symbol) {
186 return isa<const RecordVal *>(symbol->definition);
187 }
188
189 /// Return the value of this symbol.
190 const RecordVal *getValue() const {
191 return cast<const RecordVal *>(definition);
192 }
193
194 /// The parent record of this symbol.
195 const Record *record;
196};
197
198/// This class provides an index for definitions/uses within a TableGen
199/// document. It provides efficient lookup of a definition given an input source
200/// range.
201class TableGenIndex {
202public:
203 TableGenIndex() : intervalMap(allocator) {}
204
205 /// Initialize the index with the given RecordKeeper.
206 void initialize(const RecordKeeper &records);
207
208 /// Lookup a symbol for the given location. Returns nullptr if no symbol could
209 /// be found. If provided, `overlappedRange` is set to the range that the
210 /// provided `loc` overlapped with.
211 const TableGenIndexSymbol *lookup(SMLoc loc,
212 SMRange *overlappedRange = nullptr) const;
213
214private:
215 /// The type of interval map used to store source references. SMRange is
216 /// half-open, so we also need to use a half-open interval map.
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 *>>;
222
223 /// Get or insert a symbol for the given record.
224 TableGenIndexSymbol *getOrInsertDef(const Record *record) {
225 auto it = defToSymbol.try_emplace(record, nullptr);
226 if (it.second)
227 it.first->second = std::make_unique<TableGenRecordSymbol>(record);
228 return &*it.first->second;
229 }
230 /// Get or insert a symbol for the given record value.
231 TableGenIndexSymbol *getOrInsertDef(const Record *record,
232 const RecordVal *value) {
233 auto it = defToSymbol.try_emplace(value, nullptr);
234 if (it.second) {
235 it.first->second =
236 std::make_unique<TableGenRecordValSymbol>(record, value);
237 }
238 return &*it.first->second;
239 }
240
241 /// An allocator for the interval map.
242 MapT::Allocator allocator;
243
244 /// An interval map containing a corresponding definition mapped to a source
245 /// interval.
246 MapT intervalMap;
247
248 /// A mapping between definitions and their corresponding symbol.
250};
251} // namespace
252
253void TableGenIndex::initialize(const RecordKeeper &records) {
254 intervalMap.clear();
255 defToSymbol.clear();
256
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();
261
262 // If the location we got was empty, try to lex a token from the start
263 // location.
264 if (startLoc == endLoc) {
265 refLoc = convertTokenLocToRange(SMLoc::getFromPointer(startLoc));
266 startLoc = refLoc.Start.getPointer();
267 endLoc = refLoc.End.getPointer();
268
269 // If the location is still empty, bail on trying to use this reference
270 // location.
271 if (startLoc == endLoc)
272 return;
273 }
274
275 // Check to see if a symbol is already attached to this location.
276 // IntervalMap doesn't allow overlapping inserts, and we don't really
277 // want multiple symbols attached to a source location anyways. This
278 // shouldn't really happen in practice, but we should handle it gracefully.
279 if (!intervalMap.overlaps(startLoc, endLoc))
280 intervalMap.insert(startLoc, endLoc, sym);
281
282 if (!isDef)
283 sym->references.push_back(refLoc);
284 };
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, /*isDef=*/true);
290
291 // Add references to the definition.
292 for (SMLoc loc : def.getLoc().drop_front())
293 insertRef(sym, convertTokenLocToRange(loc));
294 for (SMRange loc : def.getReferenceLocs())
295 insertRef(sym, loc);
296
297 // Add definitions for any values.
298 for (const RecordVal &value : def.getValues()) {
299 auto *sym = getOrInsertDef(&def, &value);
300 insertRef(sym, sym->defLoc, /*isDef=*/true);
301 for (SMRange refLoc : def.getValueReferenceLocs(value.getNameInit()))
302 insertRef(sym, refLoc);
303 }
304 }
305}
306
307const TableGenIndexSymbol *
308TableGenIndex::lookup(SMLoc loc, SMRange *overlappedRange) const {
309 auto it = intervalMap.find(loc.getPointer());
310 if (!it.valid() || loc.getPointer() < it.start())
311 return nullptr;
312
313 if (overlappedRange) {
314 *overlappedRange = SMRange(SMLoc::getFromPointer(it.start()),
315 SMLoc::getFromPointer(it.stop()));
316 }
317 return it.value();
318}
319
320//===----------------------------------------------------------------------===//
321// TableGenTextFile
322//===----------------------------------------------------------------------===//
323
324namespace {
325/// This class represents a text file containing one or more TableGen documents.
326class TableGenTextFile {
327public:
328 TableGenTextFile(const llvm::lsp::URIForFile &uri, StringRef fileContents,
329 int64_t version,
330 const std::vector<std::string> &extraIncludeDirs,
331 std::vector<llvm::lsp::Diagnostic> &diagnostics);
332
333 /// Return the current version of this text file.
334 int64_t getVersion() const { return version; }
335
336 /// Update the file to the new version using the provided set of content
337 /// changes. Returns failure if the update was unsuccessful.
338 LogicalResult
339 update(const llvm::lsp::URIForFile &uri, int64_t newVersion,
340 ArrayRef<llvm::lsp::TextDocumentContentChangeEvent> changes,
341 std::vector<llvm::lsp::Diagnostic> &diagnostics);
342
343 //===--------------------------------------------------------------------===//
344 // Definitions and References
345 //===--------------------------------------------------------------------===//
346
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);
353
354 //===--------------------------------------------------------------------===//
355 // Document Links
356 //===--------------------------------------------------------------------===//
357
358 void getDocumentLinks(const llvm::lsp::URIForFile &uri,
359 std::vector<llvm::lsp::DocumentLink> &links);
360
361 //===--------------------------------------------------------------------===//
362 // Hover
363 //===--------------------------------------------------------------------===//
364
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);
376
377private:
378 /// Initialize the text file from the given file contents.
379 void initialize(const llvm::lsp::URIForFile &uri, int64_t newVersion,
380 std::vector<llvm::lsp::Diagnostic> &diagnostics);
381
382 /// The full string contents of the file.
383 std::string contents;
384
385 /// The version of this file.
386 int64_t version;
387
388 /// The include directories for this file.
389 std::vector<std::string> includeDirs;
390
391 /// The source manager containing the contents of the input file.
392 SourceMgr sourceMgr;
393
394 /// The record keeper containing the parsed tablegen constructs.
395 std::unique_ptr<RecordKeeper> recordKeeper;
396
397 /// The index of the parsed file.
398 TableGenIndex index;
399
400 /// The set of includes of the parsed file.
401 SmallVector<lsp::SourceMgrInclude> parsedIncludes;
402};
403} // namespace
404
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) {
410 // Build the set of include directories for this file.
411 llvm::SmallString<32> uriDirectory(uri.file());
412 llvm::sys::path::remove_filename(uriDirectory);
413 includeDirs.push_back(uriDirectory.str().str());
414 llvm::append_range(includeDirs, extraIncludeDirs);
415
416 // Initialize the file.
417 initialize(uri, version, diagnostics);
418}
419
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,
425 contents))) {
426 llvm::lsp::Logger::error("Failed to update contents of {0}", uri.file());
427 return failure();
428 }
429
430 // If the file contents were properly changed, reinitialize the text file.
431 initialize(uri, newVersion, diagnostics);
432 return success();
433}
434
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>();
441
442 // Build a buffer for this file.
443 auto memBuffer = llvm::MemoryBuffer::getMemBuffer(contents, uri.file());
444 if (!memBuffer) {
445 llvm::lsp::Logger::error("Failed to create memory buffer for file",
446 uri.file());
447 return;
448 }
449 sourceMgr.setIncludeDirs(includeDirs);
450 sourceMgr.setVirtualFileSystem(llvm::vfs::getRealFileSystem());
451 sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
452
453 // This class provides a context argument for the SourceMgr diagnostic
454 // handler.
455 struct DiagHandlerContext {
456 std::vector<llvm::lsp::Diagnostic> &diagnostics;
457 const llvm::lsp::URIForFile &uri;
458 } handlerContext{diagnostics, uri};
459
460 // Set the diagnostic handler for the tablegen source manager.
461 sourceMgr.setDiagHandler(
462 [](const llvm::SMDiagnostic &diag, void *rawHandlerContext) {
463 auto *ctx = reinterpret_cast<DiagHandlerContext *>(rawHandlerContext);
464 if (auto lspDiag = getLspDiagnoticFromDiag(diag, ctx->uri))
465 ctx->diagnostics.push_back(*lspDiag);
466 },
467 &handlerContext);
468 bool failedToParse = llvm::TableGenParseFile(sourceMgr, *recordKeeper);
469
470 // Process all of the include files.
471 lsp::gatherIncludeFiles(sourceMgr, parsedIncludes);
472 if (failedToParse)
473 return;
474
475 // If we successfully parsed the file, we can now build the index.
476 index.initialize(*recordKeeper);
477}
478
479//===----------------------------------------------------------------------===//
480// TableGenTextFile: Definitions and References
481//===----------------------------------------------------------------------===//
482
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);
488 if (!symbol)
489 return;
490
491 // If this symbol is a record value and the def position is already the def of
492 // the symbol, check to see if the value has a base definition. This allows
493 // for a "go-to-def" on a "let" to resolve the definition in the base class.
494 auto *valSym = dyn_cast<TableGenRecordValSymbol>(symbol);
495 if (valSym && lsp::contains(valSym->defLoc, posLoc)) {
496 if (auto *val = getBaseValue(valSym->record, valSym->getValue()).second) {
497 locations.push_back(getLocationFromLoc(sourceMgr, val->getLoc(), uri));
498 return;
499 }
500 }
501
502 locations.push_back(getLocationFromLoc(sourceMgr, symbol->defLoc, uri));
503}
504
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);
510 if (!symbol)
511 return;
512
513 references.push_back(getLocationFromLoc(sourceMgr, symbol->defLoc, uri));
514 for (SMRange refLoc : symbol->references)
515 references.push_back(getLocationFromLoc(sourceMgr, refLoc, uri));
516}
517
518//===--------------------------------------------------------------------===//
519// TableGenTextFile: Document Links
520//===--------------------------------------------------------------------===//
521
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);
527}
528
529//===----------------------------------------------------------------------===//
530// TableGenTextFile: Hover
531//===----------------------------------------------------------------------===//
532
533std::optional<llvm::lsp::Hover>
534TableGenTextFile::findHover(const llvm::lsp::URIForFile &uri,
535 const llvm::lsp::Position &hoverPos) {
536 // Check for a reference to an include.
537 for (const lsp::SourceMgrInclude &include : parsedIncludes)
538 if (include.range.contains(hoverPos))
539 return include.buildHover();
540
541 // Find the symbol at the given location.
542 SMRange hoverRange;
543 SMLoc posLoc = hoverPos.getAsSMLoc(sourceMgr);
544 const TableGenIndexSymbol *symbol = index.lookup(posLoc, &hoverRange);
545 if (!symbol)
546 return std::nullopt;
547
548 // Build hover for a Record.
549 if (auto *record = dyn_cast<TableGenRecordSymbol>(symbol))
550 return buildHoverForRecord(record->getValue(), hoverRange);
551
552 // Build hover for a RecordVal, which is either a template argument or a
553 // field.
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);
559}
560
561llvm::lsp::Hover
562TableGenTextFile::buildHoverForRecord(const Record *record,
563 const SMRange &hoverRange) {
564 llvm::lsp::Hover hover(llvm::lsp::Range(sourceMgr, hoverRange));
565 {
566 llvm::raw_string_ostream hoverOS(hover.contents.value);
567
568 // Format the type of record this is.
569 if (record->isClass()) {
570 hoverOS << "**class** `" << record->getName() << "`";
571 } else if (record->isAnonymous()) {
572 hoverOS << "**anonymous class**";
573 } else {
574 hoverOS << "**def** `" << record->getName() << "`";
575 }
576 hoverOS << "\n***\n";
577
578 // Check if this record has summary/description fields. These are often used
579 // to hold documentation for the record.
580 auto printAndFormatField = [&](StringRef fieldName) {
581 // Check that the record actually has the given field, and that it's a
582 // string.
583 const RecordVal *value = record->getValue(fieldName);
584 if (!value || !value->getValue())
585 return;
586 auto *stringValue = dyn_cast<llvm::StringInit>(value->getValue());
587 if (!stringValue)
588 return;
589
590 raw_indented_ostream ros(hoverOS);
591 ros.printReindented(stringValue->getValue().rtrim(" \t"));
592 hoverOS << "\n***\n";
593 };
594 printAndFormatField("summary");
595 printAndFormatField("description");
596
597 // Check for documentation in the source file.
598 if (std::optional<std::string> doc =
599 lsp::extractSourceDocComment(sourceMgr, record->getLoc().front())) {
600 hoverOS << "\n" << *doc << "\n";
601 }
602 }
603 return hover;
604}
605
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));
609 {
610 llvm::raw_string_ostream hoverOS(hover.contents.value);
611 StringRef name = value->getName().rsplit(':').second;
612
613 hoverOS << "**template arg** `" << name << "`\n***\nType: `";
614 value->getType()->print(hoverOS);
615 hoverOS << "`\n";
616 }
617 return hover;
618}
619
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));
623 {
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";
628
629 // Check for documentation in the source file.
630 if (std::optional<std::string> doc =
631 lsp::extractSourceDocComment(sourceMgr, value->getLoc())) {
632 hoverOS << "\n" << *doc << "\n";
633 hoverOS << "\n***\n";
634 }
635
636 // Check to see if there is a base value that we can use for
637 // documentation.
638 auto [baseRecord, baseValue] = getBaseValue(record, value);
639 if (baseValue) {
640 if (std::optional<std::string> doc =
641 lsp::extractSourceDocComment(sourceMgr, baseValue->getLoc())) {
642 hoverOS << "\n *From `" << baseRecord->getName() << "`*:\n\n"
643 << *doc << "\n";
644 }
645 }
646 }
647 return hover;
648}
649
650//===----------------------------------------------------------------------===//
651// TableGenServer::Impl
652//===----------------------------------------------------------------------===//
653
655 explicit Impl(const Options &options)
656 : options(options), compilationDatabase(options.compilationDatabases) {}
657
658 /// TableGen LSP options.
660
661 /// The compilation database containing additional information for files
662 /// passed to the server.
664
665 /// The files held by the server, mapped by their URI file name.
666 llvm::StringMap<std::unique_ptr<TableGenTextFile>> files;
667};
668
669//===----------------------------------------------------------------------===//
670// TableGenServer
671//===----------------------------------------------------------------------===//
672
676
677void lsp::TableGenServer::addDocument(const URIForFile &uri, StringRef contents,
678 int64_t version,
679 std::vector<Diagnostic> &diagnostics) {
680 // Build the set of additional include directories.
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);
684
685 impl->files[uri.file()] = std::make_unique<TableGenTextFile>(
686 uri, contents, version, additionalIncludeDirs, diagnostics);
687}
688
690 const URIForFile &uri, ArrayRef<TextDocumentContentChangeEvent> changes,
691 int64_t version, std::vector<Diagnostic> &diagnostics) {
692 // Check that we actually have a document for this uri.
693 auto it = impl->files.find(uri.file());
694 if (it == impl->files.end())
695 return;
696
697 // Try to update the document. If we fail, erase the file from the server. A
698 // failed updated generally means we've fallen out of sync somewhere.
699 if (failed(it->second->update(uri, version, changes, diagnostics)))
700 impl->files.erase(it);
701}
702
703std::optional<int64_t>
705 auto it = impl->files.find(uri.file());
706 if (it == impl->files.end())
707 return std::nullopt;
708
709 int64_t version = it->second->getVersion();
710 impl->files.erase(it);
711 return version;
712}
713
714void lsp::TableGenServer::getLocationsOf(const URIForFile &uri,
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);
720}
721
722void lsp::TableGenServer::findReferencesOf(const URIForFile &uri,
723 const Position &pos,
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);
728}
729
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);
735}
736
737std::optional<llvm::lsp::Hover>
738lsp::TableGenServer::findHover(const URIForFile &uri,
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);
743 return std::nullopt;
744}
return success()
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.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:734
Include the generated interface declarations.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
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.