From 0628142d8b5c2f50889620b0d8752c88d8126d8c Mon Sep 17 00:00:00 2001 From: joshvera Date: Fri, 16 Oct 2015 14:43:23 -0400 Subject: [PATCH] parse members --- prototype/doubt-json/main.swift | 36 ++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/prototype/doubt-json/main.swift b/prototype/doubt-json/main.swift index 344fcc2e4..5b0fbb8e8 100644 --- a/prototype/doubt-json/main.swift +++ b/prototype/doubt-json/main.swift @@ -146,12 +146,34 @@ typealias CharacterParser = Parser.Function let stringBody: StringParser = { $0.map({ String($0) }).joinWithSeparator("") } <^> not(%"\\" <|> %"\"")* let quoted = %"\"" *> stringBody <* %"\"" +let whitespace: CharacterParser = satisfy({ (c: Character) in c == " " })* + +typealias MembersParser = Parser.Function; + +func members(json: JSONParser) -> MembersParser { + let pairs: Parser.Function = (curry(pair) <^> + quoted + <* whitespace + <* %":" + <* whitespace + <*> json) + + let separatedPairs: MembersParser = (%"," *> whitespace *> pairs <* whitespace)* + + let oneOrMore: MembersParser = curry { [$0] + $1 } <^> + pairs + <* whitespace + <*> separatedPairs + + let zero: MembersParser = pure([]) + return oneOrMore + <|> zero +} let json: JSONParser = fix { json in // TODO: Parse backslashed escape characters let string: JSONParser = quoted --> { Cofree($1, .Leaf(.String($2))) } - let whitespace: CharacterParser = satisfy({ (c: Character) in c == " " })* let array: JSONParser = %"[" *> whitespace *> json* <* %"]" --> { Cofree($1, .Indexed($2)) } @@ -159,12 +181,7 @@ let json: JSONParser = fix { json in let dict: JSONParser = %"{" *> whitespace - *> (curry(pair) <^> - quoted - <* whitespace - <* %":" - <* whitespace - <*> json)* + *> members(json) <* whitespace <* %"}" --> { (_, range, values) in @@ -177,11 +194,16 @@ let json: JSONParser = fix { json in return dict <|> array <|> string } +let empty = "{}" +print(parse(json, input: empty)) let dict = "{\"hello\":\"world\"}" print(parse(json, input: dict)) let dictWithSpaces = "{ \"hello\" : \"world\" }" print(parse(json, input: dictWithSpaces)) +let dictWithMembers = "{\"hello\":\"world\",\"sup\":\"cat\"}" +print(parse(json, input: dictWithMembers)) + //if let a = arguments[1].flatMap(JSON.init), b = arguments[2].flatMap(JSON.init) { // let diff = Algorithm(a.term, b.term).evaluate(Cofree.equals(annotation: const(true), leaf: ==)) // if let JSON = NSString(data: diff.JSON(ifPure: { $0.JSON { $0.JSON } }, ifLeaf: { $0.JSON }).serialize(), encoding: NSUTF8StringEncoding) {