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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use crate::kinds::SyntaxKind::*;
use rowan::{ast::AstNode as OtherAstNode, NodeOrToken};

use crate::ast;

use super::{support::children_tokens_u, AstToken, InterpolPart, StrContent};

impl ast::Str {
    pub fn parts(&self) -> impl Iterator<Item = InterpolPart<StrContent>> {
        self.syntax().children_with_tokens().filter_map(|child| match child {
            NodeOrToken::Token(token) if token.kind() == TOKEN_STRING_CONTENT => {
                Some(InterpolPart::Literal(StrContent::cast(token).unwrap()))
            }
            NodeOrToken::Token(token) => {
                assert!(token.kind() == TOKEN_STRING_START || token.kind() == TOKEN_STRING_END);
                None
            }
            NodeOrToken::Node(node) => {
                assert_eq!(node.kind(), NODE_INTERPOL);
                Some(InterpolPart::Interpolation(ast::Interpol::cast(node.clone()).unwrap()))
            }
        })
    }

    pub fn normalized_parts(&self) -> Vec<InterpolPart<String>> {
        let multiline = children_tokens_u(self).next().map_or(false, |t| t.text() == "''");
        let mut is_first_literal = true;
        let mut at_start_of_line = true;
        let mut min_indent = 1000000;
        let mut cur_indent = 0;
        let mut n = 0;
        let mut first_is_literal = false;

        let parts: Vec<InterpolPart<StrContent>> = self.parts().collect();

        if multiline {
            for part in &parts {
                match part {
                    InterpolPart::Interpolation(_) => {
                        if at_start_of_line {
                            at_start_of_line = false;
                            min_indent = min_indent.min(cur_indent);
                        }
                        n += 1;
                    }
                    InterpolPart::Literal(literal) => {
                        let mut token_text = literal.syntax().text();

                        if n == 0 {
                            first_is_literal = true;
                        }

                        if is_first_literal && first_is_literal {
                            is_first_literal = false;
                            if let Some(p) = token_text.find('\n') {
                                if token_text[0..p].chars().all(|c| c == ' ') {
                                    token_text = &token_text[p + 1..]
                                }
                            }
                        }

                        for c in token_text.chars() {
                            if at_start_of_line {
                                if c == ' ' {
                                    cur_indent += 1;
                                } else if c == '\n' {
                                    cur_indent = 0;
                                } else {
                                    at_start_of_line = false;
                                    min_indent = min_indent.min(cur_indent);
                                }
                            } else if c == '\n' {
                                at_start_of_line = true;
                                cur_indent = 0;
                            }
                        }

                        n += 1;
                    }
                }
            }
        }

        let mut normalized_parts = Vec::new();
        let mut cur_dropped = 0;
        let mut i = 0;
        is_first_literal = true;
        at_start_of_line = true;

        for part in parts {
            match part {
                InterpolPart::Interpolation(interpol) => {
                    at_start_of_line = false;
                    cur_dropped = 0;
                    normalized_parts.push(InterpolPart::Interpolation(interpol));
                    i += 1;
                }
                InterpolPart::Literal(literal) => {
                    let mut token_text = literal.syntax().text();

                    if multiline {
                        if is_first_literal && first_is_literal {
                            is_first_literal = false;
                            if let Some(p) = token_text.find('\n') {
                                if token_text[0..p].chars().all(|c| c == ' ') {
                                    token_text = &token_text[p + 1..];
                                    if token_text.is_empty() {
                                        i += 1;
                                        continue;
                                    }
                                }
                            }
                        }

                        let mut str = String::new();
                        for c in token_text.chars() {
                            if at_start_of_line {
                                if c == ' ' {
                                    if cur_dropped >= min_indent {
                                        str.push(c);
                                    }
                                    cur_dropped += 1;
                                } else if c == '\n' {
                                    cur_dropped = 0;
                                    str.push(c);
                                } else {
                                    at_start_of_line = false;
                                    cur_dropped = 0;
                                    str.push(c);
                                }
                            } else {
                                str.push(c);
                                if c == '\n' {
                                    at_start_of_line = true;
                                }
                            }
                        }

                        if i == n - 1 {
                            if let Some(p) = str.rfind('\n') {
                                if str[p + 1..].chars().all(|c| c == ' ') {
                                    str.truncate(p + 1);
                                }
                            }
                        }

                        normalized_parts.push(InterpolPart::Literal(unescape(&str, multiline)));
                        i += 1;
                    } else {
                        normalized_parts
                            .push(InterpolPart::Literal(unescape(token_text, multiline)));
                    }
                }
            }
        }

        normalized_parts
    }
}

/// Interpret escape sequences in the nix string and return the converted value
pub fn unescape(input: &str, multiline: bool) -> String {
    let mut output = String::new();
    let mut input = input.chars().peekable();
    loop {
        match input.next() {
            None => break,
            Some('"') if !multiline => break,
            Some('\\') if !multiline => match input.next() {
                None => break,
                Some('n') => output.push('\n'),
                Some('r') => output.push('\r'),
                Some('t') => output.push('\t'),
                Some(c) => output.push(c),
            },
            Some('\'') if multiline => match input.next() {
                None => {
                    output.push('\'');
                }
                Some('\'') => match input.peek() {
                    Some('\'') => {
                        input.next().unwrap();
                        output.push_str("''");
                    }
                    Some('$') => {
                        input.next().unwrap();
                        output.push('$');
                    }
                    Some('\\') => {
                        input.next().unwrap();
                        match input.next() {
                            None => break,
                            Some('n') => output.push('\n'),
                            Some('r') => output.push('\r'),
                            Some('t') => output.push('\t'),
                            Some(c) => output.push(c),
                        }
                    }
                    _ => break,
                },
                Some(c) => {
                    output.push('\'');
                    output.push(c);
                }
            },
            Some(c) => output.push(c),
        }
    }
    output
}

#[cfg(test)]
mod tests {
    use crate::Root;

    use super::*;

    #[test]
    fn string_unescapes() {
        assert_eq!(unescape(r#"Hello\n\"World\" :D"#, false), "Hello\n\"World\" :D");
        assert_eq!(unescape(r#"\"Hello\""#, false), "\"Hello\"");

        assert_eq!(unescape(r#"Hello''\n'''World''' :D"#, true), "Hello\n''World'' :D");
        assert_eq!(unescape(r#""Hello""#, true), "\"Hello\"");
    }
    #[test]
    fn parts_leading_ws() {
        let inp = "''\n  hello\n  world''";
        let expr = Root::parse(inp).ok().unwrap().expr().unwrap();
        match expr {
            ast::Expr::Str(str) => {
                assert_eq!(
                    str.normalized_parts(),
                    vec![InterpolPart::Literal("hello\nworld".to_string())]
                )
            }
            _ => unreachable!(),
        }
    }
    #[test]
    fn parts_trailing_ws_single_line() {
        let inp = "''hello ''";
        let expr = Root::parse(inp).ok().unwrap().expr().unwrap();
        match expr {
            ast::Expr::Str(str) => {
                assert_eq!(
                    str.normalized_parts(),
                    vec![InterpolPart::Literal("hello ".to_string())]
                )
            }
            _ => unreachable!(),
        }
    }
    #[test]
    fn parts_trailing_ws_multiline() {
        let inp = "''hello\n ''";
        let expr = Root::parse(inp).ok().unwrap().expr().unwrap();
        match expr {
            ast::Expr::Str(str) => {
                assert_eq!(
                    str.normalized_parts(),
                    vec![InterpolPart::Literal("hello\n".to_string())]
                )
            }
            _ => unreachable!(),
        }
    }
    #[test]
    fn parts() {
        use crate::{NixLanguage, SyntaxNode};
        use rowan::{GreenNodeBuilder, Language};

        fn string_node(content: &str) -> ast::Str {
            let mut builder = GreenNodeBuilder::new();
            builder.start_node(NixLanguage::kind_to_raw(NODE_STRING));
            builder.token(NixLanguage::kind_to_raw(TOKEN_STRING_START), "''");
            builder.token(NixLanguage::kind_to_raw(TOKEN_STRING_CONTENT), content);
            builder.token(NixLanguage::kind_to_raw(TOKEN_STRING_END), "''");
            builder.finish_node();

            ast::Str::cast(SyntaxNode::new_root(builder.finish())).unwrap()
        }

        let txtin = r#"
                        |trailing-whitespace
                              |trailing-whitespace
                    This is a multiline string :D
                      indented by two
                    \'\'\'\'\
                    ''${ interpolation was escaped }
                    two single quotes: '''
                    three single quotes: ''''
                "#
        .replace("|trailing-whitespace", "");

        if let [InterpolPart::Literal(lit)] =
            &ast::Str::normalized_parts(&string_node(txtin.as_str()))[..]
        {
            assert_eq!(lit,
                // Get the below with nix repl
                "    \n          \nThis is a multiline string :D\n  indented by two\n\\'\\'\\'\\'\\\n${ interpolation was escaped }\ntwo single quotes: ''\nthree single quotes: '''\n"
            );
        } else {
            unreachable!();
        }
    }

    #[test]
    fn parts_ast() {
        fn assert_eq_ast_ctn(it: &mut dyn Iterator<Item = InterpolPart<String>>, x: &str) {
            let tmp = it.next().expect("unexpected EOF");
            if let InterpolPart::Interpolation(astn) = tmp {
                assert_eq!(astn.expr().unwrap().syntax().to_string(), x);
            } else {
                unreachable!("unexpected literal {:?}", tmp);
            }
        }

        let inp = r#"''

        This version of Nixpkgs requires Nix >= ${requiredVersion}, please upgrade:

        - If you are running NixOS, `nixos-rebuild' can be used to upgrade your system.

        - Alternatively, with Nix > 2.0 `nix upgrade-nix' can be used to imperatively
          upgrade Nix. You may use `nix-env --version' to check which version you have.

        - If you installed Nix using the install script (https://nixos.org/nix/install),
          it is safe to upgrade by running it again:

              curl -L https://nixos.org/nix/install | sh

        For more information, please see the NixOS release notes at
        https://nixos.org/nixos/manual or locally at
        ${toString ./nixos/doc/manual/release-notes}.

        If you need further help, see https://nixos.org/nixos/support.html
      ''"#;
        let expr = Root::parse(inp).ok().unwrap().expr().unwrap();
        match expr {
            ast::Expr::Str(s) => {
                let mut it = s.normalized_parts().into_iter();
                assert_eq!(
                    it.next().unwrap(),
                    InterpolPart::Literal("\nThis version of Nixpkgs requires Nix >= ".to_string())
                );
                assert_eq_ast_ctn(&mut it, "requiredVersion");
                assert_eq!(it.next().unwrap(), InterpolPart::Literal(
                        ", please upgrade:\n\n- If you are running NixOS, `nixos-rebuild' can be used to upgrade your system.\n\n- Alternatively, with Nix > 2.0 `nix upgrade-nix' can be used to imperatively\n  upgrade Nix. You may use `nix-env --version' to check which version you have.\n\n- If you installed Nix using the install script (https://nixos.org/nix/install),\n  it is safe to upgrade by running it again:\n\n      curl -L https://nixos.org/nix/install | sh\n\nFor more information, please see the NixOS release notes at\nhttps://nixos.org/nixos/manual or locally at\n".to_string()
                    ));
                assert_eq_ast_ctn(&mut it, "toString ./nixos/doc/manual/release-notes");
                assert_eq!(
                    it.next().unwrap(),
                    InterpolPart::Literal(
                        ".\n\nIf you need further help, see https://nixos.org/nixos/support.html\n"
                            .to_string()
                    )
                );
            }
            _ => unreachable!(),
        }
    }
}