Class: RubyNext::Language::Rewriters::Text::Normalizer

Inherits:
PacoParsers::Base show all
Defined in:
lib/ruby-next/language/rewriters/text.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from PacoParsers::Base

#parse

Constructor Details

#initializeNormalizer

Returns a new instance of Normalizer.



14
15
16
# File 'lib/ruby-next/language/rewriters/text.rb', line 14

def initialize
  @store = []
end

Instance Attribute Details

#storeObject (readonly)

Returns the value of attribute store.



12
13
14
# File 'lib/ruby-next/language/rewriters/text.rb', line 12

def store
  @store
end

Instance Method Details

#normalizing(source) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ruby-next/language/rewriters/text.rb', line 18

def normalizing(source)
  many(
    alt(
      ruby_comment,
      ruby_string,
      ruby_code
    )
  ).parse(source, with_callstack: true)
    .then(&:join)
    .then do
      if block_given?
        yield _1
      else
        _1
      end
    end
    .then do |new_source|
    restore(new_source)
  end
end

#parse_commentsObject



70
71
72
# File 'lib/ruby-next/language/rewriters/text.rb', line 70

def parse_comments
  memoize { PacoParsers::Comments.new.default }
end

#parse_stringsObject



74
75
76
# File 'lib/ruby-next/language/rewriters/text.rb', line 74

def parse_strings
  memoize { PacoParsers::StringLiterals.new.default }
end

#restore(source) ⇒ Object



64
65
66
67
68
# File 'lib/ruby-next/language/rewriters/text.rb', line 64

def restore(source)
  source.gsub(/(?:\# |_)A(\d+)Я(?:_|\n)/m) do |*args|
    store[$1.to_i - 1]
  end
end

#ruby_codeObject



60
61
62
# File 'lib/ruby-next/language/rewriters/text.rb', line 60

def ruby_code
  any_char
end

#ruby_commentObject



39
40
41
42
43
44
# File 'lib/ruby-next/language/rewriters/text.rb', line 39

def ruby_comment
  parse_comments.fmap do |result|
    store << result
    "# A#{store.size}Я\n"
  end
end

#ruby_stringObject



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ruby-next/language/rewriters/text.rb', line 46

def ruby_string
  parse_strings.fmap do |result|
    result.each_with_object([]) do |(type, str), acc|
      if type == :literal
        store << str
        acc << "_A#{store.size}Я_"
      else
        acc << str
      end
      acc
    end.join
  end
end