Class: Interscript::Compiler::Ruby

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

Instance Attribute Summary

Attributes inherited from Interscript::Compiler

#code

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Interscript::Compiler

call

Class Method Details

.read_debug_dataObject



260
261
262
# File 'lib/interscript/compiler/ruby.rb', line 260

def self.read_debug_data
  $map_debug || []
end

.reset_debug_dataObject



264
265
266
# File 'lib/interscript/compiler/ruby.rb', line 264

def self.reset_debug_data
  $map_debug = []
end

Instance Method Details

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



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/interscript/compiler/ruby.rb', line 120

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



255
256
257
258
# File 'lib/interscript/compiler/ruby.rb', line 255

def call(str, stage=:main)
  load
  Interscript::Maps.transliterate(@map.name, str, stage)
end

#compile(map, debug: false) ⇒ Object



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

def compile(map, debug: false)
  @map = map
  @debug = debug
  @parallel_trees = {}
  @parallel_regexps = {}
  c = "require 'interscript/stdlib'\n"
  c << "if !defined?(Interscript::Maps); module Interscript; module Maps\n"
  c << "module Cache; end\n"
  c << "class Map < Struct.new(:stages, :aliases, :aliases_re); end\n"
  c << "@maps = Hash.new { |h,id| h[id] = Map.new({},{},{}) }\n"
  c << "def self.has_map?(map);                      @maps.include?(map); end\n"
  c << "def self.add_map_alias(map,name,value)       @maps[map].aliases[name] = value; end\n"
  c << "def self.add_map_alias_re(map,name,value)    @maps[map].aliases_re[name] = value; end\n"
  c << "def self.add_map_stage(map,stage,&block);    @maps[map].stages[stage] = block; end\n"
  c << "def self.get_alias(map,name);                @maps[map].aliases[name]; end\n"
  c << "def self.get_alias_re(map,name);             @maps[map].aliases_re[name]; end\n"
  c << "def self.transliterate(map,string,stage=:main); @maps[map].stages[stage].(string); end\n"
  c << "end; end; end\n"
  c

  map.aliases.each do |name, value|
    val = compile_item(value.data, map, :str)
    c << "Interscript::Maps.add_map_alias(#{map.name.inspect}, #{name.inspect}, #{val})\n"
    val = '/'+compile_item(value.data, map, :re).gsub('/', '\\\\/')+'/'
    c << "Interscript::Maps.add_map_alias_re(#{map.name.inspect}, #{name.inspect}, #{val})\n"
  end

  map.stages.each do |_, stage|
    c << compile_rule(stage, @map, true)
  end
  @parallel_trees.each do |k,v|
    c << "Interscript::Maps::Cache::PTREE_#{k} ||= #{v.inspect}\n"
  end
  @parallel_regexps.each do |k,v|
    c << "Interscript::Maps::Cache::PRE_#{k} ||= #{v.inspect}\n"
  end
  @code = c
end

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



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

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::Maps.get_alias_ALIASTYPE(#{a.doc_name.inspect}, #{a.name.inspect})"
    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::Stdlib::ALIASES[#{i.name.inspect}]"
    else
      a = doc.imported_aliases[i.name]
      raise Interscript::SystemConversionError, "Alias #{i.name} not found" unless a

      "Interscript::Maps.get_alias_ALIASTYPE(#{a.doc_name.inspect}, #{a.name.inspect})"
    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("\\", "\\\\\\\\").inspect
    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 Maybe 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



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

def compile_rule(r, map = @map, wrapper = false)
  c = ""
  return c if r.reverse_run == true
  case r
  when Interscript::Node::Stage
    c += "Interscript::Maps.add_map_stage \"#{@map.name}\", #{r.name.inspect} do |s|\n"
    c += "$map_debug ||= []\n" if @debug
    c += "s = s.dup\n"
    r.children.each do |t|
      comp = compile_rule(t, map)
      c += comp
      c += %{$map_debug << [s.dup, #{@map.name.to_s.inspect}, #{r.name.to_s.inspect}, #{t.inspect.inspect}, #{comp.inspect}]\n} if @debug
    end
    c += "s\n"
    c += "end\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::Stdlib.parallel_replace_tree(s, Interscript::Maps::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 = Interscript::Stdlib.parallel_regexp_compile(a)
        @parallel_regexps[ah] = [re, a.map(&:last)]
      end
      c += "s = Interscript::Stdlib.parallel_regexp_gsub(s, *Interscript::Maps::Cache::PRE_#{ah})\n"
    end
  when Interscript::Node::Rule::Sub
    from = "/#{build_regexp(r, map).gsub("/", "\\\\/")}/"
    if r.to == :upcase
      to = '&:upcase'
    elsif r.to == :downcase
      to = '&:downcase'
    else
      to = compile_item(r.to, map, :str)
    end
    c += "s.gsub!(#{from}, #{to})\n"
  when Interscript::Node::Rule::Funcall
    c += "s = Interscript::Stdlib::Functions.#{r.name}(s, #{r.kwargs.inspect[1..-2]})\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::Maps.transliterate(#{stage.doc_name.inspect}, s, #{stage.name.inspect})\n"
  else
    raise Interscript::SystemConversionError, "Can't compile unhandled #{r.class}"
  end
  c
end

#loadObject



243
244
245
246
247
248
249
250
251
252
253
# File 'lib/interscript/compiler/ruby.rb', line 243

def load
  if !defined?(Interscript::Maps) || !Interscript::Maps.has_map?(@map.name)
    @map.dependencies.each do |dep|
      dep = dep.full_name
      if !defined?(Interscript::Maps) || !Interscript::Maps.has_map?(dep)
        Interscript.load(dep, compiler: self.class).load
      end
    end
    eval(@code, $main_binding)
  end
end