pub fn parse_expression(input: &str) -> ParseResult<Pairs<'_, Rule>>Expand description
Parses an expression.
Expressions are fundamental building blocks that compute or represent values. This parser handles a comprehensive range of expression types with proper operator precedence and associativity rules.
§Supported Expression Types
- Literals: Integer, float, boolean, and string constants
- Identifiers: Variable and function names
- Binary Operations: Arithmetic, comparison, and logical operators
- Function Calls: Invocations with argument lists
- Parenthesized Expressions: For grouping and precedence control
§Operator Precedence
Operators are evaluated in the following order (highest to lowest):
- Parentheses:
( ) - Unary operators
- Multiplicative:
*,/,% - Additive:
+,- - Comparison:
<,>,<=,>= - Equality:
==,!= - Logical AND:
&& - Logical OR:
||
§Arguments
input- A string slice containing exactly one expression
§Returns
Returns a ParseResult containing the parsed expression tree.
§Grammar Rule
This function uses the expression grammar rule from carbon.pest.
§Examples
§Literals
use carbon_parser::parse_expression;
// Integer literal
assert!(parse_expression("42").is_ok());
// Float literal
assert!(parse_expression("3.14").is_ok());
// Boolean literals
assert!(parse_expression("true").is_ok());
assert!(parse_expression("false").is_ok());
// String literal
assert!(parse_expression(r#""Hello, World!""#).is_ok());§Identifiers
use carbon_parser::parse_expression;
let code = "variable_name";
let result = parse_expression(code);
assert!(result.is_ok());§Binary Operations
use carbon_parser::parse_expression;
// Addition
assert!(parse_expression("10 + 20").is_ok());
// Complex arithmetic with precedence
assert!(parse_expression("10 + 20 * 30 - 5").is_ok());§Function Calls
use carbon_parser::parse_expression;
let code = "calculate(x, y)";
let result = parse_expression(code);
assert!(result.is_ok());§Comparison Operators
use carbon_parser::parse_expression;
assert!(parse_expression("x == y").is_ok());
assert!(parse_expression("x != y").is_ok());
assert!(parse_expression("x < y").is_ok());
assert!(parse_expression("x > y").is_ok());