Method: RBS::Inline::Parser.parse

Defined in:
lib/rbs/inline/parser.rb

.parse(result, opt_in:) ⇒ Object

Parses the given Prism result to a three tuple

Returns a three tuple of:

  1. An array of ‘use` directives

  2. An array of declarations

  3. An array of RBS declarations given as ‘@rbs!` annotation at top-level

Note that only RBS declarations are allowed in the top-level ‘@rbs!` annotations. RBS members are ignored in the array.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/rbs/inline/parser.rb', line 64

def self.parse(result, opt_in:)
  instance = Parser.new()

  annots = AnnotationParser.parse(result.comments)
  annots.each do |result|
    instance.comments[result.line_range.end] = result
  end

  with_enable_magic_comment = result.comments.any? {|comment| comment.location.slice =~ /\A# rbs_inline: enabled\Z/}
  with_disable_magic_comment = result.comments.any? {|comment| comment.location.slice =~ /\A# rbs_inline: disabled\Z/}

  return if with_disable_magic_comment # Skips if `rbs_inline: disabled`

  if opt_in
    # opt-in means the `rbs_inline: enable` is required.
    return unless with_enable_magic_comment
  end

  uses = [] #: Array[AST::Annotations::Use]
  annots.each do |annot|
    annot.each_annotation do |annotation|
      if annotation.is_a?(AST::Annotations::Use)
        uses << annotation
      end
    end
  end

  instance.visit(result.value)

  rbs_embeddeds = [] #: Array[AST::Members::RBSEmbedded]

  instance.comments.each_value do |comment|
    comment.each_annotation do |annotation|
      if annotation.is_a?(AST::Annotations::Embedded)
        rbs_embeddeds << AST::Members::RBSEmbedded.new(comment, annotation)
      end
    end
  end

  rbs_decls = rbs_embeddeds.flat_map do |embedded|
    if (members = embedded.members).is_a?(Array)
      members.select do |member|
        member.is_a?(RBS::AST::Declarations::Base)
      end
    else
      []
    end #: Array[RBS::AST::Declarations::t]
  end

  [
    uses,
    instance.decls,
    rbs_decls
  ]
end