datex-core 0.0.14

The DATEX Core Rust implementation
Documentation
//! This module contains the implementation of the visitor pattern for traversing and transforming the AST of DATEX expressions and type expressions.
//! It defines the [VisitAction] enum, which represents the possible actions that can be taken when visiting a node in the AST, such as replacing the node, skipping its children, or setting its type annotation
use crate::types::r#type::Type;

pub mod expression;
pub mod type_expression;

#[derive(Debug, Clone)]
/// Actions that can be taken when visiting an expression
pub enum VisitAction<T: Sized> {
    /// Continue visiting child nodes
    ContinueRecursion,
    /// Skip visiting child nodes
    AbortRecursion,
    /// Replace the current node with a new one, skipping child nodes
    Replace(T),
    /// Recurse into child nodes, then replace the current node with a new one
    ReplaceRecurseChildNodes(T),
    /// Replace the current node with a new one, and recurse into it
    ReplaceRecurse(T),
    /// Set the type annotation of the current node, and recurse into child nodes
    SetTypeRecurseChildNodes(Type),
    /// Set the type annotation of the current node, skipping child nodes
    SetTypeSkipChildren(Type),
    /// Convert the current node to a no-op
    ToNoop,
}

#[cfg(test)]
mod tests {
    use crate::{
        ast::{
            expressions::{
                BinaryOperation, DatexExpression, DatexExpressionData,
                DeriveRef, Statements, ValueAccessType, VariableAccess,
            },
            type_expressions::{TypeExpression, TypeExpressionData},
        },
        global::operators::{BinaryOperator, binary::ArithmeticOperator},
        parser::Parser,
        prelude::*,
        values::core_values::boolean::Boolean,
        visitor::{
            VisitAction,
            expression::{ExpressionVisitor, visitable::ExpressionVisitResult},
            type_expression::{
                TypeExpressionVisitor, visitable::TypeExpressionVisitResult,
            },
        },
    };
    use core::ops::Range;

    #[derive(Debug)]
    pub struct MyAstExpressionError {
        #[allow(unused)]
        message: String,
    }
    impl MyAstExpressionError {
        pub fn new(msg: &str) -> MyAstExpressionError {
            Self {
                message: msg.to_string(),
            }
        }
    }

    struct MyAst;
    impl TypeExpressionVisitor<MyAstExpressionError> for MyAst {
        fn visit_type_identifier(
            &mut self,
            _literal: &mut String,
            span: &Range<usize>,
        ) -> TypeExpressionVisitResult<MyAstExpressionError> {
            Ok(VisitAction::Replace(TypeExpression::new(
                TypeExpressionData::VariableAccess(VariableAccess {
                    id: 0,
                    name: "MYTYPE".to_string(),
                    access_type: ValueAccessType::MoveOrCopy,
                }),
                span.clone(),
            )))
        }
    }
    impl ExpressionVisitor<MyAstExpressionError> for MyAst {
        fn handle_expression_error(
            &mut self,
            error: MyAstExpressionError,
            expression: &DatexExpression,
        ) -> Result<VisitAction<DatexExpression>, MyAstExpressionError>
        {
            log::error!(
                "Expression error: {:?} at {:?}. Aborting...",
                error,
                expression.span
            );
            Err(error)
        }
        fn visit_get_ref(
            &mut self,
            _create_ref: &mut DeriveRef,
            _span: &Range<usize>,
        ) -> ExpressionVisitResult<MyAstExpressionError> {
            Ok(VisitAction::ContinueRecursion)
        }

        fn visit_identifier(
            &mut self,
            identifier: &mut String,
            span: &Range<usize>,
        ) -> ExpressionVisitResult<MyAstExpressionError> {
            Ok(VisitAction::Replace(DatexExpression {
                data: Box::new(DatexExpressionData::VariableAccess(
                    VariableAccess {
                        id: 0,
                        name: identifier.clone(),
                        access_type: ValueAccessType::MoveOrCopy,
                    },
                )),
                span: span.clone(),
                ty: None,
            }))
        }

        fn visit_boolean(
            &mut self,
            _boolean: &mut Boolean,
            _span: &Range<usize>,
        ) -> ExpressionVisitResult<MyAstExpressionError> {
            Err(MyAstExpressionError::new("Booleans are not allowed"))
        }
    }

    #[test]
    fn simple_test() {
        let mut ast = Parser::parse_with_default_options(
            "var x: integer/u8 = 42; x; ((42 + x))",
        )
        .unwrap();
        MyAst.visit_datex_expression(&mut ast).unwrap();
    }

    #[test]
    fn error() {
        let mut ast =
            Parser::parse_with_default_options("true + false").unwrap();
        let mut transformer = MyAst;
        let res = transformer.visit_datex_expression(&mut ast);
        assert!(res.is_err());
    }

    #[test]
    fn test() {
        let mut ast = DatexExpression {
            data: Box::new(DatexExpressionData::Statements(Statements {
                statements: vec![DatexExpression {
                    data: Box::new(DatexExpressionData::BinaryOperation(
                        BinaryOperation {
                            operator: BinaryOperator::Arithmetic(
                                ArithmeticOperator::Add,
                            ),
                            left: (DatexExpression {
                                data: Box::new(
                                    DatexExpressionData::Identifier(
                                        "x".to_string(),
                                    ),
                                ),
                                span: 0..1,
                                ty: None,
                            }),
                            right: (DatexExpression {
                                data: Box::new(
                                    DatexExpressionData::Identifier(
                                        "y".to_string(),
                                    ),
                                ),
                                span: 2..3,
                                ty: None,
                            }),
                            ty: None,
                        },
                    )),
                    span: 0..3,
                    ty: None,
                }],
                is_terminated: true,
                unbounded: None,
            })),
            span: 1..2,
            ty: None,
        };
        let transformer = &mut MyAst;
        transformer.visit_datex_expression(&mut ast).unwrap();
    }
}