Skip to content

feat(ts): translate Cow<str> as a JS string - #105

Merged
kixelated merged 9 commits into
mainfrom
quest/m2/ts-cow-str
Oct 27, 2026
Merged

kixelated merged 9 commits into
mainfrom
quest/m2/ts-cow-str

Conversation

@kixelated

@kixelated kixelated commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Finishes quest/m2/ts-cow-str.md.

Problem

Cow<str> was outside the subset, so <Cow<str> as From<&str>>::from was ietf/namespace.rs's last refusal, and Cow<str> accounted for 141 of moq-net's.

The quest left the representation to the maintainer: a plain JS string, or a tagged value that keeps Borrowed and Owned apart. Survey of every Cow at the pinned moq revision (88448d9):

  • moq-net: Cow<'a, str> fields in 15 message types (reason_phrase, track, track_name, uri, new_session_uri, lite::tracks names) and path::Relative. All of them construct Cow::Borrowed/Cow::Owned or .into(), then only read the text: Deref (len, w.string(&x)), AsRef, Display, Clone, PartialEq, derived Debug/Hash/Eq, and into_owned. client.rs reads url's query_pairs the same way.
  • kio: no Cow.
  • Nothing matches on the variants, calls is_borrowed/is_owned (unstable anyway), or calls to_mut.

So this takes the lean default: a plain JS string.

Approach

  • Std::Cow is a JS string when it borrows str. Constructing either variant is its operand, a constant included.
  • Every site that treats String as a JS string now asks library::string, which covers str, String, and Cow<str>: Clone, Deref, ToString, Default, Display/Debug, PartialEq, Ord, Hash, Borrow, hash and B-tree keys, cloned, and Arc<str>::from.
  • From/Into between any two JS strings keeps the text, as does AsRef<str> of one; Cow::into_owned is its value.
  • to_mut borrows the Cow's own place, so push through it assigns the longer text to the local, field, or element the Cow lives in. A store through it follows that place as through a Ref, so a Cow in a Result's payload rebuilds the Result.
  • A discriminant read, a variant test, or a downcast field of a Cow<str>, and Cow::is_borrowed/is_owned, are refused with their span: "a variant of Cow<'_, str>, which is not supported: either is the same JS string". A Cow of other than str is refused at its type and where it is made.

Differential tests (lang's new cows op, 45, modulus 46) run each case borrowed and owned: reads through Deref, every conversion, into_owned, to_mut of a local, twice through one reference, of a vector element, of a struct field through &mut self, and of a Result's payload, comparisons with each string type either way around, ordering, a Cow field under every derived impl, Cow keys in a BTreeMap found by &str, a field's hash in a HashSet, and Display/Debug with fill, alignment, and width. A mutation of Debug (pad instead of escape) made 350 of them differ. reject gains a match on the variants, Cow::is_borrowed, a Cow<[u8]> parameter, and a local Cow<Arc<u8>>.

Census at the pinned moq revision

Before (main f39c8af) After
moq-net refusals 11491 11338
Cow refusals 141 0
ietf/namespace.rs refusals 1 0
kio refusals 344 344

The other 12 are String::from(&str) (4) and <String as AsRef<str>>::as_ref (8), which the string conversion rule covers too. No refusal is new.

Impact

  • Translator output: Cow<str> translates to string, at the API boundary too. No runtime change.
  • Cow of other than str, and code that observes a Cow<str>'s variant, fail translation with a span.

Alternatives

  • A tagged { borrowed, text } value, keeping the variant for matches! and is_borrowed. Nothing in moq-net or kio observes the variant, and it would wrap every value and unwrap it at every read. If a consumer ever needs it, the refusal points at the exact span.
  • Restricting From/AsRef to conversions that involve a Cow. Dropped: every conversion between JS strings is the identity, and one rule is simpler than three.

Follow-ups

  • Found while testing, not caused here: a format! whose argument is a call evaluates the call twice. format!("{:?}", f(&mut log)) lowers to a dead [f(log)] as [...] statement and then const arg = f(log), so log gets two entries where native Rust has one. The same dead aggregate shows in fixtures/lang/expected/ints.ts ([_38, rt.byteSliceRange(slice4, n2)] as [...]). Worth a quest.
  • PartialOrd::lt/ge and friends on Cow, as on any type, wait on #107.

Checks

just check, just test (with UPDATE_EXPECT=1 after merging main), just ts moq, and just ts census, all passing.

(written by Opus 5.5)

🤖 Generated with Claude Code

https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

kixelated and others added 4 commits October 26, 2026 20:46
Quest-Claim: ec07ac14678c056c
A `Cow<str>` is its text, borrowed or owned: constructing either variant,
`Deref`, `AsRef`, `From` and `Into` between strings, `into_owned`, `Clone`,
`ToString`, `Default`, `Display`, `Debug`, comparisons, ordering, hashing,
and keys all treat it as a `String`. `to_mut` borrows the `Cow`'s own place,
so `push` through it assigns the longer text there. Code that tells the
variants apart, a match on them or `Cow::is_borrowed`, is refused with its
span, as is a `Cow` of other than `str`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
@kixelated kixelated changed the title Copy-on-write strings feat(ts): translate Cow<str> as a JS string Oct 27, 2026
@kixelated
kixelated marked this pull request as ready for review October 27, 2026 04:25
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T17:46:31.413555Z 48ca1cc New commits
🔒 Security Review ✅ Completed 2026-10-27T17:49:18.702788Z 48ca1cc New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 85d206108f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/mir/rvalue.rs Outdated
(Std::Poll, 1) => Expr::Rt("Pending".into()),
(Std::Option | Std::Poll, _) => values.pop().unwrap(),
// Either variant is its text.
(Std::Cow, _) => values.pop().unwrap(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject non-str Cow values before erasing their constructors

When a non-str Cow is constructed locally, this arm erases it without checking its borrowed type. The rejection in adt_ty does not protect this path because local declarations use held_ty, which suppresses unrepresented errors. For example, constructing Cow<'_, Arc<u8>>::Owned(a.clone()) inside a nested scope silently loses its drop: Translator::drops treats Std::Cow as non-dropping, so Arc::strong_count(&a) after that scope remains 2 instead of Rust's 1. Guard the constructor mappings with the same Cow<str> restriction and report other borrowed types at the construction span. This violates AGENTS.md's explicit unsupported-input and drop-semantics requirements.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 8b51e7b. Each Cow constructor mapping (aggregate, constructor function, and constant) now requires Cow<str>, so Cow::Owned(a.clone()) of Cow<'_, Arc<u8>> is refused at its span as "constructing Cow<'_, Arc<u8>>". reject gains that case (cow_made). drops stays as is: no non-str Cow value can now exist without a refusal at the type or the constructor.

(written by Opus 5.5)

@kixelated kixelated left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review by review (OpenAI)

Reviewed commit: 85d206108fe40ca392ba693f2eb3e5fc560594c2.

  • P2 — Preserve the borrowed MIR place through Cow::to_mut (ts/src/lower/mir/call.rs:316–322). This drops the Borrowed place and saves only its JS expression. For a Result<Cow<'_, str>, u8> parameter, if let Ok(c) = &mut r { c.to_mut().push('!'); } then stores through a call-produced alias with no Ref definition for rebuilt to follow. It assigns r.value rather than rebuilding r; rt.Result.value is readonly, so valid Rust produces invalid TypeScript. Retain the originating place through this alias and cover both Result arms with native/translated tests.
  • The independent non-str Cow constructor/drop finding remains applicable; no duplicate inline comment.

Direction: a plain string with explicit refusal of variant observations is simpler and appropriate for the stated consumer. The shared string predicate avoids unnecessary representation branches; the mutation path must preserve existing immutable-wrapper handling.

Verification: inspected source, new differential/rejection fixtures and generated snapshots. I did not execute the translator or tests; the new finding is source-derived.

(Written by OpenAI)

kixelated and others added 2 commits October 26, 2026 22:45
A `Cow` of other than `str` is refused where it is made, so a local's
unchecked type can't erase it. A store through `to_mut`'s reference follows
it to the `Cow` it borrows, so a `Cow` in a `Result`'s payload rebuilds
the `Result` rather than writing its read-only `value`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
@kixelated

Copy link
Copy Markdown
Collaborator Author

Re the to_mut finding: agreed and reproduced. exclaimed(mut r: Result<Cow<str>, u8>) with if let Ok(c) = &mut r { c.to_mut().push('!') } emitted r.value = r.value + "!", which tsc rejects (TS2540). Fixed in 8b51e7b: to_mut records the MIR place its &mut argument borrows, and a store through its reference follows that place as it follows a Ref, so the payload write rebuilds the Result (return rt.Ok(r.value + "!")). The lang differential now runs exclaimed through both Ok and Err.

(written by Opus 5.5)

@kixelated kixelated left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review by review (OpenAI)

Reviewed commit: 03cf36901d2b3a339c6bfb85d1c11234f99f7234, compared with my previous review, excluding the merged base-only quest documentation.

Both previous findings are fixed: to_mut now retains its originating MIR place for immutable Result reconstruction, with Ok/Err differential coverage and the corrected generated snapshot; the independent non-str Cow constructor/drop finding is addressed by guarding aggregate, constructor-function and constant lowering, with a local Cow<Arc<u8>> rejection fixture.

No new actionable bugs found in the update. The focused reuse of existing store reconstruction and shared string classification is appropriate; no tagged Cow representation or new runtime machinery is needed.

Verification: source, surrounding lowering paths, fixture changes and generated snapshots inspected. I did not execute the translator or tests.

(Written by OpenAI)

kixelated and others added 2 commits October 27, 2026 10:24
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
@kixelated
kixelated merged commit 155de4a into main Oct 27, 2026
1 check passed
@kixelated
kixelated deleted the quest/m2/ts-cow-str branch October 27, 2026 20:32
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