Class: JSON5::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/json5/parser.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  duplicate_keys: :last,
  number_mode: :native,
  string_mode: :ruby,
  lone_surrogate: :error,
  diagnostics: nil,
  limits: Limits.default,
  filename: nil,
  freeze: false,
  warn_duplicate_keys: false,
  preserve_trivia: true,
  borrow_source: false
}.freeze
PARSE_OPTION_KEYS =
(DEFAULT_OPTIONS.keys - %i[preserve_trivia borrow_source]).freeze
DOCUMENT_OPTION_KEYS =
%i[diagnostics limits filename preserve_trivia borrow_source].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, **options) ⇒ Parser

Returns a new instance of Parser.



175
176
177
178
179
180
181
182
183
184
# File 'lib/json5/parser.rb', line 175

def initialize(source, **options)
  self.class.send(:validate_option_keys!, options, PARSE_OPTION_KEYS)
  @options = DEFAULT_OPTIONS.merge(options)
  validate_options
  @input = Input.new(
    source,
    limits: @options.fetch(:limits),
    filename: @options.fetch(:filename)
  )
end

Class Method Details

.limit_excerpt(source, chunk, byte_offset, radius: 40) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/json5/parser.rb', line 162

def self.limit_excerpt(source, chunk, byte_offset, radius: 40)
  start_byte = [byte_offset - radius, 0].max
  finish_byte = byte_offset + 1
  excerpt = String.new(encoding: Encoding::BINARY)
  if start_byte < source.bytesize
    excerpt << source.byteslice(start_byte...[finish_byte, source.bytesize].min).to_s.b
  end
  chunk_start = [start_byte - source.bytesize, 0].max
  chunk_finish = [finish_byte - source.bytesize, 0].max
  excerpt << chunk.byteslice(chunk_start...chunk_finish).to_s.b
  excerpt.force_encoding(Encoding::UTF_8).scrub
end

.load(io, **options) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/json5/parser.rb', line 25

def self.load(io, **options)
  unless io.respond_to?(:read)
    raise TypeError, "io must respond to #read"
  end
  validate_option_keys!(options, PARSE_OPTION_KEYS)
  validate_parse_options!(options)
  limits = options.fetch(:limits, Limits.default)
  source = read_source(io, limits, filename: options.fetch(:filename, nil))
  parse(source, **options)
end

.merged_read_encoding(current, chunk_encoding) ⇒ Object



125
126
127
128
129
130
# File 'lib/json5/parser.rb', line 125

def self.merged_read_encoding(current, chunk_encoding)
  return current if chunk_encoding == Encoding::ASCII_8BIT
  return Encoding::UTF_8 if current == Encoding::UTF_8 || chunk_encoding == Encoding::UTF_8

  current || chunk_encoding
end

.normalize_read_encoding(source, external_encoding) ⇒ Object



119
120
121
122
123
# File 'lib/json5/parser.rb', line 119

def self.normalize_read_encoding(source, external_encoding)
  return source unless source.encoding == Encoding::ASCII_8BIT && external_encoding

  source.dup.force_encoding(external_encoding)
end

.parse(source, **options) ⇒ Object



21
22
23
# File 'lib/json5/parser.rb', line 21

def self.parse(source, **options)
  new(source, **options).parse
end

.parse_document(source, **options) ⇒ Object



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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/json5/parser.rb', line 36

def self.parse_document(source, **options)
  validate_option_keys!(options, DOCUMENT_OPTION_KEYS)
  merged = DEFAULT_OPTIONS.merge(options)
  validate_limits_option!(merged.fetch(:limits))
  validate_diagnostics_option!(merged.fetch(:diagnostics))
  validate_boolean_option!(merged.fetch(:preserve_trivia), :preserve_trivia)
  validate_boolean_option!(merged.fetch(:borrow_source), :borrow_source)
  unless source.is_a?(String)
    raise TypeError, "source must be a String"
  end
  if merged[:limits].max_input_bytes && source.bytesize > merged[:limits].max_input_bytes
    Input.new(source, limits: merged.fetch(:limits), filename: merged.fetch(:filename))
  end
  owned_source = merged.fetch(:borrow_source) ? source : source.dup.freeze
  collected_diagnostics = []
  diagnostics = merged.fetch(:diagnostics)
  diagnostic_target = case diagnostics
  when Array
    ->(diagnostic) { collected_diagnostics << diagnostic; diagnostics << diagnostic }
  when :ignore
    :ignore
  else
    if diagnostics.respond_to?(:call)
      ->(diagnostic) { collected_diagnostics << diagnostic; diagnostics.call(diagnostic) }
    else
      lambda do |diagnostic|
        collected_diagnostics << diagnostic
        DiagnosticSink.write_default_warning(diagnostic)
      end
    end
  end
  DocumentParser.new(
    owned_source,
    limits: merged.fetch(:limits),
    diagnostics: diagnostic_target,
    filename: merged.fetch(:filename),
    preserve_trivia: merged.fetch(:preserve_trivia),
    collected_diagnostics: collected_diagnostics
  ).parse
end

.read_source(io, limits, filename: nil) ⇒ Object



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
# File 'lib/json5/parser.rb', line 77

def self.read_source(io, limits, filename: nil)
  external_encoding = io.external_encoding if io.respond_to?(:external_encoding)
  external_encoding = nil unless [Encoding::UTF_8, Encoding::US_ASCII].include?(external_encoding)
  allow_binary_chunks = !external_encoding.nil?
  unless limits.max_input_bytes
    source = io.read
    validate_read_chunk!(source, filename: filename, byte_offset: 0, preceding: nil,
                         allow_binary: allow_binary_chunks)
    return normalize_read_encoding(source, external_encoding)
  end

  source = String.new(encoding: Encoding::BINARY)
  source_encoding = external_encoding
  chunk_size = [limits.max_input_bytes + 1, 16 * 1024].min
  while source.bytesize <= limits.max_input_bytes
    chunk = io.read(chunk_size)
    break if chunk.nil?
    validate_read_chunk!(chunk, filename: filename, byte_offset: source.bytesize, preceding: source,
                         allow_binary: allow_binary_chunks)
    break if chunk.empty?
    source_encoding = merged_read_encoding(source_encoding, chunk.encoding)
    remaining = limits.max_input_bytes + 1 - source.bytesize
    if chunk.bytesize >= remaining
      position_bytes = source + chunk.b.byteslice(0, remaining + 3).to_s
      position_bytes.force_encoding(source_encoding || Encoding::UTF_8)
      line, column = Input.position_for(position_bytes, limits.max_input_bytes)
      raise LimitError.new(
        "input exceeds max_input_bytes",
        code: "maximum_input_size_exceeded",
        filename: filename,
        byte_offset: limits.max_input_bytes,
        end_byte_offset: limits.max_input_bytes + 1,
        line: line,
        column: column,
        excerpt: limit_excerpt(source, chunk, limits.max_input_bytes)
      )
    end
    source << chunk.b
  end
  source.force_encoding(source_encoding || Encoding::UTF_8)
end

.validate_boolean_option!(value, name) ⇒ Object

Raises:

  • (ArgumentError)


239
240
241
242
243
# File 'lib/json5/parser.rb', line 239

def self.validate_boolean_option!(value, name)
  return if value == true || value == false

  raise ArgumentError, "#{name} must be true or false"
end

.validate_diagnostics_option!(diagnostics) ⇒ Object

Raises:

  • (ArgumentError)


233
234
235
236
237
# File 'lib/json5/parser.rb', line 233

def self.validate_diagnostics_option!(diagnostics)
  return if diagnostics.nil? || diagnostics == :ignore || diagnostics.is_a?(Array) || diagnostics.respond_to?(:call)

  raise ArgumentError, "diagnostics must be an Array, callable, :ignore, or nil"
end

.validate_enum_option!(allowed, value, name) ⇒ Object

Raises:

  • (ArgumentError)


245
246
247
248
249
# File 'lib/json5/parser.rb', line 245

def self.validate_enum_option!(allowed, value, name)
  return if allowed.include?(value)

  raise ArgumentError, "#{name} must be one of #{allowed.inspect}"
end

.validate_limits_option!(limits) ⇒ Object

Raises:

  • (ArgumentError)


227
228
229
230
231
# File 'lib/json5/parser.rb', line 227

def self.validate_limits_option!(limits)
  return if limits.is_a?(Limits)

  raise ArgumentError, "limits must be a JSON5::Limits"
end

.validate_option_keys!(options, allowed_keys) ⇒ Object

Raises:

  • (ArgumentError)


220
221
222
223
224
225
# File 'lib/json5/parser.rb', line 220

def self.validate_option_keys!(options, allowed_keys)
  unknown_options = options.keys - allowed_keys
  return if unknown_options.empty?

  raise ArgumentError, "unknown options: #{unknown_options.map(&:to_s).sort.join(', ')}"
end

.validate_parse_options!(options) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
# File 'lib/json5/parser.rb', line 150

def self.validate_parse_options!(options)
  merged = DEFAULT_OPTIONS.merge(options)
  validate_limits_option!(merged.fetch(:limits))
  validate_diagnostics_option!(merged.fetch(:diagnostics))
  validate_boolean_option!(merged.fetch(:freeze), :freeze)
  validate_boolean_option!(merged.fetch(:warn_duplicate_keys), :warn_duplicate_keys)
  validate_enum_option!(RubyValueBuilder::VALID_DUPLICATE_POLICIES, merged.fetch(:duplicate_keys), :duplicate_keys)
  validate_enum_option!(RubyValueBuilder::VALID_NUMBER_MODES, merged.fetch(:number_mode), :number_mode)
  validate_enum_option!(RubyValueBuilder::VALID_STRING_MODES, merged.fetch(:string_mode), :string_mode)
  validate_enum_option!([:error, :replace], merged.fetch(:lone_surrogate), :lone_surrogate)
end

.validate_read_chunk!(chunk, filename:, byte_offset:, preceding:, allow_binary: false) ⇒ Object

Raises:

  • (TypeError)


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/json5/parser.rb', line 132

def self.validate_read_chunk!(chunk, filename:, byte_offset:, preceding:, allow_binary: false)
  raise TypeError, "io#read must return a String" unless chunk.is_a?(String)
  return if [Encoding::UTF_8, Encoding::US_ASCII].include?(chunk.encoding) ||
    (allow_binary && chunk.encoding == Encoding::ASCII_8BIT)

  line, column = Input.position_for(preceding || chunk, byte_offset)
  raise EncodingError.new(
    "source must be UTF-8 or US-ASCII",
    code: "invalid_encoding",
    filename: filename,
    byte_offset: byte_offset,
    end_byte_offset: byte_offset + [chunk.bytesize, 1].min,
    line: line,
    column: column,
    excerpt: limit_excerpt(preceding || String.new(encoding: Encoding::BINARY), chunk, byte_offset)
  )
end

Instance Method Details

#parseObject



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
# File 'lib/json5/parser.rb', line 186

def parse
  builder = RubyValueBuilder.new(
    number_mode: @options.fetch(:number_mode),
    string_mode: @options.fetch(:string_mode),
    lone_surrogate: @options.fetch(:lone_surrogate),
    duplicate_keys: @options.fetch(:duplicate_keys),
    limits: @options.fetch(:limits),
    diagnostics: @options.fetch(:diagnostics),
    warn_duplicate_keys: @options.fetch(:warn_duplicate_keys),
    freeze_values: @options.fetch(:freeze),
    source: @input.source,
    filename: @options.fetch(:filename)
  )
  lexer = Lexer.new(
    @input,
    limits: @options.fetch(:limits),
    diagnostics: @options.fetch(:diagnostics),
    filename: @options.fetch(:filename)
  )
  @lexer = lexer
  generated = GeneratedParser.new(lexer, builder)
  generated.parse_tokens
rescue JSON5::Error => error
  raise enrich_error(error)
rescue Ibex::Runtime::ParseError => error
  raise enrich_error(translate_parse_error(error))
end