Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions .dev/accepted_divergences.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1181,9 +1181,15 @@ accepted:
- id: "AD-060"
area: "regex"
summary: |-
Backreferences (`\1` … `\9`, `\k<name>`) raise the UNCATCHABLE
unsupported-feature error at pattern-compile time; Java compiles and
matches them. This is the RE2 posture, permanent by design, not a
Backreferences (`\1` … `\9`, `\k<name>`) are declined at
pattern-compile time; Java compiles and matches them. In a `#"..."`
literal the raise is the UNCATCHABLE unsupported-feature error. In a
pattern built from a runtime string (`re-pattern`, `Pattern/compile`,
the `String` regex methods) it is a catchable
IllegalArgumentException (amended 2026-12-01, issue #136: a runtime
pattern is data, possibly untrusted, and a server must be able to
refuse one without ending the process; the same reasoning that made
malformed JSON and EDN catchable). This is the RE2 posture, permanent by design, not a
pending gap: cljw's matcher is a Pike-NFA (ADR-0031) whose worst case is
linear in the input, which is the property that lets the playground run
untrusted patterns without a ReDoS budget. A backreference makes
Expand All @@ -1197,12 +1203,12 @@ accepted:
lookbehind, named groups `(?<name>…)` (+ `.group m "name"`), `\A \z \Z`,
nested class unions `[a[b]]` / `&&` intersection, empty
alternatives/groups.
example: '(re-pattern "(a)\\1") => cljw UNCATCHABLE "this regex feature … is not supported" / clj #"(a)\1" compiles and (re-matches #"(a)\1" "aa") => ["aa" "a"]'
example: '#"(a)\1" => cljw UNCATCHABLE "a regex backreference … is not supported"; (re-pattern "(a)\\1") => cljw catchable IllegalArgumentException with the same message / clj #"(a)\1" compiles and (re-matches #"(a)\1" "aa") => ["aa" "a"]'
derives_from: "ADR-0031 (Pike-NFA, non-backtracking invariant — linear-time matching is the security property, F-002 finished form)."
pin: "test/e2e/regex_parity_gaps.sh — backref compile raises the uncatchable unsupported signal and a (catch Throwable …) does NOT swallow it."
pin: "test/e2e/regex_parity_gaps.sh — a backref LITERAL raises the uncatchable unsupported signal and a (catch Throwable …) does NOT swallow it; test/clj/suites/regex_test.clj — the same construct through re-pattern is a catchable IllegalArgumentException."
check:
expr: |-
(some? (re-matches (re-pattern "(a)\\1") "aa"))
(some? (re-matches #"(a)\1" "aa"))
clj: 'true'
cljw: 'aborts'
- id: "AD-061"
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,24 @@ first stable `1.0.0` tag; pre-1.0 `alpha` / `rc` tags may still change surfaces.

## [Unreleased]

### Changed

- `require` of a namespace that is not on the load path raises
`java.io.FileNotFoundException`, as on the JVM, so the usual probe for an
optional namespace, `(try (require 'x) (catch java.io.FileNotFoundException
_ …))`, works (#137). It was a `RuntimeException`. The uncaught report is
headed "File not found" where it was "Name error"; the message is
unchanged. `alias` and `refer` of a namespace that is not loaded look for
no file and now report "No namespace".
- A regex construct cljw declines (a backreference, an unsupported inline
flag or class form) is now a catchable `IllegalArgumentException` when the
pattern comes from a runtime string: `re-pattern`, `Pattern/compile` and
the `String` regex methods (#136). It used to end the process even inside
`(try … (catch Throwable …))`, so a server could not refuse one bad
pattern. The same construct in a `#"..."` literal is code and stays the
uncatchable unsupported-feature error. This amends accepted divergence
AD-060.

### Fixed

- A regex character-class range may have an escaped endpoint (#135). A range
Expand Down
8 changes: 4 additions & 4 deletions src/eval/analyzer/analyzer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -595,9 +595,9 @@ pub fn parseRatioLiteral(rt: *Runtime, digits: []const u8, loc: error_mod.Source
}

/// Compile a `#"..."` reader-literal body into a regex Value via
/// `runtime/regex/value.zig::alloc`. Cycle-1 compile errors surface
/// as `feature_not_supported`; cycle 5 wires the
/// `PatternSyntaxException`-aligned error messages (D-051).
/// `runtime/regex/value.zig::alloc`. A literal is code: a construct cljw
/// declines surfaces as the uncatchable `feature_not_supported`, a
/// malformed pattern as the catchable invalid-pattern error (D-051).
///
/// Return type is pinned to `AnalyzeError` so the per-variant
/// CompileError set (UnexpectedToken / NotImplemented / etc.)
Expand All @@ -606,7 +606,7 @@ pub fn parseRatioLiteral(rt: *Runtime, digits: []const u8, loc: error_mod.Source
pub fn parseRegexLiteral(rt: *Runtime, body: []const u8, loc: error_mod.SourceLocation) AnalyzeError!Value {
return regex_value.alloc(rt, body, .{}) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return regex_value.raiseCompileError(err, loc),
else => return regex_value.raiseLiteralCompileError(err, loc),
};
}

Expand Down
3 changes: 3 additions & 0 deletions src/eval/macro_dispatch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,9 @@ pub fn narrowCallFnError(e: anyerror, loc: SourceLocation) ExpandError {
error.ArithmeticError => error.ArithmeticError,
error.IndexError => error.IndexError,
error.IoError => error.IoError,
// A missing file or namespace met while a macro expands (a `require`
// or `slurp` in its body) stays the catchable FileNotFoundException.
error.FileNotFound => error.FileNotFound,
error.InternalError => error.InternalError,
// A macro that THROWS — `(defmacro m [] (throw (ex-info …)))`, and
// every argument-validating macro in clojure.core — raises
Expand Down
6 changes: 4 additions & 2 deletions src/lang/primitive/namespace.zig
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,10 @@ pub fn aliasFn(rt: *Runtime, env: *Env, args: []const Value, loc: SourceLocation
try error_catalog.checkArity("alias", args, 2, loc);
if (args[0].tag() != .symbol or args[1].tag() != .symbol)
return error_catalog.raise(.type_arg_invalid, loc, .{ .fn_name = "alias", .expected = "two symbols", .actual = @tagName(if (args[0].tag() != .symbol) args[0].tag() else args[1].tag()) });
// No file is looked for here, so this is "No namespace", as on the JVM,
// not the missing-lib error `require` raises.
const target = env.findNs(symbol_mod.asSymbol(args[1]).name) orelse
return error_catalog.raise(.lib_not_found, loc, .{ .ns = symbol_mod.asSymbol(args[1]).name });
return error_catalog.raise(.namespace_unknown, loc, .{ .ns = symbol_mod.asSymbol(args[1]).name });
const here = env.current_ns orelse
return error_catalog.raise(.current_namespace_missing, loc, .{ .sym = symbol_mod.asSymbol(args[0]).name });
try env.setAlias(here, symbol_mod.asSymbol(args[0]).name, target);
Expand Down Expand Up @@ -388,7 +390,7 @@ pub fn referFn(rt: *Runtime, env: *Env, args: []const Value, loc: SourceLocation
if (args.len < 1 or args[0].tag() != .symbol)
return error_catalog.raise(.form_malformed, loc, .{ .name = "refer requires a namespace symbol" });
const target = env.findNs(symbol_mod.asSymbol(args[0]).name) orelse
return error_catalog.raise(.lib_not_found, loc, .{ .ns = symbol_mod.asSymbol(args[0]).name });
return error_catalog.raise(.namespace_unknown, loc, .{ .ns = symbol_mod.asSymbol(args[0]).name });
const here = env.current_ns orelse
return error_catalog.raise(.current_namespace_missing, loc, .{ .sym = symbol_mod.asSymbol(args[0]).name });
var opts = try parseReferOpts(rt, args[1..], loc);
Expand Down
18 changes: 16 additions & 2 deletions src/runtime/error/catalog.zig
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,9 @@ pub const Code = enum {
circular_require,
/// args: `.{ .ns = "..." }` — raised when the active
/// `Runtime.require_resolver` returns `null` for a requested
/// namespace name.
/// namespace name. Kind `.file_not_found`, so it is catchable as
/// `java.io.FileNotFoundException` as on the JVM: portable code detects
/// an optional namespace with `(catch java.io.FileNotFoundException _ …)`.
lib_not_found,
/// args: `.{ .ns = "...", .detail = "..." }` — raised when a lib's source
/// is found but cannot be opened/read (ADR-0084). Distinct from
Expand Down Expand Up @@ -484,6 +486,13 @@ pub const Code = enum {
/// catchable IllegalArgumentException (JVM's `PatternSyntaxException` is also
/// an IllegalArgumentException), not an OOM that ends the process (INV-1).
regex_pattern_too_large,
/// args: `.{ .name }` — a pattern built from a RUNTIME STRING uses a
/// construct that is valid Java and that cljw declines (a backreference,
/// an unsupported inline flag or class form). The pattern is data, so
/// this is a catchable IllegalArgumentException; the same construct in a
/// `#"..."` literal is code and stays the uncatchable
/// `feature_not_supported` (AD-060 as amended).
regex_construct_not_supported,
/// args: `.{ .max }` — the pattern declares more capturing groups than
/// `compile.MAX_CAPTURE_GROUPS`. A resource bound like
/// `regex_pattern_too_large`, so the same catchable `.value_error`.
Expand Down Expand Up @@ -845,7 +854,7 @@ pub fn entry(comptime code: Code) Entry {
.template = "Cyclic load dependency: {[chain]s}",
},
.lib_not_found => .{
.kind = .name_error,
.kind = .file_not_found,
.phase = .analysis,
.template = "Could not locate '{[ns]s}' on the require resolver",
},
Expand Down Expand Up @@ -1834,6 +1843,11 @@ pub fn entry(comptime code: Code) Entry {
.phase = .eval,
.template = "re-pattern: the regular expression is too large to compile",
},
.regex_construct_not_supported => .{
.kind = .value_error,
.phase = .eval,
.template = "{[name]s} is not supported in ClojureWasm",
},
.regex_too_many_groups => .{
.kind = .value_error,
.phase = .eval,
Expand Down
43 changes: 30 additions & 13 deletions src/runtime/regex/value.zig
Original file line number Diff line number Diff line change
Expand Up @@ -130,30 +130,47 @@ fn ownedBytes(header: *HeapHeader) usize {
return r.source_len + @sizeOf(@TypeOf(r.program.*));
}

/// Map a `CompileError` to the right catalog raise (shared by every surface
/// that compiles a pattern). The split matters: a MALFORMED pattern is bad
/// data (catchable, Java PatternSyntaxException parity); a valid-in-Java
/// feature cljw rejects (backreferences — ADR-0031's non-backtracking
/// invariant, the RE2 posture) stays the uncatchable unsupported signal.
/// The construct a declined pattern used, for the error message; null when
/// the pattern was not declined for an unsupported construct.
fn declinedConstruct(err: anyerror) ?[]const u8 {
return switch (err) {
error.Backreference => "a regex backreference (\\N / \\k<name>; needs a backtracking engine)",
error.NotImplemented => "this regex construct (inline flag, Unicode property or class form)",
else => null,
};
}

/// Map a `CompileError` to the catalog raise for a pattern built from a
/// RUNTIME STRING (`re-pattern`, `Pattern/compile`, the `String` regex
/// methods). Such a pattern is data, possibly untrusted, so every rejection
/// is catchable: a malformed pattern (Java PatternSyntaxException parity), a
/// resource bound, and a valid-in-Java construct cljw declines
/// (backreferences, ADR-0031's non-backtracking invariant). A server must be
/// able to refuse one bad pattern without ending the process (AD-060 as
/// amended; a `#"..."` literal goes through `raiseLiteralCompileError`).
pub fn raiseCompileError(err: anyerror, loc: SourceLocation) error_catalog.ClojureWasmError {
if (declinedConstruct(err)) |name|
return error_catalog.raise(.regex_construct_not_supported, loc, .{ .name = name });
return switch (err) {
error.OutOfMemory => error.OutOfMemory,
// INV-1: a nested-counted-repetition compile-bomb is a catchable error.
error.PatternTooLarge => error_catalog.raise(.regex_pattern_too_large, loc, .{}),
// Too many groups is a resource bound, like PatternTooLarge: catchable.
error.TooManyGroups => error_catalog.raise(.regex_too_many_groups, loc, .{ .max = compile.MAX_CAPTURE_GROUPS }),
// AD-060: the declined backreference stays the uncatchable unsupported
// signal, but names the construct.
error.Backreference => error_catalog.raise(.feature_not_supported, loc, .{
.name = "a regex backreference (\\N / \\k<name>; needs a backtracking engine)",
}),
error.NotImplemented => error_catalog.raise(.feature_not_supported, loc, .{
.name = "this regex construct (inline flag, Unicode property or class form)",
}),
else => error_catalog.raise(.regex_pattern_invalid, loc, .{ .reason = @errorName(err) }),
};
}

/// The same mapping for a `#"..."` LITERAL. A literal is code, so a declined
/// construct stays the uncatchable unsupported-feature signal that a
/// `(catch Throwable …)` must not swallow (AD-060). Everything else is as
/// for a runtime string.
pub fn raiseLiteralCompileError(err: anyerror, loc: SourceLocation) error_catalog.ClojureWasmError {
if (declinedConstruct(err)) |name|
return error_catalog.raise(.feature_not_supported, loc, .{ .name = name });
return raiseCompileError(err, loc);
}

pub fn registerGcHooks() void {
tag_ops.registerOwnedBytes(.regex, &ownedBytes);
tag_ops.registerTrace(.regex, &traceRegex);
Expand Down
22 changes: 22 additions & 0 deletions test/clj/suites/regex_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,28 @@
(try (do (re-pattern "(a{65535}){65535}") :uncaught)
(catch IllegalArgumentException _ :caught))))) ; inv1_compile_bomb_catchable

;; Issue #136, AD-060 as amended: a pattern built from a runtime string is
;; data, so a construct cljw declines is a catchable IllegalArgumentException
;; that names the construct. The same construct in a #"..." literal is code
;; and stays uncatchable; that half is a process-boundary check in
;; test/e2e/regex_parity_gaps.sh.
(defn- declined [f]
(try (f) :compiled
(catch IllegalArgumentException e (ex-message e))))

(deftest a-declined-construct-in-a-runtime-pattern-is-catchable
(testing "a backreference, through every runtime surface"
(is (re-find #"regex backreference" (declined #(re-pattern "(a)\\1"))))
(is (re-find #"regex backreference" (declined #(re-pattern "(?<n>a)\\k<n>"))))
(is (re-find #"regex backreference"
(declined #(java.util.regex.Pattern/compile "(a)\\1"))))
(is (re-find #"regex backreference" (declined #(.split "aa" "(a)\\1")))))
(testing "an inline flag group cljw does not implement"
(is (re-find #"not supported in ClojureWasm" (declined #(re-pattern "a(?i)b")))))
(testing "the process goes on and the next pattern compiles"
(is (= "aa" (do (declined #(re-pattern "(a)\\1"))
(re-matches (re-pattern "a+") "aa"))))))

;; Issue #135: a range endpoint may be spelled as an escaped literal. The
;; patterns are built with re-pattern so each case states the exact source the
;; compiler sees. Every expected value was read from java.util.regex.
Expand Down
21 changes: 20 additions & 1 deletion test/clj/suites/vars_namespaces_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
(is (= "HI" (ev "(alias (quote str) (quote clojure.string)) (str/upper-case \"hi\")")) "alias-use")
(is (true? (ev "(do (alias (quote s) (quote clojure.set)) (contains? (ns-aliases *ns*) (quote s)))")) "ns-aliases")
(is (= 'clojure.walk (ev "(do (alias (quote w) (quote clojure.walk)) (ns-name ((ns-aliases *ns*) (quote w))))")) "alias-target")
(is (thrown-with-msg? Throwable #"Could not locate" (ev "(alias (quote x) (quote no.such.ns))")) "alias-unknown")))
(is (thrown-with-msg? Throwable #"No namespace" (ev "(alias (quote x) (quote no.such.ns))")) "alias-unknown")))

(def ^:dynamic *p15-x* 0)

Expand Down Expand Up @@ -178,6 +178,25 @@
(is (= "OK" (ev "(require '[clojure.string :as s]) (s/upper-case \"ok\")")) "literal-still")
(is (thrown-with-msg? Throwable #"Could not locate" (require 'p15.no.such.lib)) "missing-lib (from phase15_require_fs)")))

;; Issue #137: a namespace that is not on the load path raises
;; java.io.FileNotFoundException, as on the JVM, so the usual probe for an
;; optional namespace works. `refer` and `alias` look for no file: they raise
;; "No namespace".
(deftest a-missing-namespace-is-a-file-not-found
(is (= :absent
(try (require 'p15.no.such.optional.lib) :present
(catch java.io.FileNotFoundException _ :absent))))
(testing "the supertypes still catch it"
(is (= :io (try (require 'p15.no.such.optional.lib)
(catch java.io.IOException _ :io))))
(is (= :ex (try (require 'p15.no.such.optional.lib)
(catch Exception _ :ex)))))
(testing "refer of a namespace that is not loaded is not a missing file"
(is (= :no-namespace
(try (refer 'p15.no.such.optional.lib) :referred
(catch java.io.FileNotFoundException _ :file-not-found)
(catch Exception _ :no-namespace))))))

(deftest p15-ns-import
(testing "phase15_ns_import"
(is (true? (ev "(ns p15.im1 (:import java.util.UUID)) (uuid? (UUID/randomUUID))")) "sym-form")
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/phase6_16_b_4_require_basic.sh
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ esac

# --- (3) unknown namespace → lib_not_found ---
got="$("$BIN" -e "(require 'no.such.ns)" 2>&1 || true)"
if ! grep -q 'Name error' <<<"$got"; then
fail "require_unknown_kind: missing [name_error] tag (got '$got')"
if ! grep -q 'File not found' <<<"$got"; then
fail "require_unknown_kind: missing the 'File not found' kind label (got '$got')"
fi
if ! grep -q "Could not locate" <<<"$got"; then
fail "require_unknown_template: missing 'Could not locate' wording (got '$got')"
Expand Down
10 changes: 6 additions & 4 deletions test/e2e/regex_parity_gaps.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
# this file pins the SIGNAL SPLIT, which the corpus cannot express:
# - a MALFORMED pattern raises the CATCHABLE invalid-pattern error
# (Java: PatternSyntaxException, catchable), and
# - a VALID-in-Java backreference raises the UNCATCHABLE unsupported-feature
# error that a (catch Throwable …) must NOT swallow.
# - a VALID-in-Java backreference in a #"..." LITERAL raises the UNCATCHABLE
# unsupported-feature error that a (catch Throwable …) must NOT swallow.

set -euo pipefail
cd "$(dirname "$0")/../.."
Expand Down Expand Up @@ -51,9 +51,11 @@ EOF
|| fail "malformed_catchable: got '$(last_line "$got")'"
echo "PASS malformed_catchable"

# --- AD-060 pin: a backreference stays UNCATCHABLE ---
# --- AD-060 pin: a backreference in a LITERAL stays UNCATCHABLE ---
# A literal is code. The same construct in a runtime string (re-pattern) is
# data and catchable; that half is pinned in test/clj/suites/regex_test.clj.
got=$("$BIN" - <<'EOF' 2>&1 || true
(prn (try (re-pattern "(a)\\1") :NOT-RAISED (catch Throwable _ :swallowed)))
(prn (try #"(a)\1" :NOT-RAISED (catch Throwable _ :swallowed)))
EOF
)
grep -q 'is not supported in ClojureWasm' <<< "$got" \
Expand Down
2 changes: 1 addition & 1 deletion test/golden/cases/error_missing_ns.expected
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
--- stdout ---
before
--- stderr ---
Name error at <ROOT>/test/golden/cases/error_missing_ns.clj:2:10
File not found at <ROOT>/test/golden/cases/error_missing_ns.clj:2:10
Could not locate 'no.such.namespace' on the require resolver

1 | (println "before")
Expand Down
Loading