Class: Parlour::TypeParser

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/parlour/type_parser.rb

Overview

Parses Ruby source to find Sorbet type signatures.

Defined Under Namespace

Classes: IntermediateSig, NodePath

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ast, unknown_node_errors: false) ⇒ TypeParser

Creates a new Parlour::TypeParser from whitequark/parser AST.

Parameters:

  • The (Parser::AST::Node)

    AST.

  • unknown_node_errors (Boolean) (defaults to: false)

    Whether to raise an error if a node of an unknown kind is encountered. If false, the node is simply ignored; if true, a parse error is raised. Setting this to true is likely to raise errors for lots of non-RBI Ruby code, but setting it to false could miss genuine typed objects if Parlour or your code contains a bug.



95
96
97
98
# File 'lib/parlour/type_parser.rb', line 95

def initialize(ast, unknown_node_errors: false)
  @ast = ast
  @unknown_node_errors = unknown_node_errors
end

Instance Attribute Details

#astParser::AST::Node

Returns The AST which this type parser should use.

Returns:

  • (Parser::AST::Node)

    The AST which this type parser should use.



116
117
118
# File 'lib/parlour/type_parser.rb', line 116

def ast
  @ast
end

#unknown_node_errorsBoolean (readonly)

Returns Whether to raise an error if a node of an unknown kind is encountered.

Returns:

  • (Boolean)

    Whether to raise an error if a node of an unknown kind is encountered.



121
122
123
# File 'lib/parlour/type_parser.rb', line 121

def unknown_node_errors
  @unknown_node_errors
end

Class Method Details

.from_source(filename, source) ⇒ TypeParser

Creates a new Parlour::TypeParser from a source file and its filename.

Parameters:

  • filename (String)

    A filename. This does not need to be an actual file; it merely identifies this source.

  • source (String)

    The Ruby source code.

Returns:



107
108
109
110
111
112
# File 'lib/parlour/type_parser.rb', line 107

def self.from_source(filename, source)
  buffer = Parser::Source::Buffer.new(filename)
  buffer.source = source
  
  TypeParser.new(Parser::CurrentRuby.new.parse(buffer))
end

Instance Method Details

#parse_allObject



127
128
129
130
131
# File 'lib/parlour/type_parser.rb', line 127

def parse_all
  root = RbiGenerator::Namespace.new(DetachedRbiGenerator.new)
  root.children.concat(parse_path_to_object(NodePath.new([])))
  root
end

#parse_path_to_object(path, is_within_eigenclass: false) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/parlour/type_parser.rb', line 145

def parse_path_to_object(path, is_within_eigenclass: false)
  node = path.traverse(ast)
  
  case node.type
  when :class
    parse_err 'cannot declare classes in an eigenclass', node if is_within_eigenclass

    name, superclass, body = *node
    final = body_has_modifier?(body, :final!)
    abstract = body_has_modifier?(body, :abstract!)
    includes, extends = body ? body_includes_and_extends(body) : [[], []]

    # Create all classes, if we're given a definition like "class A::B"
    *parent_names, this_name = constant_names(name)
    target = T.let(nil, T.nilable(RbiGenerator::Namespace))
    top_level = T.let(nil, T.nilable(RbiGenerator::Namespace))
    parent_names.each do |n| 
      new_obj = RbiGenerator::Namespace.new(
        DetachedRbiGenerator.new,
        n.to_s,
        false,
      )
      target.children << new_obj if target
      target = new_obj
      top_level ||= new_obj
    end if parent_names

    final_obj = RbiGenerator::ClassNamespace.new(
      DetachedRbiGenerator.new,
      this_name.to_s,
      final,
      node_to_s(superclass),
      abstract,
    ) do |c|
      c.children.concat(parse_path_to_object(path.child(2))) if body
      c.create_includes(includes)
      c.create_extends(extends)
    end

    if target
      target.children << final_obj
      [top_level]
    else
      [final_obj]
    end
  when :module
    parse_err 'cannot declare modules in an eigenclass', node if is_within_eigenclass

    name, body = *node
    final = body_has_modifier?(body, :final!)
    interface = body_has_modifier?(body, :interface!)
    includes, extends = body ? body_includes_and_extends(body) : [[], []]

    # Create all modules, if we're given a definition like "module A::B"
    *parent_names, this_name = constant_names(name)
    target = T.let(nil, T.nilable(RbiGenerator::Namespace))
    top_level = T.let(nil, T.nilable(RbiGenerator::Namespace))
    parent_names.each do |n| 
      new_obj = RbiGenerator::Namespace.new(
        DetachedRbiGenerator.new,
        n.to_s,
        false,
      )
      target.children << new_obj if target
      target = new_obj
      top_level ||= new_obj
    end if parent_names

    final_obj = RbiGenerator::ModuleNamespace.new(
      DetachedRbiGenerator.new,
      this_name.to_s,
      final,
      interface,
    ) do |m|
      m.children.concat(parse_path_to_object(path.child(1))) if body
      m.create_includes(includes)
      m.create_extends(extends)
    end

    if target
      target.children << final_obj
      [top_level]
    else
      [final_obj]
    end
  when :send, :block
    if sig_node?(node)
      parse_sig_into_methods(path, is_within_eigenclass: is_within_eigenclass)
    else
      []
    end
  when :def, :defs
    # TODO: Support for defs without sigs
    #   If so, we need some kind of state machine to determine whether
    #   they've already been dealt with by the "when :send" clause and 
    #   #parse_sig_into_methods.
    #   If not, just ignore this.
    []
  when :sclass
    parse_err 'cannot access eigen of non-self object', node unless node.to_a[0].type == :self
    parse_path_to_object(path.child(1), is_within_eigenclass: true)
  when :begin
    # Just map over all the things
    node.to_a.length.times.map do |c|
      parse_path_to_object(path.child(c), is_within_eigenclass: is_within_eigenclass) 
    end.flatten
  else
    if unknown_node_errors
      parse_err "don't understand node type #{node.type}", node
    else
      []
    end
  end
end

#parse_sig_into_methods(path, is_within_eigenclass: false) ⇒ <RbiGenerator::Method>

Given a path to a sig in the AST, finds the associated definition and parses them into methods. This will raise an exception if the sig is invalid. Usually this will return one method; the only exception currently is for attributes, where multiple can be declared in one call, e.g. attr_reader :x, :y, :z.

Parameters:

  • path (NodePath)

    The sig to parse.

  • is_within_eigenclass (Boolean) (defaults to: false)

    Whether the method definition this sig is associated with appears inside an eigenclass definition. If true, the returned method is made a class method. If the method definition is already a class method, an exception is thrown as the method will be a class method of the eigenclass, which Parlour can’t represent.

Returns:



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/parlour/type_parser.rb', line 346

def parse_sig_into_methods(path, is_within_eigenclass: false)
  sig_block_node = path.traverse(ast)

  # A :def node represents a definition like "def x; end"
  # A :defs node represents a definition like "def self.x; end"
  def_node = path.sibling(1).traverse(ast)
  case def_node.type
  when :def
    class_method = false
    def_names = [def_node.to_a[0].to_s]
    def_params = def_node.to_a[1].to_a
    kind = :def
  when :defs
    parse_err 'targeted definitions on a non-self target are not supported', def_node \
      unless def_node.to_a[0].type == :self
    class_method = true
    def_names = [def_node.to_a[1].to_s]
    def_params = def_node.to_a[2].to_a
    kind = :def
  when :send
    target, method_name, *parameters = *def_node

    parse_err 'node after a sig must be a method definition', def_node \
      unless [:attr_reader, :attr_writer, :attr_accessor].include?(method_name) \
        || target != nil

    parse_err 'typed attribute should have at least one name', def_node if parameters&.length == 0
    
    kind = :attr
    attr_direction = method_name.to_s.gsub('attr_', '').to_sym
    def_names = T.must(parameters).map { |param| param.to_a[0].to_s }
    class_method = false
  else
    parse_err 'node after a sig must be a method definition', def_node
  end

  if is_within_eigenclass
    parse_err 'cannot represent multiple levels of eigenclassing', def_node if class_method
    class_method = true
  end

  this_sig = parse_sig_into_sig(path)
  params = this_sig.params
  return_type = this_sig.return_type

  if kind == :def
    parse_err 'mismatching number of arguments in sig and def', sig_block_node \
      if params && def_params.length != params.length

    # sig_args will look like:
    #   [(pair (sym :x) <type>), (pair (sym :y) <type>), ...]
    # def_params will look like:
    #   [(arg :x), (arg :y), ...]
    parameters = params \
      ? zip_by(params, ->x{ x.to_a[0].to_a[0] }, def_params, ->x{ x.to_a[0] })
        .map do |sig_arg, def_param|
          arg_name = def_param.to_a[0]

          # TODO: anonymous restarg
          full_name = arg_name.to_s
          full_name = "*#{arg_name}"  if def_param.type == :restarg
          full_name = "**#{arg_name}" if def_param.type == :kwrestarg
          full_name = "#{arg_name}:"  if def_param.type == :kwarg || def_param.type == :kwoptarg
          full_name = "&#{arg_name}"  if def_param.type == :blockarg

          default = def_param.to_a[1] ? node_to_s(def_param.to_a[1]) : nil
          type = node_to_s(sig_arg.to_a[1])

          RbiGenerator::Parameter.new(full_name, type: type, default: default)
        end
      : []

    # There should only be one ever here, but future-proofing anyway
    def_names.map do |def_name|
      RbiGenerator::Method.new(
        DetachedRbiGenerator.new,
        def_name,
        parameters,
        return_type,
        override: this_sig.override,
        overridable: this_sig.overridable,
        abstract: this_sig.abstract,
        final: this_sig.final,
        class_method: class_method
      )
    end
  elsif kind == :attr
    case attr_direction
    when :reader, :accessor
      parse_err "attr_#{attr_direction} sig should have no parameters", sig_block_node \
        if params && params.length > 0

      parse_err "attr_#{attr_direction} sig should have non-void return", sig_block_node \
        unless return_type
        
      attr_type = return_type
    when :writer
      # These are special and can only have one name
      raise 'typed attr_writer can only have one name' if def_names.length > 1

      def_name = def_names[0]
      parse_err "attr_writer sig should take one argument with the property's name", sig_block_node \
        if !params || params.length != 1 || params[0].to_a[0].to_a[0].to_s != def_name

      parse_err "attr_writer sig should have non-void return", sig_block_node \
        if return_type.nil?

      attr_type = T.must(node_to_s(params[0].to_a[1]))
    else
      raise "unknown attribute direction #{attr_direction}"
    end

    def_names.map do |def_name|
      RbiGenerator::Attribute.new(
        DetachedRbiGenerator.new,
        def_name,
        attr_direction,
        attr_type,
        class_attribute: class_method
      )
    end
  else
    raise "unknown definition kind #{kind}"
  end
end

#parse_sig_into_sig(path) ⇒ IntermediateSig

Given a path to a sig in the AST, parses that sig into an intermediate sig object. This will raise an exception if the sig is invalid. This is intended to be called by #parse_sig_into_methods, and shouldn’t be called manually unless you’re doing something hacky.

Parameters:

Returns:



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/parlour/type_parser.rb', line 279

def parse_sig_into_sig(path)
  sig_block_node = path.traverse(ast)

  # A sig's AST uses lots of nested nodes due to a deep call chain, so let's
  # flatten it out to make it easier to work with
  sig_chain = []
  current_sig_chain_node = sig_block_node.to_a[2]
  while current_sig_chain_node
    name = current_sig_chain_node.to_a[1]
    arguments = current_sig_chain_node.to_a[2..-1]

    sig_chain << [name, arguments]
    current_sig_chain_node = current_sig_chain_node.to_a[0]
  end

  # Get basic boolean flags
  override =    !!sig_chain.find { |(n, a)| n == :override    && a.empty? }
  overridable = !!sig_chain.find { |(n, a)| n == :overridable && a.empty? }
  abstract =    !!sig_chain.find { |(n, a)| n == :abstract    && a.empty? }

  # Determine whether this method is final (i.e. sig(:final))
  _, _, *sig_arguments = *sig_block_node.to_a[0]
  final = sig_arguments.any? { |a| a.type == :sym && a.to_a[0] == :final }

  # Find the return type by looking for a "returns" call
  return_type = sig_chain
    .find { |(n, _)| n == :returns }
    &.then do |(_, a)|
      parse_err 'wrong number of arguments in "returns" for sig', sig_block_node if a.length != 1
      node_to_s(a[0])
    end

  # Find the arguments specified in the "params" call in the sig
  sig_args = sig_chain
    .find { |(n, _)| n == :params }
    &.then do |(_, a)|
      parse_err 'wrong number of arguments in "params" for sig', sig_block_node if a.length != 1
      arg = a[0]
      parse_err 'argument to "params" should be a hash', arg unless arg.type == :hash
      arg.to_a
    end

  IntermediateSig.new(
    overridable: overridable,
    override: override,
    abstract: abstract,
    final: final,
    params: sig_args,
    return_type: return_type
  )
end