Class: YARD::Parser::Rustdoc::Parser

Inherits:
Base
  • Object
show all
Defined in:
lib/yard-rustdoc/parser.rb

Constant Summary collapse

TOP_LEVEL_KINDS =
["struct", "enum"].freeze

Instance Method Summary collapse

Constructor Details

#initialize(source, filename) ⇒ Parser

This default constructor does nothing. The subclass is responsible for storing the source contents and filename if they are required.

Parameters:

  • source (String)

    the source contents

  • filename (String)

    the name of the file if from disk



11
12
13
14
15
16
17
18
# File 'lib/yard-rustdoc/parser.rb', line 11

def initialize(source, filename)
  @source = source
  @rustdoc_json = JSON.parse(@source).fetch("index") do
    raise "Expected `index` top-level key in Rustdoc json format"
  end
  @filename = filename
  @entries = []
end

Instance Method Details

#enumeratorArray?

This method is abstract.

This method should be implemented to return a list of semantic tokens representing the source code to be post-processed. Otherwise the method should return nil.

Returns:

  • (Array)

    a list of semantic tokens representing the source code to be post-processed

  • (nil)

    if no post-processing should be done



74
75
76
# File 'lib/yard-rustdoc/parser.rb', line 74

def enumerator
  @entries
end

#inspectObject

Override inspect instead of dumping the file content because it is huge.



21
22
23
# File 'lib/yard-rustdoc/parser.rb', line 21

def inspect
  "<#{self.class.name} @filename=#{@filename.inspect}>"
end

#parseBase

Finds Rust Struct for the current crate marked with @yard and extract all the marked methods.

Returns:

  • (Base)

    this method should return itself



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/yard-rustdoc/parser.rb', line 28

def parse
  @entries = []

  @rustdoc_json.each do |id, entry|
    next unless relevant_entry?(entry)

    # "inner" is a Rust enum serialized with serde, resulting in a
    # { "variant": { ...variant fields... } } structure.
    # See https://github.com/rust-lang/rust/blob/f79a912d9edc3ad4db910c0e93672ed5c65133fa/src/rustdoc-json-types/lib.rs#L104
    kind, inner = entry["inner"].first

    next unless TOP_LEVEL_KINDS.include?(kind)

    methods = inner
      .fetch("impls")
      .flat_map do |impl_id|
        @rustdoc_json.dig(impl_id.to_s, "inner", "impl", "items")
      end
      .filter_map do |method_id|
        method_entry = @rustdoc_json.fetch(method_id.to_s)
        next unless relevant_entry?(method_entry)

        Statements::Method.new(method_entry)
      end

    @entries << Statements::Struct.new(entry, methods)
  end

  # Ensure Foo comes before Foo::Bar
  @entries.sort_by!(&:name)

  self
end

#tokenizeObject



62
63
64
# File 'lib/yard-rustdoc/parser.rb', line 62

def tokenize
  raise "Rustdoc Parser does not tokenize"
end