Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 146 additions & 18 deletions unified/extractor/src/languages/swift/swift.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ struct SwiftContext {
/// name has no argument label. It is cleared when translating accessor
/// bodies.
subscript: Option<SubscriptContext>,
/// 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<RefCell<Vec<(yeast::OutputId, String)>>>,
}
Expand Down Expand Up @@ -121,23 +125,99 @@ 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<yeast::Id>) -> 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.as_bytes().iter().take(9).position(|&b| b == b'}')?;
let digits = &body[..end];
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()?)?;
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],
Expand Down Expand Up @@ -413,25 +493,32 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
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)
Expand Down Expand Up @@ -2113,3 +2200,44 @@ 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{+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!(
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");
}
}
Loading
Loading