preserves/implementations/javascript/packages/schema/src/compiler/genctor.ts

42 lines
1.3 KiB
TypeScript

import * as M from '../meta';
import { block, braces, Item, keyvalue, parens, seq } from "./block";
import { FieldType, renderType, SimpleType } from "./type";
export function genConstructor(
name: string,
variant: string | undefined,
arg: SimpleType,
resultType: Item): Item
{
const formals: Array<[string, FieldType]> = [];
let simpleValue = false;
function examine(t: FieldType, name: string): void {
if (t.kind !== 'unit') {
formals.push([name, t]);
}
}
if (arg.kind === 'record') {
arg.fields.forEach(examine);
} else {
examine(arg, 'value');
simpleValue = variant === void 0;
}
const initializers: Item[] = (variant !== void 0)
? [keyvalue('_variant', JSON.stringify(variant))]
: [];
formals.forEach(([n, _t]) => initializers.push(n));
return seq(`export function ${M.jsId(name)}`,
parens(... formals.map(([n, t]) => seq(n, ': ', renderType(t)))),
': ', resultType, ' ', block(
seq(`return `,
((arg.kind === 'unit' && initializers.length === 0)
? 'null'
: (simpleValue
? 'value'
: braces(... initializers))))));
}