preserves/implementations/javascript/packages/schema/src/reader.ts

211 lines
8.0 KiB
TypeScript

import { Reader, Annotated, Dictionary, is, peel, preserves, Record, strip, Tuple, Value, Position, position, ReaderOptions, stringify } from '@preserves/core';
import { Input, NamedPattern, Pattern, Schema } from './meta';
import * as M from './meta';
import { SchemaSyntaxError } from './error';
const positionTable = new WeakMap<Input & object, Position>();
export function recordPosition<X extends Input & object>(v: X, pos: Position | null): X {
if (pos === null) { console.error('Internal error in Schema reader: null source position for', v); }
if (pos !== null) positionTable.set(v, pos);
return v;
}
export function refPosition(v: Input & object): Position | null {
return positionTable.get(v) ?? null;
}
function splitBy<T>(items: Array<T>, separator: T): Array<Array<T>> {
const groups: Array<Array<T>> = [];
let group: Array<T> = [];
function finish() {
if (group.length > 0) {
groups.push(group);
group = [];
}
}
for (const item of items) {
if (is(item, separator)) {
finish();
} else {
group.push(item);
}
}
finish();
return groups;
}
function invalidClause(clause: Array<Input>): never {
throw new SchemaSyntaxError(preserves`Invalid Schema clause: ${clause}`,
position(clause[0] ?? false));
}
function invalidPattern(name: string, item: Input, pos: Position | null): never {
throw new SchemaSyntaxError(`Invalid pattern in ${name}: ${stringify(item)}`, pos);
}
export function readSchema(source: string, options?: ReaderOptions<never>): Schema {
const toplevelTokens = new Reader<never>(source, { ... options ?? {}, includeAnnotations: true }).readToEnd();
return parseSchema(toplevelTokens);
}
export function parseSchema(toplevelTokens: Array<Input>): Schema {
const toplevelClauses = splitBy(peel(toplevelTokens) as Array<Input>, M.DOT);
let version: M.Version | undefined = void 0;
let pointer: M.PointerName = false;
let definitions = new Dictionary<Pattern, never>();
for (const clause of toplevelClauses) {
if (!Array.isArray(clause)) {
invalidClause(clause);
} else if (clause.length >= 2 && is(clause[1], M.EQUALS)) {
const name = peel(clause[0]);
if (typeof name !== 'symbol') invalidClause(clause);
if (!M.isValidToken(name.description!)) {
throw new SchemaSyntaxError(preserves`Invalid definition name: ${name}`,
position(clause[0]));
}
if (definitions.has(name)) {
throw new SchemaSyntaxError(preserves`Duplicate definition: ${clause}`,
position(clause[0]));
}
definitions.set(name, parseDefinition(name, clause.slice(2)));
} else if (clause.length === 2 && is(clause[0], M.$version)) {
version = M.asVersion(peel(clause[1]));
} else if (clause.length === 2 && is(clause[0], M.$pointer)) {
const pos = position(clause[1]);
const stx = peel(clause[1]);
const quasiName = 'pointer name specification';
pointer = M.asPointerName((stx === false) ? stx
: (typeof stx === 'symbol') ? parseRef(quasiName, pos, stx)
: invalidPattern(quasiName, stx, pos));
} else {
invalidClause(clause);
}
}
if (version === void 0) {
throw new SchemaSyntaxError("Schema: missing version declaration.", null);
}
return M.asSchema(Record(M.$schema, [new Dictionary<Value>([
[M.$version, version],
[M.$pointer, pointer],
[M.$definitions, definitions],
])]));
}
function parseDefinition(name: symbol, body: Array<Input>): Pattern {
return parseOp(body, M.ORSYM, p => parseOp(p, M.ANDSYM, p => parseBase(name, p)));
}
function parseOp(body: Array<Input>, op: Input, k: (p: Array<Input>) => Pattern): Pattern {
const pieces = splitBy(body, op);
if (pieces.length === 1) return k(pieces[0]);
switch (op) {
case M.ORSYM: return Record(M.$or, [pieces.map(k)]);
case M.ANDSYM: return Record(M.$and, [pieces.map(k)]);
default: throw new Error("Internal error: unexpected operator");
}
}
function findName(x: Input): symbol | false {
if (!Annotated.isAnnotated<never>(x)) return false;
for (const a0 of x.annotations) {
const a = peel(a0);
if (typeof a === 'symbol') return a;
}
return false;
}
function parseRef(name: string, pos: Position | null, item: symbol): Pattern {
const s = item.description;
if (s === void 0) invalidPattern(name, item, pos);
if (s[0] === '=') return Record(M.$lit, [Symbol.for(s.slice(1))]);
const pieces = s.split('.');
if (pieces.length === 1) {
return recordPosition(Record(M.$ref, [M.$thisModule, item]), pos);
} else {
return recordPosition(Record(M.$ref, [
pieces.slice(0, pieces.length - 1).map(Symbol.for),
Symbol.for(pieces[pieces.length - 1])
]), pos);
}
}
function parseBase(name: symbol, body: Array<Input>): Pattern {
body = peel(body) as Array<Input>;
if (body.length !== 1) {
invalidPattern(stringify(name), body, body.length > 0 ? position(body[0]) : position(body));
}
const pos = position(body[0]);
const item = peel(body[0]);
const walk = (b: Input): Pattern => parseBase(name, [b]);
const namedwalk = (b: Input): NamedPattern => {
const name = findName(b);
if (name === false) return walk(b);
return Record(M.$named, [name, walk(b)]);
};
const walkitems = (b: Input): Pattern[] => {
b = peel(b);
if (!Array.isArray(b)) complain();
return b.map(walk);
};
function complain(): never {
invalidPattern(stringify(name), item, pos);
}
if (typeof item === 'symbol') {
return parseRef(stringify(name), position(body[0]), item);
} else if (Record.isRecord<Input, Tuple<Input>, never>(item)) {
const label = item.label;
if (Record.isRecord<Input, [], never>(label)) {
if (label.length !== 0) complain();
switch (label.label) {
case M.$lit:
if (item.length !== 1) complain();
return Record(M.$lit, [item[0]]);
case M.$or:
if (item.length !== 1) complain();
return Record(M.$or, [walkitems(item[0])]);
case M.$and:
if (item.length !== 1) complain();
return Record(M.$and, [walkitems(item[0])]);
case M.$rec:
if (item.length !== 2) complain();
return Record(M.$rec, [walk(item[0]), walk(item[1])]);
default:
complain();
}
} else {
return Record(M.$rec, [Record(M.$lit, [label]), Record(M.$tuple, [item.map(namedwalk)])]);
}
} else if (Array.isArray(item)) {
if (is(item[item.length - 1], M.DOTDOTDOT)) {
if (item.length < 2) complain();
return Record(M.$tuple_STAR_, [
item.slice(0, item.length - 2).map(namedwalk),
namedwalk(item[item.length - 2]),
]);
} else {
return Record(M.$tuple, [item.map(namedwalk)]);
}
} else if (Dictionary.isDictionary<Input, never>(item)) {
if (item.size === 2 && item.has(M.DOTDOTDOT)) {
const v = item.clone();
v.delete(M.DOTDOTDOT);
const [[kp, vp]] = v.entries();
return Record(M.$dictof, [walk(kp), walk(vp)]);
} else {
return Record(M.$dict, [item.mapEntries<Pattern, Input, never>(([k, vp]) =>
[strip(k), walk(vp)])]);
}
} else if (Set.isSet<never>(item)) {
if (item.size !== 1) complain();
const [vp] = item.entries();
return Record(M.$setof, [walk(vp)]);
} else {
return Record(M.$lit, [strip(item)]);
}
}