Search code examples
pycparser

Get column number of C construct in ast generated by pycparser


I do know that "coord" attribute of AST node gives the line number but by default it has column number set as None. Is there a way to set this to true column number?


Solution

  • The master branch version on Github, which didn't make it into an official release yet, does include a column in the coord attribute of AST nodes.

    The examples/explore_ast.py example can show this in action, if you uncomment the line with showcoord=True. Here's a dumped AST snippet:

    FileAST:  (at None)
      Typedef: Node, [], ['typedef'] (at <none>:2:17)
        TypeDecl: Node, [] (at <none>:2:17)
          IdentifierType: ['int'] (at <none>:2:13)
      Typedef: Hash, [], ['typedef'] (at <none>:2:23)
        TypeDecl: Hash, [] (at <none>:2:23)
          IdentifierType: ['int'] (at <none>:2:13)
      FuncDef:  (at <none>:4:10)
        Decl: HashPrint, [], [], [] (at <none>:4:10)
          FuncDecl:  (at <none>:4:10)
            ParamList:  (at <none>:4:24)
              Decl: hash, [], [], [] (at <none>:4:24)
                PtrDecl: [] (at <none>:4:24)
                  TypeDecl: hash, [] (at <none>:4:26)
    

    The (at <none>:2:17) part means "at file <none>, line 2, column 17" (file is <none> because the example is just parsing from a string).