Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dedicated node and constructor for general custom contracts #1964

Merged
merged 7 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ expression: err
---
error: contract broken by the caller of `at`
invalid array indexing
┌─ <stdlib/std.ncl>:162:9
┌─ <stdlib/std.ncl>:166:9
162 │ | std.contract.unstable.IndexedArrayFun 'Index
166 │ | std.contract.unstable.IndexedArrayFun 'Index
│ -------------------------------------------- expected type
┌─ [INPUTS_PATH]/errors/array_at_empty_array.ncl:3:16
Expand All @@ -21,5 +21,3 @@ note:
3 │ std.array.at 0 []
│ ----------------- (1) calling at


Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ expression: err
---
error: contract broken by the caller of `at`
invalid array indexing
┌─ <stdlib/std.ncl>:162:9
┌─ <stdlib/std.ncl>:166:9
162 │ | std.contract.unstable.IndexedArrayFun 'Index
166 │ | std.contract.unstable.IndexedArrayFun 'Index
│ -------------------------------------------- expected type
┌─ [INPUTS_PATH]/errors/array_at_out_of_bound.ncl:3:16
Expand All @@ -21,5 +21,3 @@ note:
3 │ std.array.at 2 [1]
│ ------------------ (1) calling at


Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ expression: err
---
error: contract broken by the caller of `range`
invalid range
┌─ <stdlib/std.ncl>:673:9
┌─ <stdlib/std.ncl>:677:9
673 │ | std.contract.unstable.RangeFun Dyn
677 │ | std.contract.unstable.RangeFun Dyn
│ ---------------------------------- expected type
┌─ [INPUTS_PATH]/errors/array_range_reversed_indices.ncl:3:19
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ expression: err
---
error: contract broken by the caller of `range_step`
invalid range step
┌─ <stdlib/std.ncl>:648:9
┌─ <stdlib/std.ncl>:652:9
648 │ | std.contract.unstable.RangeFun (std.contract.unstable.RangeStep -> Dyn)
652 │ | std.contract.unstable.RangeFun (std.contract.unstable.RangeStep -> Dyn)
│ ----------------------------------------------------------------------- expected type
┌─ [INPUTS_PATH]/errors/array_range_step_negative_step.ncl:3:27
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ source: cli/tests/snapshot/main.rs
expression: err
---
error: contract broken by the caller of `map`
┌─ <stdlib/std.ncl>:146:33
┌─ <stdlib/std.ncl>:150:33
146 │ : forall a b. (a -> b) -> Array a -> Array b
150 │ : forall a b. (a -> b) -> Array a -> Array b
│ ------- expected type of the argument provided by the caller
┌─ [INPUTS_PATH]/errors/caller_contract_violation.ncl:3:31
Expand All @@ -18,5 +18,3 @@ note:
3 │ std.array.map std.function.id 'not-an-array
│ ------------------------------------------- (1) calling map


6 changes: 3 additions & 3 deletions core/src/eval/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ use crate::{
pattern::compile::Compile,
record::{Field, RecordData},
string::NickelString,
BinaryOp, BindingType, CustomContract, LetAttrs, MatchBranch, MatchData, RecordOpKind,
RichTerm, RuntimeContract, StrChunk, Term, UnaryOp,
BinaryOp, BindingType, LetAttrs, MatchBranch, MatchData, RecordOpKind, RichTerm,
RuntimeContract, StrChunk, Term, UnaryOp,
},
};

Expand Down Expand Up @@ -1151,7 +1151,7 @@ pub fn subst<C: Cache>(
// Do not substitute under lambdas: mutually recursive function could cause an infinite
// loop. Although avoidable, this requires some care and is not currently needed.
| v @ Term::Fun(..)
| v @ Term::CustomContract(CustomContract::Predicate(..))
| v @ Term::CustomContract(_)
| v @ Term::Lbl(_)
| v @ Term::ForeignId(_)
| v @ Term::SealingKey(_)
Expand Down
54 changes: 40 additions & 14 deletions core/src/eval/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ impl<R: ImportResolver, C: Cache> VirtualMachine<R, C> {
Term::Str(_) => "String",
Term::Enum(_) | Term::EnumVariant { .. } => "Enum",
Term::Fun(..) | Term::Match { .. } => "Function",
Term::CustomContract(_) => "CustomContract",
Term::Array(..) => "Array",
Term::Record(..) | Term::RecRecord(..) => "Record",
Term::Lbl(..) => "Label",
Expand Down Expand Up @@ -1195,18 +1196,44 @@ impl<R: ImportResolver, C: Cache> VirtualMachine<R, C> {
})
}
UnaryOp::ContractFromPredicate => {
if let Term::Fun(id, body) = &*t {
if matches!(&*t, Term::Fun(..) | Term::Match(_)) {
Ok(Closure {
body: RichTerm::new(
Term::CustomContract(CustomContract::Predicate(*id, body.clone())),
Term::CustomContract(CustomContract::Predicate(RichTerm {
term: t,
pos,
})),
pos,
),
env,
})
} else {
Err(mk_type_error!("contract_from_predicate", "Function"))
Err(mk_type_error!(
"contract/from_predicate",
"Function or MatchExpression"
))
}
}
UnaryOp::ContractCustom => {
if matches!(&*t, Term::Fun(..) | Term::Match(_)) {
Ok(Closure {
body: RichTerm::new(
Term::CustomContract(CustomContract::PartialIdentity(RichTerm {
term: t,
pos,
})),
pos,
),
env,
})
} else {
Err(mk_type_error!(
"contract/custom",
"Function or MatchExpression"
))
}
}

#[cfg(feature = "nix-experimental")]
UnaryOp::EvalNix => {
if let Term::Str(s) = &*t {
Expand Down Expand Up @@ -1540,8 +1567,8 @@ impl<R: ImportResolver, C: Cache> VirtualMachine<R, C> {
pos2.into_inherited(),
);

match *t1 {
Term::Type(ref typ) => Ok(Closure {
match &*t1 {
Term::Type(typ) => Ok(Closure {
body: typ.contract()?,
env: env1,
}),
Expand All @@ -1552,16 +1579,15 @@ impl<R: ImportResolver, C: Cache> VirtualMachine<R, C> {
},
env: env1,
}),
Term::CustomContract(CustomContract::Predicate(ref id, ref body)) => {
Ok(Closure {
body: mk_app!(
internals::predicate_to_ctr(),
RichTerm::new(Term::Fun(*id, body.clone()), pos1)
)
Term::CustomContract(CustomContract::PartialIdentity(ctr)) => Ok(Closure {
body: ctr.clone(),
env: env1,
}),
Term::CustomContract(CustomContract::Predicate(pred)) => Ok(Closure {
body: mk_app!(internals::predicate_to_ctr(), pred.clone())
.with_pos(pos1),
env: env1,
})
}
env: env1,
}),
Term::Record(..) => {
let closurized = RichTerm {
term: t1,
Expand Down
2 changes: 2 additions & 0 deletions core/src/parser/grammar.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,7 @@ UOp: UnaryOp = {
"label/go_array" => UnaryOp::LabelGoArray,
"label/go_dict" => UnaryOp::LabelGoDict,
"contract/from_predicate" => UnaryOp::ContractFromPredicate,
"contract/custom" => UnaryOp::ContractCustom,
"enum/embed" <Ident> => UnaryOp::EnumEmbed(<>),
"array/map" => UnaryOp::ArrayMap,
"array/generate" => UnaryOp::ArrayGen,
Expand Down Expand Up @@ -1514,6 +1515,7 @@ extern {
"contract/array_lazy_app" => Token::Normal(NormalToken::ContractArrayLazyApp),
"contract/record_lazy_app" => Token::Normal(NormalToken::ContractRecordLazyApp),
"contract/from_predicate" => Token::Normal(NormalToken::ContractFromPredicate),
"contract/custom" => Token::Normal(NormalToken::ContractCustom),
"op force" => Token::Normal(NormalToken::OpForce),
"blame" => Token::Normal(NormalToken::Blame),
"label/flip_polarity" => Token::Normal(NormalToken::LabelFlipPol),
Expand Down
2 changes: 2 additions & 0 deletions core/src/parser/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,8 @@ pub enum NormalToken<'input> {
ContractRecordLazyApp,
#[token("%contract/from_predicate%")]
ContractFromPredicate,
#[token("%contract/custom%")]
ContractCustom,
#[token("%blame%")]
Blame,
#[token("%label/flip_polarity%")]
Expand Down
21 changes: 12 additions & 9 deletions core/src/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ where

loop {
match body.as_ref() {
Term::Fun(id, rt) | Term::CustomContract(CustomContract::Predicate(id, rt)) => {
Term::Fun(id, rt) => {
builder = docs![self, builder, self.line(), self.as_string(id)];
body = rt;
}
Expand Down Expand Up @@ -821,18 +821,21 @@ where
Str(v) => allocator.escaped_string(v).double_quotes(),
StrChunks(chunks) => allocator.chunks(chunks, StringRenderStyle::Multiline),
Fun(id, body) => allocator.function(allocator.as_string(id), body),
CustomContract(ContractNode::PartialIdentity(ctr)) => docs![
allocator,
"%contract/custom%",
docs![allocator, allocator.line(), ctr.pretty(allocator).parens()]
.nest(2)
.group()
],
FunPattern(pat, body) => allocator.function(allocator.pat_with_parens(pat), body),
// Format this as the application `std.contract.from_predicate <pred>`.
CustomContract(ContractNode::Predicate(id, pred)) => docs![
CustomContract(ContractNode::Predicate(pred)) => docs![
allocator,
"%contract/from_predicate%",
docs![
allocator,
allocator.line(),
allocator.function(allocator.as_string(id), pred).parens()
]
.nest(2)
.group()
docs![allocator, allocator.line(), pred.pretty(allocator).parens()]
.nest(2)
.group()
],
Lbl(_lbl) => allocator.text("%<label>").append(allocator.line()),
Let(id, rt, body, attrs) => docs![
Expand Down
Loading