recursive types (and operations on them, like pretty-printing, comparison and unification) seem to be working.

big part of the code base still needs to be 'ported' to the updated type constructors.
This commit is contained in:
Joeri Exelmans 2025-05-05 17:17:45 +02:00
parent 55c5d7cffa
commit 8eec5b9239
34 changed files with 523 additions and 295 deletions

View file

@ -1,13 +1,12 @@
import { eqType } from "../primitives/type.js";
import { zip } from "../util/util.js";
import { pretty } from '../util/pretty.js';
import { prettyT } from "../util/pretty.js";
import { pretty, prettyT } from '../util/pretty.js';
// constructor for generic types
// for instance, the type:
// ∀a: a -> a -> Bool
// is created by
// makeGeneric(a => fnType(a)(fnType(a)(Bool)))
// makeGeneric(a => fnType(() => a)(() => fnType(() => a)(() => Bool)))
export const makeGeneric = callback => {
// type variables to make available:
const typeVars = ['a', 'b', 'c', 'd', 'e'].map(Symbol);
@ -20,14 +19,24 @@ export const onlyOccurring = (type, typeVars) => ({
type,
});
// From the given set of type variables, return only those that occur in the given type.
export const occurring = (type, typeVars) => {
// console.log("occurring", type);
const __occurring = state => typeVars => type => {
if (typeVars.has(type)) {
// type IS a type variable:
return new Set([type]);
}
return new Set(type.params.flatMap(p => [...occurring(p, typeVars)]));
const tag = state.nextTag++;
state.seen.add(tag);
return new Set(type.params.flatMap(p => {
const innerType = p(tag);
if (state.seen.has(innerType)) {
return []; // no endless recursion!
}
return [...__occurring(state)(typeVars)(innerType)];
}));
};
// From the given set of type variables, return only those that occur in the given type.
export const occurring = (type, typeVars) => {
return __occurring({nextTag:0, seen: new Set()})(typeVars)(type);
};
// Merge 2 substitution-mappings, uni-directional.
@ -64,16 +73,16 @@ export const mergeTwoWay = (m1, m2) => {
// checkConflict(m2, m1); // <- don't think this is necessary...
// actually merge
let stable = false;
let deleted = new Set();
let deletions = new Set();
while (!stable) {
let d;
// notice we swap m2 and m1, so the rewriting can happen both ways:
[stable, m2, m1, d] = mergeOneWay(m1, m2);
deleted = deleted.union(d);
deletions = deletions.union(d);
}
const result = {
substitutions: new Map([...m1, ...m2]),
deleted, // deleted type variables
deletions, // deleted type variables
};
// console.log("mergeTwoWay result =", result);
return result;
@ -81,9 +90,13 @@ export const mergeTwoWay = (m1, m2) => {
// Thanks to Hans for pointing out that this algorithm exactly like "Unification" in Prolog (hence the function name):
// https://www.dai.ed.ac.uk/groups/ssp/bookpages/quickprolog/node12.html
const unifyInternal = (typeVars, fType, aType) => {
// console.log("unify", pretty({typeVars, fType, aType}));
//
// Parameters:
// typeVars: all the type variables in both fType and aType
// fType, aType: generic types to unify
// fStack, aStack: internal use.
const __unify = (typeVars, fType, aType, fStack=[], aStack=[]) => {
console.log("__unify", {typeVars, fType, aType, fStack, aStack});
if (typeVars.has(fType)) {
// simplest case: formalType is a type paramater
// => substitute with actualType
@ -107,60 +120,84 @@ const unifyInternal = (typeVars, fType, aType) => {
},
};
}
// recursively unify
if (fType.symbol !== aType.symbol) {
throw new Error(`cannot unify ${prettyT(fType)} and ${prettyT(aType)}`);
}
else {
// console.log("symbols match - unify recursively", formal.symbol);
const unifiedParams =
zip(fType.params, aType.params)
.map(([fParam, aParam]) => unifyInternal(typeVars, fParam, aParam));
const {substitutions, deleted} =
unifiedParams.reduce(({substitutions: s, deleted: d}, cur) => {
// console.log('merging', s, cur.substitutions);
const {substitutions, deleted} = mergeTwoWay(s, cur.substitutions);
return {
substitutions,
deleted: deleted.union(d),
};
}, { substitutions: new Map(), deleted: new Set() });
// console.log(pretty({unifiedParams}));
return {
substitutions,
genericType: {
typeVars: typeVars.difference(substitutions).difference(deleted),
type: {
symbol: fType.symbol,
params: unifiedParams.map(p => p.genericType.type),
},
},
};
}
const fTag = fStack.length;
const aTag = aStack.length;
const unifications =
zip(fType.params, aType.params)
.map(([getFParam, getAParam]) => {
const fParam = getFParam(fTag);
const aParam = getAParam(aTag);
// type recursively points to an enclosing type that we've already seen
if (fStack[fParam] !== aStack[aParam]) {
// note that both are also allowed not to be mapped (undefined)
throw new Error("cannot unify: types differ in their recursion");
}
if (fStack[fParam] !== undefined) {
const type = fStack[fParam];
return () => ({
substitutions: new Map(),
genericType: {
typeVars,
type,
},
});
}
return parent => __unify(typeVars, fParam, aParam,
[...fStack, parent],
[...aStack, parent]);
});
const unifiedParams = unifications.map(getParam => {
return parent => getParam(parent).genericType.type;
});
const type = {
symbol: fType.symbol,
params: unifiedParams,
};
const [unifiedSubstitutions, unifiedTypeVars] = unifications.reduce((acc, getParam) => {
const self = Symbol();
const {substitutions, deletions} = mergeTwoWay(acc[0], getParam(self).substitutions);
return [substitutions, acc[1]
.difference(substitutions)
.difference(deletions)];
}, [new Map(), typeVars]);
return {
substitutions: unifiedSubstitutions,
genericType: {
typeVars: unifiedTypeVars,
type,
},
};
};
export const unify = (fGenericType, aGenericType) => {
let allTypeVars;
[allTypeVars, fGenericType, aGenericType] = safeUnionTypeVars(fGenericType, aGenericType);
const {genericType} = unifyInternal(
allTypeVars,
fGenericType.type,
aGenericType.type,
)
const {genericType} = __unify(allTypeVars, fGenericType.type, aGenericType.type);
return recomputeTypeVars(genericType);
}
};
export const substitute = (type, substitutions) => {
// console.log("substitute", {type, substitutions})
if (substitutions.has(type)) {
return substitutions.get(type);
}
if (typeof type === "symbol") {
return type; // nothing to substitute here
}
return {
export const substitute = (type, substitutions, stack=[]) => {
console.log('substitute...', {type, substitutions, stack});
return substitutions.get(type)
|| {
symbol: type.symbol,
params: type.params.map(p => substitute(p, substitutions)),
params: type.params.map(getParam => parent => {
const param = getParam(stack.length);
const have = stack[param];
return (have !== undefined)
? have
: substitute(param, substitutions, [...stack, parent]);
}),
};
};
@ -178,10 +215,9 @@ export const assignFn = (genFnType, paramType) => {
[allTypeVars, genFnType, paramType] = safeUnionTypeVars(genFnType, paramType);
const [inType] = genFnType.type.params;
const {substitutions} = unifyInternal(allTypeVars, inType, paramType.type);
// console.log({genFnType: prettyT(genFnType), paramType: prettyT(paramType), substitutions})
const substitutedFnType = substitute(genFnType.type, substitutions);
return recomputeTypeVars(onlyOccurring(substitutedFnType, allTypeVars));
}
};
export const recomputeTypeVars = (genType) => {
const newTypeVars = ['a', 'b', 'c', 'd', 'e', 'f', 'g'].map(Symbol);
@ -195,11 +231,11 @@ export const recomputeTypeVars = (genType) => {
type: substitute(genType.type, subst),
};
return substType;
}
};
export const safeUnionTypeVars = (genTypeA, genTypeB) => {
const substTypeA = recomputeTypeVars(genTypeA);
const substTypeB = recomputeTypeVars(genTypeB);
const allTypeVars = substTypeA.typeVars.union(substTypeB.typeVars);
return [allTypeVars, substTypeA, substTypeB];
}
};