interactive prompt can handle polymorphic types

This commit is contained in:
Joeri Exelmans 2025-04-02 15:49:43 +02:00
parent a0e3aa0cb3
commit 4a4983f693
20 changed files with 485 additions and 276 deletions

View file

@ -1,160 +1,180 @@
import { eqType } from "../type.js";
import { eqType } from "../primitives/type.js";
import { zip } from "../util/util.js";
import { pretty } from '../util/pretty.js';
import { prettyT } from "../structures/types.js";
// constructor for generic types
// for instance, the type:
// a -> a -> Bool
// ∀a: a -> a -> Bool
// is created by
// makeGeneric(a => fnType({in: a, out: fnType({in: a, out: 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(
letter => ({
symbol: Symbol(letter),
params: [],
}));
const typeVars = ['a', 'b', 'c', 'd', 'e'].map(Symbol);
const type = callback(...typeVars);
return {
typeVars: occurring(type, new Set(typeVars)),
type,
};
return onlyOccurring(type, new Set(typeVars));
};
export const onlyOccurring = (type, typeVars) => ({
typeVars: occurring(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);
if (typeVars.has(type)) {
// type IS a type variable:
return new Set([type]);
}
return new Set(type.params.flatMap(p => [...occurring(p, typeVars)]));
}
};
// Merge 2 substitution-mappings, uni-directional.
const mergeOneWay = (m1, m2) => {
const m1copy = new Map(m1);
const m2copy = new Map(m2);
for (const [key1, val1] of m1copy.entries()) {
if (m2copy.has(val1)) {
m1copy.set(key1, m2.get(val1));
m2copy.delete(val1);
return [false, m1copy, m2copy, new Set([val1])];
for (const [var1, typ1] of m1copy.entries()) {
if (m2copy.has(typ1)) {
// typ1 is a typeVar for which we also have a substitution
// -> fold substitutions
m1copy.set(var1, m2.get(typ1));
m2copy.delete(typ1);
return [false, m1copy, m2copy, new Set([typ1])];
}
}
return [true, m1copy, m2copy, new Set()]; // stable
}
};
// Merge 2 substitution-mappings, bi-directional.
export const mergeTwoWay = (m1, m2) => {
// check for conflicts:
for (const [typeVar, actual] of m1) {
if (m2.has(typeVar)) {
const other = m2.get(typeVar);
if (!eqType(actual, other)) {
throw new Error(`conflicting substitution: ${pretty(actual)}vs. ${pretty(other)}`);
const checkConflict = (m1, m2) => {
for (const [var1, typ1] of m1) {
if (m2.has(var1)) {
const other = m2.get(var1);
if (!eqType(typ1, other)) {
throw new Error(`conflicting substitution: ${pretty(typ1)}vs. ${pretty(other)}`);
}
}
}
};
// Merge 2 substitution-mappings, bi-directional.
export const mergeTwoWay = (m1, m2) => {
// console.log("mergeTwoWay", {m1, m2});
checkConflict(m1, m2);
// checkConflict(m2, m1); // <- don't think this is necessary...
// actually merge
let stable = false;
let deletedTypeVars = new Set();
let deleted = 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);
deletedTypeVars = deletedTypeVars.union(d);
deleted = deleted.union(d);
}
return [new Map([...m1, ...m2]), deletedTypeVars];
}
const result = {
substitutions: new Map([...m1, ...m2]),
deleted, // deleted type variables
};
// console.log("mergeTwoWay result =", result);
return result;
};
// 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
export const unify = (
{typeVars: formalTypeVars, type: formalType},
{typeVars: actualTypeVars, type: actualType},
) => {
// console.log("unify", pretty({formalTypeVars, formalType, actualTypeVars, actualType}));
const unifyInternal = (typeVars, fType, aType) => {
// console.log("unify", pretty({typeVars, fType, aType}));
if (formalTypeVars.has(formalType)) {
if (typeVars.has(fType)) {
// simplest case: formalType is a type paramater
// => substitute with actualType
// console.log("assign actual to formal");
return {
substitutions: new Map([[formalType, actualType]]),
typeVars: new Set([
...actualTypeVars,
...[...formalTypeVars].filter(a => a !== formalType),
]),
type: actualType,
substitutions: new Map([[fType, aType]]),
genericType: {
typeVars: typeVars.difference(new Set([fType])),
type: aType,
},
};
}
if (actualTypeVars.has(actualType)) {
if (typeVars.has(aType)) {
// same as above, but in the other direction
// console.log("assign formal to actual");
return {
substitutions: new Map([[actualType, formalType]]),
typeVars: new Set([
...[...actualTypeVars].filter(a => a !== actualType),
...formalTypeVars,
]),
type: formalType,
substitutions: new Map([[aType, fType]]),
genericType: {
typeVars: typeVars.difference(new Set([aType])),
type: fType,
},
};
}
// recursively unify
if (formalType.symbol !== actualType.symbol) {
throw new Error(`cannot unify ${pretty(formalType.symbol)} and ${pretty(actualType.symbol)}`);
if (fType.symbol !== aType.symbol) {
throw new Error(`cannot unify ${prettyT(fType)} and ${prettyT(aType)}`);
}
else {
// console.log("symbols match - unify recursively", formalType.symbol);
const unifiedParams = zip(formalType.params, actualType.params).map(([formalParam, actualParam]) => unify({typeVars: formalTypeVars, type: formalParam}, {typeVars: actualTypeVars, type: actualParam}));
const [unifiedSubstitusions, deleted] = unifiedParams.reduce(([substitutionsSoFar, deletedSoFar], cur) => {
// console.log('merging', substitutionsSoFar, cur.substitutions);
const [newSubstitutions, deleted] = mergeTwoWay(substitutionsSoFar, cur.substitutions);
return [newSubstitutions, deletedSoFar.union(deleted)];
}, [new Map(), new Set()]);
const unifiedTypeVars = new Set([
...actualTypeVars,
...formalTypeVars,
].filter(a => !unifiedSubstitusions.has(a) && !deleted.has(a)));
// 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: unifiedSubstitusions,
typeVars: unifiedTypeVars,
type: {
symbol: formalType.symbol,
params: unifiedParams.map(p => p.type),
substitutions,
genericType: {
typeVars: typeVars.difference(substitutions).difference(deleted),
type: {
symbol: fType.symbol,
params: unifiedParams.map(p => p.genericType.type),
},
},
};
}
};
export const unify = (fGenericType, aGenericType) => {
const {genericType} = unifyInternal(
fGenericType.typeVars.union(aGenericType.typeVars),
fGenericType.type,
aGenericType.type,
)
return genericType;
}
export const substitute = (type, substitutions) => {
// console.log("substitute", {type, substitutions})
if (substitutions.has(type)) {
// type IS a type var to be substituted:
return substitutions.get(type);
}
if (type.params.length === 0) {
// Attention: there's a reason why we have this special case.
// Types are compared by object ID, so we don't want to create a new object for a type that takes no type parameters (then the newly create type would differ).
// Should fix this some day.
return type;
if (typeof type === "symbol") {
return type; // nothing to substitute here
}
return {
symbol: type.symbol,
params: type.params.map(p => substitute(p, substitutions)),
};
}
};
export const assign = (genFnType, paramType) => {
const [inType, outType] = genFnType.type.params;
const matchedInType = unify({
typeVars: genFnType.typeVars,
type: inType,
}, paramType);
const substitutedOutType = substitute(outType, matchedInType.substitutions);
return {
typeVars: matchedInType.typeVars,
type: substitutedOutType,
};
const allTypeVars = genFnType.typeVars.union(paramType.typeVars)
const {substitutions} = unifyInternal(allTypeVars, inType, paramType.type);
const substitutedOutType = substitute(outType, substitutions);
return onlyOccurring(substitutedOutType, allTypeVars);
};
export const assignFn = (genFnType, paramType) => {
const [inType] = genFnType.type.params;
const allTypeVars = genFnType.typeVars.union(paramType.typeVars)
const {substitutions} = unifyInternal(allTypeVars, inType, paramType.type);
// console.log({genFnType: prettyT(genFnType), paramType: prettyT(paramType), substitutions})
const substitutedFnType = substitute(genFnType.type, substitutions);
return onlyOccurring(substitutedFnType, allTypeVars);
}