2020-04-20 02:05:58 +02:00
|
|
|
import abc
|
2019-04-22 21:56:30 +02:00
|
|
|
import inspect
|
2019-03-18 15:07:20 +01:00
|
|
|
import math
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
# pylint: disable=unused-import, wrong-import-order
|
2020-04-20 02:05:58 +02:00
|
|
|
from typing import Any, Generator, List, Optional, Tuple, Type, Union, Sequence
|
2019-04-08 18:08:58 +02:00
|
|
|
|
|
|
|
from esphome.core import ( # noqa
|
|
|
|
CORE, HexInt, ID, Lambda, TimePeriod, TimePeriodMicroseconds,
|
2019-04-22 21:56:30 +02:00
|
|
|
TimePeriodMilliseconds, TimePeriodMinutes, TimePeriodSeconds, coroutine, Library, Define,
|
|
|
|
EnumValue)
|
2019-04-08 18:08:58 +02:00
|
|
|
from esphome.helpers import cpp_string_escape, indent_all_but_first_and_last
|
2019-04-17 12:06:00 +02:00
|
|
|
from esphome.util import OrderedDict
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
class Expression(abc.ABC):
|
|
|
|
__slots__ = ()
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
2018-12-05 21:22:06 +01:00
|
|
|
def __str__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
"""
|
|
|
|
Convert expression into C++ code
|
|
|
|
"""
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2019-12-07 18:28:55 +01:00
|
|
|
SafeExpType = Union[Expression, bool, str, str, int, float, TimePeriod,
|
2020-04-20 02:05:58 +02:00
|
|
|
Type[bool], Type[int], Type[float], Sequence[Any]]
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class RawExpression(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("text", )
|
|
|
|
|
|
|
|
def __init__(self, text: str):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.text = text
|
|
|
|
|
|
|
|
def __str__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
return self.text
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class AssignmentExpression(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("type", "modifier", "name", "rhs", "obj")
|
|
|
|
|
|
|
|
def __init__(self, type_, modifier, name, rhs, obj):
|
|
|
|
self.type = type_
|
2018-12-05 21:22:06 +01:00
|
|
|
self.modifier = modifier
|
|
|
|
self.name = name
|
|
|
|
self.rhs = safe_exp(rhs)
|
|
|
|
self.obj = obj
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-04-17 12:06:00 +02:00
|
|
|
if self.type is None:
|
2019-12-07 18:28:55 +01:00
|
|
|
return f"{self.name} = {self.rhs}"
|
|
|
|
return f"{self.type} {self.modifier}{self.name} = {self.rhs}"
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2019-04-17 12:06:00 +02:00
|
|
|
|
|
|
|
class VariableDeclarationExpression(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("type", "modifier", "name")
|
|
|
|
|
|
|
|
def __init__(self, type_, modifier, name):
|
|
|
|
self.type = type_
|
2019-04-17 12:06:00 +02:00
|
|
|
self.modifier = modifier
|
|
|
|
self.name = name
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return f"{self.type} {self.modifier}{self.name}"
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class ExpressionList(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("args", )
|
|
|
|
|
|
|
|
def __init__(self, *args: Optional[SafeExpType]):
|
2018-12-05 21:22:06 +01:00
|
|
|
# Remove every None on end
|
|
|
|
args = list(args)
|
|
|
|
while args and args[-1] is None:
|
|
|
|
args.pop()
|
2019-04-17 12:06:00 +02:00
|
|
|
self.args = [safe_exp(arg) for arg in args]
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
text = ", ".join(str(x) for x in self.args)
|
2018-12-05 21:22:06 +01:00
|
|
|
return indent_all_but_first_and_last(text)
|
|
|
|
|
2019-04-24 23:49:02 +02:00
|
|
|
def __iter__(self):
|
|
|
|
return iter(self.args)
|
|
|
|
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
class TemplateArguments(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("args", )
|
|
|
|
|
|
|
|
def __init__(self, *args: SafeExpType):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.args = ExpressionList(*args)
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return f'<{self.args}>'
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2019-04-24 23:49:02 +02:00
|
|
|
def __iter__(self):
|
|
|
|
return iter(self.args)
|
|
|
|
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
class CallExpression(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("base", "template_args", "args")
|
|
|
|
|
|
|
|
def __init__(self, base: Expression, *args: SafeExpType):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.base = base
|
|
|
|
if args and isinstance(args[0], TemplateArguments):
|
|
|
|
self.template_args = args[0]
|
|
|
|
args = args[1:]
|
|
|
|
else:
|
|
|
|
self.template_args = None
|
|
|
|
self.args = ExpressionList(*args)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
if self.template_args is not None:
|
2019-12-07 18:28:55 +01:00
|
|
|
return f'{self.base}{self.template_args}({self.args})'
|
|
|
|
return f'{self.base}({self.args})'
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class StructInitializer(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("base", "args")
|
|
|
|
|
|
|
|
def __init__(self, base: Expression, *args: Tuple[str, Optional[SafeExpType]]):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.base = base
|
2020-04-20 02:05:58 +02:00
|
|
|
# TODO: args is always a Tuple, is this check required?
|
2018-12-05 21:22:06 +01:00
|
|
|
if not isinstance(args, OrderedDict):
|
|
|
|
args = OrderedDict(args)
|
|
|
|
self.args = OrderedDict()
|
2019-01-02 14:11:11 +01:00
|
|
|
for key, value in args.items():
|
2018-12-05 21:22:06 +01:00
|
|
|
if value is None:
|
|
|
|
continue
|
|
|
|
exp = safe_exp(value)
|
|
|
|
self.args[key] = exp
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
cpp = f'{self.base}{{\n'
|
2019-01-02 14:11:11 +01:00
|
|
|
for key, value in self.args.items():
|
2019-12-07 18:28:55 +01:00
|
|
|
cpp += f' .{key} = {value},\n'
|
|
|
|
cpp += '}'
|
2018-12-05 21:22:06 +01:00
|
|
|
return cpp
|
|
|
|
|
|
|
|
|
|
|
|
class ArrayInitializer(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("multiline", "args")
|
|
|
|
|
|
|
|
def __init__(self, *args: Any, multiline: bool = False):
|
|
|
|
self.multiline = multiline
|
2018-12-05 21:22:06 +01:00
|
|
|
self.args = []
|
|
|
|
for arg in args:
|
|
|
|
if arg is None:
|
|
|
|
continue
|
|
|
|
exp = safe_exp(arg)
|
|
|
|
self.args.append(exp)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
if not self.args:
|
2019-12-07 18:28:55 +01:00
|
|
|
return '{}'
|
2018-12-05 21:22:06 +01:00
|
|
|
if self.multiline:
|
2019-12-07 18:28:55 +01:00
|
|
|
cpp = '{\n'
|
2018-12-05 21:22:06 +01:00
|
|
|
for arg in self.args:
|
2019-12-07 18:28:55 +01:00
|
|
|
cpp += f' {arg},\n'
|
|
|
|
cpp += '}'
|
2018-12-05 21:22:06 +01:00
|
|
|
else:
|
2019-12-07 18:28:55 +01:00
|
|
|
cpp = '{' + ', '.join(str(arg) for arg in self.args) + '}'
|
2018-12-05 21:22:06 +01:00
|
|
|
return cpp
|
|
|
|
|
|
|
|
|
|
|
|
class ParameterExpression(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("type", "id")
|
|
|
|
|
|
|
|
def __init__(self, type_, id_):
|
|
|
|
self.type = safe_exp(type_)
|
|
|
|
self.id = id_
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return f"{self.type} {self.id}"
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class ParameterListExpression(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("parameters", )
|
|
|
|
|
|
|
|
def __init__(self, *parameters: Union[ParameterExpression, Tuple[SafeExpType, str]]):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.parameters = []
|
|
|
|
for parameter in parameters:
|
|
|
|
if not isinstance(parameter, ParameterExpression):
|
|
|
|
parameter = ParameterExpression(*parameter)
|
|
|
|
self.parameters.append(parameter)
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return ", ".join(str(x) for x in self.parameters)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class LambdaExpression(Expression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("parts", "parameters", "capture", "return_type")
|
|
|
|
|
|
|
|
def __init__(self, parts, parameters, capture: str = '=', return_type=None):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.parts = parts
|
|
|
|
if not isinstance(parameters, ParameterListExpression):
|
|
|
|
parameters = ParameterListExpression(*parameters)
|
|
|
|
self.parameters = parameters
|
|
|
|
self.capture = capture
|
2019-04-08 18:08:58 +02:00
|
|
|
self.return_type = safe_exp(return_type) if return_type is not None else None
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
cpp = f'[{self.capture}]({self.parameters})'
|
2018-12-05 21:22:06 +01:00
|
|
|
if self.return_type is not None:
|
2019-12-07 18:28:55 +01:00
|
|
|
cpp += f' -> {self.return_type}'
|
|
|
|
cpp += f' {{\n{self.content}\n}}'
|
2018-12-05 21:22:06 +01:00
|
|
|
return indent_all_but_first_and_last(cpp)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def content(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return ''.join(str(part) for part in self.parts)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
# pylint: disable=abstract-method
|
|
|
|
class Literal(Expression, metaclass=abc.ABCMeta):
|
|
|
|
__slots__ = ()
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class StringLiteral(Literal):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("string", )
|
|
|
|
|
|
|
|
def __init__(self, string: str):
|
2020-05-24 01:33:58 +02:00
|
|
|
super().__init__()
|
2018-12-05 21:22:06 +01:00
|
|
|
self.string = string
|
|
|
|
|
|
|
|
def __str__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
return cpp_string_escape(self.string)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class IntLiteral(Literal):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("i", )
|
|
|
|
|
|
|
|
def __init__(self, i: int):
|
2020-05-24 01:33:58 +02:00
|
|
|
super().__init__()
|
2018-12-05 21:22:06 +01:00
|
|
|
self.i = i
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
if self.i > 4294967295:
|
2019-12-07 18:28:55 +01:00
|
|
|
return f'{self.i}ULL'
|
2018-12-05 21:22:06 +01:00
|
|
|
if self.i > 2147483647:
|
2019-12-07 18:28:55 +01:00
|
|
|
return f'{self.i}UL'
|
2018-12-05 21:22:06 +01:00
|
|
|
if self.i < -2147483648:
|
2019-12-07 18:28:55 +01:00
|
|
|
return f'{self.i}LL'
|
|
|
|
return str(self.i)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class BoolLiteral(Literal):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("binary", )
|
|
|
|
|
|
|
|
def __init__(self, binary: bool):
|
2019-12-07 18:28:55 +01:00
|
|
|
super().__init__()
|
2018-12-05 21:22:06 +01:00
|
|
|
self.binary = binary
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return "true" if self.binary else "false"
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class HexIntLiteral(Literal):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("i", )
|
|
|
|
|
|
|
|
def __init__(self, i: int):
|
2020-05-24 01:33:58 +02:00
|
|
|
super().__init__()
|
2018-12-05 21:22:06 +01:00
|
|
|
self.i = HexInt(i)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return str(self.i)
|
|
|
|
|
|
|
|
|
|
|
|
class FloatLiteral(Literal):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("f", )
|
|
|
|
|
|
|
|
def __init__(self, value: float):
|
2020-05-24 01:33:58 +02:00
|
|
|
super().__init__()
|
2020-04-20 02:05:58 +02:00
|
|
|
self.f = value
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
def __str__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
if math.isnan(self.f):
|
2019-12-07 18:28:55 +01:00
|
|
|
return "NAN"
|
2020-04-20 02:05:58 +02:00
|
|
|
return f"{self.f}f"
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def safe_exp(obj: SafeExpType) -> Expression:
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Try to convert obj to an expression by automatically converting native python types to
|
|
|
|
expressions/literals.
|
|
|
|
"""
|
2019-04-08 18:08:58 +02:00
|
|
|
from esphome.cpp_types import bool_, float_, int32
|
|
|
|
|
2018-12-05 21:22:06 +01:00
|
|
|
if isinstance(obj, Expression):
|
|
|
|
return obj
|
2019-04-22 21:56:30 +02:00
|
|
|
if isinstance(obj, EnumValue):
|
|
|
|
return safe_exp(obj.enum_value)
|
2019-01-02 14:11:11 +01:00
|
|
|
if isinstance(obj, bool):
|
2018-12-05 21:22:06 +01:00
|
|
|
return BoolLiteral(obj)
|
2019-12-07 18:28:55 +01:00
|
|
|
if isinstance(obj, str):
|
2018-12-05 21:22:06 +01:00
|
|
|
return StringLiteral(obj)
|
2019-01-02 14:11:11 +01:00
|
|
|
if isinstance(obj, HexInt):
|
2018-12-05 21:22:06 +01:00
|
|
|
return HexIntLiteral(obj)
|
2019-12-07 18:28:55 +01:00
|
|
|
if isinstance(obj, int):
|
2018-12-05 21:22:06 +01:00
|
|
|
return IntLiteral(obj)
|
2019-01-02 14:11:11 +01:00
|
|
|
if isinstance(obj, float):
|
2018-12-05 21:22:06 +01:00
|
|
|
return FloatLiteral(obj)
|
2019-01-02 14:11:11 +01:00
|
|
|
if isinstance(obj, TimePeriodMicroseconds):
|
2018-12-05 21:22:06 +01:00
|
|
|
return IntLiteral(int(obj.total_microseconds))
|
2019-01-02 14:11:11 +01:00
|
|
|
if isinstance(obj, TimePeriodMilliseconds):
|
2018-12-05 21:22:06 +01:00
|
|
|
return IntLiteral(int(obj.total_milliseconds))
|
2019-01-02 14:11:11 +01:00
|
|
|
if isinstance(obj, TimePeriodSeconds):
|
2018-12-05 21:22:06 +01:00
|
|
|
return IntLiteral(int(obj.total_seconds))
|
2019-03-06 12:39:52 +01:00
|
|
|
if isinstance(obj, TimePeriodMinutes):
|
|
|
|
return IntLiteral(int(obj.total_minutes))
|
2019-02-03 20:46:18 +01:00
|
|
|
if isinstance(obj, (tuple, list)):
|
|
|
|
return ArrayInitializer(*[safe_exp(o) for o in obj])
|
2019-04-08 18:08:58 +02:00
|
|
|
if obj is bool:
|
|
|
|
return bool_
|
|
|
|
if obj is int:
|
|
|
|
return int32
|
|
|
|
if obj is float:
|
|
|
|
return float_
|
2019-04-22 21:56:30 +02:00
|
|
|
if isinstance(obj, ID):
|
2019-12-07 18:28:55 +01:00
|
|
|
raise ValueError("Object {} is an ID. Did you forget to register the variable?"
|
|
|
|
"".format(obj))
|
2019-04-22 21:56:30 +02:00
|
|
|
if inspect.isgenerator(obj):
|
2019-12-07 18:28:55 +01:00
|
|
|
raise ValueError("Object {} is a coroutine. Did you forget to await the expression with "
|
|
|
|
"'yield'?".format(obj))
|
|
|
|
raise ValueError("Object is not an expression", obj)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
class Statement(abc.ABC):
|
|
|
|
__slots__ = ()
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
@abc.abstractmethod
|
2018-12-05 21:22:06 +01:00
|
|
|
def __str__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
"""
|
|
|
|
Convert statement into C++ code
|
|
|
|
"""
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class RawStatement(Statement):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("text", )
|
|
|
|
|
|
|
|
def __init__(self, text: str):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.text = text
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.text
|
|
|
|
|
|
|
|
|
|
|
|
class ExpressionStatement(Statement):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("expression", )
|
|
|
|
|
2018-12-05 21:22:06 +01:00
|
|
|
def __init__(self, expression):
|
|
|
|
self.expression = safe_exp(expression)
|
|
|
|
|
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return f"{self.expression};"
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2019-05-12 23:04:36 +02:00
|
|
|
class LineComment(Statement):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("value", )
|
|
|
|
|
|
|
|
def __init__(self, value: str):
|
|
|
|
self.value = value
|
2019-05-12 23:04:36 +02:00
|
|
|
|
|
|
|
def __str__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
parts = self.value.split('\n')
|
2019-12-07 18:28:55 +01:00
|
|
|
parts = [f'// {x}' for x in parts]
|
|
|
|
return '\n'.join(parts)
|
2019-05-12 23:04:36 +02:00
|
|
|
|
|
|
|
|
2019-02-10 16:41:12 +01:00
|
|
|
class ProgmemAssignmentExpression(AssignmentExpression):
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ()
|
|
|
|
|
|
|
|
def __init__(self, type_, name, rhs, obj):
|
|
|
|
super().__init__(type_, '', name, rhs, obj)
|
2019-02-10 16:41:12 +01:00
|
|
|
|
|
|
|
def __str__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
return f"static const {self.type} {self.name}[] PROGMEM = {self.rhs}"
|
2019-02-10 16:41:12 +01:00
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def progmem_array(id_, rhs) -> "MockObj":
|
2019-02-10 16:41:12 +01:00
|
|
|
rhs = safe_exp(rhs)
|
2020-04-20 02:05:58 +02:00
|
|
|
obj = MockObj(id_, '.')
|
|
|
|
assignment = ProgmemAssignmentExpression(id_.type, id_, rhs, obj)
|
2019-02-10 16:41:12 +01:00
|
|
|
CORE.add(assignment)
|
2020-04-20 02:05:58 +02:00
|
|
|
CORE.register_variable(id_, obj)
|
2019-02-10 16:41:12 +01:00
|
|
|
return obj
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def statement(expression: Union[Expression, Statement]) -> Statement:
|
|
|
|
"""Convert expression into a statement unless is already a statement.
|
|
|
|
"""
|
2018-12-05 21:22:06 +01:00
|
|
|
if isinstance(expression, Statement):
|
|
|
|
return expression
|
|
|
|
return ExpressionStatement(expression)
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def variable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj":
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Declare a new variable (not pointer type) in the code generation.
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
:param id_: The ID used to declare the variable.
|
2019-04-22 21:56:30 +02:00
|
|
|
:param rhs: The expression to place on the right hand side of the assignment.
|
2020-04-20 02:05:58 +02:00
|
|
|
:param type_: Manually define a type for the variable, only use this when it's not possible
|
2019-04-22 21:56:30 +02:00
|
|
|
to do so during config validation phase (for example because of template arguments).
|
|
|
|
|
|
|
|
:returns The new variable as a MockObj.
|
|
|
|
"""
|
2020-04-20 02:05:58 +02:00
|
|
|
assert isinstance(id_, ID)
|
2018-12-05 21:22:06 +01:00
|
|
|
rhs = safe_exp(rhs)
|
2020-04-20 02:05:58 +02:00
|
|
|
obj = MockObj(id_, '.')
|
|
|
|
if type_ is not None:
|
|
|
|
id_.type = type_
|
|
|
|
assignment = AssignmentExpression(id_.type, '', id_, rhs, obj)
|
2018-12-05 21:22:06 +01:00
|
|
|
CORE.add(assignment)
|
2020-04-20 02:05:58 +02:00
|
|
|
CORE.register_variable(id_, obj)
|
2018-12-05 21:22:06 +01:00
|
|
|
return obj
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def Pvariable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj":
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Declare a new pointer variable in the code generation.
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
:param id_: The ID used to declare the variable.
|
2019-04-22 21:56:30 +02:00
|
|
|
:param rhs: The expression to place on the right hand side of the assignment.
|
2020-04-20 02:05:58 +02:00
|
|
|
:param type_: Manually define a type for the variable, only use this when it's not possible
|
2019-04-22 21:56:30 +02:00
|
|
|
to do so during config validation phase (for example because of template arguments).
|
|
|
|
|
|
|
|
:returns The new variable as a MockObj.
|
|
|
|
"""
|
2018-12-05 21:22:06 +01:00
|
|
|
rhs = safe_exp(rhs)
|
2020-04-20 02:05:58 +02:00
|
|
|
obj = MockObj(id_, '->')
|
|
|
|
if type_ is not None:
|
|
|
|
id_.type = type_
|
|
|
|
decl = VariableDeclarationExpression(id_.type, '*', id_)
|
2019-04-17 12:06:00 +02:00
|
|
|
CORE.add_global(decl)
|
2020-04-20 02:05:58 +02:00
|
|
|
assignment = AssignmentExpression(None, None, id_, rhs, obj)
|
2018-12-05 21:22:06 +01:00
|
|
|
CORE.add(assignment)
|
2020-04-20 02:05:58 +02:00
|
|
|
CORE.register_variable(id_, obj)
|
2018-12-05 21:22:06 +01:00
|
|
|
return obj
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def new_Pvariable(id_: ID, *args: SafeExpType) -> Pvariable:
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Declare a new pointer variable in the code generation by calling it's constructor
|
|
|
|
with the given arguments.
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
:param id_: The ID used to declare the variable (also specifies the type).
|
2019-04-22 21:56:30 +02:00
|
|
|
:param args: The values to pass to the constructor.
|
|
|
|
|
|
|
|
:returns The new variable as a MockObj.
|
|
|
|
"""
|
|
|
|
if args and isinstance(args[0], TemplateArguments):
|
2020-04-20 02:05:58 +02:00
|
|
|
id_ = id_.copy()
|
|
|
|
id_.type = id_.type.template(args[0])
|
2019-04-22 21:56:30 +02:00
|
|
|
args = args[1:]
|
2020-04-20 02:05:58 +02:00
|
|
|
rhs = id_.type.new(*args)
|
|
|
|
return Pvariable(id_, rhs)
|
2019-04-17 12:06:00 +02:00
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def add(expression: Union[Expression, Statement]):
|
2019-05-11 12:31:00 +02:00
|
|
|
"""Add an expression to the codegen section.
|
|
|
|
|
|
|
|
After this is called, the given given expression will
|
|
|
|
show up in the setup() function after this has been called.
|
|
|
|
"""
|
2019-04-17 12:06:00 +02:00
|
|
|
CORE.add(expression)
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def add_global(expression: Union[SafeExpType, Statement]):
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Add an expression to the codegen global storage (above setup())."""
|
2019-04-17 12:06:00 +02:00
|
|
|
CORE.add_global(expression)
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def add_library(name: str, version: Optional[str]):
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Add a library to the codegen library storage.
|
|
|
|
|
|
|
|
:param name: The name of the library (for example 'AsyncTCP')
|
|
|
|
:param version: The version of the library, may be None.
|
|
|
|
"""
|
2019-04-17 12:06:00 +02:00
|
|
|
CORE.add_library(Library(name, version))
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def add_build_flag(build_flag: str):
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Add a global build flag to the compiler flags."""
|
2019-04-17 12:06:00 +02:00
|
|
|
CORE.add_build_flag(build_flag)
|
|
|
|
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def add_define(name: str, value: SafeExpType = None):
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Add a global define to the auto-generated defines.h file.
|
|
|
|
|
|
|
|
Optionally define a value to set this define to.
|
|
|
|
"""
|
2019-04-17 12:06:00 +02:00
|
|
|
if value is None:
|
|
|
|
CORE.add_define(Define(name))
|
|
|
|
else:
|
|
|
|
CORE.add_define(Define(name, safe_exp(value)))
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2019-04-09 14:30:12 +02:00
|
|
|
@coroutine
|
2020-04-20 02:05:58 +02:00
|
|
|
def get_variable(id_: ID) -> Generator["MockObj", None, None]:
|
2019-04-22 21:56:30 +02:00
|
|
|
"""
|
|
|
|
Wait for the given ID to be defined in the code generation and
|
|
|
|
return it as a MockObj.
|
|
|
|
|
|
|
|
This is a coroutine, you need to await it with a 'yield' expression!
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
:param id_: The ID to retrieve
|
2019-04-22 21:56:30 +02:00
|
|
|
:return: The variable as a MockObj.
|
|
|
|
"""
|
2020-04-20 02:05:58 +02:00
|
|
|
var = yield CORE.get_variable(id_)
|
2018-12-05 21:22:06 +01:00
|
|
|
yield var
|
|
|
|
|
|
|
|
|
2019-04-24 23:49:02 +02:00
|
|
|
@coroutine
|
2020-04-20 02:05:58 +02:00
|
|
|
def get_variable_with_full_id(id_: ID) -> Generator[Tuple[ID, "MockObj"], None, None]:
|
2019-04-24 23:49:02 +02:00
|
|
|
"""
|
|
|
|
Wait for the given ID to be defined in the code generation and
|
|
|
|
return it as a MockObj.
|
|
|
|
|
|
|
|
This is a coroutine, you need to await it with a 'yield' expression!
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
:param id_: The ID to retrieve
|
2019-04-24 23:49:02 +02:00
|
|
|
:return: The variable as a MockObj.
|
|
|
|
"""
|
2020-04-20 02:05:58 +02:00
|
|
|
full_id, var = yield CORE.get_variable_with_full_id(id_)
|
2019-04-24 23:49:02 +02:00
|
|
|
yield full_id, var
|
|
|
|
|
|
|
|
|
2019-04-09 14:30:12 +02:00
|
|
|
@coroutine
|
2020-04-20 02:05:58 +02:00
|
|
|
def process_lambda(
|
|
|
|
value: Lambda, parameters: List[Tuple[SafeExpType, str]],
|
|
|
|
capture: str = '=', return_type: SafeExpType = None
|
|
|
|
) -> Generator[LambdaExpression, None, None]:
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Process the given lambda value into a LambdaExpression.
|
|
|
|
|
|
|
|
This is a coroutine because lambdas can depend on other IDs,
|
|
|
|
you need to await it with 'yield'!
|
|
|
|
|
|
|
|
:param value: The lambda to process.
|
|
|
|
:param parameters: The parameters to pass to the Lambda, list of tuples
|
|
|
|
:param capture: The capture expression for the lambda, usually ''.
|
|
|
|
:param return_type: The return type of the lambda.
|
|
|
|
:return: The generated lambda expression.
|
|
|
|
"""
|
2019-04-17 12:06:00 +02:00
|
|
|
from esphome.components.globals import GlobalsComponent
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
if value is None:
|
|
|
|
yield
|
|
|
|
return
|
|
|
|
parts = value.parts[:]
|
|
|
|
for i, id in enumerate(value.requires_ids):
|
2019-04-09 14:30:12 +02:00
|
|
|
full_id, var = yield CORE.get_variable_with_full_id(id)
|
2018-12-05 21:22:06 +01:00
|
|
|
if full_id is not None and isinstance(full_id.type, MockObjClass) and \
|
2019-04-17 12:06:00 +02:00
|
|
|
full_id.type.inherits_from(GlobalsComponent):
|
2018-12-05 21:22:06 +01:00
|
|
|
parts[i * 3 + 1] = var.value()
|
|
|
|
continue
|
|
|
|
|
|
|
|
if parts[i * 3 + 2] == '.':
|
|
|
|
parts[i * 3 + 1] = var._
|
|
|
|
else:
|
|
|
|
parts[i * 3 + 1] = var
|
|
|
|
parts[i * 3 + 2] = ''
|
|
|
|
yield LambdaExpression(parts, parameters, capture, return_type)
|
|
|
|
|
|
|
|
|
2019-04-17 12:06:00 +02:00
|
|
|
def is_template(value):
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Return if value is a lambda expression."""
|
2019-04-17 12:06:00 +02:00
|
|
|
return isinstance(value, Lambda)
|
|
|
|
|
|
|
|
|
2019-04-09 14:30:12 +02:00
|
|
|
@coroutine
|
2020-04-20 02:05:58 +02:00
|
|
|
def templatable(value: Any,
|
|
|
|
args: List[Tuple[SafeExpType, str]],
|
|
|
|
output_type: Optional[SafeExpType],
|
|
|
|
to_exp: Any = None):
|
2019-04-22 21:56:30 +02:00
|
|
|
"""Generate code for a templatable config option.
|
|
|
|
|
|
|
|
If `value` is a templated value, the lambda expression is returned.
|
|
|
|
Otherwise the value is returned as-is (optionally process with to_exp).
|
|
|
|
|
|
|
|
:param value: The value to process.
|
|
|
|
:param args: The arguments for the lambda expression.
|
|
|
|
:param output_type: The output type of the lambda expression.
|
|
|
|
:param to_exp: An optional callable to use for converting non-templated values.
|
|
|
|
:return: The potentially templated value.
|
|
|
|
"""
|
2019-04-17 12:06:00 +02:00
|
|
|
if is_template(value):
|
2019-04-09 14:30:12 +02:00
|
|
|
lambda_ = yield process_lambda(value, args, return_type=output_type)
|
2018-12-05 21:22:06 +01:00
|
|
|
yield lambda_
|
|
|
|
else:
|
2019-04-08 18:08:58 +02:00
|
|
|
if to_exp is None:
|
|
|
|
yield value
|
|
|
|
elif isinstance(to_exp, dict):
|
|
|
|
yield to_exp[value]
|
|
|
|
else:
|
|
|
|
yield to_exp(value)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
|
|
|
class MockObj(Expression):
|
2019-04-22 21:56:30 +02:00
|
|
|
"""A general expression that can be used to represent any value.
|
|
|
|
|
|
|
|
Mostly consists of magic methods that allow ESPHome's codegen syntax.
|
|
|
|
"""
|
2020-04-20 02:05:58 +02:00
|
|
|
__slots__ = ("base", "op")
|
|
|
|
|
2019-12-07 18:28:55 +01:00
|
|
|
def __init__(self, base, op='.'):
|
2018-12-05 21:22:06 +01:00
|
|
|
self.base = base
|
|
|
|
self.op = op
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def __getattr__(self, attr: str) -> "MockObj":
|
2019-12-07 18:28:55 +01:00
|
|
|
next_op = '.'
|
|
|
|
if attr.startswith('P') and self.op not in ['::', '']:
|
2018-12-05 21:22:06 +01:00
|
|
|
attr = attr[1:]
|
2019-12-07 18:28:55 +01:00
|
|
|
next_op = '->'
|
|
|
|
if attr.startswith('_'):
|
2018-12-05 21:22:06 +01:00
|
|
|
attr = attr[1:]
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'{self.base}{self.op}{attr}', next_op)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2019-04-24 23:49:02 +02:00
|
|
|
def __call__(self, *args): # type: (SafeExpType) -> MockObj
|
2018-12-05 21:22:06 +01:00
|
|
|
call = CallExpression(self.base, *args)
|
2019-04-17 12:06:00 +02:00
|
|
|
return MockObj(call, self.op)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def __str__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return str(self.base)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2019-04-17 12:06:00 +02:00
|
|
|
def __repr__(self):
|
2019-12-07 18:28:55 +01:00
|
|
|
return 'MockObj<{}>'.format(str(self.base))
|
2019-04-17 12:06:00 +02:00
|
|
|
|
|
|
|
@property
|
2020-04-20 02:05:58 +02:00
|
|
|
def _(self) -> "MockObj":
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'{self.base}{self.op}')
|
2019-04-17 12:06:00 +02:00
|
|
|
|
|
|
|
@property
|
2020-04-20 02:05:58 +02:00
|
|
|
def new(self) -> "MockObj":
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'new {self.base}', '->')
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def template(self, *args: SafeExpType) -> "MockObj":
|
2019-02-26 19:28:11 +01:00
|
|
|
if len(args) != 1 or not isinstance(args[0], TemplateArguments):
|
|
|
|
args = TemplateArguments(*args)
|
|
|
|
else:
|
|
|
|
args = args[0]
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'{self.base}{args}')
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def namespace(self, name: str) -> "MockObj":
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'{self._}{name}', '::')
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def class_(self, name: str, *parents: "MockObjClass") -> "MockObjClass":
|
2018-12-05 21:22:06 +01:00
|
|
|
op = '' if self.op == '' else '::'
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObjClass(f'{self.base}{op}{name}', '.', parents=parents)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def struct(self, name: str) -> "MockObjClass":
|
2018-12-05 21:22:06 +01:00
|
|
|
return self.class_(name)
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def enum(self, name: str, is_class: bool = False) -> "MockObj":
|
2019-04-24 23:49:02 +02:00
|
|
|
return MockObjEnum(enum=name, is_class=is_class, base=self.base, op=self.op)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def operator(self, name: str) -> "MockObj":
|
2018-12-05 21:22:06 +01:00
|
|
|
if name == 'ref':
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'{self.base} &', '')
|
2018-12-05 21:22:06 +01:00
|
|
|
if name == 'ptr':
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'{self.base} *', '')
|
2018-12-05 21:22:06 +01:00
|
|
|
if name == "const":
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'const {self.base}', '')
|
2020-04-20 02:05:58 +02:00
|
|
|
raise ValueError("Expected one of ref, ptr, const.")
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2019-04-17 12:06:00 +02:00
|
|
|
@property
|
2020-04-20 02:05:58 +02:00
|
|
|
def using(self) -> "MockObj":
|
2019-04-17 12:06:00 +02:00
|
|
|
assert self.op == '::'
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObj(f'using namespace {self.base}')
|
2018-12-05 21:22:06 +01:00
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def __getitem__(self, item: Union[str, Expression]) -> "MockObj":
|
2019-12-07 18:28:55 +01:00
|
|
|
next_op = '.'
|
|
|
|
if isinstance(item, str) and item.startswith('P'):
|
2018-12-05 21:22:06 +01:00
|
|
|
item = item[1:]
|
2019-12-07 18:28:55 +01:00
|
|
|
next_op = '->'
|
|
|
|
return MockObj(f'{self.base}[{item}]', next_op)
|
2018-12-05 21:22:06 +01:00
|
|
|
|
|
|
|
|
2019-04-24 23:49:02 +02:00
|
|
|
class MockObjEnum(MockObj):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self._enum = kwargs.pop('enum')
|
|
|
|
self._is_class = kwargs.pop('is_class')
|
|
|
|
base = kwargs.pop('base')
|
|
|
|
if self._is_class:
|
|
|
|
base = base + '::' + self._enum
|
|
|
|
kwargs['op'] = '::'
|
|
|
|
kwargs['base'] = base
|
|
|
|
MockObj.__init__(self, *args, **kwargs)
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def __str__(self):
|
2019-04-24 23:49:02 +02:00
|
|
|
if self._is_class:
|
2019-12-07 18:28:55 +01:00
|
|
|
return super().__str__()
|
|
|
|
return f'{self.base}{self.op}{self._enum}'
|
2019-04-24 23:49:02 +02:00
|
|
|
|
|
|
|
def __repr__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
return f'MockObj<{str(self.base)}>'
|
2019-04-24 23:49:02 +02:00
|
|
|
|
|
|
|
|
2018-12-05 21:22:06 +01:00
|
|
|
class MockObjClass(MockObj):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
parens = kwargs.pop('parents')
|
|
|
|
MockObj.__init__(self, *args, **kwargs)
|
|
|
|
self._parents = []
|
|
|
|
for paren in parens:
|
|
|
|
if not isinstance(paren, MockObjClass):
|
|
|
|
raise ValueError
|
|
|
|
self._parents.append(paren)
|
|
|
|
# pylint: disable=protected-access
|
|
|
|
self._parents += paren._parents
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def inherits_from(self, other: "MockObjClass") -> bool:
|
2018-12-05 21:22:06 +01:00
|
|
|
if self == other:
|
|
|
|
return True
|
|
|
|
for parent in self._parents:
|
|
|
|
if parent == other:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2020-04-20 02:05:58 +02:00
|
|
|
def template(self, *args: SafeExpType) -> "MockObjClass":
|
2019-02-26 19:28:11 +01:00
|
|
|
if len(args) != 1 or not isinstance(args[0], TemplateArguments):
|
|
|
|
args = TemplateArguments(*args)
|
|
|
|
else:
|
|
|
|
args = args[0]
|
2018-12-05 21:22:06 +01:00
|
|
|
new_parents = self._parents[:]
|
|
|
|
new_parents.append(self)
|
2019-12-07 18:28:55 +01:00
|
|
|
return MockObjClass(f'{self.base}{args}', parents=new_parents)
|
2019-04-17 12:06:00 +02:00
|
|
|
|
|
|
|
def __repr__(self):
|
2020-04-20 02:05:58 +02:00
|
|
|
return f'MockObjClass<{str(self.base)}, parents={self._parents}>'
|