Class: EBNF::Writer
- Inherits:
-
Object
- Object
- EBNF::Writer
- Defined in:
- lib/ebnf/writer.rb
Constant Summary collapse
- LINE_LENGTH =
80
Class Method Summary collapse
-
.print(*rules) ⇒ Object
Format rules to $stdout.
-
.string(*rules) ⇒ Object
Format rules to a String.
-
.write(out, *rules) ⇒ Object
Write formatted rules to an IO like object.
Instance Method Summary collapse
-
#initialize(rules, options = {}) ⇒ Writer
constructor
A new instance of Writer.
Constructor Details
#initialize(rules, options = {}) ⇒ Writer
Returns a new instance of Writer.
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, = {}) out = .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
.print(*rules) ⇒ Object
Format rules to $stdout
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
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
37 38 39 |
# File 'lib/ebnf/writer.rb', line 37 def self.write(out, *rules) Writer.new(rules, out: out) end |