Skip to content

Commit

Permalink
Implement {Match,Cursor}.at-{key,pos}
Browse files Browse the repository at this point in the history
  • Loading branch information
sorear committed Sep 13, 2010
1 parent ba15f79 commit bedd19a
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/Cursor.cs
Expand Up @@ -313,6 +313,42 @@ public Cursor(IP6 proto, string text)
return new Cursor(klass, xact, backing, backing_ca, npos);
}

// TODO: keep variables around so { $<foo> = 1 } will work
public Variable GetKey(string str) {
PSN<string[]> cn_it = capnames;
PSN<Cursor> cr_it = captures;
VarDeque caps = new VarDeque();
bool list = false;

while (cr_it != null) {
foreach (string cn in cn_it.obj) {
if (cn == str)
goto yes;
}
goto no;
yes:
if (cr_it.obj == null) {
list = true;
} else {
caps.Unshift(Kernel.NewRWScalar(cr_it.obj));
}
no:
cr_it = cr_it.next;
cn_it = cn_it.next;
}

if (list) {
DynObject l = new DynObject(RxFrame.ListMO);
l.SetSlot("flat", Kernel.NewROScalar(Kernel.AnyP));
l.SetSlot("items", caps);
l.SetSlot("rest", new VarDeque());
return Kernel.NewRWListVar(l);
} else {
return caps.Count() != 0 ? caps[0] :
Kernel.NewRWScalar(Kernel.AnyP);
}
}

public Variable SimpleWS() {
int l = backing_ca.Length;
int p = pos;
Expand Down
1 change: 1 addition & 0 deletions src/CodeGen.pm
Expand Up @@ -90,6 +90,7 @@ use 5.010;
{ At => [m => 'Cursor'],
pos => [f => 'Int32'],
from => [f => 'Int32'],
GetKey => [m => 'Variable'],
backing => [f => 'String'],
SimpleWS => [m => 'Variable'] },
'Lexer' =>
Expand Down
27 changes: 27 additions & 0 deletions test2.pl
Expand Up @@ -18,4 +18,31 @@
}
}

use MONKEY_TYPING;
augment class Match {
method at-key($k) { Q:CgOp {
(rawcall (cast Cursor (@ {self})) GetKey (unbox String (@ {$k.Str})))
} }
method at-pos($i) { self.at-key($i) }
}
augment class Cursor {
method at-key($k) { Q:CgOp {
(rawcall (cast Cursor (@ {self})) GetKey (unbox String (@ {$k.Str})))
} }
method at-pos($i) { self.at-key($i) }
}

{
my $ma = (grammar {
regex TOP { <foo> <bar> }
regex foo { \d+ }
regex bar { \w+ }
}).parse("123abc");
ok $ma<foo> ~~ Match, "<foo> sub is a Match";
is $ma<foo>, "123", "<foo> sub got 123";
ok $ma<bar> ~~ Match, "<bar> sub is a Match";
is $ma<bar>, "abc", "<bar> sub got 123";
ok !$ma<quux>, "no <quux> sub";
}

done-testing;

0 comments on commit bedd19a

Please sign in to comment.