Skip to content

Commit 507cb1b

Browse files
committed
Adds starting point for patterns code
1 parent 625aea6 commit 507cb1b

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

patterns/patterns.grace

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
dialect "minispec"
2+
3+
describe "pattern construction" with {
4+
specify "star" by {
5+
expect (pattern "*".asString) toBe "(star Token)"
6+
}
7+
specify "* ABC *" by {
8+
expect (pattern "*ABC*".asString) toBe "(star Token)(ABC Token)(star Token)"
9+
}
10+
specify "* ABC * XYZ *" by {
11+
expect (pattern "*ABC*XYZ*".asString) toBe "(star Token)(ABC Token)(star Token)(XYZ Token)(star Token)"
12+
}
13+
}
14+
describe "pattern matching behaviour" with {
15+
specify "star matches anything" by {
16+
expect (pattern "*".matches "abc") toBe true
17+
}
18+
specify "star matches nothing" by {
19+
expect (pattern "*".matches "") toBe true
20+
}
21+
specify "star matches a single character" by {
22+
expect (pattern "*".matches "3") toBe true
23+
}
24+
}
25+
26+
class pattern (patternChars:String) {
27+
// returns a pattern object defined by patternChars
28+
// In patternChars, * mathces any sequence of zero or more characters,
29+
// and any other chracters match themselves.
30+
31+
def matchTokens = list.empty
32+
var plainChars := ""
33+
patternChars.do { ch →
34+
if (ch == "*") then {
35+
if (plainChars.isEmpty.not) then {
36+
matchTokens.add(plainToken(plainChars))
37+
plainChars := ""
38+
}
39+
matchTokens.add(starToken)
40+
} else {
41+
plainChars := plainChars ++ ch
42+
}
43+
}
44+
45+
method matches (aString:String) {
46+
tokens (matchTokens) matches (aString) segment 1 to (aString.size)
47+
}
48+
49+
method tokens (toks) matches (aString) segment (start) to (end) is confidential {
50+
if (toks.first).
51+
}
52+
53+
method asString {
54+
matchTokens.fold { sum, each → sum ++ each.asString } startingWith ""
55+
}
56+
57+
}
58+
59+
class starToken {
60+
method matches (another) { true }
61+
method asString { "(star Token)" }
62+
}
63+
64+
class plainToken(tokenChars) {
65+
method matches (another) { another.startsWith(tokenChars) }
66+
method asString { "({tokenChars} Token)" }
67+
}
68+

0 commit comments

Comments
 (0)