Search code examples
antlrantlr4

getting lvalue and rvalue of a declaration


Im parsing C++ with ANTLR4 grammar, I have a visitor function for visitDeclarationStatement. In the C++ code that Im trying to parse Person p; or a declaration of any custom type, in the tree I get two similar nodes and I cannot differentiate between the Lvalue and Rvalue!

"declarationStatement": [
{
  "blockDeclaration": [
  {
    "simpleDeclaration": [
    {
      "declSpecifierSeq": [
      {
        "declSpecifier": [
        {
          "typeSpecifier": [
          {
            "trailingTypeSpecifier": [
            {
              "simpleTypeSpecifier": [
              {
                "theTypeName": [
                {
                  "className": [
                  {
                    "type": 128,
                    "text": "Person"
                  }
                  ]
                }
                ]
              }
              ]
            }
            ]
          }
          ]
        }
        ]
      },
      {
        "declSpecifier": [
        {
          "typeSpecifier": [
          {
            "trailingTypeSpecifier": [
            {
              "simpleTypeSpecifier": [
              {
                "theTypeName": [
                {
                  "className": [
                  {
                    "type": 128,
                    "text": "p"
                  }
                  ]
                }
                ]
              }
              ]
            }
            ]
          }
          ]
        }
        ]
      }
      ]
    },
    {
      "type": 124,
      "text": ";"
    }
    ]
  }

I want to be able to get Variable Type and Variable Name separately. What is the right way of doing that? How can I change the g4 file to get those results in a way that I can differentiate between the type and the name?

Thanks


Solution

  • You don't need to change the grammar. In case of Person p;, which is matched by:

    declSpecifierSeq: declSpecifier+ attributeSpecifierSeq?;
    

    the first child of declSpecifierSeq (which is declSpecifier+) will be a List of declSpecifier-contexts, of which the first is the type and the second the name.