Mini Parser
🎯 In Python, parsing a simple value might use json.loads or manual checking:
import json
def parse_primitive(text):
text = text.strip()
if text in ("true", "false"):
return text == "true"
if text == "null":
return None
return int(text) # raises ValueError on bad input
Simple, but error handling is implicit — int() raises, json.loads raises, and callers need to know what exceptions to catch.
This exercise combines everything from the intro track: enums with data, pattern matching, Result for errors, string processing, and character-level parsing. You'll build a parser that handles JSON-style primitives with explicit, type-safe error handling.
Enums as both values and errors
You'll see two enums already defined; one for successfully parsed values, one for error cases:
enum JsonValue {
Bool(bool),
Null,
Number(i64),
}
enum ParseError {
Empty,
Invalid,
Overflow,
}
The return type Result<JsonValue, ParseError> makes every possible outcome explicit. The caller sees exactly what can succeed and what can fail — no hidden exceptions.
Parsing strategy
Instead of regex, you'll handle each value type explicitly:
- Trim whitespace
- Check for keyword literals (
true,false,null) - Parse integers (Rust's
parse::<i64>()handles optional+/-signs) - Use the error's
kind()to distinguish overflow from invalid input
Login to see the full task and start coding.
This is a premium exercise
Log in to unlock the full exercise and start coding.
Login to access this exercise