simplify: no distinction between generic types and 'normal' types.

This commit is contained in:
Joeri Exelmans 2025-05-08 16:58:07 +02:00
parent b4826605af
commit a664ddac8a
27 changed files with 535 additions and 360 deletions

View file

@ -1,36 +1,30 @@
import { inspect } from 'node:util';
import { symbolDict, symbolFunction, symbolList, symbolProduct, symbolSum } from '../structures/type_constructors.js';
import { symbolSet } from "../structures/type_constructors.js";
import { mapRecursiveStructure } from './util.js';
import { getHumanReadableName } from '../primitives/symbol.js';
import { getSymbol } from '../primitives/type.js';
export function pretty(obj) {
return inspect(obj, { colors: true, depth: null, breakLength: 120 });
}
// Pretty print Type
export const prettyT = type => {
return mapRecursiveStructure(([type, m, seen], map) => {
if (typeof type === "symbol") {
// type variable
return type.description;
}
// if (type.params === undefined) {
// throw new Error("parameter is not a Type ... did you mean to call prettyGenT instead?")
// }
if (!m.has(type)) {
m.add(type); // next time we encounter this type, we'll only render a placeholder
const params = type.params.map(p => map([p(type), m, seen])());
// if while visiting the children, we encountered ourselves, add annotation:
const annot = seen.has(type) ? seen.get(type) : ``;
return renderType(type.symbol, annot, params);
}
if (!seen.has(type)) {
seen.set(type, `#${seen.size}`);
}
return seen.get(type);
})([type, new Set(), new Map()])();
};
export const _prettyT = (depth, tags) => type => {
if (typeof type === 'number' && type < depth) {
// we've already seen this type, so we'll tag it
// we mutate tags in-place so our parent type can see it
const hashTag = `#${tags.size}`;
// upper level will be tagged:
tags.set(type, hashTag);
// and this level is entirely replaced by tag:
return hashTag;
}
const params = type.params.map(p => _prettyT(depth+1, tags)(p(depth)));
const annot = tags.get(depth) || '';
return renderType(getSymbol(type), annot, params);
}
export const prettyT = type => _prettyT(0, new Map())(type);
const renderType = (symbol, annot, params) => {
return {
@ -42,8 +36,3 @@ const renderType = (symbol, annot, params) => {
[symbolDict] : `${annot}(${params[0]} => ${params[1]})`,
}[symbol] || getHumanReadableName(symbol);
};
// Pretty print GenericType
export const prettyGenT = genericType => {
return `${[...genericType.typeVars].map(prettyT).sort((a, b) => a.localeCompare(b)).join(",")}: ${prettyT(genericType.type)}`;
};

View file

@ -25,3 +25,15 @@ const _mapRecursiveStructure = mapping => transform => root => {
};
export const mapRecursiveStructure = _mapRecursiveStructure(new Map());
export const memoize = callback => {
let called = false
let result;
return () => {
if (!called) {
result = callback();
called = true;
}
return result;
};
};