Class: ABNF

Inherits:
Object
  • Object
show all
Defined in:
lib/abnftt.rb,
lib/abnftt/abnf-writer.rb,
lib/abnftt/abnf-visitor.rb,
lib/abnftt/abnf-squasher.rb,
lib/abnftt/abnf-flattener.rb

Constant Summary collapse

FIXUP_NAMES =
Hash.new {|h, k| k}
UNESCAPED_SQSTR_RANGES =
[[0xA, 0xA], [0x20, 0x26],  # "'"
   # [0x28, 0x5b], [0x5d, 0x7e], [0xa0, 0xd7ff], -- but JSON allows 7F-9F
   [0x28, 0x5b], [0x5d, 0xd7ff], # \
   [0xe000, 0x10ffff]].map {|l, r|
  [l.chr(Encoding::UTF_8), r.chr(Encoding::UTF_8)]
}
ESCAPED_SQSTR_MAPPINGS =
[
["\x08", "b"],
["\x09", "t"],
["\x0A", "n"],
["\x0C", "f"],
["\x0D", "r"],
["\x27", "'"],
["\x2F", "/"],
["\x5C", "\\"]]
@@parser =
ABNFGrammarParser.new
@@gensym =
0

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ast_ = nil, rules_ = {}) ⇒ ABNF

Returns a new instance of ABNF.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/abnftt.rb', line 61

def initialize(ast_ = nil, rules_ = {})
  if ast_
    @ast = ast_
    @tree = ast.ast
  end
  @rules = rules_
  @tree.each do |x|
    op, name, val, rest = x
    fail rest if rest
    @rules[name] =
      if old = @rules[name]
        fail "duplicate rule for name #{name}" if op == "="
        if Array === old && old[0] == "alt"
          old.dup << val
        else
          ["alt", old, val]
        end
      else
        val
      end
  end if @tree
  # warn "** rules #{rules.inspect}"
end

Instance Attribute Details

#astObject

Returns the value of attribute ast.



60
61
62
# File 'lib/abnftt.rb', line 60

def ast
  @ast
end

#parserObject

Returns the value of attribute parser.



206
207
208
# File 'lib/abnftt.rb', line 206

def parser
  @parser
end

#rulesObject

Returns the value of attribute rules.



60
61
62
# File 'lib/abnftt.rb', line 60

def rules
  @rules
end

#treeObject

Returns the value of attribute tree.



60
61
62
# File 'lib/abnftt.rb', line 60

def tree
  @tree
end

Class Method Details

.from_abnf(s) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/abnftt.rb', line 48

def self.from_abnf(s)
  ast = @@parser.parse s
  if !ast
    fail self.reason(@@parser, s)
  end
  ABNF.new(ast)
end

.from_rules(r) ⇒ Object



56
57
58
# File 'lib/abnftt.rb', line 56

def self.from_rules(r)
  ABNF.new(nil, r)
end

.reason(parser, s) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/abnftt.rb', line 37

def self.reason(parser, s)
  reason = [parser.failure_reason]
  parser.failure_reason =~ /^(Expected .+) after/m
  reason << "#{$1.gsub("\n", '<<<NEWLINE>>>')}:" if $1
  if line = s.lines.to_a[parser.failure_line - 1]
    reason << line
    reason << "#{'~' * (parser.failure_column - 1)}^"
  end
  reason.join("\n")
end

Instance Method Details

#breaker(s, col = 69) ⇒ Object

primitively break down lines so they fit on a teletype



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/abnftt/abnf-writer.rb', line 90

def breaker(s, col = 69)
  ret = ""
  s.each_line do |*l|
    while l[-1].size > col
      breakpoint = l[-1][0...col].rindex(' ')
      break unless breakpoint && breakpoint > 4
      while (partial = l[-1][0...breakpoint]).count('"').odd?
        break1 = partial.rindex('"')
        breakpoint = l[-1][0...break1].rindex(' ')
        break unless breakpoint && breakpoint > 4
      end
      l[-1..-1] = [
        l[-1][0...breakpoint],
        "    " << l[-1][breakpoint+1..-1]
      ]
    end
    ret << l.join("\n")
  end
  ret
end

#expand_op_into(s, op, out = [op]) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/abnftt/abnf-flattener.rb', line 4

def expand_op_into(s, op, out = [op])
  s.each do |el|
    case el
    in [^op, *inner]
      expand_op_into(inner, op, out)
    else
      out << flatten_ops_1(el)
    end
  end
  out
end

#flatten_opsObject



27
28
29
30
31
# File 'lib/abnftt/abnf-flattener.rb', line 27

def flatten_ops
  rules.each do |name, prod|
    rules[name] = flatten_ops_1(prod)
  end
end

#flatten_ops_1(prod) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/abnftt/abnf-flattener.rb', line 15

def flatten_ops_1(prod)
  visit(prod) do |here|
      case here
      in ["seq", *rest]
        [true, expand_op_into(rest, "seq")]
      in ["alt", *rest]
        [true, expand_op_into(rest, "alt")]
      else
        false
      end
  end
end

#generateObject



85
86
87
# File 'lib/abnftt.rb', line 85

def generate
  generate1(rules.first.first)
end

#generate1(what) ⇒ Object



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
# File 'lib/abnftt.rb', line 89

def generate1(what)
  case what
  when String
    expansion = rules[what]
    fail "can't find rules #{what}" unless expansion
    generate1(expansion)
  when Array
    op, *args = what
    case op
    when "seq"
      args.map {|arg| generate1(arg)}.join
    when "alt"
      generate1(args.sample)
    when "rep"
      l, h, x, rest = args
      fail rest if rest
      h = l+3 if h == true
      n = rand(h-l+1)+l
      (0...n).map { generate1(x) }.join
    when "ci"
      s, rest = args
      fail rest if rest
      s.chars.map{|x|[x.upcase, x.downcase].sample}.join
    when "cs"
      s, rest = args
      fail rest if rest
      s
    when "char-range"
      l, r = args
      fail rest if rest
      (rand(r.ord-l.ord+1)+l.ord).chr(Encoding::UTF_8)
    when "prose" # ["prose", text]
      fail "prose not implemented #{what.inspect}"
    when "im"
      warn "abnftt-style inline module ignored #{what.inspect}"
      ''
    else
      fail [op, args].inspect
    end
  else
    fail
  end
end

#prec_check(inner, targetprec, prec) ⇒ Object

precedence: 1: / alt -> (type1) 2: »« seq 4: atomic



19
20
21
22
23
24
25
# File 'lib/abnftt/abnf-writer.rb', line 19

def prec_check(inner, targetprec, prec)
  if targetprec >= prec
    "(#{inner})"
  else
    inner
  end
end

#squash_edn_levels(**options) ⇒ Object



59
60
61
62
63
# File 'lib/abnftt/abnf-squasher.rb', line 59

def squash_edn_levels(**options)
  rules.each do |name, prod|
    rules[name] = squash_edn_levels_1(prod, **options)
  end
end

#squash_edn_levels_1(prod, **options) ⇒ Object



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
# File 'lib/abnftt/abnf-squasher.rb', line 27

def squash_edn_levels_1(prod, **options)
  f1 = visit(prod) do |here|
    case here
    in ["char-range", c1, c2]
      lit = UNESCAPED_SQSTR_RANGES.map { |u1, u2|
        overlap(here, u1, u2) }.compact
      esc = ESCAPED_SQSTR_MAPPINGS.map {|cv, ev|
        if cv >= c1 && cv <= c2
          ["seq", ["char-range", "\\", "\\"], ["char-range", ev, ev]]
        end
      }.compact
      u_escapes = []
      if options[:ascii]
        do_ranges_outside(here, " ", "~") do |l, r|
          u_escapes << alt_ranges_legacy(l, r) # old
          u_escapes << alt_ranges_modern(l, r) # new
        end
      else
        u_escapes << alt_ranges_legacy(c1.ord, c2.ord) # old
        u_escapes << alt_ranges_modern(c1.ord, c2.ord) # new
      end
      oldnew = ["seq",
                ["cs", "\\u"],
                wrap_flat("alt", u_escapes) ] if u_escapes != []
      [true, wrap_flat("alt", [*lit, *esc, oldnew].compact.sort)]
    else
      false
    end
  end
  flatten_ops_1(f1)
end

#stringify(s) ⇒ Object

return [precedence ((2 if seq needed)), string]



5
6
7
8
# File 'lib/abnftt/abnf-writer.rb', line 5

def stringify(s)
  fail "Can't stringify #{s.inspect} yet" unless s =~ /\A[ !#-~]*\z/
  %{"#{s}"}
end

#to_sObject



85
86
87
# File 'lib/abnftt/abnf-writer.rb', line 85

def to_s
  rules.map {|k, v| write_rule(k, v) }.join("\n").sub(/.\z/) {$& << "\n"}
end

#to_treetop(modname) ⇒ Object



134
135
136
137
138
139
140
141
# File 'lib/abnftt.rb', line 134

def to_treetop(modname)
  <<~EOS
  # Encoding: UTF-8
  grammar #{modname}
  #{rules.map {|k, v| to_treetop0(k, v)}.join}
  end
EOS
end

#to_treetop0(k, v) ⇒ Object



142
143
144
145
146
147
148
# File 'lib/abnftt.rb', line 142

def to_treetop0(k, v)
  <<~EOS
  rule #{to_treetop1(k)}
  #{to_treetop1(v)}
  end
EOS
end

#to_treetop1(ast) ⇒ Object



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
# File 'lib/abnftt.rb', line 154

def to_treetop1(ast)
  case ast
  when String
    FIXUP_NAMES[ast].gsub("-", "_")
  when Array
    case ast[0]
    when "alt" # ["alt", *a]
      "(#{ast[1..-1].map {|x| to_treetop1(x)}.join(" / ")})"
    when "seq" # ["seq", *a]
      "(#{ast[1..-1].map {|x| to_treetop1(x)}.join(" ")})"
    when "rep" # ["rep", s, e, a]
      t = to_treetop1(ast[3]) || "@@@"
      if ast[3][0] == "rep"
        t = "(#{t})"
      end
      case [ast[1], ast[2]]
      when [0, 1]
        t + "?"
      when [0, true]
        t + "*"
      when [1, true]
        t + "+"
      else
        t + " #{ast[1]}..#{ast[2] == true ? '' : ast[2]}"
      end
    when "prose" # ["prose", text]
      fail "prose not implemented #{ast.inspect}"
    when "ci" # ["ci", text]
      s = ast[1]
      if s =~ /\A[^A-Za-z]*\z/
        s.inspect
      else
        s.inspect << "i"        # could do this always, but reduce noise
      end
    when "cs" # ["cs", text]
      ast[1].inspect
    when "char-range" # ["char-range", c1, c2]
      c1 = Regexp.quote(ast[1])
      c2 = Regexp.quote(ast[2])
      "[#{c1}-#{c2}]"           # XXX does that always work
    when "im" # ["im", a, text]
      to_treetop1(ast[1]) + " " + ast[2]
    else
      fail "to_treetop(#{ast.inspect})"
    end
  else
    fail "to_treetop(#{ast.inspect})"
  end
end

#validate(s) ⇒ Object



207
208
209
210
211
212
213
# File 'lib/abnftt.rb', line 207

def validate(s)
  @parser ||= Treetop.load_from_string(to_treetop("ABNF_Mod" << (@@gensym += 1).to_s))
  parser_instance ||= @parser.new
  unless result1 = parser_instance.parse(s)
    fail self.class.reason(parser_instance, s)
  end
end

#visit(prod, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/abnftt/abnf-visitor.rb', line 7

def visit(prod, &block)
  done, ret = block.call(prod, &block)
  if done
    return ret
  end

  case prod
  in ["alt", *prods]
    ["alt", *visit_all(prods, &block)]
  in ["tadd", *prods]
    ["tadd", *visit_all(prods, &block)]
  in ["seq", *prods]
    ["seq", *visit_all(prods, &block)]
  in ["rep", s, e, prod]
    ["rep", s, e, visit(prod, &block)]
  else
    prod
  end
end

#visit_all(prod_array, &block) ⇒ Object



4
5
6
# File 'lib/abnftt/abnf-visitor.rb', line 4

def visit_all(prod_array, &block)
  prod_array.map {|prod| visit(prod, &block)}
end

#write_lhs(k) ⇒ Object



10
11
12
# File 'lib/abnftt/abnf-writer.rb', line 10

def write_lhs(k)
    k
end

#write_rhs(v, targetprec = 0) ⇒ Object



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
# File 'lib/abnftt/abnf-writer.rb', line 27

def write_rhs(v, targetprec = 0)
  prec, ret =
  case v
  in String                   # this should really be ["name", id]
    [4, v]
  in ["name", id]
    [4, id]
  in ["alt" | "tadd", *types]
    [1, types.map{write_rhs(_1, 1)}.join(" / ")]
  in ["seq", *groups]
    case groups.size
    when 0; [4, ""]           # XXX
    else
      [2, "#{groups.map{write_rhs(_1, 2)}.join(" ")}"]
    end
  in ["ci", s]
    [4, stringify(s)]
  in ["cs", s]
    if s =~ /\A[^A-Za-z]*\z/
      [4, stringify(s)]
    else
      [4, "%s" << stringify(s)]  # reduce noise if no alphabetics
    end
  in ["char-range", c1, c2]
    nc1 = "%02x" % c1.ord

    nc2 = "%02x" % c2.ord
    nc2add = "-#{nc2}" if nc2 != nc1
    [4, "%x#{nc1}#{nc2add}"]
  in ["rep", s, e, group]
    if s == 0 && e == 1
      [4, "[#{write_rhs(group)}]"]
    else
      occur = case [s, e]
              in [1, 1];    ""
              in [0, true]; "*"
              in [n, ^n]; n.to_s
              else
                "#{s}*#{e != true ? e : ""}"
              end
      [4, "#{occur}#{write_rhs(group, 4)}"]
    end
  else
    fail [:WRITE_NOMATCH, v].inspect
  end
  prec_check(ret, targetprec, prec)
end

#write_rule(k, v) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/abnftt/abnf-writer.rb', line 75

def write_rule(k, v)
    case v
    in ["tadd", *_rest]
      assign = "=/"
    else
      assign = "="
    end
    "#{write_lhs(k)} #{assign} #{write_rhs(v, 0)}"
end