hashicorp / hil

HIL is a small embedded language for string interpolations.
Mozilla Public License 2.0
396 stars 34 forks source link

Arithmetic operator precedence rules #33

Closed apparentlymart closed 8 years ago

apparentlymart commented 8 years ago

Previously all operators had equal precedence and they were all parsed in a left-associative manner. This was a simple rule, but it was counter-intuitive to people familiar with conventional expression notation or other languages with precedence rules.

Here we give multiplication and division higher precedence than addition and subtraction, so that e.g. 1+2*3 will parse as 1+(2*3) rather than (1+2)*3 as before. This is a breaking change for anyone that was depending on the old left-associative parsing behavior, but I assume that this will be relatively few people simply because the old behavior was so counter-intuitive that users are likely to have used explicit parentheses to make their code understandable.

This implementation just uses the standard Go stack to keep track of the nested parsing states required to process the levels of precedence. With only two levels of precedence this is a no-brainer, and this approach should suffice for any reasonable number of levels of precedence.

This is one of the follow-on changes I proposed in #32, and (if included into Terraform) resolves hashicorp/terraform#9169. I chose to attack this one of the proposals first because I figured that if it will be included into Terraform 0.8 it should be included in as many betas and release candidates as possible to give people warning and the opportunity to test existing configs that have non-trivial arithmetic expressions.

mitchellh commented 8 years ago

LGTM