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

Grammars and Inheritance

A grammar is a set of patterns set onto an object. Standard inheritance rules can be used to allow sub grammars to reuse override, and extend 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


  1. Ometa, Alessandro Warth -
  2. Experimenting with Programming Languages, Chapter 1.1, Alessandro Warth -

Last edited Nov 24, 2012 at 5:35 PM by justinc, version 6


No comments yet.