parse_var_decl

Function parse_var_decl 

Source
pub fn parse_var_decl(input: &str) -> ParseResult<Pairs<'_, Rule>>
Expand description

Parses a variable declaration statement.

Variable declarations in Carbon require explicit type annotations and may optionally include an initializer expression. Variables use the var keyword and must specify their type before use.

§Carbon Variable Syntax

A variable declaration has the following structure:

var variable_name: Type = initial_value;

Components:

  • var keyword to start the declaration
  • Variable name (identifier)
  • Type annotation preceded by :
  • Optional initializer with = and expression
  • Terminating semicolon

§Arguments

  • input - A string slice containing exactly one variable declaration

§Returns

Returns a ParseResult containing the parsed variable declaration tree.

§Grammar Rule

This function uses the var_decl grammar rule from carbon.pest.

§Examples

§Variable With Initialization

use carbon_parser::parse_var_decl;

let code = "var x: i32 = 42;";
let result = parse_var_decl(code);
assert!(result.is_ok());

§Variable Without Initialization

use carbon_parser::parse_var_decl;

let code = "var y: bool;";
let result = parse_var_decl(code);
assert!(result.is_ok());

§String Variable

use carbon_parser::parse_var_decl;

let code = r#"var name: String = "John";"#;
let result = parse_var_decl(code);
assert!(result.is_ok());

§Float Variable

use carbon_parser::parse_var_decl;

let code = "var pi: f64 = 3.14;";
let result = parse_var_decl(code);
assert!(result.is_ok());

§Variable With Expression

use carbon_parser::parse_var_decl;

let code = "var sum: i32 = 10 + 20;";
let result = parse_var_decl(code);
assert!(result.is_ok());