Expand description

Top-level declaration parsers

Parsers for function declarations and static variable/constant declarations.

Function Definition Example:

let source_code = "\
function f(a, b)
  return (a + 1) * b
end
";
let (_remaining, parsed_ast) = function_decl(source_code).expect("parse error");

let expected_ast = FunctionDecl {
  name: Identifier("f".to_owned()),
  params: vec![Identifier("a".to_owned()), Identifier("b".to_owned())],
  body: vec![
    Statement::ReturnStatement(Some(Expression::Binary {
      left: Box::new(Expression::Binary {
        left: Box::new(Expression::Identifier(Identifier("a".to_owned()))),
        op: BinaryOperator::Add,
        right: Box::new(Expression::Integer(IntegerLiteral(1_i64))),
      }),
      op: BinaryOperator::Mul,
      right: Box::new(Expression::Identifier(Identifier("b".to_owned()))),
    })),
  ],
};

assert_eq!(parsed_ast, expected_ast);

Static Declaration Example:

let source_code = "\
static SIZE = 512
";
let (_remaining, parsed_ast) = static_decl(source_code).expect("parse error");

let expected_ast = StaticDecl {
  name: Identifier("SIZE".to_owned()),
  value: Some(Expression::Integer(IntegerLiteral(512_i64))),
};

assert_eq!(parsed_ast, expected_ast);

The declaration parser can parse either declaration type and returns a Declaration which is an enum of either a function declaration or a static declaration.

Functions

Parses any declaration

Parses a function declaration

Parses a static declaration