-
Notifications
You must be signed in to change notification settings - Fork 111
/
pgx2dot.pl
executable file
·151 lines (119 loc) · 2.82 KB
/
pgx2dot.pl
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env perl
use v5.10.1;
use strict;
use warnings;
use Getopt::Std qw( getopts );
my %opts;
getopts("t", \%opts)
or die "usage: $0 [-t] <infile>\n";
my $trim = $opts{t};
my $infile = shift or die "no input file specified.\n";
open my $in, $infile
or die "cannot open $infile for reading: $!\n";
my $lang;
my $ver;
my $rule_name;
my $rule_def;
my @rules;
while (<$in>) {
next if /^\s*\#/ || /^\s*$/;
if (/^ \s* \%grammar \s+ (\S+)/xsm) {
$lang = $1;
next;
}
if (/^ \s* \%version \s+ (\S+)/xsm) {
$ver = $1;
next;
}
if (/^ \s* ([a-z][-\w]* \s*) :/xsmi) {
s/ \s+ \# \s+ .* //x;
if ($rule_name) {
#$rule_def =~ s/\n+\z//s;
push @rules, [$rule_name, $rule_def];
undef $rule_def;
undef $rule_name;
}
$rule_name = $1;
$rule_def = $_;
next;
}
if (defined $rule_name) {
s/ \s+ \# \s+ .* //x;
$rule_def .= $_;
next;
}
if (/^ \s* unit \s+ grammar \s+ \w[-\w]* (?: :: \w[-\w]*)* \s* ; \s* $/xsmi) {
# ignore the unit grammar declaration in fanlang grammar module files.
next;
}
die "unexpected line: $_";
}
close $in;
my $title;
if (!defined $lang) {
($lang = $infile) =~ s/\.\w+$//;
}
$title = "Grammar for <b>$lang</b>";
if (defined $ver) {
$title .= " v$ver";
}
my $node_shape;
if ($trim) {
$node_shape = "ellipse";
} else {
$node_shape = "box";
}
print <<_EOC_;
digraph grammar_spec {
graph [fontname="helvetica"];
labelloc="t";
label=<$title>;
node [shape=$node_shape, fontname="helvetica"];
edge [color=red, fontname="helvetica"];
_EOC_
my %rule_ids;
for my $rule (@rules) {
my ($name, $def) = @$rule;
my $id = gen_id($name);
$rule_ids{$id} = 1;
my $label;
if ($trim) {
$label = "<b>$name</b>";
} else {
$label = $def;
if ($label !~ /\n.*?\n/s) {
$label =~ s/\s* : \s*/:\n /xgs;
}
$label =~ s/\&/\&/g;
$label =~ s/ /\ /g;
$label =~ s/</\</g;
$label =~ s/>/\>/g;
$label =~ s/"/\"/g;
$label =~ s/\A \s+ //;
$label =~ s{^ ([a-z][-\w]*) :}{<b>$1</b> :}x;
$label =~ s{\n}{<br align="left"/>}g;
}
say " $id [label=<$label>];"
}
say "";
for my $rule (@rules) {
my ($name, $def) = @$rule;
my $id = gen_id($name);
my %edges;
while ($def =~ /\b <? ([a-z][-\w]*) >? \b/gxsm) {
my $dep_id = gen_id($1);
if ($rule_ids{$dep_id} && $dep_id ne $id) {
my $key = "$id,$dep_id";
if (!$edges{$key}) {
say " $id -> $dep_id";
$edges{$key} = 1;
}
}
}
}
sub gen_id {
my $s = shift;
$s =~ s/\W/_/g;
$s;
}
say "}";