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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` (`<module path>:<qualified name>`, 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 |
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ export {
export {
indent,
PHP_FILE_HEADER,
phpSingleQuotedLiteral,
renderDocArgument,
renderPhpFile,
renderRecordMetadataArguments,
} from "./php.js";
export {
ComposerAutoloadConflictError,
Expand Down Expand Up @@ -68,6 +71,7 @@ export type {
NormalizedRecord,
NormalizedSchema,
NormalizedType,
SkirDoc,
SkirField,
SkirMethod,
SkirModule,
Expand Down
20 changes: 20 additions & 0 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ export interface SkirToken {
readonly text: string;
}

export interface SkirDoc {
readonly text: string;
}

export type SkirRecordNamePart =
| string
| SkirToken
Expand All @@ -31,6 +35,7 @@ export type SkirField =
readonly name: string | SkirToken;
readonly number: number;
readonly type?: SkirType;
readonly doc?: SkirDoc;
}
| {
readonly kind: "removed";
Expand All @@ -45,6 +50,7 @@ export interface SkirRecord {
readonly fields?: readonly SkirField[];
readonly removedNumbers?: readonly number[];
readonly phpClassName?: string;
readonly doc?: SkirDoc;
}

export interface SkirRecordLocation {
Expand All @@ -60,6 +66,7 @@ export interface SkirMethod {
readonly number: number;
readonly requestType?: SkirType;
readonly responseType?: SkirType;
readonly doc?: SkirDoc;
}

export interface SkirModule {
Expand Down Expand Up @@ -100,19 +107,30 @@ 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 {
readonly kind: "field";
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, `<module path>:<qualified name>`, 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 (
Expand All @@ -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 {
Expand Down
26 changes: 26 additions & 0 deletions src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
NormalizedRecord,
NormalizedSchema,
NormalizedType,
SkirDoc,
SkirField,
SkirMethod,
SkirModule,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -272,6 +283,8 @@ function recordMapSource(
modulePath,
qualifiedName,
identity: `${modulePath}::${qualifiedName}`,
recordId: `${modulePath}:${qualifiedName}`,
...docProperty(docText(location.record.doc)),
recordType,
...(location.record.phpClassName === undefined
? {}
Expand Down Expand Up @@ -409,6 +422,7 @@ function normalizeField(
name,
number: field.number,
hasPayload: false,
...docProperty(docText(field.doc)),
};
}

Expand All @@ -421,6 +435,7 @@ function normalizeField(
number: field.number,
hasPayload: true,
type: normalizeType(field.type, context),
...docProperty(docText(field.doc)),
};
}

Expand All @@ -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)),
};
}

Expand Down Expand Up @@ -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;
}
Expand Down
51 changes: 51 additions & 0 deletions src/php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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("'", "\\'")}'`;
}
13 changes: 9 additions & 4 deletions src/render-enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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");

Expand All @@ -141,7 +146,7 @@ function renderEnumSkirType(
"{",
` return ${typeClass}::enum([`,
entries,
" ]);",
` ]${renderRecordMetadataArguments(record)});`,
"}",
].join("\n");
}
Expand Down
5 changes: 4 additions & 1 deletion src/render-rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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");
Expand Down
Loading
Loading