'Field access and method call in tree-sitter

I would like to write a parser for expressions, which has

  • literals, e.g. 5
  • absolute keypaths, which start with $d, and then the fields are accessed with ., e.g. $d.field1.field2
  • method calls on expressions, e.g. 5.toString() or $d.field1.toLowerCase()

I've come up with the following grammar:

rules: {

    expression: $ => choice(
      $.int_literal,
      $.absolute_keypath,
      $.method_call
    ),

    int_literal: $ =>
      /[0-9]+/,

    absolute_keypath: $ =>
      choice($.keypath_root, $.field_access),

    keypath_root: $ =>
      '$d',

    field_access: $ => seq(
      choice($.keypath_root, $.field_access),
      '.',
      $.identifier,
    ),

    method_call: $ => seq(
      $.expression,
      '.',
      $.identifier,
      '(',
      ')'
    ),

    identifier: $ =>
      /[a-zA-Z_*][a-zA-Z0-9_*]*/

  }

My problem is that I didn't manage to come up with a solution that can parse the examples above. I think that it should be solvable by setting precedence and associativity between field_access and method_call, but I feel I've tried out all the possible combinations without success so far. Can someone help me come up with a grammar for this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source