Module: Peruby::Interpolation

Defined in:
lib/peruby/runtime/interpolation.rb

Overview

Expands the escape and variable forms needed by interpolating strings.

Constant Summary collapse

ESCAPED_DOLLAR =
"\u0000DOLLAR\u0000"
ESCAPED_ARRAY =
"\u0000ARRAY\u0000"
ESCAPED_BACKSLASH =
"\u0000BACKSLASH\u0000"
NAME =
/[A-Za-z_]\w*(?:(?:::|')[A-Za-z_]\w*)*/
ESCAPES =
{ 'n' => "\n", 't' => "\t", 'r' => "\r", 'f' => "\f", 'b' => "\b",
'a' => "\a", 'e' => "\e", '\\' => '\\', '"' => '"', '$' => '$', '@' => '@' }.freeze

Class Method Summary collapse

Class Method Details

.array_last(source, index, env) ⇒ Object



122
123
124
125
126
127
# File 'lib/peruby/runtime/interpolation.rb', line 122

def array_last(source, index, env)
  name = source[(index + 2)..].match(/\A(#{NAME.source})/)&.[](1)
  return [nil, nil] unless name

  [name.length + 2, (env.fetch(:array, name).size - 1).to_s]
end

.balanced_finish(source, start) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/peruby/runtime/interpolation.rb', line 150

def balanced_finish(source, start)
  pairs = { '{' => '}', '[' => ']' }
  close = pairs[source[start]]
  return unless close

  depth = 1
  index = start + 1
  while index < source.length
    depth += 1 if source[index] == source[start]
    depth -= 1 if source[index] == close
    return index + 1 if depth.zero?

    index += source[index] == '\\' ? 2 : 1
  end
end

.braced_interpolation(source, index, env) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/peruby/runtime/interpolation.rb', line 108

def braced_interpolation(source, index, env)
  finish = balanced_finish(source, index + 1)
  return [nil, nil] unless finish

  body = source[(index + 2)...(finish - 1)].strip
  marker = source[index]
  value = if marker == '$' && body.match?(/\A#{NAME.source}\z/)
            env.fetch(:scalar, body).get
          else
            dereferenced(evaluate(body, env, :scalar), marker)
          end
  [finish - index, stringify(value, marker, env)]
end

.cases(text) ⇒ Object



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
# File 'lib/peruby/runtime/interpolation.rb', line 192

def cases(text)
  output = +''
  mode = nil
  quote = false
  once = nil
  index = 0
  while index < text.length
    control = text[index, 2]
    if control.match?(/\A\\[ULQulE]\z/)
      command = control[1]
      mode = command if %w[U L].include?(command)
      quote = true if command == 'Q'
      once = command if %w[u l].include?(command)
      if command == 'E'
        mode = once = nil
        quote = false
      end
      index += 2
      next
    end

    character = text[index]
    character = mode == 'U' ? character.upcase : character.downcase if mode
    character = once == 'u' ? character.upcase : character.downcase if once
    once = nil
    output << (quote ? Regexp.escape(character) : character)
    index += 1
  end
  output
end

.consume_access_chain(source, index) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/peruby/runtime/interpolation.rb', line 136

def consume_access_chain(source, index)
  loop do
    start = if source[index, 2] == '->' && source[index + 2] && '[{'.include?(source[index + 2])
              index + 2
            elsif source[index] && '[{'.include?(source[index])
              index
            end
    break unless start

    index = balanced_finish(source, start) || index
  end
  index
end

.dereferenced(value, marker) ⇒ Object



171
172
173
174
175
176
177
# File 'lib/peruby/runtime/interpolation.rb', line 171

def dereferenced(value, marker)
  return value unless value.is_a?(Ref)
  return value.target.get if marker == '$' && value.target.is_a?(Scalar)
  return value.target.list if marker == '@' && value.target.is_a?(PerlArray)

  value
end

.escape_match(match) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/peruby/runtime/interpolation.rb', line 43

def escape_match(match)
  return match[1].to_i(16).chr(Encoding::UTF_8) if match[1]
  return match[2].to_i(16).chr(Encoding::UTF_8) if match[2]
  return match[3].to_i(8).chr if match[3]
  return (match[4].ord & 31).chr if match[4]
  return match[5].to_i(16).chr(Encoding::UTF_8) if match[5]

  return "\\#{match[6]}" if %w[U L Q u l E].include?(match[6])

  ESCAPES.fetch(match[6], match[6])
end

.escapes(text) ⇒ Object



37
38
39
40
41
# File 'lib/peruby/runtime/interpolation.rb', line 37

def escapes(text)
  text.gsub(/\\(?:x\{([0-9a-fA-F]+)\}|x([0-9a-fA-F]{1,2})|0([0-7]{0,2})|c(.)|N\{U\+([0-9a-fA-F]+)\}|(.))/) do
    escape_match(Regexp.last_match)
  end
end

.evaluate(source, env, context) ⇒ Object



166
167
168
169
# File 'lib/peruby/runtime/interpolation.rb', line 166

def evaluate(source, env, context)
  tree = Parser.parse("#{source};", file: env.runtime.current_file, package: env.package)
  Compiler.new.compile(tree).run(env, context)
end

.expand(quote, env) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/peruby/runtime/interpolation.rb', line 15

def expand(quote, env)
  raw = quote.parts.first
  return escapes(raw) unless quote.interpolate

  text = interpolate_expressions(raw, env)
  cases(escapes(text)).gsub(ESCAPED_DOLLAR, '$').gsub(ESCAPED_ARRAY, '@').gsub(ESCAPED_BACKSLASH, '\\')
end

.interpolate(value, sigil, env) ⇒ Object



55
56
57
58
59
# File 'lib/peruby/runtime/interpolation.rb', line 55

def interpolate(value, sigil, env)
  return Conv.to_str(value.get) if sigil == :scalar

  value.list.map { |cell| Conv.to_str(cell.get) }.join(Conv.to_str(env.fetch(:scalar, '"').get))
end

.interpolate_expressions(source, env) ⇒ Object



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
# File 'lib/peruby/runtime/interpolation.rb', line 61

def interpolate_expressions(source, env)
  output = +''
  index = 0
  while index < source.length
    if source[index] == '\\'
      output << source[index, 2]
      index += 2
      next
    end
    unless '$@'.include?(source[index])
      output << source[index]
      index += 1
      next
    end

    length, value = interpolation_at(source, index, env)
    unless length
      output << source[index]
      index += 1
      next
    end
    output << protect(value)
    index += length
  end
  output
end

.interpolation_at(source, index, env) ⇒ Object

rubocop:disable-next Metrics/AbcSize



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/peruby/runtime/interpolation.rb', line 89

def interpolation_at(source, index, env)
  marker = source[index]
  return array_last(source, index, env) if marker == '$' && source[index + 1] == '#'
  return scalar_dereference(source, index, env) if marker == '$' && source[index + 1] == '$'
  return braced_interpolation(source, index, env) if source[index + 1] == '{'

  name = source[(index + 1)..].match(/\A(#{NAME.source}|\d+|[&`'+])/)&.[](1)
  return [nil, nil] unless name

  finish = consume_access_chain(source, index + 1 + name.length)
  expression = source[index...finish]
  value = if finish == index + 1 + name.length
            interpolate(env.fetch(marker == '$' ? :scalar : :array, name), marker == '$' ? :scalar : :array, env)
          else
            evaluate(expression, env, marker == '$' ? :scalar : :list)
          end
  [finish - index, stringify(value, marker, env)]
end

.pattern(quote, env) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/peruby/runtime/interpolation.rb', line 23

def pattern(quote, env)
  raw = quote.parts.first.gsub('\\$', ESCAPED_DOLLAR).gsub('\\@', ESCAPED_ARRAY)
  text = raw.gsub(variable_pattern) do
    sigil = Regexp.last_match(1) == '$' ? :scalar : :array
    name = Regexp.last_match(2) || Regexp.last_match(3)
    interpolate(env.fetch(sigil, name), sigil, env)
  end
  text.gsub(ESCAPED_DOLLAR, '\\$').gsub(ESCAPED_ARRAY, '\\@')
end

.protect(value) ⇒ Object



188
189
190
# File 'lib/peruby/runtime/interpolation.rb', line 188

def protect(value)
  value.gsub('\\', ESCAPED_BACKSLASH).gsub('$', ESCAPED_DOLLAR).gsub('@', ESCAPED_ARRAY)
end

.scalar_dereference(source, index, env) ⇒ Object



129
130
131
132
133
134
# File 'lib/peruby/runtime/interpolation.rb', line 129

def scalar_dereference(source, index, env)
  name = source[(index + 2)..].match(/\A(#{NAME.source})/)&.[](1)
  return [nil, nil] unless name

  [name.length + 2, Conv.to_str(dereferenced(env.fetch(:scalar, name).get, '$'))]
end

.stringify(value, marker, env) ⇒ Object



179
180
181
182
183
184
185
186
# File 'lib/peruby/runtime/interpolation.rb', line 179

def stringify(value, marker, env)
  if marker == '@'
    return Array(value).map { |item| Conv.to_str(item.respond_to?(:get) ? item.get : item) }
                       .join(Conv.to_str(env.fetch(:scalar, '"').get))
  end

  Conv.to_str(value.respond_to?(:get) ? value.get : value)
end

.variable_patternObject



33
34
35
# File 'lib/peruby/runtime/interpolation.rb', line 33

def variable_pattern
  /([$@])(?:\{(#{NAME.source})\}|(#{NAME.source}|\d+|[&`'+]))/
end