Repository navigation
feat(ts): translate Cow<str> as a JS string - #105
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| (Std::Poll, 1) => Expr::Rt("Pending".into()), | ||
| (Std::Option | Std::Poll, _) => values.pop().unwrap(), | ||
| // Either variant is its text. | ||
| (Std::Cow, _) => values.pop().unwrap(), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 theBorrowedplace and saves only its JS expression. For aResult<Cow<'_, str>, u8>parameter,if let Ok(c) = &mut r { c.to_mut().push('!'); }then stores through a call-produced alias with noRefdefinition forrebuiltto follow. It assignsr.valuerather than rebuildingr;rt.Result.valueis 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)
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
|
Re the (written by Opus 5.5) |
kixelated
left a comment
There was a problem hiding this comment.
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)
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Finishes quest/m2/ts-cow-str.md.
Problem
Cow<str>was outside the subset, so<Cow<str> as From<&str>>::fromwasietf/namespace.rs's last refusal, andCow<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
BorrowedandOwnedapart. Survey of everyCowat the pinned moq revision (88448d9):Cow<'a, str>fields in 15 message types (reason_phrase,track,track_name,uri,new_session_uri,lite::tracksnames) andpath::Relative. All of them constructCow::Borrowed/Cow::Ownedor.into(), then only read the text:Deref(len,w.string(&x)),AsRef,Display,Clone,PartialEq, derivedDebug/Hash/Eq, andinto_owned.client.rsreads url'squery_pairsthe same way.Cow.is_borrowed/is_owned(unstable anyway), or callsto_mut.So this takes the lean default: a plain JS string.
Approach
Std::Cowis a JS string when it borrowsstr. Constructing either variant is its operand, a constant included.Stringas a JS string now askslibrary::string, which coversstr,String, andCow<str>:Clone,Deref,ToString,Default,Display/Debug,PartialEq,Ord,Hash,Borrow, hash and B-tree keys,cloned, andArc<str>::from.From/Intobetween any two JS strings keeps the text, as doesAsRef<str>of one;Cow::into_ownedis its value.to_mutborrows theCow's own place, sopushthrough it assigns the longer text to the local, field, or element theCowlives in. A store through it follows that place as through aRef, so aCowin aResult's payload rebuilds theResult.Cow<str>, andCow::is_borrowed/is_owned, are refused with their span: "a variant ofCow<'_, str>, which is not supported: either is the same JS string". ACowof other thanstris refused at its type and where it is made.Differential tests (
lang's newcowsop, 45, modulus 46) run each case borrowed and owned: reads throughDeref, every conversion,into_owned,to_mutof a local, twice through one reference, of a vector element, of a struct field through&mut self, and of aResult's payload, comparisons with each string type either way around, ordering, aCowfield under every derived impl,Cowkeys in aBTreeMapfound by&str, a field's hash in aHashSet, andDisplay/Debugwith fill, alignment, and width. A mutation ofDebug(pad instead of escape) made 350 of them differ.rejectgains a match on the variants,Cow::is_borrowed, aCow<[u8]>parameter, and a localCow<Arc<u8>>.Census at the pinned moq revision
f39c8af)Cowrefusalsietf/namespace.rsrefusalsThe 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
Cow<str>translates tostring, at the API boundary too. No runtime change.Cowof other thanstr, and code that observes aCow<str>'s variant, fail translation with a span.Alternatives
{ borrowed, text }value, keeping the variant formatches!andis_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.From/AsRefto conversions that involve aCow. Dropped: every conversion between JS strings is the identity, and one rule is simpler than three.Follow-ups
format!whose argument is a call evaluates the call twice.format!("{:?}", f(&mut log))lowers to a dead[f(log)] as [...]statement and thenconst arg = f(log), sologgets two entries where native Rust has one. The same dead aggregate shows infixtures/lang/expected/ints.ts([_38, rt.byteSliceRange(slice4, n2)] as [...]). Worth a quest.PartialOrd::lt/geand friends onCow, as on any type, wait on #107.Checks
just check,just test(withUPDATE_EXPECT=1after merging main),just ts moq, andjust ts census, all passing.(written by Opus 5.5)
🤖 Generated with Claude Code
https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn