Skip to content

Commit

Permalink
feat: visibility for impl functions (noir-lang/noir#6179)
Browse files Browse the repository at this point in the history
feat: Inclusive for loop (noir-lang/noir#6200)
chore: Release Noir(0.35.0) (noir-lang/noir#6030)
chore: revert mistaken stack size change (noir-lang/noir#6212)
chore: fix typo in code snippet (noir-lang/noir#6211)
feat: Sync from aztec-packages (noir-lang/noir#6210)
fix: ignore compression of blocks after msg.len in sha256_var (noir-lang/noir#6206)
feat(perf): Optimize array set from get (noir-lang/noir#6207)
chore(refactor): Array set optimization context struct for analysis (noir-lang/noir#6204)
fix: type variables by default should have Any kind (noir-lang/noir#6203)
feat: remove orphaned blocks from cfg to improve `simplify_cfg` pass. (noir-lang/noir#6198)
fix(ssa): Check if result of array set is used in value of another array set (noir-lang/noir#6197)
fix(docs): Rename recursion.md to recursion.mdx (noir-lang/noir#6195)
feat: skip `remove_enable_side_effects` pass on brillig functions (noir-lang/noir#6199)
feat!: Syncing TypeVariableKind with Kind (noir-lang/noir#6094)
feat(perf): Simplify the cfg after DIE (noir-lang/noir#6184)
feat: refactor SSA passes to run on individual functions (noir-lang/noir#6072)
chore: Remove macros_api module (noir-lang/noir#6190)
fix: ensure to_bytes returns the canonical decomposition (noir-lang/noir#6084)
chore: rename `DefinitionKind::GenericType` (noir-lang/noir#6182)
  • Loading branch information
AztecBot committed Oct 3, 2024
2 parents 605d092 + 93d85a5 commit b0b5518
Show file tree
Hide file tree
Showing 46 changed files with 444 additions and 181 deletions.
2 changes: 1 addition & 1 deletion .noir-sync-commit
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2a0d211b92d002fa75855d4ba27267f8892dd52c
1b26440889379f491315cd9d088537b1898d57c5
62 changes: 57 additions & 5 deletions noir/noir-repo/compiler/noirc_frontend/src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use iter_extended::vecmap;
use noirc_errors::{Span, Spanned};

use super::{
BlockExpression, ConstructorExpression, Expression, ExpressionKind, GenericTypeArgs,
IndexExpression, ItemVisibility, MemberAccessExpression, MethodCallExpression, UnresolvedType,
BinaryOpKind, BlockExpression, ConstructorExpression, Expression, ExpressionKind,
GenericTypeArgs, IndexExpression, InfixExpression, ItemVisibility, MemberAccessExpression,
MethodCallExpression, UnresolvedType,
};
use crate::ast::UnresolvedTypeData;
use crate::elaborator::types::SELF_TYPE_NAME;
Expand Down Expand Up @@ -770,13 +771,57 @@ impl LValue {
}
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ForBounds {
pub start: Expression,
pub end: Expression,
pub inclusive: bool,
}

impl ForBounds {
/// Create a half-open range bounded inclusively below and exclusively above (`start..end`),
/// desugaring `start..=end` into `start..end+1` if necessary.
///
/// Returns the `start` and `end` expressions.
pub(crate) fn into_half_open(self) -> (Expression, Expression) {
let end = if self.inclusive {
let end_span = self.end.span;
let end = ExpressionKind::Infix(Box::new(InfixExpression {
lhs: self.end,
operator: Spanned::from(end_span, BinaryOpKind::Add),
rhs: Expression::new(ExpressionKind::integer(FieldElement::from(1u32)), end_span),
}));
Expression::new(end, end_span)
} else {
self.end
};

(self.start, end)
}
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ForRange {
Range(/*start:*/ Expression, /*end:*/ Expression),
Range(ForBounds),
Array(Expression),
}

impl ForRange {
/// Create a half-open range, bounded inclusively below and exclusively above.
pub fn range(start: Expression, end: Expression) -> Self {
Self::Range(ForBounds { start, end, inclusive: false })
}

/// Create a range bounded inclusively below and above.
pub fn range_inclusive(start: Expression, end: Expression) -> Self {
Self::Range(ForBounds { start, end, inclusive: true })
}

/// Create a range over some array.
pub fn array(value: Expression) -> Self {
Self::Array(value)
}

/// Create a 'for' expression taking care of desugaring a 'for e in array' loop
/// into the following if needed:
///
Expand Down Expand Up @@ -879,7 +924,7 @@ impl ForRange {
let for_loop = Statement {
kind: StatementKind::For(ForLoopStatement {
identifier: fresh_identifier,
range: ForRange::Range(start_range, end_range),
range: ForRange::range(start_range, end_range),
block: new_block,
span: for_loop_span,
}),
Expand Down Expand Up @@ -1009,7 +1054,14 @@ impl Display for Pattern {
impl Display for ForLoopStatement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let range = match &self.range {
ForRange::Range(start, end) => format!("{start}..{end}"),
ForRange::Range(bounds) => {
format!(
"{}{}{}",
bounds.start,
if bounds.inclusive { "..=" } else { ".." },
bounds.end
)
}
ForRange::Array(expr) => expr.to_string(),
};

Expand Down
8 changes: 4 additions & 4 deletions noir/noir-repo/compiler/noirc_frontend/src/ast/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ use crate::{
};

use super::{
FunctionReturnType, GenericTypeArgs, IntegerBitSize, ItemVisibility, Pattern, Signedness,
TraitImplItemKind, TypePath, UnresolvedGenerics, UnresolvedTraitConstraint, UnresolvedType,
UnresolvedTypeData, UnresolvedTypeExpression,
ForBounds, FunctionReturnType, GenericTypeArgs, IntegerBitSize, ItemVisibility, Pattern,
Signedness, TraitImplItemKind, TypePath, UnresolvedGenerics, UnresolvedTraitConstraint,
UnresolvedType, UnresolvedTypeData, UnresolvedTypeExpression,
};

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -1192,7 +1192,7 @@ impl ForRange {

pub fn accept_children(&self, visitor: &mut impl Visitor) {
match self {
ForRange::Range(start, end) => {
ForRange::Range(ForBounds { start, end, inclusive: _ }) => {
start.accept(visitor);
end.accept(visitor);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1125,7 +1125,7 @@ impl<'context> Elaborator<'context> {
// object types in each method overlap or not. If they do, we issue an error.
// If not, that is specialization which is allowed.
let name = method.name_ident().clone();
if module.declare_function(name, ItemVisibility::Public, *method_id).is_err() {
if module.declare_function(name, method.def.visibility, *method_id).is_err() {
let existing = module.find_func_with_name(method.name_ident()).expect(
"declare_function should only error if there is an existing function",
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,13 @@ impl<'context> Elaborator<'context> {
}

fn resolve_path_in_module(&mut self, path: Path, module_id: ModuleId) -> PathResolutionResult {
let resolver = StandardPathResolver::new(module_id);
let self_type_module_id = if let Some(Type::Struct(struct_type, _)) = &self.self_type {
Some(struct_type.borrow().id.module_id())
} else {
None
};

let resolver = StandardPathResolver::new(module_id, self_type_module_id);

if !self.interner.lsp_mode {
return resolver.resolve(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ impl<'context> Elaborator<'context> {

pub(super) fn elaborate_for(&mut self, for_loop: ForLoopStatement) -> (HirStatement, Type) {
let (start, end) = match for_loop.range {
ForRange::Range(start, end) => (start, end),
ForRange::Range(bounds) => bounds.into_half_open(),
ForRange::Array(_) => {
let for_stmt =
for_loop.range.into_for(for_loop.identifier, for_loop.block, for_loop.span);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
ast::{
ArrayLiteral, AsTraitPath, AssignStatement, BlockExpression, CallExpression,
CastExpression, ConstrainStatement, ConstructorExpression, Expression, ExpressionKind,
ForLoopStatement, ForRange, GenericTypeArgs, IfExpression, IndexExpression,
ForBounds, ForLoopStatement, ForRange, GenericTypeArgs, IfExpression, IndexExpression,
InfixExpression, LValue, Lambda, LetStatement, Literal, MemberAccessExpression,
MethodCallExpression, Pattern, PrefixExpression, Statement, StatementKind, UnresolvedType,
UnresolvedTypeData,
Expand Down Expand Up @@ -267,6 +267,7 @@ impl<'interner> TokenPrettyPrinter<'interner> {
| Token::Dot
| Token::DoubleColon
| Token::DoubleDot
| Token::DoubleDotEqual
| Token::Caret
| Token::Pound
| Token::Pipe
Expand Down Expand Up @@ -713,10 +714,13 @@ fn remove_interned_in_statement_kind(
}),
StatementKind::For(for_loop) => StatementKind::For(ForLoopStatement {
range: match for_loop.range {
ForRange::Range(from, to) => ForRange::Range(
remove_interned_in_expression(interner, from),
remove_interned_in_expression(interner, to),
),
ForRange::Range(ForBounds { start, end, inclusive }) => {
ForRange::Range(ForBounds {
start: remove_interned_in_expression(interner, start),
end: remove_interned_in_expression(interner, end),
inclusive,
})
}
ForRange::Array(expr) => {
ForRange::Array(remove_interned_in_expression(interner, expr))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl HirStatement {
}),
HirStatement::For(for_stmt) => StatementKind::For(ForLoopStatement {
identifier: for_stmt.identifier.to_display_ast(interner),
range: ForRange::Range(
range: ForRange::range(
for_stmt.start_range.to_display_ast(interner),
for_stmt.end_range.to_display_ast(interner),
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1514,7 +1514,8 @@ fn expr_as_for_range(
) -> IResult<Value> {
expr_as(interner, arguments, return_type, location, |expr| {
if let ExprValue::Statement(StatementKind::For(for_statement)) = expr {
if let ForRange::Range(from, to) = for_statement.range {
if let ForRange::Range(bounds) = for_statement.range {
let (from, to) = bounds.into_half_open();
let identifier =
Value::Quoted(Rc::new(vec![Token::Ident(for_statement.identifier.0.contents)]));
let from = Value::expression(from.kind);
Expand Down
16 changes: 15 additions & 1 deletion noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ fn interpret_helper(src: &str) -> Result<Value, InterpreterError> {
location,
Vec::new(),
Vec::new(),
false,
false, // is contract
false, // is struct
)));
assert_eq!(root, module_id);

Expand Down Expand Up @@ -160,6 +161,19 @@ fn for_loop() {
assert_eq!(result, Value::U8(15));
}

#[test]
fn for_loop_inclusive() {
let program = "comptime fn main() -> pub u8 {
let mut x = 0;
for i in 0 ..= 6 {
x += i;
}
x
}";
let result = interpret(program);
assert_eq!(result, Value::U8(21));
}

#[test]
fn for_loop_u16() {
let program = "comptime fn main() -> pub u16 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ fn inject_prelude(
if let Ok(PathResolution { module_def_id, error }) = path_resolver::resolve_path(
&context.def_maps,
ModuleId { krate: crate_id, local_id: crate_root },
None,
path,
&mut context.def_interner.usage_tracker,
&mut None,
Expand All @@ -571,6 +572,7 @@ fn inject_prelude(
ImportDirective {
visibility: ItemVisibility::Private,
module_id: crate_root,
self_type_module_id: None,
path: Path { segments, kind: PathKind::Plain, span: Span::default() },
alias: None,
is_prelude: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ pub fn collect_defs(
collector.def_collector.imports.push(ImportDirective {
visibility: import.visibility,
module_id: collector.module_id,
self_type_module_id: None,
path: import.path,
alias: import.alias,
is_prelude: false,
Expand Down Expand Up @@ -385,7 +386,8 @@ impl<'a> ModCollector<'a> {
Vec::new(),
Vec::new(),
false,
false,
false, // is contract
false, // is struct
) {
Ok(module_id) => TraitId(ModuleId { krate, local_id: module_id.local_id }),
Err(error) => {
Expand Down Expand Up @@ -619,6 +621,7 @@ impl<'a> ModCollector<'a> {
submodule.contents.inner_attributes.clone(),
true,
submodule.is_contract,
false, // is struct
) {
Ok(child) => {
self.collect_attributes(
Expand Down Expand Up @@ -718,7 +721,8 @@ impl<'a> ModCollector<'a> {
mod_decl.outer_attributes.clone(),
ast.inner_attributes.clone(),
true,
false,
false, // is contract
false, // is struct
) {
Ok(child_mod_id) => {
self.collect_attributes(
Expand Down Expand Up @@ -770,6 +774,7 @@ impl<'a> ModCollector<'a> {
inner_attributes: Vec<SecondaryAttribute>,
add_to_parent_scope: bool,
is_contract: bool,
is_struct: bool,
) -> Result<ModuleId, DefCollectorErrorKind> {
push_child_module(
&mut context.def_interner,
Expand All @@ -782,6 +787,7 @@ impl<'a> ModCollector<'a> {
inner_attributes,
add_to_parent_scope,
is_contract,
is_struct,
)
}

Expand Down Expand Up @@ -817,6 +823,7 @@ fn push_child_module(
inner_attributes: Vec<SecondaryAttribute>,
add_to_parent_scope: bool,
is_contract: bool,
is_struct: bool,
) -> Result<ModuleId, DefCollectorErrorKind> {
// Note: the difference between `location` and `mod_location` is:
// - `mod_location` will point to either the token "foo" in `mod foo { ... }`
Expand All @@ -826,8 +833,14 @@ fn push_child_module(
// Eventually the location put in `ModuleData` is used for codelenses about `contract`s,
// so we keep using `location` so that it continues to work as usual.
let location = Location::new(mod_name.span(), mod_location.file);
let new_module =
ModuleData::new(Some(parent), location, outer_attributes, inner_attributes, is_contract);
let new_module = ModuleData::new(
Some(parent),
location,
outer_attributes,
inner_attributes,
is_contract,
is_struct,
);

let module_id = def_map.modules.insert(new_module);
let modules = &mut def_map.modules;
Expand Down Expand Up @@ -962,8 +975,9 @@ pub fn collect_struct(
location,
Vec::new(),
Vec::new(),
false,
false,
false, // add to parent scope
false, // is contract
true, // is struct
) {
Ok(module_id) => {
interner.new_struct(&unresolved, resolved_generics, krate, module_id.local_id, file_id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ impl CrateDefMap {
location,
Vec::new(),
ast.inner_attributes.clone(),
false,
false, // is contract
false, // is struct
));

let def_map = CrateDefMap {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ pub struct ModuleData {
/// True if this module is a `contract Foo { ... }` module containing contract functions
pub is_contract: bool,

/// True if this module is actually a struct
pub is_struct: bool,

pub attributes: Vec<SecondaryAttribute>,
}

Expand All @@ -36,6 +39,7 @@ impl ModuleData {
outer_attributes: Vec<SecondaryAttribute>,
inner_attributes: Vec<SecondaryAttribute>,
is_contract: bool,
is_struct: bool,
) -> ModuleData {
let mut attributes = outer_attributes;
attributes.extend(inner_attributes);
Expand All @@ -47,6 +51,7 @@ impl ModuleData {
definitions: ItemScope::default(),
location,
is_contract,
is_struct,
attributes,
}
}
Expand Down
Loading

0 comments on commit b0b5518

Please sign in to comment.