#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Tok {
Ident(String),
Str(Option<String>),
Template,
Num(String),
Regex,
Punct(&'static str),
}
#[derive(Debug, Clone)]
pub(crate) struct Token {
pub tok: Tok,
pub start: usize,
pub end: usize,
pub nl_before: bool,
pub pair: Option<usize>,
pub tick: bool,
pub inner: Vec<String>,
}
pub(crate) const MAX_DEPTH: usize = 64;
impl Token {
pub(crate) fn is(&self, p: &str) -> bool {
matches!(&self.tok, Tok::Punct(q) if *q == p)
}
pub(crate) fn ident(&self) -> Option<&str> {
match &self.tok {
Tok::Ident(s) => Some(s),
_ => None,
}
}
pub(crate) fn is_ident(&self, name: &str) -> bool {
self.ident() == Some(name)
}
}
const PUNCTS: [&str; 52] = [
">>>=", "...", "===", "!==", "**=", "<<=", ">>=", ">>>", "&&=", "||=", "??=", "=>", "==", "!=",
"<=", ">=", "&&", "||", "??", "?.", "++", "--", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=",
"**", "<<", ">>", "{", "}", "(", ")", "[", "]", ";", ",", "<", ">", "+", "-", "*", "%", "&",
"|", "^", "!", "~",
];
const MORE_PUNCTS: [&str; 6] = ["?", ":", "=", ".", "/", "@"];
const REGEX_AFTER: [&str; 12] = [
"return",
"typeof",
"instanceof",
"in",
"of",
"new",
"delete",
"void",
"throw",
"case",
"do",
"else",
];
fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_' || b == b'$'
}
fn is_ident_part(b: u8) -> bool {
is_ident_start(b) || b.is_ascii_digit()
}
pub(crate) fn is_line_terminator(c: char) -> bool {
matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}
fn is_line_break(b: u8) -> bool {
is_line_terminator(char::from(b))
}
fn unusual_terminator(src: &str) -> Option<&'static str> {
let b = src.as_bytes();
for (i, c) in src.char_indices() {
if !is_line_terminator(c) || c == '\n' {
continue;
}
if c == '\r' && b.get(i + 1) == Some(&b'\n') {
continue;
}
return Some(match c {
'\r' => "a carriage return without a line feed",
'\u{2028}' => "a U+2028 line separator",
_ => "a U+2029 paragraph separator",
});
}
None
}
pub(crate) fn tokenize(src: &str) -> Result<Vec<Token>, String> {
if let Some(what) = unusual_terminator(src) {
return Err(format!("it has {what}, which Brrrty doesn't read"));
}
let b = src.as_bytes();
let mut i = 0;
if src.starts_with("#!") {
while i < b.len() && !is_line_break(b[i]) {
i += 1;
}
}
let (mut out, _) = lex(src, i, false, 0)?;
pair_up(&mut out)?;
Ok(out)
}
fn lex(src: &str, mut i: usize, subst: bool, depth: usize) -> Result<(Vec<Token>, usize), String> {
let b = src.as_bytes();
let mut out: Vec<Token> = Vec::new();
let mut nl = false;
let mut parens: Vec<bool> = Vec::new();
let mut closed_condition = false;
let mut braces = 0usize;
while i < b.len() {
let c = b[i];
if is_line_break(c) {
nl = true;
i += 1;
continue;
}
if c.is_ascii_whitespace() {
i += 1;
continue;
}
if i == 0 && src.starts_with('\u{feff}') {
i += 3;
continue;
}
if c >= 0x80 {
return Err("there is a non-ASCII character outside a string or comment".into());
}
if src[i..].starts_with("//") {
i = line_comment(src, i)?;
continue;
}
if src[i..].starts_with("/*") {
let Some(end) = src[i + 2..].find("*/") else {
return Err("a /* comment is never closed".into());
};
if src[i..i + 2 + end].chars().any(is_line_terminator) {
nl = true;
}
i += end + 4;
continue;
}
if subst && c == b'}' && braces == 0 {
return Ok((out, i + 1));
}
let start = i;
let mut inner = Vec::new();
let tok = if c == b'"' || c == b'\'' {
let (end, value) = string(src, i)?;
i = end;
Tok::Str(value)
} else if c == b'`' {
let (end, value) = template(src, i, depth, &mut inner)?;
i = end;
match value {
Some(v) => Tok::Str(v),
None => Tok::Template,
}
} else if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit))
{
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'.' || b[i] == b'_') {
if (b[i] == b'e' || b[i] == b'E')
&& !src[start..].starts_with("0x")
&& matches!(b.get(i + 1), Some(b'+' | b'-'))
{
i += 1;
}
i += 1;
}
Tok::Num(src[start..i].to_string())
} else if is_ident_start(c) || c == b'#' || c == b'\\' {
i += 1;
while i < b.len() && (is_ident_part(b[i]) || b[i] == b'\\') {
i += 1;
}
if src[start..i].contains('\\') {
return Err("a name is written with a `\\` escape".into());
}
Tok::Ident(src[start..i].to_string())
} else if c == b'/' && slash(out.last(), closed_condition)? {
i = regex(b, i)?;
Tok::Regex
} else {
let p = PUNCTS
.iter()
.chain(MORE_PUNCTS.iter())
.find(|p| src[i..].starts_with(**p));
match p {
Some(p) => {
i += p.len();
Tok::Punct(p)
}
None => {
let ch = src[i..].chars().next().unwrap_or('?');
return Err(format!("unexpected `{ch}`"));
}
}
};
closed_condition = false;
match tok {
Tok::Punct("{") => braces += 1,
Tok::Punct("}") => braces = braces.saturating_sub(1),
Tok::Punct("(") => parens.push(
out.last()
.and_then(Token::ident)
.is_some_and(|w| matches!(w, "if" | "while" | "for" | "with")),
),
Tok::Punct(")") => closed_condition = parens.pop().unwrap_or(false),
_ => {}
}
out.push(Token {
tok,
start,
end: i,
nl_before: nl,
pair: None,
tick: c == b'`',
inner,
});
nl = false;
}
if subst {
return Err("a template literal is never closed".into());
}
Ok((out, i))
}
fn pair_up(toks: &mut [Token]) -> Result<(), String> {
let mut stack: Vec<usize> = Vec::new();
for k in 0..toks.len() {
match toks[k].tok {
Tok::Punct("(" | "[" | "{") => {
if stack.len() >= MAX_DEPTH {
return Err(format!("brackets nest more than {MAX_DEPTH} deep"));
}
stack.push(k);
}
Tok::Punct(close @ (")" | "]" | "}")) => {
let Some(o) = stack.pop() else {
return Err(format!("a `{close}` closes nothing"));
};
let want = match toks[o].tok {
Tok::Punct("(") => ")",
Tok::Punct("[") => "]",
_ => "}",
};
if want != close {
return Err(format!(
"a `{close}` closes a bracket opened with something else"
));
}
toks[o].pair = Some(k);
toks[k].pair = Some(o);
}
_ => {}
}
}
if !stack.is_empty() {
return Err("a bracket is never closed".into());
}
Ok(())
}
fn slash(prev: Option<&Token>, after_condition: bool) -> Result<bool, String> {
let unsure = || {
Err(
"Brrrty can't tell whether a `/` here starts a regular expression or divides"
.to_string(),
)
};
match prev.map(|t| &t.tok) {
None => Ok(true),
Some(Tok::Ident(k)) => match k.as_str() {
"of" | "yield" | "await" | "let" | "async" | "get" | "set" | "static" => unsure(),
k if REGEX_AFTER.contains(&k) => Ok(true),
_ => Ok(false),
},
Some(Tok::Punct(")")) if after_condition => unsure(),
Some(Tok::Punct(")" | "]")) => Ok(false),
Some(Tok::Punct("}" | "++" | "--")) => unsure(),
Some(Tok::Punct(_)) => Ok(true),
Some(_) => Ok(false),
}
}
fn line_comment(src: &str, mut i: usize) -> Result<usize, String> {
let b = src.as_bytes();
while i < b.len() && !is_line_break(b[i]) {
i += 1;
}
Ok(i)
}
fn regex(b: &[u8], mut i: usize) -> Result<usize, String> {
i += 1;
let mut class = false;
loop {
match b.get(i) {
None => return Err("a regular expression is never closed".into()),
Some(&c) if is_line_break(c) => {
return Err("a regular expression is never closed".into());
}
Some(b'\\') => i += 2,
Some(b'[') => {
class = true;
i += 1;
}
Some(b']') => {
class = false;
i += 1;
}
Some(b'/') if !class => {
i += 1;
while i < b.len() && is_ident_part(b[i]) {
i += 1;
}
return Ok(i);
}
Some(_) => i += 1,
}
}
}
fn string(src: &str, i: usize) -> Result<(usize, Option<String>), String> {
let b = src.as_bytes();
let quote = b[i];
let mut j = i + 1;
let mut units: Vec<u16> = Vec::new();
let mut exact = true;
loop {
match b.get(j) {
None => return Err("a string is never closed".into()),
Some(&c) if is_line_break(c) => return Err("a string is never closed".into()),
Some(&q) if q == quote => break,
Some(b'\\') => {
let (next, ok) = escape(src, j, &mut units);
exact &= ok;
j = next;
}
Some(_) => {
let ch = src[j..].chars().next().unwrap_or('\u{fffd}');
let mut buf = [0u16; 2];
units.extend_from_slice(ch.encode_utf16(&mut buf));
j += ch.len_utf8();
}
}
}
let value = if exact {
String::from_utf16(&units).ok()
} else {
None
};
Ok((j + 1, value))
}
fn escape(src: &str, j: usize, units: &mut Vec<u16>) -> (usize, bool) {
let b = src.as_bytes();
let Some(&c) = b.get(j + 1) else {
return (j + 1, false);
};
let simple = match c {
b'n' => Some(0x0a),
b'r' => Some(0x0d),
b't' => Some(0x09),
b'b' => Some(0x08),
b'f' => Some(0x0c),
b'v' => Some(0x0b),
b'0' if !b.get(j + 2).is_some_and(u8::is_ascii_digit) => Some(0),
_ => None,
};
if let Some(u) = simple {
units.push(u);
return (j + 2, true);
}
let hex = |s: &str| u32::from_str_radix(s, 16).ok();
match c {
b'\n' => (j + 2, true),
b'\r' => (
if b.get(j + 2) == Some(&b'\n') {
j + 3
} else {
j + 2
},
true,
),
b'x' => match src.get(j + 2..j + 4).and_then(hex) {
Some(v) => {
units.push(v as u16);
(j + 4, true)
}
None => (j + 2, false),
},
b'u' if b.get(j + 2) == Some(&b'{') => {
let Some(close) = src[j + 3..].find('}') else {
return (j + 2, false);
};
match hex(&src[j + 3..j + 3 + close]).and_then(char::from_u32) {
Some(ch) => {
let mut buf = [0u16; 2];
units.extend_from_slice(ch.encode_utf16(&mut buf));
(j + 4 + close, true)
}
None => (j + 4 + close, false),
}
}
b'u' => match src.get(j + 2..j + 6).and_then(hex) {
Some(v) => {
units.push(v as u16);
(j + 6, true)
}
None => (j + 2, false),
},
b'1'..=b'9' | b'0' => (j + 2, false),
_ => {
let ch = src[j + 1..].chars().next().unwrap_or('\u{fffd}');
let mut buf = [0u16; 2];
units.extend_from_slice(ch.encode_utf16(&mut buf));
(j + 1 + ch.len_utf8(), true)
}
}
}
fn template(
src: &str,
i: usize,
depth: usize,
inner: &mut Vec<String>,
) -> Result<(usize, Option<Option<String>>), String> {
if depth > MAX_DEPTH {
return Err(format!("template literals nest more than {MAX_DEPTH} deep"));
}
let b = src.as_bytes();
let mut j = i + 1;
let mut units: Vec<u16> = Vec::new();
let mut exact = true;
let mut plain = true;
loop {
match b.get(j) {
None => return Err("a template literal is never closed".into()),
Some(b'`') => break,
Some(b'\\') => {
let (next, ok) = escape(src, j, &mut units);
exact &= ok;
j = next;
}
Some(b'$') if b.get(j + 1) == Some(&b'{') => {
plain = false;
let (mut toks, end) = lex(src, j + 2, true, depth + 1)?;
pair_up(&mut toks)?;
for (k, t) in toks.iter().enumerate() {
if let Some(name) = t.ident()
&& !(k > 0 && (toks[k - 1].is(".") || toks[k - 1].is("?.")))
{
inner.push(name.to_string());
}
inner.extend(t.inner.iter().cloned());
}
j = end;
}
Some(b'\r') => {
units.push(0x0a);
j += if b.get(j + 1) == Some(&b'\n') { 2 } else { 1 };
}
Some(_) => {
let ch = src[j..].chars().next().unwrap_or('\u{fffd}');
let mut buf = [0u16; 2];
units.extend_from_slice(ch.encode_utf16(&mut buf));
j += ch.len_utf8();
}
}
}
let value = if !plain {
None
} else if exact {
Some(String::from_utf16(&units).ok())
} else {
Some(None)
};
Ok((j + 1, value))
}
pub(crate) fn matching(toks: &[Token], open: usize) -> Option<usize> {
let t = toks.get(open)?;
if !matches!(t.tok, Tok::Punct("(" | "[" | "{")) {
return None;
}
t.pair
}
const RESTRICTED: [&str; 5] = ["return", "throw", "break", "continue", "yield"];
fn can_end(t: &Token) -> bool {
match &t.tok {
Tok::Punct(p) => matches!(*p, ")" | "]" | "}" | "++" | "--"),
_ => true,
}
}
fn continues(t: &Token) -> bool {
if t.tick {
return true;
}
match &t.tok {
Tok::Punct(p) => !matches!(*p, "!" | "~" | "++" | "--"),
Tok::Ident(k) => matches!(k.as_str(), "else" | "catch" | "finally"),
_ => false,
}
}
pub(crate) fn statements(toks: &[Token], from: usize, to: usize) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut depth = 0i32;
let mut start = from;
for k in from..to {
let t = &toks[k];
if depth == 0
&& k > start
&& t.nl_before
&& (toks[k - 1].ident().is_some_and(|w| RESTRICTED.contains(&w))
|| (can_end(&toks[k - 1]) && !continues(t)))
{
out.push((start, k));
start = k;
}
match t.tok {
Tok::Punct("(" | "[" | "{") => depth += 1,
Tok::Punct(")" | "]" | "}") => depth -= 1,
Tok::Punct(";") if depth == 0 => {
if k > start {
out.push((start, k));
}
start = k + 1;
}
_ => {}
}
}
if start < to {
out.push((start, to));
}
out
}
pub(crate) fn split_commas(toks: &[Token], from: usize, to: usize) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut depth = 0i32;
let mut start = from;
for (k, t) in toks.iter().enumerate().take(to).skip(from) {
match t.tok {
Tok::Punct("(" | "[" | "{") => depth += 1,
Tok::Punct(")" | "]" | "}") => depth -= 1,
Tok::Punct(",") if depth == 0 => {
out.push((start, k));
start = k + 1;
}
_ => {}
}
}
if start < to {
out.push((start, to));
}
out
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Lit {
Str(String),
Num(String),
Bool(bool),
Null,
Array(Vec<Lit>),
Object(Vec<(String, Lit)>),
}
pub(crate) struct Prop {
pub key: String,
pub range: (usize, usize),
pub value: (usize, usize),
}
pub(crate) fn object_props(toks: &[Token], from: usize, to: usize) -> Option<Vec<Prop>> {
if to <= from || !toks[from].is("{") || matching(toks, from)? != to - 1 {
return None;
}
let mut out = Vec::new();
for (a, b) in split_commas(toks, from + 1, to - 1) {
if b < a + 3 || !toks[a + 1].is(":") {
return None;
}
let key = match &toks[a].tok {
Tok::Ident(s) => s.clone(),
Tok::Str(Some(s)) => s.clone(),
Tok::Num(n) if n.bytes().all(|c| c.is_ascii_digit()) => n.clone(),
_ => return None,
};
out.push(Prop {
key,
range: (a, b),
value: (a + 2, b),
});
}
Some(out)
}
pub(crate) fn literal(toks: &[Token], from: usize, to: usize) -> Option<Lit> {
let first = toks.get(from)?;
if to == from + 1 {
return match &first.tok {
Tok::Str(Some(s)) => Some(Lit::Str(s.clone())),
Tok::Num(n) => number(n, false),
Tok::Ident(k) => match k.as_str() {
"true" => Some(Lit::Bool(true)),
"false" => Some(Lit::Bool(false)),
"null" => Some(Lit::Null),
_ => None,
},
_ => None,
};
}
if to == from + 2 && first.is("-") {
if let Tok::Num(n) = &toks[from + 1].tok {
return number(n, true);
}
return None;
}
if first.is("[") {
if matching(toks, from)? != to - 1 {
return None;
}
let mut items = Vec::new();
for (a, b) in split_commas(toks, from + 1, to - 1) {
items.push(literal(toks, a, b)?);
}
return Some(Lit::Array(items));
}
if first.is("{") {
let mut pairs: Vec<(String, Lit)> = Vec::new();
for p in object_props(toks, from, to)? {
let v = literal(toks, p.value.0, p.value.1)?;
if let Some(slot) = pairs.iter_mut().find(|(k, _)| *k == p.key) {
slot.1 = v;
} else {
pairs.push((p.key, v));
}
}
return Some(Lit::Object(pairs));
}
None
}
fn number(n: &str, negative: bool) -> Option<Lit> {
let (whole, frac) = match n.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (n, None),
};
let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
if !digits(whole) || (whole.len() > 1 && whole.starts_with('0')) {
return None;
}
if let Some(f) = frac
&& !digits(f)
{
return None;
}
if frac.is_none() && whole.len() > 15 {
return None;
}
Some(Lit::Num(if negative {
format!("-{n}")
} else {
n.to_string()
}))
}
pub(crate) fn rhai_string(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for ch in s.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 || c == '\u{7f}' => {
out.push_str(&format!("\\x{:02x}", c as u32));
}
'\u{85}' | '\u{2028}' | '\u{2029}' => {
out.push_str(&format!("\\u{:04x}", ch as u32));
}
c => out.push(c),
}
}
out.push('"');
out
}
const RHAI_RESERVED: &[&str] = &[
"true",
"false",
"let",
"const",
"if",
"else",
"switch",
"do",
"while",
"until",
"loop",
"for",
"in",
"continue",
"break",
"return",
"throw",
"try",
"catch",
"import",
"export",
"as",
"global",
"private",
"fn",
"this",
"is",
"var",
"static",
"shared",
"sync",
"async",
"await",
"yield",
"default",
"void",
"null",
"nil",
"spawn",
"thread",
"go",
"exit",
"goto",
"match",
"case",
"public",
"protected",
"new",
"use",
"with",
"module",
"package",
"super",
"type_of",
"print",
"debug",
"eval",
"Fn",
"call",
"curry",
];
fn rhai_key(k: &str) -> String {
let bare = k.bytes().next().is_some_and(|c| c.is_ascii_alphabetic())
&& k.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
&& !RHAI_RESERVED.contains(&k);
if bare { k.to_string() } else { rhai_string(k) }
}
pub(crate) fn rhai(lit: &Lit, indent: usize) -> String {
let flat = rhai_flat(lit);
if indent * 4 + flat.len() <= 76 {
return flat;
}
let pad = " ".repeat(indent + 1);
let close = " ".repeat(indent);
match lit {
Lit::Array(items) => {
let mut s = "[\n".to_string();
for v in items {
s += &format!("{pad}{},\n", rhai(v, indent + 1));
}
format!("{s}{close}]")
}
Lit::Object(pairs) => {
let mut s = "#{\n".to_string();
for (k, v) in pairs {
s += &format!("{pad}{}: {},\n", rhai_key(k), rhai(v, indent + 1));
}
format!("{s}{close}}}")
}
_ => flat,
}
}
fn rhai_flat(lit: &Lit) -> String {
match lit {
Lit::Str(s) => rhai_string(s),
Lit::Num(n) => n.clone(),
Lit::Bool(b) => b.to_string(),
Lit::Null => "null_value()".into(),
Lit::Array(items) => format!(
"[{}]",
items.iter().map(rhai_flat).collect::<Vec<_>>().join(", ")
),
Lit::Object(pairs) if pairs.is_empty() => "#{}".into(),
Lit::Object(pairs) => format!(
"#{{ {} }}",
pairs
.iter()
.map(|(k, v)| format!("{}: {}", rhai_key(k), rhai_flat(v)))
.collect::<Vec<_>>()
.join(", ")
),
}
}
pub(crate) fn order_safe(lit: &Lit) -> bool {
match lit {
Lit::Object(pairs) => {
pairs
.iter()
.all(|(k, _)| !k.bytes().all(|c| c.is_ascii_digit()))
&& pairs.windows(2).all(|w| w[0].0 < w[1].0)
&& pairs.iter().all(|(_, v)| order_safe(v))
}
Lit::Array(items) => items.iter().all(order_safe),
_ => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lit(src: &str) -> Option<Lit> {
let t = tokenize(src).unwrap();
literal(&t, 0, t.len())
}
#[test]
fn reads_literals() {
assert_eq!(lit("'a\\'b'"), Some(Lit::Str("a'b".into())));
assert_eq!(lit("`plain`"), Some(Lit::Str("plain".into())));
assert_eq!(lit("`x${y}`"), None);
assert_eq!(lit("-2"), Some(Lit::Num("-2".into())));
assert_eq!(lit("0x10"), None);
assert_eq!(lit("1e3"), None);
assert_eq!(
lit("{ a: [1, 'x'], 'b-c': null, }"),
Some(Lit::Object(vec![
(
"a".into(),
Lit::Array(vec![Lit::Num("1".into()), Lit::Str("x".into())])
),
("b-c".into(), Lit::Null),
]))
);
assert_eq!(lit("{ a }"), None);
assert_eq!(lit("{ ...a }"), None);
assert_eq!(lit("f()"), None);
assert_eq!(lit("'\\ud83d\\ude00'"), Some(Lit::Str("😀".into())));
assert_eq!(lit("'\\ud83d'"), None);
}
#[test]
fn splits_statements_with_and_without_semicolons() {
let src = "a.b(1)\nc.d({\n x: 1\n})\nif (x) {\n} else {\n}\nreturn { y: 2 };";
let t = tokenize(src).unwrap();
let s = statements(&t, 0, t.len());
let text: Vec<&str> = s
.iter()
.map(|&(a, b)| &src[t[a].start..t[b - 1].end])
.collect();
assert_eq!(
text,
[
"a.b(1)",
"c.d({\n x: 1\n})",
"if (x) {\n} else {\n}",
"return { y: 2 }"
]
);
}
#[test]
fn regex_and_comments() {
let t = tokenize("x = /a\\/[/]b/g; // c\n/* d */ y = 4 / 2").unwrap();
assert!(t.iter().any(|t| t.tok == Tok::Regex));
assert_eq!(t.iter().filter(|t| t.is("/")).count(), 1);
assert!(tokenize("'open").is_err());
}
#[test]
fn template_substitutions_are_read_as_code() {
let t = tokenize("x = `a${s.replace(/[}'`]/g, '')}b${n / 2}c${`${cfg.d}`}`; y").unwrap();
assert_eq!(t.iter().filter(|t| t.tok == Tok::Template).count(), 1);
let tpl = t.iter().find(|t| t.tok == Tok::Template).unwrap();
assert_eq!(tpl.inner, ["s", "n", "cfg"]);
assert!(t.last().unwrap().is_ident("y"));
assert!(tokenize("`${(x) /'/.test(s)}`").is_err());
assert!(tokenize("`${a").is_err());
assert!(tokenize("x = /é\\u{a0}/u").is_ok());
assert!(tokenize("`${é}`").is_err());
}
#[test]
fn writes_rhai() {
let v = lit("{ name: 'a\"b', type: 'x', 'data-x': 1, n: null }").unwrap();
assert_eq!(
rhai(&v, 0),
"#{ name: \"a\\\"b\", type: \"x\", \"data-x\": 1, n: null_value() }"
);
assert!(!order_safe(&lit("{ b: 1, a: 2 }").unwrap()));
assert!(!order_safe(&lit("{ 2: 1 }").unwrap()));
assert!(order_safe(&lit("{ a: 1, b: { c: 1 } }").unwrap()));
}
}