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
8 changes: 4 additions & 4 deletions packages/quicktype-core/src/language/Rust/RustRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import type { Name, Namer } from "../../Naming.js";
import type { RenderContext } from "../../Renderer.js";
import type { OptionValues } from "../../RendererOptions/index.js";
import { type Sourcelike, maybeAnnotated } from "../../Source.js";
import { defined } from "../../support/Support.js";
import type { TargetLanguage } from "../../TargetLanguage.js";
import {
type ClassType,
Expand Down Expand Up @@ -351,9 +350,10 @@ export class RustRenderer extends ConvenienceRenderer {
return;
}

const topLevelName = defined(
mapFirst(this.topLevels),
).getCombinedName();
const topLevel = mapFirst(this.topLevels);
if (topLevel === undefined) return;

const topLevelName = topLevel.getCombinedName();
this.emitMultiline(
`// Example code that deserializes and serializes the model.
// extern crate serde;
Expand Down
44 changes: 44 additions & 0 deletions test/unit/rust-empty-top-levels.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { expect, test } from "vitest";

import {
InputData,
JSONSchemaInput,
quicktype,
} from "../../packages/quicktype-core/src/index.js";

async function renderTypeScriptSchema(definitions: object): Promise<string> {
const schemaInput = new JSONSchemaInput(undefined);
await schemaInput.addSource({
name: "",
schema: JSON.stringify({ definitions }),
uris: ["#/definitions/"],
isConverted: true,
});

const inputData = new InputData();
inputData.addInput(schemaInput);

const result = await quicktype({ inputData, lang: "rust" });
return result.lines.join("\n");
}

// TypeScript inputs without a #TopLevel marker use #/definitions/ as their
// source URI. If the compiler did not produce any definitions, the renderer
// receives no top levels and must still emit Rust without crashing.
test("Rust renders TypeScript schemas with no top levels", async () => {
const output = await renderTypeScriptSchema({});

expect(output).toContain("use serde::{Serialize, Deserialize};");
});

test("Rust still renders named TypeScript schema definitions", async () => {
const output = await renderTypeScriptSchema({
Person: {
type: "object",
properties: { age: { type: "integer" } },
required: ["age"],
},
});

expect(output).toContain("pub struct Person");
});
Loading