Class: RBSJsonSchema::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/rbs_json_schema/generator.rb

Constant Summary collapse

Alias =
RBS::AST::Declarations::Alias

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stringify_keys:, output:, stdout:, stderr:) ⇒ Generator

Returns a new instance of Generator.



12
13
14
15
16
17
18
19
# File 'lib/rbs_json_schema/generator.rb', line 12

def initialize(stringify_keys:, output:, stdout:, stderr:)
  @stringify_keys = stringify_keys ? true : false
  @output = output
  @stdout = stdout
  @stderr = stderr
  @path_decls = {}
  @generated_schemas = {}
end

Instance Attribute Details

#generated_schemasObject (readonly)

Returns the value of attribute generated_schemas.



8
9
10
# File 'lib/rbs_json_schema/generator.rb', line 8

def generated_schemas
  @generated_schemas
end

#outputObject (readonly)

Returns the value of attribute output.



4
5
6
# File 'lib/rbs_json_schema/generator.rb', line 4

def output
  @output
end

#path_declsObject (readonly)

Returns the value of attribute path_decls.



7
8
9
# File 'lib/rbs_json_schema/generator.rb', line 7

def path_decls
  @path_decls
end

#stderrObject (readonly)

Returns the value of attribute stderr.



6
7
8
# File 'lib/rbs_json_schema/generator.rb', line 6

def stderr
  @stderr
end

#stdoutObject (readonly)

Returns the value of attribute stdout.



5
6
7
# File 'lib/rbs_json_schema/generator.rb', line 5

def stdout
  @stdout
end

#stringify_keysObject (readonly)

Returns the value of attribute stringify_keys.



3
4
5
# File 'lib/rbs_json_schema/generator.rb', line 3

def stringify_keys
  @stringify_keys
end

Instance Method Details

#generate(uri) ⇒ Object

IMPORTANT: Function invoked to generate RBS from JSON schema Generates RBS from JSON schema after validating options & writes to file/STDOUT



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rbs_json_schema/generator.rb', line 23

def generate(uri)
  # Validate options received from CLI
  validate_options()

  @path_decls[uri.path] ||= RBS::AST::Declarations::Module.new(
    name: generate_type_name_for_uri(uri, module_name: true),
    type_params: RBS::AST::Declarations::ModuleTypeParams.empty,
    members: [],
    self_types: [],
    annotations: [],
    location: nil,
    comment: nil
  )
  generate_rbs(uri, read_from_uri(uri))
end

#generate_rbs(uri, document) ⇒ Object

IMPORTANT: Function used to generate AST alias declarations from a URI & a schema document



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/rbs_json_schema/generator.rb', line 40

def generate_rbs(uri, document)
  # If schema is already generated for a URI, do not re-generate declarations/types
  if fragment = uri.fragment
    # return if fragment.empty? # If fragment is empty, implies top level schema which is always generated since it is the starting point of the algorithm

    if @generated_schemas.dig(uri.path, fragment.empty? ? "#" : fragment) # Check if types have been generated for a particular path & fragment
      return
    end
  else
    if @generated_schemas.dig(uri.path, "#") # Check if types have been generated for a particular path
      return
    end
  end

  unless document.is_a?(Hash)
    raise ValidationError.new(message: "Invalid JSON Schema: #{document}")
  end

  @generated_schemas[uri.path] ||= {}
  if fragment = uri.fragment
    @generated_schemas[uri.path][fragment.empty? ? "#" : fragment] = true
  else
    @generated_schemas[uri.path]["#"] = true
  end
  # Parse & generate declarations from remaining schema content
  decl = Alias.new(
    name: generate_type_name_for_uri(uri), # Normal type name with no prefix
    type: translate_type(uri, document), # Obtain type of alias by parsing the schema document
    annotations: [],
    location: nil,
    comment: nil
  )
  # Append the declaration if & only if the declaration has a valid RBS::Type assigned
  if @path_decls[uri.path]
    @path_decls[uri.path].members << decl if !decl.type.nil?
  else
    @path_decls[uri.path] = RBS::AST::Declarations::Module.new(
      name: generate_type_name_for_uri(uri, module_name: true),
      type_params: RBS::AST::Declarations::ModuleTypeParams.empty,
      members: [],
      self_types: [],
      annotations: [],
      location: nil,
      comment: nil
    )
    @path_decls[uri.path].members << decl if !decl.type.nil?
  end
end

#literal_type(literal) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/rbs_json_schema/generator.rb', line 89

def literal_type(literal)
  # Assign literal type
  case literal
  when String, Integer, TrueClass, FalseClass
    RBS::Types::Literal.new(literal: literal, location: nil)
  when nil
    RBS::Types::Bases::Nil.new(location: nil)
  else
    raise ValidationError.new(message: "Unresolved literal found: #{literal}")
  end
end

#read_from_uri(uri) ⇒ Object

Read contents from a URI



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
# File 'lib/rbs_json_schema/generator.rb', line 202

def read_from_uri(uri)
  schema_source =
    case uri.scheme
    when "file", nil
      File.read(uri.path)
    when "http", "https"
      Net::HTTP.get(uri)
    else
      raise ValidationError.new(message: "Could not read content from URI: #{uri}")
    end

  schema = JSON.parse(schema_source)

  if (fragment = uri.fragment) && !fragment.empty?
    case
    when fragment.start_with?("/")
      path = fragment.split("/")
      path.shift()

      schema.dig(*path) or
        raise ValidationError.new(message: "JSON pointer doesn't point a schema: #{uri.fragment}")
    else
      raise ValidationError.new(message: "JSON pointer is expected: #{uri.fragment}")
    end
  else
    schema
  end
end

#translate_type(uri, schema) ⇒ Object

Parse JSON schema & return the ‘RBS::Types` to be assigned



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
# File 'lib/rbs_json_schema/generator.rb', line 106

def translate_type(uri, schema)
  case
  when values = schema["enum"]
    unless values.is_a?(Array)
      raise ValidationError.new(message: "Invalid JSON Schema: enum: #{values}")
    end

    types = values.map { |literal| literal_type(literal) }
    RBS::Types::Union.new(types: types, location: nil)
  when const = schema["const"]
    literal_type(const)
  when schema["type"] == "array" || schema.key?("items")
    case
    when schema["items"].is_a?(Array)
      # tuple
      types = schema["items"].map { |definition| translate_type(uri, definition) }
      RBS::Types::Tuple.new(types: types, location: nil)
    when schema["items"].is_a?(Hash)
      # array
      elem_type = translate_type(uri, schema["items"])
      RBS::BuiltinNames::Array.instance_type(elem_type)
    else
      RBS::BuiltinNames::Array.instance_type(untyped_type)
    end
  when schema["type"] == "object" || schema.key?("properties") || schema.key?("additionalProperties")
    case
    when properties = schema["properties"]
      # @type var properties: json_schema
      fields = properties.each.with_object({}) do |pair, hash|
        # @type var hash: Hash[Symbol, RBS::Types::t]
        key, value = pair

        hash[key.to_sym] = translate_type(uri, value)
      end

      RBS::Types::Record.new(fields: fields, location: nil)
    when prop = schema["additionalProperties"]
      RBS::BuiltinNames::Hash.instance_type(
        RBS::BuiltinNames::String.instance_type,
        translate_type(uri, prop)
      )
    else
      RBS::BuiltinNames::Hash.instance_type(
        RBS::BuiltinNames::String.instance_type,
        untyped_type
      )
    end
  when one_of = schema["oneOf"]
    RBS::Types::Union.new(
      types: one_of.map { |defn| translate_type(uri, defn) },
      location: nil
    )
  when all_of = schema["allOf"]
    RBS::Types::Intersection.new(
      types: all_of.map { |defn| translate_type(uri, defn) },
      location: nil
    )
  when ty = schema["type"]
    case ty
    when "integer"
      RBS::BuiltinNames::Integer.instance_type
    when "number"
      RBS::BuiltinNames::Numeric.instance_type
    when "string"
      RBS::BuiltinNames::String.instance_type
    when "boolean"
      RBS::Types::Bases::Bool.new(location: nil)
    when "null"
      RBS::Types::Bases::Nil.new(location: nil)
    else
      raise ValidationError.new(message: "Invalid JSON Schema: type: #{ty}")
    end
  when ref = schema["$ref"]
    ref_uri =
      begin
        # Parse URI of `$ref`
        URI.parse(schema["$ref"])
      rescue URI::InvalidURIError => _
        raise ValidationError.new(message: "Invalid URI encountered in: $ref = #{ref}")
      end

    resolved_uri = resolve_uri(uri, ref_uri) # Resolve `$ref` URI with respect to current URI
    # Generate AST::Declarations::Alias
    generate_rbs(resolved_uri, read_from_uri(resolved_uri))

    # Assign alias type with appropriate namespace
    RBS::Types::Alias.new(
      name: generate_type_name_for_uri(resolved_uri, namespace: resolved_uri.path != uri.path),
      location: nil
    )
  else
    raise ValidationError.new(message: "Invalid JSON Schema: #{schema.keys.join(", ")}")
  end
end

#untyped_typeObject



101
102
103
# File 'lib/rbs_json_schema/generator.rb', line 101

def untyped_type
  RBS::Types::Bases::Any.new(location: nil)
end

#write_outputObject

Write output using ‘RBS::Writer` to a particular `IO`



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/rbs_json_schema/generator.rb', line 232

def write_output
  # If an output directory is given, open a file & write to it
  if output = self.output
    @path_decls.each do |path, decls|
      name = decls.name.name.to_s.underscore
      file_path = File.join(output, "#{name}.rbs")
      File.open(file_path, 'w') do |io|
        stdout.puts "Writing output to file: #{file_path}"
        RBS::Writer.new(out: io).write([decls])
      end
    end
  # If no output directory is given write to STDOUT
  else
    RBS::Writer.new(out: stdout).write(@path_decls.values)
  end
end