Class: Abnf::Renderer

Inherits:
Object
  • Object
show all
Defined in:
../lib/abnf_renderer.rb

Overview

Abnf::Renderer renders the ABNF syntax tree from the Mapper::Grammar.

Class Method Summary (collapse)

Class Method Details

+ (Object) canonical(grammar)

If the grammar provided is the valid Mapper::Grammar instance, Renderer.canonical method returns the formatted ABNF text.



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

def Renderer.canonical grammar
  start = grammar.start_symbol
  res = ";start symbol is <#{start}>\n"
  symbols = grammar.symbols
  symbols.delete start
  symbols.unshift start
  symbols.each do |name|
    rule = grammar.fetch name
    rule.each do |alt|
      res += ( name + ' =' )
      res += '/' if alt != rule.first
      alt.each do |token|
        res += ' '
        case token.type
        when :literal
          res += ('"' + token.data.gsub(/\n/,'\\n') + '"')
        when :symbol
          res += token.data
        else
          raise "unsupported token.type=#{token.type}"
        end
      end
      res += "\n"
    end
    res += "\n"
  end
  res
end