Pattern Matching
Patterns can match against streams of any objects. There are many primitive pattern expressions that can be combined together to form more complex patterns.
Patterns can be declared using the
pattern keyword and matching is invoked using the
match and
with keywords.
var p = pattern any+ // matches one or more of anything
var m = match "xyz" with p // match the characters in the provided string using the pattern p
print(m) // xyz
Basic Patterns
| Name | Syntax |
| Character | 'x' |
| String | "xyz" |
| Number | 7 or 7.11 or 0xFF |
| Value Range | "a".."z" or 0..100 |
| Bool | true or false |
| Array | [ x y z ] |
| Object | x { y = z } |
| Any | any |
| Default | default |
| Fail | fail |
| Reference | x or self.x or super.x |
| Variable | x:X |
- The any keyword matches exactly one of anything in the stream, if the stream is empty it returns fail.
- The default pattern always matches, even if the stream is empty, and consumes nothing from the stream. It is especially useful for the last pattern in an Or clause.
Logical Patterns
| Name | Syntax |
| And | x y z |
| Or | x | y | z |
| Not | !x |
| Group | ( x ( y z ) ) |
| Production | x -> y |
Quantity Patterns
| Name | Syntax |
| One or More | x+ |
| Zero or More | x* |
| Zero or One | x? |
| Exactly N | x#n |
| Quantity Range | x#n..m |
Rules and Inheritance
Patterns can be set onto an object and standard inheritance rules used to allow sub grammars to override and extend common behavior.
var g = {
main = pattern (self.identifier ' '+)*,
identifier = pattern 'a'..'z' | 'A'..'Z'
}
var g2 = g {
identifier = pattern super.identifier | '0'..9'
}
var m = match "abc xyz123" with g2
References
- Ometa, Alessandro Warth - http://www.tinlizzie.org/ometa
- Experimenting with Programming Languages, Chapter 1.1, Alessandro Warth - http://www.vpri.org/pdf/tr2008003_experimenting.pdf