File: unparser_spec.rb

package info (click to toggle)
ruby-unparser 0.6.13-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 936 kB
  • sloc: ruby: 7,691; sh: 6; makefile: 4
file content (439 lines) | stat: -rw-r--r-- 9,911 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
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
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
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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
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
require 'spec_helper'

describe Unparser do
  describe '.buffer' do
    let(:source) { 'a + b' }

    def apply
      described_class.buffer(source)
    end

    it 'returns parser buffer with expected name' do
      expect(apply.name).to eql('(string)')
    end

    it 'returns parser buffer with pre-filled source' do
      expect(apply.source).to eql(source)
    end

    context 'on non default identification' do
      def apply
        described_class.buffer(source, '(foo)')
      end

      it 'returns parser buffer with expected name' do
        expect(apply.name).to eql('(foo)')
      end
    end
  end

  describe '.parser' do
    let(:invalid_source_buffer) { Unparser.buffer('a +') }

    def apply
      described_class.parser
    end

    context 'failure' do
      def apply
        super.tap do |parser|
          parser.diagnostics.consumer = ->(_) {}
        end
      end

      it 'returns a parser that fails with syntax error' do
        expect { apply.parse(invalid_source_buffer) }
          .to raise_error(Parser::SyntaxError)
      end
    end
  end

  describe '.parse' do
    def apply
      described_class.parse(source)
    end

    context 'on present source' do
      let(:source) { 'self[1]=2' }

      it 'returns expected AST' do
        expect(apply).to eql(s(:indexasgn, s(:self), s(:int, 1), s(:int, 2)))
      end
    end

    context 'on empty source' do
      let(:source) { '' }

      it 'returns ni' do
        expect(apply).to be(nil)
      end
    end

    context 'on syntax error' do
      let(:source) { '[' }

      it 'raises error' do
        expect { apply }.to raise_error(Parser::SyntaxError)
      end
    end
  end

  describe '.parse_either' do
    def apply
      described_class.parse_either(source)
    end

    context 'on present source' do
      let(:source) { 'self[1]=2' }

      it 'returns right value with expected AST' do
        expect(apply).to eql(right(s(:indexasgn, s(:self), s(:int, 1), s(:int, 2))))
      end
    end

    context 'on empty source' do
      let(:source) { '' }

      it 'returns right value with nil' do
        expect(apply).to eql(right(nil))
      end
    end

    context 'on syntax error' do
      let(:source) { '[' }

      it 'returns left value with syntax error' do
        result = apply

        # Syntax errors that compare nicely under #eql? are hard to construct
        expect(result).to be_instance_of(Unparser::Either::Left)
        expect(result.from_left).to be_instance_of(Parser::SyntaxError)
      end
    end
  end

  describe '.unparse_validate' do
    def apply
      Unparser.unparse_validate(s(:true))
    end

    context 'on successful validation' do
      context 'with comments' do
        def apply
          Unparser.unparse_validate(
            *Unparser.parser.parse_with_comments(Unparser.buffer('true # foo'))
          )
        end

        it 'returns right value with generated source' do
          expect(apply).to eql(right('true # foo'))
        end
      end

      context 'without comments' do
        it 'returns right value with generated source' do
          expect(apply).to eql(right('true'))
        end
      end
    end

    context 'on unsuccessful validation' do
      before do
        allow(Unparser::Validation).to receive_messages(from_string: validation)
      end

      let(:validation) do
        instance_double(Unparser::Validation, success?: false)
      end

      it 'returns left value with validation' do
        expect(apply).to eql(left(validation))
      end
    end
  end

  describe '.unparse' do
    context 'on unknown node type' do
      def apply
        Unparser.unparse(node)
      end

      let(:node) { s(:example_node) }

      it 'raises UnknownNodeError' do
        expect { apply }.to raise_error(
          Unparser::UnknownNodeError,
          'Unknown node type: :example_node'
        )
      end
    end
  end

  describe '.unparse' do
    def parser
      Unparser.parser
    end

    def buffer(input)
      Unparser.buffer(input)
    end

    def parse_with_comments(string)
      parser.parse_with_comments(buffer(string))
    end

    def assert_generates_from_string(parser, string, expected)
      ast_with_comments = parse_with_comments(string)
      assert_generates_from_ast(parser, ast_with_comments, expected.chomp)
    end

    def assert_generates_from_ast(parser, ast_with_comments, expected)
      generated = Unparser.unparse(*ast_with_comments).chomp
      expect(generated).to eql(expected)
      ast, comments = parse_with_comments(generated)
      expect(ast).to eql(ast_with_comments.first)
      expect(Unparser.unparse(ast, comments).chomp).to eql(expected)
    end

    def self.assert_generates(input, expected)
      it "should generate #{input} as #{expected}" do
        if input.is_a?(String)
          assert_generates_from_string(parser, input, expected)
        else
          assert_generates_from_ast(parser, [input, []], expected)
        end
      end
    end

    def self.assert_source(string)
      it 'round trips' do
        ast, comments = parse_with_comments(string)
        generated = Unparser.unparse(ast, comments).chomp
        expect(generated).to eql(string.chomp)
        generated_ast, _comments = parse_with_comments(generated)
        expect(ast == generated_ast).to be(true)
      end
    end

    context 'on empty source' do
      assert_source ''
    end

    context 'invalid send selector' do
      let(:node) { s(:send, nil, :module) }

      it 'raises InvalidNode error' do
        expect { Unparser.unparse(node) }.to raise_error do |error|
          expect(error).to be_a(Unparser::InvalidNodeError)
          expect(error.message).to eql('Invalid selector for send node: :module')
          expect(error.node).to be(node)
        end
      end
    end

    %w(next return break).each do |keyword|
      context keyword do
        assert_source "#{keyword} 1"
        assert_source "#{keyword} 2, 3"
        assert_source "#{keyword} *nil"
        assert_source "#{keyword} *foo, bar"

        assert_source <<~RUBY
          foo { |bar|
            bar =~ // or #{keyword}
            baz
          }
        RUBY
      end
    end

    context 'op assign' do
      %w(|= ||= &= &&= += -= *= /= **= %=).each do |op|
        assert_source "self.foo #{op} bar"
        assert_source "foo[key] #{op} bar"
        assert_source "a #{op} (true; false)"
      end
    end

    context 'element assignment' do
      %w(+ - * / % & | || &&).each do |operator|
        context "with #{operator}" do
          assert_source "foo[index] #{operator}= 2"
          assert_source "foo[] #{operator}= 2"
        end
      end
    end

    context 'binary operator methods' do
      %w(+ - * / & | << >> == === != <= < <=> > >= =~ !~ ^ **).each do |operator|
        assert_source "(-1) #{operator} 2"
        assert_source "(-1.2) #{operator} 2"
        assert_source "left.#{operator}(*foo)"
        assert_source "left.#{operator}(a, b)"
        assert_source "self #{operator} b"
        assert_source "a #{operator} b"
        assert_source "(a #{operator} b).foo"
      end

      assert_source 'left / right'
    end

    assert_source <<~'RUBY'
      # comment before
      a_line_of_code
    RUBY

    assert_source <<~'RUBY'
      a_line_of_code # comment after
    RUBY

    assert_source <<~'RUBY'
      nested {
        # first
        # second
        something # comment
      } # another
      # last
    RUBY

    assert_generates <<~'RUBY', <<~'RUBY'
      foo if bar
      # comment
    RUBY
      if bar
        foo
      end
      # comment
    RUBY

    assert_source <<~'RUBY'
      def noop
        # do nothing
      end
    RUBY

    assert_source <<~'RUBY'
      =begin
        block comment
      =end
      nested {
      =begin
      another block comment
      =end
        something
      }
      =begin
      last block comment
      =end
    RUBY

    assert_generates(<<~'RUBY', <<~'RUBY')
      1 + # first
        2 # second
    RUBY
      1 + 2 # first # second
    RUBY

    assert_generates(<<~'RUBY', <<~'RUBY')
      1 +
        # first
        2 # second
    RUBY
      1 + 2 # first # second
    RUBY

    assert_generates(<<~'RUBY', <<~'RUBY')
      1 +
      =begin
        block comment
      =end
        2
    RUBY
      1 + 2
      =begin
        block comment
      =end
    RUBY

    assert_generates(<<~'RUBY', <<~'RUBY')
      true ? "true" : ()
    RUBY
      if true
        "true"
      else
        ()
      end
    RUBY

    assert_generates(<<~'RUBY', <<~'RUBY')
      true ? () : "false"
    RUBY
      if true
        ()
      else
        "false"
      end
    RUBY

    assert_source(<<~'RUBY')
      if true
        "true"
      else
        ()
      end
    RUBY

    assert_source(<<~'RUBY')
      if true
        ()
      else
        "false"
      end
    RUBY

    # Test Symbol#inspect Ruby bug: https://bugs.ruby-lang.org/issues/18905
    assert_source(':"@="')
    assert_source(':"$$$$="')
    assert_source(':"8 >="')
  end

  describe 'corpus' do
    let(:version_excludes) do
      excludes = []

      if RUBY_VERSION < '3.2.'
        excludes.concat(
          %w[
            test/corpus/literal/since/32.rb
          ]
        )
      end

      if RUBY_VERSION < '3.1.'
        excludes.concat(
          %w[
            test/corpus/literal/since/31.rb
          ]
        )
      end

      if RUBY_VERSION < '3.0.'
        excludes.concat(
          %w[
            test/corpus/literal/since/30.rb
          ]
        )
      end

      excludes.flat_map { |file| ['--ignore', file] }
    end

    it 'passes the literal corpus' do
      expect(Unparser::CLI.run(%w[test/corpus/literal --literal] + version_excludes)).to be(0)
    end

    it 'passes the semantic corpus' do
      expect(Unparser::CLI.run(%w[test/corpus/semantic] + version_excludes)).to be(0)
    end
  end
end