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