Repository navigation
feat(diagnostics): locate E0104, name a continued if/match, add char_to_string #862
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
6d390c6
583dc7a
d272e53
7654057
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -900,6 +900,11 @@ let create_initial_env () : env = | |
| else Error (RuntimeError "int_to_char: code point out of ASCII range") | ||
| | _ -> Error (TypeMismatch "int_to_char expects Int") | ||
| )); | ||
| ("char_to_string", VBuiltin ("char_to_string", fun args -> | ||
| match args with | ||
| | [VChar c] -> Ok (VString (String.make 1 c)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Preserve the character as valid UTF-8. For Make the interpreter's
|
||
| | _ -> Error (TypeMismatch "char_to_string expects Char") | ||
| )); | ||
| (* Byte-oriented String <-> Int accessors (see typecheck.ml bindings). | ||
| string_char_code_at returns the 0..255 byte at [i]; out-of-bounds | ||
| reads return -1 (mirroring string_find's "absent" sentinel rather | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -127,6 +127,19 @@ type type_error = | |
| (** Two impls of the same trait have overlapping (unifiable) self | ||
| types, so method resolution would be ambiguous (#559). The string | ||
| is the human-readable overlap description. *) | ||
| | StatementContinued of { kind : string; ty : ty } | ||
| (** An `if` or `match` statement whose closing `}` is followed by `(` | ||
| was read as a call on the statement's value (#644: a statement | ||
| `if`/`match` followed by `(`, `[`, `*`, `-`, `&` or `|` continues | ||
| the expression). [kind] is "if" or "match"; [ty] is the value | ||
| that was called. Reported in place of [NotAFunction] so the | ||
| message names the rule and its remedy. *) | ||
| | Located of type_error * Span.t | ||
| (** An error with the source location it was found at. Phase B of | ||
| the span threading (json_output.ml): renderers print the | ||
| location, then the inner error. Raised first at calls | ||
| ([NotAFunction], [StatementContinued]); other errors gain it as | ||
| their sites learn a span. *) | ||
|
|
||
| (* Known exports of stdlib/prelude.affine. Mirrors the same list in | ||
| lib/face.ml — when an UnboundVariable fires at type-check time with | ||
|
|
@@ -149,7 +162,17 @@ let prelude_hint (name : string) : string = | |
| else "" | ||
|
|
||
| (** Format a type error for human consumption. *) | ||
| let show_type_error = function | ||
| let rec show_type_error = function | ||
| | Located (e, span) -> | ||
| Format.asprintf "%a: %s" Span.pp_short span (show_type_error e) | ||
| | StatementContinued { kind; ty } -> | ||
| Printf.sprintf | ||
| "Expected a function type, got %s: the `%s` statement before `(` was \ | ||
| read as a call on its value. A statement `if` or `match` followed by \ | ||
| `(`, `[`, `*`, `-`, `&` or `|` continues the expression \ | ||
| (docs/ON-RAMP.adoc, \"Statements and `;`\"). Put `;` after its \ | ||
| closing `}`." | ||
| (ty_to_string ty) kind | ||
| | UnboundVariable v -> "Unbound variable: " ^ v ^ prelude_hint v | ||
| | TypeMismatch { expected; got } -> | ||
| Printf.sprintf "Type mismatch: expected %s, got %s" | ||
|
|
@@ -211,6 +234,65 @@ let show_type_error = function | |
|
|
||
| let format_type_error = show_type_error | ||
|
|
||
| (** Where an expression starts, when the AST knows: identifiers and | ||
| literals carry spans; compound expressions take the span of their | ||
| first spanned part. [None] when nothing in it is spanned. *) | ||
| let rec expr_start_span (e : expr) : Span.t option = | ||
| let known s = if s = Span.dummy then None else Some s in | ||
| match e with | ||
| | ExprSpan (_, s) -> known s | ||
| | ExprVar id -> known id.span | ||
| | ExprLit (LitInt (_, s) | LitFloat (_, s) | LitBool (_, s) | ||
| | LitChar (_, s) | LitString (_, s) | LitUnit s) -> known s | ||
| | ExprIf { ei_cond; _ } -> expr_start_span ei_cond | ||
| | ExprMatch { em_scrutinee; _ } -> expr_start_span em_scrutinee | ||
| | ExprApp (f, _) | ExprField (f, _) | ExprTupleIndex (f, _) | ||
| | ExprIndex (f, _) | ExprBinary (f, _, _) | ExprUnary (_, f) -> expr_start_span f | ||
| | ExprTuple (f :: _) | ExprArray (f :: _) -> expr_start_span f | ||
| | _ -> None | ||
|
|
||
| (** Calls that stand as a whole statement, or as a block's final | ||
| expression, with an `if`/`match` callee: the only places a #644 | ||
| continuation can produce. Recorded by [synth_block_body], compared by | ||
| physical identity. *) | ||
| let statement_calls : expr list ref = ref [] | ||
|
|
||
| let rec strip_spans = function ExprSpan (e, _) -> strip_spans e | e -> e | ||
|
|
||
| let note_statement_call (e : expr) : unit = | ||
| match strip_spans e with | ||
| | ExprApp (f, _) as app -> | ||
| (match strip_spans f with | ||
| | ExprIf _ | ExprMatch _ -> statement_calls := app :: !statement_calls | ||
| | _ -> ()) | ||
| | _ -> () | ||
|
|
||
| (** The error for calling [callee] whose type [ty] is not a function: | ||
| [StatementContinued] when the callee is a statement `if`/`match` | ||
| continued by `(` (#644), else [NotAFunction]; located when the | ||
| callee's start is known. | ||
|
|
||
| The evidence for "a statement was continued" is twofold: the call | ||
| stands as a statement or as a block's final expression | ||
| ([statement_calls]), and the callee's value is Unit, as a statement | ||
| `if`/`match` has. A value-position call such as | ||
| `let y = (if c { () } else { () })(3);` keeps [NotAFunction], so it is | ||
| not told to add a `;` it does not need. (A parenthesised callee is not | ||
| visible in the AST, so `(if c { () } else { () })(3);` standing alone | ||
| as a statement is still read as a continuation.) *) | ||
| let not_a_function_error (app : expr) (callee : expr) (ty : ty) : type_error = | ||
| let continued = | ||
| List.memq app !statement_calls | ||
| && (match ty with TCon "Unit" -> true | TTuple [] -> true | _ -> false) in | ||
| let err = match strip_spans callee with | ||
| | ExprIf _ when continued -> StatementContinued { kind = "if"; ty } | ||
| | ExprMatch _ when continued -> StatementContinued { kind = "match"; ty } | ||
| | _ -> NotAFunction ty | ||
| in | ||
| match expr_start_span callee with | ||
| | Some s -> Located (err, s) | ||
| | None -> err | ||
|
|
||
| (** Raised by [lower_effect_expr] for an unknown effect name; caught at | ||
| the [check_program] boundary and converted to [UnknownEffect] | ||
| (lowering is not in the result monad). *) | ||
|
|
@@ -1058,6 +1140,10 @@ let rec synth (ctx : context) (expr : expr) : ty result = | |
| (* Function application *) | ||
| | ExprApp (fn_expr, args) as app_node -> | ||
| let* fn_ty = synth ctx fn_expr in | ||
| let locate_call r = match r with | ||
| | Error (NotAFunction t) -> Error (not_a_function_error app_node fn_expr t) | ||
| | r -> r | ||
| in | ||
| (* #560: remember the instantiated type at `slice`/`show` calls; the | ||
| argument type is read off it after [apply_args] has unified it. *) | ||
| (match fn_expr, args with | ||
|
|
@@ -1078,9 +1164,9 @@ let rec synth (ctx : context) (expr : expr) : ty result = | |
| begin match repr fn_ty with | ||
| | TArrow (param_ty, _q, ret_ty, _eff) | ||
| when repr param_ty = ty_unit -> Ok ret_ty | ||
| | _ -> apply_args ctx fn_ty args | ||
| | _ -> locate_call (apply_args ctx fn_ty args) | ||
| end | ||
| | _ -> apply_args ctx fn_ty args | ||
| | _ -> locate_call (apply_args ctx fn_ty args) | ||
| end | ||
|
|
||
| (* Tuple *) | ||
|
|
@@ -1617,6 +1703,8 @@ and synth_block (ctx : context) (blk : block) : ty result = | |
| Fun.protect ~finally:restore (fun () -> synth_block_body ctx blk) | ||
|
|
||
| and synth_block_body (ctx : context) (blk : block) : ty result = | ||
| List.iter (function StmtExpr e -> note_statement_call e | _ -> ()) blk.blk_stmts; | ||
| Option.iter note_statement_call blk.blk_expr; | ||
| (* Type-check each statement for side effects *) | ||
| let* () = List.fold_left (fun acc stmt -> | ||
| let* () = acc in | ||
|
|
@@ -2152,6 +2240,10 @@ let register_builtins (ctx : context) : unit = | |
| bind_var ctx "parse_float" (TArrow (ty_string, QOmega, opt ty_float, EPure)); | ||
| bind_var ctx "char_to_int" (TArrow (ty_char, QOmega, ty_int, EPure)); | ||
| bind_var ctx "int_to_char" (TArrow (ty_int, QOmega, ty_char, EPure)); | ||
| (* One Char as a one-character String. Without it, code that builds a | ||
| String from code points had no total route: string_from_char_code | ||
| keeps only the low 8 bits. *) | ||
| bind_var ctx "char_to_string" (TArrow (ty_char, QOmega, ty_string, EPure)); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a program uses the newly registered builtin with the default core-Wasm target—for example, Useful? React with 👍 / 👎. |
||
| (* Byte-oriented String accessors underpinning stdlib/encoding.affine's | ||
| base64. Unlike string_get/int_to_char (which traffic in [Char] and, on | ||
| the interpreter, clamp to ASCII), these go String<->Int directly so a | ||
|
|
@@ -2689,6 +2781,7 @@ let check_program ?(import_types : (string, scheme) Hashtbl.t option) | |
| (symbols : Symbol.t) (prog : Ast.program) | ||
| : (context, type_error) Result.t = | ||
| try | ||
| statement_calls := []; | ||
| let ctx = create_context symbols in | ||
| register_builtins ctx; | ||
| (* ADR-014 / #228: record `use Mod;` qualifiers so qualified type/effect | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| (* SPDX-License-Identifier: MPL-2.0 *) | ||
| (* Copyright (c) 2026 Jonathan D.A. Jewell <jonathan.jewell@open.ac.uk> *) | ||
| (** Calling a value that is not a function: where, and why. | ||
|
|
||
| E0104 used to carry no location, even with [check --json] (start line | ||
| 0, file "<dummy>"), so a program with one bad call gave no clue which | ||
| line it was on. Its commonest cause is the documented #644 rule: a | ||
| statement [if] or [match] followed on the next line by [(] continues | ||
| the expression, so [if c { .. }] then [(a, b)] is a call on Unit. | ||
|
|
||
| These tests pin three things: the error now carries the callee's | ||
| location ([Typecheck.Located]); a continued [if]/[match] is reported | ||
| as [StatementContinued], naming the rule and the remedy; and the | ||
| remedy, a [;] after the [}], type-checks. They also pin the | ||
| [char_to_string] builtin. *) | ||
|
|
||
| open Affinescript | ||
|
|
||
| let typecheck (src : string) : (unit, Typecheck.type_error) result = | ||
| let prog = Parse_driver.parse_string ~file:"t.affine" src in | ||
| let dir = Sys.getcwd () in | ||
| let config = | ||
| { (Module_loader.default_config ()) with current_dir = dir; search_paths = [ dir ] } | ||
| in | ||
| let loader = Module_loader.create config in | ||
| match Resolve.resolve_program_with_loader prog loader with | ||
| | Error (e, _) -> Alcotest.failf "resolution error: %s" (Resolve.show_resolve_error e) | ||
| | Ok (rc, tc) -> | ||
| (match Typecheck.check_program ~import_types:tc.Typecheck.name_types rc.symbols prog with | ||
| | Ok _ -> Ok () | ||
| | Error e -> Error e) | ||
|
|
||
| let expect_error src = | ||
| match typecheck src with | ||
| | Ok () -> Alcotest.fail "expected a type error, got Ok" | ||
| | Error e -> e | ||
|
|
||
| let line_of (e : Typecheck.type_error) = | ||
| match e with | ||
| | Typecheck.Located (_, s) -> s.Span.start_pos.line | ||
| | _ -> Alcotest.failf "error has no location: %s" (Typecheck.format_type_error e) | ||
|
|
||
| let continued_if_is_named_and_located () = | ||
| let e = expect_error | ||
| "pub fn f(t: Int) -> (Int, Int) {\n\ | ||
| \ let mut u = t;\n\ | ||
| \ if u > 0 { u = 1; }\n\ | ||
| \ (u, 2)\n\ | ||
|
Comment on lines
+44
to
+48
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The parent already contains the #863 grammar change: the statement-first productions in Useful? React with 👍 / 👎. |
||
| }\n" in | ||
| Alcotest.(check int) "line of the if" 3 (line_of e); | ||
| match e with | ||
| | Typecheck.Located (Typecheck.StatementContinued { kind = "if"; _ }, _) -> () | ||
| | _ -> Alcotest.failf "expected StatementContinued if, got %s" (Typecheck.format_type_error e) | ||
|
|
||
| let continued_match_is_named_and_located () = | ||
| let e = expect_error | ||
| "pub fn f(t: Int) -> (Int, Int) {\n\ | ||
| \ let mut u = t;\n\ | ||
| \ match u { 0 => { u = 1; }, _ => {} }\n\ | ||
| \ (u, 2)\n\ | ||
| }\n" in | ||
| Alcotest.(check int) "line of the match" 3 (line_of e); | ||
| match e with | ||
| | Typecheck.Located (Typecheck.StatementContinued { kind = "match"; _ }, _) -> () | ||
| | _ -> Alcotest.failf "expected StatementContinued match, got %s" (Typecheck.format_type_error e) | ||
|
|
||
| (* A value-position `if` that is not Unit was not a continued statement: | ||
| plain E0104, located, with no `;` advice (CodeRabbit review on #862). *) | ||
| let value_position_if_keeps_not_a_function () = | ||
| let e = expect_error | ||
| "pub fn f(c: Bool) -> Int {\n\ | ||
| \ let y = (if c { 1 } else { 2 })(3);\n\ | ||
| \ y\n\ | ||
| }\n" in | ||
| match e with | ||
| | Typecheck.Located (Typecheck.NotAFunction _, _) -> () | ||
| | _ -> Alcotest.failf "expected located NotAFunction, got %s" (Typecheck.format_type_error e) | ||
|
|
||
| (* Unit-valued value-position calls: Unit alone is not evidence of a | ||
| continued statement; the call must also stand as a statement or a | ||
| block's final expression (CodeRabbit follow-up on #862). *) | ||
| let unit_valued_value_position_keeps_not_a_function () = | ||
| List.iter (fun src -> | ||
| match expect_error src with | ||
| | Typecheck.Located (Typecheck.NotAFunction _, _) -> () | ||
| | e -> Alcotest.failf "expected located NotAFunction, got %s" (Typecheck.format_type_error e)) | ||
| [ "pub fn f(c: Bool) -> Int {\n let y = (if c { () } else { () })(3);\n 0\n}\n"; | ||
| "pub fn f(n: Int) -> Int {\n let y = (match n { 0 => (), _ => () })(3);\n 0\n}\n" ] | ||
|
|
||
| let the_documented_remedy_typechecks () = | ||
| match typecheck | ||
| "pub fn f(t: Int) -> (Int, Int) {\n\ | ||
| \ let mut u = t;\n\ | ||
| \ if u > 0 { u = 1; };\n\ | ||
| \ (u, 2)\n\ | ||
| }\n" with | ||
| | Ok () -> () | ||
| | Error e -> Alcotest.failf "the ; remedy should type-check: %s" (Typecheck.format_type_error e) | ||
|
|
||
| let plain_bad_call_is_located () = | ||
| let e = expect_error "pub fn h(n: Int) -> Int {\n n(1)\n}\n" in | ||
| Alcotest.(check int) "line of the call" 2 (line_of e); | ||
| match e with | ||
| | Typecheck.Located (Typecheck.NotAFunction _, _) -> () | ||
| | _ -> Alcotest.failf "expected NotAFunction, got %s" (Typecheck.format_type_error e) | ||
|
|
||
| let text_and_json_carry_the_location () = | ||
| let e = expect_error "pub fn h(n: Int) -> Int {\n n(1)\n}\n" in | ||
| let text = Typecheck.format_type_error e in | ||
| Alcotest.(check bool) "text starts with t.affine:2:" true | ||
| (String.length text > 11 && String.sub text 0 11 = "t.affine:2:"); | ||
| let d = Json_output.of_type_error e in | ||
| Alcotest.(check string) "json code" "E0104" d.Json_output.code; | ||
| Alcotest.(check int) "json start line" 2 d.Json_output.span.Span.start_pos.line; | ||
| Alcotest.(check string) "json file" "t.affine" d.Json_output.span.Span.file | ||
|
|
||
| let char_to_string_types () = | ||
| match typecheck | ||
| "pub fn g(c: Int) -> String {\n\ | ||
| \ char_to_string(int_to_char(c)) ++ \"!\"\n\ | ||
| }\n" with | ||
| | Ok () -> () | ||
| | Error e -> Alcotest.failf "char_to_string should type: %s" (Typecheck.format_type_error e) | ||
|
|
||
| let char_to_string_rejects_a_string () = | ||
| ignore (expect_error "pub fn g(s: String) -> String {\n char_to_string(s)\n}\n") | ||
|
|
||
| let tests = [ | ||
| Alcotest.test_case "continued if: named and located" `Quick continued_if_is_named_and_located; | ||
| Alcotest.test_case "continued match: named and located" `Quick continued_match_is_named_and_located; | ||
| Alcotest.test_case "the ; remedy type-checks" `Quick the_documented_remedy_typechecks; | ||
| Alcotest.test_case "value-position if keeps NotAFunction" `Quick value_position_if_keeps_not_a_function; | ||
| Alcotest.test_case "Unit-valued value-position if/match keep NotAFunction" `Quick unit_valued_value_position_keeps_not_a_function; | ||
| Alcotest.test_case "plain call on a non-function is located" `Quick plain_bad_call_is_located; | ||
| Alcotest.test_case "text and JSON carry the location" `Quick text_and_json_carry_the_location; | ||
| Alcotest.test_case "char_to_string : Char -> String" `Quick char_to_string_types; | ||
| Alcotest.test_case "char_to_string rejects a String" `Quick char_to_string_rejects_a_string; | ||
| ] | ||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handle characters returned by
string_get.On Bun,
string_get("😀", 0)returns the first UTF-16 code unit. This lowering preserves that lone surrogate, socode_points(char_to_string(string_get("😀", 0)))throws instead of receiving a character string.Make the
Charproducer and conversion agree on whole Unicode characters.Script executed:
Repository: hyperpolymath/affinescript
Length of output: 17676
Script executed:
Repository: hyperpolymath/affinescript
Length of output: 7291
Bare
char_to_stringvalues can fail at runtime in Bun output.A program can pass the type checker with
char_to_stringused as a function value, for examplelet f = char_to_string;. The Bun code generator does not wrap that value. The reference is emitted as a bare name, and the generated module defines no such binding, so calling the value can fail with aReferenceError. Direct calls such aschar_to_string(c)are lowered toString(c)and work. The interpreter supports the value form.The change must either support first-class use on the Bun backend or reject it before code generation. The choice needs a decision that also covers other non-extern intrinsics such as
lenandstring_sub. Do not add a one-off wrapper for this name alone.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Both points are real, and both predate this PR.
string_get("😀", 0)comes fromstring_getindexing UTF-16 code units on Bun.char_to_stringonly passes the Char through. Which unit a string index counts is ADR-0029 (semantics: string indices mean octets on interp/wasm but UTF-16 units on Bun-ESM (owner decision) #831), a draft awaiting an owner decision. Changingstring_gethere would pre-empt it.char_to_string(int_to_char(n))is total for any code point (tests cover astral).len,string_suband every other non-extern intrinsic fail the same way when used as a value on Bun. As you say, it needs one estate-wide policy, not a one-off wrapper.Both go to the owner as decisions. Leaving this thread open.
Generated by Claude Code
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@hyperpolymath Understood. I will not mark either finding as addressed.
Learnings added
Learnings used
You are interacting with an AI system.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update on point 2: the owner ruled "first-class wrappers for every intrinsic". That is implemented in #864. Arity is derived from each builtin's type, and one rule is shared with #818's extern wrapping, with a coverage test. Once both PRs merge,
char_to_stringis wrapped like the rest. Point 1, the Char units, still waits on ADR-0029 (#831).Generated by Claude Code
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@hyperpolymath Thanks for the update. The earlier guidance also calls for consistent handling across intrinsics. I will not mark either finding as addressed.
Learnings added
Learnings used
You are interacting with an AI system.