1 //===--- Protocol.cpp - Language Server Protocol Implementation -----------===//
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 // This file contains the serialization code for the PDLL specific LSP structs.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "Protocol.h"
14 #include "llvm/ADT/Hashing.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Support/FormatVariadic.h"
19 #include "llvm/Support/JSON.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/raw_ostream.h"
22
23 using namespace mlir;
24 using namespace mlir::lsp;
25
26 // Helper that doesn't treat `null` and absent fields as failures.
27 template <typename T>
mapOptOrNull(const llvm::json::Value & params,llvm::StringLiteral prop,T & out,llvm::json::Path path)28 static bool mapOptOrNull(const llvm::json::Value ¶ms,
29 llvm::StringLiteral prop, T &out,
30 llvm::json::Path path) {
31 const llvm::json::Object *o = params.getAsObject();
32 assert(o);
33
34 // Field is missing or null.
35 auto *v = o->get(prop);
36 if (!v || v->getAsNull())
37 return true;
38 return fromJSON(*v, out, path.field(prop));
39 }
40
41 //===----------------------------------------------------------------------===//
42 // PDLLViewOutputParams
43 //===----------------------------------------------------------------------===//
44
fromJSON(const llvm::json::Value & value,PDLLViewOutputKind & result,llvm::json::Path path)45 bool mlir::lsp::fromJSON(const llvm::json::Value &value,
46 PDLLViewOutputKind &result, llvm::json::Path path) {
47 if (std::optional<StringRef> str = value.getAsString()) {
48 if (*str == "ast") {
49 result = PDLLViewOutputKind::AST;
50 return true;
51 }
52 if (*str == "mlir") {
53 result = PDLLViewOutputKind::MLIR;
54 return true;
55 }
56 if (*str == "cpp") {
57 result = PDLLViewOutputKind::CPP;
58 return true;
59 }
60 }
61 return false;
62 }
63
fromJSON(const llvm::json::Value & value,PDLLViewOutputParams & result,llvm::json::Path path)64 bool mlir::lsp::fromJSON(const llvm::json::Value &value,
65 PDLLViewOutputParams &result, llvm::json::Path path) {
66 llvm::json::ObjectMapper o(value, path);
67 return o && o.map("uri", result.uri) && o.map("kind", result.kind);
68 }
69
70 //===----------------------------------------------------------------------===//
71 // PDLLViewOutputResult
72 //===----------------------------------------------------------------------===//
73
toJSON(const PDLLViewOutputResult & value)74 llvm::json::Value mlir::lsp::toJSON(const PDLLViewOutputResult &value) {
75 return llvm::json::Object{{"output", value.output}};
76 }
77