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

Allow casting bools to integers (and vice-versa) #278

Merged
merged 6 commits into from
Jul 18, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion crates/noirc_evaluator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ impl<'a> Evaluator<'a> {
}
}
Type::PolymorphicInteger(..) => unreachable!(),
Type::Bool => todo!(),
Type::Bool(_) => todo!(),
Type::Unit => todo!(),
Type::Struct(_, _) => todo!(),
Type::Tuple(_) => todo!(),
Expand Down
3 changes: 2 additions & 1 deletion crates/noirc_evaluator/src/ssa/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,8 @@ impl node::Operation {
) {
match self {
//default way to handle arrays dunring inlining; we map arrays using the stack_frame
Operation::Binary(_) => {
Operation::Binary(_)
| Operation::Constrain(..) => {
self.map_id_mut(|id| {
if let Some(a) = Memory::deref(ctx, id) {
let b = stack_frame.get_or_default(a);
Expand Down
2 changes: 1 addition & 1 deletion crates/noirc_evaluator/src/ssa/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ impl From<ObjectType> for NumericType {
impl From<&Type> for ObjectType {
fn from(t: &noirc_frontend::Type) -> ObjectType {
match t {
Type::Bool => ObjectType::Boolean,
Type::Bool(_) => ObjectType::Boolean,
Type::FieldElement(..) => ObjectType::NativeField,
Type::Integer(_, _ftype, sign, bit_size) => {
assert!(
Expand Down
4 changes: 2 additions & 2 deletions crates/noirc_frontend/src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ pub enum UnresolvedType {
FieldElement(IsConst, FieldElementType),
Array(FieldElementType, ArraySize, Box<UnresolvedType>), // [4]Witness = Array(4, Witness)
Integer(IsConst, FieldElementType, Signedness, u32), // u32 = Integer(unsigned, 32)
Bool,
Bool(IsConst),
Unit,
Struct(FieldElementType, Path),

Expand Down Expand Up @@ -143,7 +143,7 @@ impl std::fmt::Display for UnresolvedType {
let elements = vecmap(elements, ToString::to_string);
write!(f, "({})", elements.join(", "))
}
Bool => write!(f, "bool"),
Bool(is_const) => write!(f, "{}bool", is_const),
Unit => write!(f, "()"),
Error => write!(f, "error"),
Unspecified => write!(f, "unspecified"),
Expand Down
2 changes: 1 addition & 1 deletion crates/noirc_frontend/src/hir/resolution/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ impl<'a> Resolver<'a> {
UnresolvedType::Integer(is_const, vis, sign, bits) => {
Type::Integer(is_const, vis, sign, bits)
}
UnresolvedType::Bool => Type::Bool,
UnresolvedType::Bool(is_const) => Type::Bool(is_const),
UnresolvedType::Unit => Type::Unit,
UnresolvedType::Unspecified => Type::Unspecified,
UnresolvedType::Error => Type::Error,
Expand Down
56 changes: 38 additions & 18 deletions crates/noirc_frontend/src/hir/type_check/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ pub(crate) fn type_check_expression(

arr_type
}
HirLiteral::Bool(_) => Type::Bool,
HirLiteral::Bool(_) => Type::Bool(IsConst::new(interner)),
HirLiteral::Integer(_) => {
let id = interner.next_type_variable_id();
Type::PolymorphicInteger(
IsConst::Maybe(id, Rc::new(RefCell::new(None))),
IsConst::new(interner),
Rc::new(RefCell::new(TypeBinding::Unbound(id))),
)
}
Expand Down Expand Up @@ -264,6 +264,8 @@ fn check_cast(from: Type, to: Type, span: Span, errors: &mut Vec<TypeCheckError>
TypeBinding::Bound(from) => return check_cast(from.clone(), to, span, errors),
TypeBinding::Unbound(_) => is_const,
},
// TODO: Track const for bools
jfecher marked this conversation as resolved.
Show resolved Hide resolved
Type::Bool(is_const) => is_const,
Type::Error => return Type::Error,
from => {
let msg = format!(
Expand Down Expand Up @@ -292,6 +294,13 @@ fn check_cast(from: Type, to: Type, span: Span, errors: &mut Vec<TypeCheckError>

Type::FieldElement(is_const, to_vis)
}
Type::Bool(dest_is_const) => {
if dest_is_const.is_const() && is_const.unify(&dest_is_const, span).is_err() {
let msg = "Cannot cast to a const type, argument to cast is non-const (not known at compile-time)".into();
errors.push(TypeCheckError::Unstructured { msg, span });
}
Type::Bool(dest_is_const)
}
Type::Error => Type::Error,
_ => {
let msg = "Only integer and Field types may be casted to".into();
Expand Down Expand Up @@ -387,7 +396,7 @@ pub fn prefix_operand_type_rules(op: &HirUnaryOp, rhs_type: &Type) -> Result<Typ
}
}
HirUnaryOp::Not => {
if !matches!(rhs_type, Type::Integer(..) | Type::Bool | Type::Error) {
if !matches!(rhs_type, Type::Integer(..) | Type::Bool(_) | Type::Error) {
return Err("Only Integers or Bool can be used in a Not expression".to_string());
}
}
Expand Down Expand Up @@ -428,7 +437,7 @@ pub fn infix_operand_type_rules(
if let TypeBinding::Bound(binding) = &*int.borrow() {
return infix_operand_type_rules(binding, op, other, errors);
}
if other.try_bind_to_polymorphic_int(int, is_const, op.span).is_ok() {
if other.try_bind_to_polymorphic_int(int, is_const, op.span).is_ok() || other == &Type::Error {
jfecher marked this conversation as resolved.
Show resolved Hide resolved
Ok(other.clone())
} else {
Err(format!("Types in a binary operation should match, but found {} and {}", lhs_type, rhs_type))
Expand All @@ -453,7 +462,7 @@ pub fn infix_operand_type_rules(
Ok(FieldElement(is_const, Private))
}

(Bool, Bool) => Ok(Bool),
(Bool(is_const_x), Bool(is_const_y)) => Ok(Bool(is_const_x.and(is_const_y, op.span))),

(lhs, rhs) => Err(format!("Unsupported types for binary operation: {} and {}", lhs, rhs)),
}
Expand All @@ -469,10 +478,12 @@ fn check_if_expr(
let then_type = type_check_expression(interner, &if_expr.consequence, errors);

let expr_span = interner.expr_span(&if_expr.condition);
cond_type.unify(&Type::Bool, expr_span, errors, || TypeCheckError::TypeMismatch {
expected_typ: Type::Bool.to_string(),
expr_typ: cond_type.to_string(),
expr_span,
cond_type.unify(&Type::Bool(IsConst::new(interner)), expr_span, errors, || {
TypeCheckError::TypeMismatch {
expected_typ: Type::Bool(IsConst::No(None)).to_string(),
expr_typ: cond_type.to_string(),
expr_span,
}
});

match if_expr.alternative {
Expand Down Expand Up @@ -589,14 +600,15 @@ pub fn comparator_operand_type_rules(
use HirBinaryOpKind::{Equal, NotEqual};
use Type::*;
match (lhs_type, rhs_type) {
(Integer(_, _, sign_x, bit_width_x), Integer(_, _, sign_y, bit_width_y)) => {
(Integer(is_const_x, _, sign_x, bit_width_x), Integer(is_const_y, _, sign_y, bit_width_y)) => {
if sign_x != sign_y {
return Err(format!("Integers must have the same signedness LHS is {:?}, RHS is {:?} ", sign_x, sign_y))
}
if bit_width_x != bit_width_y {
return Err(format!("Integers must have the same bit width LHS is {}, RHS is {} ", bit_width_x, bit_width_y))
}
Ok(Bool)
let is_const = is_const_x.and(is_const_y, op.span);
Ok(Bool(is_const))
}
(Integer(..), FieldElement(..)) | ( FieldElement(..), Integer(..) ) => {
Err("Cannot use an integer and a Field in a binary operation, try converting the Field into an integer first".to_string())
Expand All @@ -606,23 +618,29 @@ pub fn comparator_operand_type_rules(
if let TypeBinding::Bound(binding) = &*int.borrow() {
return comparator_operand_type_rules(other, binding, op, errors);
}
if other.try_bind_to_polymorphic_int(int, is_const, op.span).is_ok() {
Ok(Bool)
if other.try_bind_to_polymorphic_int(int, is_const, op.span).is_ok() || other == &Type::Error {
Ok(Bool(is_const.clone()))
} else {
Err(format!("Types in a binary operation should match, but found {} and {}", lhs_type, rhs_type))
}
}
(Integer(..), typ) | (typ,Integer(..)) => {
Err(format!("Integer cannot be used with type {}", typ))
}
(FieldElement(..), FieldElement(..)) => Ok(Bool),
(FieldElement(is_const_x, ..), FieldElement(is_const_y, ..)) => {
let is_const = is_const_x.and(is_const_y, op.span);
Ok(Bool(is_const))
}

// <= and friends are technically valid for booleans, just not very useful
(Bool, Bool) => Ok(Bool),
(Bool(is_const_x), Bool(is_const_y)) => {
let is_const = is_const_x.and(is_const_y, op.span);
Ok(Bool(is_const))
}

// Avoid reporting errors multiple times
(Error, _) | (_,Error) => Ok(Bool),
(Unspecified, _) | (_,Unspecified) => Ok(Bool),
(Error, _) | (_,Error) => Ok(Bool(IsConst::Yes(None))),
(Unspecified, _) | (_,Unspecified) => Ok(Bool(IsConst::Yes(None))),

// Special-case == and != for arrays
(Array(_, x_size, x_type), Array(_, y_size, y_type)) if matches!(op.kind, Equal | NotEqual) => {
Expand All @@ -637,7 +655,9 @@ pub fn comparator_operand_type_rules(
return Err(format!("Can only compare arrays of the same length. Here LHS is of length {}, and RHS is {} ",
x_size, y_size));
}
Ok(Bool)

// We could check if all elements of all arrays are const but I am lazy
jfecher marked this conversation as resolved.
Show resolved Hide resolved
Ok(Bool(IsConst::No(Some(op.span))))
}
(lhs, rhs) => Err(format!("Unsupported types for comparison: {} and {}", lhs, rhs)),
}
Expand Down
12 changes: 8 additions & 4 deletions crates/noirc_frontend/src/hir/type_check/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::hir_def::stmt::{
};
use crate::hir_def::types::Type;
use crate::node_interner::{ExprId, NodeInterner, StmtId};
use crate::IsConst;

use super::{errors::TypeCheckError, expr::type_check_expression};

Expand Down Expand Up @@ -200,10 +201,13 @@ fn type_check_constrain_stmt(
let expr_type = type_check_expression(interner, &stmt.0, errors);
let expr_span = interner.expr_span(&stmt.0);

expr_type.unify(&Type::Bool, expr_span, errors, &mut || TypeCheckError::TypeMismatch {
expr_typ: expr_type.to_string(),
expected_typ: Type::Bool.to_string(),
expr_span,
expr_type.unify(&dbg!(Type::Bool(IsConst::new(interner))), expr_span, errors, &mut || {
dbg!(&expr_type);
jfecher marked this conversation as resolved.
Show resolved Hide resolved
TypeCheckError::TypeMismatch {
expr_typ: expr_type.to_string(),
expected_typ: Type::Bool(IsConst::No(None)).to_string(),
expr_span,
}
});
}

Expand Down
32 changes: 15 additions & 17 deletions crates/noirc_frontend/src/hir_def/types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{cell::RefCell, collections::HashMap, rc::Rc};

use crate::hir::type_check::TypeCheckError;
use crate::{hir::type_check::TypeCheckError, node_interner::NodeInterner};
use noirc_abi::{AbiFEType, AbiType};
use noirc_errors::Span;

Expand Down Expand Up @@ -47,7 +47,7 @@ pub enum Type {
Array(FieldElementType, ArraySize, Box<Type>), // [4]Witness = Array(4, Witness)
Integer(IsConst, FieldElementType, Signedness, u32), // u32 = Integer(unsigned, 32)
PolymorphicInteger(IsConst, TypeVariable),
Bool,
Bool(IsConst),
Unit,
Struct(FieldElementType, Rc<RefCell<StructType>>),
Tuple(Vec<Type>),
Expand Down Expand Up @@ -86,6 +86,11 @@ pub enum SpanKind {
}

impl IsConst {
pub fn new(interner: &mut NodeInterner) -> Self {
let id = interner.next_type_variable_id();
Self::Maybe(id, Rc::new(RefCell::new(None)))
}

fn set_span(&mut self, new_span: Span) {
match self {
IsConst::Yes(span) | IsConst::No(span) => *span = Some(new_span),
Expand Down Expand Up @@ -254,7 +259,7 @@ impl std::fmt::Display for Type {
let elements = vecmap(elements, ToString::to_string);
write!(f, "({})", elements.join(", "))
}
Type::Bool => write!(f, "bool"),
Type::Bool(is_const) => write!(f, "{}bool", is_const),
jfecher marked this conversation as resolved.
Show resolved Hide resolved
Type::Unit => write!(f, "()"),
Type::Error => write!(f, "error"),
Type::Unspecified => write!(f, "unspecified"),
Expand Down Expand Up @@ -455,6 +460,8 @@ impl Type {
}
}

(Bool(const_a), Bool(const_b)) => const_a.unify(const_b, span),

(other_a, other_b) => {
if other_a == other_b {
Ok(())
Expand Down Expand Up @@ -545,6 +552,8 @@ impl Type {
}
}

(Bool(const_a), Bool(const_b)) => const_a.is_subtype_of(const_b, span),

(other_a, other_b) => {
if other_a == other_b {
Ok(())
Expand All @@ -567,32 +576,21 @@ impl Type {
Type::FieldElement(..)
| Type::Integer(..)
| Type::PolymorphicInteger(..)
| Type::Bool
| Type::Bool(_)
| Type::Error
| Type::Unspecified
| Type::Unit => 1,
}
}

pub fn can_be_used_in_constrain(&self) -> bool {
matches!(
self,
Type::FieldElement(..)
| Type::Integer(..)
| Type::PolymorphicInteger(..)
| Type::Array(_, _, _)
| Type::Error
| Type::Bool
)
}

pub fn is_fixed_sized_array(&self) -> bool {
let (sized, _) = match self.array() {
None => return false,
Some(arr) => arr,
};
sized.is_fixed()
}

pub fn is_variable_sized_array(&self) -> bool {
let (sized, _) = match self.array() {
None => return false,
Expand Down Expand Up @@ -652,7 +650,7 @@ impl Type {
TypeBinding::Bound(typ) => typ.as_abi_type(),
TypeBinding::Unbound(_) => Type::default_int_type(None).as_abi_type(),
},
Type::Bool => panic!("currently, cannot have a bool in the entry point function"),
Type::Bool(_) => panic!("currently, cannot have a bool in the entry point function"),
Type::Error => unreachable!(),
Type::Unspecified => unreachable!(),
Type::Unit => unreachable!(),
Expand Down
3 changes: 3 additions & 0 deletions crates/noirc_frontend/src/lexer/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@ pub enum Keyword {
// Field types
Pub,
Const,
Bool,
//
SetPub,
//
Expand Down Expand Up @@ -409,6 +410,7 @@ impl fmt::Display for Keyword {
Keyword::Pub => write!(f, "pub"),
Keyword::Field => write!(f, "Field"),
Keyword::Const => write!(f, "const"),
Keyword::Bool => write!(f, "bool"),
}
}
}
Expand Down Expand Up @@ -442,6 +444,7 @@ impl Keyword {

// Native Types
"Field" => Keyword::Field,
"bool" => Keyword::Bool,

"true" => return Some(Token::Bool(true)),
"false" => return Some(Token::Bool(false)),
Expand Down
5 changes: 5 additions & 0 deletions crates/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@ where
struct_type(visibility_parser.clone()),
array_type(visibility_parser, recursive_type_parser.clone()),
tuple_type(recursive_type_parser),
bool_type(),
))
}

Expand Down Expand Up @@ -411,6 +412,10 @@ where
.map(|(vis, is_const)| UnresolvedType::FieldElement(is_const, vis))
}

fn bool_type() -> impl NoirParser<UnresolvedType> {
maybe_const().then_ignore(keyword(Keyword::Bool)).map(UnresolvedType::Bool)
}

fn int_type<P>(visibility_parser: P) -> impl NoirParser<UnresolvedType>
where
P: NoirParser<FieldElementType>,
Expand Down