Skip to content

Commit

Permalink
Allow self in use statements
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Oct 23, 2024
1 parent a7d58de commit f30b438
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
4 changes: 3 additions & 1 deletion compiler/noirc_frontend/src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,9 @@ impl UseTree {

match self.kind {
UseTreeKind::Path(name, alias) => {
vec![ImportStatement { visibility, path: prefix.join(name), alias }]
// Desugar `use foo::{self}` to `use foo`
let path = if name.0.contents == "self" { prefix } else { prefix.join(name) };
vec![ImportStatement { visibility, path, alias }]
}
UseTreeKind::List(trees) => {
let trees = trees.into_iter();
Expand Down
15 changes: 15 additions & 0 deletions compiler/noirc_frontend/src/parser/parser/use_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ impl<'a> Parser<'a> {
fn parse_use_tree_in_list(&mut self) -> Option<UseTree> {
let start_span = self.current_token_span;

// Special case: "self" cannot be followed by anything else
if self.eat_self() {
return Some(UseTree {
prefix: Path { segments: Vec::new(), kind: PathKind::Plain, span: start_span },
kind: UseTreeKind::Path(Ident::new("self".to_string(), start_span), None),
});
}

let use_tree = self.parse_use_tree_without_kind(
start_span,
PathKind::Plain,
Expand Down Expand Up @@ -250,4 +258,11 @@ mod tests {
let (_, errors) = parse_program(src);
assert!(!errors.is_empty());
}

#[test]
fn errors_on_double_colon_after_self() {
let src = "use foo::{self::bar};";
let (_, errors) = parse_program(src);
assert!(!errors.is_empty());
}
}
22 changes: 22 additions & 0 deletions compiler/noirc_frontend/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3389,3 +3389,25 @@ fn arithmetic_generics_rounding_fail() {
let errors = get_program_errors(src);
assert_eq!(errors.len(), 1);
}

#[test]
fn uses_self_in_import() {
let src = r#"
mod moo {
pub mod bar {
pub fn foo() -> i32 {
1
}
}
}
use moo::bar::{self};
pub fn baz() -> i32 {
bar::foo()
}
fn main() {}
"#;
assert_no_errors(src);
}

0 comments on commit f30b438

Please sign in to comment.