https://github.com/eteran/reader
A class that makes writing a parser programatically easy
https://github.com/eteran/reader
Last synced: about 1 year ago
JSON representation
A class that makes writing a parser programatically easy
- Host: GitHub
- URL: https://github.com/eteran/reader
- Owner: eteran
- License: mit
- Created: 2021-02-23T23:37:22.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2024-02-21T16:09:51.000Z (over 2 years ago)
- Last Synced: 2024-05-01T13:39:01.256Z (about 2 years ago)
- Language: C++
- Size: 33.2 KB
- Stars: 2
- Watchers: 4
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# reader
A class that makes writing a parser programmatically easy
## Common usage patterns:
### Tokenization
```
Reader reader(source);
// recommended that the tokens are sorted by length because the first match wins
if (reader.match("++")) {
// make increment token
} else if (reader.match("--")) {
// make decrement token
}
...
```
### Reading numbers (using a regex)
```
if (std::isdigit(reader.peek())) {
static const std::regex integer_regex(R"(^(0|[1-9][0-9]*))");
auto number = reader.match(integer_regex);
if (!number) {
return invalid_numeric_constant();
}
// make sure that this is a valid integer that won't overflow
// when converted to an integer
try {
(void)std::stoi(*number, nullptr, 10);
} catch (const std::out_of_range &ex) {
(void)ex;
return overflow_in_numeric_constant();
}
// create number token or convert to integer here
}
```
### Match characters based on a predicate
```
// This effectively matches the regex: "[a-zA-Z0-9_-]+"
auto key = reader.match_while([](char ch) {
return std::isalnum(ch) || ch == '-' || ch == '_';
});
if (!key) {
return malformed_key();
}
use_character(*key);
```
### skipping whitespace
```
reader.consume_whitespace(); // skips ' ' and '\t'
```