Skip to content

Commit

Permalink
Merge pull request #57 from davidcairns/dc-postfix-repetition-sugar
Browse files Browse the repository at this point in the history
Dc postfix repetition sugar
  • Loading branch information
robrix committed Feb 5, 2015
2 parents 53e28ba + 7ac0c3e commit 7df721f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
10 changes: 10 additions & 0 deletions Madness/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ public postfix func * <T> (parser: Parser<T>.Function) -> Parser<[T]>.Function {
return repeat(parser)
}

/// Creates a parser from `string`, and parses it 0 or more times.
public postfix func * (string: String) -> Parser<[String]>.Function {
return repeat(%(string))
}

/// Parses `parser` 0 or more times and drops its parse trees.
public postfix func * (parser: Parser<()>.Function) -> Parser<()>.Function {
return repeat(parser) --> const(())
Expand All @@ -112,6 +117,11 @@ public postfix func + <T> (parser: Parser<T>.Function) -> Parser<[T]>.Function {
return repeat(parser, 1..<Int.max)
}

/// Creates a parser from `string`, and parses it 1 or more times.
public postfix func + (string: String) -> Parser<[String]>.Function {
return repeat(%(string), 1..<Int.max)
}

/// Parses `parser` 0 or more times and drops its parse trees.
public postfix func + (parser: Parser<()>.Function) -> Parser<()>.Function {
return repeat(parser, 1..<Int.max) --> const(())
Expand Down
46 changes: 45 additions & 1 deletion MadnessTests/ParserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,51 @@ final class ParserTests: XCTestCase {
func testMToNRepetitionMatchesUpToN() {
assertEqual(mToN("xxxx")?.1, "x")
}



// MARK: Repetition shorthand
let zeroOrMoreSimple = "x"*

func testZeroOrMoreSimpleRepetitionAcceptsTheEmptyString() {
assertNotNil(zeroOrMoreSimple(""))
}

func testZeroOrMoreSimpleRepetitionAcceptsUnmatchedStrings() {
assertNotNil(zeroOrMoreSimple("y"))
}

func testZeroOrMoreSimpleRepetitionDoesNotAdvanceWithUnmatchedStrings() {
assertEqual(zeroOrMoreSimple("y")?.1, "y")
}

func testZeroOrMoreSimpleRepetitionParsesUnmatchedStringsAsEmptyArrays() {
assertEqual(zeroOrMoreSimple("y")?.0, [])
}

func testZeroOrMoreSimpleRepetitionParsesAMatchedString() {
assertEqual(zeroOrMoreSimple("x")?.0, ["x"])
}

func testZeroOrMoreSimpleRepetitionParsesMatchedStrings() {
assertEqual(zeroOrMoreSimple("xx")?.0, ["x", "x"])
}


let oneOrMoreSimple = "x"+

func testOneOrMoreSimpleRepetitionRejectsTheEmptyString() {
assertNil(oneOrMoreSimple(""))
}

func testOneOrMoreSimpleRepetitionParsesASingleMatchedString() {
assertEqual(oneOrMoreSimple("x")?.0, ["x"])
}

func testOneOrMoreSimpleRepetitonParsesMultipleMatchedStrings() {
assertEqual(oneOrMoreSimple("xxy")?.0, ["x", "x"])
}



// MARK: Ignoring

Expand Down

0 comments on commit 7df721f

Please sign in to comment.