summaryrefslogtreecommitdiff
path: root/lib/erb/compiler.rb
blob: 7096c8dcea802ca482589577c377b6d19b0cd5aa (plain)
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# frozen_string_literal: true
#--
# ERB::Compiler
#
# Compiles ERB templates into Ruby code; the compiled code produces the
# template result when evaluated. ERB::Compiler provides hooks to define how
# generated output is handled.
#
# Internally ERB does something like this to generate the code returned by
# ERB#src:
#
#   compiler = ERB::Compiler.new('<>')
#   compiler.pre_cmd    = ["_erbout=+''"]
#   compiler.put_cmd    = "_erbout.<<"
#   compiler.insert_cmd = "_erbout.<<"
#   compiler.post_cmd   = ["_erbout"]
#
#   code, enc = compiler.compile("Got <%= obj %>!\n")
#   puts code
#
# <i>Generates</i>:
#
#   #coding:UTF-8
#   _erbout=+''; _erbout.<< "Got ".freeze; _erbout.<<(( obj ).to_s); _erbout.<< "!\n".freeze; _erbout
#
# By default the output is sent to the print method.  For example:
#
#   compiler = ERB::Compiler.new('<>')
#   code, enc = compiler.compile("Got <%= obj %>!\n")
#   puts code
#
# <i>Generates</i>:
#
#   #coding:UTF-8
#   print "Got ".freeze; print(( obj ).to_s); print "!\n".freeze
#
# == Evaluation
#
# The compiled code can be used in any context where the names in the code
# correctly resolve. Using the last example, each of these print 'Got It!'
#
# Evaluate using a variable:
#
#   obj = 'It'
#   eval code
#
# Evaluate using an input:
#
#   mod = Module.new
#   mod.module_eval %{
#     def get(obj)
#       #{code}
#     end
#   }
#   extend mod
#   get('It')
#
# Evaluate using an accessor:
#
#   klass = Class.new Object
#   klass.class_eval %{
#     attr_accessor :obj
#     def initialize(obj)
#       @obj = obj
#     end
#     def get_it
#       #{code}
#     end
#   }
#   klass.new('It').get_it
#
# Good! See also ERB#def_method, ERB#def_module, and ERB#def_class.
class ERB::Compiler # :nodoc:
  class PercentLine # :nodoc:
    def initialize(str)
      @value = str
    end
    attr_reader :value
    alias :to_s :value
  end

  class Scanner # :nodoc:
    @scanner_map = {}
    class << self
      def register_scanner(klass, trim_mode, percent)
        @scanner_map[[trim_mode, percent]] = klass
      end
      alias :regist_scanner :register_scanner
    end

    def self.default_scanner=(klass)
      @default_scanner = klass
    end

    def self.make_scanner(src, trim_mode, percent)
      klass = @scanner_map.fetch([trim_mode, percent], @default_scanner)
      klass.new(src, trim_mode, percent)
    end

    DEFAULT_STAGS = %w(<%% <%= <%# <%).freeze
    DEFAULT_ETAGS = %w(%%> %>).freeze
    def initialize(src, trim_mode, percent)
      @src = src
      @stag = nil
      @stags = DEFAULT_STAGS
      @etags = DEFAULT_ETAGS
    end
    attr_accessor :stag
    attr_reader :stags, :etags

    def scan; end
  end

  class TrimScanner < Scanner # :nodoc:
    def initialize(src, trim_mode, percent)
      super
      @trim_mode = trim_mode
      @percent = percent
      if @trim_mode == '>'
        @scan_reg  = /(.*?)(%>\r?\n|#{(stags + etags).join('|')}|\n|\z)/m
        @scan_line = self.method(:trim_line1)
      elsif @trim_mode == '<>'
        @scan_reg  = /(.*?)(%>\r?\n|#{(stags + etags).join('|')}|\n|\z)/m
        @scan_line = self.method(:trim_line2)
      elsif @trim_mode == '-'
        @scan_reg  = /(.*?)(^[ \t]*<%\-|<%\-|-%>\r?\n|-%>|#{(stags + etags).join('|')}|\z)/m
        @scan_line = self.method(:explicit_trim_line)
      else
        @scan_reg  = /(.*?)(#{(stags + etags).join('|')}|\n|\z)/m
        @scan_line = self.method(:scan_line)
      end
    end

    def scan(&block)
      @stag = nil
      if @percent
        @src.each_line do |line|
          percent_line(line, &block)
        end
      else
        @scan_line.call(@src, &block)
      end
      nil
    end

    def percent_line(line, &block)
      if @stag || line[0] != ?%
        return @scan_line.call(line, &block)
      end

      line[0] = ''
      if line[0] == ?%
        @scan_line.call(line, &block)
      else
        yield(PercentLine.new(line.chomp))
      end
    end

    def scan_line(line)
      line.scan(@scan_reg) do |tokens|
        tokens.each do |token|
          next if token.empty?
          yield(token)
        end
      end
    end

    def trim_line1(line)
      line.scan(@scan_reg) do |tokens|
        tokens.each do |token|
          next if token.empty?
          if token == "%>\n" || token == "%>\r\n"
            yield('%>')
            yield(:cr)
          else
            yield(token)
          end
        end
      end
    end

    def trim_line2(line)
      head = nil
      line.scan(@scan_reg) do |tokens|
        tokens.each do |token|
          next if token.empty?
          head = token unless head
          if token == "%>\n" || token == "%>\r\n"
            yield('%>')
            if is_erb_stag?(head)
              yield(:cr)
            else
              yield("\n")
            end
            head = nil
          else
            yield(token)
            head = nil if token == "\n"
          end
        end
      end
    end

    def explicit_trim_line(line)
      line.scan(@scan_reg) do |tokens|
        tokens.each do |token|
          next if token.empty?
          if @stag.nil? && /[ \t]*<%-/ =~ token
            yield('<%')
          elsif @stag && (token == "-%>\n" || token == "-%>\r\n")
            yield('%>')
            yield(:cr)
          elsif @stag && token == '-%>'
            yield('%>')
          else
            yield(token)
          end
        end
      end
    end

    ERB_STAG = %w(<%= <%# <%)
    def is_erb_stag?(s)
      ERB_STAG.member?(s)
    end
  end

  Scanner.default_scanner = TrimScanner

  begin
    require 'strscan'
  rescue LoadError
  else
    class SimpleScanner < Scanner # :nodoc:
      def scan
        stag_reg = (stags == DEFAULT_STAGS) ? /(.*?)(<%[%=#]?|\z)/m : /(.*?)(#{stags.join('|')}|\z)/m
        etag_reg = (etags == DEFAULT_ETAGS) ? /(.*?)(%%?>|\z)/m : /(.*?)(#{etags.join('|')}|\z)/m
        scanner = StringScanner.new(@src)
        while ! scanner.eos?
          scanner.scan(@stag ? etag_reg : stag_reg)
          yield(scanner[1])
          yield(scanner[2])
        end
      end
    end
    Scanner.register_scanner(SimpleScanner, nil, false)

    class ExplicitScanner < Scanner # :nodoc:
      def scan
        stag_reg = /(.*?)(^[ \t]*<%-|<%-|#{stags.join('|')}|\z)/m
        etag_reg = /(.*?)(-%>|#{etags.join('|')}|\z)/m
        scanner = StringScanner.new(@src)
        while ! scanner.eos?
          scanner.scan(@stag ? etag_reg : stag_reg)
          yield(scanner[1])

          elem = scanner[2]
          if /[ \t]*<%-/ =~ elem
            yield('<%')
          elsif elem == '-%>'
            yield('%>')
            yield(:cr) if scanner.scan(/(\r?\n|\z)/)
          else
            yield(elem)
          end
        end
      end
    end
    Scanner.register_scanner(ExplicitScanner, '-', false)
  end

  class Buffer # :nodoc:
    def initialize(compiler, enc=nil, frozen=nil)
      @compiler = compiler
      @line = []
      @script = +''
      @script << "#coding:#{enc}\n" if enc
      @script << "#frozen-string-literal:#{frozen}\n" unless frozen.nil?
      @compiler.pre_cmd.each do |x|
        push(x)
      end
    end
    attr_reader :script

    def push(cmd)
      @line << cmd
    end

    def cr
      @script << (@line.join('; '))
      @line = []
      @script << "\n"
    end

    def close
      return unless @line
      @compiler.post_cmd.each do |x|
        push(x)
      end
      @script << (@line.join('; '))
      @line = nil
    end
  end

  def add_put_cmd(out, content)
    out.push("#{@put_cmd} #{content.dump}.freeze#{"\n" * content.count("\n")}")
  end

  def add_insert_cmd(out, content)
    out.push("#{@insert_cmd}((#{content}).to_s)")
  end

  # Compiles an ERB template into Ruby code.  Returns an array of the code
  # and encoding like ["code", Encoding].
  def compile(s)
    enc = s.encoding
    raise ArgumentError, "#{enc} is not ASCII compatible" if enc.dummy?
    s = s.b # see String#b
    magic_comment = detect_magic_comment(s, enc)
    out = Buffer.new(self, *magic_comment)

    self.content = +''
    scanner = make_scanner(s)
    scanner.scan do |token|
      next if token.nil?
      next if token == ''
      if scanner.stag.nil?
        compile_stag(token, out, scanner)
      else
        compile_etag(token, out, scanner)
      end
    end
    add_put_cmd(out, content) if content.size > 0
    out.close
    return out.script, *magic_comment
  end

  def compile_stag(stag, out, scanner)
    case stag
    when PercentLine
      add_put_cmd(out, content) if content.size > 0
      self.content = +''
      out.push(stag.to_s)
      out.cr
    when :cr
      out.cr
    when '<%', '<%=', '<%#'
      scanner.stag = stag
      add_put_cmd(out, content) if content.size > 0
      self.content = +''
    when "\n"
      content << "\n"
      add_put_cmd(out, content)
      self.content = +''
    when '<%%'
      content << '<%'
    else
      content << stag
    end
  end

  def compile_etag(etag, out, scanner)
    case etag
    when '%>'
      compile_content(scanner.stag, out)
      scanner.stag = nil
      self.content = +''
    when '%%>'
      content << '%>'
    else
      content << etag
    end
  end

  def compile_content(stag, out)
    case stag
    when '<%'
      if content[-1] == ?\n
        content.chop!
        out.push(content)
        out.cr
      else
        out.push(content)
      end
    when '<%='
      add_insert_cmd(out, content)
    when '<%#'
      out.push("\n" * content.count("\n")) # only adjust lineno
    end
  end

  def prepare_trim_mode(mode) # :nodoc:
    case mode
    when 1
      return [false, '>']
    when 2
      return [false, '<>']
    when 0, nil
      return [false, nil]
    when String
      unless mode.match?(/\A(%|-|>|<>){1,2}\z/)
        warn_invalid_trim_mode(mode, uplevel: 5)
      end

      perc = mode.include?('%')
      if mode.include?('-')
        return [perc, '-']
      elsif mode.include?('<>')
        return [perc, '<>']
      elsif mode.include?('>')
        return [perc, '>']
      else
        [perc, nil]
      end
    else
      warn_invalid_trim_mode(mode, uplevel: 5)
      return [false, nil]
    end
  end

  def make_scanner(src) # :nodoc:
    Scanner.make_scanner(src, @trim_mode, @percent)
  end

  # Construct a new compiler using the trim_mode. See ERB::new for available
  # trim modes.
  def initialize(trim_mode)
    @percent, @trim_mode = prepare_trim_mode(trim_mode)
    @put_cmd = 'print'
    @insert_cmd = @put_cmd
    @pre_cmd = []
    @post_cmd = []
  end
  attr_reader :percent, :trim_mode

  # The command to handle text that ends with a newline
  attr_accessor :put_cmd

  # The command to handle text that is inserted prior to a newline
  attr_accessor :insert_cmd

  # An array of commands prepended to compiled code
  attr_accessor :pre_cmd

  # An array of commands appended to compiled code
  attr_accessor :post_cmd

  private

  # A buffered text in #compile
  attr_accessor :content

  def detect_magic_comment(s, enc = nil)
    re = @percent ? /\G(?:<%#(.*)%>|%#(.*)\n)/ : /\G<%#(.*)%>/
    frozen = nil
    s.scan(re) do
      comment = $+
      comment = $1 if comment[/-\*-\s*([^\s].*?)\s*-\*-$/]
      case comment
      when %r"coding\s*[=:]\s*([[:alnum:]\-_]+)"
        enc = Encoding.find($1.sub(/-(?:mac|dos|unix)/i, ''))
      when %r"frozen[-_]string[-_]literal\s*:\s*([[:alnum:]]+)"
        frozen = $1
      end
    end
    return enc, frozen
  end

  def warn_invalid_trim_mode(mode, uplevel:)
    warn "Invalid ERB trim mode: #{mode.inspect} (trim_mode: nil, 0, 1, 2, or String composed of '%' and/or '-', '>', '<>')", uplevel: uplevel + 1
  end
end