use itertools::Itertools; use pest::iterators::Pair; use pest::prec_climber as pcl; use pest::Parser; use std::borrow::Cow; use std::rc::Rc; use dhall_generated_parser::{DhallParser, Rule}; use crate::map::{DupTreeMap, DupTreeSet}; use crate::ExprF::*; use crate::*; // This file consumes the parse tree generated by pest and turns it into // our own AST. All those custom macros should eventually moved into // their own crate because they are quite general and useful. For now they // are here and hopefully you can figure out how they work. pub(crate) type ParsedExpr = Expr; pub(crate) type ParsedSubExpr = SubExpr; type ParsedText = InterpolatedText; type ParsedTextContents = InterpolatedTextContents; pub type ParseError = pest::error::Error; pub type ParseResult = Result; #[derive(Debug)] enum Either { Left(A), Right(B), } impl crate::Builtin { pub fn parse(s: &str) -> Option { use crate::Builtin::*; match s { "Bool" => Some(Bool), "Natural" => Some(Natural), "Integer" => Some(Integer), "Double" => Some(Double), "Text" => Some(Text), "List" => Some(List), "Optional" => Some(Optional), "None" => Some(OptionalNone), "Natural/build" => Some(NaturalBuild), "Natural/fold" => Some(NaturalFold), "Natural/isZero" => Some(NaturalIsZero), "Natural/even" => Some(NaturalEven), "Natural/odd" => Some(NaturalOdd), "Natural/toInteger" => Some(NaturalToInteger), "Natural/show" => Some(NaturalShow), "Natural/subtract" => Some(NaturalSubtract), "Integer/toDouble" => Some(IntegerToDouble), "Integer/show" => Some(IntegerShow), "Double/show" => Some(DoubleShow), "List/build" => Some(ListBuild), "List/fold" => Some(ListFold), "List/length" => Some(ListLength), "List/head" => Some(ListHead), "List/last" => Some(ListLast), "List/indexed" => Some(ListIndexed), "List/reverse" => Some(ListReverse), "Optional/fold" => Some(OptionalFold), "Optional/build" => Some(OptionalBuild), "Text/show" => Some(TextShow), _ => None, } } } pub fn custom_parse_error(pair: &Pair, msg: String) -> ParseError { let msg = format!("{} while matching on:\n{}", msg, debug_pair(pair.clone())); let e = pest::error::ErrorVariant::CustomError { message: msg }; pest::error::Error::new_from_span(e, pair.as_span()) } fn debug_pair(pair: Pair) -> String { use std::fmt::Write; let mut s = String::new(); fn aux(s: &mut String, indent: usize, prefix: String, pair: Pair) { let indent_str = "| ".repeat(indent); let rule = pair.as_rule(); let contents = pair.as_str(); let mut inner = pair.into_inner(); let mut first = true; while let Some(p) = inner.next() { if first { first = false; let last = inner.peek().is_none(); if last && p.as_str() == contents { let prefix = format!("{}{:?} > ", prefix, rule); aux(s, indent, prefix, p); continue; } else { writeln!( s, r#"{}{}{:?}: "{}""#, indent_str, prefix, rule, contents ) .unwrap(); } } aux(s, indent + 1, "".into(), p); } if first { writeln!( s, r#"{}{}{:?}: "{}""#, indent_str, prefix, rule, contents ) .unwrap(); } } aux(&mut s, 0, "".into(), pair); s } macro_rules! make_parser { (@pattern, rule, $name:ident) => (Rule::$name); (@pattern, token_rule, $name:ident) => (Rule::$name); (@pattern, rule_group, $name:ident) => (_); (@filter, rule) => (true); (@filter, token_rule) => (true); (@filter, rule_group) => (false); (@body, ($($things:tt)*), rule!( $name:ident<$o:ty>; $($args:tt)* ) ) => ( make_parser!(@body, ($($things)*), rule!( $name<$o> as $name; $($args)* ) ) ); (@body, ($_input:expr, $pair:expr, $_children:expr), rule!( $name:ident<$o:ty> as $group:ident; captured_str!($x:pat) => $body:expr ) ) => ({ let $x = $pair.as_str(); let res: $o = $body; Ok(ParsedValue::$group(res)) }); (@body, ($_input:expr, $_pair:expr, $children:expr), rule!( $name:ident<$o:ty> as $group:ident; children!( $( [$($args:tt)*] => $body:expr ),* $(,)* ) ) ) => ({ #[allow(unused_imports)] use ParsedValue::*; #[allow(unreachable_code)] let res: $o = improved_slice_patterns::match_vec!($children; $( [$($args)*] => $body, )* [x..] => Err( format!("Unexpected children: {:?}", x.collect::>()) )?, ).map_err(|_| -> String { unreachable!() })?; Ok(ParsedValue::$group(res)) }); (@body, ($input:expr, $pair:expr, $children:expr), rule!( $name:ident<$o:ty> as $group:ident; $span:ident; $($args:tt)* ) ) => ({ let $span = Span::make($input, $pair.as_span()); make_parser!(@body, ($input, $pair, $children), rule!( $name<$o> as $group; $($args)* ) ) }); (@body, ($($things:tt)*), token_rule!($name:ident<$o:ty>) ) => ({ Ok(ParsedValue::$name(())) }); (@body, ($($things:tt)*), rule_group!( $name:ident<$o:ty> )) => ( unreachable!() ); ($( $submac:ident!( $name:ident<$o:ty> $($args:tt)* ); )*) => ( #[allow(non_camel_case_types, dead_code, clippy::large_enum_variant)] #[derive(Debug)] enum ParsedValue<'a> { $( $name($o), )* } fn parse_any<'a>( input: Rc, pair: Pair<'a, Rule>, children: Vec>, ) -> Result, String> { match pair.as_rule() { $( make_parser!(@pattern, $submac, $name) if make_parser!(@filter, $submac) => make_parser!(@body, (input, pair, children), $submac!( $name<$o> $($args)* )) , )* r => Err(format!("Unexpected {:?}", r)), } } ); } fn do_parse<'a>( input: Rc, mut pair: Pair<'a, Rule>, ) -> ParseResult> { // Avoid parsing while the pair has exactly one child that can be returned as-is loop { if can_be_shortcutted(pair.as_rule()) { let mut i = pair.clone().into_inner(); let first = i.next(); let second = i.next(); match (first, second) { // If pair has exactly one child, just go on parsing that child (Some(p), None) => { pair = p; continue; } // Otherwise parse normally _ => break, } } break; } // Use precedence climbing to parse operator_expression if pair.as_rule() == Rule::operator_expression { let rule_to_binop = { use crate::BinOp::*; use Rule::*; |r| { Some(match r { import_alt => ImportAlt, bool_or => BoolOr, natural_plus => NaturalPlus, text_append => TextAppend, list_append => ListAppend, bool_and => BoolAnd, combine => RecursiveRecordMerge, prefer => RightBiasedRecordMerge, combine_types => RecursiveRecordTypeMerge, natural_times => NaturalTimes, bool_eq => BoolEQ, bool_ne => BoolNE, equivalent => Equivalence, _ => return None, }) } }; let operators = { use Rule::*; // In order of precedence vec![ import_alt, bool_or, natural_plus, text_append, list_append, bool_and, combine, prefer, combine_types, natural_times, bool_eq, bool_ne, equivalent, ] }; let climber = pcl::PrecClimber::new( operators .into_iter() .map(|op| pcl::Operator::new(op, pcl::Assoc::Left)) .collect(), ); climber.climb( pair.clone().into_inner(), |p| do_parse(input.clone(), p), |l, p, r| { let o = match rule_to_binop(p.as_rule()) { Some(o) => o, None => Err(custom_parse_error( &pair, format!("Rule {:?} isn't an operator", p.as_rule()), ))?, }; use ParsedValue::expression; match (l?, r?) { (expression(l), expression(r)) => { Ok(expression(unspanned(BinOp(o, l, r)))) } (l, r) => Err(custom_parse_error( &pair, format!("Unexpected children: {:?}", [l, r]), ))?, } }, ) } else { let children = pair .clone() .into_inner() .map(|p| do_parse(input.clone(), p)) .collect::>()?; parse_any(input.clone(), pair.clone(), children) .map_err(|msg| custom_parse_error(&pair, msg)) } } // List of rules that can be shortcutted if they have a single child fn can_be_shortcutted(rule: Rule) -> bool { use Rule::*; match rule { expression | operator_expression | application_expression | first_application_expression | selector_expression | annotated_expression => true, _ => false, } } // Trim the shared indent off of a vec of lines, as defined by the Dhall semantics of multiline // literals. fn trim_indent(lines: &mut Vec) { let is_indent = |c: char| c == ' ' || c == '\t'; // There is at least one line so this is safe let last_line_head = lines.last().unwrap().head(); let indent_chars = last_line_head .char_indices() .take_while(|(_, c)| is_indent(*c)); let mut min_indent_idx = match indent_chars.last() { Some((i, _)) => i, // If there is no indent char, then no indent needs to be stripped None => return, }; for line in lines.iter() { // Ignore empty lines if line.is_empty() { continue; } // Take chars from line while they match the current minimum indent. let indent_chars = last_line_head[0..=min_indent_idx] .char_indices() .zip(line.head().chars()) .take_while(|((_, c1), c2)| c1 == c2); match indent_chars.last() { Some(((i, _), _)) => min_indent_idx = i, // If there is no indent char, then no indent needs to be stripped None => return, }; } // Remove the shared indent from non-empty lines for line in lines.iter_mut() { if !line.is_empty() { line.head_mut().replace_range(0..=min_indent_idx, ""); } } } make_parser! { token_rule!(EOI<()>); rule!(simple_label