Sha256: 6f898544a5aa00841a1bfa906537ba2c1f6b63fe30e45d55f0dc1f17632201d4

Contents?: true

Size: 1.99 KB

Versions: 14

Compression:

Stored size: 1.99 KB

Contents

require 'strscan'

module JsDuck

  # Validates the syntax of type definitions
  #
  # Quick summary of supported types:
  #
  # - SomeType
  # - Name.spaced.Type
  # - Number[]
  # - String/RegExp
  # - Type...
  #
  # Details are covered in spec.
  #
  class TypeParser
    # Allows to check the type of error that was encountered.
    # It will be either of the two:
    # - :syntax - type definition syntax is incorrect
    # - :name - one of the names of the types is unknown
    attr_reader :error

    # When parsing was successful, then contains the output HTML - the
    # input type-definition with types themselves replaced with links.
    attr_reader :out

    # Initializes the parser with hash of valid type names and doc_formatter.
    def initialize(relations={}, formatter={})
      @relations = relations
      @formatter = formatter
    end

    def parse(str)
      @input = StringScanner.new(str)
      @error = :syntax
      @out = []

      # Return immediately if base type doesn't match
      return false unless base_type

      # Go through enumeration of types, separated with "/"
      while @input.check(/\//)
        @out << @input.scan(/\//)
        # Fail if there's no base type after "/"
        return false unless base_type
      end

      # Concatenate all output
      @out = @out.join

      # Success if we have reached the end of input
      return @input.eos?
    end

    # The basic type
    #
    #     <ident> [ "." <ident> ]* [ "[]" ]* [ "..." ]
    #
    # dot-separated identifiers followed by optional "[]"
    def base_type
      type = @input.scan(/[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*/)

      if !type
        return false
      elsif @relations[type]
        @out << @formatter.link(type, nil, type)
      elsif @relations.ignore?(type) || type == "undefined"
        @out << type
      else
        @error = :name
        return false
      end

      while @input.scan(/\[\]/)
        @out << "[]"
      end

      @out << "..." if @input.scan(/\.\.\./)

      true
    end

  end

end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
jsduck-3.7.0 lib/jsduck/type_parser.rb
jsduck-3.6.1 lib/jsduck/type_parser.rb
jsduck-3.6.0 lib/jsduck/type_parser.rb
jsduck-3.5.0 lib/jsduck/type_parser.rb
jsduck-3.4.1 lib/jsduck/type_parser.rb
jsduck-3.4.0 lib/jsduck/type_parser.rb
jsduck-3.3.1 lib/jsduck/type_parser.rb
jsduck-3.3.0 lib/jsduck/type_parser.rb
jsduck-3.2.1 lib/jsduck/type_parser.rb
jsduck-3.1.0 lib/jsduck/type_parser.rb
jsduck-3.0.1 lib/jsduck/type_parser.rb
jsduck-3.0 lib/jsduck/type_parser.rb
jsduck-3.0.pre3 lib/jsduck/type_parser.rb
jsduck-3.0.pre2 lib/jsduck/type_parser.rb