Skip to content

fix: enforce range and canonical form in from_str - #5

Open
gaoflow wants to merge 1 commit into
mipli:masterfrom
gaoflow:fix/from-str-canonical-range
Open

fix: enforce range and canonical form in from_str#5
gaoflow wants to merge 1 commit into
mipli:masterfrom
gaoflow:fix/from-str-canonical-range

Conversation

@gaoflow

@gaoflow gaoflow commented Jul 24, 2026

Copy link
Copy Markdown

Summary

Roman::from_str does not enforce the invariants that Roman::from enforces, and accepts non-canonical grammar. The Error::InvalidNumber variant is dead code — declared in src/errors.rs but never returned by the parser.

Internal-consistency smoking gun (no external oracle needed)

Roman::from rejects val == 0 || val > 3999 with Error::OutOfRange, but from_str accumulates the value and returns Ok(Roman(acc.val)) directly, bypassing the constructor. The parser builds values the constructor forbids:

Roman::from(4000)       = Err(OutOfRange(4000))
Roman::from_str("MMMM") = Ok(4000)        // 4000 > 3999 max
Roman::from_str("")     = Ok(0)           // 0 is out of range
Roman::from_str("MMMMMMMM") = Ok(8000)    // 8000 >> 3999

from and from_str disagree within the same library.

Canonical round-trip collision

from_str is a char-level tokenizer with a naive left-to-right subtractive accumulator. It has no grammar rules, so it accepts inputs that violate standard Roman-numeral grammar and normalizes them on round-trip. Distinct strings collide to the same value, breaking injectivity of the string -> value mapping:

from_str("IIII") = Ok(4)   .to_string() == "IV"     // I repeated 4x; "IV"/"IIII" collide
from_str("IC")   = Ok(99)  .to_string() == "XCIX"   // I cannot precede C
from_str("VV")   = Ok(10)  .to_string() == "X"      // V cannot repeat
from_str("XXXX") = Ok(40)  .to_string() == "XL"     // X repeated 4x
from_str("MIM")  = Ok(1999).to_string() == "MCMXCIX"// invalid subtractive
from_str("IIX")  = Ok(10)  .to_string() == "X"      // invalid subtractive

A non-canonical string is accepted and then re-emitted in canonical form by to_string(), so from_str(s).to_string() != s for non-canonical s.

Dead InvalidNumber

Error::InvalidNumber ("could not be parsed as a single roman numeral") exists in src/errors.rs but is never returned by from_str (unreachable from the parser).

The fix

In src/roman.rs from_str, after accumulating the numeric value and before returning Ok, add two checks:

  1. Range check matching from's invariant: if acc.val == 0 || acc.val > 3999 { return Err(Error::OutOfRange(acc.val)); } (same error/variant from uses).
  2. Canonical round-trip validator: let canonical = Roman::from(acc.val)?.to_string(); if canonical != s.to_ascii_uppercase() { return Err(Error::InvalidNumber(acc.val)); }. The comparison is case-insensitive (input uppercased) so lowercase canonical inputs such as "vii" still parse, matching the existing Digit::from_byte lowercase acceptance and the lib.rs doc-tests. Non-canonical inputs are rejected with InvalidNumber, making the previously-dead variant reachable per its documented meaning.

Roman::from_unchecked (the documented escape hatch for arbitrary/large values) is untouched. All canonical inputs (1..=3999, incl. lowercase) continue to parse correctly.

Test results

  • cargo testPASS (existing 8 + 4 + 9 doc-tests + 6 new tests = 27 total; 0 fail).
  • cargo fmt --check → clean.
  • cargo clippy --all-targets → only 3 pre-existing recursive_format_impl lints in src/errors.rs (untouched by this PR; present on pristine HEAD 2f8cff1). 0 new warnings/errors.

Pre-fix RED / post-fix GREEN (scanner harness)

input pre-fix post-fix
from_str("MMMM") Ok(4000) Err(OutOfRange(4000))
from_str("") Ok(0) Err(OutOfRange(0))
from_str("MMMMMMMM") Ok(8000) Err(OutOfRange(8000))
from_str("IIII") Ok(4) Err(InvalidNumber(4))
from_str("IC") Ok(99) Err(InvalidNumber(99))
from_str("VV") Ok(10) Err(InvalidNumber(10))
from_str("MIM") Ok(1999) Err(InvalidNumber(1999))

Canonical inputs unchanged

from_str("I")=Ok(1), ("IV")=Ok(4), ("XCIX")=Ok(99), ("MMMCMXCIX")=Ok(3999), ("vii")=Ok(7), ("dxxxii")=Ok(532); from_str("ABC")=Err(InvalidDigit('A')) (bad-char path unchanged).

New regression tests (tests/roman.rs)

  • from_str_rejects_range_bypassMMMM/MMMMMMMM/""Err(OutOfRange).
  • from_str_rejects_non_canonical_grammarIIII/VV/IC/IIX/XXXX/MIMErr(InvalidNumber).
  • from_str_accepts_canonical_controlsI/IV/XCIX/MMMCMXCIX still Ok & correct.
  • from_str_still_rejects_bad_charABCInvalidDigit('A').
  • from_str_accepts_lowercase_canonicalvii/dxxxii/mmmcmxcix.
  • from_str_canonical_round_trip_property — every n in 1..=3999: from(n).to_string() parses back to n; non-canonical spellings rejected.

2 files changed: src/roman.rs (+19/-0 in from_str), tests/roman.rs (+97/-0). 1 commit.

Roman::from enforces the 1..=3999 range invariant, but Roman::from_str
bypassed it: from_str("MMMM") returned Ok(4000) while from(4000) returned
Err(OutOfRange), and from_str("") returned Ok(0). from_str also accepted
non-canonical grammar (e.g. "IIII", "IC", "VV", "XXXX", "MIM", "IIX")
and normalized it on round-trip, so "IV" and "IIII" both parsed to 4 and
collided. The Error::InvalidNumber variant ("could not be parsed as a single
roman numeral") existed but was never returned by from_str.

This patch makes from_str enforce the same invariants as from:
  * Range check: reject val == 0 || val > 3999 with OutOfRange (matching
    the constructor).
  * Canonical round-trip validator: reject inputs whose parsed value's
    canonical form (from(val).to_string()) does not equal the input
    (compared case-insensitively, so lowercase canonical inputs such as
    "vii" still parse, matching existing from_byte acceptance) with
    InvalidNumber, making that variant reachable per its documented meaning.

from_unchecked remains the documented escape hatch for arbitrary/large
values and is untouched. All canonical inputs (1..=3999, incl. lowercase)
continue to parse correctly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant