Skip to content

Commit

Permalink
Merge branch 'master' into phated/lsp-wasm
Browse files Browse the repository at this point in the history
* master:
  chore: update `async-lsp` to v0.1.0 (#3489)
  fix: adding proving key initialization (#3322)
  chore(fmt): don't lose line breaks between comments (#3505)
  feat: Add LSP command to profile opcodes in vscode (#3496)
  chore: format integration tests (#3399)
  chore: Refactor parser tests (with concat!()) (#3500)
  chore: format function signature (#3495)
  chore: update `self_cell` to v1.0.2 (#3487)
  chore: Fix broken link (#3497)
  chore: update array formatting style (#3486)
  chore(fmt): add fn_call_width (#3480)
  chore: Fix undesirable line break before '{' in function signature with comments (#3473)
  fix: apply predicate to over/underflow checks (#3494)
  • Loading branch information
TomAFrench committed Nov 17, 2023
2 parents a8a6fc2 + 9701f90 commit 88b44e8
Show file tree
Hide file tree
Showing 270 changed files with 1,700 additions and 1,376 deletions.
12 changes: 8 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ noirc_abi = { path = "tooling/noirc_abi" }
bb_abstraction_leaks = { path = "tooling/bb_abstraction_leaks" }

# LSP
async-lsp = { version = "0.0.5", default-features = false }
async-lsp = { version = "0.1.0", default-features = false }
lsp-types = "0.94.1"
tower = "0.4"

Expand Down
2 changes: 1 addition & 1 deletion compiler/integration-tests/circuits/main/src/main.nr
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
fn main(x : Field, y : pub Field) {
fn main(x: Field, y: pub Field) {
assert(x != y);
}
10 changes: 5 additions & 5 deletions compiler/integration-tests/circuits/recursion/src/main.nr
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use dep::std;

fn main(
verification_key : [Field; 114],
proof : [Field; 94],
public_inputs : [Field; 1],
key_hash : Field,
input_aggregation_object : [Field; 16],
verification_key: [Field; 114],
proof: [Field; 94],
public_inputs: [Field; 1],
key_hash: Field,
input_aggregation_object: [Field; 16]
) -> pub [Field; 16] {
let vk : [Field] = verification_key;
let p : [Field] = proof;
Expand Down
7 changes: 4 additions & 3 deletions compiler/noirc_errors/src/debug_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub struct DebugInfo {

/// Holds OpCodes Counts for Acir and Brillig Opcodes
/// To be printed with `nargo info --profile-info`
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub struct OpCodesCount {
pub acir_size: usize,
pub brillig_size: usize,
Expand Down Expand Up @@ -51,12 +52,12 @@ impl DebugInfo {
self.locations.get(loc).cloned()
}

pub fn count_span_opcodes(&self) -> HashMap<&Location, OpCodesCount> {
let mut accumulator: HashMap<&Location, Vec<&OpcodeLocation>> = HashMap::new();
pub fn count_span_opcodes(&self) -> HashMap<Location, OpCodesCount> {
let mut accumulator: HashMap<Location, Vec<&OpcodeLocation>> = HashMap::new();

for (opcode_location, locations) in self.locations.iter() {
for location in locations.iter() {
let opcodes = accumulator.entry(location).or_insert(Vec::new());
let opcodes = accumulator.entry(*location).or_insert(Vec::new());
opcodes.push(opcode_location);
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_evaluator/src/ssa/ir/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ pub(crate) fn display_instruction(
)
}
Instruction::RangeCheck { value, max_bit_size, .. } => {
write!(f, "range_check {} to {} bits", show(*value), *max_bit_size,)
writeln!(f, "range_check {} to {} bits", show(*value), *max_bit_size,)
}
}
}
16 changes: 16 additions & 0 deletions compiler/noirc_evaluator/src/ssa/opt/flatten_cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,22 @@ impl<'f> Context<'f> {
self.remember_store(address, value);
Instruction::Store { address, value }
}
Instruction::RangeCheck { value, max_bit_size, assert_message } => {
// Replace value with `value * predicate` to zero out value when predicate is inactive.

// Condition needs to be cast to argument type in order to multiply them together.
let argument_type = self.inserter.function.dfg.type_of_value(value);
let casted_condition = self.insert_instruction(
Instruction::Cast(condition, argument_type),
call_stack.clone(),
);

let value = self.insert_instruction(
Instruction::binary(BinaryOp::Mul, value, casted_condition),
call_stack.clone(),
);
Instruction::RangeCheck { value, max_bit_size, assert_message }
}
other => other,
}
} else {
Expand Down
21 changes: 16 additions & 5 deletions compiler/noirc_frontend/src/ast/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ pub struct FunctionDefinition {
pub visibility: FunctionVisibility,

pub generics: UnresolvedGenerics,
pub parameters: Vec<(Pattern, UnresolvedType, Visibility)>,
pub parameters: Vec<Param>,
pub body: BlockExpression,
pub span: Span,
pub where_clause: Vec<UnresolvedTraitConstraint>,
Expand All @@ -379,6 +379,14 @@ pub struct FunctionDefinition {
pub return_distinctness: Distinctness,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Param {
pub visibility: Visibility,
pub pattern: Pattern,
pub typ: UnresolvedType,
pub span: Span,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum FunctionReturnType {
/// Returns type is not specified.
Expand Down Expand Up @@ -634,8 +642,11 @@ impl FunctionDefinition {
) -> FunctionDefinition {
let p = parameters
.iter()
.map(|(ident, unresolved_type)| {
(Pattern::Identifier(ident.clone()), unresolved_type.clone(), Visibility::Private)
.map(|(ident, unresolved_type)| Param {
visibility: Visibility::Private,
pattern: Pattern::Identifier(ident.clone()),
typ: unresolved_type.clone(),
span: ident.span().merge(unresolved_type.span.unwrap()),
})
.collect();
FunctionDefinition {
Expand All @@ -661,8 +672,8 @@ impl Display for FunctionDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{:?}", self.attributes)?;

let parameters = vecmap(&self.parameters, |(name, r#type, visibility)| {
format!("{name}: {visibility} {type}")
let parameters = vecmap(&self.parameters, |Param { visibility, pattern, typ, span: _ }| {
format!("{pattern}: {visibility} {typ}")
});

let where_clause = vecmap(&self.where_clause, ToString::to_string);
Expand Down
8 changes: 6 additions & 2 deletions compiler/noirc_frontend/src/ast/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use noirc_errors::Span;

use crate::{
token::{Attributes, FunctionAttribute, SecondaryAttribute},
FunctionReturnType, Ident, Pattern, Visibility,
FunctionReturnType, Ident, Param, Visibility,
};

use super::{FunctionDefinition, UnresolvedType, UnresolvedTypeData};
Expand Down Expand Up @@ -45,6 +45,10 @@ impl NoirFunction {
NoirFunction { kind: FunctionKind::Oracle, def }
}

pub fn return_visibility(&self) -> Visibility {
self.def.return_visibility
}

pub fn return_type(&self) -> UnresolvedType {
match &self.def.return_type {
FunctionReturnType::Default(_) => {
Expand All @@ -59,7 +63,7 @@ impl NoirFunction {
pub fn name_ident(&self) -> &Ident {
&self.def.name
}
pub fn parameters(&self) -> &Vec<(Pattern, UnresolvedType, Visibility)> {
pub fn parameters(&self) -> &[Param] {
&self.def.parameters
}
pub fn attributes(&self) -> &Attributes {
Expand Down
8 changes: 8 additions & 0 deletions compiler/noirc_frontend/src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,14 @@ pub enum Pattern {
}

impl Pattern {
pub fn span(&self) -> Span {
match self {
Pattern::Identifier(ident) => ident.span(),
Pattern::Mutable(_, span) | Pattern::Tuple(_, span) | Pattern::Struct(_, _, span) => {
*span
}
}
}
pub fn name_ident(&self) -> &Ident {
match self {
Pattern::Identifier(name_ident) => name_ident,
Expand Down
19 changes: 10 additions & 9 deletions compiler/noirc_frontend/src/hir/aztec_library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ use crate::{
};
use crate::{
ForLoopStatement, ForRange, FunctionDefinition, FunctionVisibility, ImportStatement,
NoirStruct, PrefixExpression, Signedness, StatementKind, StructType, Type, TypeImpl, UnaryOp,
NoirStruct, Param, PrefixExpression, Signedness, StatementKind, StructType, Type, TypeImpl,
UnaryOp,
};
use fm::FileId;

Expand Down Expand Up @@ -226,12 +227,12 @@ fn check_for_compute_note_hash_and_nullifier_definition(module: &SortedModule) -
module.functions.iter().any(|func| {
func.def.name.0.contents == "compute_note_hash_and_nullifier"
&& func.def.parameters.len() == 4
&& func.def.parameters[0].1.typ == UnresolvedTypeData::FieldElement
&& func.def.parameters[1].1.typ == UnresolvedTypeData::FieldElement
&& func.def.parameters[2].1.typ == UnresolvedTypeData::FieldElement
&& func.def.parameters[0].typ.typ == UnresolvedTypeData::FieldElement
&& func.def.parameters[1].typ.typ == UnresolvedTypeData::FieldElement
&& func.def.parameters[2].typ.typ == UnresolvedTypeData::FieldElement
// checks if the 4th parameter is an array and the Box<UnresolvedType> in
// Array(Option<UnresolvedTypeExpression>, Box<UnresolvedType>) contains only fields
&& match &func.def.parameters[3].1.typ {
&& match &func.def.parameters[3].typ.typ {
UnresolvedTypeData::Array(_, inner_type) => {
match inner_type.typ {
UnresolvedTypeData::FieldElement => true,
Expand Down Expand Up @@ -513,14 +514,14 @@ fn generate_selector_impl(structure: &NoirStruct) -> TypeImpl {
/// fn foo() {
/// // ...
/// }
pub(crate) fn create_inputs(ty: &str) -> (Pattern, UnresolvedType, Visibility) {
pub(crate) fn create_inputs(ty: &str) -> Param {
let context_ident = ident("inputs");
let context_pattern = Pattern::Identifier(context_ident);
let type_path = chained_path!("aztec", "abi", ty);
let context_type = make_type(UnresolvedTypeData::Named(type_path, vec![]));
let visibility = Visibility::Private;

(context_pattern, context_type, visibility)
Param { pattern: context_pattern, typ: context_type, visibility, span: Span::default() }
}

/// Creates the private context object to be accessed within the function, the parameters need to be extracted to be
Expand Down Expand Up @@ -548,7 +549,7 @@ pub(crate) fn create_inputs(ty: &str) -> (Pattern, UnresolvedType, Visibility) {
/// let mut context = PrivateContext::new(inputs, hasher.hash());
/// }
/// ```
fn create_context(ty: &str, params: &[(Pattern, UnresolvedType, Visibility)]) -> Vec<Statement> {
fn create_context(ty: &str, params: &[Param]) -> Vec<Statement> {
let mut injected_expressions: Vec<Statement> = vec![];

// `let mut hasher = Hasher::new();`
Expand All @@ -564,7 +565,7 @@ fn create_context(ty: &str, params: &[(Pattern, UnresolvedType, Visibility)]) ->
injected_expressions.push(let_hasher);

// Iterate over each of the function parameters, adding to them to the hasher
params.iter().for_each(|(pattern, typ, _vis)| {
params.iter().for_each(|Param { pattern, typ, span: _, visibility: _ }| {
match pattern {
Pattern::Identifier(identifier) => {
// Match the type to determine the padding to do
Expand Down
4 changes: 2 additions & 2 deletions compiler/noirc_frontend/src/hir/resolution/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ use crate::{
};
use crate::{
ArrayLiteral, ContractFunctionType, Distinctness, ForRange, FunctionVisibility, Generics,
LValue, NoirStruct, NoirTypeAlias, Path, PathKind, Pattern, Shared, StructType, Type,
LValue, NoirStruct, NoirTypeAlias, Param, Path, PathKind, Pattern, Shared, StructType, Type,
TypeAliasType, TypeBinding, TypeVariable, UnaryOp, UnresolvedGenerics,
UnresolvedTraitConstraint, UnresolvedType, UnresolvedTypeData, UnresolvedTypeExpression,
Visibility, ERROR_IDENT,
Expand Down Expand Up @@ -760,7 +760,7 @@ impl<'a> Resolver<'a> {
let mut parameters = vec![];
let mut parameter_types = vec![];

for (pattern, typ, visibility) in func.parameters().iter().cloned() {
for Param { visibility, pattern, typ, span: _ } in func.parameters().iter().cloned() {
if visibility == Visibility::Public && !self.pub_allowed(func) {
self.push_err(ResolverError::UnnecessaryPub {
ident: func.name_ident().clone(),
Expand Down
30 changes: 24 additions & 6 deletions compiler/noirc_frontend/src/lexer/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub struct Lexer<'a> {
position: Position,
done: bool,
skip_comments: bool,
skip_whitespaces: bool,
}

pub type SpannedTokenResult = Result<SpannedToken, LexerErrorKind>;
Expand All @@ -37,14 +38,25 @@ impl<'a> Lexer<'a> {
}

pub fn new(source: &'a str) -> Self {
Lexer { chars: source.char_indices(), position: 0, done: false, skip_comments: true }
Lexer {
chars: source.char_indices(),
position: 0,
done: false,
skip_comments: true,
skip_whitespaces: true,
}
}

pub fn skip_comments(mut self, flag: bool) -> Self {
self.skip_comments = flag;
self
}

pub fn skip_whitespaces(mut self, flag: bool) -> Self {
self.skip_whitespaces = flag;
self
}

/// Iterates the cursor and returns the char at the new cursor position
fn next_char(&mut self) -> Option<char> {
let (position, ch) = self.chars.next()?;
Expand Down Expand Up @@ -82,9 +94,13 @@ impl<'a> Lexer<'a> {

fn next_token(&mut self) -> SpannedTokenResult {
match self.next_char() {
Some(x) if { x.is_whitespace() } => {
self.eat_whitespace();
self.next_token()
Some(x) if x.is_whitespace() => {
let spanned = self.eat_whitespace(x);
if self.skip_whitespaces {
self.next_token()
} else {
Ok(spanned)
}
}
Some('<') => self.glue(Token::Less),
Some('>') => self.glue(Token::Greater),
Expand Down Expand Up @@ -454,8 +470,10 @@ impl<'a> Lexer<'a> {
}

/// Skips white space. They are not significant in the source language
fn eat_whitespace(&mut self) {
self.eat_while(None, |ch| ch.is_whitespace());
fn eat_whitespace(&mut self, initial_char: char) -> SpannedToken {
let start = self.position;
let whitespace = self.eat_while(initial_char.into(), |ch| ch.is_whitespace());
SpannedToken::new(Token::Whitespace(whitespace), Span::inclusive(start, self.position))
}
}

Expand Down
3 changes: 3 additions & 0 deletions compiler/noirc_frontend/src/lexer/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ pub enum Token {
#[allow(clippy::upper_case_acronyms)]
EOF,

Whitespace(String),

/// An invalid character is one that is not in noir's language or grammar.
///
/// We don't report invalid tokens in the source as errors until parsing to
Expand Down Expand Up @@ -194,6 +196,7 @@ impl fmt::Display for Token {
Token::Bang => write!(f, "!"),
Token::EOF => write!(f, "end of input"),
Token::Invalid(c) => write!(f, "{c}"),
Token::Whitespace(ref s) => write!(f, "{s}"),
}
}
}
Expand Down
Loading

0 comments on commit 88b44e8

Please sign in to comment.