Skip to content
Open
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
20 changes: 18 additions & 2 deletions packages/commons/octobot_commons/dsl_interpreter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
get_all_operators,
clear_get_all_operators_cache,
)
from octobot_commons.dsl_interpreter.operator_parameter import OperatorParameter
from octobot_commons.dsl_interpreter.operator_parameter import (
OperatorParameter,
UNINITIALIZED_VALUE,
)
from octobot_commons.dsl_interpreter.operator_docs import OperatorDocs
from octobot_commons.dsl_interpreter.operators import (
BinaryOperator,
Expand All @@ -34,15 +37,24 @@
CallOperator,
NameOperator,
ExpressionOperator,
PreComputingCallOperator,
)
from octobot_commons.dsl_interpreter.interpreter_dependency import (
InterpreterDependency,
)
from octobot_commons.dsl_interpreter.parameters_util import (
format_parameter_value,
resove_operator_params,
)
from octobot_commons.dsl_interpreter.interpreter_dependency import InterpreterDependency
from octobot_commons.dsl_interpreter.dsl_call_result import DSLCallResult

__all__ = [
"get_all_operators",
"clear_get_all_operators_cache",
"Interpreter",
"Operator",
"OperatorParameter",
"UNINITIALIZED_VALUE",
"OperatorDocs",
"BinaryOperator",
"UnaryOperator",
Expand All @@ -51,5 +63,9 @@
"CallOperator",
"NameOperator",
"ExpressionOperator",
"PreComputingCallOperator",
"InterpreterDependency",
"format_parameter_value",
"resove_operator_params",
"DSLCallResult",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Drakkar-Software OctoBot
# Copyright (c) Drakkar-Software, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.

import dataclasses
import typing
import octobot_commons.dataclasses
import octobot_commons.errors

@dataclasses.dataclass
class DSLCallResult(octobot_commons.dataclasses.FlexibleDataclass):
statement: str
result: typing.Optional[typing.Any] = None
error: typing.Optional[str] = None
105 changes: 98 additions & 7 deletions packages/commons/octobot_commons/dsl_interpreter/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import octobot_commons.errors
import octobot_commons.dsl_interpreter.operator as dsl_interpreter_operator
import octobot_commons.dsl_interpreter.interpreter_dependency as dsl_interpreter_dependency
import octobot_commons.dsl_interpreter.parameters_util as parameters_util
import octobot_commons.dsl_interpreter.dsl_call_result as dsl_call_result


class Interpreter:
Expand All @@ -45,6 +47,7 @@ def __init__(
dsl_interpreter_operator.Operator,
dsl_interpreter_operator.ComputedOperatorParameterType,
] = None
self._parsed_expression: typing.Optional[str] = None

def extend(
self, operators: typing.List[typing.Type[dsl_interpreter_operator.Operator]]
Expand Down Expand Up @@ -73,7 +76,7 @@ async def interprete(

def get_dependencies(
self,
) -> typing.List[dsl_interpreter_dependency.InterpreterDependency]:
) -> list[dsl_interpreter_dependency.InterpreterDependency]:
"""
Get the dependencies of the interpreter's parsed expression.
"""
Expand Down Expand Up @@ -109,10 +112,17 @@ def _parse_expression(self, expression: str):
# it consists of a single expression, or 'single' if it consists of a single
# interactive statement.
# docs: https://docs.python.org/3/library/functions.html#compile
tree = ast.parse(expression, mode="eval")

# Visit the AST and convert nodes to Operator instances
self._operator_tree_or_constant = self._visit_node(tree.body)
self._parsed_expression = expression
try:
tree = ast.parse(expression, mode="eval")
self._operator_tree_or_constant = self._visit_node(tree.body)
except SyntaxError:
tree = ast.parse(expression, mode="single")
if len(tree.body) != 1:
raise octobot_commons.errors.DSLInterpreterError(
"Single statement required when using statement mode"
)
self._operator_tree_or_constant = self._visit_node(tree.body[0])

async def compute_expression(
self,
Expand All @@ -129,6 +139,25 @@ async def compute_expression(
return self._operator_tree_or_constant.compute()
return self._operator_tree_or_constant

async def compute_expression_with_result(
self,
) -> dsl_call_result.DSLCallResult:
"""
Compute the result of the expression stored in self._operator_tree_or_constant.
If the expression is a constant, return it directly.
If the expression is an operator, pre_compute and compute its result.
"""
try:
return dsl_call_result.DSLCallResult(
statement=self._parsed_expression,
result=await self.compute_expression(),
)
except octobot_commons.errors.ErrorStatementEncountered as err:
return dsl_call_result.DSLCallResult(
statement=self._parsed_expression,
error=err.args[0] if err.args else ""
)

def _visit_node(self, node: typing.Optional[ast.AST]) -> typing.Union[
dsl_interpreter_operator.Operator,
dsl_interpreter_operator.ComputedOperatorParameterType,
Expand Down Expand Up @@ -159,7 +188,26 @@ def _visit_node(self, node: typing.Optional[ast.AST]) -> typing.Union[
)
for arg in node.args
]
return operator_class(*args)
kwargs = {}
for kw in node.keywords:
value = (
self._get_value_from_constant_node(kw.value)
if isinstance(kw.value, ast.Constant)
else self._visit_node(kw.value)
)
if kw.arg is not None:
kwargs[kw.arg] = value
else:
if isinstance(value, dict):
kwargs.update(value)
else:
raise octobot_commons.errors.UnsupportedOperatorError(
f"**kwargs must unpack a dict, got {type(value).__name__}"
)
args, kwargs = parameters_util.resolve_operator_args_and_kwargs(
operator_class, args, kwargs
)
return operator_class(*args, **kwargs)
raise octobot_commons.errors.UnsupportedOperatorError(
f"Unknown operator: {func_name}"
)
Expand Down Expand Up @@ -259,6 +307,23 @@ def _visit_node(self, node: typing.Optional[ast.AST]) -> typing.Union[
operands = [self._visit_node(operand) for operand in node.elts]
return operator_class(*operands)

if isinstance(node, ast.Dict):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

# Dict: {"a": 1, "b": 2} or {"a": 1, **other}
op_name = ast.Dict.__name__
result = {}
for key, value in zip(node.keys, node.values):
if key is not None:
result[self._visit_node(key)] = self._visit_node(value)
else:
unpacked = self._visit_node(value)
if isinstance(unpacked, dict):
result.update(unpacked)
else:
raise octobot_commons.errors.UnsupportedOperatorError(
f"** unpacking in dict requires a dict, got {type(unpacked).__name__}"
)
return result

if isinstance(node, ast.Slice):
# Slice: slice(1, 2, 3)
op_name = ast.Slice.__name__
Expand All @@ -269,6 +334,32 @@ def _visit_node(self, node: typing.Optional[ast.AST]) -> typing.Union[
step = self._visit_node(node.step)
return operator_class(lower, upper, step)

if isinstance(node, ast.Raise):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

# Raise statement: raise exc [from cause] - maps to RaiseOperator
op_name = "raise"
if op_name in self.operators_by_name:
operator_class = self.operators_by_name[op_name]
args = []
if node.exc is not None:
args.append(
self._get_value_from_constant_node(node.exc)
if isinstance(node.exc, ast.Constant)
else self._visit_node(node.exc)
)
if node.cause is not None:
args.append(
self._get_value_from_constant_node(node.cause)
if isinstance(node.cause, ast.Constant)
else self._visit_node(node.cause)
)
args, kwargs = parameters_util.resolve_operator_args_and_kwargs(
operator_class, args, {}
)
return operator_class(*args, **kwargs)
raise octobot_commons.errors.UnsupportedOperatorError(
f"Unknown operator: {op_name}"
)

raise octobot_commons.errors.UnsupportedOperatorError(
f"Unsupported AST node type: {type(node).__name__}"
)
Expand All @@ -289,7 +380,7 @@ def _get_value_from_constant_node(
"""Extract a literal value from an AST constant node."""
value = node.value
# Filter out unsupported types like complex numbers or Ellipsis
if isinstance(value, (str, int, float, bool, type(None))):
if isinstance(value, (str, int, float, bool, type(None), dict)):
return value
raise octobot_commons.errors.UnsupportedOperatorError(
f"Unsupported constant type: {type(value).__name__}"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# pylint: disable=too-many-branches,too-many-return-statements
# Drakkar-Software OctoBot-Commons
# Copyright (c) Drakkar-Software, All rights reserved.
#
Expand Down
Loading
Loading