fix bug in type inferencing
This commit is contained in:
parent
bb6e742f5f
commit
c3f7cea310
8 changed files with 205 additions and 155 deletions
301
src/eval.ts
301
src/eval.ts
|
|
@ -1,10 +1,10 @@
|
|||
import { Double, fnType, getHumanReadableName, getSymbol, Int, isTypeVar, mergeUnifications, NotAFunctionError, occurring, prettyT, prettyU, recomputeTypeVarsWithInverse, reduceUnification, substitute, symbolFunction, trie, TYPE_VARS, UNBOUND_SYMBOLS, UnifyError, unifyLL } from "dope2";
|
||||
import { Double, eqType, fnType, getHumanReadableName, getSymbol, Int, isTypeVar, mergeUnifications, NotAFunctionError, occurring, prettyT, prettyU, recomputeTypeVarsWithInverse, reduceUnification, substitute, symbolFunction, transitivelyGrow, trie, TYPE_VARS, UNBOUND_SYMBOLS, UnifyError, unifyLL } from "dope2";
|
||||
|
||||
import type { ExprBlockState } from "./ExprBlock";
|
||||
import type { InputValueType } from "./InputBlock";
|
||||
|
||||
const IS_DEV = (import.meta.env.MODE === "development");
|
||||
const VERBOSE = true;
|
||||
const VERBOSE = true && IS_DEV;
|
||||
|
||||
export interface Environment {
|
||||
names: any;
|
||||
|
|
@ -57,7 +57,8 @@ export const evalExprBlock = (s: ExprBlockState, env: Environment): [ResolvedTyp
|
|||
return evalLetInBlock(s.value, s.name, s.inner, env);
|
||||
}
|
||||
else { // (s.kind === "lambda")
|
||||
return evalLambdaBlock(s.paramName, s.expr, env);
|
||||
const [resolved, env2] = evalLambdaBlock(s.paramName, s.expr, env);
|
||||
return [resolved, env2];
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -68,15 +69,9 @@ export function evalInputBlock(text: string, value: InputValueType, env: Environ
|
|||
else if (value.kind === "name") {
|
||||
const found = trie.get(env.names)(text);
|
||||
if (found) {
|
||||
if (found.kind === "unknown") {
|
||||
// console.log('returning', text, 'as-is');
|
||||
return [found, env]; // don't rewrite lambda parameters
|
||||
}
|
||||
// console.log('rewriting', text);
|
||||
return recomputeTypeVarsForEnv(text, found, env);
|
||||
return [found, env]; // don't rewrite lambda parameters
|
||||
}
|
||||
}
|
||||
// kind === "text" -> unresolved
|
||||
const [t, env2] = makeTypeVar(env, 'err')
|
||||
return [{
|
||||
kind: "error",
|
||||
|
|
@ -88,24 +83,35 @@ export function evalInputBlock(text: string, value: InputValueType, env: Environ
|
|||
}
|
||||
|
||||
export function evalCallBlock(fn: ExprBlockState, input: ExprBlockState, env: Environment): [ResolvedType,Environment] {
|
||||
const [fnResolved, env2] = evalExprBlock(fn, env);
|
||||
const [inputResolved, env3] = evalExprBlock(input, env2);
|
||||
if (VERBOSE) {
|
||||
console.log('==== evalCallBlock ====');
|
||||
console.log('env :', env);
|
||||
console.log('fnResolved :', fnResolved);
|
||||
console.log('env2 :', env2);
|
||||
console.log('inputResolved:', inputResolved);
|
||||
console.log('env3 :', env3);
|
||||
console.log('=======================');
|
||||
let [fnResolved, env2] = evalExprBlock(fn, env);
|
||||
if (fnResolved.kind === "value") {
|
||||
[fnResolved, env2] = recomputeTypeVarsForEnv("<name unused>", fnResolved, env2);
|
||||
}
|
||||
return evalCallBlock2(fnResolved, inputResolved, env3);
|
||||
let [inputResolved, env3] = evalExprBlock(input, env2);
|
||||
if (inputResolved.kind === "value") {
|
||||
[inputResolved, env3] = recomputeTypeVarsForEnv("<name unused>", inputResolved, env3);
|
||||
}
|
||||
const result = evalCallBlock2(fnResolved, inputResolved, env3);
|
||||
if (VERBOSE) {
|
||||
// @ts-ignore
|
||||
result[0].__debug = (result[0].__debug || '') + `
|
||||
==== evalCallBlock ====
|
||||
env.typeVars : ${[...env.typeVars].map(getHumanReadableName)}
|
||||
env.nextFreeTypeVar: ${getHumanReadableName(UNBOUND_SYMBOLS[env.nextFreeTypeVar])}
|
||||
fn.kind : ${fn.kind}
|
||||
fn.t : ${prettyT(fnResolved.t)}
|
||||
env2.typeVars : ${[...env2.typeVars].map(getHumanReadableName)}
|
||||
env2.nextFreeTypeVar: ${getHumanReadableName(UNBOUND_SYMBOLS[env2.nextFreeTypeVar])}
|
||||
input.kind : ${input.kind}
|
||||
input.t : ${prettyT(inputResolved.t)}
|
||||
env3.typeVars : ${[...env3.typeVars].map(getHumanReadableName)}
|
||||
env3.nextFreeTypeVar: ${getHumanReadableName(UNBOUND_SYMBOLS[env3.nextFreeTypeVar])}
|
||||
=======================`;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function evalCallBlock2(fnResolved: ResolvedType, inputResolved: ResolvedType, env: Environment): [ResolvedType,Environment] {
|
||||
if (occurring(fnResolved.t).intersection(occurring(inputResolved.t)).size > 0) {
|
||||
throw new Error(`Precondition failed: function (${prettyT(fnResolved.t)}) and its input (${prettyT(inputResolved.t)}) have overlapping typevars!`);
|
||||
}
|
||||
if (getSymbol(fnResolved.t) !== symbolFunction) {
|
||||
// not a function...
|
||||
if (isTypeVar(fnResolved.t)) {
|
||||
|
|
@ -157,7 +163,8 @@ export function recomputeTypeVarsForEnv(name: string, resolved: ResolvedType, en
|
|||
// hacky
|
||||
const typeVars = env.typeVars.union(occurring(newType)) as Set<string>;
|
||||
const newEnv: Environment = {
|
||||
names: trie.insert(env.names)(name)(newResolved),
|
||||
// names: trie.insert(env.names)(name)(newResolved),
|
||||
names: env.names,
|
||||
typeVars,
|
||||
nextFreeTypeVar: highestTypeVar2(typeVars) + 1,
|
||||
};
|
||||
|
|
@ -166,24 +173,35 @@ export function recomputeTypeVarsForEnv(name: string, resolved: ResolvedType, en
|
|||
}
|
||||
|
||||
function evalCallBlock3(fnResolved: ResolvedType, inputResolved: ResolvedType, env: Environment): [ResolvedType,Environment] {
|
||||
let __debug = '';
|
||||
try {
|
||||
if (occurring(fnResolved.t).intersection(occurring(inputResolved.t)).size > 0) {
|
||||
throw new Error(`Precondition failed: function (${prettyT(fnResolved.t)}) and its input (${prettyT(inputResolved.t)}) have overlapping typevars!`);
|
||||
}
|
||||
|
||||
// turn input in to a function
|
||||
const [abstractOutputType, env2] = makeTypeVar(env, "<out>");
|
||||
const matchFnType = fnType(_ => inputResolved.t)(_ => abstractOutputType);
|
||||
|
||||
if (VERBOSE) {
|
||||
console.log('========= evalCallBlock3 =========')
|
||||
console.log('env :', env);
|
||||
console.log('fnKind :', fnResolved.kind);
|
||||
console.log('inputKind :', inputResolved.kind);
|
||||
console.log('fnType :', prettyT(fnResolved.t));
|
||||
console.log('inputType :', prettyT(inputResolved.t));
|
||||
console.log('matchFnType :', prettyT(matchFnType));
|
||||
__debug += `========= evalCallBlock3 =========
|
||||
env.typeVars : ${[...env.typeVars].map(getHumanReadableName)}
|
||||
nextFreeTypeVar: ${getHumanReadableName(UNBOUND_SYMBOLS[env.nextFreeTypeVar])}
|
||||
fnKind : ${fnResolved.kind}
|
||||
inputKind : ${inputResolved.kind}
|
||||
fnType : ${prettyT(fnResolved.t)}
|
||||
inputType : ${prettyT(inputResolved.t)}
|
||||
matchFnType : ${prettyT(matchFnType)}`;
|
||||
}
|
||||
|
||||
// unify both functions
|
||||
const unification = /*transitivelyGrow*/(unifyLL(fnResolved.t, matchFnType));
|
||||
|
||||
if (VERBOSE) {
|
||||
__debug += `
|
||||
unification : ${prettyU(unification)}`;
|
||||
}
|
||||
|
||||
const unificationR = reduceUnification(unification);
|
||||
const unifiedFnType = substitute(
|
||||
// matchFnType,
|
||||
|
|
@ -196,26 +214,25 @@ function evalCallBlock3(fnResolved: ResolvedType, inputResolved: ResolvedType, e
|
|||
|
||||
// we don't want to 'bubble up' our outType substitution, because it's just a temporary variable
|
||||
const unificationWithoutOutType = new Map([...unification].filter(([symbol]) => symbol !== abstractOutputType.symbol));
|
||||
|
||||
|
||||
if (VERBOSE) {
|
||||
console.log('unification :', prettyU(unification));
|
||||
console.log('unificationInvR :', prettyRU(unificationR));
|
||||
console.log('unifiedFnType :', prettyT(unifiedFnType));
|
||||
console.log('outType :', prettyT(outType));
|
||||
console.log('fn.unification :', prettyU(fnResolved.unification));
|
||||
console.log('input.unification :', prettyU(inputResolved.unification));
|
||||
console.log('unificationWithoutOutType:', prettyU(unificationWithoutOutType));
|
||||
__debug += `
|
||||
unificationInvR : ${prettyRU(unificationR)}
|
||||
unifiedFnType : ${prettyT(unifiedFnType)}
|
||||
outType : ${prettyT(outType)}
|
||||
fn.unification : ${prettyU(fnResolved.unification)}
|
||||
input.unification : ${prettyU(inputResolved.unification)}
|
||||
unificationWithoutOutType: ${prettyU(unificationWithoutOutType)}`;
|
||||
}
|
||||
|
||||
const grandUnification = [fnResolved.unification, inputResolved.unification]
|
||||
.reduce(mergeUnifications, unificationWithoutOutType);
|
||||
|
||||
// const grandUnification = unificationWithoutOutType;
|
||||
const grandUnification = transitivelyGrow([fnResolved.unification, inputResolved.unification]
|
||||
.reduce(mergeUnifications, unificationWithoutOutType));
|
||||
|
||||
if (VERBOSE) {
|
||||
console.log('grandUnification :', prettyU(grandUnification));
|
||||
console.log('==================================')
|
||||
__debug += `
|
||||
grandUnification : ${prettyU(grandUnification)}`;
|
||||
}
|
||||
|
||||
|
||||
if (inputResolved.kind === "error") {
|
||||
// throw inputResolved.e;
|
||||
|
|
@ -225,6 +242,8 @@ function evalCallBlock3(fnResolved: ResolvedType, inputResolved: ResolvedType, e
|
|||
depth: 0,
|
||||
t: outType,
|
||||
unification: grandUnification,
|
||||
// @ts-ignore
|
||||
__debug,
|
||||
}, newEnv];
|
||||
}
|
||||
if (fnResolved.kind === "error") {
|
||||
|
|
@ -236,6 +255,8 @@ function evalCallBlock3(fnResolved: ResolvedType, inputResolved: ResolvedType, e
|
|||
depth: fnResolved.depth+1,
|
||||
t: outType,
|
||||
unification: grandUnification,
|
||||
// @ts-ignore
|
||||
__debug,
|
||||
}, newEnv];
|
||||
}
|
||||
// if the above statement did not throw => types are compatible...
|
||||
|
|
@ -247,6 +268,8 @@ function evalCallBlock3(fnResolved: ResolvedType, inputResolved: ResolvedType, e
|
|||
i: outValue,
|
||||
t: outType,
|
||||
unification: grandUnification,
|
||||
// @ts-ignore
|
||||
__debug,
|
||||
}, newEnv];
|
||||
}
|
||||
else {
|
||||
|
|
@ -255,31 +278,22 @@ function evalCallBlock3(fnResolved: ResolvedType, inputResolved: ResolvedType, e
|
|||
kind: "unknown",
|
||||
t: outType,
|
||||
unification: grandUnification,
|
||||
// @ts-ignore
|
||||
__debug,
|
||||
}, newEnv];
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// if ((e instanceof UnifyError)) {
|
||||
if (VERBOSE) {
|
||||
console.log('UnifyError!', (e as Error).message);
|
||||
}
|
||||
// even though fn was incompatible with the given parameter, we can still suppose that our output-type will be that of fn...?
|
||||
const outType = fnResolved.t.params[1](fnResolved.t);
|
||||
try {
|
||||
return [{
|
||||
kind: "error",
|
||||
e: e as Error,
|
||||
depth: 0,
|
||||
t: outType,
|
||||
unification: mergeUnifications(fnResolved.unification, inputResolved.unification), // may throw!
|
||||
}, env];
|
||||
}
|
||||
catch (e) {
|
||||
if ((e instanceof UnifyError)) {
|
||||
return makeError(env, e);
|
||||
}
|
||||
throw e;
|
||||
__debug += '\n\nUnifyError! ' + (e as Error).message;
|
||||
}
|
||||
const err = makeError(env, e as Error);
|
||||
// @ts-ignore
|
||||
err[0].__debug = __debug;
|
||||
return err;
|
||||
// }
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -293,74 +307,95 @@ const prettyRU = (rUni: Map<string, Type>) => {
|
|||
return '{'+[...rUni].map(([symbol,type]) => `${getHumanReadableName(symbol)} => ${prettyT(type)}`).join(', ')+'}';
|
||||
}
|
||||
|
||||
export function evalLambdaBlock(paramName: string, expr: ExprBlockState, env: Environment): [ResolvedType,Environment] {
|
||||
const [paramType, staticInnerEnv] = makeTypeVar(env, paramName);
|
||||
export function evalLambdaBlock(paramName: string, expr: ExprBlockState, env: Environment): [ResolvedType,Environment,Environment] {
|
||||
let [paramType, innerEnv] = makeTypeVar(env, paramName);
|
||||
let round = 0;
|
||||
let __debug = '';
|
||||
while (true) {
|
||||
// fixpoint computation...
|
||||
const [exprResolved] = evalExprBlock(expr, innerEnv);
|
||||
const lambdaT = fnType(_ => paramType)(_ => exprResolved.t);
|
||||
// This is the only place in the code where we actually do something with the 'substitutions'. We compute the type of our lambda function:
|
||||
const reduced = reduceUnification(exprResolved.unification);
|
||||
const lambdaTSubstituted = substitute(
|
||||
lambdaT,
|
||||
reduced,
|
||||
[]); // <- not important
|
||||
|
||||
let lambdaResolved: ResolvedType;
|
||||
if (exprResolved.kind === "error") {
|
||||
lambdaResolved = {
|
||||
kind: "error",
|
||||
t: lambdaTSubstituted,
|
||||
depth: 0,
|
||||
e: exprResolved.e,
|
||||
unification: exprResolved.unification,
|
||||
}
|
||||
}
|
||||
else {
|
||||
lambdaResolved = {
|
||||
kind: "value",
|
||||
t: lambdaTSubstituted,
|
||||
i: (x: any) => {
|
||||
const innerEnv = makeInnerEnv(env, paramName, {
|
||||
kind: "value",
|
||||
i: x,
|
||||
t: lambdaTSubstituted,
|
||||
unification: new Map(),
|
||||
});
|
||||
const [result] = evalExprBlock(expr, innerEnv);
|
||||
if (result.kind === "value") {
|
||||
return result.i;
|
||||
}
|
||||
},
|
||||
unification: exprResolved.unification,
|
||||
}
|
||||
}
|
||||
|
||||
if (VERBOSE) {
|
||||
console.log('====== begin evalLambdaBlock ======')
|
||||
console.log('paramName :', paramName);
|
||||
console.log('paramType :', prettyT(paramType));
|
||||
console.log('staticInnerEnv:', staticInnerEnv);
|
||||
console.log('===================================')
|
||||
}
|
||||
const [betterResolved, newInnerEnv] = recomputeTypeVarsForEnv("<name unused>", lambdaResolved, env);
|
||||
|
||||
const [exprResolved] = evalExprBlock(expr, staticInnerEnv);
|
||||
const lambdaT = fnType(_ => paramType)(_ => exprResolved.t);
|
||||
// This is the only place in the code where we actually do something with the 'substitutions'. We compute the type of our lambda function:
|
||||
const reduced = reduceUnification(exprResolved.unification);
|
||||
const lambdaTSubstituted = substitute(
|
||||
lambdaT,
|
||||
reduced,
|
||||
[]); // <- not important
|
||||
let lambdaResolved: ResolvedType;
|
||||
if (exprResolved.kind === "error") {
|
||||
lambdaResolved = {
|
||||
kind: "error",
|
||||
t: lambdaTSubstituted,
|
||||
depth: 0,
|
||||
e: exprResolved.e,
|
||||
unification: exprResolved.unification,
|
||||
const inferredParamType = betterResolved.t.params[0](betterResolved.t);
|
||||
|
||||
if (VERBOSE) {
|
||||
__debug += `
|
||||
====== evalLambdaBlock (round ${round}) ======
|
||||
env.typeVars : ${[...env.typeVars].map(getHumanReadableName)}
|
||||
nextFreeTypeVar: ${getHumanReadableName(UNBOUND_SYMBOLS[env.nextFreeTypeVar])}
|
||||
paramName : ${paramName}
|
||||
paramType : ${prettyT(paramType)}
|
||||
staticInnerEnv: ${innerEnv}
|
||||
paramType : ${prettyT(paramType)}
|
||||
exprType : ${prettyT(exprResolved.t)}
|
||||
exprUnification : ${prettyU(exprResolved.unification)}
|
||||
exprUnificationR : ${prettyRU(reduced)}
|
||||
lambdaType : ${prettyT(lambdaT)}
|
||||
lambdaTypeSubsituted: ${prettyT(lambdaTSubstituted)}
|
||||
betterResolvedT : ${prettyT(betterResolved.t)}
|
||||
inferredParamType : ${prettyT(inferredParamType)}`;
|
||||
}
|
||||
|
||||
if (eqType(paramType)(inferredParamType)) {
|
||||
// reached fixpoint
|
||||
// @ts-ignore
|
||||
lambdaResolved.__debug = __debug;
|
||||
return [lambdaResolved, env, innerEnv];
|
||||
}
|
||||
else {
|
||||
paramType = inferredParamType;
|
||||
innerEnv = {
|
||||
...newInnerEnv,
|
||||
names: trie.insert(newInnerEnv.names)(paramName)({
|
||||
kind: "unknown",
|
||||
t: inferredParamType,
|
||||
unification: new Map(), // <-- ??
|
||||
}),
|
||||
};
|
||||
round++;
|
||||
if (round === 10) {
|
||||
throw new Error("too many rounds!");
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
const paramTypeSubstituted = lambdaTSubstituted.params[0](lambdaTSubstituted);
|
||||
lambdaResolved = {
|
||||
kind: "value",
|
||||
t: lambdaTSubstituted,
|
||||
i: (x: any) => {
|
||||
const innerEnv = makeInnerEnv(env, paramName, {
|
||||
kind: "value",
|
||||
i: x,
|
||||
t: paramTypeSubstituted,
|
||||
unification: new Map(),
|
||||
});
|
||||
const [result] = evalExprBlock(expr, innerEnv);
|
||||
if (result.kind === "value") {
|
||||
return result.i;
|
||||
}
|
||||
},
|
||||
unification: exprResolved.unification,
|
||||
}
|
||||
}
|
||||
|
||||
// const [lambdaResolvedNormalized, resultEnv] = recomputeTypeVarsForEnv(paramName, lambdaResolved, env);
|
||||
|
||||
if (VERBOSE) {
|
||||
console.log('======= end evalLambdaBlock =======')
|
||||
console.log('paramType :', prettyT(paramType));
|
||||
console.log('exprType :', prettyT(exprResolved.t));
|
||||
console.log('exprUnification :', prettyU(exprResolved.unification));
|
||||
console.log('exprUnificationR :', prettyRU(reduced));
|
||||
console.log('lambdaType :', prettyT(lambdaT));
|
||||
console.log('lambdaTypeSubsituted:', prettyT(lambdaTSubstituted));
|
||||
console.log('===================================')
|
||||
}
|
||||
return [lambdaResolved, env];
|
||||
}
|
||||
|
||||
export function haveValue(resolved: ResolvedType) {
|
||||
// return resolved && !(resolved instanceof DeepError);
|
||||
return resolved.kind === "value";
|
||||
}
|
||||
|
||||
function parseLiteral(text: string, type: string, env: Environment): [ResolvedType,Environment] {
|
||||
|
|
@ -413,23 +448,17 @@ export function attemptParseLiteral(text: string, env: Environment): Dynamic[] {
|
|||
|
||||
export function scoreResolved(resolved: ResolvedType, outPriority: (s:ResolvedType) => number) {
|
||||
const bias = outPriority(resolved);
|
||||
|
||||
console.log('scoreResolved...', resolved);
|
||||
|
||||
if (resolved.kind === "value") {
|
||||
console.log('best:', 2, bias);
|
||||
return 2 + bias;
|
||||
return bias;
|
||||
}
|
||||
else if (resolved.kind === "unknown") {
|
||||
console.log('ok:', 1, bias);
|
||||
return 1 + bias;
|
||||
return bias;
|
||||
}
|
||||
if (resolved.e instanceof UnifyError) {
|
||||
console.log('bad:', -1, bias);
|
||||
return -1 + bias; // parameter doesn't match
|
||||
}
|
||||
else {
|
||||
console.log('worst:', -2, bias);
|
||||
return -2 + bias; // even worse: fn is not a function!
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue