From 91df77764df705061a0f13f111ed066e75f771a2 Mon Sep 17 00:00:00 2001 From: Asger F Date: Wed, 2 Dec 2026 14:24:47 +0100 Subject: [PATCH 1/2] Unified: Interpret all kinds of Swift string literals Resolve escape sequences (including raw-string delimiters) and normalise line endings when computing interpreted string values, and extract interpolation-free multi-segment literals (e.g. multi-line strings) as a single string literal. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../extractor/src/languages/swift/swift.rs | 155 ++++++++++-- .../literals/string-literal-kinds.output | 225 ++++++++++++++++++ .../swift/literals/string-literal-kinds.swift | 36 +++ .../library-tests/BasicTest/strings.swift | 10 + .../library-tests/BasicTest/test.expected | 17 ++ 5 files changed, 425 insertions(+), 18 deletions(-) create mode 100644 unified/extractor/tests/corpus/swift/literals/string-literal-kinds.output create mode 100644 unified/extractor/tests/corpus/swift/literals/string-literal-kinds.swift diff --git a/unified/extractor/src/languages/swift/swift.rs b/unified/extractor/src/languages/swift/swift.rs index 2582955ab8d7..9a8e44af65ea 100644 --- a/unified/extractor/src/languages/swift/swift.rs +++ b/unified/extractor/src/languages/swift/swift.rs @@ -85,6 +85,10 @@ struct SwiftContext { /// name has no argument label. It is cleared when translating accessor /// bodies. subscript: Option, + /// Number of `#` delimiters of the enclosing raw string literal, set by + /// the string literal rules before translating their segments so that + /// escape sequences (`\#n`) are recognised correctly. + string_pounds: usize, /// Interpreted values keyed by their output string literal. interpreted_strings: Rc>>, } @@ -121,23 +125,96 @@ impl SwiftContext { } } +/// Creates a `string_literal` located at `location` whose interpreted value is +/// the concatenation of the interpreted `segments` (`stringSegment` nodes). fn make_string_literal( ctx: &mut yeast::build::BuildCtx<'_, SwiftContext>, - source: yeast::Id, + location: yeast::Id, + segments: &[yeast::Id], + pounds: usize, ) -> yeast::OutputId { - let raw = ctx.source_text(source); - let interpreted = raw - .strip_prefix('"') - .and_then(|value| value.strip_suffix('"')) - .unwrap_or(&raw) - .to_string(); - let literal = tree!((string_literal #{source})); + let interpreted: String = segments + .iter() + .map(|&segment| interpret_string_segment(&ctx.source_text(segment), pounds)) + .collect(); + let literal = tree!((string_literal #{location})); ctx.interpreted_strings .borrow_mut() .push((literal, interpreted)); literal } +/// Gets the number of `#` characters in a raw string delimiter. +fn pound_count(ctx: &yeast::build::BuildCtx<'_, SwiftContext>, pounds: Option) -> usize { + pounds.map_or(0, |p| { + ctx.source_text(p).chars().filter(|&c| c == '#').count() + }) +} + +/// Holds if every node in `nodes` is a `stringSegment` (no interpolations). +fn all_string_segments(ast: &yeast::Ast, nodes: &[yeast::Id]) -> bool { + nodes.iter().all(|&n| { + ast.get_node(n) + .is_some_and(|node| node.kind_name() == "stringSegment") + }) +} + +/// Interprets the text of a string literal segment: resolves escape sequences +/// (whose delimiter is a backslash followed by `pounds` `#` characters, for raw +/// strings) and normalises line endings to `\n`. +/// +/// swift-syntax already excludes the quotes, the indentation of multi-line +/// literals, and escaped newlines (line continuations) from segment text. +/// Malformed escape sequences are kept verbatim. +fn interpret_string_segment(raw: &str, pounds: usize) -> String { + let delimiter = format!("\\{}", "#".repeat(pounds)); + let mut result = String::with_capacity(raw.len()); + let mut rest = raw; + while let Some(c) = rest.chars().next() { + if let Some(escape) = rest.strip_prefix(delimiter.as_str()) + && let Some((value, len)) = interpret_escape(escape) + { + result.push_str(&value); + rest = &escape[len..]; + continue; + } else if c == '\r' { + result.push('\n'); + let after = &rest[1..]; + rest = after.strip_prefix('\n').unwrap_or(after); + continue; + } + result.push(c); + rest = &rest[c.len_utf8()..]; + } + result +} + +/// Interprets the escape sequence at the start of `text` (just after the escape +/// delimiter), returning its value and the number of bytes consumed. +fn interpret_escape(text: &str) -> Option<(String, usize)> { + let simple = match text.chars().next()? { + '0' => '\0', + '\\' => '\\', + 't' => '\t', + 'n' => '\n', + 'r' => '\r', + '"' => '"', + '\'' => '\'', + 'u' => { + let body = text.strip_prefix("u{")?; + let end = body.find('}')?; + let digits = &body[..end]; + if digits.is_empty() || digits.len() > 8 { + return None; + } + let value = char::from_u32(u32::from_str_radix(digits, 16).ok()?)?; + return Some((value.to_string(), "u{".len() + end + 1)); + } + _ => return None, + }; + Some((simple.to_string(), 1)) +} + fn implicit_parameterless_initializer( ctx: &mut yeast::build::BuildCtx<'_, SwiftContext>, members: &[yeast::OutputId], @@ -413,25 +490,32 @@ fn translation_rules() -> Vec> { rule!((nilLiteralExpr) @node => expr { tree!((builtin_expr #{node})) }), - rule!((simpleStringLiteralExpr) @node => expr { - make_string_literal(&mut ctx, node) + rule!((simpleStringLiteralExpr segments: _* @segments) @node => expr { + make_string_literal(&mut ctx, node, &segments, 0) }), - // String literal with a single constant segment (for some reason not typed as simpleStringLiteralExpr) + // A string literal without interpolations (including multi-line and + // raw literals, whose content swift-syntax may split into several + // segments) becomes a single string literal. rule!( - (stringLiteralExpr segments: (stringSegment) segments: _* @rest) @node - where rest.is_empty() + (stringLiteralExpr openingPounds: _? @pounds segments: _* @segments) @node + where all_string_segments(ast, &segments) => expr { - make_string_literal(&mut ctx, node) + let pounds = pound_count(&ctx, pounds); + make_string_literal(&mut ctx, node, &segments, pounds) } ), rule!( - (stringLiteralExpr segments: _* @segments) + (stringLiteralExpr openingPounds: _? @pounds segments: _* @segments) => - (string_interpolation_expr element: {segments}) + (string_interpolation_expr element: { + ctx.string_pounds = pound_count(&ctx, pounds); + segments + }) ), - rule!((stringSegment content: @content) => expr { - make_string_literal(&mut ctx, content) + rule!((stringSegment) @segment => expr { + let pounds = ctx.string_pounds; + make_string_literal(&mut ctx, segment, &[segment], pounds) }), rule!( (expressionSegment expressions: _* @expressions) @@ -2113,3 +2197,38 @@ pub fn language_spec(desugared_ast_schema: &'static str) -> desugaring::Language .build() .expect("failed to build Swift desugarer") } + +#[cfg(test)] +mod tests { + use super::interpret_string_segment; + + #[test] + fn interprets_escape_sequences() { + assert_eq!( + interpret_string_segment(r#"a\tb\n\r\"\'\\\0\u{41}\u{1F600}"#, 0), + "a\tb\n\r\"'\\\0A\u{1F600}" + ); + } + + #[test] + fn keeps_malformed_escapes() { + assert_eq!( + interpret_string_segment(r"\q\u{}\u{110000}\u{41", 0), + r"\q\u{}\u{110000}\u{41" + ); + } + + #[test] + fn interprets_raw_string_escapes() { + assert_eq!( + interpret_string_segment(r"\n \#n \#t \##n \#u{41}", 1), + "\\n \n \t \\##n A" + ); + assert_eq!(interpret_string_segment(r"\#n \##n", 2), "\\#n \n"); + } + + #[test] + fn normalises_line_endings() { + assert_eq!(interpret_string_segment("a\r\nb\rc\n", 0), "a\nb\nc\n"); + } +} diff --git a/unified/extractor/tests/corpus/swift/literals/string-literal-kinds.output b/unified/extractor/tests/corpus/swift/literals/string-literal-kinds.output new file mode 100644 index 000000000000..cf238ced3372 --- /dev/null +++ b/unified/extractor/tests/corpus/swift/literals/string-literal-kinds.output @@ -0,0 +1,225 @@ +// Escape sequences +"tab\there \"quoted\" \\ \u{1F600} \0 \'" + +// Raw string +#"raw \n "quoted" \#n \#(x)"# + +// Multi-line string +let s = """ + first line + indented "quote" + continued \ + line \(x) end + escaped \""" + """ + +// Raw multi-line string +##""" + raw \(x) \##(y) + done + """## + +// Multi-line string without interpolation +""" + one + two \t + three \ + four + """ + +// Raw string without interpolation +#"no \(interpolation) here \#t"# + +// Empty strings +"" +""" +""" + +--- + +sourceFile + endOfFileToken: endOfFile + statements: + codeBlockItem + item: + stringLiteralExpr + closingQuote: " + openingQuote: " + segments: + stringSegment + content: stringSegment "tab\\there \\\"quoted\\\" \\\\ \\u{1F600} \\0 \\'" + codeBlockItem + item: + stringLiteralExpr + closingPounds: rawStringPoundDelimiter "#" + openingPounds: rawStringPoundDelimiter "#" + closingQuote: " + openingQuote: " + segments: + stringSegment + content: stringSegment "raw \\n \"quoted\" \\#n" + stringSegment + content: stringSegment " " + expressionSegment + leftParen: ( + rightParen: ) + backslash: \ + expressions: + labeledExpr + expression: + declReferenceExpr + baseName: identifier "x" + pounds: rawStringPoundDelimiter "#" + stringSegment + content: stringSegment + codeBlockItem + item: + variableDecl + attributes: + modifiers: + bindingSpecifier: let + bindings: + patternBinding + initializer: + initializerClause + equal: = + value: + stringLiteralExpr + closingQuote: """ + openingQuote: """ + segments: + stringSegment + content: stringSegment "first line\n" + stringSegment + content: stringSegment " indented \"quote\"\n" + stringSegment + content: stringSegment "continued " + stringSegment + content: stringSegment "line " + expressionSegment + leftParen: ( + rightParen: ) + backslash: \ + expressions: + labeledExpr + expression: + declReferenceExpr + baseName: identifier "x" + stringSegment + content: stringSegment " end\n" + stringSegment + content: stringSegment "escaped \\\"\"\"" + pattern: + identifierPattern + identifier: identifier "s" + codeBlockItem + item: + stringLiteralExpr + closingPounds: rawStringPoundDelimiter "##" + openingPounds: rawStringPoundDelimiter "##" + closingQuote: """ + openingQuote: """ + segments: + stringSegment + content: stringSegment "raw \\(x) " + expressionSegment + leftParen: ( + rightParen: ) + backslash: \ + expressions: + labeledExpr + expression: + declReferenceExpr + baseName: identifier "y" + pounds: rawStringPoundDelimiter "##" + stringSegment + content: stringSegment "\n" + stringSegment + content: stringSegment "done" + codeBlockItem + item: + stringLiteralExpr + closingQuote: """ + openingQuote: """ + segments: + stringSegment + content: stringSegment "one\n" + stringSegment + content: stringSegment " two \\t\n" + stringSegment + content: stringSegment "three " + stringSegment + content: stringSegment "four" + codeBlockItem + item: + stringLiteralExpr + closingPounds: rawStringPoundDelimiter "#" + openingPounds: rawStringPoundDelimiter "#" + closingQuote: " + openingQuote: " + segments: + stringSegment + content: stringSegment "no \\(interpolation) here \\#t" + codeBlockItem + item: + stringLiteralExpr + closingQuote: " + openingQuote: " + segments: + stringSegment + content: stringSegment + codeBlockItem + item: + stringLiteralExpr + closingQuote: """ + openingQuote: """ + segments: + +--- + +top_level source="⟨body⟩" + body: + block source="⟨stmt⟩\n\n// Raw string\n⟨stmt⟩\n\n// Multi-line string\n⟨stmt⟩\n\n// Raw multi-line string\n⟨stmt⟩\n\n// Multi-line string without interpolation\n⟨stmt⟩\n\n// Raw string without interpolation\n⟨stmt⟩\n\n// Empty strings\n⟨stmt⟩\n⟨stmt⟩" + stmt: + string_literal "\"tab\\there \\\"quoted\\\" \\\\ \\u{1F600} \\0 \\'\"" source="\"tab\\there \\\"quoted\\\" \\\\ \\u{1F600} \\0 \\'\"" + string_interpolation_expr source="#\"⟨element⟩⟨element⟩⟨element⟩\"#" + element: + string_literal "raw \\n \"quoted\" \\#n" source="raw \\n \"quoted\" \\#n" + string_literal " " source=" " + call_expr source="\\#(⟨argument⟩)" + callee: builtin_expr "interpolation" source="" + argument: + argument source="⟨value⟩" + value: identifier "x" source="x" + string_literal source="" + variable_declaration source="⟨modifier⟩ ⟨pattern⟩ = ⟨value⟩" + modifier: modifier "let" source="let" + pattern: identifier "s" source="s" + value: + string_interpolation_expr source="\"\"\"\n ⟨element⟩ ⟨element⟩ ⟨element⟩\\\n ⟨element⟩⟨element⟩⟨element⟩ ⟨element⟩\n \"\"\"" + element: + string_literal "first line\n" source="first line\n" + string_literal " indented \"quote\"\n" source=" indented \"quote\"\n" + string_literal "continued " source="continued " + string_literal "line " source="line " + call_expr source="\\(⟨argument⟩)" + callee: builtin_expr "interpolation" source="" + argument: + argument source="⟨value⟩" + value: identifier "x" source="x" + string_literal " end\n" source=" end\n" + string_literal "escaped \\\"\"\"" source="escaped \\\"\"\"" + string_interpolation_expr source="##\"\"\"\n ⟨element⟩⟨element⟩⟨element⟩ ⟨element⟩\n \"\"\"##" + element: + string_literal "raw \\(x) " source="raw \\(x) " + call_expr source="\\##(⟨argument⟩)" + callee: builtin_expr "interpolation" source="" + argument: + argument source="⟨value⟩" + value: identifier "y" source="y" + string_literal "\n" source="\n" + string_literal "done" source="done" + string_literal "\"\"\"\n one\n two \\t\n three \\\n four\n \"\"\"" source="\"\"\"\n one\n two \\t\n three \\\n four\n \"\"\"" + string_literal "#\"no \\(interpolation) here \\#t\"#" source="#\"no \\(interpolation) here \\#t\"#" + string_literal "\"\"" source="\"\"" + string_literal "\"\"\"\n\"\"\"" source="\"\"\"\n\"\"\"" diff --git a/unified/extractor/tests/corpus/swift/literals/string-literal-kinds.swift b/unified/extractor/tests/corpus/swift/literals/string-literal-kinds.swift new file mode 100644 index 000000000000..04a616648c80 --- /dev/null +++ b/unified/extractor/tests/corpus/swift/literals/string-literal-kinds.swift @@ -0,0 +1,36 @@ +// Escape sequences +"tab\there \"quoted\" \\ \u{1F600} \0 \'" + +// Raw string +#"raw \n "quoted" \#n \#(x)"# + +// Multi-line string +let s = """ + first line + indented "quote" + continued \ + line \(x) end + escaped \""" + """ + +// Raw multi-line string +##""" + raw \(x) \##(y) + done + """## + +// Multi-line string without interpolation +""" + one + two \t + three \ + four + """ + +// Raw string without interpolation +#"no \(interpolation) here \#t"# + +// Empty strings +"" +""" +""" diff --git a/unified/ql/test/library-tests/BasicTest/strings.swift b/unified/ql/test/library-tests/BasicTest/strings.swift index 0015521eae05..3a994f0f5f25 100644 --- a/unified/ql/test/library-tests/BasicTest/strings.swift +++ b/unified/ql/test/library-tests/BasicTest/strings.swift @@ -2,3 +2,13 @@ let x1 = "hello" let x2 = "hello \(123) world" let x3 = "hello \(arg: 123) world" let x4 = "hello \(1, 2, 3) world" +let x5 = "tab\t \"quoted\" \\ \u{41}\u{1F600} \0" +let x6 = #"raw \n "quoted" \#t"# +let x7 = """ + first + second \ + third + """ +let x8 = ##""" + raw \(x) \##(x) \#n \##n + """## diff --git a/unified/ql/test/library-tests/BasicTest/test.expected b/unified/ql/test/library-tests/BasicTest/test.expected index a512eea0164b..47c8c695748b 100644 --- a/unified/ql/test/library-tests/BasicTest/test.expected +++ b/unified/ql/test/library-tests/BasicTest/test.expected @@ -6,6 +6,11 @@ identifier | strings.swift:3:5:3:6 | x3 | x3 | | strings.swift:3:19:3:21 | arg | arg | | strings.swift:4:5:4:6 | x4 | x4 | +| strings.swift:5:5:5:6 | x5 | x5 | +| strings.swift:6:5:6:6 | x6 | x6 | +| strings.swift:7:5:7:6 | x7 | x7 | +| strings.swift:12:5:12:6 | x8 | x8 | +| strings.swift:13:16:13:16 | x | x | | test.swift:1:8:1:17 | Foundation | Foundation | | test.swift:1:8:1:17 | Foundation | Foundation | | test.swift:4:8:4:16 | Container | Container | @@ -172,6 +177,12 @@ rawStringValue | strings.swift:3:28:3:33 | world | world | | strings.swift:4:11:4:16 | hello | hello | | strings.swift:4:27:4:32 | world | world | +| strings.swift:5:10:5:49 | "tab\\t \\"quoted\\" \\\\ \\u{41}\\u{1F600} \\0" | "tab\\t \\"quoted\\" \\\\ \\u{41}\\u{1F600} \\0" | +| strings.swift:6:10:6:32 | #"raw \\n "quoted" \\#t"# | #"raw \\n "quoted" \\#t"# | +| strings.swift:7:10:11:7 | """\n first\n second \\\n third\n """ | """\n first\n second \\\n third\n """ | +| strings.swift:13:3:13:11 | raw \\(x) | raw \\(x) | +| strings.swift:13:18:13:26 | \\#n \\##n | \\#n \\##n | +| strings.swift:13:27:13:26 | | | | test.swift:90:17:90:23 | "hello" | "hello" | | test.swift:91:15:91:29 | "parenthesized" | "parenthesized" | | test.swift:92:16:92:37 | "double-parenthesized" | "double-parenthesized" | @@ -183,6 +194,12 @@ exprStringValue | strings.swift:3:28:3:33 | world | world | | strings.swift:4:11:4:16 | hello | hello | | strings.swift:4:27:4:32 | world | world | +| strings.swift:5:10:5:49 | "tab\\t \\"quoted\\" \\\\ \\u{41}\\u{1F600} \\0" | tab\t "quoted" \\ A\ud83d\ude00 \u0000 | +| strings.swift:6:10:6:32 | #"raw \\n "quoted" \\#t"# | raw \\n "quoted" \t | +| strings.swift:7:10:11:7 | """\n first\n second \\\n third\n """ | first\n second third | +| strings.swift:13:3:13:11 | raw \\(x) | raw \\(x) | +| strings.swift:13:18:13:26 | \\#n \\##n | \\#n \n | +| strings.swift:13:27:13:26 | | | | test.swift:90:17:90:23 | "hello" | hello | | test.swift:91:15:91:29 | "parenthesized" | parenthesized | | test.swift:92:16:92:37 | "double-parenthesized" | double-parenthesized | From 6442712cf88d6fc35a1b273baaa9772cecaa249d Mon Sep 17 00:00:00 2001 From: Asger F Date: Thu, 3 Dec 2026 14:47:45 +0100 Subject: [PATCH 2/2] Unified: Bound Swift Unicode escape parsing Limit Unicode escape parsing to a closing brace within the maximum valid escape length, and reject non-hex digits such as a leading plus. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- unified/extractor/src/languages/swift/swift.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/unified/extractor/src/languages/swift/swift.rs b/unified/extractor/src/languages/swift/swift.rs index 9a8e44af65ea..b6616fe23877 100644 --- a/unified/extractor/src/languages/swift/swift.rs +++ b/unified/extractor/src/languages/swift/swift.rs @@ -202,9 +202,12 @@ fn interpret_escape(text: &str) -> Option<(String, usize)> { '\'' => '\'', 'u' => { let body = text.strip_prefix("u{")?; - let end = body.find('}')?; + let end = body.as_bytes().iter().take(9).position(|&b| b == b'}')?; let digits = &body[..end]; - if digits.is_empty() || digits.len() > 8 { + if digits.is_empty() + || digits.len() > 8 + || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) + { return None; } let value = char::from_u32(u32::from_str_radix(digits, 16).ok()?)?; @@ -2213,11 +2216,17 @@ mod tests { #[test] fn keeps_malformed_escapes() { assert_eq!( - interpret_string_segment(r"\q\u{}\u{110000}\u{41", 0), - r"\q\u{}\u{110000}\u{41" + interpret_string_segment(r"\q\u{}\u{+41}\u{110000}\u{41", 0), + r"\q\u{}\u{+41}\u{110000}\u{41" ); } + #[test] + fn handles_many_unclosed_unicode_escapes() { + let malformed = r"\u{".repeat(10_000); + assert_eq!(interpret_string_segment(&malformed, 0), malformed); + } + #[test] fn interprets_raw_string_escapes() { assert_eq!(