Class: Interscript::Compiler::Javascript

Inherits:
Interscript::Compiler show all
Defined in:
lib/interscript/compiler/javascript.rb

Class Attribute Summary collapse

Attributes inherited from Interscript::Compiler

#code

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Interscript::Compiler

call

Class Attribute Details

.ctxObject

Returns the value of attribute ctx.



258
259
260
# File 'lib/interscript/compiler/javascript.rb', line 258

def ctx
  @ctx
end

.maps_loadedObject

Returns the value of attribute maps_loaded.



257
258
259
# File 'lib/interscript/compiler/javascript.rb', line 257

def maps_loaded
  @maps_loaded
end

Class Method Details

.read_debug_dataObject



290
291
292
# File 'lib/interscript/compiler/javascript.rb', line 290

def self.read_debug_data
  self.ctx.eval "globalThis.map_debug || []"
end

.reset_debug_dataObject



294
295
296
# File 'lib/interscript/compiler/javascript.rb', line 294

def self.reset_debug_data
  self.ctx.eval "globalThis.map_debug = []"
end

Instance Method Details

#build_regexp(r, map = @map) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/interscript/compiler/javascript.rb', line 130

def build_regexp(r, map=@map)
  from = compile_item(r.from, map, :re)
  before = compile_item(r.before, map, :re) if r.before
  after = compile_item(r.after, map, :re) if r.after
  not_before = compile_item(r.not_before, map, :re) if r.not_before
  not_after = compile_item(r.not_after, map, :re) if r.not_after

  re = ""
  re += "(?<=#{before})" if before
  re += "(?<!#{not_before})" if not_before
  re += from
  re += "(?!#{not_after})" if not_after
  re += "(?=#{after})" if after

  re
end

#call(str, stage = :main) ⇒ Object



285
286
287
288
# File 'lib/interscript/compiler/javascript.rb', line 285

def call(str, stage=:main)
  load
  self.class.ctx.eval "Interscript.transliterate(#{@map.name.to_json}, #{str.to_json}, #{stage.to_json})"
end

#compile(map, debug: false) ⇒ Object



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
# File 'lib/interscript/compiler/javascript.rb', line 9

def compile(map, debug: false)
  @map = map
  @parallel_trees = {}
  @parallel_regexps = {}
  @debug = debug
  c = "var map = function(Interscript) {"
  c << "Interscript.define_map(#{map.name.inspect}, function(Interscript, map) {\n";
  c << "map.dependencies = #{map.dependencies.map(&:full_name).to_json};\n"
  c

  map.aliases.each do |name, value|
    val = compile_item(value.data, map, :str)
    c << "map.aliases.#{name} = #{val};\n"
    val = '"'+compile_item(value.data, map, :re)+'"'
    c << "map.aliases_re.#{name} = #{val};\n"
  end

  map.stages.each do |_, stage|
    c << compile_rule(stage, @map, true)
  end
  @parallel_trees.each do |k,v|
    c << "map.cache.PTREE_#{k} = #{v.to_json};\n"
  end
  @parallel_regexps.each do |k,v|
    v = "[\"#{v[0]}\", #{v[1].to_json}]"
    c << "map.cache.PRE_#{k} = #{v};\n"
  end

  c << "});"
  c << "};"
  c << "if (typeof module !== 'undefined') { module.exports = map; }"
  c << "else if (typeof Interscript !== 'undefined') { map(Interscript); }"
  c << 'else { throw "We couldn\'t dispatch Interscript from a map!"; }'
  @code = c
end

#compile_item(i, doc = @map, target = nil) ⇒ Object



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
# File 'lib/interscript/compiler/javascript.rb', line 147

def compile_item i, doc=@map, target=nil
  i = i.first_string if %i[str parstr].include? target
  i = Interscript::Node::Item.try_convert(i)
  if target == :parstr
    parstr = true
    target = :par
  end

  out = case i
  when Interscript::Node::Item::Alias
    astr = if i.map
      d = doc.dep_aliases[i.map].document
      a = d.imported_aliases[i.name]
      raise Interscript::SystemConversionError, "Alias #{i.name} of #{i.stage.map} not found" unless a
      "Interscript.get_alias_ALIASTYPE(#{a.doc_name.to_json}, #{a.name.to_json})"
    elsif Interscript::Stdlib::ALIASES.include?(i.name)
      if target != :re && Interscript::Stdlib.re_only_alias?(i.name)
        raise Interscript::SystemConversionError, "Can't use #{i.name} in a #{target} context"
      end
      stdlib_alias = true
      "Interscript.aliases.#{i.name}"
    else
      a = doc.imported_aliases[i.name]
      raise Interscript::SystemConversionError, "Alias #{i.name} not found" unless a

      "Interscript.get_alias_ALIASTYPE(#{a.doc_name.to_json}, #{a.name.to_json})"
    end

    if target == :str
      astr = astr.sub("_ALIASTYPE(", "(")
    elsif target == :re
      astr = %{"+#{astr.sub("_ALIASTYPE(", "_re(")}+"}
    elsif parstr && stdlib_alias
      astr = Interscript::Stdlib::ALIASES[i.name]
    elsif target == :par
      # raise NotImplementedError, "Can't use aliases in parallel mode yet"
      astr = Interscript::Stdlib::ALIASES[i.name]
    end
  when Interscript::Node::Item::String
    if target == :str
      # Replace $1 with \$1, this is weird, but it works!
      i.data.gsub("$", "\\\\$").to_json
    elsif target == :par
      i.data
    elsif target == :re
      Regexp.escape(i.data)
    end
  when Interscript::Node::Item::Group
    if target == :par
      i.children.map do |j|
        compile_item(j, doc, target)
      end.reduce([""]) do |j,k|
        Array(j).product(Array(k)).map(&:join)
      end
    elsif target == :str
      i.children.map { |j| compile_item(j, doc, target) }.join("+")
    elsif target == :re
      i.children.map { |j| compile_item(j, doc, target) }.join
    end
  when Interscript::Node::Item::CaptureGroup
    if target != :re
      raise Interscript::SystemConversionError, "Can't use a CaptureGroup in a #{target} context"
    end
    "(" + compile_item(i.data, doc, target) + ")"
  when Interscript::Node::Item::Maybe,
       Interscript::Node::Item::MaybeSome,
       Interscript::Node::Item::Some

    resuffix = { Interscript::Node::Item::Maybe     => "?" ,
                 Interscript::Node::Item::Some      => "+" ,
                 Interscript::Node::Item::MaybeSome => "*" }[i.class]

    if target == :par
      raise Interscript::SystemConversionError, "Can't use a MaybeSome in a #{target} context"
    end
    if Interscript::Node::Item::String === i.data && i.data.data.length != 1
      "(?:" + compile_item(i.data, doc, target) + ")" + resuffix
    else
      compile_item(i.data, doc, target) + resuffix
    end
  when Interscript::Node::Item::CaptureRef
    if target == :par
      raise Interscript::SystemConversionError, "Can't use CaptureRef in parallel mode"
    elsif target == :re
      "\\\\#{i.id}"
    elsif target == :str
      "\"$#{i.id}\""
    end
  when Interscript::Node::Item::Any
    if target == :str
      raise Interscript::SystemConversionError, "Can't use Any in a string context" # A linter could find this!
    elsif target == :par
      i.data.map(&:data)
    elsif target == :re
      case i.value
      when Array
        data = i.data.map { |j| compile_item(j, doc, target) }
        "(?:"+data.join("|")+")"
      when String
        "[#{Regexp.escape(i.value)}]"
      when Range
        "[#{Regexp.escape(i.value.first)}-#{Regexp.escape(i.value.last)}]"
      end
    end
  end
end

#compile_rule(r, map = @map, wrapper = false) ⇒ Object



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
# File 'lib/interscript/compiler/javascript.rb', line 54

def compile_rule(r, map = @map, wrapper = false)
  c = ""
  return c if r.reverse_run == true
  case r
  when Interscript::Node::Stage
    c += "map.stages.#{r.name} = function(s) {\n"
    c += "globalThis.map_debug = globalThis.map_debug || [];\n" if @debug
    r.children.each do |t|
      comp = compile_rule(t, map)
      c += comp
      c += %{globalThis.map_debug.push([s, #{@map.name.to_s.to_json}, #{r.name.to_s.to_json}, #{t.inspect.to_json}, #{comp.to_json}]);\n} if @debug
    end
    c += "return s;\n"
    c += "};\n"
  when Interscript::Node::Group::Parallel
    begin
      # Try to build a tree
      a = []
      r.children.each do |i|
        raise Interscript::SystemConversionError, "Can't parallelize #{i.class}" unless Interscript::Node::Rule::Sub === i
        raise Interscript::SystemConversionError, "Can't parallelize rules with :before" if i.before
        raise Interscript::SystemConversionError, "Can't parallelize rules with :after" if i.after
        raise Interscript::SystemConversionError, "Can't parallelize rules with :not_before" if i.not_before
        raise Interscript::SystemConversionError, "Can't parallelize rules with :not_after" if i.not_after

        next if i.reverse_run == true
        a << [compile_item(i.from, map, :par), compile_item(i.to, map, :parstr)]
      end
      ah = a.hash.abs
      unless @parallel_trees.include? ah
        tree = Interscript::Stdlib.parallel_replace_compile_tree(a)
        @parallel_trees[ah] = tree
      end
      c += "s = Interscript.parallel_replace_tree(s, map.cache.PTREE_#{ah});\n"
    rescue
      # Otherwise let's build a megaregexp
      a = []
      Interscript::Stdlib.deterministic_sort_by_max_length(r.children).each do |i|
        raise Interscript::SystemConversionError, "Can't parallelize #{i.class}" unless Interscript::Node::Rule::Sub === i
        
        next if i.reverse_run == true
        a << [build_regexp(i, map), compile_item(i.to, map, :parstr)]
      end
      ah = a.hash.abs
      unless @parallel_regexps.include? ah
        re = parallel_regexp_compile(a)
        @parallel_regexps[ah] = [re, a.map(&:last)]
      end
      c += "s = Interscript.parallel_regexp_gsub(s, map.cache.PRE_#{ah});\n"
    end
  when Interscript::Node::Rule::Sub
    from = %{"#{build_regexp(r, map).gsub("/", "\\\\/")}"}
    if r.to == :upcase
      to = 'function(a){return a.toUpperCase();}'
    elsif r.to == :downcase
      to = 'function(a){return a.toLowerCase();}'
    else
      to = compile_item(r.to, map, :str)
    end
    c += "s = Interscript.gsub(s, #{from}, #{to});\n"
  when Interscript::Node::Rule::Funcall
    c += "s = Interscript.functions.#{r.name}(s, #{r.kwargs.to_json});\n"
  when Interscript::Node::Rule::Run
    if r.stage.map
      doc = map.dep_aliases[r.stage.map].document
      stage = doc.imported_stages[r.stage.name]
    else
      stage = map.imported_stages[r.stage.name]
    end
    c += "s = Interscript.transliterate(#{stage.doc_name.to_json}, s, #{stage.name.to_json});\n"
  else
    raise Interscript::SystemConversionError, "Can't compile unhandled #{r.class}"
  end
  c
end

#loadObject



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/interscript/compiler/javascript.rb', line 261

def load
  if !self.class.maps_loaded[@map.name]
    @map.dependencies.each do |dep|
      dep = dep.full_name
      if !self.class.maps_loaded[dep]
        Interscript.load(dep, compiler: self.class).load
      end
    end

    ctx = self.class.ctx
    unless ctx
      ctx = MiniRacer::Context.new
      ctx.eval File.read(__dir__+"/../../../../js/test-compiler/xregexp.js")
      # Compatibility with Safari: will come later
      #ctx.eval File.read(__dir__+"/../../../js/xregexp-oniguruma.js")
      ctx.eval File.read(__dir__+"/../../../../js/src/stdlib.js")
      self.class.ctx = ctx
    end
    #puts @code
    ctx.eval @code
    self.class.maps_loaded[@map.name] = true
  end
end

#parallel_regexp_compile(subs_hash) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/interscript/compiler/javascript.rb', line 45

def parallel_regexp_compile(subs_hash)
  # puts subs_hash.inspect
  regexp = subs_hash.each_with_index.map do |p,i|
    "(?<_%d>%s)" % [i,p[0]]
  end.join("|")
  subs_regexp = regexp
  # puts subs_regexp.inspect
end