Sparse is a simple parser-combinator library written in Swift.
Switch branches/tags
Clone or download
Latest commit 6c1ae17 Mar 12, 2018

README.md

✂️ Sparse ✂️

Version License Swift

Sparse is a simple parsing library, written in Swift. It is based on the parser-combinator approach used by Haskell's Parsec. Its focus is on natural language parser creation and descriptive error messages.

Example

Here is a CSV parser:

let quote = character("\"")

let illegalCellCharacters = CharacterSet.newlines.union(CharacterSet(charactersIn: ","))

let cellCharacter = characterNot(in: illegalCellCharacters).named("cell character")
let escapedQuote = quote.skipThen(quote)
let quotedCellCharacter = characterNot("\"").otherwise(escapedQuote).named("quoted cell character")

let quotedCell = many(quotedCellCharacter, boundedBy: quote).asString()
let unquotedCell = many(cellCharacter).asString().map { $0.trimmingCharacters(in: .whitespaces) }

let cell = quotedCell.otherwise(unquotedCell)
let cellSeparator = whitespaces().then(character(",")).then(whitespaces())

let line = many(cell, separator: cellSeparator)
let ending = optional(newline()).then(end())
let csv = many(line, separator: newline()).thenSkip(ending)

Naming the component parsers allows for more descriptive error messages, e.g.:

UNEXPECTED INPUT:
Line 5, Column 11
r5c1, "r5"c2" ,r5c3,r5c4 ,r5c5,r5c6,r5c7,r5c8
~~~~~~~~~~^
EXPECTED:
'"' in escaped quote
',' or whitespace in cell separator
line separator
EOF or newline in file terminator

Installation

Sparse is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "Sparse"

Credit

Sparse is based on Haskell's Parsec and has been developed as a learning exercise.

License

Sparse is available under the MIT license. See the LICENSE file for more info.