mod json;
mod tag;
mod value;
#[cfg(test)]
mod tests;
use std::fmt;
pub use crate::markdown_it::js::RangeError;
pub use tag::{MAX_NESTING, cost};
pub use value::{Function, Object, Prototype, Value, Variable};
use json::{utf16_to_json, write_str, write_utf16};
pub fn parse(content: &str) -> Result<Parsed, ParseError> {
let input: Vec<u16> = content.encode_utf16().collect();
tag::peg_parse(&input)
}
pub fn parse_utf16(input: &[u16]) -> Result<Parsed, ParseError> {
tag::peg_parse(input)
}
pub fn parse_tag(tag: &str) -> Option<Result<Parsed, ParseError>> {
let body = tag.strip_prefix("{%")?.strip_suffix("%}")?;
let body: Vec<u16> = body
.replace("\r\n", "\n")
.replace('\r', "\n")
.replace('\0', "\u{FFFD}")
.encode_utf16()
.collect();
Some(parse_utf16(crate::markdown_it::js::trim(&body)))
}
#[derive(Clone, Debug, PartialEq)]
pub enum ParseError {
Syntax(SyntaxError),
Range(RangeError),
}
impl ParseError {
pub fn as_syntax(&self) -> Option<&SyntaxError> {
match self {
ParseError::Syntax(error) => Some(error),
ParseError::Range(_) => None,
}
}
}
impl From<SyntaxError> for ParseError {
fn from(error: SyntaxError) -> ParseError {
ParseError::Syntax(error)
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::Syntax(error) => fmt::Display::fmt(error, f),
ParseError::Range(error) => fmt::Display::fmt(error, f),
}
}
}
impl std::error::Error for ParseError {}
#[derive(Clone, Debug, PartialEq)]
pub struct Parsed {
pub kind: ParsedType,
pub nesting: Option<i8>,
pub meta: Meta,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParsedType {
TagOpen,
TagClose,
Tag,
Annotation,
Variable,
}
impl ParsedType {
pub const ALL: [ParsedType; 5] = [
ParsedType::TagOpen,
ParsedType::TagClose,
ParsedType::Tag,
ParsedType::Annotation,
ParsedType::Variable,
];
pub fn as_str(self) -> &'static str {
match self {
ParsedType::TagOpen => "tag_open",
ParsedType::TagClose => "tag_close",
ParsedType::Tag => "tag",
ParsedType::Annotation => "annotation",
ParsedType::Variable => "variable",
}
}
}
impl std::str::FromStr for ParsedType {
type Err = String;
fn from_str(name: &str) -> std::result::Result<ParsedType, String> {
ParsedType::ALL
.into_iter()
.find(|kind| kind.as_str() == name)
.ok_or_else(|| format!("not a tag type: {name:?}"))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Meta {
pub tag: Option<String>,
pub attributes: Option<Option<Vec<Attribute>>>,
pub variable: Option<Value>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Attribute {
pub kind: AttributeType,
pub name: String,
pub value: Value,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttributeType {
Attribute,
Class,
}
impl AttributeType {
pub fn as_str(self) -> &'static str {
match self {
AttributeType::Attribute => "attribute",
AttributeType::Class => "class",
}
}
}
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct JsString(pub Vec<u16>);
impl JsString {
pub fn as_units(&self) -> &[u16] {
&self.0
}
pub fn to_string_lossy(&self) -> String {
String::from_utf16_lossy(&self.0)
}
}
impl From<&str> for JsString {
fn from(s: &str) -> JsString {
JsString(s.encode_utf16().collect())
}
}
impl PartialEq<str> for JsString {
fn eq(&self, other: &str) -> bool {
self.0.iter().copied().eq(other.encode_utf16())
}
}
impl PartialEq<&str> for JsString {
fn eq(&self, other: &&str) -> bool {
*self == **other
}
}
impl fmt::Display for JsString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_string_lossy())
}
}
impl fmt::Debug for JsString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = String::new();
write_utf16(&mut s, &self.0);
f.write_str(&s)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct SyntaxError {
pub message: JsString,
pub expected: Vec<Expectation>,
pub found: Option<JsString>,
pub location: Location,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Expectation {
Literal {
text: &'static str,
ignore_case: bool,
},
Class {
parts: &'static [ClassPart],
inverted: bool,
ignore_case: bool,
},
Any,
End,
Other { description: &'static str },
Not(Box<Expectation>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClassPart {
Char(&'static str),
Range(&'static str, &'static str),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Location {
pub start: Position,
pub end: Position,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Position {
pub offset: usize,
pub line: usize,
pub column: usize,
}
impl fmt::Display for SyntaxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.message, f)
}
}
impl std::error::Error for SyntaxError {}
fn obj(entries: Vec<(&str, serde_json::Value)>) -> serde_json::Value {
let mut m = serde_json::Map::new();
for (k, v) in entries {
m.insert(k.to_string(), v);
}
serde_json::Value::Object(m)
}
impl Parsed {
pub fn to_json(&self) -> serde_json::Value {
let mut entries = vec![("type", self.kind.as_str().into())];
if let Some(n) = self.nesting {
entries.push(("nesting", i64::from(n).into()));
}
entries.push(("meta", self.meta.to_json()));
obj(entries)
}
pub fn to_json_string(&self) -> String {
let mut out = String::new();
self.write_json(&mut out);
out
}
pub fn write_json(&self, out: &mut String) {
out.push_str("{\"type\":");
write_str(out, self.kind.as_str());
if let Some(n) = self.nesting {
out.push_str(",\"nesting\":");
out.push_str(&n.to_string());
}
out.push_str(",\"meta\":");
self.meta.write_json(out);
out.push('}');
}
}
impl Meta {
pub fn to_json(&self) -> serde_json::Value {
let mut entries = Vec::new();
if let Some(tag) = &self.tag {
entries.push(("tag", tag.clone().into()));
}
if let Some(attributes) = &self.attributes {
entries.push((
"attributes",
match attributes {
None => serde_json::Value::Null,
Some(list) => list.iter().map(Attribute::to_json).collect(),
},
));
}
if let Some(variable) = &self.variable {
entries.push(("variable", variable.to_json()));
}
obj(entries)
}
pub fn write_json(&self, out: &mut String) {
out.push('{');
let mut first = true;
let mut key = |out: &mut String, k: &str| {
if !first {
out.push(',');
}
first = false;
write_str(out, k);
out.push(':');
};
if let Some(tag) = &self.tag {
key(out, "tag");
write_str(out, tag);
}
if let Some(attributes) = &self.attributes {
key(out, "attributes");
match attributes {
None => out.push_str("null"),
Some(list) => {
out.push('[');
for (i, a) in list.iter().enumerate() {
if i > 0 {
out.push(',');
}
a.write_json(out);
}
out.push(']');
}
}
}
if let Some(variable) = &self.variable {
key(out, "variable");
variable.write_json(out);
}
out.push('}');
}
}
impl Attribute {
pub fn to_json(&self) -> serde_json::Value {
obj(vec![
("type", self.kind.as_str().into()),
("name", self.name.clone().into()),
("value", self.value.to_json()),
])
}
pub fn write_json(&self, out: &mut String) {
out.push_str("{\"type\":");
write_str(out, self.kind.as_str());
out.push_str(",\"name\":");
write_str(out, &self.name);
out.push_str(",\"value\":");
self.value.write_json(out);
out.push('}');
}
}
impl Expectation {
pub fn to_json(&self) -> serde_json::Value {
match self {
Expectation::Literal { text, ignore_case } => obj(vec![
("type", "literal".into()),
("text", (*text).into()),
("ignoreCase", (*ignore_case).into()),
]),
Expectation::Class {
parts,
inverted,
ignore_case,
} => obj(vec![
("type", "class".into()),
(
"parts",
parts
.iter()
.map(|p| match p {
ClassPart::Char(c) => serde_json::Value::from(*c),
ClassPart::Range(a, b) => serde_json::Value::from(vec![*a, *b]),
})
.collect(),
),
("inverted", (*inverted).into()),
("ignoreCase", (*ignore_case).into()),
]),
Expectation::Any => obj(vec![("type", "any".into())]),
Expectation::End => obj(vec![("type", "end".into())]),
Expectation::Other { description } => obj(vec![
("type", "other".into()),
("description", (*description).into()),
]),
Expectation::Not(e) => obj(vec![("type", "not".into()), ("expected", e.to_json())]),
}
}
pub fn write_json(&self, out: &mut String) {
match self {
Expectation::Literal { text, ignore_case } => {
out.push_str("{\"type\":\"literal\",\"text\":");
write_str(out, text);
out.push_str(if *ignore_case {
",\"ignoreCase\":true}"
} else {
",\"ignoreCase\":false}"
});
}
Expectation::Class {
parts,
inverted,
ignore_case,
} => {
out.push_str("{\"type\":\"class\",\"parts\":[");
for (i, p) in parts.iter().enumerate() {
if i > 0 {
out.push(',');
}
match p {
ClassPart::Char(c) => write_str(out, c),
ClassPart::Range(a, b) => {
out.push('[');
write_str(out, a);
out.push(',');
write_str(out, b);
out.push(']');
}
}
}
out.push_str("],\"inverted\":");
out.push_str(if *inverted { "true" } else { "false" });
out.push_str(",\"ignoreCase\":");
out.push_str(if *ignore_case { "true}" } else { "false}" });
}
Expectation::Any => out.push_str("{\"type\":\"any\"}"),
Expectation::End => out.push_str("{\"type\":\"end\"}"),
Expectation::Other { description } => {
out.push_str("{\"type\":\"other\",\"description\":");
write_str(out, description);
out.push('}');
}
Expectation::Not(e) => {
out.push_str("{\"type\":\"not\",\"expected\":");
e.write_json(out);
out.push('}');
}
}
}
}
impl Position {
pub fn to_json(&self) -> serde_json::Value {
obj(vec![
("offset", self.offset.into()),
("line", self.line.into()),
("column", self.column.into()),
])
}
pub fn write_json(&self, out: &mut String) {
out.push_str(&format!(
"{{\"offset\":{},\"line\":{},\"column\":{}}}",
self.offset, self.line, self.column
));
}
}
impl Location {
pub fn to_json(&self) -> serde_json::Value {
obj(vec![
("start", self.start.to_json()),
("end", self.end.to_json()),
])
}
pub fn write_json(&self, out: &mut String) {
out.push_str("{\"start\":");
self.start.write_json(out);
out.push_str(",\"end\":");
self.end.write_json(out);
out.push('}');
}
}
impl SyntaxError {
pub fn to_json(&self) -> serde_json::Value {
obj(vec![
("message", utf16_to_json(&self.message.0)),
(
"expected",
self.expected.iter().map(Expectation::to_json).collect(),
),
(
"found",
self.found
.as_ref()
.map_or(serde_json::Value::Null, |f| utf16_to_json(&f.0)),
),
("location", self.location.to_json()),
("name", "SyntaxError".into()),
])
}
pub fn to_json_string(&self) -> String {
let mut out = String::new();
self.write_fields_json(&mut out);
out.insert(0, '{');
out.push_str(",\"name\":\"SyntaxError\"}");
out
}
pub fn write_fields_json(&self, out: &mut String) {
out.push_str("\"message\":");
write_utf16(out, &self.message.0);
out.push_str(",\"expected\":[");
for (i, e) in self.expected.iter().enumerate() {
if i > 0 {
out.push(',');
}
e.write_json(out);
}
out.push_str("],\"found\":");
match &self.found {
None => out.push_str("null"),
Some(f) => write_utf16(out, &f.0),
}
out.push_str(",\"location\":");
self.location.write_json(out);
}
}