Skip to content

bug: Inconsistency when parsing comment inside if statement #309

@smitbarmase

Description

@smitbarmase

Did you check existing issues?

  • I have read all the tree-sitter docs if it relates to using the parser
  • I have searched the existing issues of tree-sitter-python

Tree-Sitter CLI Version, if relevant (output of tree-sitter --version)

tree-sitter 0.25.3 (710796b)

Describe the bug

When a comment is inside an if statement, without any other consequence statements inside it, the comment is not considered a child of the if_statement but instead as a sibling.

Broken:

  1. Just comment in child:
if a == 2:
    # this is a comment

Results in:

(module [0, 0] - [2, 0]
  (if_statement [0, 0] - [0, 10]
    condition: (comparison_operator [0, 3] - [0, 9]
      (identifier [0, 3] - [0, 4])
      (integer [0, 8] - [0, 9]))
    consequence: (block [0, 10] - [0, 10]))
  (comment [1, 4] - [1, 23]))

Correct:

  1. Comment after child statement:
if a == 2:
    a = 3
    # this is a comment

Results in:

(module [0, 0] - [3, 0]
  (if_statement [0, 0] - [2, 23]
    condition: (comparison_operator [0, 3] - [0, 9]
      (identifier [0, 3] - [0, 4])
      (integer [0, 8] - [0, 9]))
    consequence: (block [1, 4] - [2, 23]
      (expression_statement [1, 4] - [1, 9]
        (assignment [1, 4] - [1, 9]
          left: (identifier [1, 4] - [1, 5])
          right: (integer [1, 8] - [1, 9])))
      (comment [2, 4] - [2, 23]))))
  1. Comment before child statement:
if a == 2:
    # this is a comment
    a = 3
(module [0, 0] - [3, 0]
  (if_statement [0, 0] - [2, 9]
    condition: (comparison_operator [0, 3] - [0, 9]
      (identifier [0, 3] - [0, 4])
      (integer [0, 8] - [0, 9]))
    (comment [1, 4] - [1, 23])
    consequence: (block [2, 4] - [2, 9]
      (expression_statement [2, 4] - [2, 9]
        (assignment [2, 4] - [2, 9]
          left: (identifier [2, 4] - [2, 5])
          right: (integer [2, 8] - [2, 9]))))))

Steps To Reproduce/Bad Parse Tree

(module [0, 0] - [2, 0]
  (if_statement [0, 0] - [0, 10]
    condition: (comparison_operator [0, 3] - [0, 9]
      (identifier [0, 3] - [0, 4])
      (integer [0, 8] - [0, 9]))
    consequence: (block [0, 10] - [0, 10]))
  (comment [1, 4] - [1, 23]))

Expected Behavior/Parse Tree

(module [0, 0] - [2, 0]
  (if_statement [0, 0] - [0, 10]
    condition: (comparison_operator [0, 3] - [0, 9]
      (identifier [0, 3] - [0, 4])
      (integer [0, 8] - [0, 9]))
    consequence: (block [0, 10] - [0, 10]))
    (comment [1, 4] - [1, 23]))

Repro

if a == 2:
    # this is a comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions