update: Add validation for get_name which rejects empty string (which is not a valid token)

This commit is contained in:
Wataru Otsubo 2025-02-01 20:39:23 +09:00
parent 1ed3843508
commit 859d9c0fa3

View file

@ -54,8 +54,11 @@ pub enum DomConversionError {
param: &'static str, param: &'static str,
pos: (TextPos, TextPos), pos: (TextPos, TextPos),
}, },
#[error("other dom conversion error: {0}")] #[error("other dom conversion error: {comment}: {start} - {end}", start = pos.0, end = pos.1)]
OtherError(String), OtherError {
comment: &'static str,
pos: (TextPos, TextPos),
},
} }
impl DomConversionError { impl DomConversionError {
@ -115,6 +118,15 @@ impl DomConversionError {
found, found,
} }
} }
fn other_error(comment: &'static str, node: Node) -> Self {
let range = node.range();
let doc = node.document();
Self::OtherError {
comment,
pos: (doc.text_pos_at(range.start), doc.text_pos_at(range.end)),
}
}
} }
mod util { mod util {
@ -126,7 +138,11 @@ mod util {
pub(crate) fn get_name(node: Node) -> Result<String, DomConversionError> { pub(crate) fn get_name(node: Node) -> Result<String, DomConversionError> {
match node.attribute("name") { match node.attribute("name") {
Some(name) => Ok(name.to_string()), Some(name) if !name.is_empty() => Ok(name.to_string()),
Some(_name) => Err(DomConversionError::other_error(
"name cannot be empty",
node,
)),
None => Err(DomConversionError::attr_not_found("name", node)), None => Err(DomConversionError::attr_not_found("name", node)),
} }
} }
@ -286,8 +302,9 @@ impl Block {
.next() .next()
{ {
Some(s) => Ok(s.to_string()), Some(s) => Ok(s.to_string()),
None => Err(DomConversionError::OtherError( None => Err(DomConversionError::other_error(
"decoder format is not yet fixed".to_string(), "decoder format is not yet fixed",
node,
)), )),
}?, }?,
}; };
@ -377,18 +394,16 @@ impl Register {
// Validation // Validation
if mask.is_some() && !children.is_empty() { if mask.is_some() && !children.is_empty() {
return Err(DomConversionError::OtherError(format!( return Err(DomConversionError::other_error(
"both mask and field are used in the same register: {} - {}", "both mask and field are used in the same register",
node.document().text_pos_at(node.range().start), node,
node.document().text_pos_at(node.range().end), ));
)));
} }
if default.is_some() && !children.is_empty() { if default.is_some() && !children.is_empty() {
return Err(DomConversionError::OtherError(format!( return Err(DomConversionError::other_error(
"both default and field are used in the same register: {} - {}", "both default and field are used in the same register",
node.document().text_pos_at(node.range().start), node,
node.document().text_pos_at(node.range().end), ));
)));
} }
if let (Some(mask), Some(default)) = (mask, default) { if let (Some(mask), Some(default)) = (mask, default) {
if default & !(mask) != 0 { if default & !(mask) != 0 {