Browse Source

feat: use `new` keyword to initialize structs

structs
Garrit Franke 3 years ago
parent
commit
081212673c
  1. 2
      src/lexer/mod.rs
  2. 2
      src/parser/rules.rs
  3. 22
      src/parser/tests.rs
  4. 13
      tests/struct_initialization.sb

2
src/lexer/mod.rs

@ -142,6 +142,7 @@ pub enum Keyword {
Function,
Boolean,
Struct,
New,
Unknown,
}
@ -363,6 +364,7 @@ impl Cursor<'_> {
c if c == "break" => Keyword::Break,
c if c == "continue" => Keyword::Continue,
c if c == "struct" => Keyword::Struct,
c if c == "new" => Keyword::New,
_ => Keyword::Unknown,
}
}

2
src/parser/rules.rs

@ -306,7 +306,7 @@ impl Parser {
Ok(state)
}
TokenKind::SquareBraceOpen => self.parse_array(),
TokenKind::Keyword(Keyword::Struct) => self.parse_struct_initialization(),
TokenKind::Keyword(Keyword::New) => self.parse_struct_initialization(),
other => Err(format!("Expected Expression, found {:?}", other)),
}
}

22
src/parser/tests.rs

@ -776,3 +776,25 @@ fn test_array_as_argument() {
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok());
}
#[test]
fn test_struct_initialization() {
let raw = "
struct User {
username: string,
first_name: string,
last_name: string
}
fn main() {
let foo = new User {
username: 'foobar',
first_name: 'Foo',
last_name: 'Bar'
}
}
";
let tokens = tokenize(raw);
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok());
}

13
tests/struct_initialization.sb

@ -0,0 +1,13 @@
struct User {
username: string,
first_name: string,
last_name: string
}
fn main() {
let foo = new User {
username: 'foobar',
first_name: 'Foo',
last_name: 'Bar'
}
}
Loading…
Cancel
Save