Arithmetic operator precedence rules #33
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 as1+(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.