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

chore: single integral type #6843

Draft
wants to merge 17 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
10 changes: 7 additions & 3 deletions compiler/noirc_driver/src/abi_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ fn build_abi_error_type(context: &Context, typ: ErrorType) -> AbiErrorType {

pub(super) fn abi_type_from_hir_type(context: &Context, typ: &Type) -> AbiType {
match typ {
Type::FieldElement => AbiType::Field,
Type::Array(size, typ) => {
let span = get_main_function_span(context);
let length = size
Expand All @@ -82,6 +81,13 @@ pub(super) fn abi_type_from_hir_type(context: &Context, typ: &Type) -> AbiType {
AbiType::Array { length, typ: Box::new(abi_type_from_hir_type(context, typ)) }
}
Type::Integer(sign, bit_width) => {
if bit_width.is_zero() {
unreachable!("{typ} cannot be used in the abi")
} else if bit_width.is_one() {
return AbiType::Boolean;
} else if bit_width.is_field_element_bits() {
return AbiType::Field;
}
let sign = match sign {
Signedness::Unsigned => Sign::Unsigned,
Signedness::Signed => Sign::Signed,
Expand All @@ -101,7 +107,6 @@ pub(super) fn abi_type_from_hir_type(context: &Context, typ: &Type) -> AbiType {
unreachable!("{typ} cannot be used in the abi")
}
}
Type::Bool => AbiType::Boolean,
Type::String(size) => {
let span = get_main_function_span(context);
let size = size
Expand All @@ -126,7 +131,6 @@ pub(super) fn abi_type_from_hir_type(context: &Context, typ: &Type) -> AbiType {
AbiType::Tuple { fields }
}
Type::Error
| Type::Unit
| Type::Constant(..)
| Type::InfixExpr(..)
| Type::TraitAsType(..)
Expand Down
33 changes: 25 additions & 8 deletions compiler/noirc_frontend/src/ast/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,24 @@ impl UnresolvedGeneric {
&self,
typ: &UnresolvedType,
) -> Result<Type, UnsupportedNumericGenericType> {
use crate::ast::UnresolvedTypeData::{FieldElement, Integer};
use crate::ast::UnresolvedTypeData::Integer;

match typ.typ {
FieldElement => Ok(Type::FieldElement),
Integer(sign, bits) => Ok(Type::Integer(sign, bits)),
// Only fields and integers are supported for numeric kinds
_ => Err(UnsupportedNumericGenericType {
let unsupported_numeric_generic_type = || {
Err(UnsupportedNumericGenericType {
ident: self.ident().clone(),
typ: typ.typ.clone(),
}),
})
};

match typ.typ {
Integer(sign, num_bits) => {
if !num_bits.is_integer_or_field_size() {
return unsupported_numeric_generic_type();
}
Ok(Type::Integer(sign, num_bits))
},
// Only fields and integers are supported for numeric kinds
_ => unsupported_numeric_generic_type(),
}
}

Expand Down Expand Up @@ -345,6 +353,15 @@ impl BinaryOpKind {
)
}

pub fn is_bitwise(&self) -> bool {
matches!(
self,
BinaryOpKind::And
| BinaryOpKind::Or
| BinaryOpKind::Xor
)
}

pub fn is_valid_for_field_type(self) -> bool {
matches!(
self,
Expand Down Expand Up @@ -888,7 +905,7 @@ impl FunctionReturnType {
pub fn get_type(&self) -> Cow<UnresolvedType> {
match self {
FunctionReturnType::Default(span) => {
Cow::Owned(UnresolvedType { typ: UnresolvedTypeData::Unit, span: *span })
Cow::Owned(UnresolvedTypeData::unit().with_span(*span))
}
FunctionReturnType::Ty(typ) => Cow::Borrowed(typ),
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/ast/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl NoirFunction {

pub fn return_type(&self) -> UnresolvedType {
match &self.def.return_type {
FunctionReturnType::Default(span) => UnresolvedTypeData::Unit.with_span(*span),
FunctionReturnType::Default(span) => UnresolvedTypeData::unit().with_span(*span),
FunctionReturnType::Ty(ty) => ty.clone(),
}
}
Expand Down
115 changes: 86 additions & 29 deletions compiler/noirc_frontend/src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,40 +43,80 @@ use iter_extended::vecmap;
#[cfg_attr(test, derive(Arbitrary))]
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Ord, PartialOrd)]
pub enum IntegerBitSize {
One,
Zero, // bit size of Unit
One(/* is_bool */ bool),
Eight,
Sixteen,
ThirtyTwo,
SixtyFour,
FieldElementBits, // max bit size of FieldElement
}

impl IntegerBitSize {
pub fn bit_size(&self) -> u8 {
match self {
IntegerBitSize::One => 1,
IntegerBitSize::Zero => 0,
IntegerBitSize::One(_) => 1,
IntegerBitSize::Eight => 8,
IntegerBitSize::Sixteen => 16,
IntegerBitSize::ThirtyTwo => 32,
IntegerBitSize::SixtyFour => 64,
IntegerBitSize::FieldElementBits => {
FieldElement::max_num_bits().try_into().expect("ICE: FieldElement has more than u8::MAX bits")
}
}
}

pub fn bool() -> IntegerBitSize {
IntegerBitSize::One(true)
}

pub fn u1() -> IntegerBitSize {
IntegerBitSize::One(false)
}

pub fn is_zero(&self) -> bool {
matches!(self, IntegerBitSize::Zero)
}

pub fn is_u1(&self) -> bool {
matches!(self, IntegerBitSize::One(false))
}

pub fn is_bool(&self) -> bool {
matches!(self, IntegerBitSize::One(false))
}

pub fn is_field_element_bits(&self) -> bool {
matches!(self, IntegerBitSize::FieldElementBits)
}

pub fn is_integer_size(&self) -> bool {
!self.is_zero() && !self.is_bool() && !self.is_field_element_bits()
}

pub fn is_integer_or_field_size(&self) -> bool {
!self.is_zero() && !self.is_bool()
}
}

impl IntegerBitSize {
pub fn allowed_sizes() -> Vec<Self> {
vec![Self::One, Self::Eight, Self::ThirtyTwo, Self::SixtyFour]
vec![Self::bool(), Self::u1(), Self::Eight, Self::ThirtyTwo, Self::SixtyFour]
}
}

impl From<IntegerBitSize> for u32 {
fn from(size: IntegerBitSize) -> u32 {
use IntegerBitSize::*;
match size {
One => 1,
Zero => 0,
One(_) => 1,
Eight => 8,
Sixteen => 16,
ThirtyTwo => 32,
SixtyFour => 64,
FieldElementBits => FieldElement::max_num_bits(),
}
}
}
Expand All @@ -88,8 +128,12 @@ impl TryFrom<u32> for IntegerBitSize {

fn try_from(value: u32) -> Result<Self, Self::Error> {
use IntegerBitSize::*;
if value == FieldElement::max_num_bits() {
return Ok(FieldElementBits);
}
match value {
1 => Ok(One),
0 => Ok(Zero),
1 => Ok(One(/* is_bool */ false)),
8 => Ok(Eight),
16 => Ok(Sixteen),
32 => Ok(ThirtyTwo),
Expand All @@ -110,15 +154,12 @@ impl core::fmt::Display for IntegerBitSize {
/// for structs within, but are otherwise identical to Types.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum UnresolvedTypeData {
FieldElement,
Array(UnresolvedTypeExpression, Box<UnresolvedType>), // [Field; 4] = Array(4, Field)
Slice(Box<UnresolvedType>),
Integer(Signedness, IntegerBitSize), // u32 = Integer(unsigned, ThirtyTwo)
Bool,
Expression(UnresolvedTypeExpression),
String(UnresolvedTypeExpression),
FormatString(UnresolvedTypeExpression, Box<UnresolvedType>),
Unit,

Parenthesized(Box<UnresolvedType>),

Expand Down Expand Up @@ -287,21 +328,19 @@ impl std::fmt::Display for UnresolvedTypeData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use UnresolvedTypeData::*;
match self {
FieldElement => write!(f, "Field"),
Array(len, typ) => write!(f, "[{typ}; {len}]"),
Slice(typ) => write!(f, "[{typ}]"),
Integer(sign, num_bits) => match sign {
Signedness::Signed => write!(f, "i{num_bits}"),
Signedness::Unsigned => write!(f, "u{num_bits}"),
},
// NOTE: identical to implementation in Display for Type
Integer(sign, num_bits) => {
write!(f, "{}", crate::Type::Integer(*sign, *num_bits))
}
Named(s, args, _) => write!(f, "{s}{args}"),
TraitAsType(s, args) => write!(f, "impl {s}{args}"),
Tuple(elements) => {
let elements = vecmap(elements, ToString::to_string);
write!(f, "({})", elements.join(", "))
}
Expression(expression) => expression.fmt(f),
Bool => write!(f, "bool"),
String(len) => write!(f, "str<{len}>"),
FormatString(len, elements) => write!(f, "fmt<{len}, {elements}"),
Function(args, ret, env, unconstrained) => {
Expand All @@ -310,21 +349,18 @@ impl std::fmt::Display for UnresolvedTypeData {
}

let args = vecmap(args, ToString::to_string).join(", ");

match &env.as_ref().typ {
UnresolvedTypeData::Unit => {
write!(f, "fn({args}) -> {ret}")
}
UnresolvedTypeData::Tuple(env_types) => {
let env_types = vecmap(env_types, |arg| arg.typ.to_string()).join(", ");
write!(f, "fn[{env_types}]({args}) -> {ret}")
}
other => write!(f, "fn[{other}]({args}) -> {ret}"),
let env_typ = &env.as_ref().typ;
if env_typ.is_unit() {
write!(f, "fn({args}) -> {ret}")
} else if let UnresolvedTypeData::Tuple(env_types) = env_typ {
let env_types = vecmap(env_types, |arg| arg.typ.to_string()).join(", ");
write!(f, "fn[{env_types}]({args}) -> {ret}")
} else {
write!(f, "fn[{env_typ}]({args}) -> {ret}")
}
}
MutableReference(element) => write!(f, "&mut {element}"),
Quoted(quoted) => write!(f, "{}", quoted),
Unit => write!(f, "()"),
Error => write!(f, "error"),
Unspecified => write!(f, "unspecified"),
Parenthesized(typ) => write!(f, "({typ})"),
Expand Down Expand Up @@ -437,17 +473,38 @@ impl UnresolvedTypeData {
}
UnresolvedTypeData::Unspecified => true,

UnresolvedTypeData::FieldElement
| UnresolvedTypeData::Integer(_, _)
| UnresolvedTypeData::Bool
| UnresolvedTypeData::Unit
UnresolvedTypeData::Integer(_, _)
| UnresolvedTypeData::Quoted(_)
| UnresolvedTypeData::AsTraitPath(_)
| UnresolvedTypeData::Resolved(_)
| UnresolvedTypeData::Interned(_)
| UnresolvedTypeData::Error => false,
}
}

pub(crate) fn unit() -> UnresolvedTypeData {
UnresolvedTypeData::Integer(Signedness::Unsigned, IntegerBitSize::Zero)
}

pub(crate) fn bool() -> UnresolvedTypeData {
UnresolvedTypeData::Integer(Signedness::Unsigned, IntegerBitSize::bool())
}

pub(crate) fn field_element() -> UnresolvedTypeData {
UnresolvedTypeData::Integer(Signedness::Unsigned, IntegerBitSize::FieldElementBits)
}

pub(crate) fn is_unit(&self) -> bool {
matches!(self, UnresolvedTypeData::Integer(Signedness::Unsigned, IntegerBitSize::Zero))
}

pub(crate) fn is_bool(&self) -> bool {
matches!(self, UnresolvedTypeData::Integer(Signedness::Unsigned, IntegerBitSize::One(/* is_bool */ true)))
}

pub(crate) fn is_field_element(&self) -> bool {
matches!(self, UnresolvedTypeData::Integer(Signedness::Unsigned, IntegerBitSize::FieldElementBits))
}
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)]
Expand Down
9 changes: 0 additions & 9 deletions compiler/noirc_frontend/src/ast/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,14 +414,8 @@ pub trait Visitor {

fn visit_quoted_type(&mut self, _: &QuotedType, _: Span) {}

fn visit_field_element_type(&mut self, _: Span) {}

fn visit_integer_type(&mut self, _: Signedness, _: IntegerBitSize, _: Span) {}

fn visit_bool_type(&mut self, _: Span) {}

fn visit_unit_type(&mut self, _: Span) {}

fn visit_resolved_type(&mut self, _: QuotedTypeId, _: Span) {}

fn visit_interned_type(&mut self, _: InternedUnresolvedTypeData, _: Span) {}
Expand Down Expand Up @@ -1321,12 +1315,9 @@ impl UnresolvedType {
UnresolvedTypeData::String(expr) => visitor.visit_string_type(expr, self.span),
UnresolvedTypeData::Unspecified => visitor.visit_unspecified_type(self.span),
UnresolvedTypeData::Quoted(typ) => visitor.visit_quoted_type(typ, self.span),
UnresolvedTypeData::FieldElement => visitor.visit_field_element_type(self.span),
UnresolvedTypeData::Integer(signdness, size) => {
visitor.visit_integer_type(*signdness, *size, self.span);
}
UnresolvedTypeData::Bool => visitor.visit_bool_type(self.span),
UnresolvedTypeData::Unit => visitor.visit_unit_type(self.span),
UnresolvedTypeData::Resolved(id) => visitor.visit_resolved_type(*id, self.span),
UnresolvedTypeData::Interned(id) => visitor.visit_interned_type(*id, self.span),
UnresolvedTypeData::Error => visitor.visit_error_type(self.span),
Expand Down
Loading
Loading