Parsey
Swift Parser Combinator Framework
In addition to simple combinators, Parsey supports source location/range tracking,
backtracking prevention, and custom error messages.
Features
-
Combinator interface
|
,~~
,~~>
,<~~
,^^
combinator operators
-
Lexer primitives:
Lexer.whitespace
,Lexer.signedInteger
, ...
-
Regex-like combinators:
- Postfix
.+
for.many()
.- Example:
let arrayLiteral = "[" ~~> expression.+ <~~ "]"
- Example:
- Postfix
.*
for.manyOrNone()
.- Example:
let classDef = (attribute | method).*
- Example:
- Postfix
.?
for.optional()
.- Example:
let declaration = "let" ~~> id ~~ (":" ~~> type).? ~~ ("=" ~~> expression)
- Example:
- Postfix
+
for.manyConcatenated()
.- Example:
let skippedSpaces = (Lexer.space | Lexer.tab)+
- Example:
- Infix
+
for.concatenatingResult(with:)
.- Example:
let type = Lexer.upperLetter + Lexer.letter*
- Example:
Lexer.regex(_:)
for directly applying regular expressions.- Example:
let id = Lexer.regex("[a-zA-Z][a-zA-Z0-9]*")
- Example:
- Postfix
-
Backtracking prevention
.!
postfix operator or.nonbacktracking()
-
Parser tagging for error messages
<!--
operator or.tagged(_:)
-
Rich error messages with source location
- For example:
Parse failure at 2:4 ---- (+ %% 1 -20) 2 3) ^~~~~~~~~~~~~~ Expecting an expression, but found "%"
-
Source range tracking
^^^
operator or.mapParse(_:)
- For example, S-expression
\n(+ \n\n(+ +1 -20) 2 3)
gets parsed to
the following range-tracked AST:
Expr:(2:1..<4:16):[ ID:(2:2..<2:3):+, Expr:(4:1..<4:11):[ ID:(4:2..<4:3):+, Int:(4:4..<4:6):1, Int:(4:7..<4:10):-20], Int:(4:12..<4:13):2, Int:(4:14..<4:15):3]
Requirements
-
Swift 3
-
Any operating system
Package
To use it in your Swift project, add the following dependency to your
Swift package description file.
⚙ Examples
0️⃣ An LLVM Compiler Frontend written in Swift using Parsey
1️⃣ Parse Left-associative Infix Expressions with Operator Precedence
2️⃣ Parse S-Expressions
3️⃣ Parse S-Expressions with Source Range Tracking
Dependency
License
MIT License