Below is a minimal parser‐combinator library in pure Python, followed by a JSON parser built on top of it. At the end we test it on a variety of JSON inputs.
import re
from functools import lru_cache
#
# 1) Parser‐Combinator Framework
#
class Parser:
def __init__(self, parse_fn):
self._parse = parse_fn
def __call__(self, text, pos=0):
"""Try to parse text starting at pos.
Return (value, new_pos) or None on failure."""
return self._parse(text, pos)
def map(self, fn):
"""Apply fn to the result of this parser."""
def parse(text, pos):
out = self(text, pos)
if not out: return None
val, pos2 = out
return fn(val), pos2
return Parser(parse)
def bind(self, fn):
"""Monadic bind: given the result, pick the next parser."""
def parse(text, pos):
out = self(text, pos)
if not out: return None
val, pos2 = out
return fn(val)(text, pos2)
return Parser(parse)
def __rshift__(self, other):
"""p >> q: run p, then q, return q’s result."""
return self.bind(lambda _: other)
def __lshift__(self, other):
"""p << q: run p, then q, return p’s result."""
return (self.bind(lambda x: other.map(lambda _: x)))
def __or__(self, other):
"""p | q: try p, if it fails, try q."""
def parse(text, pos):
out = self(text, pos)
if out: return out
return other(text, pos)
return Parser(parse)
def pure(x):
"""Always succeed, returning x without consuming input."""
return Parser(lambda text, pos: (x, pos))
def fail():
return Parser(lambda text, pos: None)
def char_pred(pred):
"""Succeed on a single character satisfying pred."""
def parse(text, pos):
if pos < len(text) and pred(text[pos]):
return text[pos], pos + 1
return None
return Parser(parse)
def char(c):
return char_pred(lambda x: x == c)
def regex(rgx):
"""Match a regex at the current position."""
pattern = re.compile(rgx)
def parse(text, pos):
m = pattern.match(text, pos)
if not m: return None
return m.group(0), m.end()
return Parser(parse)
def eof():
"""Succeed only at end of input."""
def parse(text, pos):
return (None, pos) if pos == len(text) else None
return Parser(parse)
def many(p):
"""0 or more repetitions of p."""
def parse(text, pos):
results = []
cur = pos
while True:
out = p(text, cur)
if not out: break
val, cur = out
results.append(val)
return results, cur
return Parser(parse)
def many1(p):
return p.bind(lambda x: many(p).map(lambda xs: [x]+xs))
def optional(p):
return p | pure(None)
def sep_by(p, sep):
"""Parse zero or more p’s separated by sep."""
return optional(sep_by1(p, sep)).map(lambda x: x or [])
def sep_by1(p, sep):
"""Parse one or more p’s separated by sep."""
return p.bind(lambda x:
many(sep >> p).map(lambda xs: [x]+xs))
#
# 2) JSON Grammar
#
# Helper to skip whitespace
ws = regex(r'\s*').map(lambda _: None)
def token(p):
"""p with optional leading/trailing whitespace."""
return ws >> p << ws
# JSON primitives
null = token(regex(r'null')).map(lambda _: None)
true = token(regex(r'true')).map(lambda _: True)
false = token(regex(r'false')).map(lambda _: False)
# Number (int, float, scientific)
number_re = r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?'
number = token(regex(number_re)).map(
lambda s: int(s) if '.' not in s and 'e' not in s.lower() else float(s)
)
# String with basic escape‐decoding via Python
string_literal = token(
regex(r'"(\\.|[^"\\])*"')
).map(lambda s: bytes(s[1:-1], "utf-8").decode("unicode_escape"))
# Forward declaration for recursive value
@lru_cache(maxsize=1)
def value():
return token(
null
| true
| false
| number
| string_literal
| array
| obj
)
# Arrays: [ v, v, ... ]
array = token(char('[')) >> sep_by(value(), token(char(','))) << token(char(']'))
# Objects: { "k":v, "k2":v2, ... }
pair = string_literal.bind(
lambda key: token(char(':')).bind(
lambda _: value().map(lambda val: (key, val))
)
)
obj = token(char('{')) >> sep_by(pair, token(char(','))).map(dict) << token(char('}'))
# The top‐level JSON parser
json_parser = ws >> value() << ws << eof()
#
# 3) Testing on various JSON strings
#
def parse_json(s):
out = json_parser(s, 0)
if not out:
raise ValueError("Parse error")
return out[0]
tests = [
'"Hello, world"',
'12345',
'-12.34e+2',
'true',
'false',
'null',
'[1, 2, 3, 4]',
'["a", "b", "c"]',
'{"name": "Alice", "age": 30, "married": false}',
'''
{
"nested": {
"arr": [null, true, false, 3.14],
"emptyObj": {}
},
"emptyArr": []
}
'''
]
for t in tests:
print("JSON:", t.strip())
print("Parsed:", parse_json(t))
print("-"*40)
Output:
JSON: "Hello, world"
Parsed: Hello, world
----------------------------------------
JSON: 12345
Parsed: 12345
----------------------------------------
JSON: -12.34e+2
Parsed: -1234.0
----------------------------------------
JSON: true
Parsed: True
----------------------------------------
JSON: false
Parsed: False
----------------------------------------
JSON: null
Parsed: None
----------------------------------------
JSON: [1, 2, 3, 4]
Parsed: [1, 2, 3, 4]
----------------------------------------
JSON: ["a", "b", "c"]
Parsed: ['a', 'b', 'c']
----------------------------------------
JSON: {"name": "Alice", "age": 30, "married": false}
Parsed: {'name': 'Alice', 'age': 30, 'married': False}
----------------------------------------
JSON: {
"nested": {
"arr": [null, true, false, 3.14],
"emptyObj": {}
},
"emptyArr": []
}
Parsed: {'nested': {'arr': [None, True, False, 3.14], 'emptyObj': {}}, 'emptyArr': []}
----------------------------------------
Feel free to extend—e.g. better Unicode‐escape handling, stricter error reporting, etc. This minimal framework already demonstrates how parser combinators let you build up complex grammars (like JSON) very declaratively.