rune/ast/
lit_str.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use crate::alloc::borrow::Cow;
use crate::ast::prelude::*;

#[test]
#[cfg(not(miri))]
fn ast_parse() {
    rt::<ast::LitStr>("\"hello world\"");
    rt::<ast::LitStr>("\"hello\\nworld\"");
}

/// A string literal.
///
/// * `"Hello World"`.
/// * `"Hello\nWorld"`.
#[derive(Debug, TryClone, Clone, Copy, PartialEq, Eq, Spanned)]
#[try_clone(copy)]
#[non_exhaustive]
pub struct LitStr {
    /// The span corresponding to the literal.
    pub span: Span,
    /// The source of the literal string.
    #[rune(skip)]
    pub source: ast::StrSource,
}

impl LitStr {
    /// Resolve a template string.
    pub(crate) fn resolve_template_string<'a>(
        &self,
        cx: ResolveContext<'a>,
    ) -> Result<Cow<'a, str>> {
        self.resolve_inner(cx, ast::unescape::WithTemplate(true))
    }

    /// Resolve as a regular string.
    pub(crate) fn resolve_string<'a>(&self, cx: ResolveContext<'a>) -> Result<Cow<'a, str>> {
        self.resolve_inner(cx, ast::unescape::WithTemplate(false))
    }

    /// Resolve the given string with the specified configuration.
    fn resolve_inner<'a>(
        &self,
        cx: ResolveContext<'a>,
        with_template: ast::unescape::WithTemplate,
    ) -> Result<Cow<'a, str>> {
        let span = self.span;

        let text = match self.source {
            ast::StrSource::Text(text) => text,
            ast::StrSource::Synthetic(id) => {
                let bytes = cx.storage.get_string(id).ok_or_else(|| {
                    compile::Error::new(
                        span,
                        ErrorKind::BadSyntheticId {
                            kind: SyntheticKind::String,
                            id,
                        },
                    )
                })?;

                return Ok(Cow::Borrowed(bytes));
            }
        };

        let span = if text.wrapped {
            span.narrow(1u32)
        } else {
            span
        };

        let string = cx
            .sources
            .source(text.source_id, span)
            .ok_or_else(|| compile::Error::new(span, ErrorKind::BadSlice))?;

        Ok(if text.escaped {
            Cow::Owned(Self::parse_escaped(span, string, with_template)?)
        } else {
            Cow::Borrowed(string)
        })
    }

    fn parse_escaped(
        span: Span,
        source: &str,
        with_template: ast::unescape::WithTemplate,
    ) -> Result<String> {
        let mut buffer = String::try_with_capacity(source.len())?;

        let start = span.start.into_usize();

        let mut it = source
            .char_indices()
            .map(|(n, c)| (start + n, c))
            .peekable();

        while let Some((start, c)) = it.next() {
            buffer.try_extend(match c {
                '\\' => match ast::unescape::parse_char_escape(
                    &mut it,
                    with_template,
                    ast::unescape::WithLineCont(true),
                ) {
                    Ok(c) => c,
                    Err(kind) => {
                        let end = it
                            .next()
                            .map(|n| n.0)
                            .unwrap_or_else(|| span.end.into_usize());
                        return Err(compile::Error::new(Span::new(start, end), kind));
                    }
                },
                c => Some(c),
            })?;
        }

        Ok(buffer)
    }
}

impl ToAst for LitStr {
    fn to_ast(span: Span, kind: ast::Kind) -> Result<Self> {
        match kind {
            K![str(source)] => Ok(Self { span, source }),
            _ => Err(compile::Error::expected(
                ast::Token { span, kind },
                Self::into_expectation(),
            )),
        }
    }

    #[inline]
    fn matches(kind: &ast::Kind) -> bool {
        matches!(kind, K![str])
    }

    #[inline]
    fn into_expectation() -> Expectation {
        Expectation::Description("a string literal")
    }
}

impl Parse for LitStr {
    fn parse(parser: &mut Parser<'_>) -> Result<Self> {
        let t = parser.next()?;
        LitStr::to_ast(t.span, t.kind)
    }
}

impl<'a> Resolve<'a> for LitStr {
    type Output = Cow<'a, str>;

    fn resolve(&self, cx: ResolveContext<'a>) -> Result<Cow<'a, str>> {
        self.resolve_string(cx)
    }
}

impl ToTokens for LitStr {
    fn to_tokens(
        &self,
        _: &mut MacroContext<'_, '_, '_>,
        stream: &mut TokenStream,
    ) -> alloc::Result<()> {
        stream.push(ast::Token {
            span: self.span,
            kind: ast::Kind::Str(self.source),
        })
    }
}