Skip to content

Commit e1eaa4c

Browse files
committed
add Perl6::TypeGraph, wihch reads type-graph.txt and constructs a -- you have already guessed it -- type graph
1 parent 28f5a6c commit e1eaa4c

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

lib/Perl6/TypeGraph.pm

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
class Perl6::TypeGraph {
2+
has %.types;
3+
class Type {
4+
has Str $.name handles <Str>;
5+
has @.super;
6+
has @.roles;
7+
has $.packagetype is rw = 'class';
8+
}
9+
my grammar Decl {
10+
token ident { <.alpha> \w* }
11+
token apostrophe { <[ ' \- ]> }
12+
token identifier { <.ident> [ <.apostrophe> <.ident> ]* }
13+
token longname { <identifier>+ % '::' }
14+
token scoped { 'my' | 'our' | 'has' }
15+
token package { pmclass | class | module | package |role | enum }
16+
token rolesig { '[' <-[ \[\] ]>* ']' } # TODO might need to be become better
17+
rule inherits { 'is' <longname> }
18+
rule roles { 'does' <longname><rolesig>? }
19+
20+
rule TOP {
21+
^
22+
<scoped>?
23+
<package>
24+
<type=longname><rolesig>?
25+
:my $*CURRENT_TYPE;
26+
{ $*CURRENT_TYPE = $<type>.ast }
27+
[ <inherits> | <roles>]*
28+
$
29+
}
30+
}
31+
32+
method new-from-file($fn) {
33+
my $n = self.bless(*);
34+
$n.parse-from-file($fn);
35+
$n;
36+
}
37+
38+
method parse-from-file($fn) {
39+
my $f = open $fn;
40+
my $get-type = -> Str $name {
41+
%.types{$name} //= Type.new(:$name);
42+
};
43+
my class Actions {
44+
method longname($/) {
45+
make $get-type($/.Str);
46+
}
47+
method inherits($/) {
48+
$*CURRENT_TYPE.super.push: $<longname>.ast;
49+
}
50+
method roles($/) {
51+
$*CURRENT_TYPE.roles.push: $<longname>.ast;
52+
}
53+
}
54+
for $f.lines -> $l {
55+
next if $l ~~ / ^ '#' /;
56+
next if $l ~~ / ^ \s* $ /;
57+
my $m = Decl.parse($l, :actions(Actions.new));
58+
my $t = $m<type>.ast;
59+
$t.packagetype = ~$m<package>;
60+
}
61+
}
62+
}
63+
64+
# vim: ft=perl6

t/typegraph.t

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
use v6;
2+
use Test;
3+
use lib 'lib';
4+
use Perl6::TypeGraph;
5+
6+
my $t = Perl6::TypeGraph.new-from-file('type-graph.txt');
7+
ok $t, 'Could parse the file';
8+
ok $t.types<Array>, 'has type Array';
9+
ok $t.types<Array>.super.any eq 'List',
10+
'Array has List as a superclass';
11+
ok $t.types<List>.roles.any eq 'Positional',
12+
'List does positional';
13+
done;

0 commit comments

Comments
 (0)