Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions packages/cxx-gen-lsp/src/MetaModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,20 @@ export type Enumeration = {
values: EnumerationValue[];
};

export type Notification = {};
export type Notification = Omit<Request, "result" | "partialResult" | "registrationOptions">;

export type Request = {};
type MessageDirection = "clientToServer" | "serverToClient" | "both";

export type Request = {
documentation?: string;
messageDirection: MessageDirection;
method: string;
params: ReferenceType;
partialResult?: ReferenceType | ArrayType | OrType;
registrationOptions?: ReferenceType | AndType;
result?: BaseType | ReferenceType | ArrayType | OrType;
typeName: string;
};

export type Property = {
documentation?: string;
Expand Down Expand Up @@ -128,6 +139,10 @@ export type MetaModel = {
typeAliases: TypeAlias[];
};

export function isRequest(request: Request | Notification): request is Request {
return "result" in request;
}

export function getEnumBaseType(enumeration: Enumeration) {
switch (enumeration.type.name) {
case "integer":
Expand Down
21 changes: 20 additions & 1 deletion packages/cxx-gen-lsp/src/gen_fwd_h.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
// SOFTWARE.

import * as path from "node:path";
import { getEnumBaseType, MetaModel, toCppType, Type } from "./MetaModel.js";
import { getEnumBaseType, MetaModel, toCppType, Type, Request, Notification, isRequest } from "./MetaModel.js";
import { writeFileSync } from "node:fs";
import { copyrightHeader } from "./copyrightHeader.js";

Expand All @@ -42,6 +42,16 @@ class LSPObject {
json* repr_{nullptr};
};

class LSPRequest : public LSPObject {
public:
using LSPObject::LSPObject;
};

class LSPResponse : public LSPObject {
public:
using LSPObject::LSPObject;
};

template <typename T>
class Vector final : public LSPObject {
public:
Expand Down Expand Up @@ -314,9 +324,18 @@ export function gen_fwd_h({ model, outputDirectory }: { model: MetaModel; output
emit(`enum class ${enumeration.name}${enumBaseType};`);
});
emit();
emit(`// structures`);
model.structures.forEach((structure) => {
emit(`class ${structure.name};`);
});
emit(`// requests`);
const requestsAndNotifications: Array<Request | Notification> = [...model.requests, ...model.notifications];
requestsAndNotifications.forEach((request) => {
emit(`class ${request.typeName};`);
if (isRequest(request) && request.result) {
emit(`class ${request.typeName.replace(/Request$/, "Response")};`);
}
});
emit();

const knownTypes = new Set<string>();
Expand Down
170 changes: 170 additions & 0 deletions packages/cxx-gen-lsp/src/gen_requests_cc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// Copyright (c) 2024 Roberto Raggi <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import * as path from "node:path";
import { Enumeration, isRequest, MetaModel, Structure, toCppType, Type, TypeAlias } from "./MetaModel.js";
import { writeFileSync } from "node:fs";
import { copyrightHeader } from "./copyrightHeader.js";

class RequestGenerator {
readonly structByName: Map<string, Structure>;
readonly enumByName: Map<string, Enumeration>;
readonly typeAliasByName: Map<string, TypeAlias>;
readonly model: MetaModel;
readonly outputDirectory: string;
out: string = "";

constructor({ model, outputDirectory }: { model: MetaModel; outputDirectory: string }) {
this.model = model;
this.outputDirectory = outputDirectory;
this.structByName = new Map(model.structures.map((s) => [s.name, s]));
this.enumByName = new Map(model.enumerations.map((e) => [e.name, e]));
this.typeAliasByName = new Map(model.typeAliases.map((t) => [t.name, t]));
}

genTypes() {
this.begin();

const requestsAndNotifications = [...this.model.requests, ...this.model.notifications];

requestsAndNotifications.forEach((request) => {
const { typeName } = request;
this.emit();
this.emit(`auto ${typeName}::method() const -> std::string {`);
this.emit(` return repr_->at("method");`);
this.emit(`}`);
this.emit();
this.emit(`auto ${typeName}::method(std::string method) -> ${typeName}& {`);
this.emit(` (*repr_)["method"] = std::move(method);`);
this.emit(` return *this;`);
this.emit(`}`);
this.emit();
this.emit(`auto ${typeName}::id() const -> std::variant<long, std::string> {`);
this.emit(` const auto& id = repr_->at("id");`);
this.emit(` if (id.is_string()) return id.get<std::string>();`);
this.emit(` return id.get<long>();`);
this.emit(`}`);
this.emit();
this.emit(`auto ${typeName}::id(long id) -> ${typeName}& {`);
this.emit(` (*repr_)["id"] = id;`);
this.emit(` return *this;`);
this.emit(`}`);
this.emit();
this.emit(`auto ${typeName}::id(std::string id) -> ${typeName}& {`);
this.emit(` (*repr_)["id"] = std::move(id);`);
this.emit(` return *this;`);
this.emit(`}`);

if (request.params) {
const paramsTypeName = toCppType(request.params);

this.emit();
this.emit(`auto ${typeName}::params() const -> ${paramsTypeName} {`);
this.emit(` if (!repr_->contains("params")) repr_->emplace("params", json::object());`);
this.emit(` return ${paramsTypeName}(repr_->at("params"));`);
this.emit(`}`);
this.emit();
this.emit(`auto ${typeName}::params(${paramsTypeName} params) -> ${typeName}& {`);
this.emit(` (*repr_)["params"] = std::move(params);`);
this.emit(` return *this;`);
this.emit(`}`);
}

if (isRequest(request) && request.result) {
const resultTypeName = typeName.replace(/Request$/, "Response");
this.emit();
this.emit(`auto ${resultTypeName}::id() const -> std::variant<long, std::string> {`);
this.emit(` const auto& id = repr_->at("id");`);
this.emit(` if (id.is_string()) return id.get<std::string>();`);
this.emit(` return id.get<long>();`);
this.emit(`}`);
this.emit();
this.emit(`auto ${resultTypeName}::id(long id) -> ${resultTypeName}& {`);
this.emit(` (*repr_)["id"] = id;`);
this.emit(` return *this;`);
this.emit(`}`);
this.emit();
this.emit(`auto ${resultTypeName}::id(std::string id) -> ${resultTypeName}& {`);
this.emit(` (*repr_)["id"] = std::move(id);`);
this.emit(` return *this;`);
this.emit(`}`);
}
});

this.end();
}

emit(s: string = "") {
this.out += `${s}\n`;
}

getPropertyType({ type, optional }: { type: Type; optional?: boolean }): string {
let propertyType = toCppType(type);

if (optional) {
propertyType = `std::optional<${propertyType}>`;
}

return propertyType;
}

isStringLike(type: Type): boolean {
switch (type.kind) {
case "base":
return type.name === "string";

case "reference": {
if (this.typeAliasByName.has(type.name)) {
return this.isStringLike(this.typeAliasByName.get(type.name)!.type);
}
return false;
}

case "stringLiteral":
return true;

default:
return false;
} // switch
}

begin() {
this.emit(copyrightHeader);
this.emit();
this.emit(`#include <cxx/lsp/requests.h>`);
this.emit(`#include <cxx/lsp/types.h>`);
this.emit(`#include <cxx/lsp/enums.h>`);
this.emit();
this.emit(`namespace cxx::lsp {`);
this.emit();
}

end() {
this.emit(`} // namespace cxx::lsp`);

const outputFile = path.join(this.outputDirectory, "requests.cc");
writeFileSync(outputFile, this.out);
}
}

export function gen_requests_cc({ model, outputDirectory }: { model: MetaModel; outputDirectory: string }) {
const generator = new RequestGenerator({ model, outputDirectory });
generator.genTypes();
}
97 changes: 97 additions & 0 deletions packages/cxx-gen-lsp/src/gen_requests_h.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright (c) 2024 Roberto Raggi <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import * as path from "node:path";
import { MetaModel, toCppType, Request, Notification, isRequest } from "./MetaModel.js";
import { writeFileSync } from "node:fs";
import { copyrightHeader } from "./copyrightHeader.js";

const beginHeaderFragment = `
#pragma once

#include <cxx/lsp/fwd.h>

namespace cxx::lsp {

`;

export function gen_requests_h({ model, outputDirectory }: { model: MetaModel; outputDirectory: string }) {
let out = "";

const emit = (s: string = "") => {
out += `${s}\n`;
};

emit(copyrightHeader);
emit(beginHeaderFragment);

const requestsAndNotifications: Array<Request | Notification> = [...model.requests, ...model.notifications];

requestsAndNotifications.forEach((request) => {
const typeName = request.typeName;
emit();
emit(`class ${typeName} final : public LSPRequest {`);
emit(`public:`);
emit(` using LSPRequest::LSPRequest;`);
emit();
emit(` [[nodiscard]] auto method() const -> std::string;`);
emit(` auto method(std::string method) -> ${typeName}&;`);
emit();
emit(` [[nodiscard]] auto id() const -> std::variant<long, std::string>;`);
emit(` auto id(long id) -> ${typeName}&;`);
emit(` auto id(std::string id) -> ${typeName}&;`);

if (request.params) {
const paramsType = toCppType(request.params);
emit();
emit(` [[nodiscard]] auto params() const -> ${paramsType};`);
emit(` auto params(${paramsType} result) -> ${typeName}&;`);
}

emit(`};`);

// generate the respose type if the request has a result
if (isRequest(request) && request.result) {
const responseTypeName = typeName.replace(/Request$/, "Response");
const resultType = toCppType(request.result);

emit();

emit(`class ${responseTypeName} final : public LSPResponse {`);
emit(`public:`);
emit(` using LSPResponse::LSPResponse;`);
emit();
emit(` [[nodiscard]] auto id() const -> std::variant<long, std::string>;`);
emit(` auto id(long id) -> ${responseTypeName}&;`);
emit(` auto id(std::string id) -> ${responseTypeName}&;`);
emit();
emit(` [[nodiscard]] auto result() const -> ${resultType};`);
emit();
emit(` auto result(${resultType} result) -> ${responseTypeName}&;`);
emit(`};`);
}
});

emit();
emit(`}`);

const outputFile = path.join(outputDirectory, "requests.h");
writeFileSync(outputFile, out);
}
4 changes: 4 additions & 0 deletions packages/cxx-gen-lsp/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import { gen_enums_cc } from "./gen_enums_cc.js";
import { gen_fwd_h } from "./gen_fwd_h.js";
import { gen_types_h } from "./gen_types_h.js";
import { gen_types_cc } from "./gen_types_cc.js";
import { gen_requests_h } from "./gen_requests_h.js";
import { gen_requests_cc } from "./gen_requests_cc.js";

async function main() {
try {
Expand Down Expand Up @@ -66,6 +68,8 @@ async function main() {
gen_enums_cc({ outputDirectory, model });
gen_types_h({ outputDirectory, model });
gen_types_cc({ outputDirectory, model });
gen_requests_h({ outputDirectory, model });
gen_requests_cc({ outputDirectory, model });

console.log(
child_process
Expand Down
Loading