1use super::*;
2use nom::branch::alt;
3use nom::bytes::complete::tag;
4use nom::character::complete::{alpha1, alphanumeric1, digit1, one_of};
5use nom::combinator::{all_consuming, map, map_res, recognize};
6use nom::multi::{fold, many0, separated_list0};
7use nom::sequence::{delimited, pair, preceded, separated_pair};
8use nom::{IResult, Parser};
9use nom_language::error::VerboseError;
10
11type R<'i, O> = IResult<&'i str, O, VerboseError<&'i str>>;
12
13pub fn parse_tdim(symbol_table: &SymbolScope, input: &str) -> TractResult<TDim> {
14 match all_consuming(|i| expr(symbol_table, i)).parse(input) {
15 Ok(pair) => Ok(pair.1),
16 Err(e) => bail!("Failed to parse {:?}, {:?}", input, e),
17 }
18}
19
20pub fn parse_assertion(symbol_table: &SymbolScope, input: &str) -> TractResult<Assertion> {
21 match all_consuming(|i| assertion(symbol_table, i)).parse(input) {
22 Ok(pair) => Ok(pair.1),
23 Err(e) => bail!("Failed to parse {:?}, {:?}", input, e),
24 }
25}
26
27fn assertion<'i>(s: &SymbolScope, i: &'i str) -> R<'i, Assertion> {
28 delimited(
29 spaces,
30 alt((
31 map(separated_pair(|i| expr(s, i), stag("=="), |i| expr(s, i)), |(a, b)| {
32 Assertion::Eq(a, b)
33 }),
34 map(separated_pair(|i| expr(s, i), stag("<="), |i| expr(s, i)), |(a, b)| {
35 Assertion::LTE(a, b)
36 }),
37 map(separated_pair(|i| expr(s, i), stag(">="), |i| expr(s, i)), |(a, b)| {
38 Assertion::GTE(a, b)
39 }),
40 map(separated_pair(|i| expr(s, i), stag("<"), |i| expr(s, i)), |(a, b)| {
41 Assertion::LT(a, b)
42 }),
43 map(separated_pair(|i| expr(s, i), stag(">"), |i| expr(s, i)), |(a, b)| {
44 Assertion::GT(a, b)
45 }),
46 )),
47 spaces,
48 )
49 .parse(i)
50}
51
52fn expr<'i>(symbol_table: &SymbolScope, i: &'i str) -> R<'i, TDim> {
53 broadcast(symbol_table, i)
54}
55
56fn broadcast<'i>(symbol_table: &SymbolScope, input: &'i str) -> R<'i, TDim> {
57 let s = symbol_table;
58 let (mut input, mut result) = add(s, input)?;
59 while let Ok((i, _)) = stag("#").parse(input) {
60 let (i, next) = map_res(|i| add(s, i), |v| result.clone().broadcast(v)).parse(i)?;
61 (input, result) = (i, next);
62 }
63 Ok((input, result))
64}
65
66macro_rules! bin {
67 ($name: ident, $left: expr, $right: expr, $op: expr, $builder: expr) => {
68 fn $name<'i>(symbol_table: &SymbolScope, input: &'i str) -> R<'i, TDim> {
69 let s = symbol_table;
70 let (input, result) = $left(s, input)?;
71 fold(0.., preceded(stag($op), |i| $right(s, i)), move || result.clone(), $builder)
72 .parse(input)
73 }
74 };
75}
76
77bin!(add, sub, sub, "+", |a, b| a + b);
78bin!(sub, mul, mul, "-", |a, b| a - b);
79bin!(mul, div, div, "*", |a, b| a * b);
80bin!(div, atom, |_s, i| numeric(i), "/", |a, b| a / b);
81
82fn atom<'i>(symbol_table: &SymbolScope, i: &'i str) -> R<'i, TDim> {
83 alt((
84 map(numeric, TDim::Val),
85 map(|i| func(symbol_table, "min", i), TDim::Min),
86 map(|i| func(symbol_table, "max", i), TDim::Max),
87 map(|i| func(symbol_table, "floor", i), |xs| xs[0].clone()),
88 map(|i| identifier(symbol_table, i), TDim::Sym),
89 map(pair(recognize(stag("-")), |i| atom(symbol_table, i)), |(_, dim)| dim * -1),
90 delimited(stag("("), |i| expr(symbol_table, i), stag(")")),
91 ))
92 .parse(i)
93}
94
95fn func<'i>(symbol_table: &SymbolScope, name: &'static str, i: &'i str) -> R<'i, Vec<TDim>> {
96 preceded(
97 stag(name),
98 delimited(stag("("), separated_list0(stag(","), |i| expr(symbol_table, i)), stag(")")),
99 )
100 .parse(i)
101}
102
103fn identifier<'i>(symbol_table: &SymbolScope, i: &'i str) -> R<'i, Symbol> {
104 map(
105 recognize(pair(alt((alpha1, tag("_"))), many0(alt((alphanumeric1, tag("_"), tag(".")))))),
106 |s| symbol_table.sym(s),
107 )
108 .parse(i)
109}
110
111fn numeric(i: &str) -> R<'_, i64> {
112 map_res(digit1, std::str::FromStr::from_str).parse(i)
113}
114
115fn spaces(i: &str) -> R<'_, ()> {
116 map(many0(one_of(" \t\n\r")), |_| ()).parse(i)
117}
118
119fn spaced<'s, O, P>(it: P) -> impl Parser<&'s str, Output = O, Error = VerboseError<&'s str>>
120where
121 P: Parser<&'s str, Output = O, Error = VerboseError<&'s str>>,
122{
123 delimited(spaces, it, spaces)
124}
125
126pub(super) fn stag<'s>(
127 t: &'static str,
128) -> impl Parser<&'s str, Output = &'s str, Error = VerboseError<&'s str>> {
129 spaced(tag(t))
130}
131
132#[cfg(test)]
133mod test {
134 use super::*;
135
136 #[test]
137 fn parse_int() {
138 let table = SymbolScope::default();
139 assert_eq!(parse_tdim(&table, "12").unwrap(), TDim::Val(12));
140 assert_eq!(parse_tdim(&table, "-12").unwrap(), TDim::Val(-12));
141 }
142
143 #[test]
144 fn parse_sym() {
145 let table = SymbolScope::default();
146 assert_eq!(parse_tdim(&table, "x").unwrap(), TDim::Sym(table.sym("x")));
147 assert_eq!(
148 parse_tdim(&table, "-y").unwrap(),
149 TDim::MulInt(-1, Box::new(table.sym("y").into()))
150 );
151 }
152
153 #[test]
154 fn parse_bin() {
155 let table = SymbolScope::default();
156 assert_eq!(parse_tdim(&table, "1+2").unwrap(), 3.into());
157 assert_eq!(parse_tdim(&table, "1-2").unwrap(), (-1).into());
158 assert_eq!(parse_tdim(&table, "1*2").unwrap(), 2.into());
159 assert_eq!(parse_tdim(&table, "1/2").unwrap(), 0.into());
160 }
161
162 #[test]
163 fn parse_prio() {
164 let table = SymbolScope::default();
165 assert_eq!(parse_tdim(&table, "1+2*3").unwrap(), 7.into());
166 assert_eq!(parse_tdim(&table, "1*2+3").unwrap(), 5.into());
167 }
168
169 #[test]
170 fn parse_min() {
171 let table = SymbolScope::default();
172 assert_eq!(
173 parse_tdim(&table, "min(P,S)").unwrap(),
174 TDim::Min(vec!(table.sym("P").into(), table.sym("S").into()))
175 );
176 }
177
178 #[test]
179 fn parse_inequality_0() {
180 let table = SymbolScope::default();
181 assert_eq!(
182 parse_assertion(&table, "P+S<4096").unwrap(),
183 Assertion::LT(parse_tdim(&table, "P+S").unwrap(), 4096.to_dim())
184 );
185 }
186
187 #[test]
188 fn parse_dot_ids() {
189 let table = SymbolScope::default();
190 assert_eq!(parse_tdim(&table, "dot.0").unwrap(), table.sym("dot.0").into());
191 }
192
193 #[test]
194 fn parse_dot_ids_arith() {
195 let table = SymbolScope::default();
196 assert_eq!(parse_tdim(&table, "dot.0/2").unwrap(), table.sym("dot.0").to_dim() / 2);
197 }
198
199 #[test]
200 fn parse_floors() {
201 let table = SymbolScope::default();
202 assert_eq!(parse_tdim(&table, "floor(a)").unwrap(), table.sym("a").to_dim());
203 }
204}