1use crate::error::error_helpers::schema_error;
2use crate::error::PoolResult;
3
4use super::attrs::Attrs;
5use super::content::ContentMatch;
6use super::mark_type::{MarkSpec, MarkType};
7use super::node_type::{NodeSpec, NodeType};
8use serde::Serialize;
9use serde_json::Value;
10use std::any::Any;
11use std::collections::HashMap;
12use std::sync::{Arc, Mutex};
13#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize)]
16pub struct Attribute {
17 pub has_default: bool,
18 pub default: Option<Value>,
19}
20
21impl Attribute {
22 pub(crate) fn new(options: AttributeSpec) -> Self {
24 Attribute {
25 has_default: options.default.is_some(),
26 default: options.default,
27 }
28 }
29 pub fn is_required(&self) -> bool {
32 !self.has_default
33 }
34}
35#[derive(Clone, Debug)]
38pub struct Schema {
39 pub spec: SchemaSpec,
41 pub top_node_type: Option<NodeType>,
43 pub cached: Arc<Mutex<HashMap<String, Arc<dyn Any + Send + Sync>>>>,
45 pub nodes: HashMap<String, NodeType>,
47 pub marks: HashMap<String, MarkType>,
49}
50impl PartialEq for Schema {
51 fn eq(
52 &self,
53 other: &Self,
54 ) -> bool {
55 self.spec == other.spec
56 && self.top_node_type == other.top_node_type
57 && self.nodes == other.nodes
58 && self.marks == other.marks
59 }
60}
61impl Eq for Schema {}
62impl Schema {
63 pub fn new(spec: SchemaSpec) -> Self {
65 let mut instance_spec = SchemaSpec {
66 nodes: HashMap::new(),
67 marks: HashMap::new(),
68 top_node: spec.top_node,
69 };
70 for (key, value) in spec.nodes {
72 instance_spec.nodes.insert(key, value);
73 }
74 for (key, value) in spec.marks {
75 instance_spec.marks.insert(key, value);
76 }
77 Schema {
78 spec: instance_spec,
79 top_node_type: None,
80 cached: Arc::new(Mutex::new(HashMap::new())),
81 nodes: HashMap::new(),
82 marks: HashMap::new(),
83 }
84 }
85 pub fn compile(instance_spec: SchemaSpec) -> PoolResult<Schema> {
88 let mut schema: Schema = Schema::new(instance_spec);
89 let nodes: HashMap<String, NodeType> =
90 NodeType::compile(schema.spec.nodes.clone());
91 let marks = MarkType::compile(schema.spec.marks.clone());
92 let mut content_expr_cache = HashMap::new();
93 let mut updated_nodes = HashMap::new();
94 for (prop, type_) in &nodes {
95 if marks.contains_key(prop) {
96 return Err(schema_error(&format!(
97 "{} 不能既是节点又是标记",
98 prop
99 )));
100 }
101
102 let content_expr = type_.spec.content.as_deref().unwrap_or("");
103 let mark_expr = type_.spec.marks.as_deref();
104
105 let content_match = content_expr_cache
106 .entry(content_expr.to_string())
107 .or_insert_with(|| {
108 ContentMatch::parse(content_expr.to_string(), &nodes)
109 })
110 .clone();
111
112 let mark_set = match mark_expr {
113 Some("_") => None,
114 Some(expr) => {
115 let marks_result = gather_marks(
116 &schema,
117 expr.split_whitespace().collect(),
118 );
119 match marks_result {
120 Ok(marks) => Some(marks.into_iter().cloned().collect()), Err(e) => return Err(schema_error(&e)),
122 }
123 },
124 None => None,
125 };
126
127 let mut node = type_.clone();
128 node.content_match = Some(content_match);
129 node.mark_set = mark_set;
130 updated_nodes.insert(prop.clone(), node);
131 }
132 schema.nodes = updated_nodes;
133 schema.marks = marks;
134 schema.top_node_type = match schema.nodes.get(
135 &schema.spec.top_node.clone().unwrap_or_else(|| "doc".to_string()),
136 ) {
137 Some(node) => Some(node.clone()),
138 None => {
139 return Err(schema_error("未找到顶级节点类型定义"));
140 },
141 };
142
143 Ok(schema)
144 }
145}
146#[derive(Clone, PartialEq, Eq, Debug)]
149pub struct SchemaSpec {
150 pub nodes: HashMap<String, NodeSpec>,
151 pub marks: HashMap<String, MarkSpec>,
152 pub top_node: Option<String>,
153}
154
155pub fn default_attrs(
160 attrs: &HashMap<String, Attribute>
161) -> Option<HashMap<String, Value>> {
162 let mut defaults = HashMap::new();
163
164 for (attr_name, attr) in attrs {
165 if let Some(default) = &attr.default {
166 defaults.insert(attr_name.clone(), default.clone());
167 } else {
168 return None;
169 }
170 }
171
172 Some(defaults)
173}
174#[derive(Clone, PartialEq, Debug, Eq, Hash, Serialize)]
176pub struct AttributeSpec {
177 pub default: Option<Value>,
179}
180fn gather_marks<'a>(
183 schema: &'a Schema,
184 marks: Vec<&'a str>,
185) -> Result<Vec<&'a MarkType>, String> {
186 let mut found = Vec::new();
187
188 for name in marks {
189 if let Some(mark) = schema.marks.get(name) {
190 found.push(mark);
191 } else {
192 let mut ok = None;
193 for mark_ref in schema.marks.values() {
194 if name == "_"
195 || mark_ref.spec.group.as_ref().is_some_and(|group| {
196 group.split_whitespace().any(|g| g == name)
197 })
198 {
199 found.push(mark_ref);
200 ok = Some(mark_ref);
201 break;
202 }
203 }
204 if ok.is_none() {
205 return Err(format!("未知的标记类型: '{}'", name));
206 }
207 }
208 }
209 Ok(found)
210}
211pub fn compute_attrs(
214 attrs: &HashMap<String, Attribute>,
215 value: Option<&HashMap<String, Value>>,
216) -> Attrs {
217 let mut built = Attrs::default();
218
219 for (name, attr) in attrs {
220 let given = value.and_then(|v| v.get(name));
221
222 let given = match given {
223 Some(val) => val.clone(),
224 None => {
225 if attr.has_default {
226 attr.default.clone().unwrap_or_else(|| {
227 panic!("没有为属性提供默认值 {}", name)
228 })
229 } else {
230 Value::Null
231 }
232 },
233 };
234
235 built[&name] = given;
236 }
237
238 built
239}