Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix preproc alternatives (elif, elifdef, else) #203

Merged
merged 1 commit into from
Apr 5, 2024

Conversation

touzeauv
Copy link
Contributor

@touzeauv touzeauv commented Apr 4, 2024

Currently, there are two functions ("elseBlock" and "elifBlock") that are used to generate alternatives (i.e. "#elif", "#elifdef", "#else").
More precisely, "elseBlock" generates "#else" and "#elif" nodes, and elifBlock generates "#elifdef" nodes.

The "#ifdef" is currently the only node offering a choice between elseBlock and elifBlock. Other conditional directives only allow elseBlock and thus do not offer the possiblity to have (for example) a "#if" followed by a "#elifdef".

Concretely, consider the following code:

#if defined(FOO)
#elifdef BAR
#endif

This is currently parsed as a preproc_call

(translation_unit [0, 0] - [3, 0]
(preproc_if [0, 0] - [2, 6]
  condition: (preproc_defined [0, 4] - [0, 16]
    (identifier [0, 12] - [0, 15]))
  (preproc_call [1, 0] - [2, 0]
    directive: (preproc_directive [1, 0] - [1, 8])
    argument: (preproc_arg [1, 9] - [1, 12]))))

I can't think about any reason to disallow this behavior so I suggest to merge both function into a single one that generate all possible alternatives.
For the given example, this would result in

(translation_unit [0, 0] - [3, 0]
  (preproc_if [0, 0] - [2, 6]
    condition: (preproc_defined [0, 4] - [0, 16]
      (identifier [0, 12] - [0, 15]))
    alternative: (preproc_elifdef [1, 0] - [1, 12]
      name: (identifier [1, 9] - [1, 12]))))

This commit also adds a test to check for regression

Copy link
Contributor

@maxbrunsfeld maxbrunsfeld left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great point. Thank you.

This commit merges functions "elseBlock" and "elifBlock" in a single
function "alternativeBlock". Any call to either function is replaced by
a call to "alternativeBlock", which cover all alternatives (elif,
elifdef and else). The goal is twofold:

1) Correct the grammar to allow all kind of alternatives independently
   of the "if" directive. Before the fix, "#if" alternative was
   generated by elseBlock only, and thus disallow "#elifdef" as a
   follow-up.
2) As a side effect, simplify the parser.
@amaanq amaanq merged commit ff7f769 into tree-sitter:master Apr 5, 2024
2 of 3 checks passed
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.

3 participants