pub enum Expression {
Parsed(Box<ExpressionAst>),
Unparsed(String),
}
Expand description
An expression that may be parsed or unparsed
This is the core type for representing expressions in the IR. It gracefully handles both structured and unstructured forms.
§Learning: Enums for Polymorphism
Instead of inheritance (like in C++), Rust uses enums to represent “one of several types”. This is more explicit and type-safe.
§Learning: Box for Recursion
The Parsed
variant contains Box<ExpressionAst>
instead of
ExpressionAst
directly. Why? Because ExpressionAst
itself
contains Expression
values (recursion!).
Without Box
, the type would have infinite size. Box
provides
indirection through a heap pointer, breaking the cycle.
§Example
use roup::ir::{Expression, ParserConfig};
let config = ParserConfig::default();
// Simple expression gets parsed
let simple = Expression::new("42", &config);
assert!(simple.is_parsed());
// Complex expression falls back to string
let complex = Expression::new("sizeof(struct foo)", &config);
// May or may not be parsed depending on parser capability
// With parsing disabled, always unparsed
let config_no_parse = ParserConfig::string_only(roup::ir::Language::C);
let expr = Expression::new("N * 2", &config_no_parse);
assert!(!expr.is_parsed());
assert_eq!(expr.as_str(), "N * 2");
Variants§
Parsed(Box<ExpressionAst>)
Expression was successfully parsed into structured form
The compiler can analyze the AST structure for optimization, validation, or transformation.
Unparsed(String)
Expression kept as raw string
This happens when:
- Expression parsing is disabled
- Expression is too complex for the parser
- Parser doesn’t support this language construct yet
The compiler must parse this string according to the source language.
Implementations§
Source§impl Expression
impl Expression
Sourcepub fn new(raw: impl Into<String>, config: &ParserConfig) -> Self
pub fn new(raw: impl Into<String>, config: &ParserConfig) -> Self
Create a new expression, attempting to parse if enabled
§Example
use roup::ir::{Expression, ParserConfig, Language};
let config = ParserConfig::default();
let expr = Expression::new("100", &config);
assert_eq!(expr.as_str(), "100");
Sourcepub fn unparsed(raw: impl Into<String>) -> Self
pub fn unparsed(raw: impl Into<String>) -> Self
Create an unparsed expression directly
Useful when you know parsing will fail or you want to bypass it.
Sourcepub fn as_str(&self) -> &str
pub fn as_str(&self) -> &str
Get the raw string representation
This always works, whether the expression is parsed or not. The original source is always preserved.
Sourcepub fn as_ast(&self) -> Option<&ExpressionAst>
pub fn as_ast(&self) -> Option<&ExpressionAst>
Get the parsed AST if available
Trait Implementations§
Source§impl Clone for Expression
impl Clone for Expression
Source§fn clone(&self) -> Expression
fn clone(&self) -> Expression
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more