Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Adapt to the compiler foundation: locate/toSource positions, compileTsus in migrate, tagged errors in examples 33/34/53, no mixed literal/tagged error types

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
358de066a178c3a5611920dba7dd487a57a92725
Parent 8b87e58 Browse filesHistory

Changed files

8 files changed89 additions57 deletionsagainst 8b87e58

  1. Changedexamples/33-await-in-string/src/main.tsus+1−1
  2. Changedexamples/34-try-operator/src/main.tsus+12−9
  3. Changedexamples/53-boundary-file/src/config.boundary.tsus+4−2
  4. Changedexamples/55-migrate/expected/inventory.tsus+2−2
  5. Changedexamples/55-migrate/src/main.tsus+1−1
  6. Changedpackages/cli/src/migrate.js+22−22
  7. Changedpackages/cli/src/rules/results.js+44−17
  8. Changedpackages/cli/templates/src/main.tsus+3−3
Changedexamples/33-await-in-string/src/main.tsus+1−1
@@ -17,7 +17,7 @@
};
// A real await in one arm makes every arm async; the string one is untouched.
-const describe = async (r: Result<number, string>): Promise<string> =>
+const describe = async (r: Result<number, "boom">): Promise<string> =>
await match (r) {
Ok(n) => await slow(n),
Err(e) => "await failed: " + e,
View file
Changedexamples/34-try-operator/src/main.tsus+12−9
@@ -1,12 +1,15 @@
-import { Ok, Err, Some, None, type Result, type Option } from "@tsus/runtime";
+import { Ok, Err, Some, None, tag, type Result, type Option, type Tagged } from "@tsus/runtime";
-const parsePort = (raw: string): Result<number, string> => {
+// Error types are tagged (TSUS410), so callers can match on what failed.
+type PortError = Tagged<"BadPort", string>;
+
+const parsePort = (raw: string): Result<number, PortError> => {
const n = Number(raw);
- return Number.isInteger(n) && n > 0 ? Ok(n) : Err(`bad port: ${raw}`);
+ return Number.isInteger(n) && n > 0 ? Ok(n) : Err(tag("BadPort", raw));
};
// ? on a Result returns the Err early.
-const describePort = (raw: string): Result<string, string> => {
+const describePort = (raw: string): Result<string, PortError> => {
const port = parsePort(raw)?;
const kind = port < 1024 ? "privileged" : "user";
if (raw.startsWith("+")) return Ok(`signed ${parsePort(raw.slice(1))?}`);
@@ -14,7 +17,7 @@
};
// Several ? in one expression run left to right.
-const sum = (a: string, b: string): Result<number, string> => Ok((parsePort(a)?) + (parsePort(b)?));
+const sum = (a: string, b: string): Result<number, PortError> => Ok((parsePort(a)?) + (parsePort(b)?));
// ? on an Option returns None early.
const lookup = (env: Map<string, string>, key: string): Option<string> =>
@@ -26,20 +29,20 @@
};
// Async: ? applies to the awaited Result.
-const fetchPort = async (raw: string): Promise<Result<number, string>> => {
+const fetchPort = async (raw: string): Promise<Result<number, PortError>> => {
await Promise.resolve();
return parsePort(raw);
};
-const doubled = async (raw: string): Promise<Result<number, string>> => {
+const doubled = async (raw: string): Promise<Result<number, PortError>> => {
const port = await fetchPort(raw)?;
return Ok(port * 2);
};
-const show = (r: Result<string | number, string>): string =>
+const show = (r: Result<string | number, PortError>): string =>
match (r) {
Ok(v) => `ok ${v}`,
- Err(e) => `err ${e}`,
+ Err(e) => `err bad port: ${e.value}`,
};
console.log(show(describePort("80")));
View file
Changedexamples/53-boundary-file/src/config.boundary.tsus+4−2
@@ -15,8 +15,10 @@
return typeof fields.port === "number" && typeof fields.host === "string";
};
+const fail = (error: ConfigError): Result<Config, ConfigError> => Err(error);
+
export const loadConfig = (raw: string): Result<Config, ConfigError> =>
match (parseJson(raw)) {
- Ok(data) => (looksLikeConfig(data) ? Ok(data as Config) : Err("invalid shape")),
- Err(e) => Err("unparseable"),
+ Ok(data) => (looksLikeConfig(data) ? Ok(data as Config) : fail("invalid shape")),
+ Err(e) => fail("unparseable"),
};
View file
Changedexamples/55-migrate/expected/inventory.tsus+2−2
@@ -25,10 +25,10 @@
export const firstLow = (items: Item[]): Option<Item> => fromNullable(items.find((it) => itemIsLow(it)));
-export function parseQty(raw: string): Result<number, "not a number" | { tag: "RangeError"; message: string }> {
+export function parseQty(raw: string): Result<number, { tag: "Error"; message: string } | { tag: "RangeError"; message: string }> {
const n = Number(raw);
if (Number.isNaN(n)) {
- return Err("not a number");
+ return Err({ tag: "Error", message: "not a number" });
}
if (n < 0) {
return Err({ tag: "RangeError", message: `negative quantity: ${n}` });
View file
Changedexamples/55-migrate/src/main.tsus+1−1
@@ -15,7 +15,7 @@
match (parseQty(raw)) {
Ok(n) => `qty ${n}`,
Err(e) => match (e) {
- "not a number" => "not a number",
+ Error(err) => err.message,
RangeError(err) => err.message,
},
};
View file
Changedpackages/cli/src/migrate.js+22−22
@@ -15,8 +15,7 @@
import { varFix } from "./rules/immutability.js";
import { walk, skipParens, hasModifier, collectWrites } from "./rules/analysis.js";
import { createSourceMap, lineColOf } from "./rules/sourcemap.js";
-import { checkSource } from "./check.js";
-import { preprocess } from "./preprocess.js";
+import { compileTsus } from "./compile.js";
const parse = (code, name = "migrate.ts") =>
ts.createSourceFile(name, code, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);
@@ -560,27 +559,25 @@
return false;
};
-// { type, value } for one throw statement.
+// Two encodings of one throw statement: as a string literal (when the
+// message is a literal) and as a tagged object. A function's errors use the
+// literal form only if every throw has one, because one match cannot mix
+// literal patterns and variant patterns.
const errorOf = (sf, thr) => {
const e = skipParens(thr.expression);
if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e)) {
const lit = JSON.stringify(e.text);
- return { type: lit, value: lit };
+ return { literal: lit, type: `{ tag: "Thrown"; value: string }`, value: `{ tag: "Thrown", value: ${lit} }` };
}
if (ts.isNewExpression(e) && ts.isIdentifier(e.expression)) {
const ctorName = e.expression.text;
const arg = e.arguments?.[0];
- if (!arg) {
- const lit = JSON.stringify(ctorName);
- return { type: lit, value: lit };
- }
- if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {
- const lit = JSON.stringify(arg.text);
- return { type: lit, value: lit };
- }
- return { type: `{ tag: "${ctorName}"; message: string }`, value: `{ tag: "${ctorName}", message: ${arg.getText(sf)} }` };
+ const isLit = !arg || ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg);
+ const lit = isLit ? JSON.stringify(arg ? arg.text : ctorName) : undefined;
+ const message = arg ? arg.getText(sf) : JSON.stringify(ctorName);
+ return { literal: lit, type: `{ tag: "${ctorName}"; message: string }`, value: `{ tag: "${ctorName}", message: ${message} }` };
}
- return { type: `{ tag: "Thrown"; value: unknown }`, value: `{ tag: "Thrown", value: ${e.getText(sf)} }` };
+ return { literal: undefined, type: `{ tag: "Thrown"; value: unknown }`, value: `{ tag: "Thrown", value: ${e.getText(sf)} }` };
};
const isVoidType = (t) => t && (t.kind === ts.SyntaxKind.VoidKeyword || (ts.isTypeReferenceNode(t) && t.typeName.getText() === "Promise" && t.typeArguments?.[0]?.kind === ts.SyntaxKind.VoidKeyword));
@@ -606,7 +603,9 @@
state.unconverted.push({ kind: "throw", name, ...where, reason: "throws inside its own try block; untangle the control flow by hand" });
continue;
}
- const errors = throws.map((t) => errorOf(sf, t));
+ const encoded = throws.map((t) => errorOf(sf, t));
+ const allLiteral = encoded.every((e) => e.literal !== undefined);
+ const errors = encoded.map((e) => (allLiteral ? { type: e.literal, value: e.literal } : e));
const errorType = [...new Set(errors.map((e) => e.type))].join(" | ");
const isAsync = hasModifier(fn, ts.SyntaxKind.AsyncKeyword);
const voidish = isVoidType(fn.type) || (!fn.type && ownReturns(fn).every((r) => !r.expression));
@@ -708,17 +707,18 @@
runPass(state, importPass);
// What the strict checker still rejects in the output.
const outName = fileName.replace(/\.(ts|tsx|mts)$/, ".tsus");
- let remaining = [];
- try {
- const { code } = preprocess(state.code);
- remaining = checkSource(outName, code, { original: state.code });
- } catch (error) {
- remaining = [{ code: "TSUS006", message: error.message, line: 1, col: 1, start: 0 }];
+ const remaining = compileTsus(state.code, outName).diagnostics;
+ const lineStarts = [0];
+ for (let i = 0; i < state.code.length; i += 1) {
+ if (state.code.charCodeAt(i) === 10) {
+ lineStarts.push(i + 1);
+ }
}
+ const offsetOf = (d) => d.start ?? (lineStarts[Math.max(0, (d.line ?? 1) - 1)] ?? 0) + Math.max(0, (d.col ?? 1) - 1);
const outputToInput = createSourceMap(state.source, state.code);
const inputToOutput = createSourceMap(state.code, state.source);
for (const d of remaining) {
- const inputOffset = outputToInput.approx(d.start ?? 0);
+ const inputOffset = outputToInput.approx(offsetOf(d));
state.unconverted.push({
kind: "check",
code: d.code,
View file
Changedpackages/cli/src/rules/results.js+44−17
@@ -47,7 +47,7 @@
}
if (target.module !== undefined) {
if (target.module === "@tsus/runtime") {
- return { ok: target.imported === "Tagged" };
+ return { ok: target.imported === "Tagged", shape: "tagged" };
}
return { ok: true }; // a package type: give it the benefit of the doubt
}
@@ -70,7 +70,7 @@
const spec = stmt.moduleSpecifier.text;
const imported = (el.propertyName ?? el.name).text;
if (spec === "@tsus/runtime") {
- return { ok: imported === "Tagged" };
+ return { ok: imported === "Tagged", shape: "tagged" };
}
if (!spec.startsWith(".")) {
return { ok: true };
@@ -95,7 +95,7 @@
return { ok: true }; // TSUS404 already reports the enum itself
}
if (ts.isInterfaceDeclaration(decl)) {
- return { ok: hasLiteralTag(decl.members) };
+ return { ok: hasLiteralTag(decl.members), shape: "tagged" };
}
if (ts.isTypeAliasDeclaration(decl)) {
const params = new Set((decl.typeParameters ?? []).map((p) => p.name.text));
@@ -105,33 +105,54 @@
return { ok: true };
};
-const isTaggedError = (typeNode, scope, depth = 0) => {
+// The shapes an error type is built from: "literal" (string literals),
+// "tagged" (objects with a literal discriminant) and "open" (type
+// parameters, never, package types we cannot see). Returns undefined when
+// some part is neither, such as string, Error or unknown.
+const errorShapes = (typeNode, scope, depth = 0) => {
+ const one = (shape) => new Set([shape]);
if (depth > 12) {
- return true;
+ return one("open");
}
const t = typeNode;
switch (t.kind) {
case ts.SyntaxKind.NeverKeyword:
- return true;
+ return one("open");
case ts.SyntaxKind.ParenthesizedType:
- return isTaggedError(t.type, scope, depth + 1);
+ return errorShapes(t.type, scope, depth + 1);
case ts.SyntaxKind.LiteralType:
- return isStringLiteralUnion(t);
- case ts.SyntaxKind.UnionType:
- return t.types.every((m) => isTaggedError(m, scope, depth + 1));
- case ts.SyntaxKind.IntersectionType:
- return t.types.some((m) => isTaggedError(m, scope, depth + 1));
+ return isStringLiteralUnion(t) ? one("literal") : undefined;
+ case ts.SyntaxKind.UnionType: {
+ const all = new Set();
+ for (const m of t.types) {
+ const part = errorShapes(m, scope, depth + 1);
+ if (!part) {
+ return undefined;
+ }
+ part.forEach((x) => all.add(x));
+ }
+ return all;
+ }
+ case ts.SyntaxKind.IntersectionType: {
+ for (const m of t.types) {
+ const part = errorShapes(m, scope, depth + 1);
+ if (part) {
+ return part;
+ }
+ }
+ return undefined;
+ }
case ts.SyntaxKind.TypeLiteral:
- return hasLiteralTag(t.members);
+ return hasLiteralTag(t.members) ? one("tagged") : undefined;
case ts.SyntaxKind.TypeReference: {
const r = scope.resolve(t);
if (r.node) {
- return isTaggedError(r.node, r.scope, depth + 1);
+ return errorShapes(r.node, r.scope, depth + 1);
}
- return r.ok;
+ return r.ok ? one(r.shape ?? "open") : undefined;
}
default:
- return false;
+ return undefined;
}
};
@@ -149,9 +170,15 @@
return;
}
const errorType = node.typeArguments[1];
- if (!isTaggedError(errorType, localScope(ctx))) {
+ const shapes = errorShapes(errorType, localScope(ctx));
+ if (!shapes) {
ctx.report("TSUS410", errorType, {
message: `Result error type \`${errorType.getText(ctx.sf)}\` must be a string literal union or a tagged union`,
+ });
+ } else if (shapes.has("literal") && shapes.has("tagged")) {
+ ctx.report("TSUS410", errorType, {
+ message: `Result error type \`${errorType.getText(ctx.sf)}\` mixes string literals and tagged variants, which one match cannot cover`,
+ hint: "Make every case a string literal, or every case a tagged variant (Tagged<\"EmptyId\", string> | Tagged<\"NotFound\", string>).",
});
}
});
View file
Changedpackages/cli/templates/src/main.tsus+3−3
@@ -4,7 +4,7 @@
type User = { readonly name: string; readonly email: Option<string> };
-type LookupError = "empty id" | Tagged<"NotFound", string>;
+type LookupError = Tagged<"EmptyId", string> | Tagged<"NotFound", string>;
const users: readonly User[] = [
{ name: "ada", email: Some("ada@example.com") },
@@ -14,7 +14,7 @@
// Array.find returns T | undefined; fromNullable turns that into an Option.
const findUser = (id: string): Result<User, LookupError> =>
id === ""
- ? Err("empty id")
+ ? Err(tag("EmptyId", id))
: fromNullable(users.find((u) => u.name === id)).okOr(tag("NotFound", id));
const contact = (user: User): string =>
@@ -27,7 +27,7 @@
match (findUser(id)) {
Ok(user) => contact(user),
Err(e) => match (e) {
- "empty id" => "no id given",
+ EmptyId(blank) => "no id given",
NotFound(missing) => `no user named ${missing}`,
},
};
View file

Checks

No checks reported for this commit.

Runs

No runs for this commit.