1 //===- PDLLServer.cpp - PDLL 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 "PDLLServer.h"
10 
11 #include "../lsp-server-support/Logging.h"
12 #include "../lsp-server-support/Protocol.h"
13 #include "mlir/Tools/PDLL/AST/Context.h"
14 #include "mlir/Tools/PDLL/AST/Nodes.h"
15 #include "mlir/Tools/PDLL/AST/Types.h"
16 #include "mlir/Tools/PDLL/ODS/Constraint.h"
17 #include "mlir/Tools/PDLL/ODS/Context.h"
18 #include "mlir/Tools/PDLL/ODS/Dialect.h"
19 #include "mlir/Tools/PDLL/ODS/Operation.h"
20 #include "mlir/Tools/PDLL/Parser/CodeComplete.h"
21 #include "mlir/Tools/PDLL/Parser/Parser.h"
22 #include "llvm/ADT/IntervalMap.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/TypeSwitch.h"
25 #include "llvm/Support/Path.h"
26 
27 using namespace mlir;
28 using namespace mlir::pdll;
29 
30 /// Returns a language server uri for the given source location. `mainFileURI`
31 /// corresponds to the uri for the main file of the source manager.
32 static lsp::URIForFile getURIFromLoc(llvm::SourceMgr &mgr, SMRange loc,
33                                      const lsp::URIForFile &mainFileURI) {
34   int bufferId = mgr.FindBufferContainingLoc(loc.Start);
35   if (bufferId == 0 || bufferId == static_cast<int>(mgr.getMainFileID()))
36     return mainFileURI;
37   llvm::Expected<lsp::URIForFile> fileForLoc = lsp::URIForFile::fromFile(
38       mgr.getBufferInfo(bufferId).Buffer->getBufferIdentifier());
39   if (fileForLoc)
40     return *fileForLoc;
41   lsp::Logger::error("Failed to create URI for include file: {0}",
42                      llvm::toString(fileForLoc.takeError()));
43   return mainFileURI;
44 }
45 
46 /// Returns true if the given location is in the main file of the source
47 /// manager.
48 static bool isMainFileLoc(llvm::SourceMgr &mgr, SMRange loc) {
49   return mgr.FindBufferContainingLoc(loc.Start) == mgr.getMainFileID();
50 }
51 
52 /// Returns a language server location from the given source range.
53 static lsp::Location getLocationFromLoc(llvm::SourceMgr &mgr, SMRange range,
54                                         const lsp::URIForFile &uri) {
55   return lsp::Location(getURIFromLoc(mgr, range, uri), lsp::Range(mgr, range));
56 }
57 
58 /// Convert the given MLIR diagnostic to the LSP form.
59 static Optional<lsp::Diagnostic>
60 getLspDiagnoticFromDiag(llvm::SourceMgr &sourceMgr, const ast::Diagnostic &diag,
61                         const lsp::URIForFile &uri) {
62   lsp::Diagnostic lspDiag;
63   lspDiag.source = "pdll";
64 
65   // FIXME: Right now all of the diagnostics are treated as parser issues, but
66   // some are parser and some are verifier.
67   lspDiag.category = "Parse Error";
68 
69   // Try to grab a file location for this diagnostic.
70   lsp::Location loc = getLocationFromLoc(sourceMgr, diag.getLocation(), uri);
71   lspDiag.range = loc.range;
72 
73   // Skip diagnostics that weren't emitted within the main file.
74   if (loc.uri != uri)
75     return llvm::None;
76 
77   // Convert the severity for the diagnostic.
78   switch (diag.getSeverity()) {
79   case ast::Diagnostic::Severity::DK_Note:
80     llvm_unreachable("expected notes to be handled separately");
81   case ast::Diagnostic::Severity::DK_Warning:
82     lspDiag.severity = lsp::DiagnosticSeverity::Warning;
83     break;
84   case ast::Diagnostic::Severity::DK_Error:
85     lspDiag.severity = lsp::DiagnosticSeverity::Error;
86     break;
87   case ast::Diagnostic::Severity::DK_Remark:
88     lspDiag.severity = lsp::DiagnosticSeverity::Information;
89     break;
90   }
91   lspDiag.message = diag.getMessage().str();
92 
93   // Attach any notes to the main diagnostic as related information.
94   std::vector<lsp::DiagnosticRelatedInformation> relatedDiags;
95   for (const ast::Diagnostic &note : diag.getNotes()) {
96     relatedDiags.emplace_back(
97         getLocationFromLoc(sourceMgr, note.getLocation(), uri),
98         note.getMessage().str());
99   }
100   if (!relatedDiags.empty())
101     lspDiag.relatedInformation = std::move(relatedDiags);
102 
103   return lspDiag;
104 }
105 
106 //===----------------------------------------------------------------------===//
107 // PDLIndex
108 //===----------------------------------------------------------------------===//
109 
110 namespace {
111 struct PDLIndexSymbol {
112   explicit PDLIndexSymbol(const ast::Decl *definition)
113       : definition(definition) {}
114   explicit PDLIndexSymbol(const ods::Operation *definition)
115       : definition(definition) {}
116 
117   /// Return the location of the definition of this symbol.
118   SMRange getDefLoc() const {
119     if (const ast::Decl *decl = definition.dyn_cast<const ast::Decl *>()) {
120       const ast::Name *declName = decl->getName();
121       return declName ? declName->getLoc() : decl->getLoc();
122     }
123     return definition.get<const ods::Operation *>()->getLoc();
124   }
125 
126   /// The main definition of the symbol.
127   PointerUnion<const ast::Decl *, const ods::Operation *> definition;
128   /// The set of references to the symbol.
129   std::vector<SMRange> references;
130 };
131 
132 /// This class provides an index for definitions/uses within a PDL document.
133 /// It provides efficient lookup of a definition given an input source range.
134 class PDLIndex {
135 public:
136   PDLIndex() : intervalMap(allocator) {}
137 
138   /// Initialize the index with the given ast::Module.
139   void initialize(const ast::Module &module, const ods::Context &odsContext);
140 
141   /// Lookup a symbol for the given location. Returns nullptr if no symbol could
142   /// be found. If provided, `overlappedRange` is set to the range that the
143   /// provided `loc` overlapped with.
144   const PDLIndexSymbol *lookup(SMLoc loc,
145                                SMRange *overlappedRange = nullptr) const;
146 
147 private:
148   /// The type of interval map used to store source references. SMRange is
149   /// half-open, so we also need to use a half-open interval map.
150   using MapT =
151       llvm::IntervalMap<const char *, const PDLIndexSymbol *,
152                         llvm::IntervalMapImpl::NodeSizer<
153                             const char *, const PDLIndexSymbol *>::LeafSize,
154                         llvm::IntervalMapHalfOpenInfo<const char *>>;
155 
156   /// An allocator for the interval map.
157   MapT::Allocator allocator;
158 
159   /// An interval map containing a corresponding definition mapped to a source
160   /// interval.
161   MapT intervalMap;
162 
163   /// A mapping between definitions and their corresponding symbol.
164   DenseMap<const void *, std::unique_ptr<PDLIndexSymbol>> defToSymbol;
165 };
166 } // namespace
167 
168 void PDLIndex::initialize(const ast::Module &module,
169                           const ods::Context &odsContext) {
170   auto getOrInsertDef = [&](const auto *def) -> PDLIndexSymbol * {
171     auto it = defToSymbol.try_emplace(def, nullptr);
172     if (it.second)
173       it.first->second = std::make_unique<PDLIndexSymbol>(def);
174     return &*it.first->second;
175   };
176   auto insertDeclRef = [&](PDLIndexSymbol *sym, SMRange refLoc,
177                            bool isDef = false) {
178     const char *startLoc = refLoc.Start.getPointer();
179     const char *endLoc = refLoc.End.getPointer();
180     if (!intervalMap.overlaps(startLoc, endLoc)) {
181       intervalMap.insert(startLoc, endLoc, sym);
182       if (!isDef)
183         sym->references.push_back(refLoc);
184     }
185   };
186   auto insertODSOpRef = [&](StringRef opName, SMRange refLoc) {
187     const ods::Operation *odsOp = odsContext.lookupOperation(opName);
188     if (!odsOp)
189       return;
190 
191     PDLIndexSymbol *symbol = getOrInsertDef(odsOp);
192     insertDeclRef(symbol, odsOp->getLoc(), /*isDef=*/true);
193     insertDeclRef(symbol, refLoc);
194   };
195 
196   module.walk([&](const ast::Node *node) {
197     // Handle references to PDL decls.
198     if (const auto *decl = dyn_cast<ast::OpNameDecl>(node)) {
199       if (Optional<StringRef> name = decl->getName())
200         insertODSOpRef(*name, decl->getLoc());
201     } else if (const ast::Decl *decl = dyn_cast<ast::Decl>(node)) {
202       const ast::Name *name = decl->getName();
203       if (!name)
204         return;
205       PDLIndexSymbol *declSym = getOrInsertDef(decl);
206       insertDeclRef(declSym, name->getLoc(), /*isDef=*/true);
207 
208       if (const auto *varDecl = dyn_cast<ast::VariableDecl>(decl)) {
209         // Record references to any constraints.
210         for (const auto &it : varDecl->getConstraints())
211           insertDeclRef(getOrInsertDef(it.constraint), it.referenceLoc);
212       }
213     } else if (const auto *expr = dyn_cast<ast::DeclRefExpr>(node)) {
214       insertDeclRef(getOrInsertDef(expr->getDecl()), expr->getLoc());
215     }
216   });
217 }
218 
219 const PDLIndexSymbol *PDLIndex::lookup(SMLoc loc,
220                                        SMRange *overlappedRange) const {
221   auto it = intervalMap.find(loc.getPointer());
222   if (!it.valid() || loc.getPointer() < it.start())
223     return nullptr;
224 
225   if (overlappedRange) {
226     *overlappedRange = SMRange(SMLoc::getFromPointer(it.start()),
227                                SMLoc::getFromPointer(it.stop()));
228   }
229   return it.value();
230 }
231 
232 //===----------------------------------------------------------------------===//
233 // PDLDocument
234 //===----------------------------------------------------------------------===//
235 
236 namespace {
237 /// This class represents all of the information pertaining to a specific PDL
238 /// document.
239 struct PDLDocument {
240   PDLDocument(const lsp::URIForFile &uri, StringRef contents,
241               const std::vector<std::string> &extraDirs,
242               std::vector<lsp::Diagnostic> &diagnostics);
243   PDLDocument(const PDLDocument &) = delete;
244   PDLDocument &operator=(const PDLDocument &) = delete;
245 
246   //===--------------------------------------------------------------------===//
247   // Definitions and References
248   //===--------------------------------------------------------------------===//
249 
250   void getLocationsOf(const lsp::URIForFile &uri, const lsp::Position &defPos,
251                       std::vector<lsp::Location> &locations);
252   void findReferencesOf(const lsp::URIForFile &uri, const lsp::Position &pos,
253                         std::vector<lsp::Location> &references);
254 
255   //===--------------------------------------------------------------------===//
256   // Hover
257   //===--------------------------------------------------------------------===//
258 
259   Optional<lsp::Hover> findHover(const lsp::URIForFile &uri,
260                                  const lsp::Position &hoverPos);
261   Optional<lsp::Hover> findHover(const ast::Decl *decl,
262                                  const SMRange &hoverRange);
263   lsp::Hover buildHoverForOpName(const ods::Operation *op,
264                                  const SMRange &hoverRange);
265   lsp::Hover buildHoverForVariable(const ast::VariableDecl *varDecl,
266                                    const SMRange &hoverRange);
267   lsp::Hover buildHoverForPattern(const ast::PatternDecl *patternDecl,
268                                   const SMRange &hoverRange);
269   lsp::Hover buildHoverForCoreConstraint(const ast::CoreConstraintDecl *decl,
270                                          const SMRange &hoverRange);
271   template <typename T>
272   lsp::Hover buildHoverForUserConstraintOrRewrite(StringRef typeName,
273                                                   const T *decl,
274                                                   const SMRange &hoverRange);
275 
276   //===--------------------------------------------------------------------===//
277   // Document Symbols
278   //===--------------------------------------------------------------------===//
279 
280   void findDocumentSymbols(std::vector<lsp::DocumentSymbol> &symbols);
281 
282   //===--------------------------------------------------------------------===//
283   // Code Completion
284   //===--------------------------------------------------------------------===//
285 
286   lsp::CompletionList getCodeCompletion(const lsp::URIForFile &uri,
287                                         const lsp::Position &completePos);
288 
289   //===--------------------------------------------------------------------===//
290   // Signature Help
291   //===--------------------------------------------------------------------===//
292 
293   lsp::SignatureHelp getSignatureHelp(const lsp::URIForFile &uri,
294                                       const lsp::Position &helpPos);
295 
296   //===--------------------------------------------------------------------===//
297   // Fields
298   //===--------------------------------------------------------------------===//
299 
300   /// The include directories for this file.
301   std::vector<std::string> includeDirs;
302 
303   /// The source manager containing the contents of the input file.
304   llvm::SourceMgr sourceMgr;
305 
306   /// The ODS and AST contexts.
307   ods::Context odsContext;
308   ast::Context astContext;
309 
310   /// The parsed AST module, or failure if the file wasn't valid.
311   FailureOr<ast::Module *> astModule;
312 
313   /// The index of the parsed module.
314   PDLIndex index;
315 };
316 } // namespace
317 
318 PDLDocument::PDLDocument(const lsp::URIForFile &uri, StringRef contents,
319                          const std::vector<std::string> &extraDirs,
320                          std::vector<lsp::Diagnostic> &diagnostics)
321     : astContext(odsContext) {
322   auto memBuffer = llvm::MemoryBuffer::getMemBufferCopy(contents, uri.file());
323   if (!memBuffer) {
324     lsp::Logger::error("Failed to create memory buffer for file", uri.file());
325     return;
326   }
327 
328   // TODO: Properly provide include directories from the client.
329   llvm::SmallString<32> uriDirectory(uri.file());
330   llvm::sys::path::remove_filename(uriDirectory);
331   includeDirs.push_back(uriDirectory.str().str());
332   includeDirs.insert(includeDirs.end(), extraDirs.begin(), extraDirs.end());
333 
334   sourceMgr.setIncludeDirs(includeDirs);
335   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
336 
337   astContext.getDiagEngine().setHandlerFn([&](const ast::Diagnostic &diag) {
338     if (auto lspDiag = getLspDiagnoticFromDiag(sourceMgr, diag, uri))
339       diagnostics.push_back(std::move(*lspDiag));
340   });
341   astModule = parsePDLAST(astContext, sourceMgr);
342   if (succeeded(astModule))
343     index.initialize(**astModule, odsContext);
344 }
345 
346 //===----------------------------------------------------------------------===//
347 // PDLDocument: Definitions and References
348 //===----------------------------------------------------------------------===//
349 
350 void PDLDocument::getLocationsOf(const lsp::URIForFile &uri,
351                                  const lsp::Position &defPos,
352                                  std::vector<lsp::Location> &locations) {
353   SMLoc posLoc = defPos.getAsSMLoc(sourceMgr);
354   const PDLIndexSymbol *symbol = index.lookup(posLoc);
355   if (!symbol)
356     return;
357 
358   locations.push_back(getLocationFromLoc(sourceMgr, symbol->getDefLoc(), uri));
359 }
360 
361 void PDLDocument::findReferencesOf(const lsp::URIForFile &uri,
362                                    const lsp::Position &pos,
363                                    std::vector<lsp::Location> &references) {
364   SMLoc posLoc = pos.getAsSMLoc(sourceMgr);
365   const PDLIndexSymbol *symbol = index.lookup(posLoc);
366   if (!symbol)
367     return;
368 
369   references.push_back(getLocationFromLoc(sourceMgr, symbol->getDefLoc(), uri));
370   for (SMRange refLoc : symbol->references)
371     references.push_back(getLocationFromLoc(sourceMgr, refLoc, uri));
372 }
373 
374 //===----------------------------------------------------------------------===//
375 // PDLDocument: Hover
376 //===----------------------------------------------------------------------===//
377 
378 Optional<lsp::Hover> PDLDocument::findHover(const lsp::URIForFile &uri,
379                                             const lsp::Position &hoverPos) {
380   SMLoc posLoc = hoverPos.getAsSMLoc(sourceMgr);
381   SMRange hoverRange;
382   const PDLIndexSymbol *symbol = index.lookup(posLoc, &hoverRange);
383   if (!symbol)
384     return llvm::None;
385 
386   // Add hover for operation names.
387   if (const auto *op = symbol->definition.dyn_cast<const ods::Operation *>())
388     return buildHoverForOpName(op, hoverRange);
389   const auto *decl = symbol->definition.get<const ast::Decl *>();
390   return findHover(decl, hoverRange);
391 }
392 
393 Optional<lsp::Hover> PDLDocument::findHover(const ast::Decl *decl,
394                                             const SMRange &hoverRange) {
395   // Add hover for variables.
396   if (const auto *varDecl = dyn_cast<ast::VariableDecl>(decl))
397     return buildHoverForVariable(varDecl, hoverRange);
398 
399   // Add hover for patterns.
400   if (const auto *patternDecl = dyn_cast<ast::PatternDecl>(decl))
401     return buildHoverForPattern(patternDecl, hoverRange);
402 
403   // Add hover for core constraints.
404   if (const auto *cst = dyn_cast<ast::CoreConstraintDecl>(decl))
405     return buildHoverForCoreConstraint(cst, hoverRange);
406 
407   // Add hover for user constraints.
408   if (const auto *cst = dyn_cast<ast::UserConstraintDecl>(decl))
409     return buildHoverForUserConstraintOrRewrite("Constraint", cst, hoverRange);
410 
411   // Add hover for user rewrites.
412   if (const auto *rewrite = dyn_cast<ast::UserRewriteDecl>(decl))
413     return buildHoverForUserConstraintOrRewrite("Rewrite", rewrite, hoverRange);
414 
415   return llvm::None;
416 }
417 
418 lsp::Hover PDLDocument::buildHoverForOpName(const ods::Operation *op,
419                                             const SMRange &hoverRange) {
420   lsp::Hover hover(lsp::Range(sourceMgr, hoverRange));
421   {
422     llvm::raw_string_ostream hoverOS(hover.contents.value);
423     hoverOS << "**OpName**: `" << op->getName() << "`\n***\n"
424             << op->getSummary() << "\n***\n"
425             << op->getDescription();
426   }
427   return hover;
428 }
429 
430 lsp::Hover PDLDocument::buildHoverForVariable(const ast::VariableDecl *varDecl,
431                                               const SMRange &hoverRange) {
432   lsp::Hover hover(lsp::Range(sourceMgr, hoverRange));
433   {
434     llvm::raw_string_ostream hoverOS(hover.contents.value);
435     hoverOS << "**Variable**: `" << varDecl->getName().getName() << "`\n***\n"
436             << "Type: `" << varDecl->getType() << "`\n";
437   }
438   return hover;
439 }
440 
441 lsp::Hover
442 PDLDocument::buildHoverForPattern(const ast::PatternDecl *patternDecl,
443                                   const SMRange &hoverRange) {
444   lsp::Hover hover(lsp::Range(sourceMgr, hoverRange));
445   {
446     llvm::raw_string_ostream hoverOS(hover.contents.value);
447     hoverOS << "**Pattern**";
448     if (const ast::Name *name = patternDecl->getName())
449       hoverOS << ": `" << name->getName() << "`";
450     hoverOS << "\n***\n";
451     if (Optional<uint16_t> benefit = patternDecl->getBenefit())
452       hoverOS << "Benefit: " << *benefit << "\n";
453     if (patternDecl->hasBoundedRewriteRecursion())
454       hoverOS << "HasBoundedRewriteRecursion\n";
455     hoverOS << "RootOp: `"
456             << patternDecl->getRootRewriteStmt()->getRootOpExpr()->getType()
457             << "`\n";
458   }
459   return hover;
460 }
461 
462 lsp::Hover
463 PDLDocument::buildHoverForCoreConstraint(const ast::CoreConstraintDecl *decl,
464                                          const SMRange &hoverRange) {
465   lsp::Hover hover(lsp::Range(sourceMgr, hoverRange));
466   {
467     llvm::raw_string_ostream hoverOS(hover.contents.value);
468     hoverOS << "**Constraint**: `";
469     TypeSwitch<const ast::Decl *>(decl)
470         .Case([&](const ast::AttrConstraintDecl *) { hoverOS << "Attr"; })
471         .Case([&](const ast::OpConstraintDecl *opCst) {
472           hoverOS << "Op";
473           if (Optional<StringRef> name = opCst->getName())
474             hoverOS << "<" << name << ">";
475         })
476         .Case([&](const ast::TypeConstraintDecl *) { hoverOS << "Type"; })
477         .Case([&](const ast::TypeRangeConstraintDecl *) {
478           hoverOS << "TypeRange";
479         })
480         .Case([&](const ast::ValueConstraintDecl *) { hoverOS << "Value"; })
481         .Case([&](const ast::ValueRangeConstraintDecl *) {
482           hoverOS << "ValueRange";
483         });
484     hoverOS << "`\n";
485   }
486   return hover;
487 }
488 
489 template <typename T>
490 lsp::Hover PDLDocument::buildHoverForUserConstraintOrRewrite(
491     StringRef typeName, const T *decl, const SMRange &hoverRange) {
492   lsp::Hover hover(lsp::Range(sourceMgr, hoverRange));
493   {
494     llvm::raw_string_ostream hoverOS(hover.contents.value);
495     hoverOS << "**" << typeName << "**: `" << decl->getName().getName()
496             << "`\n***\n";
497     ArrayRef<ast::VariableDecl *> inputs = decl->getInputs();
498     if (!inputs.empty()) {
499       hoverOS << "Parameters:\n";
500       for (const ast::VariableDecl *input : inputs)
501         hoverOS << "* " << input->getName().getName() << ": `"
502                 << input->getType() << "`\n";
503       hoverOS << "***\n";
504     }
505     ast::Type resultType = decl->getResultType();
506     if (auto resultTupleTy = resultType.dyn_cast<ast::TupleType>()) {
507       if (resultTupleTy.empty())
508         return hover;
509 
510       hoverOS << "Results:\n";
511       for (auto it : llvm::zip(resultTupleTy.getElementNames(),
512                                resultTupleTy.getElementTypes())) {
513         StringRef name = std::get<0>(it);
514         hoverOS << "* " << (name.empty() ? "" : (name + ": ")) << "`"
515                 << std::get<1>(it) << "`\n";
516       }
517     } else {
518       hoverOS << "Results:\n* `" << resultType << "`\n";
519     }
520     hoverOS << "***\n";
521   }
522   return hover;
523 }
524 
525 //===----------------------------------------------------------------------===//
526 // PDLDocument: Document Symbols
527 //===----------------------------------------------------------------------===//
528 
529 void PDLDocument::findDocumentSymbols(
530     std::vector<lsp::DocumentSymbol> &symbols) {
531   if (failed(astModule))
532     return;
533 
534   for (const ast::Decl *decl : (*astModule)->getChildren()) {
535     if (!isMainFileLoc(sourceMgr, decl->getLoc()))
536       continue;
537 
538     if (const auto *patternDecl = dyn_cast<ast::PatternDecl>(decl)) {
539       const ast::Name *name = patternDecl->getName();
540 
541       SMRange nameLoc = name ? name->getLoc() : patternDecl->getLoc();
542       SMRange bodyLoc(nameLoc.Start, patternDecl->getBody()->getLoc().End);
543 
544       symbols.emplace_back(
545           name ? name->getName() : "<pattern>", lsp::SymbolKind::Class,
546           lsp::Range(sourceMgr, bodyLoc), lsp::Range(sourceMgr, nameLoc));
547     } else if (const auto *cDecl = dyn_cast<ast::UserConstraintDecl>(decl)) {
548       // TODO: Add source information for the code block body.
549       SMRange nameLoc = cDecl->getName().getLoc();
550       SMRange bodyLoc = nameLoc;
551 
552       symbols.emplace_back(
553           cDecl->getName().getName(), lsp::SymbolKind::Function,
554           lsp::Range(sourceMgr, bodyLoc), lsp::Range(sourceMgr, nameLoc));
555     } else if (const auto *cDecl = dyn_cast<ast::UserRewriteDecl>(decl)) {
556       // TODO: Add source information for the code block body.
557       SMRange nameLoc = cDecl->getName().getLoc();
558       SMRange bodyLoc = nameLoc;
559 
560       symbols.emplace_back(
561           cDecl->getName().getName(), lsp::SymbolKind::Function,
562           lsp::Range(sourceMgr, bodyLoc), lsp::Range(sourceMgr, nameLoc));
563     }
564   }
565 }
566 
567 //===----------------------------------------------------------------------===//
568 // PDLDocument: Code Completion
569 //===----------------------------------------------------------------------===//
570 
571 namespace {
572 class LSPCodeCompleteContext : public CodeCompleteContext {
573 public:
574   LSPCodeCompleteContext(SMLoc completeLoc, lsp::CompletionList &completionList,
575                          ods::Context &odsContext)
576       : CodeCompleteContext(completeLoc), completionList(completionList),
577         odsContext(odsContext) {}
578 
579   void codeCompleteTupleMemberAccess(ast::TupleType tupleType) final {
580     ArrayRef<ast::Type> elementTypes = tupleType.getElementTypes();
581     ArrayRef<StringRef> elementNames = tupleType.getElementNames();
582     for (unsigned i = 0, e = tupleType.size(); i < e; ++i) {
583       // Push back a completion item that uses the result index.
584       lsp::CompletionItem item;
585       item.label = llvm::formatv("{0} (field #{0})", i).str();
586       item.insertText = Twine(i).str();
587       item.filterText = item.sortText = item.insertText;
588       item.kind = lsp::CompletionItemKind::Field;
589       item.detail = llvm::formatv("{0}: {1}", i, elementTypes[i]);
590       item.insertTextFormat = lsp::InsertTextFormat::PlainText;
591       completionList.items.emplace_back(item);
592 
593       // If the element has a name, push back a completion item with that name.
594       if (!elementNames[i].empty()) {
595         item.label =
596             llvm::formatv("{1} (field #{0})", i, elementNames[i]).str();
597         item.filterText = item.label;
598         item.insertText = elementNames[i].str();
599         completionList.items.emplace_back(item);
600       }
601     }
602   }
603 
604   void codeCompleteOperationMemberAccess(ast::OperationType opType) final {
605     Optional<StringRef> opName = opType.getName();
606     const ods::Operation *odsOp =
607         opName ? odsContext.lookupOperation(*opName) : nullptr;
608     if (!odsOp)
609       return;
610 
611     ArrayRef<ods::OperandOrResult> results = odsOp->getResults();
612     for (const auto &it : llvm::enumerate(results)) {
613       const ods::OperandOrResult &result = it.value();
614       const ods::TypeConstraint &constraint = result.getConstraint();
615 
616       // Push back a completion item that uses the result index.
617       lsp::CompletionItem item;
618       item.label = llvm::formatv("{0} (field #{0})", it.index()).str();
619       item.insertText = Twine(it.index()).str();
620       item.filterText = item.sortText = item.insertText;
621       item.kind = lsp::CompletionItemKind::Field;
622       switch (result.getVariableLengthKind()) {
623       case ods::VariableLengthKind::Single:
624         item.detail = llvm::formatv("{0}: Value", it.index()).str();
625         break;
626       case ods::VariableLengthKind::Optional:
627         item.detail = llvm::formatv("{0}: Value?", it.index()).str();
628         break;
629       case ods::VariableLengthKind::Variadic:
630         item.detail = llvm::formatv("{0}: ValueRange", it.index()).str();
631         break;
632       }
633       item.documentation = lsp::MarkupContent{
634           lsp::MarkupKind::Markdown,
635           llvm::formatv("{0}\n\n```c++\n{1}\n```\n", constraint.getSummary(),
636                         constraint.getCppClass())
637               .str()};
638       item.insertTextFormat = lsp::InsertTextFormat::PlainText;
639       completionList.items.emplace_back(item);
640 
641       // If the result has a name, push back a completion item with the result
642       // name.
643       if (!result.getName().empty()) {
644         item.label =
645             llvm::formatv("{1} (field #{0})", it.index(), result.getName())
646                 .str();
647         item.filterText = item.label;
648         item.insertText = result.getName().str();
649         completionList.items.emplace_back(item);
650       }
651     }
652   }
653 
654   void codeCompleteOperationAttributeName(StringRef opName) final {
655     const ods::Operation *odsOp = odsContext.lookupOperation(opName);
656     if (!odsOp)
657       return;
658 
659     for (const ods::Attribute &attr : odsOp->getAttributes()) {
660       const ods::AttributeConstraint &constraint = attr.getConstraint();
661 
662       lsp::CompletionItem item;
663       item.label = attr.getName().str();
664       item.kind = lsp::CompletionItemKind::Field;
665       item.detail = attr.isOptional() ? "optional" : "";
666       item.documentation = lsp::MarkupContent{
667           lsp::MarkupKind::Markdown,
668           llvm::formatv("{0}\n\n```c++\n{1}\n```\n", constraint.getSummary(),
669                         constraint.getCppClass())
670               .str()};
671       item.insertTextFormat = lsp::InsertTextFormat::PlainText;
672       completionList.items.emplace_back(item);
673     }
674   }
675 
676   void codeCompleteConstraintName(ast::Type currentType,
677                                   bool allowNonCoreConstraints,
678                                   bool allowInlineTypeConstraints,
679                                   const ast::DeclScope *scope) final {
680     auto addCoreConstraint = [&](StringRef constraint, StringRef mlirType,
681                                  StringRef snippetText = "") {
682       lsp::CompletionItem item;
683       item.label = constraint.str();
684       item.kind = lsp::CompletionItemKind::Class;
685       item.detail = (constraint + " constraint").str();
686       item.documentation = lsp::MarkupContent{
687           lsp::MarkupKind::Markdown,
688           ("A single entity core constraint of type `" + mlirType + "`").str()};
689       item.sortText = "0";
690       item.insertText = snippetText.str();
691       item.insertTextFormat = snippetText.empty()
692                                   ? lsp::InsertTextFormat::PlainText
693                                   : lsp::InsertTextFormat::Snippet;
694       completionList.items.emplace_back(item);
695     };
696 
697     // Insert completions for the core constraints. Some core constraints have
698     // additional characteristics, so we may add then even if a type has been
699     // inferred.
700     if (!currentType) {
701       addCoreConstraint("Attr", "mlir::Attribute");
702       addCoreConstraint("Op", "mlir::Operation *");
703       addCoreConstraint("Value", "mlir::Value");
704       addCoreConstraint("ValueRange", "mlir::ValueRange");
705       addCoreConstraint("Type", "mlir::Type");
706       addCoreConstraint("TypeRange", "mlir::TypeRange");
707     }
708     if (allowInlineTypeConstraints) {
709       /// Attr<Type>.
710       if (!currentType || currentType.isa<ast::AttributeType>())
711         addCoreConstraint("Attr<type>", "mlir::Attribute", "Attr<$1>");
712       /// Value<Type>.
713       if (!currentType || currentType.isa<ast::ValueType>())
714         addCoreConstraint("Value<type>", "mlir::Value", "Value<$1>");
715       /// ValueRange<TypeRange>.
716       if (!currentType || currentType.isa<ast::ValueRangeType>())
717         addCoreConstraint("ValueRange<type>", "mlir::ValueRange",
718                           "ValueRange<$1>");
719     }
720 
721     // If a scope was provided, check it for potential constraints.
722     while (scope) {
723       for (const ast::Decl *decl : scope->getDecls()) {
724         if (const auto *cst = dyn_cast<ast::UserConstraintDecl>(decl)) {
725           if (!allowNonCoreConstraints)
726             continue;
727 
728           lsp::CompletionItem item;
729           item.label = cst->getName().getName().str();
730           item.kind = lsp::CompletionItemKind::Interface;
731           item.sortText = "2_" + item.label;
732 
733           // Skip constraints that are not single-arg. We currently only
734           // complete variable constraints.
735           if (cst->getInputs().size() != 1)
736             continue;
737 
738           // Ensure the input type matched the given type.
739           ast::Type constraintType = cst->getInputs()[0]->getType();
740           if (currentType && !currentType.refineWith(constraintType))
741             continue;
742 
743           // Format the constraint signature.
744           {
745             llvm::raw_string_ostream strOS(item.detail);
746             strOS << "(";
747             llvm::interleaveComma(
748                 cst->getInputs(), strOS, [&](const ast::VariableDecl *var) {
749                   strOS << var->getName().getName() << ": " << var->getType();
750                 });
751             strOS << ") -> " << cst->getResultType();
752           }
753 
754           completionList.items.emplace_back(item);
755         }
756       }
757 
758       scope = scope->getParentScope();
759     }
760   }
761 
762   void codeCompleteDialectName() final {
763     // Code complete known dialects.
764     for (const ods::Dialect &dialect : odsContext.getDialects()) {
765       lsp::CompletionItem item;
766       item.label = dialect.getName().str();
767       item.kind = lsp::CompletionItemKind::Class;
768       item.insertTextFormat = lsp::InsertTextFormat::PlainText;
769       completionList.items.emplace_back(item);
770     }
771   }
772 
773   void codeCompleteOperationName(StringRef dialectName) final {
774     const ods::Dialect *dialect = odsContext.lookupDialect(dialectName);
775     if (!dialect)
776       return;
777 
778     for (const auto &it : dialect->getOperations()) {
779       const ods::Operation &op = *it.second;
780 
781       lsp::CompletionItem item;
782       item.label = op.getName().drop_front(dialectName.size() + 1).str();
783       item.kind = lsp::CompletionItemKind::Field;
784       item.insertTextFormat = lsp::InsertTextFormat::PlainText;
785       completionList.items.emplace_back(item);
786     }
787   }
788 
789   void codeCompletePatternMetadata() final {
790     auto addSimpleConstraint = [&](StringRef constraint, StringRef desc,
791                                    StringRef snippetText = "") {
792       lsp::CompletionItem item;
793       item.label = constraint.str();
794       item.kind = lsp::CompletionItemKind::Class;
795       item.detail = "pattern metadata";
796       item.documentation =
797           lsp::MarkupContent{lsp::MarkupKind::Markdown, desc.str()};
798       item.insertText = snippetText.str();
799       item.insertTextFormat = snippetText.empty()
800                                   ? lsp::InsertTextFormat::PlainText
801                                   : lsp::InsertTextFormat::Snippet;
802       completionList.items.emplace_back(item);
803     };
804 
805     addSimpleConstraint("benefit", "The `benefit` of matching the pattern.",
806                         "benefit($1)");
807     addSimpleConstraint("recursion",
808                         "The pattern properly handles recursive application.");
809   }
810 
811 private:
812   lsp::CompletionList &completionList;
813   ods::Context &odsContext;
814 };
815 } // namespace
816 
817 lsp::CompletionList
818 PDLDocument::getCodeCompletion(const lsp::URIForFile &uri,
819                                const lsp::Position &completePos) {
820   SMLoc posLoc = completePos.getAsSMLoc(sourceMgr);
821   if (!posLoc.isValid())
822     return lsp::CompletionList();
823 
824   // Adjust the position one further to after the completion trigger token.
825   posLoc = SMLoc::getFromPointer(posLoc.getPointer() + 1);
826 
827   // To perform code completion, we run another parse of the module with the
828   // code completion context provided.
829   ods::Context tmpODSContext;
830   lsp::CompletionList completionList;
831   LSPCodeCompleteContext lspCompleteContext(posLoc, completionList,
832                                             tmpODSContext);
833 
834   ast::Context tmpContext(tmpODSContext);
835   (void)parsePDLAST(tmpContext, sourceMgr, &lspCompleteContext);
836 
837   return completionList;
838 }
839 
840 //===----------------------------------------------------------------------===//
841 // PDLDocument: Signature Help
842 //===----------------------------------------------------------------------===//
843 
844 namespace {
845 class LSPSignatureHelpContext : public CodeCompleteContext {
846 public:
847   LSPSignatureHelpContext(SMLoc completeLoc, lsp::SignatureHelp &signatureHelp,
848                           ods::Context &odsContext)
849       : CodeCompleteContext(completeLoc), signatureHelp(signatureHelp),
850         odsContext(odsContext) {}
851 
852   void codeCompleteCallSignature(const ast::CallableDecl *callable,
853                                  unsigned currentNumArgs) final {
854     signatureHelp.activeParameter = currentNumArgs;
855 
856     lsp::SignatureInformation signatureInfo;
857     {
858       llvm::raw_string_ostream strOS(signatureInfo.label);
859       strOS << callable->getName()->getName() << "(";
860       auto formatParamFn = [&](const ast::VariableDecl *var) {
861         unsigned paramStart = strOS.str().size();
862         strOS << var->getName().getName() << ": " << var->getType();
863         unsigned paramEnd = strOS.str().size();
864         signatureInfo.parameters.emplace_back(lsp::ParameterInformation{
865             StringRef(strOS.str()).slice(paramStart, paramEnd).str(),
866             std::make_pair(paramStart, paramEnd), /*paramDoc*/ std::string()});
867       };
868       llvm::interleaveComma(callable->getInputs(), strOS, formatParamFn);
869       strOS << ") -> " << callable->getResultType();
870     }
871     signatureHelp.signatures.emplace_back(std::move(signatureInfo));
872   }
873 
874   void
875   codeCompleteOperationOperandsSignature(Optional<StringRef> opName,
876                                          unsigned currentNumOperands) final {
877     const ods::Operation *odsOp =
878         opName ? odsContext.lookupOperation(*opName) : nullptr;
879     codeCompleteOperationOperandOrResultSignature(
880         opName, odsOp, odsOp ? odsOp->getOperands() : llvm::None,
881         currentNumOperands, "operand", "Value");
882   }
883 
884   void codeCompleteOperationResultsSignature(Optional<StringRef> opName,
885                                              unsigned currentNumResults) final {
886     const ods::Operation *odsOp =
887         opName ? odsContext.lookupOperation(*opName) : nullptr;
888     codeCompleteOperationOperandOrResultSignature(
889         opName, odsOp, odsOp ? odsOp->getResults() : llvm::None,
890         currentNumResults, "result", "Type");
891   }
892 
893   void codeCompleteOperationOperandOrResultSignature(
894       Optional<StringRef> opName, const ods::Operation *odsOp,
895       ArrayRef<ods::OperandOrResult> values, unsigned currentValue,
896       StringRef label, StringRef dataType) {
897     signatureHelp.activeParameter = currentValue;
898 
899     // If we have ODS information for the operation, add in the ODS signature
900     // for the operation. We also verify that the current number of values is
901     // not more than what is defined in ODS, as this will result in an error
902     // anyways.
903     if (odsOp && currentValue < values.size()) {
904       lsp::SignatureInformation signatureInfo;
905 
906       // Build the signature label.
907       {
908         llvm::raw_string_ostream strOS(signatureInfo.label);
909         strOS << "(";
910         auto formatFn = [&](const ods::OperandOrResult &value) {
911           unsigned paramStart = strOS.str().size();
912 
913           strOS << value.getName() << ": ";
914 
915           StringRef constraintDoc = value.getConstraint().getSummary();
916           std::string paramDoc;
917           switch (value.getVariableLengthKind()) {
918           case ods::VariableLengthKind::Single:
919             strOS << dataType;
920             paramDoc = constraintDoc.str();
921             break;
922           case ods::VariableLengthKind::Optional:
923             strOS << dataType << "?";
924             paramDoc = ("optional: " + constraintDoc).str();
925             break;
926           case ods::VariableLengthKind::Variadic:
927             strOS << dataType << "Range";
928             paramDoc = ("variadic: " + constraintDoc).str();
929             break;
930           }
931 
932           unsigned paramEnd = strOS.str().size();
933           signatureInfo.parameters.emplace_back(lsp::ParameterInformation{
934               StringRef(strOS.str()).slice(paramStart, paramEnd).str(),
935               std::make_pair(paramStart, paramEnd), paramDoc});
936         };
937         llvm::interleaveComma(values, strOS, formatFn);
938         strOS << ")";
939       }
940       signatureInfo.documentation =
941           llvm::formatv("`op<{0}>` ODS {1} specification", *opName, label)
942               .str();
943       signatureHelp.signatures.emplace_back(std::move(signatureInfo));
944     }
945 
946     // If there aren't any arguments yet, we also add the generic signature.
947     if (currentValue == 0 && (!odsOp || !values.empty())) {
948       lsp::SignatureInformation signatureInfo;
949       signatureInfo.label =
950           llvm::formatv("(<{0}s>: {1}Range)", label, dataType).str();
951       signatureInfo.documentation =
952           ("Generic operation " + label + " specification").str();
953       signatureInfo.parameters.emplace_back(lsp::ParameterInformation{
954           StringRef(signatureInfo.label).drop_front().drop_back().str(),
955           std::pair<unsigned, unsigned>(1, signatureInfo.label.size() - 1),
956           ("All of the " + label + "s of the operation.").str()});
957       signatureHelp.signatures.emplace_back(std::move(signatureInfo));
958     }
959   }
960 
961 private:
962   lsp::SignatureHelp &signatureHelp;
963   ods::Context &odsContext;
964 };
965 } // namespace
966 
967 lsp::SignatureHelp PDLDocument::getSignatureHelp(const lsp::URIForFile &uri,
968                                                  const lsp::Position &helpPos) {
969   SMLoc posLoc = helpPos.getAsSMLoc(sourceMgr);
970   if (!posLoc.isValid())
971     return lsp::SignatureHelp();
972 
973   // Adjust the position one further to after the completion trigger token.
974   posLoc = SMLoc::getFromPointer(posLoc.getPointer() + 1);
975 
976   // To perform code completion, we run another parse of the module with the
977   // code completion context provided.
978   ods::Context tmpODSContext;
979   lsp::SignatureHelp signatureHelp;
980   LSPSignatureHelpContext completeContext(posLoc, signatureHelp, tmpODSContext);
981 
982   ast::Context tmpContext(tmpODSContext);
983   (void)parsePDLAST(tmpContext, sourceMgr, &completeContext);
984 
985   return signatureHelp;
986 }
987 
988 //===----------------------------------------------------------------------===//
989 // PDLTextFileChunk
990 //===----------------------------------------------------------------------===//
991 
992 namespace {
993 /// This class represents a single chunk of an PDL text file.
994 struct PDLTextFileChunk {
995   PDLTextFileChunk(uint64_t lineOffset, const lsp::URIForFile &uri,
996                    StringRef contents,
997                    const std::vector<std::string> &extraDirs,
998                    std::vector<lsp::Diagnostic> &diagnostics)
999       : lineOffset(lineOffset),
1000         document(uri, contents, extraDirs, diagnostics) {}
1001 
1002   /// Adjust the line number of the given range to anchor at the beginning of
1003   /// the file, instead of the beginning of this chunk.
1004   void adjustLocForChunkOffset(lsp::Range &range) {
1005     adjustLocForChunkOffset(range.start);
1006     adjustLocForChunkOffset(range.end);
1007   }
1008   /// Adjust the line number of the given position to anchor at the beginning of
1009   /// the file, instead of the beginning of this chunk.
1010   void adjustLocForChunkOffset(lsp::Position &pos) { pos.line += lineOffset; }
1011 
1012   /// The line offset of this chunk from the beginning of the file.
1013   uint64_t lineOffset;
1014   /// The document referred to by this chunk.
1015   PDLDocument document;
1016 };
1017 } // namespace
1018 
1019 //===----------------------------------------------------------------------===//
1020 // PDLTextFile
1021 //===----------------------------------------------------------------------===//
1022 
1023 namespace {
1024 /// This class represents a text file containing one or more PDL documents.
1025 class PDLTextFile {
1026 public:
1027   PDLTextFile(const lsp::URIForFile &uri, StringRef fileContents,
1028               int64_t version, const std::vector<std::string> &extraDirs,
1029               std::vector<lsp::Diagnostic> &diagnostics);
1030 
1031   /// Return the current version of this text file.
1032   int64_t getVersion() const { return version; }
1033 
1034   //===--------------------------------------------------------------------===//
1035   // LSP Queries
1036   //===--------------------------------------------------------------------===//
1037 
1038   void getLocationsOf(const lsp::URIForFile &uri, lsp::Position defPos,
1039                       std::vector<lsp::Location> &locations);
1040   void findReferencesOf(const lsp::URIForFile &uri, lsp::Position pos,
1041                         std::vector<lsp::Location> &references);
1042   Optional<lsp::Hover> findHover(const lsp::URIForFile &uri,
1043                                  lsp::Position hoverPos);
1044   void findDocumentSymbols(std::vector<lsp::DocumentSymbol> &symbols);
1045   lsp::CompletionList getCodeCompletion(const lsp::URIForFile &uri,
1046                                         lsp::Position completePos);
1047   lsp::SignatureHelp getSignatureHelp(const lsp::URIForFile &uri,
1048                                       lsp::Position helpPos);
1049 
1050 private:
1051   /// Find the PDL document that contains the given position, and update the
1052   /// position to be anchored at the start of the found chunk instead of the
1053   /// beginning of the file.
1054   PDLTextFileChunk &getChunkFor(lsp::Position &pos);
1055 
1056   /// The full string contents of the file.
1057   std::string contents;
1058 
1059   /// The version of this file.
1060   int64_t version;
1061 
1062   /// The number of lines in the file.
1063   int64_t totalNumLines = 0;
1064 
1065   /// The chunks of this file. The order of these chunks is the order in which
1066   /// they appear in the text file.
1067   std::vector<std::unique_ptr<PDLTextFileChunk>> chunks;
1068 };
1069 } // namespace
1070 
1071 PDLTextFile::PDLTextFile(const lsp::URIForFile &uri, StringRef fileContents,
1072                          int64_t version,
1073                          const std::vector<std::string> &extraDirs,
1074                          std::vector<lsp::Diagnostic> &diagnostics)
1075     : contents(fileContents.str()), version(version) {
1076   // Split the file into separate PDL documents.
1077   // TODO: Find a way to share the split file marker with other tools. We don't
1078   // want to use `splitAndProcessBuffer` here, but we do want to make sure this
1079   // marker doesn't go out of sync.
1080   SmallVector<StringRef, 8> subContents;
1081   StringRef(contents).split(subContents, "// -----");
1082   chunks.emplace_back(std::make_unique<PDLTextFileChunk>(
1083       /*lineOffset=*/0, uri, subContents.front(), extraDirs, diagnostics));
1084 
1085   uint64_t lineOffset = subContents.front().count('\n');
1086   for (StringRef docContents : llvm::drop_begin(subContents)) {
1087     unsigned currentNumDiags = diagnostics.size();
1088     auto chunk = std::make_unique<PDLTextFileChunk>(
1089         lineOffset, uri, docContents, extraDirs, diagnostics);
1090     lineOffset += docContents.count('\n');
1091 
1092     // Adjust locations used in diagnostics to account for the offset from the
1093     // beginning of the file.
1094     for (lsp::Diagnostic &diag :
1095          llvm::drop_begin(diagnostics, currentNumDiags)) {
1096       chunk->adjustLocForChunkOffset(diag.range);
1097 
1098       if (!diag.relatedInformation)
1099         continue;
1100       for (auto &it : *diag.relatedInformation)
1101         if (it.location.uri == uri)
1102           chunk->adjustLocForChunkOffset(it.location.range);
1103     }
1104     chunks.emplace_back(std::move(chunk));
1105   }
1106   totalNumLines = lineOffset;
1107 }
1108 
1109 void PDLTextFile::getLocationsOf(const lsp::URIForFile &uri,
1110                                  lsp::Position defPos,
1111                                  std::vector<lsp::Location> &locations) {
1112   PDLTextFileChunk &chunk = getChunkFor(defPos);
1113   chunk.document.getLocationsOf(uri, defPos, locations);
1114 
1115   // Adjust any locations within this file for the offset of this chunk.
1116   if (chunk.lineOffset == 0)
1117     return;
1118   for (lsp::Location &loc : locations)
1119     if (loc.uri == uri)
1120       chunk.adjustLocForChunkOffset(loc.range);
1121 }
1122 
1123 void PDLTextFile::findReferencesOf(const lsp::URIForFile &uri,
1124                                    lsp::Position pos,
1125                                    std::vector<lsp::Location> &references) {
1126   PDLTextFileChunk &chunk = getChunkFor(pos);
1127   chunk.document.findReferencesOf(uri, pos, references);
1128 
1129   // Adjust any locations within this file for the offset of this chunk.
1130   if (chunk.lineOffset == 0)
1131     return;
1132   for (lsp::Location &loc : references)
1133     if (loc.uri == uri)
1134       chunk.adjustLocForChunkOffset(loc.range);
1135 }
1136 
1137 Optional<lsp::Hover> PDLTextFile::findHover(const lsp::URIForFile &uri,
1138                                             lsp::Position hoverPos) {
1139   PDLTextFileChunk &chunk = getChunkFor(hoverPos);
1140   Optional<lsp::Hover> hoverInfo = chunk.document.findHover(uri, hoverPos);
1141 
1142   // Adjust any locations within this file for the offset of this chunk.
1143   if (chunk.lineOffset != 0 && hoverInfo && hoverInfo->range)
1144     chunk.adjustLocForChunkOffset(*hoverInfo->range);
1145   return hoverInfo;
1146 }
1147 
1148 void PDLTextFile::findDocumentSymbols(
1149     std::vector<lsp::DocumentSymbol> &symbols) {
1150   if (chunks.size() == 1)
1151     return chunks.front()->document.findDocumentSymbols(symbols);
1152 
1153   // If there are multiple chunks in this file, we create top-level symbols for
1154   // each chunk.
1155   for (unsigned i = 0, e = chunks.size(); i < e; ++i) {
1156     PDLTextFileChunk &chunk = *chunks[i];
1157     lsp::Position startPos(chunk.lineOffset);
1158     lsp::Position endPos((i == e - 1) ? totalNumLines - 1
1159                                       : chunks[i + 1]->lineOffset);
1160     lsp::DocumentSymbol symbol("<file-split-" + Twine(i) + ">",
1161                                lsp::SymbolKind::Namespace,
1162                                /*range=*/lsp::Range(startPos, endPos),
1163                                /*selectionRange=*/lsp::Range(startPos));
1164     chunk.document.findDocumentSymbols(symbol.children);
1165 
1166     // Fixup the locations of document symbols within this chunk.
1167     if (i != 0) {
1168       SmallVector<lsp::DocumentSymbol *> symbolsToFix;
1169       for (lsp::DocumentSymbol &childSymbol : symbol.children)
1170         symbolsToFix.push_back(&childSymbol);
1171 
1172       while (!symbolsToFix.empty()) {
1173         lsp::DocumentSymbol *symbol = symbolsToFix.pop_back_val();
1174         chunk.adjustLocForChunkOffset(symbol->range);
1175         chunk.adjustLocForChunkOffset(symbol->selectionRange);
1176 
1177         for (lsp::DocumentSymbol &childSymbol : symbol->children)
1178           symbolsToFix.push_back(&childSymbol);
1179       }
1180     }
1181 
1182     // Push the symbol for this chunk.
1183     symbols.emplace_back(std::move(symbol));
1184   }
1185 }
1186 
1187 lsp::CompletionList PDLTextFile::getCodeCompletion(const lsp::URIForFile &uri,
1188                                                    lsp::Position completePos) {
1189   PDLTextFileChunk &chunk = getChunkFor(completePos);
1190   lsp::CompletionList completionList =
1191       chunk.document.getCodeCompletion(uri, completePos);
1192 
1193   // Adjust any completion locations.
1194   for (lsp::CompletionItem &item : completionList.items) {
1195     if (item.textEdit)
1196       chunk.adjustLocForChunkOffset(item.textEdit->range);
1197     for (lsp::TextEdit &edit : item.additionalTextEdits)
1198       chunk.adjustLocForChunkOffset(edit.range);
1199   }
1200   return completionList;
1201 }
1202 
1203 lsp::SignatureHelp PDLTextFile::getSignatureHelp(const lsp::URIForFile &uri,
1204                                                  lsp::Position helpPos) {
1205   return getChunkFor(helpPos).document.getSignatureHelp(uri, helpPos);
1206 }
1207 
1208 PDLTextFileChunk &PDLTextFile::getChunkFor(lsp::Position &pos) {
1209   if (chunks.size() == 1)
1210     return *chunks.front();
1211 
1212   // Search for the first chunk with a greater line offset, the previous chunk
1213   // is the one that contains `pos`.
1214   auto it = llvm::upper_bound(
1215       chunks, pos, [](const lsp::Position &pos, const auto &chunk) {
1216         return static_cast<uint64_t>(pos.line) < chunk->lineOffset;
1217       });
1218   PDLTextFileChunk &chunk = it == chunks.end() ? *chunks.back() : **(--it);
1219   pos.line -= chunk.lineOffset;
1220   return chunk;
1221 }
1222 
1223 //===----------------------------------------------------------------------===//
1224 // PDLLServer::Impl
1225 //===----------------------------------------------------------------------===//
1226 
1227 struct lsp::PDLLServer::Impl {
1228   explicit Impl(const Options &options) : options(options) {}
1229 
1230   /// PDLL LSP options.
1231   const Options &options;
1232 
1233   /// The files held by the server, mapped by their URI file name.
1234   llvm::StringMap<std::unique_ptr<PDLTextFile>> files;
1235 };
1236 
1237 //===----------------------------------------------------------------------===//
1238 // PDLLServer
1239 //===----------------------------------------------------------------------===//
1240 
1241 lsp::PDLLServer::PDLLServer(const Options &options)
1242     : impl(std::make_unique<Impl>(options)) {}
1243 lsp::PDLLServer::~PDLLServer() = default;
1244 
1245 void lsp::PDLLServer::addOrUpdateDocument(
1246     const URIForFile &uri, StringRef contents, int64_t version,
1247     std::vector<Diagnostic> &diagnostics) {
1248   impl->files[uri.file()] = std::make_unique<PDLTextFile>(
1249       uri, contents, version, impl->options.extraDirs, diagnostics);
1250 }
1251 
1252 Optional<int64_t> lsp::PDLLServer::removeDocument(const URIForFile &uri) {
1253   auto it = impl->files.find(uri.file());
1254   if (it == impl->files.end())
1255     return llvm::None;
1256 
1257   int64_t version = it->second->getVersion();
1258   impl->files.erase(it);
1259   return version;
1260 }
1261 
1262 void lsp::PDLLServer::getLocationsOf(const URIForFile &uri,
1263                                      const Position &defPos,
1264                                      std::vector<Location> &locations) {
1265   auto fileIt = impl->files.find(uri.file());
1266   if (fileIt != impl->files.end())
1267     fileIt->second->getLocationsOf(uri, defPos, locations);
1268 }
1269 
1270 void lsp::PDLLServer::findReferencesOf(const URIForFile &uri,
1271                                        const Position &pos,
1272                                        std::vector<Location> &references) {
1273   auto fileIt = impl->files.find(uri.file());
1274   if (fileIt != impl->files.end())
1275     fileIt->second->findReferencesOf(uri, pos, references);
1276 }
1277 
1278 Optional<lsp::Hover> lsp::PDLLServer::findHover(const URIForFile &uri,
1279                                                 const Position &hoverPos) {
1280   auto fileIt = impl->files.find(uri.file());
1281   if (fileIt != impl->files.end())
1282     return fileIt->second->findHover(uri, hoverPos);
1283   return llvm::None;
1284 }
1285 
1286 void lsp::PDLLServer::findDocumentSymbols(
1287     const URIForFile &uri, std::vector<DocumentSymbol> &symbols) {
1288   auto fileIt = impl->files.find(uri.file());
1289   if (fileIt != impl->files.end())
1290     fileIt->second->findDocumentSymbols(symbols);
1291 }
1292 
1293 lsp::CompletionList
1294 lsp::PDLLServer::getCodeCompletion(const URIForFile &uri,
1295                                    const Position &completePos) {
1296   auto fileIt = impl->files.find(uri.file());
1297   if (fileIt != impl->files.end())
1298     return fileIt->second->getCodeCompletion(uri, completePos);
1299   return CompletionList();
1300 }
1301 
1302 lsp::SignatureHelp lsp::PDLLServer::getSignatureHelp(const URIForFile &uri,
1303                                                      const Position &helpPos) {
1304   auto fileIt = impl->files.find(uri.file());
1305   if (fileIt != impl->files.end())
1306     return fileIt->second->getSignatureHelp(uri, helpPos);
1307   return SignatureHelp();
1308 }
1309