Function parse_unary

Source
pub fn parse_unary(input: &str) -> IResult<&str, Unary>
Expand description

Parse a unary expression.

This function parses unary expressions including logical NOT, unary plus/minus, and type casting operations. It handles the right-to-left associativity of unary operators and chaining of multiple unary operations.

§Arguments

  • input - A string slice containing the unary expression to parse

§Returns

  • IResult<&str, Unary> - A nom result with remaining input and parsed unary expression

§Parsing Algorithm

The parser follows this algorithm:

  1. Attempt to parse one or more unary operators using many1(unary_operator)
  2. If successful, parse the postfix expression (operand)
  3. Convert the postfix to a unary expression
  4. Apply unary operators in right-to-left order (reverse of parsing order)
  5. If no unary operators are found, parse the expression as a postfix expression

§Right-to-Left Associativity

Unary operators are right-to-left associative. This means !+5 parses as !(+5) rather than (!+)5. The parser maintains a stack of operators and applies them in reverse order to achieve this associativity.

§Examples

use aimx::expressions::unary::parse_unary;
 
// Basic unary operations
let (remaining, expr) = parse_unary("!true").unwrap();
assert_eq!(remaining, "");
 
// Chained operations demonstrate right-to-left associativity
let (remaining, expr) = parse_unary("!(Bool)0").unwrap();
assert_eq!(remaining, "");
 
// Multiple unary operators
let (remaining, expr) = parse_unary("+-+5").unwrap();
assert_eq!(remaining, "");
 
// Type casting
let (remaining, expr) = parse_unary("(Number)\"123\"").unwrap();
assert_eq!(remaining, "");

§Error Handling

Returns IResult::Err if the input cannot be parsed as a valid unary expression. Common errors include:

  • Invalid unary operator syntax
  • Missing operand after unary operator
  • Invalid type name in cast operator