Search code examples
crystal-lang

Is there any alternative to python ast module in Crystal?


Does Crystal expose its internal parser as a standard library as python does with it's ast module? How to parse crystal source code and get the AST of it?


Solution

  • Yes! In fact it ships the entire compiler in the stdlib. So we can just access the parser to get an AST:

    require "compiler/crystal/syntax/*"
    
    root = Crystal::Parser.new(%(
    class Foo
      def hello
        :world
      end
    end)).parse
    

    The official docs do not include the Crystal::ASTNode and its subclasses, the ones you find the docs are the ones exposed the macro language and thus slightly differ. So you'll have to dive into the source code to see how to make use of the AST.