Parse
Parsing is formatting in reverse: text in, value out. Unlike formatting, it fails all the time, because the text usually comes from a person or a file and may not spell a number at all — "seven", "12abc", or nothing. So every parser in the Format package throws an error that says what was wrong and where:
ParseInt32(text) -> int32 throws ParseError
What can go wrong
ParseError is a variant, and every case but the first carries the byte position where the trouble was found:
| Case | Means |
|---|---|
Empty | there was no text at all |
InvalidCharacter(at) | the byte at at is not part of a number |
Overflow(at) | a well-formed number too large for the type, usually at its end |
Describe names each case. A match on a variant must be exhaustive, so every case gets an arm:
func Describe(error: ParseError) {
match error {
.Empty => PrintLine("empty text"),
.InvalidCharacter(at) => PrintLine("not a digit at byte {}", at),
.Overflow(at) => PrintLine("too large for an int32, at byte {}", at)
}
}
Read handles the error where the call is made, with a try { } catch { } block, as in Catch. Inside the block, ParseInt32 needs no mark of its own; if it throws, the rest of the block is skipped and the catch arm runs with the error bound to error:
func Read(text: char8[..]) {
try {
let value = ParseInt32(text);
PrintLine("[{}] {}", text, value);
} catch {
error => {
Print("[{}] refused, ", text);
Describe(error);
}
}
}
What counts as a number
A sign is understood, and so is a base prefix of the kind {:#x} writes, so "0x1F" reads as 31. Everything else must be digits. The parser does not skip spaces or stop at the first non-digit: the whole text must be a number, or the parser throws an error saying which byte is wrong.
| Text | Result | Why |
|---|---|---|
"42" | 42 | |
"-17" | -17 | a sign |
"0x1F" | 31 | a base prefix, as {:#x} writes |
"" | Empty | nothing to read |
" 42" | InvalidCharacter(0) | a space is not a digit, even at the start |
"12abc" | InvalidCharacter(2) | a is the first byte that is not a digit |
"2147483647" | 2147483647 | the largest int32 |
"2147483648" | Overflow(10) | one more does not fit |
"-2147483648" | -2147483648 | the negative side holds one more |
flowchart LR
t(["`text`"]) --> e{"empty?"}
e -- "yes" --> E["`Empty`"]
e -- "no" --> d{"sign, prefix and digits<br/>— and nothing else?"}
d -- "no" --> I["`InvalidCharacter(at)`"]
d -- "yes" --> f{"fits an `int32`?"}
f -- "no" --> O["`Overflow(at)`"]
f -- "yes" --> S["the `int32` value"]An int32 holds −2147483648 to 2147483647. The negative side holds one more than the positive, so -2147483648 parses even though 2147483648 does not.
A fallback in one expression
Often an error just means "use a default". With try … catch, as in Catch fallback, that takes one expression:
let fallback = try ParseInt32("seven") catch { _ => 0 };
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// Parsing is formatting in reverse: text in, value out. Unlike formatting, it fails all the time,
// because the text usually comes from a person or a file and may not spell a number at all.
// So every parser in the Format package declares the error it throws:
//
// ParseInt32(text) -> int32 throws ParseError
//
// `ParseError` is a variant, and every case says where in the text the trouble was found:
//
// Empty there was no text at all
// InvalidCharacter(at) the byte at `at` is not part of a number
// Overflow(at) a well-formed number too large for an `int32`, usually at its end
import Format::{ ParseError, ParseInt32 };
import Io::{ Print, PrintLine };
func Describe(error: ParseError) {
match error {
.Empty => PrintLine("empty text"),
.InvalidCharacter(at) => PrintLine("not a digit at byte {}", at),
.Overflow(at) => PrintLine("too large for an int32, at byte {}", at)
}
}
func Read(text: char8[..]) {
try {
let value = ParseInt32(text);
PrintLine("[{}] {}", text, value);
} catch {
error => {
Print("[{}] refused, ", text);
Describe(error);
}
}
}
func Main() -> int {
// A sign, and a base prefix of the kind `{:#x}` writes, are both understood.
Read("42");
Read("-17");
Read("0x1F");
// Malformed text. The parser does not skip spaces or stop at the first non-digit: the
// whole text must be a number, or the parser throws an error saying which byte is wrong.
Read("");
Read(" 42");
Read("12abc");
// Well-formed but too large. An `int32` holds -2147483648 to 2147483647, and the
// negative side holds one more than the positive.
Read("2147483647");
Read("2147483648");
Read("-2147483648");
// With `catch`, an error can become a fallback value in one expression.
let fallback = try ParseInt32("seven") catch { _ => 0 };
PrintLine("[seven] with a fallback {}", fallback);
return 0;
}
Besides Io, its Rux.toml lists Format under [Dependencies].
Run it
cd Examples/Text/Parse
rux run
[42] 42
[-17] -17
[0x1F] 31
[] refused, empty text
[ 42] refused, not a digit at byte 0
[12abc] refused, not a digit at byte 2
[2147483647] 2147483647
[2147483648] refused, too large for an int32, at byte 10
[-2147483648] -2147483648
[seven] with a fallback 0
Common mistakes
Try it yourself
- Parse
"0b101"and"0o17". Which other prefixes does the parser understand? - Parse
"300"and"-1"withParseUint8. What does each report? - Trim
" 42\n"withStringView::FromValidated(…).Trim()and parse the view. You will needTextin[Dependencies]andimport Text::StringView;. - Parse
"3.75"withParseFloat64, then try"3,75".
Learn more
- Format in the API reference
- Format number — the spellings
ParseInt32reads back - Catch and Catch fallback — handling the error
- Input — text typed by a person, the usual thing to parse
14.11 Render
Format into a String you keep with Render, which throws a FormatError for a wrong pattern before writing anything, and keep each outcome as a Result<String, FormatError> to report it later.
14.13 Input
Read lines from standard input with ReadLine, where reaching the end of the input is an IoError whose kind is EndOfStream.