From 2cf9169e1a21e1196e0265847abcfa904e2d45a3 Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Mon, 6 Apr 2020 22:13:36 +0100 Subject: Move builtins module up a level --- dhall/src/builtins.rs | 494 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 494 insertions(+) create mode 100644 dhall/src/builtins.rs (limited to 'dhall/src/builtins.rs') diff --git a/dhall/src/builtins.rs b/dhall/src/builtins.rs new file mode 100644 index 0000000..f65e8d1 --- /dev/null +++ b/dhall/src/builtins.rs @@ -0,0 +1,494 @@ +use crate::operations::OpKind; +use crate::semantics::{ + skip_resolve_expr, typecheck, Hir, HirKind, Nir, NirKind, NzEnv, VarEnv, +}; +use crate::syntax::map::DupTreeMap; +use crate::syntax::Const::Type; +use crate::syntax::{ + BinOp, Builtin, Const, Expr, ExprKind, InterpolatedText, + InterpolatedTextContents, Label, NaiveDouble, NumKind, Span, UnspannedExpr, + V, +}; +use std::collections::HashMap; +use std::convert::TryInto; + +/// A partially applied builtin. +/// Invariant: the evaluation of the given args must not be able to progress further +#[derive(Debug, Clone)] +pub struct BuiltinClosure { + env: NzEnv, + b: Builtin, + /// Arguments applied to the closure so far. + args: Vec, +} + +impl BuiltinClosure { + pub fn new(b: Builtin, env: NzEnv) -> NirKind { + apply_builtin(b, Vec::new(), env) + } + pub fn apply(&self, a: Nir) -> NirKind { + use std::iter::once; + let args = self.args.iter().cloned().chain(once(a)).collect(); + apply_builtin(self.b, args, self.env.clone()) + } + pub fn to_hirkind(&self, venv: VarEnv) -> HirKind { + HirKind::Expr(self.args.iter().fold( + ExprKind::Builtin(self.b), + |acc, v| { + ExprKind::Op(OpKind::App( + Hir::new(HirKind::Expr(acc), Span::Artificial), + v.to_hir(venv), + )) + }, + )) + } +} + +pub fn rc(x: UnspannedExpr) -> Expr { + Expr::new(x, Span::Artificial) +} + +// Ad-hoc macro to help construct the types of builtins +macro_rules! make_type { + (Type) => { rc(ExprKind::Const(Const::Type)) }; + (Bool) => { rc(ExprKind::Builtin(Builtin::Bool)) }; + (Natural) => { rc(ExprKind::Builtin(Builtin::Natural)) }; + (Integer) => { rc(ExprKind::Builtin(Builtin::Integer)) }; + (Double) => { rc(ExprKind::Builtin(Builtin::Double)) }; + (Text) => { rc(ExprKind::Builtin(Builtin::Text)) }; + ($var:ident) => { + rc(ExprKind::Var(V(stringify!($var).into(), 0))) + }; + (Optional $ty:ident) => { + rc(ExprKind::Op(OpKind::App( + rc(ExprKind::Builtin(Builtin::Optional)), + make_type!($ty) + ))) + }; + (List $($rest:tt)*) => { + rc(ExprKind::Op(OpKind::App( + rc(ExprKind::Builtin(Builtin::List)), + make_type!($($rest)*) + ))) + }; + ({ $($label:ident : $ty:ident),* }) => {{ + let mut kts = DupTreeMap::new(); + $( + kts.insert( + Label::from(stringify!($label)), + make_type!($ty), + ); + )* + rc(ExprKind::RecordType(kts)) + }}; + ($ty:ident -> $($rest:tt)*) => { + rc(ExprKind::Pi( + "_".into(), + make_type!($ty), + make_type!($($rest)*) + )) + }; + (($($arg:tt)*) -> $($rest:tt)*) => { + rc(ExprKind::Pi( + "_".into(), + make_type!($($arg)*), + make_type!($($rest)*) + )) + }; + (forall ($var:ident : $($ty:tt)*) -> $($rest:tt)*) => { + rc(ExprKind::Pi( + stringify!($var).into(), + make_type!($($ty)*), + make_type!($($rest)*) + )) + }; +} + +pub fn type_of_builtin(b: Builtin) -> Hir { + use Builtin::*; + let expr = match b { + Bool | Natural | Integer | Double | Text => make_type!(Type), + List | Optional => make_type!( + Type -> Type + ), + + NaturalFold => make_type!( + Natural -> + forall (natural: Type) -> + forall (succ: natural -> natural) -> + forall (zero: natural) -> + natural + ), + NaturalBuild => make_type!( + (forall (natural: Type) -> + forall (succ: natural -> natural) -> + forall (zero: natural) -> + natural) -> + Natural + ), + NaturalIsZero | NaturalEven | NaturalOdd => make_type!( + Natural -> Bool + ), + NaturalToInteger => make_type!(Natural -> Integer), + NaturalShow => make_type!(Natural -> Text), + NaturalSubtract => make_type!(Natural -> Natural -> Natural), + + IntegerToDouble => make_type!(Integer -> Double), + IntegerShow => make_type!(Integer -> Text), + IntegerNegate => make_type!(Integer -> Integer), + IntegerClamp => make_type!(Integer -> Natural), + + DoubleShow => make_type!(Double -> Text), + TextShow => make_type!(Text -> Text), + + ListBuild => make_type!( + forall (a: Type) -> + (forall (list: Type) -> + forall (cons: a -> list -> list) -> + forall (nil: list) -> + list) -> + List a + ), + ListFold => make_type!( + forall (a: Type) -> + (List a) -> + forall (list: Type) -> + forall (cons: a -> list -> list) -> + forall (nil: list) -> + list + ), + ListLength => make_type!(forall (a: Type) -> (List a) -> Natural), + ListHead | ListLast => { + make_type!(forall (a: Type) -> (List a) -> Optional a) + } + ListIndexed => make_type!( + forall (a: Type) -> + (List a) -> + List { index: Natural, value: a } + ), + ListReverse => make_type!( + forall (a: Type) -> (List a) -> List a + ), + + OptionalBuild => make_type!( + forall (a: Type) -> + (forall (optional: Type) -> + forall (just: a -> optional) -> + forall (nothing: optional) -> + optional) -> + Optional a + ), + OptionalFold => make_type!( + forall (a: Type) -> + (Optional a) -> + forall (optional: Type) -> + forall (just: a -> optional) -> + forall (nothing: optional) -> + optional + ), + OptionalNone => make_type!( + forall (A: Type) -> Optional A + ), + }; + skip_resolve_expr(&expr).unwrap() +} + +// Ad-hoc macro to help construct closures +macro_rules! make_closure { + (var($var:ident)) => {{ + rc(ExprKind::Var(V( + Label::from(stringify!($var)).into(), + 0 + ))) + }}; + (λ($var:tt : $($ty:tt)*) -> $($body:tt)*) => {{ + let var = Label::from(stringify!($var)); + let ty = make_closure!($($ty)*); + let body = make_closure!($($body)*); + rc(ExprKind::Lam(var, ty, body)) + }}; + (Type) => { + rc(ExprKind::Const(Type)) + }; + (Natural) => { + rc(ExprKind::Builtin(Builtin::Natural)) + }; + (List $($ty:tt)*) => {{ + let ty = make_closure!($($ty)*); + rc(ExprKind::Op(OpKind::App( + rc(ExprKind::Builtin(Builtin::List)), + ty + ))) + }}; + (Some($($v:tt)*)) => { + rc(ExprKind::SomeLit( + make_closure!($($v)*) + )) + }; + (1 + $($v:tt)*) => { + rc(ExprKind::Op(OpKind::BinOp( + BinOp::NaturalPlus, + make_closure!($($v)*), + rc(ExprKind::Num(NumKind::Natural(1))) + ))) + }; + ([ $($head:tt)* ] # $($tail:tt)*) => {{ + let head = make_closure!($($head)*); + let tail = make_closure!($($tail)*); + rc(ExprKind::Op(OpKind::BinOp( + BinOp::ListAppend, + rc(ExprKind::NEListLit(vec![head])), + tail, + ))) + }}; +} + +#[allow(clippy::cognitive_complexity)] +fn apply_builtin(b: Builtin, args: Vec, env: NzEnv) -> NirKind { + use NirKind::*; + use NumKind::{Bool, Double, Integer, Natural}; + + // Small helper enum + enum Ret { + NirKind(NirKind), + Nir(Nir), + DoneAsIs, + } + let make_closure = |e| { + typecheck(&skip_resolve_expr(&e).unwrap()) + .unwrap() + .eval(env.clone()) + }; + + let ret = match (b, args.as_slice()) { + (Builtin::Bool, []) + | (Builtin::Natural, []) + | (Builtin::Integer, []) + | (Builtin::Double, []) + | (Builtin::Text, []) => Ret::NirKind(BuiltinType(b)), + (Builtin::Optional, [t]) => Ret::NirKind(OptionalType(t.clone())), + (Builtin::List, [t]) => Ret::NirKind(ListType(t.clone())), + + (Builtin::OptionalNone, [t]) => { + Ret::NirKind(EmptyOptionalLit(t.clone())) + } + (Builtin::NaturalIsZero, [n]) => match &*n.kind() { + Num(Natural(n)) => Ret::NirKind(Num(Bool(*n == 0))), + _ => Ret::DoneAsIs, + }, + (Builtin::NaturalEven, [n]) => match &*n.kind() { + Num(Natural(n)) => Ret::NirKind(Num(Bool(*n % 2 == 0))), + _ => Ret::DoneAsIs, + }, + (Builtin::NaturalOdd, [n]) => match &*n.kind() { + Num(Natural(n)) => Ret::NirKind(Num(Bool(*n % 2 != 0))), + _ => Ret::DoneAsIs, + }, + (Builtin::NaturalToInteger, [n]) => match &*n.kind() { + Num(Natural(n)) => Ret::NirKind(Num(Integer(*n as isize))), + _ => Ret::DoneAsIs, + }, + (Builtin::NaturalShow, [n]) => match &*n.kind() { + Num(Natural(n)) => Ret::Nir(Nir::from_text(n)), + _ => Ret::DoneAsIs, + }, + (Builtin::NaturalSubtract, [a, b]) => match (&*a.kind(), &*b.kind()) { + (Num(Natural(a)), Num(Natural(b))) => { + Ret::NirKind(Num(Natural(if b > a { b - a } else { 0 }))) + } + (Num(Natural(0)), _) => Ret::Nir(b.clone()), + (_, Num(Natural(0))) => Ret::NirKind(Num(Natural(0))), + _ if a == b => Ret::NirKind(Num(Natural(0))), + _ => Ret::DoneAsIs, + }, + (Builtin::IntegerShow, [n]) => match &*n.kind() { + Num(Integer(n)) => { + let s = if *n < 0 { + n.to_string() + } else { + format!("+{}", n) + }; + Ret::Nir(Nir::from_text(s)) + } + _ => Ret::DoneAsIs, + }, + (Builtin::IntegerToDouble, [n]) => match &*n.kind() { + Num(Integer(n)) => { + Ret::NirKind(Num(Double(NaiveDouble::from(*n as f64)))) + } + _ => Ret::DoneAsIs, + }, + (Builtin::IntegerNegate, [n]) => match &*n.kind() { + Num(Integer(n)) => Ret::NirKind(Num(Integer(-n))), + _ => Ret::DoneAsIs, + }, + (Builtin::IntegerClamp, [n]) => match &*n.kind() { + Num(Integer(n)) => { + Ret::NirKind(Num(Natural((*n).try_into().unwrap_or(0)))) + } + _ => Ret::DoneAsIs, + }, + (Builtin::DoubleShow, [n]) => match &*n.kind() { + Num(Double(n)) => Ret::Nir(Nir::from_text(n)), + _ => Ret::DoneAsIs, + }, + (Builtin::TextShow, [v]) => match &*v.kind() { + TextLit(tlit) => { + if let Some(s) = tlit.as_text() { + // Printing InterpolatedText takes care of all the escaping + let txt: InterpolatedText = + std::iter::once(InterpolatedTextContents::Text(s)) + .collect(); + Ret::Nir(Nir::from_text(txt)) + } else { + Ret::DoneAsIs + } + } + _ => Ret::DoneAsIs, + }, + (Builtin::ListLength, [_, l]) => match &*l.kind() { + EmptyListLit(_) => Ret::NirKind(Num(Natural(0))), + NEListLit(xs) => Ret::NirKind(Num(Natural(xs.len()))), + _ => Ret::DoneAsIs, + }, + (Builtin::ListHead, [_, l]) => match &*l.kind() { + EmptyListLit(n) => Ret::NirKind(EmptyOptionalLit(n.clone())), + NEListLit(xs) => { + Ret::NirKind(NEOptionalLit(xs.iter().next().unwrap().clone())) + } + _ => Ret::DoneAsIs, + }, + (Builtin::ListLast, [_, l]) => match &*l.kind() { + EmptyListLit(n) => Ret::NirKind(EmptyOptionalLit(n.clone())), + NEListLit(xs) => Ret::NirKind(NEOptionalLit( + xs.iter().rev().next().unwrap().clone(), + )), + _ => Ret::DoneAsIs, + }, + (Builtin::ListReverse, [_, l]) => match &*l.kind() { + EmptyListLit(n) => Ret::NirKind(EmptyListLit(n.clone())), + NEListLit(xs) => { + Ret::NirKind(NEListLit(xs.iter().rev().cloned().collect())) + } + _ => Ret::DoneAsIs, + }, + (Builtin::ListIndexed, [t, l]) => { + match l.kind() { + EmptyListLit(_) | NEListLit(_) => { + // Construct the returned record type: { index: Natural, value: t } + let mut kts = HashMap::new(); + kts.insert( + "index".into(), + Nir::from_builtin(Builtin::Natural), + ); + kts.insert("value".into(), t.clone()); + let t = Nir::from_kind(RecordType(kts)); + + // Construct the new list, with added indices + let list = match l.kind() { + EmptyListLit(_) => EmptyListLit(t), + NEListLit(xs) => NEListLit( + xs.iter() + .enumerate() + .map(|(i, e)| { + let mut kvs = HashMap::new(); + kvs.insert( + "index".into(), + Nir::from_kind(Num(Natural(i))), + ); + kvs.insert("value".into(), e.clone()); + Nir::from_kind(RecordLit(kvs)) + }) + .collect(), + ), + _ => unreachable!(), + }; + Ret::NirKind(list) + } + _ => Ret::DoneAsIs, + } + } + (Builtin::ListBuild, [t, f]) => { + let list_t = Nir::from_builtin(Builtin::List).app(t.clone()); + Ret::Nir( + f.app(list_t) + .app( + make_closure(make_closure!( + λ(T : Type) -> + λ(a : var(T)) -> + λ(as : List var(T)) -> + [ var(a) ] # var(as) + )) + .app(t.clone()), + ) + .app(EmptyListLit(t.clone()).into_nir()), + ) + } + (Builtin::ListFold, [_, l, _, cons, nil]) => match &*l.kind() { + EmptyListLit(_) => Ret::Nir(nil.clone()), + NEListLit(xs) => { + let mut v = nil.clone(); + for x in xs.iter().cloned().rev() { + v = cons.app(x).app(v); + } + Ret::Nir(v) + } + _ => Ret::DoneAsIs, + }, + (Builtin::OptionalBuild, [t, f]) => { + let optional_t = + Nir::from_builtin(Builtin::Optional).app(t.clone()); + Ret::Nir( + f.app(optional_t) + .app( + make_closure(make_closure!( + λ(T : Type) -> + λ(a : var(T)) -> + Some(var(a)) + )) + .app(t.clone()), + ) + .app(EmptyOptionalLit(t.clone()).into_nir()), + ) + } + (Builtin::OptionalFold, [_, v, _, just, nothing]) => match &*v.kind() { + EmptyOptionalLit(_) => Ret::Nir(nothing.clone()), + NEOptionalLit(x) => Ret::Nir(just.app(x.clone())), + _ => Ret::DoneAsIs, + }, + (Builtin::NaturalBuild, [f]) => Ret::Nir( + f.app(Nir::from_builtin(Builtin::Natural)) + .app(make_closure(make_closure!( + λ(x : Natural) -> + 1 + var(x) + ))) + .app(Num(Natural(0)).into_nir()), + ), + + (Builtin::NaturalFold, [n, t, succ, zero]) => match &*n.kind() { + Num(Natural(0)) => Ret::Nir(zero.clone()), + Num(Natural(n)) => { + let fold = Nir::from_builtin(Builtin::NaturalFold) + .app(Num(Natural(n - 1)).into_nir()) + .app(t.clone()) + .app(succ.clone()) + .app(zero.clone()); + Ret::Nir(succ.app(fold)) + } + _ => Ret::DoneAsIs, + }, + _ => Ret::DoneAsIs, + }; + match ret { + Ret::NirKind(v) => v, + Ret::Nir(v) => v.kind().clone(), + Ret::DoneAsIs => AppliedBuiltin(BuiltinClosure { b, args, env }), + } +} + +impl std::cmp::PartialEq for BuiltinClosure { + fn eq(&self, other: &Self) -> bool { + self.b == other.b && self.args == other.args + } +} +impl std::cmp::Eq for BuiltinClosure {} -- cgit v1.3.1 From 56efd2ac39149d8652bd625fbf0679c10823b137 Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Mon, 6 Apr 2020 22:24:15 +0100 Subject: Move BinOp and Builtin definitions in the relevant module --- dhall/src/builtins.rs | 122 +++++++++++++++++++++++++++++++-- dhall/src/operations.rs | 37 +++++++++- dhall/src/semantics/nze/nir.rs | 7 +- dhall/src/semantics/resolve/resolve.rs | 7 +- dhall/src/semantics/tck/tir.rs | 3 +- dhall/src/semantics/tck/typecheck.rs | 6 +- dhall/src/syntax/ast/expr.rs | 69 +------------------ dhall/src/syntax/binary/decode.rs | 4 +- dhall/src/syntax/binary/encode.rs | 8 +-- dhall/src/syntax/text/parser.rs | 48 ++----------- dhall/src/syntax/text/printer.rs | 48 ++----------- serde_dhall/src/value.rs | 3 +- 12 files changed, 182 insertions(+), 180 deletions(-) (limited to 'dhall/src/builtins.rs') diff --git a/dhall/src/builtins.rs b/dhall/src/builtins.rs index f65e8d1..bb8173c 100644 --- a/dhall/src/builtins.rs +++ b/dhall/src/builtins.rs @@ -1,17 +1,92 @@ -use crate::operations::OpKind; +use crate::operations::{BinOp, OpKind}; use crate::semantics::{ skip_resolve_expr, typecheck, Hir, HirKind, Nir, NirKind, NzEnv, VarEnv, }; use crate::syntax::map::DupTreeMap; use crate::syntax::Const::Type; use crate::syntax::{ - BinOp, Builtin, Const, Expr, ExprKind, InterpolatedText, - InterpolatedTextContents, Label, NaiveDouble, NumKind, Span, UnspannedExpr, - V, + Const, Expr, ExprKind, InterpolatedText, InterpolatedTextContents, Label, + NaiveDouble, NumKind, Span, UnspannedExpr, V, }; use std::collections::HashMap; use std::convert::TryInto; +/// Built-ins +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum Builtin { + Bool, + Natural, + Integer, + Double, + Text, + List, + Optional, + OptionalNone, + NaturalBuild, + NaturalFold, + NaturalIsZero, + NaturalEven, + NaturalOdd, + NaturalToInteger, + NaturalShow, + NaturalSubtract, + IntegerToDouble, + IntegerShow, + IntegerNegate, + IntegerClamp, + DoubleShow, + ListBuild, + ListFold, + ListLength, + ListHead, + ListLast, + ListIndexed, + ListReverse, + OptionalFold, + OptionalBuild, + TextShow, +} + +impl Builtin { + pub fn parse(s: &str) -> Option { + use 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), + "Integer/negate" => Some(IntegerNegate), + "Integer/clamp" => Some(IntegerClamp), + "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, + } + } +} + /// A partially applied builtin. /// Invariant: the evaluation of the given args must not be able to progress further #[derive(Debug, Clone)] @@ -492,3 +567,42 @@ impl std::cmp::PartialEq for BuiltinClosure { } } impl std::cmp::Eq for BuiltinClosure {} + +impl std::fmt::Display for Builtin { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + use Builtin::*; + f.write_str(match *self { + Bool => "Bool", + Natural => "Natural", + Integer => "Integer", + Double => "Double", + Text => "Text", + List => "List", + Optional => "Optional", + OptionalNone => "None", + NaturalBuild => "Natural/build", + NaturalFold => "Natural/fold", + NaturalIsZero => "Natural/isZero", + NaturalEven => "Natural/even", + NaturalOdd => "Natural/odd", + NaturalToInteger => "Natural/toInteger", + NaturalShow => "Natural/show", + NaturalSubtract => "Natural/subtract", + IntegerToDouble => "Integer/toDouble", + IntegerNegate => "Integer/negate", + IntegerClamp => "Integer/clamp", + IntegerShow => "Integer/show", + DoubleShow => "Double/show", + ListBuild => "List/build", + ListFold => "List/fold", + ListLength => "List/length", + ListHead => "List/head", + ListLast => "List/last", + ListIndexed => "List/indexed", + ListReverse => "List/reverse", + OptionalFold => "Optional/fold", + OptionalBuild => "Optional/build", + TextShow => "Text/show", + }) + } +} diff --git a/dhall/src/operations.rs b/dhall/src/operations.rs index 363cd10..1ebf288 100644 --- a/dhall/src/operations.rs +++ b/dhall/src/operations.rs @@ -3,15 +3,46 @@ use std::borrow::Cow; use std::cmp::max; use std::collections::HashMap; +use crate::builtins::Builtin; use crate::error::{ErrorBuilder, TypeError}; use crate::semantics::{ merge_maps, mk_span_err, mkerr, ret_kind, ret_op, ret_ref, Binder, Closure, Hir, HirKind, Nir, NirKind, Ret, TextLit, Tir, TyEnv, Type, }; use crate::syntax::map::DupTreeSet; -use crate::syntax::{ - trivial_result, BinOp, Builtin, Const, ExprKind, Label, NumKind, Span, -}; +use crate::syntax::{trivial_result, Const, ExprKind, Label, NumKind, Span}; + +// Definition order must match precedence order for +// pretty-printing to work correctly +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum BinOp { + /// `x ? y` + ImportAlt, + /// `x || y` + BoolOr, + /// `x + y` + NaturalPlus, + /// `x ++ y` + TextAppend, + /// `x # y` + ListAppend, + /// `x && y` + BoolAnd, + /// `x ∧ y` + RecursiveRecordMerge, + /// `x ⫽ y` + RightBiasedRecordMerge, + /// `x ⩓ y` + RecursiveRecordTypeMerge, + /// `x * y` + NaturalTimes, + /// `x == y` + BoolEQ, + /// `x != y` + BoolNE, + /// x === y + Equivalence, +} /// Operations #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] diff --git a/dhall/src/semantics/nze/nir.rs b/dhall/src/semantics/nze/nir.rs index e2a0113..12f1b14 100644 --- a/dhall/src/semantics/nze/nir.rs +++ b/dhall/src/semantics/nze/nir.rs @@ -1,16 +1,15 @@ use std::collections::HashMap; use std::rc::Rc; -use crate::builtins::BuiltinClosure; -use crate::operations::OpKind; +use crate::builtins::{Builtin, BuiltinClosure}; +use crate::operations::{BinOp, OpKind}; use crate::semantics::nze::lazy; use crate::semantics::{ apply_any, normalize_hir, normalize_one_layer, squash_textlit, Binder, Hir, HirKind, NzEnv, NzVar, TyEnv, Type, Universe, VarEnv, }; use crate::syntax::{ - BinOp, Builtin, Const, Expr, ExprKind, InterpolatedTextContents, Label, - NumKind, Span, + Const, Expr, ExprKind, InterpolatedTextContents, Label, NumKind, Span, }; use crate::ToExprOptions; diff --git a/dhall/src/semantics/resolve/resolve.rs b/dhall/src/semantics/resolve/resolve.rs index bbcd240..cd5232a 100644 --- a/dhall/src/semantics/resolve/resolve.rs +++ b/dhall/src/semantics/resolve/resolve.rs @@ -4,15 +4,16 @@ use std::env; use std::path::PathBuf; use url::Url; +use crate::builtins::Builtin; use crate::error::ErrorBuilder; use crate::error::{Error, ImportError}; -use crate::operations::OpKind; +use crate::operations::{BinOp, OpKind}; use crate::semantics::{mkerr, Hir, HirKind, ImportEnv, NameEnv, Type}; use crate::syntax; use crate::syntax::map::DupTreeMap; use crate::syntax::{ - BinOp, Builtin, Expr, ExprKind, FilePath, FilePrefix, Hash, ImportMode, - ImportTarget, Span, UnspannedExpr, URL, + Expr, ExprKind, FilePath, FilePrefix, Hash, ImportMode, ImportTarget, Span, + UnspannedExpr, URL, }; use crate::{Parsed, Resolved}; diff --git a/dhall/src/semantics/tck/tir.rs b/dhall/src/semantics/tck/tir.rs index 89a8027..ec15a1f 100644 --- a/dhall/src/semantics/tck/tir.rs +++ b/dhall/src/semantics/tck/tir.rs @@ -1,6 +1,7 @@ +use crate::builtins::Builtin; use crate::error::{ErrorBuilder, TypeError}; use crate::semantics::{mkerr, Hir, Nir, NirKind, NzEnv, TyEnv, VarEnv}; -use crate::syntax::{Builtin, Const, Expr, Span}; +use crate::syntax::{Const, Expr, Span}; /// The type of a type. 0 is `Type`, 1 is `Kind`, etc... #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] diff --git a/dhall/src/semantics/tck/typecheck.rs b/dhall/src/semantics/tck/typecheck.rs index a31f15c..c6300d9 100644 --- a/dhall/src/semantics/tck/typecheck.rs +++ b/dhall/src/semantics/tck/typecheck.rs @@ -1,13 +1,11 @@ use std::cmp::max; use std::collections::HashMap; -use crate::builtins::type_of_builtin; +use crate::builtins::{type_of_builtin, Builtin}; use crate::error::{ErrorBuilder, TypeError, TypeMessage}; use crate::operations::typecheck_operation; use crate::semantics::{Hir, HirKind, Nir, NirKind, Tir, TyEnv, Type}; -use crate::syntax::{ - Builtin, Const, ExprKind, InterpolatedTextContents, NumKind, Span, -}; +use crate::syntax::{Const, ExprKind, InterpolatedTextContents, NumKind, Span}; fn function_check(a: Const, b: Const) -> Const { if b == Const::Type { diff --git a/dhall/src/syntax/ast/expr.rs b/dhall/src/syntax/ast/expr.rs index 62734bf..8f55540 100644 --- a/dhall/src/syntax/ast/expr.rs +++ b/dhall/src/syntax/ast/expr.rs @@ -1,5 +1,6 @@ use std::collections::BTreeMap; +use crate::builtins::Builtin; use crate::error::Error; use crate::operations::OpKind; use crate::semantics::Universe; @@ -37,74 +38,6 @@ impl Const { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct V(pub Label, pub usize); -// Definition order must match precedence order for -// pretty-printing to work correctly -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum BinOp { - /// `x ? y` - ImportAlt, - /// `x || y` - BoolOr, - /// `x + y` - NaturalPlus, - /// `x ++ y` - TextAppend, - /// `x # y` - ListAppend, - /// `x && y` - BoolAnd, - /// `x ∧ y` - RecursiveRecordMerge, - /// `x ⫽ y` - RightBiasedRecordMerge, - /// `x ⩓ y` - RecursiveRecordTypeMerge, - /// `x * y` - NaturalTimes, - /// `x == y` - BoolEQ, - /// `x != y` - BoolNE, - /// x === y - Equivalence, -} - -/// Built-ins -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub enum Builtin { - Bool, - Natural, - Integer, - Double, - Text, - List, - Optional, - OptionalNone, - NaturalBuild, - NaturalFold, - NaturalIsZero, - NaturalEven, - NaturalOdd, - NaturalToInteger, - NaturalShow, - NaturalSubtract, - IntegerToDouble, - IntegerShow, - IntegerNegate, - IntegerClamp, - DoubleShow, - ListBuild, - ListFold, - ListLength, - ListHead, - ListLast, - ListIndexed, - ListReverse, - OptionalFold, - OptionalBuild, - TextShow, -} - // Each node carries an annotation. #[derive(Debug, Clone)] pub struct Expr { diff --git a/dhall/src/syntax/binary/decode.rs b/dhall/src/syntax/binary/decode.rs index f062089..195bd0a 100644 --- a/dhall/src/syntax/binary/decode.rs +++ b/dhall/src/syntax/binary/decode.rs @@ -25,8 +25,10 @@ fn rc(x: UnspannedExpr) -> Expr { } fn cbor_value_to_dhall(data: &cbor::Value) -> Result { + use crate::builtins::Builtin; + use crate::operations::BinOp; use cbor::Value::*; - use syntax::{BinOp, Builtin, Const}; + use syntax::Const; use ExprKind::*; use OpKind::*; Ok(rc(match data { diff --git a/dhall/src/syntax/binary/encode.rs b/dhall/src/syntax/binary/encode.rs index cef2af8..913dd67 100644 --- a/dhall/src/syntax/binary/encode.rs +++ b/dhall/src/syntax/binary/encode.rs @@ -2,8 +2,9 @@ use serde_cbor::value::value as cbor; use std::collections::BTreeMap; use std::vec; +use crate::builtins::Builtin; use crate::error::EncodeError; -use crate::operations::OpKind; +use crate::operations::{BinOp, OpKind}; use crate::syntax; use crate::syntax::map::DupTreeMap; use crate::syntax::{ @@ -47,7 +48,6 @@ where { use cbor::Value::{String, I64, U64}; use std::iter::once; - use syntax::Builtin; use syntax::ExprKind::*; use syntax::NumKind::*; use OpKind::*; @@ -116,7 +116,7 @@ where SomeLit(x) => ser_seq!(ser; tag(5), null(), expr(x)), EmptyListLit(x) => match x.as_ref() { Op(App(f, a)) => match f.as_ref() { - ExprKind::Builtin(Builtin::List) => { + ExprKind::Builtin(self::Builtin::List) => { ser_seq!(ser; tag(4), expr(a)) } _ => ser_seq!(ser; tag(28), expr(x)), @@ -138,7 +138,7 @@ where UnionType(map) => ser_seq!(ser; tag(11), UnionMap(map)), Op(Field(x, l)) => ser_seq!(ser; tag(9), expr(x), label(l)), Op(BinOp(op, x, y)) => { - use syntax::BinOp::*; + use self::BinOp::*; let op = match op { BoolOr => 0, BoolAnd => 1, diff --git a/dhall/src/syntax/text/parser.rs b/dhall/src/syntax/text/parser.rs index 8d76225..dbf5c75 100644 --- a/dhall/src/syntax/text/parser.rs +++ b/dhall/src/syntax/text/parser.rs @@ -36,46 +36,6 @@ enum Selector { ProjectionByExpr(Expr), } -impl crate::syntax::Builtin { - pub fn parse(s: &str) -> Option { - use crate::syntax::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), - "Integer/negate" => Some(IntegerNegate), - "Integer/clamp" => Some(IntegerClamp), - "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, - } - } -} - fn input_to_span(input: ParseInput) -> Span { Span::make(input.user_data().clone(), input.as_pair().as_span()) } @@ -129,7 +89,7 @@ fn trim_indent(lines: &mut Vec) { /// Insert the expr into the map; in case of collision, create a RecursiveRecordMerge node. fn insert_recordlit_entry(map: &mut BTreeMap, l: Label, e: Expr) { - use crate::syntax::BinOp::RecursiveRecordMerge; + use crate::operations::BinOp::RecursiveRecordMerge; use std::collections::btree_map::Entry; match map.entry(l) { Entry::Vacant(entry) => { @@ -147,7 +107,7 @@ fn insert_recordlit_entry(map: &mut BTreeMap, l: Label, e: Expr) { } fn desugar_with_expr(x: Expr, labels: &[Label], y: Expr) -> Expr { - use crate::syntax::BinOp::RightBiasedRecordMerge; + use crate::operations::BinOp::RightBiasedRecordMerge; let expr = |k| Expr::new(k, Span::WithSugar); match labels { [] => y, @@ -391,7 +351,7 @@ impl DhallParser { #[alias(expression)] fn builtin(input: ParseInput) -> ParseResult { let s = input.as_str(); - let e = match crate::syntax::Builtin::parse(s) { + let e = match crate::builtins::Builtin::parse(s) { Some(b) => Builtin(b), None => match s { "True" => Num(Bool(true)), @@ -784,7 +744,7 @@ impl DhallParser { op: ParseInput, r: Expr, ) -> ParseResult { - use crate::syntax::BinOp::*; + use crate::operations::BinOp::*; use Rule::*; let op = match op.as_rule() { import_alt => ImportAlt, diff --git a/dhall/src/syntax/text/printer.rs b/dhall/src/syntax/text/printer.rs index a85f435..9e90660 100644 --- a/dhall/src/syntax/text/printer.rs +++ b/dhall/src/syntax/text/printer.rs @@ -1,4 +1,5 @@ -use crate::operations::OpKind; +use crate::builtins::Builtin; +use crate::operations::{BinOp, OpKind}; use crate::syntax::*; use itertools::Itertools; use std::fmt::{self, Display}; @@ -15,7 +16,7 @@ enum PrintPhase { // `operator-expression` Operator, // All the `-expression`s - BinOp(ast::BinOp), + BinOp(self::BinOp), // `application-expression` App, // `import-expression` @@ -335,7 +336,7 @@ impl Display for Const { impl Display for BinOp { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - use crate::syntax::BinOp::*; + use BinOp::*; f.write_str(match self { BoolOr => "||", TextAppend => "++", @@ -383,7 +384,7 @@ impl Display for Label { let is_reserved = match s.as_str() { "let" | "in" | "if" | "then" | "else" | "Type" | "Kind" | "Sort" | "True" | "False" | "Some" => true, - _ => crate::syntax::Builtin::parse(&s).is_some(), + _ => Builtin::parse(&s).is_some(), }; if !is_reserved && s.chars().all(|c| c.is_ascii_alphanumeric()) { write!(f, "{}", s) @@ -481,45 +482,6 @@ impl Display for Import { } } -impl Display for Builtin { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - use crate::syntax::Builtin::*; - f.write_str(match *self { - Bool => "Bool", - Natural => "Natural", - Integer => "Integer", - Double => "Double", - Text => "Text", - List => "List", - Optional => "Optional", - OptionalNone => "None", - NaturalBuild => "Natural/build", - NaturalFold => "Natural/fold", - NaturalIsZero => "Natural/isZero", - NaturalEven => "Natural/even", - NaturalOdd => "Natural/odd", - NaturalToInteger => "Natural/toInteger", - NaturalShow => "Natural/show", - NaturalSubtract => "Natural/subtract", - IntegerToDouble => "Integer/toDouble", - IntegerNegate => "Integer/negate", - IntegerClamp => "Integer/clamp", - IntegerShow => "Integer/show", - DoubleShow => "Double/show", - ListBuild => "List/build", - ListFold => "List/fold", - ListLength => "List/length", - ListHead => "List/head", - ListLast => "List/last", - ListIndexed => "List/indexed", - ListReverse => "List/reverse", - OptionalFold => "Optional/fold", - OptionalBuild => "Optional/build", - TextShow => "Text/show", - }) - } -} - impl Display for Scheme { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use crate::syntax::Scheme::*; diff --git a/serde_dhall/src/value.rs b/serde_dhall/src/value.rs index e8f333e..03cfdba 100644 --- a/serde_dhall/src/value.rs +++ b/serde_dhall/src/value.rs @@ -1,8 +1,9 @@ use std::collections::{BTreeMap, HashMap}; +use dhall::builtins::Builtin; use dhall::operations::OpKind; use dhall::semantics::{Hir, HirKind, Nir, NirKind}; -use dhall::syntax::{Builtin, Expr, ExprKind, NumKind, Span}; +use dhall::syntax::{Expr, ExprKind, NumKind, Span}; use crate::{Error, ErrorKind, FromDhall, Result, Sealed}; -- cgit v1.3.1 From 092b7208ffd22f8facc7af387ac307e59208d52c Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Tue, 7 Apr 2020 11:19:36 +0100 Subject: Move duplicate field checking to parser --- dhall/src/builtins.rs | 8 +- dhall/src/operations.rs | 13 +- dhall/src/semantics/resolve/resolve.rs | 4 +- dhall/src/semantics/tck/typecheck.rs | 61 ++--- dhall/src/syntax/ast/expr.rs | 5 +- dhall/src/syntax/ast/map.rs | 282 --------------------- dhall/src/syntax/ast/mod.rs | 1 - dhall/src/syntax/binary/encode.rs | 13 +- dhall/src/syntax/text/parser.rs | 64 ++++- dhall/tests/type-inference/failure/mixedUnions.txt | 6 +- .../tests/type-inference/failure/recordOfKind.txt | 4 +- .../failure/unit/RecordMixedKinds3.txt | 4 +- .../unit/RecordProjectionDuplicateFields.txt | 8 +- .../failure/unit/RecordTypeDuplicateFields.txt | 8 +- .../failure/unit/RecordTypeValueMember.txt | 4 +- .../unit/RightBiasedRecordMergeMixedKinds2.txt | 4 +- .../unit/RightBiasedRecordMergeMixedKinds3.txt | 4 +- .../failure/unit/UnionTypeDuplicateVariants1.txt | 8 +- .../failure/unit/UnionTypeDuplicateVariants2.txt | 8 +- .../failure/unit/UnionTypeMixedKinds.txt | 6 +- .../failure/unit/UnionTypeMixedKinds2.txt | 6 +- .../failure/unit/UnionTypeMixedKinds3.txt | 6 +- .../failure/unit/UnionTypeNotType.txt | 6 +- tests_buffer | 1 + 24 files changed, 132 insertions(+), 402 deletions(-) delete mode 100644 dhall/src/syntax/ast/map.rs (limited to 'dhall/src/builtins.rs') diff --git a/dhall/src/builtins.rs b/dhall/src/builtins.rs index bb8173c..67929a0 100644 --- a/dhall/src/builtins.rs +++ b/dhall/src/builtins.rs @@ -1,15 +1,15 @@ +use std::collections::{BTreeMap, HashMap}; +use std::convert::TryInto; + use crate::operations::{BinOp, OpKind}; use crate::semantics::{ skip_resolve_expr, typecheck, Hir, HirKind, Nir, NirKind, NzEnv, VarEnv, }; -use crate::syntax::map::DupTreeMap; use crate::syntax::Const::Type; use crate::syntax::{ Const, Expr, ExprKind, InterpolatedText, InterpolatedTextContents, Label, NaiveDouble, NumKind, Span, UnspannedExpr, V, }; -use std::collections::HashMap; -use std::convert::TryInto; /// Built-ins #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] @@ -147,7 +147,7 @@ macro_rules! make_type { ))) }; ({ $($label:ident : $ty:ident),* }) => {{ - let mut kts = DupTreeMap::new(); + let mut kts = BTreeMap::new(); $( kts.insert( Label::from(stringify!($label)), diff --git a/dhall/src/operations.rs b/dhall/src/operations.rs index 1ebf288..8b5fa10 100644 --- a/dhall/src/operations.rs +++ b/dhall/src/operations.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use std::borrow::Cow; use std::cmp::max; -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use crate::builtins::Builtin; use crate::error::{ErrorBuilder, TypeError}; @@ -9,7 +9,6 @@ use crate::semantics::{ merge_maps, mk_span_err, mkerr, ret_kind, ret_op, ret_ref, Binder, Closure, Hir, HirKind, Nir, NirKind, Ret, TextLit, Tir, TyEnv, Type, }; -use crate::syntax::map::DupTreeSet; use crate::syntax::{trivial_result, Const, ExprKind, Label, NumKind, Span}; // Definition order must match precedence order for @@ -60,7 +59,7 @@ pub enum OpKind { /// `e.x` Field(SubExpr, Label), /// `e.{ x, y, z }` - Projection(SubExpr, DupTreeSet