Class: Dommy::Js::Quickjs::SourceGuard::Rewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/js/quickjs/source_guard.rb

Overview

Walks source once, copying literals/comments verbatim and rewriting a for-of-with-yield-in-iterable found at a statement boundary.

Constant Summary collapse

HEAD_SCAN_LIMIT =

Upper bound on a ‘for (…)` head length we will consider (well above any real for-of header, including a large iterable expression).

64 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(src) ⇒ Rewriter

Returns a new instance of Rewriter.



230
231
232
233
# File 'lib/dommy/js/quickjs/source_guard.rb', line 230

def initialize(src)
  @src = src
  @n = src.length
end

Instance Method Details

#runObject



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
# File 'lib/dommy/js/quickjs/source_guard.rb', line 235

def run
  out = +""
  i = 0
  prev = nil  # previous significant code char
  counter = 0
  while i < @n
    stop = SourceGuard.atom_end(@src, i, prev)
    if stop
      out << @src[i...stop]
      prev = @src[stop - 1]
      i = stop
      next
    end

    ch = @src[i]
    if ch == "f" && @src[i, 3] == "for" &&
       !SourceGuard.ident_char?(i.zero? ? nil : @src[i - 1]) &&
       !SourceGuard.ident_char?(@src[i + 3]) &&
       boundary?(prev)
      rewrite = transform_for(i, counter)
      if rewrite
        out << rewrite[:text]
        i = rewrite[:next]
        counter += 1
        prev = ")"
        next
      end
    end

    out << ch
    prev = ch unless ch =~ /\s/
    i += 1
  end
  out
end