Skip to content

Commit

Permalink
feat(formatter): add formatter support for array literals (noir-lang#…
Browse files Browse the repository at this point in the history
…3061)

Co-authored-by: kevaundray <kevtheappdev@gmail.com>
  • Loading branch information
2 people authored and Sakapoi committed Oct 19, 2023
1 parent 05bba0f commit 9816168
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ fn sum_x(notes: [Field; 2], x: Field, y: Field) -> Field {
}

unconstrained fn create_notes(x: Field, y: Field) -> [Field; 2] {
[x,y]
}
[x, y]
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn test5(a : u32) {


fn issue_661_foo(array: [u32;4], b:u32) ->[u32;1] {
[array[0]+b]
[array[0] + b]
}

fn issue_661_bar(a : [u32;4]) ->[u32;4] {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Example that uses the distinct keyword
fn main(x: pub Field) -> distinct pub [Field;2] {
[x+1, x]
[x + 1, x]
}
19 changes: 18 additions & 1 deletion tooling/nargo_fmt/src/visitor/expr.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use noirc_frontend::{
hir::resolution::errors::Span, BlockExpression, Expression, ExpressionKind, Statement,
hir::resolution::errors::Span, ArrayLiteral, BlockExpression, Expression, ExpressionKind,
Literal, Statement,
};

use super::FmtVisitor;
Expand Down Expand Up @@ -38,6 +39,22 @@ impl FmtVisitor<'_> {
self.format_expr(infix.rhs)
)
}
ExpressionKind::Literal(literal) => match literal {
Literal::Integer(_) => slice!(self, span.start(), span.end()).to_string(),
Literal::Array(ArrayLiteral::Repeated { repeated_element, length }) => {
format!("[{}; {length}]", self.format_expr(*repeated_element))
}
// TODO: Handle line breaks when array gets too long.
Literal::Array(ArrayLiteral::Standard(exprs)) => {
let contents: Vec<String> =
exprs.into_iter().map(|expr| self.format_expr(expr)).collect();
format!("[{}]", contents.join(", "))
}

Literal::Bool(_) | Literal::Str(_) | Literal::FmtStr(_) | Literal::Unit => {
literal.to_string()
}
},
// TODO:
_expr => slice!(self, span.start(), span.end()).to_string(),
}
Expand Down
13 changes: 13 additions & 0 deletions tooling/nargo_fmt/tests/expected/literals.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
fn main() {
[1, 2, 3, 4, 5];

[1; 5];

[0xff; 5];

true;

"hello world";

()
}
15 changes: 15 additions & 0 deletions tooling/nargo_fmt/tests/input/literals.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

fn main() {
[1,2,3,4,5];


[1;5];

[0xff;5];

true;

"hello world";

()
}

0 comments on commit 9816168

Please sign in to comment.