Browse Source

Allow uninitialized variables

github-actions
Garrit Franke 1 year ago
parent
commit
147a56b209
  1. 1
      TODO
  2. 4
      examples/playground.sb
  3. 14
      src/parser/rules.rs
  4. 20
      src/parser/tests.rs

1
TODO

@ -1,5 +1,4 @@
# Bugs
- Uninitialized variables don't compile
- stdlib moves line of file, which makes error reporting impossible
# Features

4
examples/playground.sb

@ -1,4 +1,6 @@
fn main() {
let x: string = "Hello World\n"
let x: string
x = "Hello World"
_printf(x)
}

14
src/parser/rules.rs

@ -366,9 +366,17 @@ impl Parser {
TokenKind::Colon => Some(self.parse_type()?),
_ => None,
};
self.match_token(TokenKind::Assign)?;
let expr = self.parse_expression()?;
Ok(Statement::Declare(Variable { name, ty }, Some(expr)))
match self.peek()?.kind {
TokenKind::Assign => {
self.match_token(TokenKind::Assign)?;
let expr = self.parse_expression()?;
Ok(Statement::Declare(Variable { name, ty }, Some(expr)))
},
_ => {
Ok(Statement::Declare(Variable {name, ty}, None))
}
}
}
fn parse_assignent(&mut self, name: Option<Expression>) -> Result<Statement, String> {

20
src/parser/tests.rs

@ -621,3 +621,23 @@ fn test_booleans_in_function_call() {
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok());
}
#[test]
fn test_late_initializing_variable() {
let raw = "
fn main() {
let x: int
let y: string
x = 5
if x > 2 {
y = 'test'
}
_printf(x)
_printf(y)
}
";
let tokens = tokenize(raw);
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok());
}

Loading…
Cancel
Save