diff --git a/README.md b/README.md index b8f73ea..6613875 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,8 @@ Import hooks are planning hooks, not rendered `use` statements. Include every co `RenderContext` supplies the root namespace, current namespace, output path prefix, resolved record names, and the file's import registry. Helpers such as `renderPhpFile()`, `indent()`, and `PHP_FILE_HEADER` keep generated PHP consistent. +Normalized records carry a `recordId` (`:`, the upstream Skir type signature), and records, fields, variants, and methods carry their doc comment text in `doc` when they have one. The core passes them to `Type::enum()`, `Variant`, and `MethodDescriptor`; struct renderers should append `renderRecordMetadataArguments(record)` to `Type::struct([...])` and `renderDocArgument(field.doc)` to `Field::value(...)`. `phpSingleQuotedLiteral()` renders arbitrary text as a one-line PHP string expression. + ### PHP types and wire conversion | Member | Purpose | diff --git a/package-lock.json b/package-lock.json index 770ba7e..057e678 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@php-skir/generator-core", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@php-skir/generator-core", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { "jsonc-parser": "^3.3.1", diff --git a/package.json b/package.json index ed3e47d..3e1386b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@php-skir/generator-core", - "version": "0.2.0", + "version": "0.3.0", "description": "Shared generation core for PHP Skir code generators.", "type": "module", "license": "MIT", diff --git a/src/index.ts b/src/index.ts index 704908f..450b346 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,7 +20,10 @@ export { export { indent, PHP_FILE_HEADER, + phpSingleQuotedLiteral, + renderDocArgument, renderPhpFile, + renderRecordMetadataArguments, } from "./php.js"; export { ComposerAutoloadConflictError, @@ -68,6 +71,7 @@ export type { NormalizedRecord, NormalizedSchema, NormalizedType, + SkirDoc, SkirField, SkirMethod, SkirModule, diff --git a/src/model.ts b/src/model.ts index b7c9914..40ae749 100644 --- a/src/model.ts +++ b/src/model.ts @@ -7,6 +7,10 @@ export interface SkirToken { readonly text: string; } +export interface SkirDoc { + readonly text: string; +} + export type SkirRecordNamePart = | string | SkirToken @@ -31,6 +35,7 @@ export type SkirField = readonly name: string | SkirToken; readonly number: number; readonly type?: SkirType; + readonly doc?: SkirDoc; } | { readonly kind: "removed"; @@ -45,6 +50,7 @@ export interface SkirRecord { readonly fields?: readonly SkirField[]; readonly removedNumbers?: readonly number[]; readonly phpClassName?: string; + readonly doc?: SkirDoc; } export interface SkirRecordLocation { @@ -60,6 +66,7 @@ export interface SkirMethod { readonly number: number; readonly requestType?: SkirType; readonly responseType?: SkirType; + readonly doc?: SkirDoc; } export interface SkirModule { @@ -100,6 +107,8 @@ export interface NormalizedField { readonly number: number; readonly hasPayload: true; readonly type: NormalizedType; + /** Doc comment text of the field or wrapper variant, when it has one. */ + readonly doc?: string; } export interface NormalizedEnumConstant { @@ -107,12 +116,21 @@ export interface NormalizedEnumConstant { readonly name: string; readonly number: number; readonly hasPayload: false; + /** Doc comment text of the constant variant, when it has one. */ + readonly doc?: string; } export interface NormalizedRecord { readonly identity: string; readonly modulePath: string; readonly qualifiedName: string; + /** + * Schema-level record id, `:`, matching the + * type signature of upstream Skir type descriptors. + */ + readonly recordId: string; + /** Doc comment text of the record, when it has one. */ + readonly doc?: string; readonly recordType: "struct" | "enum"; readonly phpClassName?: string; readonly fields: readonly ( @@ -128,6 +146,8 @@ export interface NormalizedMethod { readonly number: number; readonly requestType: NormalizedType; readonly responseType: NormalizedType; + /** Doc comment text of the method, when it has one. */ + readonly doc?: string; } export interface NormalizedModule { diff --git a/src/normalize.ts b/src/normalize.ts index c04cb60..8a630bb 100644 --- a/src/normalize.ts +++ b/src/normalize.ts @@ -7,6 +7,7 @@ import type { NormalizedRecord, NormalizedSchema, NormalizedType, + SkirDoc, SkirField, SkirMethod, SkirModule, @@ -36,6 +37,8 @@ interface RecordSource { readonly identity: string; readonly modulePath: string; readonly qualifiedName: string; + readonly recordId: string; + readonly doc?: string; readonly recordType: "struct" | "enum"; readonly key?: string; readonly phpClassName?: string; @@ -71,6 +74,8 @@ export function normalizeSchema(input: CoreGeneratorInput): NormalizedSchema { identity: source.identity, modulePath: source.modulePath, qualifiedName: source.qualifiedName, + recordId: source.recordId, + ...docProperty(source.doc), recordType: source.recordType, fields: [], ...(source.key === undefined ? {} : { key: source.key }), @@ -100,6 +105,8 @@ export function normalizeSchema(input: CoreGeneratorInput): NormalizedSchema { identity: source.identity, modulePath: source.modulePath, qualifiedName: source.qualifiedName, + recordId: source.recordId, + ...docProperty(source.doc), recordType: source.recordType, fields: [], key: mapKey, @@ -160,6 +167,8 @@ export function normalizeSchema(input: CoreGeneratorInput): NormalizedSchema { identity: source.identity, modulePath: source.modulePath, qualifiedName: source.qualifiedName, + recordId: source.recordId, + ...docProperty(source.doc), recordType: source.recordType, fields: normalizeFields(source.record, source.recordType, context), ...(source.key === undefined ? {} : { key: source.key }), @@ -224,6 +233,8 @@ function recordSource(module: SkirModule, input: SkirRecord | SkirRecordLocation modulePath, qualifiedName, identity: `${modulePath}::${qualifiedName}`, + recordId: `${modulePath}:${qualifiedName}`, + ...docProperty(docText(record.doc)), recordType, ...(key === undefined ? {} : { key }), ...(record.phpClassName === undefined ? {} : { phpClassName: record.phpClassName }), @@ -272,6 +283,8 @@ function recordMapSource( modulePath, qualifiedName, identity: `${modulePath}::${qualifiedName}`, + recordId: `${modulePath}:${qualifiedName}`, + ...docProperty(docText(location.record.doc)), recordType, ...(location.record.phpClassName === undefined ? {} @@ -409,6 +422,7 @@ function normalizeField( name, number: field.number, hasPayload: false, + ...docProperty(docText(field.doc)), }; } @@ -421,6 +435,7 @@ function normalizeField( number: field.number, hasPayload: true, type: normalizeType(field.type, context), + ...docProperty(docText(field.doc)), }; } @@ -430,6 +445,7 @@ function normalizeMethod(method: SkirMethod, context: NormalizationContext): Nor number: method.number, requestType: normalizeType(method.requestType ?? "string", context), responseType: normalizeType(method.responseType ?? "string", context), + ...docProperty(docText(method.doc)), }; } @@ -584,6 +600,16 @@ function recordNamePartText(part: SkirRecordNamePart): string { return tokenText(part); } +function docText(doc: SkirDoc | undefined): string | undefined { + const text = doc?.text; + + return text === undefined || text.trim() === "" ? undefined : text; +} + +function docProperty(doc: string | undefined): { readonly doc?: string } { + return doc === undefined ? {} : { doc }; +} + function tokenText(token: string | SkirToken): string { return typeof token === "string" ? token : token.text; } diff --git a/src/php.ts b/src/php.ts index 851a5a3..4e217eb 100644 --- a/src/php.ts +++ b/src/php.ts @@ -35,3 +35,54 @@ export function renderPhpFile(input: PhpFileInput): string { "", ].join("\n"); } + +/** + * Renders a PHP string expression for arbitrary text. Line breaks are emitted + * as double-quoted escapes concatenated to single-quoted segments, so the + * generated expression always stays on one line. + */ +export function phpSingleQuotedLiteral(value: string): string { + const expressions: string[] = []; + let segment = ""; + + for (const character of value) { + if (character !== "\n" && character !== "\r") { + segment += character; + continue; + } + + if (segment !== "") { + expressions.push(escapedPhpStringSegment(segment)); + segment = ""; + } + + expressions.push(character === "\n" ? '"\\n"' : '"\\r"'); + } + + if (segment !== "" || expressions.length === 0) { + expressions.push(escapedPhpStringSegment(segment)); + } + + return expressions.join("."); +} + +/** Renders `, doc: '...'`, or an empty string when there is no doc comment. */ +export function renderDocArgument(doc: string | undefined): string { + return doc === undefined || doc.trim() === "" + ? "" + : `, doc: ${phpSingleQuotedLiteral(doc)}`; +} + +/** + * Renders the trailing `, recordId: '...'` (and `, doc: '...'` when present) + * arguments of a runtime `Type::struct()` or `Type::enum()` call. + */ +export function renderRecordMetadataArguments( + record: { readonly recordId: string; readonly doc?: string }, +): string { + return `, recordId: ${phpSingleQuotedLiteral(record.recordId)}${renderDocArgument(record.doc)}`; +} + +function escapedPhpStringSegment(value: string): string { + return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`; +} diff --git a/src/render-enum.ts b/src/render-enum.ts index f31c525..770932f 100644 --- a/src/render-enum.ts +++ b/src/render-enum.ts @@ -8,7 +8,12 @@ import type { NormalizedType, } from "./model.js"; import { toPropertyName } from "./naming.js"; -import { indent, renderPhpFile } from "./php.js"; +import { + indent, + renderDocArgument, + renderPhpFile, + renderRecordMetadataArguments, +} from "./php.js"; const BINARY_FORMAT = "Skir\\Runtime\\BinaryFormat"; const DENSE_JSON = "Skir\\Runtime\\DenseJson"; @@ -129,10 +134,10 @@ function renderEnumSkirType( .filter((field): field is NormalizedField | NormalizedEnumConstant => field.kind === "field") .map((field) => { if (!field.hasPayload) { - return ` ${variant}::constant('${field.name}', ${field.number}),`; + return ` ${variant}::constant('${field.name}', ${field.number}${renderDocArgument(field.doc)}),`; } - return ` ${variant}::wrapper('${field.name}', ${field.number}, ${runtimeTypeExpression(field.type, context, adapter, typeClass)}),`; + return ` ${variant}::wrapper('${field.name}', ${field.number}, ${runtimeTypeExpression(field.type, context, adapter, typeClass)}${renderDocArgument(field.doc)}),`; }) .join("\n"); @@ -141,7 +146,7 @@ function renderEnumSkirType( "{", ` return ${typeClass}::enum([`, entries, - " ]);", + ` ]${renderRecordMetadataArguments(record)});`, "}", ].join("\n"); } diff --git a/src/render-rpc.ts b/src/render-rpc.ts index 6f81d86..d750188 100644 --- a/src/render-rpc.ts +++ b/src/render-rpc.ts @@ -12,7 +12,7 @@ import type { } from "./model.js"; import type { PhpNameRegistry } from "./naming.js"; import { toClassName, toPropertyName } from "./naming.js"; -import { indent, renderPhpFile } from "./php.js"; +import { indent, phpSingleQuotedLiteral, renderPhpFile } from "./php.js"; export interface RenderRpcInput { readonly rootNamespace: string; @@ -151,6 +151,9 @@ function renderMethodDescriptor( ` number: ${method.number},`, ` requestType: ${runtimeTypeExpression(method.requestType, context, adapter, typeClass)},`, ` responseType: ${runtimeTypeExpression(method.responseType, context, adapter, typeClass)},`, + ...(method.doc === undefined || method.doc.trim() === "" + ? [] + : [` doc: ${phpSingleQuotedLiteral(method.doc)},`]), " );", "}", ].join("\n"); diff --git a/tests/type-metadata.test.ts b/tests/type-metadata.test.ts new file mode 100644 index 0000000..cf18e45 --- /dev/null +++ b/tests/type-metadata.test.ts @@ -0,0 +1,300 @@ +import { execFileSync } from "node:child_process"; + +import { describe, expect, it } from "vitest"; + +import { + generatePhp, + normalizeSchema, + phpSingleQuotedLiteral, + renderDocArgument, + renderRecordMetadataArguments, + toClassName, + type GeneratedFile, + type NormalizedRecord, + type NormalizedType, + type PhpTargetAdapter, + type RenderContext, + type SkirModule, + type SkirRecord, + type SkirRecordLocation, + type StructRenderRequest, +} from "../src/index.js"; + +const TRICKY_DOC = "It's a \"quote\", a back\\slash\nand a second line.\\"; + +class MinimalAdapter implements PhpTargetAdapter { + public readonly id = "metadata-adapter"; + + public recordClassName(record: NormalizedRecord): string { + return toClassName(record.qualifiedName.replaceAll(".", "_")); + } + + public renderStruct({ record, context }: StructRenderRequest): GeneratedFile { + const className = context.names.namesByIdentity.get(record.identity) ?? "Missing"; + + return { + path: context.pathPrefix === "" ? `${className}.php` : `${context.pathPrefix}/${className}.php`, + code: `struct ${record.recordId}\n`, + }; + } + + public phpType(type: NormalizedType, context: RenderContext): string { + if (type.kind === "record") { + return context.names.namesByIdentity.get(type.recordIdentity) ?? "Missing"; + } + + return type.kind === "string" ? "string" : "mixed"; + } + + public toSkirExpression(_type: NormalizedType, expression: string): string { + return expression; + } + + public fromSkirExpression(_type: NormalizedType, expression: string): string { + return expression; + } + + public clientResponseExpression(_type: NormalizedType, expression: string): string { + return expression; + } + + public manifestObjectClass(): string | null { + return null; + } +} + +const invitation: SkirRecord = { + kind: "record", + key: "invitation-key", + name: "Invitation", + recordType: "struct", + doc: { text: "An invitation to join a team." }, + fields: [ + { kind: "field", name: "email", number: 0, type: "string", doc: { text: "Where it was sent." } }, + { kind: "field", name: "token", number: 1, type: "string" }, + { kind: "field", name: "note", number: 2, type: "string", doc: { text: " \n " } }, + ], +}; +const invitationStatus: SkirRecord = { + kind: "record", + key: "invitation-status-key", + name: "Status", + recordType: "enum", + doc: { text: TRICKY_DOC }, + fields: [ + { kind: "field", name: "pending", number: 1 }, + { kind: "field", name: "accepted", number: 2, doc: { text: "The invitee joined." } }, + { kind: "field", name: "declined", number: 3, type: "string", doc: { text: "Carries the reason." } }, + { kind: "field", name: "expired_at", number: 4, type: "timestamp" }, + ], +}; +const client: SkirRecord = { + kind: "record", + key: "client-key", + name: "Client", + recordType: "enum", + fields: [{ kind: "field", name: "tablet", number: 1 }], +}; +const nestedStatusLocation: SkirRecordLocation = { + kind: "record-location", + record: invitationStatus, + recordAncestors: [invitation, invitationStatus], + modulePath: "identity/identity.skir", +}; +const modules: readonly SkirModule[] = [{ + path: "identity/identity.skir", + records: [invitation, nestedStatusLocation, client], + methods: [ + { + kind: "method", + name: "GetInvitation", + number: 10, + requestType: "string", + responseType: { kind: "record", key: "invitation-key", recordType: "struct" }, + doc: { text: "Returns the invitation." }, + }, + { + kind: "method", + name: "Ping", + number: 11, + requestType: "string", + responseType: "string", + }, + { + kind: "method", + name: "Tricky", + number: 12, + requestType: "string", + responseType: "string", + doc: { text: TRICKY_DOC }, + }, + { + kind: "method", + name: "Blank", + number: 13, + requestType: "string", + responseType: "string", + doc: { text: " " }, + }, + ], +}]; + +function evaluatePhpExpression(expression: string): string { + return execFileSync("php", ["-r", `echo ${expression};`], { encoding: "utf8" }); +} + +describe("type metadata normalization", () => { + const schema = normalizeSchema({ modules }); + + it("derives upstream-style record ids for top-level and nested records", () => { + const records = schema.modules[0]?.records ?? []; + + expect(records.map((record) => record.recordId)).toEqual([ + "identity/identity.skir:Invitation", + "identity/identity.skir:Invitation.Status", + "identity/identity.skir:Client", + ]); + expect(records.map((record) => record.identity)).toEqual([ + "identity/identity.skir::Invitation", + "identity/identity.skir::Invitation.Status", + "identity/identity.skir::Client", + ]); + expect(schema.recordsByKey.get("invitation-status-key")?.recordId) + .toBe("identity/identity.skir:Invitation.Status"); + }); + + it("sets the record id on records known only through the record map", () => { + const external: SkirRecord = { kind: "record", name: "Money", recordType: "struct", doc: { text: "An amount." } }; + const withRecordMap = normalizeSchema({ + modules: [], + recordMap: new Map([[ + "money-key", + { + kind: "record-location", + record: external, + recordAncestors: [external], + modulePath: "common/money.skir", + }, + ]]), + }); + + expect(withRecordMap.recordsByKey.get("money-key")).toMatchObject({ + recordId: "common/money.skir:Money", + doc: "An amount.", + }); + }); + + it("keeps record, field, variant, and method doc text and drops blank docs", () => { + const [invitationRecord, statusRecord, clientRecord] = schema.modules[0]?.records ?? []; + + expect(invitationRecord?.doc).toBe("An invitation to join a team."); + expect(statusRecord?.doc).toBe(TRICKY_DOC); + expect(clientRecord).not.toHaveProperty("doc"); + expect(invitationRecord?.fields).toEqual([ + { kind: "field", name: "email", number: 0, hasPayload: true, type: { kind: "string" }, doc: "Where it was sent." }, + { kind: "field", name: "token", number: 1, hasPayload: true, type: { kind: "string" } }, + { kind: "field", name: "note", number: 2, hasPayload: true, type: { kind: "string" } }, + ]); + expect(statusRecord?.fields).toEqual([ + { kind: "field", name: "pending", number: 1, hasPayload: false }, + { kind: "field", name: "accepted", number: 2, hasPayload: false, doc: "The invitee joined." }, + { kind: "field", name: "declined", number: 3, hasPayload: true, type: { kind: "string" }, doc: "Carries the reason." }, + { kind: "field", name: "expired_at", number: 4, hasPayload: true, type: { kind: "timestamp" } }, + ]); + expect(schema.modules[0]?.methods.map((method) => method.doc)).toEqual([ + "Returns the invitation.", + undefined, + TRICKY_DOC, + undefined, + ]); + expect(schema.modules[0]?.methods[1]).not.toHaveProperty("doc"); + }); +}); + +describe("type metadata rendering", () => { + const files = generatePhp({ namespace: "App\\Skir", modules, adapter: new MinimalAdapter() }); + const codeFor = (path: string): string => files.find((file) => file.path === path)?.code ?? ""; + + it("passes the normalized record id to struct renderers", () => { + expect(codeFor("Identity/Invitation.php")).toBe("struct identity/identity.skir:Invitation\n"); + }); + + it("renders the record id and docs on a nested enum", () => { + const code = codeFor("Identity/InvitationStatus.php"); + + expect(code).toContain([ + " return Type::enum([", + " Variant::constant('pending', 1),", + " Variant::constant('accepted', 2, doc: 'The invitee joined.'),", + " Variant::wrapper('declined', 3, Type::string(), doc: 'Carries the reason.'),", + " Variant::wrapper('expired_at', 4, Type::timestamp()),", + ` ], recordId: 'identity/identity.skir:Invitation.Status', doc: ${phpSingleQuotedLiteral(TRICKY_DOC)});`, + ].join("\n")); + }); + + it("renders the record id without a doc argument on an undocumented enum", () => { + const code = codeFor("Identity/Client.php"); + + expect(code).toContain([ + " return Type::enum([", + " Variant::constant('tablet', 1),", + " ], recordId: 'identity/identity.skir:Client');", + ].join("\n")); + expect(code).not.toContain("doc:"); + }); + + it("renders method docs only for documented methods", () => { + const code = codeFor("Identity/SkirMethods.php"); + + expect(code).toContain([ + " return new MethodDescriptor(", + " name: 'GetInvitation',", + " number: 10,", + " requestType: Type::string(),", + " responseType: Invitation::skirType(),", + " doc: 'Returns the invitation.',", + " );", + ].join("\n")); + expect(code).toContain([ + " name: 'Ping',", + " number: 11,", + " requestType: Type::string(),", + " responseType: Type::string(),", + " );", + ].join("\n")); + expect(code).toContain(` doc: ${phpSingleQuotedLiteral(TRICKY_DOC)},`); + expect(code.match(/doc:/g)).toHaveLength(2); + }); +}); + +describe("PHP metadata argument helpers", () => { + it("escapes quotes, backslashes, and line breaks into a one-line PHP expression", () => { + const literal = phpSingleQuotedLiteral(TRICKY_DOC); + + expect(literal).toBe( + "'It\\'s a \"quote\", a back\\\\slash'.\"\\n\".'and a second line.\\\\'", + ); + expect(literal).not.toContain("\n"); + expect(evaluatePhpExpression(literal)).toBe(TRICKY_DOC); + }); + + it("round-trips carriage returns, dollar signs, and empty text through PHP", () => { + for (const text of ["", "a\r\nb", "$name {$x} \\n", "\n", "trailing\n"]) { + expect(evaluatePhpExpression(phpSingleQuotedLiteral(text))).toBe(text); + } + }); + + it("renders the doc argument only for non-blank docs", () => { + expect(renderDocArgument(undefined)).toBe(""); + expect(renderDocArgument("")).toBe(""); + expect(renderDocArgument(" \n\t")).toBe(""); + expect(renderDocArgument("The phone app.")).toBe(", doc: 'The phone app.'"); + }); + + it("always renders the record id and appends the doc when present", () => { + expect(renderRecordMetadataArguments({ recordId: "a/b.skir:Outer.Inner" })) + .toBe(", recordId: 'a/b.skir:Outer.Inner'"); + expect(renderRecordMetadataArguments({ recordId: "a/b.skir:Outer", doc: "It's documented." })) + .toBe(", recordId: 'a/b.skir:Outer', doc: 'It\\'s documented.'"); + }); +});