Repository navigation
Let trigger expressions start and end with blanks and span lines (#617) - #921
Conversation
) A trigger expression with a leading space or new line, such as @state_trigger(""" pyscript.a == 'x'"""), failed with IndentationError and the trigger was never created. Surrounding spaces, tabs and new lines are now stripped from a trigger expression before it is parsed, for @state_trigger, @state_active and the filters of @event_trigger, @mqtt_trigger and @webhook_trigger, for both the current and the legacy decorators, and for task.wait_until. Bare state names are stripped before they are recognised, so " pyscript.a" still means any change. Syntax errors show the stripped expression. The time triggers, eval() and script code are unchanged. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
|
Thanks @HoneyBearTech. The stripping works, but the example in #617 still fails: its lines end in Could you parse each trigger expression as |
|
A simpler variant: only wrap when the expression contains a new line, and otherwise just strip it, as you do now. Single-line expressions then keep their exact error offsets. For a multi-line one, |
|
Thanks @craigbarratt, you're right on all counts. I've added a second commit on top of the first, so you can see what changed since your review. I'm happy to squash them. The #617 example. It now works. One entry vs several. Each Parsing as
That covers the leading and trailing blanks, so Trailing The first line's offset in the error report. The error text is the expression exactly as written. After parsing, AST positions on line 1 move back by one, so errors while the expression runs point at the right place. A
The docs note. In the Beyond what you asked, so you can say if you'd rather drop them:
Both are one short pass over the expression's tokens with the One small change in behaviour: an entry written as a bare tuple, like |
|
+1 to @craigbarratt's simpler variant: wrap only multi-line expressions, strip single-line ones. The current version solves a small problem with a lot of machinery: a tokenize pass, position remapping for every expression, and tests that pin exact CPython error offsets. It also quietly makes new syntax valid, like a bare generator, walrus, or |
…m-components#617) Stripping the blanks wasn't enough for custom-components#617's own example: its lines end in "and" with no brackets around the whole expression. As one of several @state_trigger entries it already worked, inside the any([...]). A trigger expression that still has a line break after stripping is now parsed unstripped as "(" + expr + "\n)", by AstEval.parse_trigger_expr(). Its line numbers stay as written, and positions on its first line move back by one, in the logged error and in a caught SyntaxError. A one-line expression is stripped and parsed exactly as before. Nothing becomes valid only because of the added brackets: over several lines, a bare generator expression, a bare tuple, an empty expression, "a) or (b", and a bare := or yield give a SyntaxError. Inside the user's own brackets they work as before, and anything that parsed before still parses as before, such as a tuple followed by a comment line. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
9fe371a to
a2e13b7
Compare
|
Thanks @craigbarratt and @dmamelin. Sorry, I missed the 20:21 comment before my earlier reply, which answered only the first suggestion. I've replaced the second commit. I didn't add a third on top. The first commit, Only wrap when the expression contains a new line. Done, in
Otherwise just strip it, keeping the exact error offsets. A one-line expression is stripped and goes through Line numbers stay the same as the original. A multi-line expression is wrapped without being stripped, so its lines keep their numbers. That needed one more change: the Only the columns on the first line shift by one. After parsing, positions on line 1 move one place left, which is a five-line loop. So an error while the expression runs points at the right place. A syntax error is moved by
The lines are split the way Python counts them (
The tokenize pass. Gone, along with Position remapping for every expression. It now runs only for a multi-line expression. It's the five-line loop above and Tests that pin exact CPython error offsets. Gone. Wherever Python chooses the place, the tests ask Python. The new unit tests at the end of No new syntax. The only new thing is that a line break no longer needs brackets. Over several lines, the added brackets would make a few forms valid. A short check after parsing gives each one a
Python reports where each part of an expression starts. For the first four, it says the whole expression starts at our added Nothing that parsed before is rejected. Before giving one of these errors, the check parses the stripped text the way the first commit does. If that works, the expression is parsed exactly as before. So The same forms in the user's own brackets still work: The bare generator footgun. Over several lines it's now an error with that message, not a trigger that always fires. On one line it was already a
#617's example now works as a single |
There was a problem hiding this comment.
Thanks @HoneyBearTech, this is what I had in mind, and rejecting the forms that only work because of the added brackets addresses @dmamelin's concern. Approving. One nit: a line in the new docs paragraph in docs/reference.rst is much longer than the rest; I'll fix that.
|
Looking at this again after it was merged, I think it ended up over-engineered: the gain is small and the cost is noticeable. I'd like to discuss it before the release. The gain #617 is a "can I do this" question, not a bug, and a comment there already gave a working approach: adjacent f-strings inside brackets. The example from the issue works without this PR once two characters are added, @state_trigger(f"""(
{_state_sensor} in ['recently occupied', 'unoccupied', 'dormant', 'unavailable'] and
(sensor.octoprint_actual_tool0_temp == 'unavailable' or float(sensor.octoprint_actual_tool0_temp) <= 110) and
(sensor.octoprint_actual_bed_temp == 'unavailable' or float(sensor.octoprint_actual_bed_temp) <= 110)
)""", state_hold_false=0)Explicit brackets are plain Python that users already know. I'd keep stripping the blanks around the expression: it fixes the Hidden problems Inside the implicit brackets a line break no longer ends the expression, so a missing operator gets joined with the next line. In plain Python this is a # Next line starts with "(": the value before it gets called
@state_trigger("""
binary_sensor.door == 'on'
(input_boolean.away == 'on' or input_boolean.night == 'on')
""")
# parsed as: binary_sensor.door == 'on'(...)
# TypeError: 'str' object is not callable -- only when the trigger fires
# Next line starts with a string: the strings are joined and the comparisons chain
@state_trigger("""
input_select.mode == 'away'
'on' == input_boolean.alarm
""")
# parsed as: input_select.mode == 'awayon' == input_boolean.alarm
# always False, no error at all
# Next line starts with "-": it becomes a binary operator
@state_trigger("""
sensor.temp > 20
-5 < sensor.temp_delta
""")
# parsed as: sensor.temp > 20 - 5 < sensor.temp_delta
# wrong logic, no error at allThe error for an unclosed bracket also got worse. The added @state_trigger("""
pyscript.a == 'on' and (pyscript.b == 'on' or
pyscript.c == 'on'
""")
# now: '(' was never closed -- on line 1, with empty text
# without wrapping: '(' was never closed -- at the bracket before pyscript.bDifference from CPython, and the cost In Python, a multi-line expression without brackets is an error, and inside brackets anything goes. Now it's neither: without brackets it's allowed, with exceptions — a bare generator, a tuple, To be fair, several @craigbarratt, what do you think? Is the implicit wrapping worth it, or is stripping plus a line in the docs ("put a multi-line expression in brackets") enough? It would be good to decide before the release; removing it afterwards would be a breaking change. |
Closes #617
What was broken
A trigger expression that starts with a space or tab (also after a new line) fails, and the trigger is never created:
An expression written over several lines without brackets around the whole of it fails too. #617's own example is like this: its lines end in
and.It was also inconsistent. The same multi-line text worked as one of several
@state_triggerentries, because those are joined into oneany([...])and so sit inside brackets. On its own it failed.A bare state name with blanks around it was also wrong.
" pyscript.a"didn't match the "any change" pattern, so it became the expressionpyscript.a(true or false by value)."pyscript.a\n"did match, but the name kept its new line, so it never matched the real entity.Why
mode="eval", exactly as written. Python's rules for a bare expression apply there: no spaces or tabs before it, and a line break only inside brackets or after a\.@state_triggerentries, the entries are joined intoany([...]), so they are inside brackets and those rules don't bite. A single entry isn't inside any brackets, so the same text fails there.What I changed
There are two commits. The first one,
let trigger expressions start and end with blanks, is unchanged since the first review. The second commit has been replaced, not added to. The earlier second commit (9fe371a, with a token pass and position fixes for every expression) is gone. In its place is a much smaller one that follows @craigbarratt's simpler variant: wrap only a multi-line expression, and strip a one-line one as the first commit does. @dmamelin's review shaped what it keeps out: no token pass, position fixes only for multi-line expressions, tests that don't pin Python's exact error positions, and no new syntax.From the first commit:
strip_trigger_expr()intrigger.pyremoves spaces, tabs and new lines around an expression.@state_triggerentries, the callers strip each entry, andany_trigger_exprs()puts each one on its own lines inside theany([...]), so a trailing# commentcan't swallow the,or])after it. Theany([...])is kept, so all entries are still evaluated, as before." pyscript.a "means any change topyscript.a, and the name is exact.In the second commit:
New
AstEval.parse_trigger_expr()ineval.py. It strips the expression first.AstEval.parse. Its error positions are Python's own. Nothing new is accepted or rejected:a, bis still a tuple (always true), and(x := 1)still works.\nor\r) after stripping: it's parsed as"(" + expr + "\n)", without stripping, as @craigbarratt suggested. So it reads as it would inside brackets in Python. It needs no brackets of its own, and any of its lines can end with a# comment. Its line numbers stay as written.Errors point at the user's own text. The text shown in error messages is the expression as written, split into lines the way Python counts them (
\r\n,\rand\n). Those lines are joined with\nbefore the brackets are added. Python reads\r\nand\ras\nanyway, even inside strings, so nothing else changes. But the added)is always on a line of its own, even after a final lone\r(which would otherwise join the added\ninto one line break).(. So an error while the expression runs, like a division by zero, points at the right place. Later lines are unchanged.SyntaxError. Itslineno,offset,end_lineno,end_offset,textandargsall agree, so the logged message and the error a script catches are the same.), when the expression stops short likex == 1 and, is reported at the end of the last line that isn't blank.(. That's reported at the start of the first line. It isn't traced back to the user's own bracket, since that would need the token pass again.EvalExceptionFormattergets a small change: it treatsparse_trigger_exprlikeparse.No new syntax, as @dmamelin asked. Over several lines, the added brackets would make a few things valid that aren't valid without them. A short check after parsing gives each one a
SyntaxErrorthat says what's wrong:x == 1 for x in y(forgettingany(), so it would always be true)generator expression must be inside bracketsa,thenb, also with*tuple must be inside bracketsexpression is emptya andthenb) or (cunmatched ')':=':=' must be inside bracketsyieldoryield from'yield' must be inside bracketsHow it tells them apart:
(. A user's own expression always starts after it. For a tuple or generator in the user's own brackets, the start is the user's(.:=oryieldcan't be told apart that way, because Python drops plain brackets from its result. For these only, the text is parsed once more as a keyword value,f(value=...). There a bare one is an error and a bracketed one isn't.(x == 1 for x in y),any(x == 1 for x in y),(a, b),(),(x := 1),(yield 1),(yield from a).a, bfollowed by a comment line,a, (with the bracket closed on a later line,a, \continued on the next line, and a tuple holding a triple-quoted string that runs over several lines.parse_trigger_expr()is used everywhere a trigger expression is parsed:create_expressionindecorators/base.py:@state_trigger,@state_active, the expressions of@event_trigger,@mqtt_trigger,@webhook_triggerand@webhook_handler, andtask.wait_until;TrigInfointrigger.py):@state_trigger,@state_activeand the event, MQTT and webhook expressions;task.wait_until(TrigTime.wait_until): the state, event, MQTT and webhook expressions. The legacy code has no@webhook_handler.The
@state_triggercallers (indecorators/state.py,TrigTime.wait_untilandTrigInfo) now use a stripped copy only to recognise a bare state name. They pass the entry on as written, so a single multi-line expression keeps its line numbers. With several expression entries, each entry is still stripped before it goes into theany([...]); that now happens insideany_trigger_exprs(). Only expression entries are counted, after the bare names are taken out, so one bare name plus one expression is parsed as that expression alone.Not changed:
@time_triggerand@time_active(they have their own format),eval(), ordinary script code andAstEval.parse. They keep Python's exact rules.The second commit adds 108 lines and removes 24 in
eval.py,trigger.pyanddecorators/. The commit it replaces added 170 and removed 59.Testing
tests/test_unit_trigger.py. They check behaviour by comparing with what Python itself does with the same text, so no Python error message or position is written into them. Only positions this code chooses (a rejection, an error at the added)) are worked out in the test:test_parse_trigger_expr_one_line(16 expressions): a one-line expression with blanks, a trailing comment,a, b,(x := 1), a barex := 1, a bare generator,a) or (b, a cut-short line, a final\, only a comment, only blanks, and non-English letters. Each gives the same tree, with the same positions, or the same error (message, line, offset and text), as Python gives for the stripped text. That is what the first commit does.test_parse_trigger_expr_several_lines(25 expressions): multi-line expressions without brackets, including Is it possible to use multiline strings in state trigger decorators? #617's shape, comments on any line, a comment line first, blank lines, a\continuation,\r\nand a lone\r, non-English letters on the first line, an f-string holding), a lambda and a bracketed walrus. Plus the user-bracketed forms above, each after a comment line and indented before a comment line. Each gives the same tree as Python does for the text inside brackets. Every part of the tree points at the same text in the expression as written.test_parse_trigger_expr_needs_brackets(14 cases): the 7 rejected forms from the table above other than comments only (generator, tuple, tuple with*, early close,:=,yield,yield from), each written over several lines, once after a comment line and once indented. Each gives aSyntaxErroron the right line, at the first character the user wrote, with that line's text, andargsagrees.test_parse_trigger_expr_empty(2 cases): comments only, over several lines.test_parse_trigger_expr_syntax_error(8 cases): syntax errors on the first line (also with non-English letters) and on later lines, a cut-short expression with blank lines after it, cut-short expressions with\rand\r\nline endings that end in a line break, and an unclosed bracket. Each is at Python's place for the text inside brackets, moved one place left on line 1, or at the end of the last line that isn't blank when Python stops at the added).test_parse_trigger_expr_still_valid(7 expressions): multi-line text the first commit accepts that looks like a tuple needing brackets, such asa, bthen a comment line,a, (closed on a later line, a\continuation, a tuple holding a multi-line triple-quoted string, and(a), b. Each gives the same tree, with the same positions, as the first commit.test_parse_trigger_expr_fuzz: 20,000 random texts built from pieces such as names, commas, brackets,and,for,:=,yield, comments,\, line breaks of each kind and a triple-quoted string, with a fixed seed. Of these, 1,021 parse as the first commit parses them, 343 of them over several lines. Each of those still parses, to the same tree.test_trigger_expression_whitespaceintests/test_decorator_errors.py, from the first commit, extended. It runs with the current and the legacy decorators. Each trigger really fires when its condition becomes true, and not before:and,state_hold_false=0), as a single@state_triggerand as one of two expressions;\r\nand a lone\r;a, b(fires on any change) and(k := ...) == '1', as before;@state_active,@event_triggerand@mqtt_triggerexpressions (MQTT subscriptions are patched in the test);task.wait_untilwith multi-linestate_trigger,event_triggerandmqtt_triggerexpressions;SyntaxErrorfromtask.wait_untilfor a one-line and a multi-line expression. It reads the line, the place and the text of the expression as written.test_trigger_expression_error_messages, which replaces the first commit'stest_trigger_expression_whitespace_syntax_error, runs in both decorator modes. For 8 functions it checks the logged line number, the code line shown and the marker under it, not Python's wording. Where Python chooses the place, the expected frame is built from Python's own error, or its tree, for the same text (moved one place left on line 1) and drawn by Python'stracebackmodule. Literal positions are only used where this code chooses the place: cut short, the unclosed bracket and the bare generator:test_webhook_trigger_expression_over_several_lines(both modes, includingtask.wait_until(webhook_trigger=...)) andtest_webhook_handler_expression_over_several_lines, intests/decorators/test_webhook.py.test_trigger_expression_comments,test_script_indentation_stays_strictand the threestrip_trigger_expr()unit tests are kept unchanged and still pass. The fakeAstEvalintests/test_decorator_manager.pynow recordsparse_trigger_expr().@state_triggerfails on the first commit withSyntaxError: invalid syntax, in both decorator modes, and passes with this change.sphinx-build -Wpass. The branch merges cleanly into current master, and the suite passes on the merged result (328 tests).Docs
In the
@state_triggersection ofdocs/reference.rst, the note from the first commit is replaced. It now says:# comment. There's a short example;any()), a bare tuple that needs them for its line break, an empty expression, or a bare:=oryieldgives aSyntaxError. Inside brackets of your own they work as they do in Python;@state_active,task.wait_untiland the expressions of@event_trigger,@mqtt_trigger,@webhook_triggerand@webhook_handler.The sentence saying that a multi-line expression needs brackets is gone.
Note
a b andfollowed by a linecnow saysinvalid syntax. Perhaps you forgot a comma?. One-line expressions keep Python's exact messages and positions.'(' was never closed, but no code line.^marker when it would cover the whole code line. The caughtSyntaxErrorstill has the positions.@state_triggerentries, error messages show the joinedany([...])text, and line numbers count from it, as before. A bare tuple entry like"a, b"still becomes two items of theany([...])there, as it always has. The earlier second commit had changed that; this one doesn't.