rlang 0.1.11

R as a fusevm frontend: a lexer, parser, and compiler to fusevm bytecode on an RHost vector heap, with no bespoke VM or JIT
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! R's `deparse` for the rlang AST — a port of GNU R's `src/main/deparse.c`
//! (`deparse2buff`, `args2buff`, `print2buff`, `writeline`, `linebreak`).
//!
//! This is what `print(f)`, `deparse(f)` and `format(f)` show for a closure.
//! `Rscript` runs with `keep.source = FALSE`, so R does *not* echo the original
//! text: it re-renders the parse tree under its own layout rules, which is why
//! the output is `function (x, y = 2) ` on its own line, four-space block
//! indentation, and an `if` inside `{ }` broken across three lines. Those rules
//! are reproduced here exactly rather than approximated, because a closure's
//! printed form is compared byte-for-byte against the reference in the parity
//! corpus.
//!
//! The layout state that drives it, straight from `LocalParseData`:
//!
//! - `indent` — printed lazily at the first text on a line, four spaces per
//!   level for the first four, then two, then one (R's `printtab2buff`).
//! - `incurly` — inside a `{ }`, an `if` puts its branches on their own lines;
//!   outside one it stays on a single line. This is the whole reason
//!   `function(a, b) if (a > b) a else b` deparses to one line while the same
//!   `if` wrapped in braces deparses to three.
//! - `len` / `cutoff` — the running line length against `width.cutoff = 60`.
//!   Binary operators and argument lists break there and indent the
//!   continuation one extra level.
//!
//! Parentheses the source wrote are *preserved*: `Expr::Paren` keeps the `(`
//! exactly as R keeps a `(` call in its parse tree. A tree built at run time
//! (`bquote`, `substitute`) can nest a looser operator under a tighter one with
//! no `(` at all, and for that the deparser carries R's precedence table and
//! `needsparens` rule, which add the parentheses R prints. For parsed source
//! they never fire.

use crate::ast::{Arg, BinOp, Expr, IndexKind, NaKind, Param, UnOp};
use crate::host::{fixed_decimals, render_fixed, render_sci, sci_decimals};

/// R's `width.cutoff` default for `deparse`.
pub(crate) const CUTOFF: usize = 60;

/// The deparse buffer: R's `LocalParseData`, minus the options rlang has no
/// use for.
pub(crate) struct Deparser {
    lines: Vec<String>,
    buf: String,
    /// Bytes on the current line, indentation included — R counts `strlen`.
    len: usize,
    indent: usize,
    startline: bool,
    incurly: usize,
    /// `width.cutoff`: the line length past which a wrap point breaks.
    cutoff: usize,
}

impl Deparser {
    pub(crate) fn new() -> Self {
        Self::with_cutoff(CUTOFF)
    }

    pub(crate) fn with_cutoff(cutoff: usize) -> Self {
        Deparser {
            lines: Vec::new(),
            buf: String::new(),
            len: 0,
            indent: 0,
            startline: true,
            incurly: 0,
            cutoff,
        }
    }

    /// `print2buff`: append text, tabbing over first if this is a line's start.
    pub(crate) fn print(&mut self, s: &str) {
        if self.startline {
            self.startline = false;
            self.tabs(self.indent);
        }
        self.buf.push_str(s);
        self.len += s.len();
    }

    /// `printtab2buff`: four spaces per level to depth 4, then two, then one.
    fn tabs(&mut self, n: usize) {
        for i in 1..=n {
            self.print(match i {
                1..=4 => "    ",
                5..=6 => "  ",
                _ => " ",
            });
        }
    }

    /// `writeline`: flush the current line (trailing spaces and all — R keeps
    /// them, which is why a deparsed header is `"function (x) "`).
    pub(crate) fn writeline(&mut self) {
        self.lines.push(std::mem::take(&mut self.buf));
        self.len = 0;
        self.startline = true;
    }

    /// `linebreak`: wrap past the cutoff, indenting the continuation once for
    /// the whole operator/argument run.
    pub(crate) fn linebreak(&mut self, lbreak: &mut bool) {
        if self.len > self.cutoff {
            if !*lbreak {
                *lbreak = true;
                self.indent += 1;
            }
            self.writeline();
        }
    }

    /// Close a run that [`Self::linebreak`] may have indented.
    pub(crate) fn end_break(&mut self, lbreak: bool) {
        if lbreak {
            self.indent -= 1;
        }
    }

    /// The wrap an atomic vector's elements take (`vector2buff`): past the
    /// cutoff the line simply ends — the continuation is *not* indented, unlike
    /// the argument and list runs [`Self::linebreak`] wraps.
    pub(crate) fn wrap_vector(&mut self) {
        if self.len > self.cutoff {
            self.writeline();
        }
    }

    pub(crate) fn finish(mut self) -> Vec<String> {
        if !self.startline || !self.buf.is_empty() {
            self.writeline();
        }
        self.lines
    }

    /// `args2buff` with `formals = 1`: a formal prints its default only when it
    /// has one (an unsupplied formal is `R_MissingArg`, printed bare).
    fn formals(&mut self, params: &[Param]) {
        let mut lbreak = false;
        for (i, p) in params.iter().enumerate() {
            self.print(&quote_name(&p.name));
            if let Some(d) = &p.default {
                self.print(" = ");
                self.expr(d);
            }
            if i + 1 < params.len() {
                self.print(", ");
                self.linebreak(&mut lbreak);
            }
        }
        if lbreak {
            self.indent -= 1;
        }
    }

    /// `args2buff` with `formals = 0`: a call-site tag always prints its `=`,
    /// even when the value is empty (`x[i, ]` has neither tag nor value).
    fn args(&mut self, args: &[Arg]) {
        let mut lbreak = false;
        for (i, a) in args.iter().enumerate() {
            if let Some(n) = &a.name {
                self.print(&quote_name(n));
                self.print(" = ");
            }
            if let Some(v) = &a.value {
                self.expr(v);
            }
            if i + 1 < args.len() {
                self.print(", ");
                self.linebreak(&mut lbreak);
            }
        }
        if lbreak {
            self.indent -= 1;
        }
    }

    /// `PP_BINARY`: a space each side, with a wrap point after the operator.
    fn binary(&mut self, lhs: &Expr, op: &str, rhs: &Expr, main: Prec) {
        let mut lbreak = false;
        self.operand(lhs, main, true);
        self.print(" ");
        self.print(op);
        self.print(" ");
        self.linebreak(&mut lbreak);
        self.operand(rhs, main, false);
        if lbreak {
            self.indent -= 1;
        }
    }

    /// `PP_BINARY2`: no space, no wrap point (`x/2`, `x^2`, `1:10`, `x%%3`).
    fn binary2(&mut self, lhs: &Expr, op: &str, rhs: &Expr, main: Prec) {
        self.operand(lhs, main, true);
        self.print(op);
        self.operand(rhs, main, false);
    }

    /// An operand of an operator, parenthesized when `needsparens` says the
    /// tree would not read back as written without them.
    fn operand(&mut self, e: &Expr, main: Prec, left: bool) {
        if needs_parens(main, e, left) {
            self.print("(");
            self.expr(e);
            self.print(")");
        } else {
            self.expr(e);
        }
    }

    pub(crate) fn expr(&mut self, e: &Expr) {
        match e {
            Expr::Num(n) => {
                let s = num_literal(*n);
                self.print(&s)
            }
            Expr::Int(i) => {
                let s = format!("{i}L");
                self.print(&s)
            }
            Expr::Str(s) => {
                let q = format!("\"{}\"", crate::builtins::encode_string(s));
                self.print(&q)
            }
            Expr::Bool(true) => self.print("TRUE"),
            Expr::Bool(false) => self.print("FALSE"),
            Expr::Null => self.print("NULL"),
            Expr::Na(k) => self.print(match k {
                NaKind::Logical => "NA",
                NaKind::Integer => "NA_integer_",
                NaKind::Real => "NA_real_",
                NaKind::Character => "NA_character_",
            }),
            Expr::Inf => self.print("Inf"),
            Expr::NaN => self.print("NaN"),
            Expr::Ident(s) => {
                let q = quote_name(s);
                self.print(&q)
            }
            Expr::Dots => self.print("..."),
            Expr::Break => self.print("break"),
            Expr::Next => self.print("next"),
            Expr::Paren(inner) => {
                self.print("(");
                self.expr(inner);
                self.print(")");
            }
            Expr::Call { fun, args } => {
                self.expr(fun);
                self.print("(");
                self.args(args);
                self.print(")");
            }
            // A nested `function` is language, not a closure: R writes it
            // `function(x) body` — no space after the keyword, and no line
            // break before the body (both of which a top-level closure gets).
            Expr::Function { params, body } => {
                self.print("function(");
                self.formals(params);
                self.print(") ");
                self.expr(body);
            }
            Expr::If { cond, then, els } => {
                self.print("if (");
                self.expr(cond);
                self.print(") ");
                // Inside `{ }` the branches go on their own lines — unless the
                // branch is itself a `{`, which stays on the `if` line (R's
                // `curlyahead`).
                let mut lookahead = false;
                if self.incurly > 0 {
                    lookahead = matches!(then.as_ref(), Expr::Block(_));
                    if !lookahead {
                        self.writeline();
                        self.indent += 1;
                    }
                }
                self.expr(then);
                match els {
                    Some(els) => {
                        if self.incurly > 0 {
                            self.writeline();
                            if !lookahead {
                                self.indent -= 1;
                            }
                        } else {
                            self.print(" ");
                        }
                        self.print("else ");
                        self.expr(els);
                    }
                    None => {
                        if self.incurly > 0 && !lookahead {
                            self.indent -= 1;
                        }
                    }
                }
            }
            Expr::For { var, seq, body } => {
                self.print("for (");
                let v = quote_name(var);
                self.print(&v);
                self.print(" in ");
                self.expr(seq);
                self.print(") ");
                self.expr(body);
            }
            Expr::While { cond, body } => {
                self.print("while (");
                self.expr(cond);
                self.print(") ");
                self.expr(body);
            }
            Expr::Repeat(body) => {
                self.print("repeat ");
                self.expr(body);
            }
            Expr::Block(stmts) => {
                self.print("{");
                self.incurly += 1;
                self.indent += 1;
                self.writeline();
                for s in stmts {
                    self.expr(s);
                    self.writeline();
                }
                self.indent -= 1;
                self.print("}");
                self.incurly -= 1;
            }
            Expr::Assign {
                target,
                value,
                super_assign,
            } => {
                // `PP_ASSIGN`: spaces, but no wrap point.
                self.expr(target);
                self.print(if *super_assign { " <<- " } else { " <- " });
                self.expr(value);
            }
            // `~` with one operand deparses as a prefix operator (`~x`), with
            // two as an infix one (`y ~ x`) — R downgrades `PP_BINARY` to
            // `PP_UNARY` when the call has a single argument.
            Expr::Formula { lhs, rhs } => match lhs {
                Some(l) => self.binary(l, "~", rhs, Prec::left(PREC_TILDE)),
                None => {
                    self.print("~");
                    self.operand(rhs, Prec::left(PREC_TILDE), false);
                }
            },
            Expr::Binary { op, lhs, rhs } => match op {
                // The `PP_BINARY2` operators: `/`, `^` and `:` print tight.
                BinOp::Div => self.binary2(lhs, "/", rhs, Prec::left(PREC_PROD)),
                BinOp::Pow => self.binary2(lhs, "^", rhs, Prec::right(PREC_POWER)),
                BinOp::Colon => self.binary2(lhs, ":", rhs, Prec::left(PREC_COLON)),
                _ => {
                    let name = match op {
                        BinOp::Add => "+",
                        BinOp::Sub => "-",
                        BinOp::Mul => "*",
                        BinOp::Lt => "<",
                        BinOp::Gt => ">",
                        BinOp::Le => "<=",
                        BinOp::Ge => ">=",
                        BinOp::Eq => "==",
                        BinOp::Ne => "!=",
                        BinOp::And => "&",
                        BinOp::Or => "|",
                        BinOp::And2 => "&&",
                        BinOp::Or2 => "||",
                        BinOp::Div | BinOp::Pow | BinOp::Colon => unreachable!(),
                    };
                    self.binary(lhs, name, rhs, Prec::left(binop_prec(op)))
                }
            },
            // `%%` and `%/%` are primitives (`PP_BINARY2`, tight); every other
            // `%op%` is an R-level infix function, which R spaces.
            Expr::Special { name, lhs, rhs } => {
                let op = format!("%{name}%");
                if name.is_empty() || name == "/" {
                    self.binary2(lhs, &op, rhs, Prec::left(PREC_PERCENT))
                } else {
                    self.binary(lhs, &op, rhs, Prec::left(PREC_PERCENT))
                }
            }
            Expr::Unary { op, operand } => {
                self.print(match op {
                    UnOp::Neg => "-",
                    UnOp::Plus => "+",
                    UnOp::Not => "!",
                });
                let main = match op {
                    UnOp::Not => PREC_NOT,
                    UnOp::Neg | UnOp::Plus => PREC_SIGN,
                };
                self.operand(operand, Prec::left(main), false);
            }
            Expr::Index { kind, obj, args } => {
                self.operand(obj, Prec::left(PREC_SUBSET), true);
                match kind {
                    IndexKind::Single => {
                        self.print("[");
                        self.args(args);
                        self.print("]");
                    }
                    IndexKind::Double => {
                        self.print("[[");
                        self.args(args);
                        self.print("]]");
                    }
                    IndexKind::Dollar | IndexKind::At => {
                        self.print(if matches!(kind, IndexKind::Dollar) {
                            "$"
                        } else {
                            "@"
                        });
                        // `a$"b"` normalizes to `a$b` when the tag is a name.
                        for a in args {
                            match a.value.as_ref() {
                                Some(Expr::Str(s)) => {
                                    let q = quote_name(s);
                                    self.print(&q)
                                }
                                Some(v) => self.expr(v),
                                None => {}
                            }
                        }
                    }
                }
            }
        }
    }
}

/// The lines `print`/`deparse`/`format` show for `function(params) body`, in
/// R's `keep.source = FALSE` layout: the header on its own line, then the body.
pub fn deparse_closure(params: &[Param], body: &Expr) -> Vec<String> {
    let mut d = Deparser::new();
    d.print("function (");
    d.formals(params);
    d.print(") ");
    d.writeline();
    d.expr(body);
    d.finish()
}

/// One expression's source text on a single logical line — for callers that
/// want a deparsed *argument* rather than a whole function (`rbind(x, x)`'s
/// seam labels, `table(z)`'s dimension name).
pub fn deparse_expr(e: &Expr) -> String {
    let mut d = Deparser::new();
    d.expr(e);
    d.finish().join("")
}

/// The first line of `e`'s deparse — R's `deparse1s(call)` followed by
/// `STRING_ELT(., 0)`, which is how a condition renders the call it carries.
/// A call whose deparse runs to several lines shows only its first, so
/// `withCallingHandlers({ … }, warning = …)` reports as `withCallingHandlers({`.
pub fn deparse_first_line(e: &Expr) -> String {
    let mut d = Deparser::new();
    d.expr(e);
    d.finish().into_iter().next().unwrap_or_default()
}

/// How R spells a binary operator as a function name — what the head of the
/// call is when `as.list(quote(a + b))` takes it apart.
pub fn binop_symbol(op: &BinOp) -> &'static str {
    match op {
        BinOp::Add => "+",
        BinOp::Sub => "-",
        BinOp::Mul => "*",
        BinOp::Div => "/",
        BinOp::Pow => "^",
        BinOp::Lt => "<",
        BinOp::Gt => ">",
        BinOp::Le => "<=",
        BinOp::Ge => ">=",
        BinOp::Eq => "==",
        BinOp::Ne => "!=",
        BinOp::And => "&",
        BinOp::Or => "|",
        BinOp::And2 => "&&",
        BinOp::Or2 => "||",
        BinOp::Colon => ":",
    }
}

/// `e`'s deparse as separate lines — what `print` on a language object shows
/// and what `deparse()` returns as a character vector.
pub fn deparse_all_lines(e: &Expr) -> Vec<String> {
    let mut d = Deparser::new();
    d.expr(e);
    d.finish()
}

/// `e`'s full deparse, newline-separated — R source that parses back to the
/// same tree. The lines must be *joined by newlines*, not concatenated: R's
/// layout separates the statements inside a `{ }` by line breaks alone, so
/// gluing them together would fuse two statements into one expression.
pub fn deparse_lines(e: &Expr) -> String {
    let mut d = Deparser::new();
    d.expr(e);
    d.finish().join("\n")
}

// R's operator precedences (`PREC_*` in `Defn.h`), lowest binding first —
// only the ones an operand's parenthesization depends on.
const PREC_LEFT: u8 = 2;
const PREC_TILDE: u8 = 4;
const PREC_OR: u8 = 5;
const PREC_AND: u8 = 6;
const PREC_NOT: u8 = 7;
const PREC_COMPARE: u8 = 8;
const PREC_SUM: u8 = 9;
const PREC_PROD: u8 = 10;
const PREC_PERCENT: u8 = 11;
const PREC_COLON: u8 = 12;
const PREC_SIGN: u8 = 13;
const PREC_POWER: u8 = 14;
const PREC_SUBSET: u8 = 15;

/// The `PPinfo` of the operator an operand sits under: its precedence and
/// whether it groups to the right (`^`).
#[derive(Clone, Copy)]
struct Prec {
    prec: u8,
    right_assoc: bool,
}

impl Prec {
    fn left(prec: u8) -> Self {
        Prec {
            prec,
            right_assoc: false,
        }
    }
    fn right(prec: u8) -> Self {
        Prec {
            prec,
            right_assoc: true,
        }
    }
}

fn binop_prec(op: &BinOp) -> u8 {
    match op {
        BinOp::Or | BinOp::Or2 => PREC_OR,
        BinOp::And | BinOp::And2 => PREC_AND,
        BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge | BinOp::Eq | BinOp::Ne => PREC_COMPARE,
        BinOp::Add | BinOp::Sub => PREC_SUM,
        BinOp::Mul | BinOp::Div => PREC_PROD,
        BinOp::Colon => PREC_COLON,
        BinOp::Pow => PREC_POWER,
    }
}

/// `deparse.c`'s `needsparens`: whether operand `arg` of an operator with
/// `main`'s precedence must be parenthesized to read back as the same tree —
/// `left` says which side it is on.
///
/// Source parentheses are kept as `Expr::Paren`, so for parsed code this never
/// fires; it matters for trees built at run time, such as `bquote(.(z) * 2)`
/// with `z` holding `a + b`, which R prints as `(a + b) * 2`.
fn needs_parens(main: Prec, arg: &Expr, left: bool) -> bool {
    let outranks = |p: u8| main.prec > p || (main.prec == p && left == main.right_assoc);
    match arg {
        Expr::Binary { op, .. } => {
            let p = binop_prec(op);
            // `a < b < c` is not legal syntax, so a comparison under one is
            // always wrapped.
            (main.prec == PREC_COMPARE && p == PREC_COMPARE) || outranks(p)
        }
        Expr::Special { .. } => outranks(PREC_PERCENT),
        Expr::Formula { lhs: Some(_), .. } => outranks(PREC_TILDE),
        // A prefix operator never needs parentheses on the right (`b - -a`);
        // on the left a sign binds as `PREC_SIGN`, not as the binary `-`.
        Expr::Formula { lhs: None, .. } => left && outranks(PREC_TILDE),
        Expr::Unary { op, .. } => {
            let p = match op {
                UnOp::Not => PREC_NOT,
                UnOp::Neg | UnOp::Plus => PREC_SIGN,
            };
            left && outranks(p)
        }
        Expr::Assign { .. } => outranks(PREC_LEFT),
        Expr::Index { .. } => outranks(PREC_SUBSET),
        // `(if (p) q) + 1`, but `1 + if (p) q`: a trailing control flow
        // construct swallows nothing after it.
        Expr::If { .. } | Expr::For { .. } | Expr::While { .. } | Expr::Repeat(_) => left,
        _ => false,
    }
}

/// A numeric literal as R writes it: the same fixed-vs-scientific choice
/// `print` makes for a length-one double, so `100000` deparses to `1e+05`.
fn num_literal(x: f64) -> String {
    if !x.is_finite() {
        return render_fixed(x, 0);
    }
    let fixed = render_fixed(x, fixed_decimals(x));
    let sci = render_sci(x, sci_decimals(x));
    if crate::host::prefers_fixed(fixed.chars().count(), sci.chars().count()) {
        fixed
    } else {
        sci
    }
}

/// R's `isValidName`: a name that the parser would read back as this same
/// symbol prints bare; anything else gets backticks.
pub fn is_syntactic_name(s: &str) -> bool {
    if s == "..." {
        return true;
    }
    let mut cs = s.chars();
    let Some(first) = cs.next() else {
        return false;
    };
    if first != '.' && !first.is_ascii_alphabetic() {
        return false;
    }
    // `.5` and `.1x` are numbers, not names.
    if first == '.' && cs.clone().next().is_some_and(|c| c.is_ascii_digit()) {
        return false;
    }
    if !cs.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_') {
        return false;
    }
    !matches!(
        s,
        "NULL"
            | "NA"
            | "TRUE"
            | "FALSE"
            | "Inf"
            | "NaN"
            | "NA_integer_"
            | "NA_real_"
            | "NA_character_"
            | "function"
            | "while"
            | "repeat"
            | "for"
            | "if"
            | "in"
            | "else"
            | "next"
            | "break"
    )
}

/// A name written as a tag — an element name in `c(…)`/`list(…)` or an
/// attribute name in `structure(…)` — which R quotes with `"` rather than
/// backticks when it is not syntactic: `c("a b" = 1)`.
pub(crate) fn quote_tag(s: &str) -> String {
    if is_syntactic_name(s) {
        s.to_string()
    } else {
        format!("\"{}\"", crate::builtins::encode_string(s))
    }
}

pub(crate) fn quote_name(s: &str) -> String {
    if is_syntactic_name(s) {
        s.to_string()
    } else {
        format!("`{s}`")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse;

    /// Deparse the single `function` expression in `src`.
    fn dep(src: &str) -> Vec<String> {
        let exprs = parse(src).expect("parse");
        match &exprs[0] {
            Expr::Function { params, body } => deparse_closure(params, body),
            other => panic!("not a function: {other:?}"),
        }
    }

    #[test]
    fn header_is_its_own_line_with_a_trailing_space() {
        assert_eq!(dep("function(x) x + 1"), vec!["function (x) ", "x + 1"]);
    }

    #[test]
    fn if_breaks_only_inside_braces() {
        // Bare body: one line.
        assert_eq!(
            dep("function(a, b) if (a > b) a else b"),
            vec!["function (a, b) ", "if (a > b) a else b"]
        );
        // Braced body: R splits the branches and indents the consequent.
        assert_eq!(
            dep("function(y) { if (y > 3) y else 0 }"),
            vec![
                "function (y) ",
                "{",
                "    if (y > 3) ",
                "        y",
                "    else 0",
                "}"
            ]
        );
    }

    #[test]
    fn tight_operators_take_no_spaces() {
        assert_eq!(dep("function(x) x/2")[1], "x/2");
        assert_eq!(dep("function(x) x^2")[1], "x^2");
        assert_eq!(dep("function(x) x %% 3")[1], "x%%3");
        assert_eq!(dep("function(x) x %in% y")[1], "x %in% y");
        assert_eq!(dep("function(x) x * 2 + 1")[1], "x * 2 + 1");
    }

    #[test]
    fn parentheses_survive_verbatim() {
        assert_eq!(dep("function(x) (x + 1) * 2")[1], "(x + 1) * 2");
        assert_eq!(dep("function(x) -(x + 1)")[1], "-(x + 1)");
    }

    #[test]
    fn long_binary_run_wraps_at_the_cutoff() {
        assert_eq!(
            dep("function(a) { a + 100000 + 200000 + 300000 + 400000 + 500000 + 600000 + 700000 + 800000 }"),
            vec![
                "function (a) ",
                "{",
                "    a + 1e+05 + 2e+05 + 3e+05 + 4e+05 + 5e+05 + 6e+05 + 7e+05 + ",
                "        8e+05",
                "}",
            ]
        );
    }

    #[test]
    fn defaults_and_nested_functions() {
        assert_eq!(
            dep("function(x = c(1,2), y = \"a\") function(z = 2) z"),
            vec!["function (x = c(1, 2), y = \"a\") ", "function(z = 2) z"]
        );
    }

    #[test]
    fn non_syntactic_names_are_backticked() {
        assert!(!is_syntactic_name("my var"));
        assert!(!is_syntactic_name("if"));
        assert!(!is_syntactic_name(".5x"));
        assert!(is_syntactic_name("..."));
        assert!(is_syntactic_name(".x"));
    }
}