lsegal / yard-types-parser

Parses YARD formal type declarations into a human readable format.
http://yardoc.org/types
MIT License
9 stars 0 forks source link

Structure around type parsing #3

Open ioquatix opened 4 years ago

ioquatix commented 4 years ago

I'd like to be able to use Ruby to parse types.

This might not be practical, but it would be nice if I could define my types as classes, and then use eval on a string to build a type tree.

For example:

module MyTypes
  class Array
    class << self
      alias [] new
    end

    def initialize(item_type)
      @item_type = item_type
    end
  end

  pp Array[String]
end

#<MyTypes::Array:0x000055c4a4e01028 @item_type=String>

Do you think something like this makes sense?

lsegal commented 4 years ago

This could work, namely, it would be extremely easy to build something up using refinements + the Ruby syntax of:

type { [Array[String, Symbol]] => String }
def foo(arr) end

That said, have you taken a look at Sorbet? The syntax is a little less familiar, but provides much of the same logic you're probably looking for, plus it has a full type checking runtime.

ioquatix commented 4 years ago

Yeah, it makes sense. I prefer something similar to YARD syntax, because I want to use the type signature for parsing string arguments into rich data.

ioquatix commented 4 years ago

I'm going to hopefully put this code in it's own gem, but here is a proof of concept I whipped up:

https://github.com/ioquatix/bake/blob/master/lib/bake/types.rb#L34

Parsed by files in:

https://github.com/ioquatix/bake/tree/master/lib/bake/types

It's a little bit less terse than the syntax of this repository, but it's very simple and logical to parse which is good for my usecase.