Class: CDDL

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

Constant Summary collapse

RULE_OP_TO_CHOICE =
{"/=" => "tcho", "//=" => "gcho"}
@@parser =
CDDLGRAMMARParser.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ast_) ⇒ CDDL

Returns a new instance of CDDL.



26
27
28
29
30
# File 'lib/cddlc.rb', line 26

def initialize(ast_)
  @ast = ast_
  @tree = ast.ast
  @rules = nil                # only fill in if needed
end

Instance Attribute Details

#astObject

Returns the value of attribute ast.



25
26
27
# File 'lib/cddlc.rb', line 25

def ast
  @ast
end

#treeObject

Returns the value of attribute tree.



25
26
27
# File 'lib/cddlc.rb', line 25

def tree
  @tree
end

Class Method Details

.from_cddl(s) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/cddlc.rb', line 17

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

.reason(parser, s) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/cddlc.rb', line 6

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

#rulesObject



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

def rules
  if @rules.nil?              # memoize
    @rules = {}
    fail unless @tree.first == "cddl"
    @tree[1..-1].each do |x|
      op, name, val, rest = x
      cho = RULE_OP_TO_CHOICE[op]
      fail rest if rest
      fail name unless Array === name
      case name[0]
      when "name"
        fail unless name.size == 2
        name = name[1]
      when "gen"
        name = name[1..-1]
      else
        fail name
      end
      @rules[name] =
        if old = @rules[name]
          fail "duplicate rule for name #{name}" unless cho
          if Array === old && old[0] == cho
            old.dup << val
          else
            [cho, old, val]
          end
        else
          val
        end
    end
    # warn "** rules #{rules.inspect}"
  end
  @rules
end