From 7991e55211ed7663308ece0d423e0d01667a8c72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:28:38 -0800 Subject: [PATCH 1/2] i18n: the message scan reads raw string literals The untranslated-strings scan and the undo step-name check read only "..." literals. A message, a &str constant, a step name or a format! string written as r"..." or r#"..."# was skipped, and a raw string that was read went through escape decoding and ended at its first inner quote. The scan now reads a raw string up to the quote followed by the literal's own number of # and keeps its backslashes, as the Rust Reference defines raw strings (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). Byte strings and C strings, raw or not, are not read as text. The walkers that find an error helper's argument, a statement's end, a closure's returned values and a format!'s arguments now use the same literal boundaries, so a comma, semicolon, bracket or return inside a raw string or a character literal is no longer read as syntax. No current message or step name is a raw string, so no catalog row changes. --- crates/ui-egui/src/i18n/tests.rs | 322 ++++++++++++++++++++----------- docs/target-app-parity.md | 1 + 2 files changed, 215 insertions(+), 108 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 25e378a43a..b6200fb66a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1915,7 +1915,7 @@ fn undo_scan() -> UndoScan { } for t in &files { let named = t.match_indices(NAMED_MARKER).filter_map(|(at, _)| arguments(&t[at + NAMED_MARKER.len()..]).first().copied()); - templates.extend(named.filter_map(|a| a.strip_prefix('"').and_then(string_literal))); + templates.extend(named.filter_map(leading_text)); } } UndoScan { labels: out, templates, formatted } @@ -1998,8 +1998,7 @@ fn quoted_end(text: &str, at: usize) -> Option { } return it.next().filter(|(_, c)| *c == '\'').map(|(n, _)| at + 1 + n + 1); } - let hashes = text[..at].chars().rev().take_while(|c| *c == '#').count(); - if text[..at - hashes].ends_with('r') { + if let Some(hashes) = raw_hashes(text, at) { let close = format!("\"{}", "#".repeat(hashes)); return rest.find(&close).map(|n| at + 1 + n + close.len()); } @@ -2016,6 +2015,46 @@ fn quoted_end(text: &str, at: usize) -> Option { None } +/// The number of `#` around the raw string literal whose opening `"` is at `text[quote]` (`r"…"`, +/// `r#"…"#`, `br#"…"#`); `None` when the literal is not raw. +fn raw_hashes(text: &str, quote: usize) -> Option { + let hashes = quote - text[..quote].trim_end_matches('#').len(); + text[..quote - hashes].ends_with('r').then_some(hashes) +} + +/// The string literal whose opening `"` is at `text[quote]`: where it starts, its prefix (`r`, +/// `r#`, `b`, `br`, `c`, `cr`) included, where it ends, and its text when it is a `&str` literal: +/// a `"…"` literal with its escapes resolved (see [`string_literal`]), or a raw `r"…"` or `r#"…"#` +/// literal as written, backslashes included (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). +/// A byte string or a C string has no text; `None` when the literal is not closed. +fn literal_at(text: &str, quote: usize) -> Option<(usize, usize, Option)> { + let end = quoted_end(text, quote)?; + let raw = raw_hashes(text, quote); + let mut start = quote - raw.map_or(0, |hashes| hashes + 1); + let not_text = text[..start].ends_with(['b', 'c']) && !text[..start - 1].ends_with(|c: char| c.is_alphanumeric() || c == '_'); + if not_text { + start -= 1; + return Some((start, end, None)); + } + let lit = match raw { + Some(hashes) => Some(text[quote + 1..end - 1 - hashes].to_string()), + None => string_literal(&text[quote + 1..]), + }; + Some((start, end, lit)) +} + +/// The text of the `&str` literal `s` starts with (`"…"`, `r"…"`, `r#"…"#`), as [`literal_at`] +/// reads it; `None` when `s` does not start with one. +fn leading_text(s: &str) -> Option { + let quote = s.find('"')?; + let prefix = &s[..quote]; + let raw_prefix = prefix.strip_prefix('r').is_some_and(|hashes| hashes.chars().all(|c| c == '#')); + if !prefix.is_empty() && !raw_prefix { + return None; + } + literal_at(s, quote)?.2 +} + /// In `s` (the text after an opening bracket), the offset of each top-level `,`, and where the /// list ends: at the bracket that closes it, a top-level `;`, or the end of `s`. fn top_level(s: &str) -> (Vec, usize) { @@ -2140,7 +2179,7 @@ fn label_literals( ) { let mut e = bare(e); if let Some(args) = e.strip_prefix("format!(") { - formatted.extend(args.trim_start().strip_prefix('"').and_then(string_literal)); + formatted.extend(leading_text(args.trim_start())); return; } if let Some(body) = e.strip_prefix('|').and_then(|r| r.find('|').map(|n| &r[n + 1..])) { @@ -2167,19 +2206,24 @@ fn label_literals( } } -/// The string literals in `e` that `keep` accepts, given the text before and after each. +/// The text of each `&str` literal in `e` (`"…"`, `r"…"`, `r#"…"#`, see [`literal_at`]) that `keep` +/// accepts, given the text before the literal and its prefix and the text after it. Byte strings and +/// C strings are not read. fn string_literals(e: &str, keep: impl Fn(&str, &str) -> bool) -> Vec { let mut out = vec![]; let mut i = 0; while let Some(c) = e[i..].chars().next() { - if let Some(end) = (c == '"' || c == '\'').then(|| quoted_end(e, i)).flatten() { - if c == '"' - && let Some(lit) = string_literal(&e[i + 1..]) - && keep(&e[..i], &e[end..]) + if c == '"' + && let Some((start, end, lit)) = literal_at(e, i) + { + if let Some(lit) = lit + && keep(&e[..start], &e[end..]) { out.push(lit); } i = end; + } else if let Some(end) = (c == '\'').then(|| quoted_end(e, i)).flatten() { + i = end; } else { i += c.len_utf8(); } @@ -4702,6 +4746,124 @@ fn message_scan_rejects_invalid_rust_escapes() { assert_eq!(source_messages(code, &[], &Default::default()), ["good value"]); } +/// The undo scan reads a step name or a `format!` template written as a raw string (`r"…"`, +/// `r#"…"#`, `r##"…"##`) as Rust reads it: up to the quote followed by the literal's own number of +/// `#`, with its backslashes kept (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). +/// `Session::edit_named` templates are read the same way. +#[test] +fn undo_scan_reads_raw_step_names() { + let (mut names, mut formatted) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for e in [ + r#"r"Move path""#, + r##"r#"Move "named" path"#"##, + r###"r##"Move "#tag" path"##"###, + r#"r"Move\npath""#, + r##"if copy { r#"Copy "it""# } else { "Move it" }"##, + r##"format!(r#"Move "named" {n}"#, n = 2)"##, + ] { + label_literals(e, 0, &[], &mut names, &mut formatted); + } + let want = ["Copy \"it\"", "Move \"#tag\" path", "Move \"named\" path", "Move it", "Move path", "Move\\npath"]; + assert_eq!(names.iter().collect::>(), want); + assert_eq!(formatted.iter().collect::>(), ["Move \"named\" {n}"]); + assert_eq!(leading_text(r##"r#"Move "{0}" layers"#, count)"##).as_deref(), Some("Move \"{0}\" layers")); + assert_eq!(leading_text(r#""Move {0} layers", count)"#).as_deref(), Some("Move {0} layers")); + assert_eq!(leading_text(r#"br"Move", count)"#), None); +} + +/// The message scan reads a raw string where it reads a message: after `Err(`, as an error +/// variant's message and in `#[error(…)]`, as an error helper's argument, as a `&str` constant's +/// value, and as the `format!` string a `.map_err` closure returns. Its quotes and backslashes stay +/// as written, and only the `format!` string's `{e}` is a placeholder. +#[test] +fn message_scan_reads_raw_strings() { + let code = r####" +fn run() -> Result<()> { + let _ = Err(r"the file is missing"); + let _ = Err(r"the C:\temp folder is missing"); + let _ = Error::Manifest(r#"the "named" file is missing"#); + let _ = bad(cmd, r#"the file is missing, {really}"#); + let _ = Err(LOST); + let _ = Err(QUOTED); + load().map_err(|e| format!(r##"the "#tag" file failed: {e}"##))?; + Ok(()) +} +#[derive(Error)] +enum Failure { + #[error(r#"the "named" file is lost: {0}"#)] + Lost(String), +} +"####; + let declared = r##"const LOST: &str = r"the file is lost"; const QUOTED: &'static str = r#"the "named" file is lost"#;"##; + let consts = str_consts(declared); + let want = [("LOST", "the file is lost"), ("QUOTED", "the \"named\" file is lost")]; + assert_eq!(consts.iter().map(|(n, v)| (n.as_str(), v.as_str())).collect::>(), want); + let consts = std::collections::BTreeMap::from_iter(consts.into_iter().map(|(name, value)| (name, vec![value]))); + let found: std::collections::BTreeSet = source_messages(code, &[("bad(", 1)], &consts).into_iter().collect(); + let want = [ + "the \"#tag\" file failed: {e}", + "the \"named\" file is lost", + "the \"named\" file is lost: {0}", + "the \"named\" file is missing", + "the C:\\temp folder is missing", + "the file is lost", + "the file is missing", + "the file is missing, {{really}}", + ]; + assert_eq!(found.iter().collect::>(), want); +} + +/// Byte strings and C strings, raw or not, are not text: the scan reads none of them as a message +/// or a step name. +#[test] +fn message_scan_skips_byte_and_c_strings() { + let e = r##"(b"byte error", br#"byte "error""#, c"C error", cr"C error", "text error")"##; + assert_eq!(string_literals(e, |_, _| true), ["text error"]); + let code = r##"fn run() { let _ = Err(b"byte error"); let _ = Err(br#"byte "error""#); let _ = Err(c"C error"); }"##; + assert!(source_messages(code, &[], &Default::default()).is_empty()); + let (mut names, mut formatted) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for e in [r#"b"Move""#, r##"br#"Move"#"##, r#"c"Move""#, r#"format!(b"Move {n}")"#] { + label_literals(e, 0, &[], &mut names, &mut formatted); + } + assert!(names.is_empty() && formatted.is_empty(), "{names:?} {formatted:?}"); +} + +/// A comma, bracket, semicolon, quote, `return` or backslash inside a raw string is text, not +/// syntax: an error helper's message is the argument after the raw one, a statement ends at the +/// `;` after a raw string, a closure's raw string holds no `return`, and the raw string is emptied +/// whole before the scan looks for a local's name. +#[test] +fn message_scan_reads_past_raw_strings() { + let code = r###"fn run() { let _ = bad(r#"command ", other"#, r"the second argument is the error"); }"###; + assert_eq!(source_messages(code, &[("bad(", 1)], &Default::default()), ["the second argument is the error"]); + assert_eq!(statement(r##"r#"note "; still text"#; tail"##), r##"r#"note "; still text"#"##); + assert_eq!(statement(r#"(';', ")") ; tail"#), r#"(';', ")") "#); + let code = r###" +fn run() -> Result<()> { + let fail = |e| { let note = r#"note "; still text"#; format!("the file failed: {e}") }; + load().map_err(fail)?; + open().map_err(|e| { + let note = r##"name"; return "fake" {x}"##; + format!("the file could not be opened: {e}") + })?; + Ok(()) +} +"###; + let found: std::collections::BTreeSet = source_messages(code, &[], &Default::default()).into_iter().collect(); + assert_eq!(found.iter().collect::>(), ["the file could not be opened: {e}", "the file failed: {e}"]); + assert_eq!(without_strings(r###"let note = r#"a "used_name" {x}"#; note"###), r##"let note = r#""#; note"##); + assert_eq!(without_strings(r###"x(r#"a\"#, "b\"c", y)"###), r##"x(r#""#, "", y)"##); + assert_eq!(without_strings(r#"f('"', "a")"#), r#"f('"', "")"#); +} + +/// A bracket in a character literal among a `format!`'s arguments does not end them: the scan +/// removes the arguments up to the `format!`'s own closing parenthesis. +#[test] +fn format_args_end_at_the_closing_parenthesis() { + assert_eq!(without_format_args(r#"format!("", ')', x) + why"#), "format!() + why"); + assert_eq!(without_format_args(r#"format!("", f(x)[0]) + why"#), "format!() + why"); +} + /// The scan reads the message of each of the plug-in host's [`ERROR_HELPERS`]: a literal, a /// `format!` string with or without a `&` before it, after the location of `out_err` (a /// `format!` string too), the number and range of `in_range`, the number and location of `unit`, @@ -7060,8 +7222,8 @@ fn scoped_consts<'a>( std::borrow::Cow::Owned(consts) } -/// The `&str` constants `code` declares outside its comments (`const NAME: &str = "…";`), with -/// their text, escapes resolved. +/// The `&str` constants `code` declares outside its comments (`const NAME: &str = "…";`, or a raw +/// `r#"…"#` value), with their text as [`leading_text`] reads it. fn str_consts(code: &str) -> Vec<(String, String)> { let code = &without_comments(code); code.match_indices("const ") @@ -7071,7 +7233,7 @@ fn str_consts(code: &str) -> Vec<(String, String)> { let (name, rest) = rest.split_at(rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_')?); let rest = rest.trim_start().strip_prefix(':')?.trim_start(); let rest = rest.strip_prefix("&'static str").or_else(|| rest.strip_prefix("&str"))?.trim_start(); - let value = string_literal(rest.strip_prefix('=')?.trim_start().strip_prefix('"')?)?; + let value = leading_text(rest.strip_prefix('=')?.trim_start())?; Some((name.to_string(), value)) }) .collect() @@ -7097,7 +7259,7 @@ fn named_const<'a>(rest: &str, consts: &'a std::collections::BTreeMap string_literal(quoted).into_iter().collect(), + let lits = match leading_text(rest) { + Some(lit) => vec![lit], None => named_const(rest, consts).to_vec(), }; for lit in lits { @@ -7164,35 +7326,14 @@ fn source_messages(code: &str, helpers: &[(&str, usize)], consts: &std::collecti } /// The arguments of a call whose opening parenthesis was just read, past the first `n` of them; -/// `None` when `n` is 1 or more and the call has `n` arguments or fewer. +/// `None` when `n` is 1 or more and the call has `n` arguments or fewer. A comma or bracket inside a +/// string literal, raw ones included, or a character literal does not count (see [`top_level`]). fn skip_args(args: &str, n: usize) -> Option<&str> { if n == 0 { return Some(args); } - let (mut left, mut depth, mut chars) = (n, 0usize, args.char_indices()); - while let Some((at, c)) = chars.next() { - match c { - '(' | '[' | '{' => depth += 1, - ')' | ']' | '}' => depth = depth.checked_sub(1)?, - '"' => loop { - match chars.next()?.1 { - '\\' => { - chars.next()?; - } - '"' => break, - _ => {} - } - }, - ',' if depth == 0 => { - left -= 1; - if left == 0 { - return Some(&args[at + 1..]); - } - } - _ => {} - } - } - None + let comma = *top_level(args).0.get(n - 1)?; + Some(&args[comma + 1..]) } /// Where each value the error handler `name` of a `.map_err(name)` in `code` can return starts: @@ -7219,30 +7360,11 @@ fn handler_returns<'a>(code: &'a str, name: &str) -> Vec<&'a str> { out } -/// The statement `code` starts with, up to its `;` or the bracket that closes the block it is in. +/// The statement `code` starts with, up to its `;` or the bracket that closes the block it is in; +/// a `;` or bracket inside a string literal, raw ones included, or a character literal does not +/// end it (see [`top_level`]). fn statement(code: &str) -> &str { - let (mut depth, mut chars) = (0usize, code.char_indices()); - while let Some((at, c)) = chars.next() { - match c { - '(' | '[' | '{' => depth += 1, - ')' | ']' | '}' => match depth.checked_sub(1) { - Some(d) => depth = d, - None => return &code[..at], - }, - ';' if depth == 0 => return &code[..at], - '"' => loop { - match chars.next() { - Some((_, '\\')) => { - chars.next(); - } - Some((_, '"')) | None => break, - _ => {} - } - }, - _ => {} - } - } - code + &code[..top_level(code).1] } /// Where each value a closure can return starts, `body` being the text after its parameters: the @@ -7269,10 +7391,15 @@ fn closure_returns(body: &str) -> Vec<&str> { // For each open bracket, the `quiet` and `in_let` of the text around it: `quiet` names the // `let` that a value inside the bracket belongs to, `in_let` the `let` the statement is. let mut outer = vec![]; - let (mut quiet, mut in_let, mut chars) = (None, let_at(0), body.char_indices()); + let (mut quiet, mut in_let) = (None, let_at(0)); // Where the innermost closure in the body that a `return` would leave ends. let mut inner_closure_end = 0; - while let Some((at, c)) = chars.next() { + // Where the string or character literal last read ends: nothing inside one is syntax. + let mut literal_end = 0; + for (at, c) in body.char_indices() { + if at < literal_end { + continue; + } match c { '|' if at >= inner_closure_end => { let before = body[..at].trim_end(); @@ -7313,15 +7440,8 @@ fn closure_returns(body: &str) -> Vec<&str> { { found.push((&body[at + "return".len()..], None, true)); } - '"' => loop { - match chars.next() { - Some((_, '\\')) => { - chars.next(); - } - Some((_, '"')) | None => break, - _ => {} - } - }, + '"' => literal_end = quoted_end(body, at).unwrap_or(body.len()), + '\'' => literal_end = quoted_end(body, at).unwrap_or(at), _ => {} } } @@ -7340,52 +7460,38 @@ fn closure_returns(body: &str) -> Vec<&str> { } /// `code`, its string literals already emptied, with the arguments of each `format!(…)` removed: -/// a value written into a format string is part of a message, not one of its own. +/// a value written into a format string is part of a message, not one of its own. A bracket in a +/// character literal (`')'`) does not end the arguments (see [`top_level`]). fn without_format_args(code: &str) -> String { let (mut out, mut rest) = (String::new(), code); while let Some(at) = rest.find("format!(") { out.push_str(&rest[..at + "format!(".len()]); rest = &rest[at + "format!(".len()..]; - let mut depth = 0usize; - let end = rest.char_indices().find_map(|(i, c)| match c { - '(' | '[' | '{' => { - depth += 1; - None - } - ')' | ']' | '}' => match depth.checked_sub(1) { - Some(d) => { - depth = d; - None - } - None => Some(i), - }, - _ => None, - }); - rest = &rest[end.unwrap_or(rest.len())..]; + let (_, end) = top_level(rest); + rest = &rest[end..]; } out.push_str(rest); out } -/// `code` with the text of its string literals removed, the quotes kept. +/// `code` with the text of its string literals removed, the quotes kept: a raw literal keeps its +/// prefix and its `#`s (`r#""#`). Character literals stay as they are. fn without_strings(code: &str) -> String { - let (mut out, mut chars) = (String::new(), code.chars()); - while let Some(c) = chars.next() { - out.push(c); + let (mut out, mut i) = (String::new(), 0); + while let Some(c) = code[i..].chars().next() { if c == '"' { - loop { - match chars.next() { - Some('\\') => { - chars.next(); - } - Some('"') => { - out.push('"'); - break; - } - Some(_) => {} - None => break, - } - } + let Some(end) = quoted_end(code, i) else { + out.push('"'); + break; + }; + let close = 1 + raw_hashes(code, i).unwrap_or(0); + out.push('"'); + out.push_str(&code[end - close..end]); + i = end; + } else { + let end = (c == '\'').then(|| quoted_end(code, i)).flatten().unwrap_or(i + c.len_utf8()); + out.push_str(&code[i..end]); + i = end; } } out diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e93c07ed..666fa5bc80 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1153,6 +1153,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - The untranslated-strings report reads the escapes in a message (`\r`, `\0`, `\x41`, `\u{e9}` and the others the Rust Reference lists at https://doc.rust-lang.org/reference/tokens.html#character-escapes) as the characters the program shows, and leaves out a literal with an escape Rust does not accept, such as `\q` or `\u{D800}` (`message_scan_decodes_rust_character_escapes`, `message_scan_rejects_invalid_rust_escapes`). + - The untranslated-strings report and the undo step-name check read a message, a `&str` constant, a step name or a `format!` string written as a raw string (`r"…"`, `r#"…"#`, `r##"…"##`) with its backslashes kept, up to the quote followed by the literal's own number of `#` (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). They read no byte string or C string as a message, and a comma, `;`, bracket or `return` inside a raw string or a character literal does not end an argument, a statement or a closure's value (`undo_scan_reads_raw_step_names`, `message_scan_reads_raw_strings`, `message_scan_skips_byte_and_c_strings`, `message_scan_reads_past_raw_strings`, `format_args_end_at_the_closing_parenthesis`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). From 3ee68d5aa91d19873c13518bed5ad9878b6fd48a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:26:47 -0800 Subject: [PATCH 2/2] i18n: the message scan skips calls written inside string literals A marker such as `Err(`, an error variant, a `.map_err` or an error helper call that appears inside a string literal is text, not code. The scan matched these anyway, so a source holding `r##"Err(r#"sample error"#)"##` added "sample error" as a message. source_messages now finds every string and character literal span first and drops each match that starts inside one, and a new test covers the nested raw-string forms beside a real `Err(r#"..."#)` call. --- crates/ui-egui/src/i18n/tests.rs | 60 +++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b6200fb66a..7dd9a3f6a7 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2231,6 +2231,28 @@ fn string_literals(e: &str, keep: impl Fn(&str, &str) -> bool) -> Vec { out } +/// Where each string literal (its prefix included, see [`literal_at`]) and character literal in +/// `code` starts and ends, in order. +fn literal_spans(code: &str) -> Vec<(usize, usize)> { + let mut out = vec![]; + let mut i = 0; + while let Some(c) = code[i..].chars().next() { + let span = match c { + '"' => literal_at(code, i).map(|(start, end, _)| (start, end)), + '\'' => quoted_end(code, i).map(|end| (i, end)), + _ => None, + }; + match span { + Some((start, end)) => { + out.push((start, end)); + i = end; + } + None => i += c.len_utf8(), + } + } + out +} + /// For translators, `cargo test -p vectorcraft-ui-egui dump_source_strings` writes every English /// interface string to `VECTORCRAFT_I18N_DUMP=`, and every status and error message as a /// catalog template that [`untranslated_report`] checks to `VECTORCRAFT_I18N_DUMP_MESSAGES=`, @@ -4856,6 +4878,25 @@ fn run() -> Result<()> { assert_eq!(without_strings(r#"f('"', "a")"#), r#"f('"', "")"#); } +/// A marker, an error variant, a `.map_err` or an error helper call written inside a string literal +/// is text, not code: the scan reads no message from it, while the same call outside a literal +/// still gives its message. +#[test] +fn message_scan_skips_calls_inside_string_literals() { + let code = r####" +const SAMPLE: &str = r##"Err(r#"sample error"#)"##; +const VARIANT: &str = r##"Error::Lost(r#"variant error"#)"##; +const CLOSURE: &str = r##"load().map_err(|e| format!(r#"closure error {e}"#))"##; +const HELPER: &str = r##"bad(cmd, r#"helper error"#)"##; +fn run() -> Result<()> { + let _ = Err(r#"real error"#); + Ok(()) +} +"####; + let found = source_messages(code, &[("bad(", 1)], &Default::default()); + assert_eq!(found, ["real error"]); +} + /// A bracket in a character literal among a `format!`'s arguments does not end them: the scan /// removes the arguments up to the `format!`'s own closing parenthesis. #[test] @@ -7263,25 +7304,33 @@ fn named_const<'a>(rest: &str, consts: &'a std::collections::BTreeMap>) -> Vec { let code = &without_comments(code); + let spans = &literal_spans(code); + // Whether `code[at]` is inside a string or character literal, where a call is text, not code. + let in_literal = move |at: usize| { + let k = spans.partition_point(|&(start, _)| start <= at); + k > 0 && at < spans[k - 1].1 + }; + let code_matches = move |pat: &'static str| code.match_indices(pat).filter(move |&(at, _)| !in_literal(at)); let after_markers = - MESSAGE_MARKERS.iter().flat_map(|marker| code.match_indices(marker).map(|(at, _)| (&code[at + marker.len()..], *marker == "#[error("))); - let in_variants = ["Error::", "Fail::"].into_iter().flat_map(|enum_end| code.match_indices(enum_end)).filter_map(|(at, m)| { + MESSAGE_MARKERS.iter().flat_map(|marker| code_matches(marker).map(|(at, _)| (&code[at + marker.len()..], *marker == "#[error("))); + let in_variants = ["Error::", "Fail::"].into_iter().flat_map(code_matches).filter_map(|(at, m)| { let rest = &code[at + m.len()..]; let (variant, args) = rest.split_at(rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len())); let named = variant.starts_with(|c: char| c.is_ascii_uppercase()) && !NAME_VARIANTS.contains(&variant); let before = LATER_MESSAGE_VARIANTS.iter().find(|(v, _)| *v == variant).map_or(0, |&(_, n)| n); if named { skip_args(args.strip_prefix('(')?, before).map(|rest| (rest, false)) } else { None } }); - let in_map_err = code.match_indices(".map_err(").flat_map(|(at, m)| { + let in_map_err = code_matches(".map_err(").flat_map(|(at, m)| { let rest = code[at + m.len()..].trim_start(); let params = rest.strip_prefix("move").map_or(rest, str::trim_start).strip_prefix('|'); params.and_then(|p| p.find('|').map(|end| &p[end + 1..])).map(closure_returns).unwrap_or_default() }); let mut handlers = vec![]; - for (at, m) in code.match_indices(".map_err(") { + for (at, m) in code_matches(".map_err(") { let rest = &code[at + m.len()..]; let name = &rest[..rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len())]; if name.starts_with(|c: char| c.is_ascii_lowercase()) && rest[name.len()..].starts_with(')') && !handlers.contains(&name) { @@ -7291,6 +7340,7 @@ fn source_messages(code: &str, helpers: &[(&str, usize)], consts: &std::collecti let in_handlers = handlers.into_iter().flat_map(|name| handler_returns(code, name)); let in_helpers = helpers.iter().flat_map(|&(call, before)| { code.match_indices(call) + .filter(move |&(at, _)| !in_literal(at)) .filter(|&(at, _)| call.starts_with('.') || !code[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_' || c == '.')) .filter(|&(at, _)| { let owner = code[..at].strip_suffix("::").map(|p| p.rsplit(|c: char| !c.is_alphanumeric() && c != '_').next().unwrap_or(""));