Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify module evaluation #80

Merged
merged 3 commits into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion boreal-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ fn scan_file(scanner: &Scanner, path: &Path, options: ScanOptions) -> std::io::R
for (module_name, module_value) in res.module_values {
// A module value must be an object. Filter out empty ones, it means the module has not
// generated any values.
if let ModuleValue::Object(map) = &*module_value {
if let ModuleValue::Object(map) = &module_value {
if !map.is_empty() {
print!("{module_name}");
print_module_value(&module_value, 4);
Expand Down
152 changes: 92 additions & 60 deletions boreal/src/compiler/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{collections::HashMap, ops::Range};

use boreal_parser::expression::{Identifier, IdentifierOperation, IdentifierOperationType};

use super::expression::{compile_expression, Expression, Type};
use super::expression::{compile_expression, Expr, Expression, Type};
use super::rule::RuleCompiler;
use super::{CompilationError, ImportedModule};
use crate::module::{self, ScanContext, StaticValue, Type as ValueType, Value};
Expand All @@ -18,17 +18,6 @@ pub struct Module {
dynamic_types: ValueType,
}

/// Operations on identifiers.
#[derive(Debug)]
pub enum ValueOperation {
/// Object subfield, i.e. `value.subfield`.
Subfield(String),
/// Array/dict subscript, i.e. `value[subscript]`.
Subscript(Box<Expression>),
/// Function call, i.e. `value(arguments)`.
FunctionCall(Vec<Expression>),
}

/// Index on a bounded value
#[derive(Debug)]
pub enum BoundedValueIndex {
Expand All @@ -42,45 +31,72 @@ pub enum BoundedValueIndex {
}

/// Different type of expressions related to the use of a module.
pub enum ModuleExpression {
#[derive(Debug)]
pub struct ModuleExpression {
/// Kind of the expression.
pub kind: ModuleExpressionKind,

/// List of operations to apply to the value to get the final value.
pub operations: ModuleOperations,
}

pub enum ModuleExpressionKind {
/// Operations on a bounded module value.
BoundedModuleValueUse {
/// Index of the bounded value.
index: BoundedValueIndex,

/// List of operations to apply to the value to get the final value.
operations: Vec<ValueOperation>,
},

/// A value coming from a function exposed by a module.
Function {
/// The function to call with the computed index
StaticFunction {
/// The function to call.
fun: fn(&ScanContext, Vec<Value>) -> Option<Value>,
/// The expressions that provides the arguments of the function.
arguments: Vec<Expression>,
/// List of operations to apply on the value returned by the function.
operations: Vec<ValueOperation>,
},
}

/// Operations to apply to a module value.
#[derive(Debug)]
pub struct ModuleOperations {
/// List of expressions that needs to be evaluated to compute all of the operations.
///
/// This list is in its own Vec instead of inlined in each operation so that they
/// can be evaluated separately, which makes the evaluation of operations simpler
/// as it can be done immutably.
///
/// The expressions are stored in the same order the operations will be evaluated.
pub expressions: Vec<Expression>,

/// List of operations to apply to the module value.
pub operations: Vec<ValueOperation>,
}

/// Operations on identifiers.
#[derive(Debug)]
pub enum ValueOperation {
/// Object subfield, i.e. `value.subfield`.
Subfield(String),
/// Array/dict subscript, i.e. `value[subscript]`.
///
/// The value used as the subscript index is stored in [`ModuleOperations::expressions`].
Subscript,
/// Function call, i.e. `value(arguments)`.
///
/// The value is the number of expressions to pick from [`ModuleOperations::expressions`]
/// to form the arguments of the function call.
FunctionCall(usize),
}

// XXX: custom Debug impl needed because derive does not work with the fn fields.
impl std::fmt::Debug for ModuleExpression {
impl std::fmt::Debug for ModuleExpressionKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BoundedModuleValueUse { index, operations } => f
Self::BoundedModuleValueUse { index } => f
.debug_struct("BoundedModuleValueUse")
.field("index", index)
.field("operations", operations)
.finish(),
Self::Function {
fun,
arguments,
operations,
} => f
Self::StaticFunction { fun } => f
.debug_struct("Function")
.field("fun", &(*fun as usize))
.field("arguments", arguments)
.field("operations", operations)
.finish(),
}
}
Expand Down Expand Up @@ -128,6 +144,7 @@ pub(super) fn compile_bounded_identifier_use<'a, 'b>(
compiler,
last_immediate_value: None,
current_value: ValueOrType::Type(starting_type),
operations_expressions: Vec::new(),
operations: Vec::with_capacity(identifier.operations.len()),
current_span: identifier.name_span,
bounded_value_index: Some(BoundedValueIndex::BoundedStack(identifier_stack_index)),
Expand Down Expand Up @@ -184,6 +201,7 @@ pub(super) fn compile_identifier<'a, 'b>(
compiler,
last_immediate_value: Some(value),
current_value: ValueOrType::Value(value),
operations_expressions: Vec::new(),
operations: Vec::with_capacity(nb_ops),
current_span: identifier.name_span,
bounded_value_index: None,
Expand All @@ -195,6 +213,7 @@ pub(super) fn compile_identifier<'a, 'b>(
compiler,
last_immediate_value: None,
current_value: ValueOrType::Type(&module.module.dynamic_types),
operations_expressions: Vec::new(),
operations: Vec::with_capacity(nb_ops),
current_span: identifier.name_span,
bounded_value_index: Some(BoundedValueIndex::Module(module.module_index)),
Expand All @@ -220,6 +239,9 @@ pub(super) struct ModuleUse<'a, 'b> {
// Current value (or type).
current_value: ValueOrType<'b>,

// Expressions that needs to be evaluated to be able to evaluate the operations.
operations_expressions: Vec<Expression>,

// Operations that will need to be evaluated at scanning time.
operations: Vec<ValueOperation>,

Expand All @@ -245,22 +267,23 @@ impl ModuleUse<'_, '_> {
res
}
IdentifierOperationType::Subscript(subscript) => {
let subscript = compile_expression(self.compiler, *subscript)?;
let Expr { expr, ty, span } = compile_expression(self.compiler, *subscript)?;

self.operations
.push(ValueOperation::Subscript(Box::new(subscript.expr)));
self.current_value.subscript(subscript.ty, subscript.span)
self.operations_expressions.push(expr);
self.operations.push(ValueOperation::Subscript);
self.current_value.subscript(ty, span)
}
IdentifierOperationType::FunctionCall(arguments) => {
let mut arguments_exprs = Vec::with_capacity(arguments.len());
self.operations
.push(ValueOperation::FunctionCall(arguments.len()));

let mut arguments_types = Vec::with_capacity(arguments.len());
for arg in arguments {
let res = compile_expression(self.compiler, arg)?;
arguments_exprs.push(res.expr);
self.operations_expressions.push(res.expr);
arguments_types.push(res.ty);
}
self.operations
.push(ValueOperation::FunctionCall(arguments_exprs));

self.current_value.function_call(&arguments_types)
}
};
Expand Down Expand Up @@ -304,9 +327,14 @@ impl ModuleUse<'_, '_> {

fn into_module_expression(self) -> Option<(ModuleExpression, ValueType)> {
let ty = self.current_value.into_type()?;
let expr = ModuleExpression::BoundedModuleValueUse {
index: self.bounded_value_index?,
operations: self.operations,
let expr = ModuleExpression {
kind: ModuleExpressionKind::BoundedModuleValueUse {
index: self.bounded_value_index?,
},
operations: ModuleOperations {
expressions: self.operations_expressions,
operations: self.operations,
},
};
Some((expr, ty))
}
Expand All @@ -324,17 +352,13 @@ impl ModuleUse<'_, '_> {

StaticValue::Object(_) => return None,

StaticValue::Function { fun, .. } => {
let mut ops = self.operations.into_iter();
let Some(ValueOperation::FunctionCall(arguments)) = ops.next() else {
return None;
};
Expression::Module(ModuleExpression::Function {
fun: *fun,
arguments,
operations: ops.collect(),
})
}
StaticValue::Function { fun, .. } => Expression::Module(ModuleExpression {
kind: ModuleExpressionKind::StaticFunction { fun: *fun },
operations: ModuleOperations {
expressions: self.operations_expressions,
operations: self.operations,
},
}),
};
let ty = self.current_value.into_type()?;

Expand Down Expand Up @@ -608,15 +632,23 @@ mod tests {
test_type_traits_non_clonable(compile_module(&crate::module::Time));
test_type_traits_non_clonable(ValueOperation::Subfield("a".to_owned()));
test_type_traits_non_clonable(BoundedValueIndex::Module(0));
test_type_traits_non_clonable(ModuleExpression::BoundedModuleValueUse {
index: BoundedValueIndex::Module(0),
test_type_traits_non_clonable(ModuleOperations {
expressions: Vec::new(),
operations: Vec::new(),
});
test_type_traits_non_clonable(ModuleExpression::Function {
fun: test_fun,
arguments: Vec::new(),
operations: Vec::new(),
test_type_traits_non_clonable(ModuleExpression {
kind: ModuleExpressionKind::BoundedModuleValueUse {
index: BoundedValueIndex::Module(0),
},
operations: ModuleOperations {
expressions: Vec::new(),
operations: Vec::new(),
},
});
test_type_traits_non_clonable(ModuleExpressionKind::BoundedModuleValueUse {
index: BoundedValueIndex::Module(0),
});
test_type_traits_non_clonable(ModuleExpressionKind::StaticFunction { fun: test_fun });
test_type_traits_non_clonable(IteratorType::Array(ValueType::Integer));
test_type_traits_non_clonable(TypeError::UnknownSubfield("a".to_owned()));
test_type_traits_non_clonable(ValueOrType::Type(&ValueType::Integer));
Expand Down
22 changes: 9 additions & 13 deletions boreal/src/evaluator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
//! - `defined`
//!
//! For all of those, an undefined value is considered to be equivalent to a false boolean value.
use std::sync::Arc;
use std::time::Duration;

use crate::compiler::expression::{Expression, ForIterator, ForSelection, VariableIndex};
Expand Down Expand Up @@ -114,7 +113,7 @@ impl From<ExternalValue> for Value {
pub struct ScanData<'a> {
pub mem: &'a [u8],

pub module_values: Vec<(&'static str, Arc<ModuleValue>)>,
pub module_values: Vec<(&'static str, ModuleValue)>,

// Context used when calling module functions
module_ctx: ScanContext<'a>,
Expand Down Expand Up @@ -153,9 +152,7 @@ impl<'a> ScanData<'a> {
.map(|module| {
(
module.get_name(),
Arc::new(crate::module::Value::Object(
module.get_dynamic_values(&mut module_ctx),
)),
crate::module::Value::Object(module.get_dynamic_values(&mut module_ctx)),
)
})
.collect(),
Expand Down Expand Up @@ -222,7 +219,7 @@ struct Evaluator<'scan, 'rule> {
currently_selected_variable_index: Option<usize>,

// Stack of bounded identifiers to their integer values.
bounded_identifiers_stack: Vec<Arc<ModuleValue>>,
bounded_identifiers_stack: Vec<ModuleValue>,

// Data related only to the scan, independent of the rule.
scan_data: &'rule mut ScanData<'scan>,
Expand Down Expand Up @@ -845,7 +842,7 @@ impl Evaluator<'_, '_> {
match value {
ModuleValue::Array(array) => {
for value in array {
self.bounded_identifiers_stack.push(Arc::new(value));
self.bounded_identifiers_stack.push(value);
let v = self.evaluate_expr(body);
self.bounded_identifiers_stack.truncate(prev_stack_len);
let v = match v {
Expand All @@ -865,9 +862,8 @@ impl Evaluator<'_, '_> {
}
ModuleValue::Dictionary(dict) => {
for (key, value) in dict {
self.bounded_identifiers_stack
.push(Arc::new(ModuleValue::Bytes(key)));
self.bounded_identifiers_stack.push(Arc::new(value));
self.bounded_identifiers_stack.push(ModuleValue::Bytes(key));
self.bounded_identifiers_stack.push(value);
let v = self.evaluate_expr(body);
self.bounded_identifiers_stack.truncate(prev_stack_len);
let v = match v {
Expand Down Expand Up @@ -900,7 +896,7 @@ impl Evaluator<'_, '_> {

for value in from..=to {
self.bounded_identifiers_stack
.push(Arc::new(ModuleValue::Integer(value)));
.push(ModuleValue::Integer(value));
let v = self.evaluate_expr(body);
self.bounded_identifiers_stack.truncate(prev_stack_len);
let v = match v {
Expand All @@ -925,11 +921,11 @@ impl Evaluator<'_, '_> {
match self.evaluate_expr(expr)? {
Value::Integer(value) => {
self.bounded_identifiers_stack
.push(Arc::new(ModuleValue::Integer(value)));
.push(ModuleValue::Integer(value));
}
Value::Bytes(value) => {
self.bounded_identifiers_stack
.push(Arc::new(ModuleValue::Bytes(value)));
.push(ModuleValue::Bytes(value));
}
_ => return Err(PoisonKind::Undefined),
}
Expand Down
Loading