1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
//! This example tokenizes a slightly modified form of JSON.
use alkale::{
common::{
error::ErrorNotification,
string::{ParseCharError, StringTokenError},
},
token::Token,
TokenizerContext,
};
#[derive(Debug, Clone)]
pub enum JsonToken {
OpenBrace,
CloseBrace,
OpenBracket,
CloseBracket,
Colon,
Comma,
Null,
Bool(bool),
Str(String),
Number(f64),
}
pub fn main() {
use JsonToken::*;
let code = r##"
{
"a": "Assigned to the \"a\" property!",
"b" : 25.2,
"c": false,
"d": true,
"12": null,
"list": [
1,
-2e+2,
3.1
]
}
"##;
let mut context = TokenizerContext::new(code.chars());
while context.has_next() {
// Map single-character tokens to their data.
let found_token = context.map_single_char_token(|x| match x {
'{' => Some(OpenBrace),
'}' => Some(CloseBrace),
'[' => Some(OpenBracket),
']' => Some(CloseBracket),
':' => Some(Colon),
',' => Some(Comma),
_ => None,
});
// If the above codeblock pushed a new token, move onto the next iteration.
if found_token {
continue;
}
// Attempt to parse an identifier for certain tokens.
if let Some((name, span)) = context.try_parse_standard_identifier() {
let data = match name.as_ref() {
"null" => Some(Null),
"true" => Some(Bool(true)),
"false" => Some(Bool(false)),
_ => None,
};
// If the above table mapped the identifier to valid token data, push a token.
// If it didn't report an error— either way restart the loop.
if let Some(data) = data {
context.push_token(Token::new(data, span));
} else {
context.report(ErrorNotification(
format!("Unexpected identifier {}", name),
span,
))
}
continue;
}
// If the next element in the source code is a string, parse it and report errors as necessary.
if let Some((result, span)) = context.try_parse_strict_string() {
match result {
Ok(string) => {
// Push the valid string.
context.push_token(Token::new(Str(string), span));
}
Err(errors) => {
// Create a notification for every error.
for error in errors {
use ParseCharError::*;
use StringTokenError::*;
match error {
CharError(NoEscape(span)) => ErrorNotification(
"Missing escape code after backslash".to_owned(),
span,
),
CharError(IllegalEscape(char, span)) => {
ErrorNotification(format!("Illegal escape code '{}'", char), span)
}
CharError(NoCharFound) => {
unreachable!("Strings will never create this error")
}
NoClosingDelimiter => ErrorNotification(
"Missing closing delimiter on string".to_owned(),
span.clone(),
),
};
}
}
}
continue;
}
// If the next character is a minus sign, skip it and set
// this variable to its span. Otherwise, set it to None.
//
// Note: Negatives are parsed during tokenization because no subtraction
// exists in JSON, every - sign is unary so there's no ambiguity.
let negative_sign_span = if context.peek_is('-') {
let span = context.next_span().unwrap().1;
context.skip_whitespace();
Some(span)
} else {
None
};
// Attempt to parse a floating point number. If one was found and it was valid, push
// a token for it, otherwise report a parsing error.
if let Some((result, span)) = context.try_parse_float() {
if let Ok(mut number) = result {
// If a negative sign was found prior, negate the number.
// This is completely lossless because floating point numbers use a sign bit.
negative_sign_span.is_some().then(|| number = -number);
context.push_token(Token::new(Number(number), span));
} else {
context.report(ErrorNotification(
"Floating-point number is malformed".to_owned(),
span,
));
}
continue;
} else if let Some(span) = negative_sign_span {
// If no number was found, but we DID find a negative sign, then that negative sign is alone and
// is thus invalid.
context.report(ErrorNotification(
"Negative sign should have a number after it".to_owned(),
span,
));
continue;
}
// If whitespace is found, skip it and continue, otherwise throw an error indicating this
// is an unknown character.
if context.peek_is_map(|char| char.is_whitespace()) {
context.skip_whitespace();
} else {
let (char, span) = context.next_span().unwrap();
context.report(ErrorNotification(
format!("Unexpected character '{char}'"),
span,
))
}
}
println!("{:#?}", context.result());
}