File: graphviz.rb

package info (click to toggle)
ruby-parslet 1.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 908 kB
  • ctags: 473
  • sloc: ruby: 5,220; makefile: 2
file content (97 lines) | stat: -rw-r--r-- 1,987 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
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
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

# Paints a graphviz graph of your parser.

begin
  require 'ruby-graphviz'
rescue LoadError
  puts "Please install the 'ruby-graphviz' gem first."
  fail
end

require 'set'
require 'parslet/atoms/visitor'

module Parslet
  class GraphvizVisitor
    def initialize g
      @graph = g
      @known_links = Set.new
      @visited = Set.new
    end

    attr_reader :parent

    def visit_parser(root)
      recurse root, node('parser')
    end
    def visit_entity(name, block)
      s = node(name)

      downwards s

      return if @visited.include?(name)
      @visited << name

      recurse block.call, s
    end
    def visit_named(name, atom)
      recurse atom, parent
    end
    def visit_repetition(tag, min, max, atom)
      recurse atom, parent
    end
    def visit_alternative(alternatives)
      p = parent
      alternatives.each do |atom|
        recurse atom, p
      end
    end
    def visit_sequence(sequence)
      p = parent
      sequence.each do |atom|
        recurse atom, p
      end
    end
    def visit_lookahead(positive, atom)
      recurse atom, parent
    end
    def visit_re(regexp)
      # downwards node(regexp.object_id, label: escape("re(#{regexp.inspect})"))
    end
    def visit_str(str)
      # downwards node(str.object_id, label: escape("#{str.inspect}"))
    end

    def escape str
      str.gsub('"', "'")
    end
    def node name, opts={}
      @graph.add_nodes name.to_s, opts
    end
    def downwards child
      if @parent && !@known_links.include?([@parent, child])
        @graph.add_edges(@parent, child)
        @known_links << [@parent, child]
      end
    end
    def recurse node, current
      @parent = current
      node.accept(self)
    end
  end

  module Graphable
    def graph opts
      g = GraphViz.new(:G, type: :digraph)
      visitor = GraphvizVisitor.new(g)

      new.accept(visitor)

      g.output opts
    end
  end

  class Parser # reopen for introducing the .graph method
    extend Graphable
  end
end