summaryrefslogtreecommitdiff
path: root/src/parse/collection.rs
blob: 95ca984703f01e275bc98152a01455ef8c312043 (plain) (blame)
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
use super::*;

/// Parse the arguments to a function call.
pub fn arguments(p: &mut Parser) -> ExprArgs {
    collection(p, vec![])
}

/// Parse a parenthesized group, which can be either of:
/// - Array literal
/// - Dictionary literal
/// - Parenthesized expression
pub fn parenthesized(p: &mut Parser) -> Expr {
    p.start_group(Group::Paren, TokenMode::Code);
    let state = if p.eat_if(Token::Colon) {
        collection(p, State::Dict(vec![]))
    } else {
        collection(p, State::Unknown)
    };
    p.end_group();
    state.into_expr()
}

/// Parse a collection.
fn collection<T: Collection>(p: &mut Parser, mut collection: T) -> T {
    let mut missing_coma = None;

    while !p.eof() {
        if let Some(arg) = p.span_if(argument) {
            collection.push_arg(p, arg);

            if let Some(pos) = missing_coma.take() {
                p.expected_at("comma", pos);
            }

            if p.eof() {
                break;
            }

            let behind = p.last_end();
            if p.eat_if(Token::Comma) {
                collection.push_comma();
            } else {
                missing_coma = Some(behind);
            }
        }
    }

    collection
}

/// Parse an expression or a named pair.
fn argument(p: &mut Parser) -> Option<Argument> {
    let first = p.span_if(expr)?;
    if p.eat_if(Token::Colon) {
        if let Expr::Ident(ident) = first.v {
            let name = ident.with_span(first.span);
            let expr = p.span_if(expr)?;
            Some(Argument::Named(Named { name, expr }))
        } else {
            p.diag(error!(first.span, "expected identifier"));
            expr(p);
            None
        }
    } else {
        Some(Argument::Pos(first))
    }
}

/// Abstraction for comma-separated list of expression / named pairs.
trait Collection {
    fn push_arg(&mut self, p: &mut Parser, arg: Spanned<Argument>);
    fn push_comma(&mut self) {}
}

impl Collection for ExprArgs {
    fn push_arg(&mut self, _: &mut Parser, arg: Spanned<Argument>) {
        self.push(arg.v);
    }
}

/// State of collection parsing.
#[derive(Debug)]
enum State {
    Unknown,
    Expr(Spanned<Expr>),
    Array(ExprArray),
    Dict(ExprDict),
}

impl State {
    fn into_expr(self) -> Expr {
        match self {
            Self::Unknown => Expr::Array(vec![]),
            Self::Expr(expr) => Expr::Group(Box::new(expr)),
            Self::Array(array) => Expr::Array(array),
            Self::Dict(dict) => Expr::Dict(dict),
        }
    }
}

impl Collection for State {
    fn push_arg(&mut self, p: &mut Parser, arg: Spanned<Argument>) {
        match self {
            Self::Unknown => match arg.v {
                Argument::Pos(expr) => *self = Self::Expr(expr),
                Argument::Named(named) => *self = Self::Dict(vec![named]),
            },
            Self::Expr(prev) => match arg.v {
                Argument::Pos(expr) => *self = Self::Array(vec![take(prev), expr]),
                Argument::Named(_) => diag(p, arg),
            },
            Self::Array(array) => match arg.v {
                Argument::Pos(expr) => array.push(expr),
                Argument::Named(_) => diag(p, arg),
            },
            Self::Dict(dict) => match arg.v {
                Argument::Pos(_) => diag(p, arg),
                Argument::Named(named) => dict.push(named),
            },
        }
    }

    fn push_comma(&mut self) {
        if let Self::Expr(expr) = self {
            *self = Self::Array(vec![take(expr)]);
        }
    }
}

fn take(expr: &mut Spanned<Expr>) -> Spanned<Expr> {
    // Replace with anything, it's overwritten anyway.
    std::mem::replace(expr, Spanned::zero(Expr::Bool(false)))
}

fn diag(p: &mut Parser, arg: Spanned<Argument>) {
    p.diag(error!(arg.span, "{}", match arg.v {
        Argument::Pos(_) => "expected named pair, found expression",
        Argument::Named(_) => "expected expression, found named pair",
    }));
}