Class: EBNF::Writer

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

Constant Summary collapse

LINE_LENGTH =
80

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rules, options = {}) ⇒ Writer

Returns a new instance of Writer.

Parameters:

  • rules (Array<Rule>)
  • options (Hash{Symbol => Object}) (defaults to: {})

Options Hash (options):

  • :format (Symbol)
  • :out (#write) — default: $stdout


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
# File 'lib/ebnf/writer.rb', line 46

def initialize(rules, options = {})
  out = options.fetch(:out, $stdio)
  #fmt = options.fetch(:format, :ebnf)

  # Determine max LHS length
  max_id = rules.max_by {|r| r.id.to_s.length}.id.to_s.length
  max_sym = rules.max_by {|r| r.sym.to_s.length}.sym.to_s.length
  lhs_length = max_sym + 3
  lhs_fmt = "%-#{max_sym}{sym} ::= "
  if max_id > 0
    lhs_fmt = "%-#{max_id+2}{id} " + lhs_fmt
    lhs_length += max_id + 3
  end
  rhs_length = LINE_LENGTH - lhs_length

  # Format each rule, considering the available rhs size
  rules.each do |rule|
    buffer = if rule.pass?
      "%-#{lhs_length-2}s" % "@pass"
    else
      lhs_fmt % {:id => "[#{rule.id}]", :sym => rule.sym}
    end
    formatted_expr = format(rule.expr)
    if formatted_expr.length > rhs_length
      buffer << format(rule.expr, ("\n" + " " * lhs_length))
    else
      buffer << formatted_expr
    end
    out.puts(buffer)
  end
end

Class Method Details

Format rules to $stdout

Parameters:

  • rules (Array<Rule>)

Returns:

  • (Object)


27
28
29
# File 'lib/ebnf/writer.rb', line 27

def self.print(*rules)
  write($stdout, *rules)
end

.string(*rules) ⇒ Object

Format rules to a String

Parameters:

  • rules (Array<Rule>)

Returns:

  • (Object)


15
16
17
18
19
20
# File 'lib/ebnf/writer.rb', line 15

def self.string(*rules)
  require 'stringio' unless defined?(StringIO)
  buf = StringIO.new
  write(buf, *rules)
  buf.string
end

.write(out, *rules) ⇒ Object

Write formatted rules to an IO like object

Parameters:

  • out (Object)
  • rules (Array<Rule>)

Returns:

  • (Object)


37
38
39
# File 'lib/ebnf/writer.rb', line 37

def self.write(out, *rules)
  Writer.new(rules, out: out)
end