From 818a7f1c78442273ed1dd91b3fc094956f039dc7 Mon Sep 17 00:00:00 2001 From: Keith Burzinski Date: Fri, 19 Mar 2021 05:40:05 -0500 Subject: [PATCH] Declare Color objects in main.cpp (#1395) --- esphome/codegen.py | 1 + esphome/components/color/__init__.py | 2 +- esphome/cpp_generator.py | 23 +++++++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/esphome/codegen.py b/esphome/codegen.py index 57316ab4fa..90f59f75bc 100644 --- a/esphome/codegen.py +++ b/esphome/codegen.py @@ -21,6 +21,7 @@ from esphome.cpp_generator import ( # noqa progmem_array, statement, variable, + new_variable, Pvariable, new_Pvariable, add, diff --git a/esphome/components/color/__init__.py b/esphome/components/color/__init__.py index 7c044040ee..6712d078a4 100644 --- a/esphome/components/color/__init__.py +++ b/esphome/components/color/__init__.py @@ -51,7 +51,7 @@ def to_code(config): elif CONF_WHITE_INT in config: w = config[CONF_WHITE_INT] - cg.variable( + cg.new_variable( config[CONF_ID], cg.StructInitializer(ColorStruct, ("r", r), ("g", g), ("b", b), ("w", w)), ) diff --git a/esphome/cpp_generator.py b/esphome/cpp_generator.py index 754ce229a9..999b252dde 100644 --- a/esphome/cpp_generator.py +++ b/esphome/cpp_generator.py @@ -448,6 +448,29 @@ def variable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj": return obj +def new_variable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj": + """Declare and define a new variable, not pointer type, in the code generation. + + :param id_: The ID used to declare the variable. + :param rhs: The expression to place on the right hand side of the assignment. + :param type_: Manually define a type for the variable, only use this when it's not possible + to do so during config validation phase (for example because of template arguments). + + :returns The new variable as a MockObj. + """ + assert isinstance(id_, ID) + rhs = safe_exp(rhs) + obj = MockObj(id_, ".") + if type_ is not None: + id_.type = type_ + decl = VariableDeclarationExpression(id_.type, "", id_) + CORE.add_global(decl) + assignment = AssignmentExpression(None, "", id_, rhs, obj) + CORE.add(assignment) + CORE.register_variable(id_, obj) + return obj + + def Pvariable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj": """Declare a new pointer variable in the code generation.