parse_function_decl

Function parse_function_decl 

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

Parses a single function declaration.

Use this function when you need to parse an individual function definition in isolation, without requiring a complete program context. This is useful for testing, code generation, incremental parsing, or working with code fragments.

§Carbon Function Syntax

A function declaration in Carbon has the following structure:

fn function_name(param1: Type1, param2: Type2) -> ReturnType {
    // function body statements
    return expression;
}

Components:

  • fn keyword to start the declaration
  • Function name (identifier)
  • Parameter list in parentheses (may be empty)
  • Optional return type preceded by ->
  • Function body in braces

§Arguments

  • input - A string slice containing exactly one function declaration

§Returns

Returns a ParseResult containing the parsed function declaration tree.

§Grammar Rule

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

§Examples

§Function Without Parameters

use carbon_parser::parse_function_decl;

let code = "fn test() -> i32 { return 42; }";
let result = parse_function_decl(code);
assert!(result.is_ok());

§Function With Single Parameter

use carbon_parser::parse_function_decl;

let code = "fn square(x: i32) -> i32 { return x; }";
let result = parse_function_decl(code);
assert!(result.is_ok());

§Function With Multiple Parameters

use carbon_parser::parse_function_decl;

let code = "fn add(x: i32, y: i32, z: i32) -> i32 { return x; }";
let result = parse_function_decl(code);
assert!(result.is_ok());

§Function Without Return Type

use carbon_parser::parse_function_decl;

let code = "fn print_hello() { return 0; }";
let result = parse_function_decl(code);
assert!(result.is_ok());

§Function With Mixed Parameter Types

use carbon_parser::parse_function_decl;

let code = "fn process(name: String, age: i32, active: bool) -> bool { return active; }";
let result = parse_function_decl(code);
assert!(result.is_ok());