Skip to content

Allow a newline after a unary operation - #154

Open
basitalisandhu wants to merge 1 commit into
bridgecrewio:masterfrom
basitalisandhu:fix-unary-op-newline
Open

basitalisandhu wants to merge 1 commit into
bridgecrewio:masterfrom
basitalisandhu:fix-unary-op-newline

Conversation

@basitalisandhu

@basitalisandhu basitalisandhu commented Oct 13, 2026 •

Copy link
Copy Markdown

Fixes #153 (reported to checkov as bridgecrewio/checkov#7713).

Problem

A unary operation followed by a newline and then a binary operator fails to parse:

condition = alltrue([
  for n in var.names :
  length(n) > 0
  && !contains(["host"], n)
  && n != "x"
])

UnexpectedToken Token('__ANON_5', '&&') at line 9, column 7. Terraform accepts this. checkov 3.3.19 to 3.3.22 pin bc-python-hcl2==0.4.3, so the whole file goes into parsing_errors and none of its resources get scanned.

Cause and fix

In hcl2/hcl2.lark, a bare expr_term can take trailing newlines (?expression : expr_term _NEW_LINE_OR_COMMENT* | ...), but unary_op cannot. So after !contains(...) and a newline, the parser can't continue into binary_term. This change adds the same optional newline/comment slot after unary_op in the ?operation rule. _NEW_LINE_OR_COMMENT is a filtered terminal and ?operation is inlined, so the transformer output is unchanged.

Testing

  • New fixture unary_operator_newline.tf with its JSON covers !x then &&, !x then ||, -x then +, and a comment between. It fails on master and passes with the fix.
  • pytest test/unit: 4 passed, 18 subtests passed (lark 1.3.1, Python 3.14). No LALR conflicts.
  • Regression check: I parsed 1,862 .tf files (checkov's tests/terraform, plus terraform-aws-modules eks, vpc, iam and rds) with the old and new grammar. The JSON output is identical for every file, and the same 7 files fail both times (all intentionally invalid checkov fixtures, such as invalid_terraform_syntax/ and hcl_timeout/).

A unary operation (!x or -x) followed by a newline and a binary
operator, such as a multi-line && chain inside a validation condition,
failed with UnexpectedToken. A bare expr_term already absorbed trailing
newlines; unary_op did not. Add the same slot to unary_op.

Fixes bridgecrewio#153

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Grammar rejects a newline after a unary operation followed by a leading binary operator (valid HCL; checkov silently skips the file)

1 participant