repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/config.rs
src/config.rs
use crate::CMD; use crokey::{key, KeyCombination}; use crossterm::event::{KeyCode, KeyModifiers}; use std::error::Error; use std::str::FromStr; use ratatui::style::Color; use serde::{Deserialize, Deserializer}; use std::collections::HashMap; use std::path::PathBuf; #[derive(Debug, Deserialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum KeyBindEvent { FocusLeft, FocusDown, FocusUp, FocusRight, MenuUp, MenuDown, Quit, Activate, None, } #[derive(Deserialize, Debug)] pub struct Config { #[serde(default = "columns")] pub columns: usize, #[serde(default = "sorting")] pub sorting: bool, #[serde(default = "colors")] pub colors: Colors, #[serde(default = "symbols")] pub symbols: Symbols, #[serde(default = "mouse")] pub mouse: bool, #[serde(default = "key_map", deserialize_with = "merge_with_default")] pub key_map: HashMap<KeyCombination, KeyBindEvent>, } fn merge_with_default<'de, D>( deserializer: D, ) -> Result<HashMap<KeyCombination, KeyBindEvent>, D::Error> where D: Deserializer<'de>, { let mut result = key_map(); let mut config_map = HashMap::<KeyCombination, KeyBindEvent>::new(); let raw_conf_map: Option<HashMap<String, KeyBindEvent>> = Option::deserialize(deserializer)?; // Check for duplicates if let Some(map) = raw_conf_map { for (k, v) in map { let kc = if k.len() == 1 && k.chars().next().unwrap().is_uppercase() { let ch = k.chars().next().unwrap(); KeyCombination::new(KeyCode::Char(ch), KeyModifiers::SHIFT) } else { KeyCombination::from_str(&k).map_err(serde::de::Error::custom)? }; if config_map.contains_key(&kc) { return Err(serde::de::Error::custom(format!("config: duplicate key binding detected for key: '{}'", k))) } config_map.insert(kc, v); } } result.extend(config_map); log::debug!("LOADED KEYMAP: {:?}", result); Ok(result) } #[derive(Deserialize, Debug)] pub struct Symbols { #[serde(default = "highlight_symbol")] pub highlight_symbol: String, #[serde(default = "node_closed_symbol")] pub node_closed_symbol: String, #[serde(default = "node_open_symbol")] pub node_open_symbol: String, #[serde(default = "node_no_children_symbol")] pub node_no_children_symbol: String, } #[derive(Deserialize, Debug, Clone)] pub struct Colors { #[serde(default = "reset")] pub bg: Color, #[serde(default = "white")] pub fg: Color, #[serde(default = "white")] pub border_fg: Color, #[serde(default = "reset")] pub border_bg: Color, #[serde(default = "reset")] pub bg_focused: Color, #[serde(default = "white")] pub fg_focused: Color, #[serde(default = "green")] pub border_fg_focused: Color, #[serde(default = "reset")] pub border_bg_focused: Color, #[serde(default = "green")] pub bg_highlighted: Color, #[serde(default = "black")] pub fg_highlighted: Color, } impl Default for Symbols { fn default() -> Self { Self { highlight_symbol: highlight_symbol(), node_open_symbol: node_open_symbol(), node_closed_symbol: node_closed_symbol(), node_no_children_symbol: node_no_children_symbol(), } } } impl Default for Config { fn default() -> Self { Self { sorting: sorting(), symbols: symbols(), colors: colors(), columns: columns(), mouse: mouse(), key_map: key_map(), } } } impl Config { pub fn new(path: &Option<PathBuf>) -> Result<Self, Box<dyn Error>> { let builder = config::Config::builder(); let builder = match path { Some(path) => builder .add_source(config::File::from(path.clone()).format(config::FileFormat::Toml)), None => { let path = Self::get_default_config_path()?; if !path.exists() { log::info!("Config file not found. Using default configuration."); return Ok(Self::default()); } builder.add_source(config::File::from(path).format(config::FileFormat::Toml)) } }; let config = builder.build()?.try_deserialize::<Config>()?; Ok(config) } fn get_default_config_path() -> Result<PathBuf, Box<dyn Error>> { match dirs::config_dir() { Some(conf_dir) => Ok(conf_dir.join(format!("{CMD}/config.toml"))), None => Err(Box::<dyn Error>::from( "Couldn't determine default config directory.", )), } } } impl Default for Colors { fn default() -> Self { Self { bg: reset(), fg: white(), border_fg: white(), border_bg: reset(), bg_focused: reset(), fg_focused: white(), border_fg_focused: green(), border_bg_focused: reset(), bg_highlighted: green(), fg_highlighted: black(), } } } fn colors() -> Colors { Colors::default() } const fn reset() -> Color { Color::Reset } const fn black() -> Color { Color::Black } const fn white() -> Color { Color::White } const fn green() -> Color { Color::Green } const fn sorting() -> bool { false } fn symbols() -> Symbols { Symbols::default() } fn highlight_symbol() -> String { String::new() } fn node_closed_symbol() -> String { String::from(" ⏷ ") } fn node_open_symbol() -> String { String::from(" ▶ ") } fn node_no_children_symbol() -> String { String::from(" ") } const fn columns() -> usize { 3 } const fn mouse() -> bool { true } fn key_map() -> HashMap<KeyCombination, KeyBindEvent> { let mut map = HashMap::new(); map.insert(key!(left), KeyBindEvent::FocusLeft); map.insert(key!(right), KeyBindEvent::FocusRight); map.insert(key!(down), KeyBindEvent::FocusDown); map.insert(key!(up), KeyBindEvent::FocusUp); map.insert(key!(h), KeyBindEvent::FocusLeft); map.insert(key!(l), KeyBindEvent::FocusRight); map.insert(key!(j), KeyBindEvent::FocusDown); map.insert(key!(k), KeyBindEvent::FocusUp); map.insert(key!(shift - up), KeyBindEvent::MenuUp); map.insert(key!(shift - down), KeyBindEvent::MenuDown); map.insert(key!(shift - k), KeyBindEvent::MenuUp); map.insert(key!(shift - j), KeyBindEvent::MenuDown); map.insert(key!(ctrl - c), KeyBindEvent::Quit); map.insert(key!(q), KeyBindEvent::Quit); map.insert(key!(enter), KeyBindEvent::Activate); map.insert(key!(space), KeyBindEvent::Activate); map }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/app.rs
src/app.rs
use indexmap::IndexMap; use ratatui::layout::{Position, Rect}; use std::{ cell::{Ref, RefMut}, collections::HashMap, error, sync::{Arc, Mutex, MutexGuard}, }; use system_tray::client::ActivateRequest; use system_tray::{ client::{Client, Event}, item::StatusNotifierItem, menu::TrayMenu, }; use tui_tree_widget::TreeState; use tokio::sync::broadcast::Receiver; use crate::wrappers::{FindMenuByUsize, GetTitle, Id, SniState}; use crate::Config; pub type BoxStack = Vec<(i32, Rect)>; /// Application result type. pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>; #[derive(Debug)] pub struct Layout { pub rows: Vec<Vec<usize>>, pub last_col: usize } impl Layout { pub fn new() -> Self { Self { rows: Vec::default(), last_col: 0, } } } /// Application. #[derive(Debug)] pub struct App { pub running: bool, /// Config pub config: Config, /// system-tray client pub client: Client, /// states saved for each [StatusNotifierItem] and their [TrayMenu] pub sni_states: IndexMap<String, SniState>, // for the StatusNotifierItem // currently focused sni item info pub focused_sni_index: usize, pub focused_sni_key: String, /// items map from system-tray pub items: Arc<Mutex<HashMap<String, (StatusNotifierItem, Option<TrayMenu>)>>>, pub tray_rx: Mutex<Receiver<Event>>, pub layout: Layout, } impl App { /// Constructs a new instance of [`App`]. pub fn new(client: Client, config: Config) -> Self { Self { running: true, config, tray_rx: Mutex::new(client.subscribe()), items: client.items(), sni_states: IndexMap::default(), client, focused_sni_index: 0, focused_sni_key: String::default(), layout: Layout::new() } } /// Updating states pub fn update(&mut self) { // sync key to index if let Some(key) = self.get_focused_sni_key() { self.focused_sni_key = key.to_owned(); } // create a buffer for items keys and their titles(for sorting) let mut buffer = IndexMap::new(); if let Some(items) = self.get_items() { buffer = items .iter() .map(|(k, v)| (k.to_owned(), v.0.get_title().to_owned())) .collect(); } // Add sni states if there are in new items for (key, _) in &buffer { self.sni_states .entry(key.to_owned()) .or_insert_with(|| SniState::new()); } // Remove states that aren't in new items self.sni_states.retain(|key, _| buffer.contains_key(key)); // Sort by titles if self.config.sorting { self.sni_states .sort_by(|k1, _, k2, _| buffer[k1].cmp(&buffer[k2])); } // sync index to key back if let Some(index) = self.sni_states.get_index_of(&self.focused_sni_key) { self.focused_sni_index = index; } self.layout.rows = (0..self.sni_states.len()) .collect::<Vec<_>>() .chunks(self.config.columns) .map(|chunk| chunk.to_vec()) .collect(); // Synchronize focus self.sync_focus(); } /// Set running to false to quit the application. pub fn quit(&mut self) { self.running = false; } pub fn get_items( &self, ) -> Option<MutexGuard<HashMap<String, (StatusNotifierItem, Option<TrayMenu>)>>> { match self.items.lock() { Ok(items) => Some(items), Err(_) => None, } } pub fn get_focused_sni_key(&self) -> Option<&String> { self.sni_states .get_index(*self.get_focused_sni_index()) .map(|(k, _)| k) } pub fn get_focused_sni_index(&self) -> &usize { &self.focused_sni_index } pub fn get_focused_sni_state(&self) -> Option<&SniState> { let (_, v) = self.sni_states.get_index(self.focused_sni_index)?; return Some(v); } pub fn get_focused_sni_state_mut(&mut self) -> Option<&mut SniState> { let (_, v) = self.sni_states.get_index_mut(self.focused_sni_index)?; return Some(v); } pub fn get_focused_sni_key_by_position(&mut self, pos: Position) -> Option<String> { self.sni_states .iter() .find(|(_, v)| v.rect.contains(pos)) .map(|(k, _)| k.to_string()) } pub fn get_focused_tree_state(&self) -> Option<Ref<TreeState<Id>>> { self.get_focused_sni_state() .map(|sni| sni.tree_state.borrow()) } pub fn get_focused_tree_state_mut(&self) -> Option<RefMut<TreeState<Id>>> { self.get_focused_sni_state() .map(|sni| sni.tree_state.borrow_mut()) } pub fn move_focus(&mut self, direction: FocusDirection) -> Option<()> { let total = self.layout.rows.iter().map(|r| r.len()).sum::<usize>(); if total <= 1 { return Some(()); } let index = self.focused_sni_index; let cols = self.config.columns; let last_row_index = self.layout.rows.len() - 1; let last_row_len = self.layout.rows[last_row_index].len(); let row = index / cols; let col = index % cols; let new_index = match direction { FocusDirection::Left => { if index > 0 { index - 1 } else { total - 1 } } FocusDirection::Right => { if index + 1 < total { index + 1 } else { 0 } } FocusDirection::Up => { let target_row = if row == 0 { last_row_index } else { row - 1 }; let target_len = if target_row == last_row_index { last_row_len } else { cols }; let clamped_col = self.layout.last_col.min(target_len - 1); target_row * cols + clamped_col } FocusDirection::Down => { let target_row = if row == last_row_index { 0 } else { row + 1 }; let target_len = if target_row == last_row_index { last_row_len } else { cols }; let clamped_col = self.layout.last_col.min(target_len - 1); target_row * cols + clamped_col } }; match direction { FocusDirection::Up | FocusDirection::Down => self.layout.last_col = col, _ => self.layout.last_col = new_index % cols } self.focused_sni_index = new_index; self.focused_sni_key = self .sni_states .get_index(new_index) .unwrap() .0 .clone(); self.sni_states.get_index_mut(index)?.1.set_focused(false); self.sync_focus(); Some(()) } pub fn sync_focus(&mut self) { if let Some(val) = self.sni_states.get_mut(&self.focused_sni_key) { val.set_focused(true); } } pub async fn activate_menu_item( &self, ids: &[Id], tree_state: &mut TreeState<Id>, ) -> Option<()> { log::debug!("Entered activate_menu_item"); let sni_key = self.get_focused_sni_key()?; log::debug!("Activating menu item with key: {}", &sni_key); let map = self.get_items()?; let (sni, menu) = map.get(sni_key)?; let menu = match menu { Some(menu) => menu, None => return None, }; let item = menu.find_menu_by_usize(ids)?; if item.submenu.is_empty() { if let Some(path) = &sni.menu { let activate_request = ActivateRequest::MenuItem { address: sni_key.to_string(), menu_path: path.to_string(), submenu_id: item.id, }; let res = self.client.activate(activate_request).await; log::debug!("Result of activating an item: {:?}", res); let _ = self .client .about_to_show_menuitem(sni_key.to_string(), path.to_string(), 0) .await; } } else { tree_state.toggle(ids.to_vec()); } Some(()) } } pub enum FocusDirection { Down, Up, Right, Left, }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/wrappers.rs
src/wrappers.rs
use std::cell::RefCell; use ratatui::widgets::{Block, StatefulWidget}; use ratatui::{ buffer::Buffer, layout::{self, Rect}, style::{Color, Style}, widgets::Widget, }; use system_tray::client::{Event, UpdateEvent}; use system_tray::{ item::StatusNotifierItem, menu::{MenuItem, TrayMenu}, }; use tui_tree_widget::{Tree, TreeItem, TreeState}; use crate::config::Config; pub type Id = usize; #[derive(Debug)] pub struct SniState { pub rect: Rect, pub focused: bool, pub tree_state: RefCell<TreeState<Id>>, } impl SniState { pub fn new() -> Self { Self { rect: Rect::default(), focused: false, tree_state: RefCell::default(), } } pub fn set_rect(&mut self, rect: Rect) { self.rect = rect; } pub fn set_focused(&mut self, focused: bool) { self.focused = focused; } } pub trait GetTitle { fn get_title(&self) -> &String; } impl GetTitle for StatusNotifierItem { fn get_title(&self) -> &String { if let Some(title) = &self.title { if !title.is_empty() { return &title; } } if let Some(tooltip) = &self.tool_tip { return &tooltip.title; } &self.id } } /// Wrapper around set of [StatusNotifierItem] and [TrayMenu] #[derive(Debug)] pub struct Item<'a> { pub sni_state: &'a SniState, pub item: &'a StatusNotifierItem, pub menu: &'a Option<TrayMenu>, config: &'a Config, pub rect: Rect, } impl<'a> Item<'a> { pub fn new( sni_state: &'a SniState, (item, menu): &'a (StatusNotifierItem, Option<TrayMenu>), config: &'a Config, ) -> Self { Self { sni_state, item, menu, config, rect: Rect::default(), } } pub fn set_rect(&mut self, rect: Rect) { self.rect = rect; } pub fn get_colors(&self) -> (Color, Color) { let colors = &self.config.colors; let mut bg = colors.bg; let mut fg = colors.fg; if self.sni_state.focused { bg = colors.bg_focused; fg = colors.fg_focused; } (bg, fg) } pub fn get_highlight_colors(&self) -> (Color, Color) { let colors = &self.config.colors; (colors.bg_highlighted, colors.fg_highlighted) } pub fn get_border_color(&self) -> (Color, Color) { let colors = &self.config.colors; match self.sni_state.focused { true => (colors.border_bg_focused, colors.border_fg_focused), false => (colors.border_bg, colors.border_fg), } } } impl Widget for Item<'_> { fn render(self, area: layout::Rect, buf: &mut Buffer) { let title = self.item.get_title().clone(); let (bg, fg) = self.get_colors(); let (bg_h, fg_h) = self.get_highlight_colors(); let (border_bg, border_fg) = self.get_border_color(); let symbols = &self.config.symbols; if let Some(menu) = self.menu { let children = menuitems_to_treeitems(&menu.submenus); let tree = Tree::new(&children); if let Ok(mut tree) = tree { tree = tree .style(Style::default().bg(bg).fg(fg)) .highlight_style(Style::default().bg(bg_h).fg(fg_h)) .highlight_symbol(&symbols.highlight_symbol) .node_open_symbol(&symbols.node_open_symbol) .node_closed_symbol(&symbols.node_closed_symbol) .node_no_children_symbol(&symbols.node_no_children_symbol); tree = tree.block( Block::bordered() .title(title) .border_style(Style::default().fg(border_fg).bg(border_bg)), ); StatefulWidget::render( tree, area, buf, &mut self.sni_state.tree_state.borrow_mut(), ); } } else { let block = Block::default().title(title).style(Style::default()); block.render(area, buf); } } } fn menuitem_to_treeitem(id: usize, menu_item: &MenuItem) -> Option<TreeItem<Id>> { if menu_item.submenu.is_empty() { match &menu_item.label { Some(label) => return Some(TreeItem::new_leaf(id, label.clone())), None => return None, } } let children = menuitems_to_treeitems(&menu_item.submenu); let root = TreeItem::new( id, menu_item.label.clone().unwrap_or(String::from("no_label")), children, ); root.ok() } fn menuitems_to_treeitems(menu_items: &Vec<MenuItem>) -> Vec<TreeItem<Id>> { menu_items .iter() .enumerate() .map(|(index, menu_item)| menuitem_to_treeitem(index, menu_item)) .filter_map(|x| x) .collect() } pub trait FindMenuByUsize { fn find_menu_by_usize(&self, ids: &[Id]) -> Option<&MenuItem>; } impl FindMenuByUsize for TrayMenu { fn find_menu_by_usize(&self, ids: &[Id]) -> Option<&MenuItem> { if ids.len() == 0 { return None; } let mut result: &MenuItem = self.submenus.get(ids[0])?; let mut submenus = &result.submenu; for i in ids.iter().skip(1) { result = submenus.get(*i)?; submenus = &result.submenu; } Some(result) } } pub struct LoggableEvent<'a>(pub &'a system_tray::client::Event); impl std::fmt::Display for LoggableEvent<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.0 { Event::Update(dest, update_event) => { write!( f, "{} Update Event for {}", update_event_variant(&update_event), dest ) } Event::Add(dest, sni) => write!(f, "Add Event for {}: {}", dest, sni.get_title()), Event::Remove(dest) => write!(f, "Remove Event for {}", dest), } } } fn update_event_variant(event: &UpdateEvent) -> &'static str { match event { UpdateEvent::AttentionIcon(_) => "AttentionIcon", UpdateEvent::Icon { icon_name: _, icon_pixmap: _, } => "Icon", UpdateEvent::OverlayIcon(_) => "OverlayIcon", UpdateEvent::Status(_) => "Status", UpdateEvent::Title(_) => "Title", UpdateEvent::Tooltip(_) => "Tooltip", UpdateEvent::Menu(_) => "Menu", UpdateEvent::MenuDiff(_) => "MenuDiff", UpdateEvent::MenuConnect(_) => "MenuConnect", } }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/event.rs
src/event.rs
use std::collections::HashMap; use crokey::KeyCombination; use crossterm::event::{Event as CrosstermEvent, MouseEvent, KeyEventKind}; use futures::{FutureExt, StreamExt}; use tokio::sync::mpsc; use crate::app::AppResult; use crate::config::KeyBindEvent; /// Terminal events. #[derive(Clone, Copy, Debug)] pub enum Event { /// Key press. Key(KeyBindEvent), /// Mouse click/scroll. Mouse(MouseEvent), /// Terminal resize. Resize(u16, u16), /// Loosing focus, doesnt' happen however :( FocusLost, } /// Terminal event handler. #[allow(dead_code)] #[derive(Debug)] pub struct EventHandler { /// Event sender channel. sender: mpsc::UnboundedSender<Event>, /// Event receiver channel. receiver: mpsc::UnboundedReceiver<Event>, /// Event handler thread. handler: tokio::task::JoinHandle<()>, } impl EventHandler { /// Constructs a new instance of [`EventHandler`]. pub fn new(use_mouse: bool, keymap: HashMap<KeyCombination, KeyBindEvent>) -> Self { let (sender, receiver) = mpsc::unbounded_channel(); let _sender = sender.clone(); let handler = tokio::spawn(async move { let mut reader = crossterm::event::EventStream::new(); loop { let crossterm_event = reader.next().fuse(); tokio::select! { _ = _sender.closed() => { break; } Some(Ok(evt)) = crossterm_event => { match evt { CrosstermEvent::Key(key) => { if key.kind == KeyEventKind::Press { let key_bind = KeyCombination::from(key); if let Some(event) = keymap.get(&key_bind) { _sender.send(Event::Key(*event)).unwrap(); } } }, CrosstermEvent::Mouse(mouse) => { if use_mouse { _sender.send(Event::Mouse(mouse)).unwrap(); } }, CrosstermEvent::Resize(x, y) => { _sender.send(Event::Resize(x, y)).unwrap(); }, CrosstermEvent::FocusLost => { _sender.send(Event::FocusLost).unwrap(); }, CrosstermEvent::FocusGained => { }, CrosstermEvent::Paste(_) => { }, } } }; } }); Self { sender, receiver, handler, } } /// Receive the next event from the handler thread. /// /// This function will always block the current thread if /// there is no data available and it's possible for more data to be sent. pub async fn next(&mut self) -> AppResult<Event> { self.receiver .recv() .await .ok_or(Box::new(std::io::Error::new( std::io::ErrorKind::Other, "This is an IO error", ))) } }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/cli.rs
src/cli.rs
use clap::value_parser; use clap::Parser; use clap_complete::Shell; #[derive(Parser, Debug)] #[command(version, about, long_about=None)] pub struct Cli { /// Path to config file #[arg(short, long, value_name = "CONFIG_PATH", value_parser = value_parser!(std::path::PathBuf))] pub config_path: Option<std::path::PathBuf>, /// Prints debug information to app.log file #[arg(short, long, action = clap::ArgAction::SetTrue, default_value_t = false)] pub debug: bool, /// Generates completion scripts for the specified shell #[arg(long, value_name = "SHELL", value_enum)] pub completions: Option<Shell>, }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/ui.rs
src/ui.rs
use std::iter::repeat_n; use ratatui::{ layout::{Constraint, Layout, Rect}, Frame, }; use crate::app::App; use crate::wrappers::Item; /// Renders the user interface widgets. pub fn render(app: &mut App, frame: &mut Frame) { let mut rectangles: Vec<Rect> = Vec::default(); if let Some(items) = app.get_items() { let mut items_vec: Vec<Item> = Vec::new(); app.sni_states.iter().for_each(|(k, v)| { if let Some(pair) = items.get(k) { let item = Item::new(v, pair, &app.config); items_vec.push(item); } }); rectangles = { let size = items_vec.len(); let columns: usize = app.config.columns; let rows: usize = (size + columns - 1) / columns; let mut result = Vec::new(); let row_layout = Layout::vertical(repeat_n(Constraint::Fill(1), rows)).split(frame.area()); for r in 0..rows { let start = r * columns; let end = (start + columns).min(size); let items_n = end - start; let col_layout = Layout::horizontal(repeat_n(Constraint::Fill(1), items_n)).split(row_layout[r]); result.extend_from_slice(&col_layout[..items_n]); } result }; render_items(frame, items_vec, rectangles.iter()); } app.sni_states .values_mut() .zip(rectangles.iter()) .for_each(|(v, ar)| v.set_rect(*ar)); } fn render_items(frame: &mut Frame, items: Vec<Item>, rects_iter: std::slice::Iter<'_, Rect>) { items.into_iter().zip(rects_iter).for_each(|(item, ar)| { frame.render_widget(item, *ar); }); }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/main.rs
src/main.rs
use std::{fs::File, io}; use crate::{ app::{App, AppResult}, cli::Cli, config::Config, event::{Event, EventHandler}, handler::{handle_key_events, handle_mouse_event}, tui::Tui, wrappers::LoggableEvent, }; use clap::{CommandFactory, Parser}; use clap_complete::generate; use ratatui::{backend::CrosstermBackend, Terminal}; use simplelog::{CombinedLogger, Config as Conf, LevelFilter, WriteLogger}; use system_tray::{client::Client, item::StatusNotifierItem, menu::TrayMenu}; pub mod app; pub mod cli; pub mod config; pub mod event; pub mod handler; pub mod tui; pub mod ui; pub mod wrappers; static CMD: &str = "tray-tui"; #[tokio::main] async fn main() -> AppResult<()> { let cli = Cli::parse(); if let Some(shell) = cli.completions { let mut cmd = Cli::command(); let mut out = io::stdout(); generate(shell, &mut cmd, CMD, &mut out); return Ok(()); } if cli.debug { CombinedLogger::init(vec![WriteLogger::new( LevelFilter::Debug, Conf::default(), File::create("app.log").unwrap(), )]) .unwrap(); } let config = Config::new(&cli.config_path)?; let client = Client::new().await.unwrap(); log::info!("Client is initialized"); let mut tray_rx = client.subscribe(); log::info!( "status: {}, traymenu {}, client {}", size_of::<StatusNotifierItem>(), size_of::<TrayMenu>(), size_of_val(&client) ); // Create an application. let mut app = App::new(client, config); let map = app.config.key_map.clone(); // Initialize the terminal user interface. let backend = CrosstermBackend::new(io::stdout()); let terminal = Terminal::new(backend)?; let events = EventHandler::new(app.config.mouse, map); let mut tui = Tui::new(terminal, events); tui.init()?; log::info!("Initialized TUI"); tui.draw(&mut app)?; while app.running { tui.draw(&mut app)?; tokio::select! { Ok(update) = tray_rx.recv() => { log::debug!("{}", LoggableEvent(&update)); app.update(); if let system_tray::client::Event::Remove(_) = update { app.sync_focus(); } } Ok(event) = tui.events.next() => { log::debug!("Key event: {:?}", &event); match event { Event::Key(key_event) => handle_key_events(key_event, &mut app).await?, Event::Mouse(mouse_event) => { handle_mouse_event(mouse_event, &mut app).await? }, Event::Resize(_, _) => {tui.draw(&mut app).unwrap()} Event::FocusLost => { // doensn't work for some reason } } } }; } log::info!("Exiting application"); tui.exit()?; Ok(()) }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/tui.rs
src/tui.rs
use crate::app::{App, AppResult}; use crate::event::EventHandler; use crate::ui; use crossterm::event::{DisableMouseCapture, EnableMouseCapture}; use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}; use ratatui::backend::Backend; use ratatui::Terminal; use std::io; use std::panic; /// Representation of a terminal user interface. /// /// It is responsible for setting up the terminal, /// initializing the interface and handling the draw events. #[derive(Debug)] pub struct Tui<B: Backend> { /// Interface to the Terminal. terminal: Terminal<B>, /// Terminal event handler. pub events: EventHandler, } impl<B: Backend> Tui<B> { /// Constructs a new instance of [`Tui`]. pub fn new(terminal: Terminal<B>, events: EventHandler) -> Self { Self { terminal, events } } /// Initializes the terminal interface. /// /// It enables the raw mode and sets terminal properties. pub fn init(&mut self) -> AppResult<()> { terminal::enable_raw_mode()?; crossterm::execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?; // Define a custom panic hook to reset the terminal properties. // This way, you won't have your terminal messed up if an unexpected error happens. let panic_hook = panic::take_hook(); panic::set_hook(Box::new(move |panic| { Self::reset().expect("failed to reset the terminal"); panic_hook(panic); })); self.terminal.hide_cursor()?; self.terminal.clear()?; Ok(()) } /// [`Draw`] the terminal interface by [`rendering`] the widgets. /// /// [`Draw`]: ratatui::Terminal::draw /// [`rendering`]: crate::ui::render pub fn draw(&mut self, app: &mut App) -> AppResult<()> { self.terminal.draw(|frame| ui::render(app, frame))?; Ok(()) } /// Resets the terminal interface. /// /// This function is also used for the panic hook to revert /// the terminal properties if unexpected errors occur. fn reset() -> AppResult<()> { terminal::disable_raw_mode()?; crossterm::execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?; Ok(()) } /// Exits the terminal interface. /// /// It disables the raw mode and reverts back the terminal properties. pub fn exit(&mut self) -> AppResult<()> { Self::reset()?; self.terminal.show_cursor()?; Ok(()) } }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
Levizor/tray-tui
https://github.com/Levizor/tray-tui/blob/fe96a8111d711dcecf0fe31922fb122e0ef8b80e/src/handler.rs
src/handler.rs
use crate::{ app::{App, AppResult, FocusDirection}, config::KeyBindEvent, }; use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; use ratatui::layout::Position; /// Handles the key events and updates the state of [`App`]. pub async fn handle_key_events(key_bind_event: KeyBindEvent, app: &mut App) -> AppResult<()> { match key_bind_event { // Exit application on `ESC` or `q` KeyBindEvent::Quit => { app.quit(); } KeyBindEvent::FocusLeft => { app.move_focus(FocusDirection::Left); } KeyBindEvent::FocusRight => { app.move_focus(FocusDirection::Right); } KeyBindEvent::FocusDown => { app.move_focus(FocusDirection::Down); } KeyBindEvent::FocusUp => { app.move_focus(FocusDirection::Up); } _ => {} } let tree_state = app.get_focused_tree_state_mut(); if tree_state.is_none() { return Ok(()); } let mut tree_state = &mut tree_state.unwrap(); match key_bind_event { KeyBindEvent::Activate => { let ids = tree_state.selected().to_vec(); let _ = app.activate_menu_item(&ids, &mut tree_state).await; } KeyBindEvent::MenuDown => { if !tree_state.key_down() { tree_state.select_first(); } } KeyBindEvent::MenuUp => { if !tree_state.key_up() { tree_state.select_last(); } } _ => {} } Ok(()) } fn get_pos(mouse_event: MouseEvent) -> Position { Position::new(mouse_event.column, mouse_event.row) } async fn handle_click(mouse_event: MouseEvent, app: &App) -> Option<()> { let pos = get_pos(mouse_event); let mut tree_state = &mut app.get_focused_tree_state_mut()?; let ids = tree_state.rendered_at(pos)?.to_vec(); app.activate_menu_item(&ids, &mut tree_state).await?; None } fn handle_scroll(mouse_event: MouseEvent, app: &App) -> Option<()> { let mut tree_state = app.get_focused_tree_state_mut()?; match mouse_event.kind { MouseEventKind::ScrollUp => { tree_state.scroll_up(1); } MouseEventKind::ScrollDown => { tree_state.scroll_down(1); } _ => {} } None } async fn handle_move(mouse_event: MouseEvent, app: &mut App) -> Option<()> { let pos = get_pos(mouse_event); if let Some((_, sni_state)) = app.sni_states.get_index_mut(app.focused_sni_index) { if sni_state.rect.contains(pos) { let mut tree_state = app.get_focused_tree_state_mut()?; let rendered = tree_state.rendered_at(pos)?.to_owned(); tree_state.select(rendered.to_vec()); return None; } else { sni_state.set_focused(false); app.focused_sni_index = 0; } } if let Some(k) = &app.get_focused_sni_key_by_position(pos) { if let Some(state_tree) = app.sni_states.get_mut(k) { state_tree.set_focused(true); app.focused_sni_index = app.sni_states.get_index_of(k).unwrap_or(0); } } Some(()) } pub async fn handle_mouse_event(mouse_event: MouseEvent, app: &mut App) -> AppResult<()> { match mouse_event.kind { MouseEventKind::Down(MouseButton::Left) => { let _ = handle_click(mouse_event, app).await; } MouseEventKind::Down(MouseButton::Right) => {} MouseEventKind::Down(MouseButton::Middle) => {} MouseEventKind::Moved => { let _ = handle_move(mouse_event, app).await; } MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => { let _ = handle_scroll(mouse_event, app); } _ => {} } Ok(()) }
rust
MIT
fe96a8111d711dcecf0fe31922fb122e0ef8b80e
2026-01-04T20:23:48.573203Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/cdylib/src/lib.rs
cdylib/src/lib.rs
#![no_std] // Keep this explicit #[allow(unused_extern_crates)] extern crate unwinding;
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/lib.rs
src/lib.rs
#![doc = include_str!("../README.md")] // We use `non_exhaustive_omitted_patterns_lint` which is a nightly lint. #![allow(unknown_lints)] #![cfg_attr( any( feature = "personality", feature = "personality-dummy", feature = "panicking", feature = "panic-handler-dummy" ), allow(internal_features) )] #![cfg_attr( any(feature = "personality", feature = "personality-dummy"), feature(lang_items) )] #![cfg_attr( any(feature = "panicking", feature = "panic-handler-dummy"), feature(core_intrinsics) )] #![cfg_attr(feature = "panic-handler", feature(thread_local))] #![no_std] #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "unwinder")] mod unwinder; #[cfg(all(feature = "unwinder", feature = "fde-custom"))] pub use unwinder::custom_eh_frame_finder; pub mod abi; mod arch; mod util; #[cfg(feature = "print")] pub mod print; #[cfg(feature = "personality")] mod personality; #[cfg(all(not(feature = "personality"), feature = "personality-dummy"))] mod personality_dummy; #[cfg(feature = "panic")] pub mod panic; #[cfg(feature = "panicking")] pub mod panicking; #[cfg(feature = "panic-handler")] mod panic_handler; #[cfg(all(not(feature = "panic-handler"), feature = "panic-handler-dummy"))] mod panic_handler_dummy; #[cfg(feature = "system-alloc")] mod system_alloc;
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/panic_handler_dummy.rs
src/panic_handler_dummy.rs
use core::panic::PanicInfo; #[panic_handler] fn panic(_info: &PanicInfo<'_>) -> ! { crate::util::abort(); }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/abi.rs
src/abi.rs
use core::ffi::c_void; use core::ops; use crate::util::*; #[cfg(not(feature = "unwinder"))] use crate::arch::Arch; #[cfg(feature = "unwinder")] pub use crate::unwinder::*; #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq)] pub struct UnwindReasonCode(pub c_int); #[allow(unused)] impl UnwindReasonCode { pub const NO_REASON: Self = Self(0); pub const FOREIGN_EXCEPTION_CAUGHT: Self = Self(1); pub const FATAL_PHASE2_ERROR: Self = Self(2); pub const FATAL_PHASE1_ERROR: Self = Self(3); pub const NORMAL_STOP: Self = Self(4); pub const END_OF_STACK: Self = Self(5); pub const HANDLER_FOUND: Self = Self(6); pub const INSTALL_CONTEXT: Self = Self(7); pub const CONTINUE_UNWIND: Self = Self(8); } #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq)] pub struct UnwindAction(pub c_int); impl UnwindAction { pub const SEARCH_PHASE: Self = Self(1); pub const CLEANUP_PHASE: Self = Self(2); pub const HANDLER_FRAME: Self = Self(4); pub const FORCE_UNWIND: Self = Self(8); pub const END_OF_STACK: Self = Self(16); } impl ops::BitOr for UnwindAction { type Output = Self; #[inline] fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl UnwindAction { #[inline] pub const fn empty() -> Self { Self(0) } #[inline] pub const fn contains(&self, other: Self) -> bool { self.0 & other.0 != 0 } } pub type UnwindExceptionCleanupFn = unsafe extern "C" fn(UnwindReasonCode, *mut UnwindException); pub type UnwindStopFn = unsafe extern "C" fn( c_int, UnwindAction, u64, *mut UnwindException, &mut UnwindContext<'_>, *mut c_void, ) -> UnwindReasonCode; #[cfg(not(feature = "unwinder"))] #[repr(C)] pub struct UnwindException { pub exception_class: u64, pub exception_cleanup: Option<UnwindExceptionCleanupFn>, private: [usize; Arch::UNWIND_PRIVATE_DATA_SIZE], } pub type UnwindTraceFn = extern "C" fn(ctx: &UnwindContext<'_>, arg: *mut c_void) -> UnwindReasonCode; #[cfg(not(feature = "unwinder"))] #[repr(C)] pub struct UnwindContext<'a> { opaque: usize, phantom: core::marker::PhantomData<&'a ()>, } pub type PersonalityRoutine = unsafe extern "C" fn( c_int, UnwindAction, u64, *mut UnwindException, &mut UnwindContext<'_>, ) -> UnwindReasonCode; #[cfg(not(feature = "unwinder"))] macro_rules! binding { () => {}; (unsafe extern $abi: literal fn $name: ident ($($arg: ident : $arg_ty: ty),*$(,)?) $(-> $ret: ty)?; $($rest: tt)*) => { unsafe extern $abi { pub unsafe fn $name($($arg: $arg_ty),*) $(-> $ret)?; } binding!($($rest)*); }; (extern $abi: literal fn $name: ident ($($arg: ident : $arg_ty: ty),*$(,)?) $(-> $ret: ty)?; $($rest: tt)*) => { unsafe extern $abi { pub safe fn $name($($arg: $arg_ty),*) $(-> $ret)?; } binding!($($rest)*); }; } #[cfg(feature = "unwinder")] macro_rules! binding { () => {}; (unsafe extern $abi: literal fn $name: ident ($($arg: ident : $arg_ty: ty),*$(,)?) $(-> $ret: ty)?; $($rest: tt)*) => { const _: unsafe extern $abi fn($($arg_ty),*) $(-> $ret)? = $name; }; (extern $abi: literal fn $name: ident ($($arg: ident : $arg_ty: ty),*$(,)?) $(-> $ret: ty)?; $($rest: tt)*) => { const _: extern $abi fn($($arg_ty),*) $(-> $ret)? = $name; }; } binding! { extern "C" fn _Unwind_GetGR(unwind_ctx: &UnwindContext<'_>, index: c_int) -> usize; extern "C" fn _Unwind_GetCFA(unwind_ctx: &UnwindContext<'_>) -> usize; extern "C" fn _Unwind_SetGR( unwind_ctx: &mut UnwindContext<'_>, index: c_int, value: usize, ); extern "C" fn _Unwind_GetIP(unwind_ctx: &UnwindContext<'_>) -> usize; extern "C" fn _Unwind_GetIPInfo( unwind_ctx: &UnwindContext<'_>, ip_before_insn: &mut c_int, ) -> usize; extern "C" fn _Unwind_SetIP( unwind_ctx: &mut UnwindContext<'_>, value: usize, ); extern "C" fn _Unwind_GetLanguageSpecificData(unwind_ctx: &UnwindContext<'_>) -> *mut c_void; extern "C" fn _Unwind_GetRegionStart(unwind_ctx: &UnwindContext<'_>) -> usize; extern "C" fn _Unwind_GetTextRelBase(unwind_ctx: &UnwindContext<'_>) -> usize; extern "C" fn _Unwind_GetDataRelBase(unwind_ctx: &UnwindContext<'_>) -> usize; extern "C" fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void; unsafe extern "C-unwind" fn _Unwind_RaiseException( exception: *mut UnwindException, ) -> UnwindReasonCode; unsafe extern "C-unwind" fn _Unwind_ForcedUnwind( exception: *mut UnwindException, stop: UnwindStopFn, stop_arg: *mut c_void, ) -> UnwindReasonCode; unsafe extern "C-unwind" fn _Unwind_Resume(exception: *mut UnwindException) -> !; unsafe extern "C-unwind" fn _Unwind_Resume_or_Rethrow( exception: *mut UnwindException, ) -> UnwindReasonCode; unsafe extern "C" fn _Unwind_DeleteException(exception: *mut UnwindException); extern "C-unwind" fn _Unwind_Backtrace( trace: UnwindTraceFn, trace_argument: *mut c_void, ) -> UnwindReasonCode; }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/panic.rs
src/panic.rs
use alloc::boxed::Box; use core::any::Any; use core::mem::MaybeUninit; use crate::abi::*; #[cfg(feature = "panic-handler")] pub use crate::panic_handler::*; use crate::panicking::Exception; static CANARY: u8 = 0; #[repr(transparent)] struct RustPanic(Box<dyn Any + Send>, DropGuard); struct DropGuard; impl Drop for DropGuard { fn drop(&mut self) { #[cfg(feature = "panic-handler")] { drop_panic(); } crate::util::abort(); } } #[repr(C)] struct ExceptionWithPayload { exception: MaybeUninit<UnwindException>, // See rust/library/panic_unwind/src/gcc.rs for the canary values canary: *const u8, payload: RustPanic, } unsafe impl Exception for RustPanic { const CLASS: [u8; 8] = *b"MOZ\0RUST"; fn wrap(this: Self) -> *mut UnwindException { Box::into_raw(Box::new(ExceptionWithPayload { exception: MaybeUninit::uninit(), canary: &CANARY, payload: this, })) as *mut UnwindException } unsafe fn unwrap(ex: *mut UnwindException) -> Self { let ex = ex as *mut ExceptionWithPayload; let canary = unsafe { core::ptr::addr_of!((*ex).canary).read() }; if !core::ptr::eq(canary, &CANARY) { // This is a Rust exception but not generated by us. #[cfg(feature = "panic-handler")] { foreign_exception(); } crate::util::abort(); } let ex = unsafe { Box::from_raw(ex) }; ex.payload } } pub fn begin_panic(payload: Box<dyn Any + Send>) -> UnwindReasonCode { crate::panicking::begin_panic(RustPanic(payload, DropGuard)) } pub fn catch_unwind<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>> { #[cold] fn process_panic(p: Option<RustPanic>) -> Box<dyn Any + Send> { match p { None => { #[cfg(feature = "panic-handler")] { foreign_exception(); } crate::util::abort(); } Some(e) => { #[cfg(feature = "panic-handler")] { panic_caught(); } core::mem::forget(e.1); e.0 } } } crate::panicking::catch_unwind(f).map_err(process_panic) }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/util.rs
src/util.rs
use gimli::{EndianSlice, NativeEndian, Pointer}; pub type StaticSlice = EndianSlice<'static, NativeEndian>; pub unsafe fn get_unlimited_slice<'a>(start: *const u8) -> &'a [u8] { // Create the largest possible slice for this address. let start = start as usize; let end = start.saturating_add(isize::MAX as _); let len = end - start; unsafe { core::slice::from_raw_parts(start as *const _, len) } } pub unsafe fn deref_pointer(ptr: Pointer) -> usize { match ptr { Pointer::Direct(x) => x as _, Pointer::Indirect(x) => unsafe { *(x as *const _) }, } } #[cfg(feature = "libc")] pub use libc::c_int; #[cfg(not(feature = "libc"))] #[allow(non_camel_case_types)] pub type c_int = i32; #[cfg(all( any(feature = "panic", feature = "panic-handler-dummy"), feature = "libc" ))] pub fn abort() -> ! { unsafe { libc::abort() }; } #[cfg(all( any(feature = "panic", feature = "panic-handler-dummy"), not(feature = "libc") ))] pub fn abort() -> ! { core::intrinsics::abort(); }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/personality.rs
src/personality.rs
// References: // https://github.com/rust-lang/rust/blob/c4be230b4a30eb74e3a3908455731ebc2f731d3d/library/panic_unwind/src/gcc.rs // https://github.com/rust-lang/rust/blob/c4be230b4a30eb74e3a3908455731ebc2f731d3d/library/panic_unwind/src/dwarf/eh.rs // https://docs.rs/gimli/0.25.0/src/gimli/read/cfi.rs.html use core::mem; use gimli::{EndianSlice, Error, Pointer, Reader}; use gimli::{NativeEndian, constants}; use crate::abi::*; use crate::arch::*; use crate::util::*; #[derive(Debug)] enum EHAction { None, Cleanup(usize), Catch(usize), Filter(usize), Terminate, } fn parse_pointer_encoding(input: &mut StaticSlice) -> gimli::Result<constants::DwEhPe> { let eh_pe = input.read_u8()?; let eh_pe = constants::DwEhPe(eh_pe); if eh_pe.is_valid_encoding() { Ok(eh_pe) } else { Err(gimli::Error::UnknownPointerEncoding(eh_pe)) } } fn parse_encoded_pointer( encoding: constants::DwEhPe, unwind_ctx: &UnwindContext<'_>, input: &mut StaticSlice, ) -> gimli::Result<Pointer> { if encoding == constants::DW_EH_PE_omit { return Err(Error::CannotParseOmitPointerEncoding); } let base = match encoding.application() { constants::DW_EH_PE_absptr => 0, constants::DW_EH_PE_pcrel => input.slice().as_ptr() as u64, constants::DW_EH_PE_textrel => _Unwind_GetTextRelBase(unwind_ctx) as u64, constants::DW_EH_PE_datarel => _Unwind_GetDataRelBase(unwind_ctx) as u64, constants::DW_EH_PE_funcrel => _Unwind_GetRegionStart(unwind_ctx) as u64, constants::DW_EH_PE_aligned => return Err(Error::UnsupportedPointerEncoding), _ => unreachable!(), }; let offset = match encoding.format() { constants::DW_EH_PE_absptr => input.read_address(mem::size_of::<usize>() as _), constants::DW_EH_PE_uleb128 => input.read_uleb128(), constants::DW_EH_PE_udata2 => input.read_u16().map(u64::from), constants::DW_EH_PE_udata4 => input.read_u32().map(u64::from), constants::DW_EH_PE_udata8 => input.read_u64(), constants::DW_EH_PE_sleb128 => input.read_sleb128().map(|a| a as u64), constants::DW_EH_PE_sdata2 => input.read_i16().map(|a| a as u64), constants::DW_EH_PE_sdata4 => input.read_i32().map(|a| a as u64), constants::DW_EH_PE_sdata8 => input.read_i64().map(|a| a as u64), _ => unreachable!(), }?; let address = base.wrapping_add(offset); Ok(if encoding.is_indirect() { Pointer::Indirect(address) } else { Pointer::Direct(address) }) } fn find_eh_action( reader: &mut StaticSlice, unwind_ctx: &UnwindContext<'_>, ) -> gimli::Result<EHAction> { let func_start = _Unwind_GetRegionStart(unwind_ctx); let mut ip_before_instr = 0; let ip = _Unwind_GetIPInfo(unwind_ctx, &mut ip_before_instr); let ip = if ip_before_instr != 0 { ip } else { ip - 1 }; let start_encoding = parse_pointer_encoding(reader)?; let lpad_base = if !start_encoding.is_absent() { unsafe { deref_pointer(parse_encoded_pointer(start_encoding, unwind_ctx, reader)?) } } else { func_start }; let ttype_encoding = parse_pointer_encoding(reader)?; if !ttype_encoding.is_absent() { reader.read_uleb128()?; } let call_site_encoding = parse_pointer_encoding(reader)?; let call_site_table_length = reader.read_uleb128()?; let (mut call_site_table, mut action_table) = reader.split_at(call_site_table_length as _); while !call_site_table.is_empty() { let cs_start = unsafe { deref_pointer(parse_encoded_pointer( call_site_encoding, unwind_ctx, &mut call_site_table, )?) }; let cs_len = unsafe { deref_pointer(parse_encoded_pointer( call_site_encoding, unwind_ctx, &mut call_site_table, )?) }; let cs_lpad = unsafe { deref_pointer(parse_encoded_pointer( call_site_encoding, unwind_ctx, &mut call_site_table, )?) }; let cs_action = call_site_table.read_uleb128()?; if ip < func_start + cs_start { break; } if ip < func_start + cs_start + cs_len { if cs_lpad == 0 { return Ok(EHAction::None); } else { let lpad = lpad_base + cs_lpad; if cs_action == 0 { return Ok(EHAction::Cleanup(lpad)); } action_table.skip((cs_action - 1) as _)?; let ttype_index = action_table.read_sleb128()?; return Ok(if ttype_index == 0 { EHAction::Cleanup(lpad) } else if ttype_index > 0 { EHAction::Catch(lpad) } else { EHAction::Filter(lpad) }); } } } Ok(EHAction::Terminate) } #[lang = "eh_personality"] unsafe fn rust_eh_personality( version: c_int, actions: UnwindAction, _exception_class: u64, exception: *mut UnwindException, unwind_ctx: &mut UnwindContext<'_>, ) -> UnwindReasonCode { if version != 1 { return UnwindReasonCode::FATAL_PHASE1_ERROR; } let lsda = _Unwind_GetLanguageSpecificData(unwind_ctx); if lsda.is_null() { return UnwindReasonCode::CONTINUE_UNWIND; } let mut lsda = EndianSlice::new(unsafe { get_unlimited_slice(lsda as _) }, NativeEndian); let eh_action = match find_eh_action(&mut lsda, unwind_ctx) { Ok(v) => v, Err(_) => return UnwindReasonCode::FATAL_PHASE1_ERROR, }; if actions.contains(UnwindAction::SEARCH_PHASE) { match eh_action { EHAction::None | EHAction::Cleanup(_) => UnwindReasonCode::CONTINUE_UNWIND, EHAction::Catch(_) | EHAction::Filter(_) => UnwindReasonCode::HANDLER_FOUND, EHAction::Terminate => UnwindReasonCode::FATAL_PHASE1_ERROR, } } else { match eh_action { EHAction::None => UnwindReasonCode::CONTINUE_UNWIND, // Forced unwinding hits a terminate action. EHAction::Filter(_) if actions.contains(UnwindAction::FORCE_UNWIND) => { UnwindReasonCode::CONTINUE_UNWIND } EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { _Unwind_SetGR( unwind_ctx, Arch::UNWIND_DATA_REG.0.0 as _, exception as usize, ); _Unwind_SetGR(unwind_ctx, Arch::UNWIND_DATA_REG.1.0 as _, 0); _Unwind_SetIP(unwind_ctx, lpad); UnwindReasonCode::INSTALL_CONTEXT } EHAction::Terminate => UnwindReasonCode::FATAL_PHASE2_ERROR, } } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/panic_handler.rs
src/panic_handler.rs
use crate::abi::*; use crate::print::*; use alloc::boxed::Box; use core::any::Any; use core::cell::Cell; use core::ffi::c_void; use core::panic::{Location, PanicInfo}; use core::sync::atomic::{AtomicI32, Ordering}; #[thread_local] static PANIC_COUNT: Cell<usize> = Cell::new(0); #[link(name = "c")] unsafe extern "C" {} pub(crate) fn drop_panic() { eprintln!("Rust panics must be rethrown"); } pub(crate) fn foreign_exception() { eprintln!("Rust cannot catch foreign exceptions"); } pub(crate) fn panic_caught() { PANIC_COUNT.set(0); } fn check_env() -> bool { static ENV: AtomicI32 = AtomicI32::new(-1); let env = ENV.load(Ordering::Relaxed); if env != -1 { return env != 0; } let val = unsafe { let ptr = libc::getenv(b"RUST_BACKTRACE\0".as_ptr() as _); if ptr.is_null() { b"" } else { let len = libc::strlen(ptr); core::slice::from_raw_parts(ptr as *const u8, len) } }; let (note, env) = match val { b"" => (true, false), b"1" | b"full" => (false, true), _ => (false, false), }; // Issue a note for the first panic. if ENV.swap(env as _, Ordering::Relaxed) == -1 && note { eprintln!("note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace"); } env } fn stack_trace() { struct CallbackData { counter: usize, } extern "C" fn callback(unwind_ctx: &UnwindContext<'_>, arg: *mut c_void) -> UnwindReasonCode { let data = unsafe { &mut *(arg as *mut CallbackData) }; data.counter += 1; eprintln!( "{:4}:{:#19x} - <unknown>", data.counter, _Unwind_GetIP(unwind_ctx) ); UnwindReasonCode::NO_REASON } let mut data = CallbackData { counter: 0 }; _Unwind_Backtrace(callback, &mut data as *mut _ as _); } fn do_panic(msg: Box<dyn Any + Send>) -> ! { if PANIC_COUNT.get() >= 1 { stack_trace(); eprintln!("thread panicked while processing panic. aborting."); crate::util::abort(); } PANIC_COUNT.set(1); if check_env() { stack_trace(); } let code = crate::panic::begin_panic(Box::new(msg)); eprintln!("failed to initiate panic, error {}", code.0); crate::util::abort(); } #[panic_handler] fn panic(info: &PanicInfo<'_>) -> ! { eprintln!("{}", info); struct NoPayload; do_panic(Box::new(NoPayload)) } #[track_caller] pub fn panic_any<M: 'static + Any + Send>(msg: M) -> ! { eprintln!("panicked at {}", Location::caller()); do_panic(Box::new(msg)) }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/personality_dummy.rs
src/personality_dummy.rs
use crate::abi::*; use crate::util::*; #[lang = "eh_personality"] unsafe extern "C" fn personality( version: c_int, _actions: UnwindAction, _exception_class: u64, _exception: *mut UnwindException, _ctx: &mut UnwindContext<'_>, ) -> UnwindReasonCode { if version != 1 { return UnwindReasonCode::FATAL_PHASE1_ERROR; } UnwindReasonCode::CONTINUE_UNWIND }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/system_alloc.rs
src/system_alloc.rs
use core::alloc::{GlobalAlloc, Layout}; use core::{cmp, mem, ptr}; pub struct System; const MIN_ALIGN: usize = mem::size_of::<usize>() * 2; // Taken std unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { unsafe { libc::malloc(layout.size()) as *mut u8 } } else { let mut out = ptr::null_mut(); let align = layout.align().max(mem::size_of::<usize>()); let ret = unsafe { libc::posix_memalign(&mut out, align, layout.size()) }; if ret != 0 { ptr::null_mut() } else { out as *mut u8 } } } #[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { unsafe { libc::calloc(layout.size(), 1) as *mut u8 } } else { let ptr = unsafe { self.alloc(layout) }; if !ptr.is_null() { unsafe { ptr::write_bytes(ptr, 0, layout.size()) }; } ptr } } #[inline] unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { unsafe { libc::free(ptr as *mut libc::c_void) } } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { if layout.align() <= MIN_ALIGN && layout.align() <= new_size { unsafe { libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 } } else { let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; let new_ptr = unsafe { self.alloc(new_layout) }; if !new_ptr.is_null() { let size = cmp::min(layout.size(), new_size); unsafe { ptr::copy_nonoverlapping(ptr, new_ptr, size) }; unsafe { self.dealloc(ptr, layout) }; } new_ptr } } } #[global_allocator] pub static GLOBAL: System = System;
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/print.rs
src/print.rs
pub use crate::{eprint, eprintln, print, println}; #[doc(hidden)] pub struct StdoutPrinter; impl core::fmt::Write for StdoutPrinter { fn write_str(&mut self, s: &str) -> core::fmt::Result { unsafe { libc::printf(b"%.*s\0".as_ptr() as _, s.len() as i32, s.as_ptr()) }; Ok(()) } } #[doc(hidden)] pub struct StderrPrinter; impl core::fmt::Write for StderrPrinter { fn write_str(&mut self, s: &str) -> core::fmt::Result { unsafe { libc::write(libc::STDERR_FILENO, s.as_ptr() as _, s.len() as _) }; Ok(()) } } #[macro_export] macro_rules! println { ($($arg:tt)*) => ({ use core::fmt::Write; let _ = core::writeln!($crate::print::StdoutPrinter, $($arg)*); }) } #[macro_export] macro_rules! print { ($($arg:tt)*) => ({ use core::fmt::Write; let _ = core::write!($crate::print::StdoutPrinter, $($arg)*); }) } #[macro_export] macro_rules! eprintln { ($($arg:tt)*) => ({ use core::fmt::Write; let _ = core::writeln!($crate::print::StderrPrinter, $($arg)*); }) } #[macro_export] macro_rules! eprint { ($($arg:tt)*) => ({ use core::fmt::Write; let _ = core::write!($crate::print::StderrPrinter, $($arg)*); }) } #[macro_export] macro_rules! dbg { () => { $crate::eprintln!("[{}:{}]", ::core::file!(), ::core::line!()) }; ($val:expr $(,)?) => { match $val { tmp => { $crate::eprintln!("[{}:{}] {} = {:#?}", ::core::file!(), ::core::line!(), ::core::stringify!($val), &tmp); tmp } } }; ($($val:expr),+ $(,)?) => { ($($crate::dbg!($val)),+,) }; }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/arch.rs
src/arch.rs
#[cfg(target_arch = "x86_64")] mod x86_64 { use gimli::{Register, X86_64}; pub struct Arch; #[allow(unused)] impl Arch { pub const SP: Register = X86_64::RSP; pub const RA: Register = X86_64::RA; pub const UNWIND_DATA_REG: (Register, Register) = (X86_64::RAX, X86_64::RDX); pub const UNWIND_PRIVATE_DATA_SIZE: usize = 6; } } #[cfg(target_arch = "x86_64")] pub use x86_64::*; #[cfg(target_arch = "x86")] mod x86 { use gimli::{Register, X86}; pub struct Arch; #[allow(unused)] impl Arch { pub const SP: Register = X86::ESP; pub const RA: Register = X86::RA; pub const UNWIND_DATA_REG: (Register, Register) = (X86::EAX, X86::EDX); pub const UNWIND_PRIVATE_DATA_SIZE: usize = 5; } } #[cfg(target_arch = "x86")] pub use x86::*; #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))] mod riscv { use gimli::{Register, RiscV}; pub struct Arch; #[allow(unused)] impl Arch { pub const SP: Register = RiscV::SP; pub const RA: Register = RiscV::RA; pub const UNWIND_DATA_REG: (Register, Register) = (RiscV::A0, RiscV::A1); pub const UNWIND_PRIVATE_DATA_SIZE: usize = 2; } } #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))] pub use riscv::*; #[cfg(target_arch = "aarch64")] mod aarch64 { use gimli::{AArch64, Register}; pub struct Arch; #[allow(unused)] impl Arch { pub const SP: Register = AArch64::SP; pub const RA: Register = AArch64::X30; pub const UNWIND_DATA_REG: (Register, Register) = (AArch64::X0, AArch64::X1); pub const UNWIND_PRIVATE_DATA_SIZE: usize = 2; } } #[cfg(target_arch = "aarch64")] pub use aarch64::*; #[cfg(not(any( target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64", target_arch = "riscv32", target_arch = "aarch64" )))] compile_error!("Current architecture is not supported");
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/panicking.rs
src/panicking.rs
use core::mem::ManuallyDrop; use crate::abi::*; pub unsafe trait Exception { const CLASS: [u8; 8]; fn wrap(this: Self) -> *mut UnwindException; unsafe fn unwrap(ex: *mut UnwindException) -> Self; } pub fn begin_panic<E: Exception>(exception: E) -> UnwindReasonCode { unsafe extern "C" fn exception_cleanup<E: Exception>( _unwind_code: UnwindReasonCode, exception: *mut UnwindException, ) { unsafe { E::unwrap(exception) }; } let ex = E::wrap(exception); unsafe { (*ex).exception_class = u64::from_ne_bytes(E::CLASS); (*ex).exception_cleanup = Some(exception_cleanup::<E>); _Unwind_RaiseException(ex) } } pub fn catch_unwind<E: Exception, R, F: FnOnce() -> R>(f: F) -> Result<R, Option<E>> { #[repr(C)] union Data<F, R, E> { f: ManuallyDrop<F>, r: ManuallyDrop<R>, p: ManuallyDrop<Option<E>>, } let mut data = Data { f: ManuallyDrop::new(f), }; let data_ptr = &mut data as *mut _ as *mut u8; unsafe { return if core::intrinsics::catch_unwind(do_call::<F, R>, data_ptr, do_catch::<E>) == 0 { Ok(ManuallyDrop::into_inner(data.r)) } else { Err(ManuallyDrop::into_inner(data.p)) }; } #[inline] fn do_call<F: FnOnce() -> R, R>(data: *mut u8) { unsafe { let data = &mut *(data as *mut Data<F, R, ()>); let f = ManuallyDrop::take(&mut data.f); data.r = ManuallyDrop::new(f()); } } #[cold] fn do_catch<E: Exception>(data: *mut u8, exception: *mut u8) { unsafe { let data = &mut *(data as *mut ManuallyDrop<Option<E>>); let exception = exception as *mut UnwindException; if (*exception).exception_class != u64::from_ne_bytes(E::CLASS) { _Unwind_DeleteException(exception); *data = ManuallyDrop::new(None); return; } *data = ManuallyDrop::new(Some(E::unwrap(exception))); } } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/mod.rs
src/unwinder/mod.rs
mod arch; mod find_fde; mod frame; use core::ffi::c_void; use core::ptr; use gimli::Register; use crate::abi::*; use crate::arch::*; use crate::util::*; use arch::*; use find_fde::FDEFinder; use frame::Frame; #[cfg(feature = "fde-custom")] pub use find_fde::custom_eh_frame_finder; // Helper function to turn `save_context` which takes function pointer to a closure-taking function. fn with_context<T, F: FnOnce(&mut Context) -> T>(f: F) -> T { use core::mem::ManuallyDrop; union Data<T, F> { f: ManuallyDrop<F>, t: ManuallyDrop<T>, } extern "C" fn delegate<T, F: FnOnce(&mut Context) -> T>(ctx: &mut Context, ptr: *mut ()) { // SAFETY: This function is called exactly once; it extracts the function, call it and // store the return value. This function is `extern "C"` so we don't need to worry about // unwinding past it. unsafe { let data = &mut *ptr.cast::<Data<T, F>>(); let t = ManuallyDrop::take(&mut data.f)(ctx); data.t = ManuallyDrop::new(t); } } let mut data = Data { f: ManuallyDrop::new(f), }; save_context(delegate::<T, F>, ptr::addr_of_mut!(data).cast()); unsafe { ManuallyDrop::into_inner(data.t) } } #[repr(C)] pub struct UnwindException { pub exception_class: u64, pub exception_cleanup: Option<UnwindExceptionCleanupFn>, private_1: Option<UnwindStopFn>, private_2: usize, private_unused: [usize; Arch::UNWIND_PRIVATE_DATA_SIZE - 2], } pub struct UnwindContext<'a> { frame: Option<&'a Frame>, ctx: &'a mut Context, signal: bool, } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetGR(unwind_ctx: &UnwindContext<'_>, index: c_int) -> usize { unwind_ctx.ctx[Register(index as u16)] } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetCFA(unwind_ctx: &UnwindContext<'_>) -> usize { unwind_ctx.ctx[Arch::SP] } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_SetGR(unwind_ctx: &mut UnwindContext<'_>, index: c_int, value: usize) { unwind_ctx.ctx[Register(index as u16)] = value; } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetIP(unwind_ctx: &UnwindContext<'_>) -> usize { unwind_ctx.ctx[Arch::RA] } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetIPInfo( unwind_ctx: &UnwindContext<'_>, ip_before_insn: &mut c_int, ) -> usize { *ip_before_insn = unwind_ctx.signal as _; unwind_ctx.ctx[Arch::RA] } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_SetIP(unwind_ctx: &mut UnwindContext<'_>, value: usize) { unwind_ctx.ctx[Arch::RA] = value; } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetLanguageSpecificData(unwind_ctx: &UnwindContext<'_>) -> *mut c_void { unwind_ctx .frame .map(|f| f.lsda() as *mut c_void) .unwrap_or(ptr::null_mut()) } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetRegionStart(unwind_ctx: &UnwindContext<'_>) -> usize { unwind_ctx.frame.map(|f| f.initial_address()).unwrap_or(0) } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetTextRelBase(unwind_ctx: &UnwindContext<'_>) -> usize { unwind_ctx .frame .map(|f| f.bases().eh_frame.text.unwrap() as _) .unwrap_or(0) } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_GetDataRelBase(unwind_ctx: &UnwindContext<'_>) -> usize { unwind_ctx .frame .map(|f| f.bases().eh_frame.data.unwrap() as _) .unwrap_or(0) } #[unsafe(no_mangle)] pub extern "C" fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void { find_fde::get_finder() .find_fde(pc as usize - 1) .map(|r| r.fde.initial_address() as usize as _) .unwrap_or(ptr::null_mut()) } macro_rules! try1 { ($e: expr) => {{ match $e { Ok(v) => v, Err(_) => return UnwindReasonCode::FATAL_PHASE1_ERROR, } }}; } macro_rules! try2 { ($e: expr) => {{ match $e { Ok(v) => v, Err(_) => return UnwindReasonCode::FATAL_PHASE2_ERROR, } }}; } #[inline(never)] #[unsafe(no_mangle)] pub unsafe extern "C-unwind" fn _Unwind_RaiseException( exception: *mut UnwindException, ) -> UnwindReasonCode { with_context(|saved_ctx| { // Phase 1: Search for handler let mut ctx = saved_ctx.clone(); let mut signal = false; loop { if let Some(frame) = try1!(Frame::from_context(&ctx, signal)) { if let Some(personality) = frame.personality() { let result = unsafe { personality( 1, UnwindAction::SEARCH_PHASE, (*exception).exception_class, exception, &mut UnwindContext { frame: Some(&frame), ctx: &mut ctx, signal, }, ) }; match result { UnwindReasonCode::CONTINUE_UNWIND => (), UnwindReasonCode::HANDLER_FOUND => { break; } _ => return UnwindReasonCode::FATAL_PHASE1_ERROR, } } ctx = try1!(frame.unwind(&ctx)); signal = frame.is_signal_trampoline(); } else { return UnwindReasonCode::END_OF_STACK; } } // Disambiguate normal frame and signal frame. let handler_cfa = ctx[Arch::SP] - signal as usize; unsafe { (*exception).private_1 = None; (*exception).private_2 = handler_cfa; } let code = raise_exception_phase2(exception, saved_ctx, handler_cfa); match code { UnwindReasonCode::INSTALL_CONTEXT => unsafe { restore_context(saved_ctx) }, _ => code, } }) } fn raise_exception_phase2( exception: *mut UnwindException, ctx: &mut Context, handler_cfa: usize, ) -> UnwindReasonCode { let mut signal = false; loop { if let Some(frame) = try2!(Frame::from_context(ctx, signal)) { let frame_cfa = ctx[Arch::SP] - signal as usize; if let Some(personality) = frame.personality() { let code = unsafe { personality( 1, UnwindAction::CLEANUP_PHASE | if frame_cfa == handler_cfa { UnwindAction::HANDLER_FRAME } else { UnwindAction::empty() }, (*exception).exception_class, exception, &mut UnwindContext { frame: Some(&frame), ctx, signal, }, ) }; match code { UnwindReasonCode::CONTINUE_UNWIND => (), UnwindReasonCode::INSTALL_CONTEXT => { frame.adjust_stack_for_args(ctx); return UnwindReasonCode::INSTALL_CONTEXT; } _ => return UnwindReasonCode::FATAL_PHASE2_ERROR, } } *ctx = try2!(frame.unwind(ctx)); signal = frame.is_signal_trampoline(); } else { return UnwindReasonCode::FATAL_PHASE2_ERROR; } } } #[inline(never)] #[unsafe(no_mangle)] pub unsafe extern "C-unwind" fn _Unwind_ForcedUnwind( exception: *mut UnwindException, stop: UnwindStopFn, stop_arg: *mut c_void, ) -> UnwindReasonCode { with_context(|ctx| { unsafe { (*exception).private_1 = Some(stop); (*exception).private_2 = stop_arg as _; } let code = force_unwind_phase2(exception, ctx, stop, stop_arg); match code { UnwindReasonCode::INSTALL_CONTEXT => unsafe { restore_context(ctx) }, _ => code, } }) } fn force_unwind_phase2( exception: *mut UnwindException, ctx: &mut Context, stop: UnwindStopFn, stop_arg: *mut c_void, ) -> UnwindReasonCode { let mut signal = false; loop { let frame = try2!(Frame::from_context(ctx, signal)); let code = unsafe { stop( 1, UnwindAction::FORCE_UNWIND | UnwindAction::END_OF_STACK | if frame.is_none() { UnwindAction::END_OF_STACK } else { UnwindAction::empty() }, (*exception).exception_class, exception, &mut UnwindContext { frame: frame.as_ref(), ctx, signal, }, stop_arg, ) }; match code { UnwindReasonCode::NO_REASON => (), _ => return UnwindReasonCode::FATAL_PHASE2_ERROR, } if let Some(frame) = frame { if let Some(personality) = frame.personality() { let code = unsafe { personality( 1, UnwindAction::FORCE_UNWIND | UnwindAction::CLEANUP_PHASE, (*exception).exception_class, exception, &mut UnwindContext { frame: Some(&frame), ctx, signal, }, ) }; match code { UnwindReasonCode::CONTINUE_UNWIND => (), UnwindReasonCode::INSTALL_CONTEXT => { frame.adjust_stack_for_args(ctx); return UnwindReasonCode::INSTALL_CONTEXT; } _ => return UnwindReasonCode::FATAL_PHASE2_ERROR, } } *ctx = try2!(frame.unwind(ctx)); signal = frame.is_signal_trampoline(); } else { return UnwindReasonCode::END_OF_STACK; } } } #[inline(never)] #[unsafe(no_mangle)] pub unsafe extern "C-unwind" fn _Unwind_Resume(exception: *mut UnwindException) -> ! { with_context(|ctx| { let code = match unsafe { (*exception).private_1 } { None => { let handler_cfa = unsafe { (*exception).private_2 }; raise_exception_phase2(exception, ctx, handler_cfa) } Some(stop) => { let stop_arg = unsafe { (*exception).private_2 as _ }; force_unwind_phase2(exception, ctx, stop, stop_arg) } }; assert!(code == UnwindReasonCode::INSTALL_CONTEXT); unsafe { restore_context(ctx) } }) } #[inline(never)] #[unsafe(no_mangle)] pub unsafe extern "C-unwind" fn _Unwind_Resume_or_Rethrow( exception: *mut UnwindException, ) -> UnwindReasonCode { let stop = match unsafe { (*exception).private_1 } { None => return unsafe { _Unwind_RaiseException(exception) }, Some(v) => v, }; with_context(|ctx| { let stop_arg = unsafe { (*exception).private_2 as _ }; let code = force_unwind_phase2(exception, ctx, stop, stop_arg); assert!(code == UnwindReasonCode::INSTALL_CONTEXT); unsafe { restore_context(ctx) } }) } #[unsafe(no_mangle)] pub unsafe extern "C" fn _Unwind_DeleteException(exception: *mut UnwindException) { if let Some(cleanup) = unsafe { (*exception).exception_cleanup } { unsafe { cleanup(UnwindReasonCode::FOREIGN_EXCEPTION_CAUGHT, exception) }; } } #[inline(never)] #[unsafe(no_mangle)] pub extern "C-unwind" fn _Unwind_Backtrace( trace: UnwindTraceFn, trace_argument: *mut c_void, ) -> UnwindReasonCode { with_context(|ctx| { let mut ctx = ctx.clone(); let mut signal = false; let mut skipping = cfg!(feature = "hide-trace"); loop { let frame = try1!(Frame::from_context(&ctx, signal)); if !skipping { let code = trace( &UnwindContext { frame: frame.as_ref(), ctx: &mut ctx, signal, }, trace_argument, ); match code { UnwindReasonCode::NO_REASON => (), _ => return UnwindReasonCode::FATAL_PHASE1_ERROR, } } if let Some(frame) = frame { if skipping { if frame.initial_address() == _Unwind_Backtrace as usize { skipping = false; } } ctx = try1!(frame.unwind(&ctx)); signal = frame.is_signal_trampoline(); } else { return UnwindReasonCode::END_OF_STACK; } } }) }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/frame.rs
src/unwinder/frame.rs
use gimli::{ BaseAddresses, CfaRule, Register, RegisterRule, UnwindContext, UnwindExpression, UnwindTableRow, }; #[cfg(feature = "dwarf-expr")] use gimli::{Evaluation, EvaluationResult, Location, Value}; use super::arch::*; use super::find_fde::{self, FDEFinder, FDESearchResult}; use crate::abi::PersonalityRoutine; use crate::arch::*; use crate::util::*; struct StoreOnStack; // gimli's MSRV doesn't allow const generics, so we need to pick a supported array size. const fn next_value(x: usize) -> usize { let supported = [0, 1, 2, 3, 4, 8, 16, 32, 64, 128]; let mut i = 0; while i < supported.len() { if supported[i] >= x { return supported[i]; } i += 1; } 192 } impl<O: gimli::ReaderOffset> gimli::UnwindContextStorage<O> for StoreOnStack { type Rules = [(Register, RegisterRule<O>); next_value(MAX_REG_RULES)]; type Stack = [UnwindTableRow<O, Self>; 2]; } #[cfg(feature = "dwarf-expr")] impl<R: gimli::Reader> gimli::EvaluationStorage<R> for StoreOnStack { type Stack = [Value; 64]; type ExpressionStack = [(R, R); 0]; type Result = [gimli::Piece<R>; 1]; } #[derive(Debug)] pub struct Frame { fde_result: FDESearchResult, row: UnwindTableRow<usize, StoreOnStack>, } impl Frame { pub fn from_context(ctx: &Context, signal: bool) -> Result<Option<Self>, gimli::Error> { let mut ra = ctx[Arch::RA]; // Reached end of stack if ra == 0 { return Ok(None); } // RA points to the *next* instruction, so move it back 1 byte for the call instruction. if !signal { ra -= 1; } let fde_result = match find_fde::get_finder().find_fde(ra as _) { Some(v) => v, None => return Ok(None), }; let mut unwinder = UnwindContext::<_, StoreOnStack>::new_in(); let row = fde_result .fde .unwind_info_for_address( &fde_result.eh_frame, &fde_result.bases, &mut unwinder, ra as _, )? .clone(); Ok(Some(Self { fde_result, row })) } #[cfg(feature = "dwarf-expr")] fn evaluate_expression( &self, ctx: &Context, expr: UnwindExpression<usize>, ) -> Result<usize, gimli::Error> { let expr = expr.get(&self.fde_result.eh_frame).unwrap(); let mut eval = Evaluation::<_, StoreOnStack>::new_in(expr.0, self.fde_result.fde.cie().encoding()); let mut result = eval.evaluate()?; loop { match result { EvaluationResult::Complete => break, EvaluationResult::RequiresMemory { address, .. } => { let value = unsafe { (address as usize as *const usize).read_unaligned() }; result = eval.resume_with_memory(Value::Generic(value as _))?; } EvaluationResult::RequiresRegister { register, .. } => { let value = ctx[register]; result = eval.resume_with_register(Value::Generic(value as _))?; } EvaluationResult::RequiresRelocatedAddress(address) => { let value = unsafe { (address as usize as *const usize).read_unaligned() }; result = eval.resume_with_memory(Value::Generic(value as _))?; } _ => unreachable!(), } } Ok( match eval .as_result() .last() .ok_or(gimli::Error::PopWithEmptyStack)? .location { Location::Address { address } => address as usize, _ => unreachable!(), }, ) } #[cfg(not(feature = "dwarf-expr"))] fn evaluate_expression( &self, _ctx: &Context, _expr: UnwindExpression<usize>, ) -> Result<usize, gimli::Error> { Err(gimli::Error::UnsupportedEvaluation) } pub fn adjust_stack_for_args(&self, ctx: &mut Context) { let size = self.row.saved_args_size(); ctx[Arch::SP] = ctx[Arch::SP].wrapping_add(size as usize); } pub fn unwind(&self, ctx: &Context) -> Result<Context, gimli::Error> { let row = &self.row; let mut new_ctx = ctx.clone(); let cfa = match *row.cfa() { CfaRule::RegisterAndOffset { register, offset } => { ctx[register].wrapping_add(offset as usize) } CfaRule::Expression(expr) => self.evaluate_expression(ctx, expr)?, }; new_ctx[Arch::SP] = cfa as _; new_ctx[Arch::RA] = 0; #[warn(non_exhaustive_omitted_patterns)] for (reg, rule) in row.registers() { let value = match *rule { RegisterRule::Undefined | RegisterRule::SameValue => ctx[*reg], RegisterRule::Offset(offset) => unsafe { *((cfa.wrapping_add(offset as usize)) as *const usize) }, RegisterRule::ValOffset(offset) => cfa.wrapping_add(offset as usize), RegisterRule::Register(r) => ctx[r], RegisterRule::Expression(expr) => { let addr = self.evaluate_expression(ctx, expr)?; unsafe { *(addr as *const usize) } } RegisterRule::ValExpression(expr) => self.evaluate_expression(ctx, expr)?, RegisterRule::Architectural => unreachable!(), RegisterRule::Constant(value) => value as usize, _ => unreachable!(), }; new_ctx[*reg] = value; } Ok(new_ctx) } pub fn bases(&self) -> &BaseAddresses { &self.fde_result.bases } pub fn personality(&self) -> Option<PersonalityRoutine> { self.fde_result .fde .personality() .map(|x| unsafe { deref_pointer(x) }) .map(|x| unsafe { core::mem::transmute(x) }) } pub fn lsda(&self) -> usize { self.fde_result .fde .lsda() .map(|x| unsafe { deref_pointer(x) }) .unwrap_or(0) } pub fn initial_address(&self) -> usize { self.fde_result.fde.initial_address() as _ } pub fn is_signal_trampoline(&self) -> bool { self.fde_result.fde.is_signal_trampoline() } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/find_fde/gnu_eh_frame_hdr.rs
src/unwinder/find_fde/gnu_eh_frame_hdr.rs
use super::FDESearchResult; use crate::util::*; use gimli::{BaseAddresses, EhFrame, EhFrameHdr, NativeEndian, UnwindSection}; pub struct StaticFinder(()); pub fn get_finder() -> &'static StaticFinder { &StaticFinder(()) } unsafe extern "C" { static __executable_start: u8; static __etext: u8; static __GNU_EH_FRAME_HDR: u8; } impl super::FDEFinder for StaticFinder { fn find_fde(&self, pc: usize) -> Option<FDESearchResult> { unsafe { let text_start = &__executable_start as *const u8 as usize; let text_end = &__etext as *const u8 as usize; if !(text_start..text_end).contains(&pc) { return None; } let eh_frame_hdr = &__GNU_EH_FRAME_HDR as *const u8 as usize; let bases = BaseAddresses::default() .set_text(text_start as _) .set_eh_frame_hdr(eh_frame_hdr as _); let eh_frame_hdr = EhFrameHdr::new(get_unlimited_slice(eh_frame_hdr as _), NativeEndian) .parse(&bases, core::mem::size_of::<usize>() as _) .ok()?; let eh_frame = deref_pointer(eh_frame_hdr.eh_frame_ptr()); let bases = bases.set_eh_frame(eh_frame as _); let eh_frame = EhFrame::new(get_unlimited_slice(eh_frame as _), NativeEndian); // Use binary search table for address if available. if let Some(table) = eh_frame_hdr.table() && let Ok(fde) = table.fde_for_address(&eh_frame, &bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } // Otherwise do the linear search. if let Ok(fde) = eh_frame.fde_for_address(&bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } None } } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/find_fde/fixed.rs
src/unwinder/find_fde/fixed.rs
use super::FDESearchResult; use crate::util::*; use gimli::{BaseAddresses, EhFrame, NativeEndian, UnwindSection}; pub struct StaticFinder(()); pub fn get_finder() -> &'static StaticFinder { &StaticFinder(()) } unsafe extern "C" { static __executable_start: u8; static __etext: u8; static __eh_frame: u8; } impl super::FDEFinder for StaticFinder { fn find_fde(&self, pc: usize) -> Option<FDESearchResult> { unsafe { let text_start = &__executable_start as *const u8 as usize; let text_end = &__etext as *const u8 as usize; if !(text_start..text_end).contains(&pc) { return None; } let eh_frame = &__eh_frame as *const u8 as usize; let bases = BaseAddresses::default() .set_eh_frame(eh_frame as _) .set_text(text_start as _); let eh_frame = EhFrame::new(get_unlimited_slice(eh_frame as _), NativeEndian); if let Ok(fde) = eh_frame.fde_for_address(&bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } None } } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/find_fde/phdr.rs
src/unwinder/find_fde/phdr.rs
use super::FDESearchResult; use crate::util::*; use core::mem; use core::slice; use gimli::{BaseAddresses, EhFrame, EhFrameHdr, NativeEndian, UnwindSection}; use libc::{PT_DYNAMIC, PT_GNU_EH_FRAME, PT_LOAD}; #[cfg(target_pointer_width = "32")] use libc::Elf32_Phdr as Elf_Phdr; #[cfg(target_pointer_width = "64")] use libc::Elf64_Phdr as Elf_Phdr; pub struct PhdrFinder(()); pub fn get_finder() -> &'static PhdrFinder { &PhdrFinder(()) } impl super::FDEFinder for PhdrFinder { fn find_fde(&self, pc: usize) -> Option<FDESearchResult> { #[cfg(feature = "fde-phdr-aux")] if let Some(v) = search_aux_phdr(pc) { return Some(v); } #[cfg(feature = "fde-phdr-dl")] if let Some(v) = search_dl_phdr(pc) { return Some(v); } None } } #[cfg(feature = "fde-phdr-aux")] fn search_aux_phdr(pc: usize) -> Option<FDESearchResult> { use libc::{AT_PHDR, AT_PHNUM, PT_PHDR, getauxval}; unsafe { let phdr = getauxval(AT_PHDR) as *const Elf_Phdr; let phnum = getauxval(AT_PHNUM) as usize; let phdrs = slice::from_raw_parts(phdr, phnum); // With known address of PHDR, we can calculate the base address in reverse. let base = phdrs.as_ptr() as usize - phdrs.iter().find(|x| x.p_type == PT_PHDR)?.p_vaddr as usize; search_phdr(phdrs, base, pc) } } #[cfg(feature = "fde-phdr-dl")] fn search_dl_phdr(pc: usize) -> Option<FDESearchResult> { use core::ffi::c_void; use libc::{dl_iterate_phdr, dl_phdr_info}; struct CallbackData { pc: usize, result: Option<FDESearchResult>, } unsafe extern "C" fn phdr_callback( info: *mut dl_phdr_info, _size: usize, data: *mut c_void, ) -> c_int { unsafe { let data = &mut *(data as *mut CallbackData); let phdrs = slice::from_raw_parts((*info).dlpi_phdr, (*info).dlpi_phnum as usize); if let Some(v) = search_phdr(phdrs, (*info).dlpi_addr as _, data.pc) { data.result = Some(v); return 1; } 0 } } let mut data = CallbackData { pc, result: None }; unsafe { dl_iterate_phdr(Some(phdr_callback), &mut data as *mut CallbackData as _) }; data.result } fn search_phdr(phdrs: &[Elf_Phdr], base: usize, pc: usize) -> Option<FDESearchResult> { unsafe { let mut text = None; let mut eh_frame_hdr = None; let mut dynamic = None; for phdr in phdrs { let start = base + phdr.p_vaddr as usize; match phdr.p_type { PT_LOAD => { let end = start + phdr.p_memsz as usize; let range = start..end; if range.contains(&pc) { text = Some(range); } } PT_GNU_EH_FRAME => { eh_frame_hdr = Some(start); } PT_DYNAMIC => { dynamic = Some(start); } _ => (), } } let text = text?; let eh_frame_hdr = eh_frame_hdr?; let mut bases = BaseAddresses::default() .set_eh_frame_hdr(eh_frame_hdr as _) .set_text(text.start as _); // Find the GOT section. if let Some(start) = dynamic { const DT_NULL: usize = 0; const DT_PLTGOT: usize = 3; let mut tags = start as *const [usize; 2]; let mut tag = *tags; while tag[0] != DT_NULL { if tag[0] == DT_PLTGOT { bases = bases.set_got(tag[1] as _); break; } tags = tags.add(1); tag = *tags; } } // Parse .eh_frame_hdr section. let eh_frame_hdr = EhFrameHdr::new(get_unlimited_slice(eh_frame_hdr as _), NativeEndian) .parse(&bases, mem::size_of::<usize>() as _) .ok()?; let eh_frame = deref_pointer(eh_frame_hdr.eh_frame_ptr()); bases = bases.set_eh_frame(eh_frame as _); let eh_frame = EhFrame::new(get_unlimited_slice(eh_frame as usize as _), NativeEndian); // Use binary search table for address if available. if let Some(table) = eh_frame_hdr.table() && let Ok(fde) = table.fde_for_address(&eh_frame, &bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } // Otherwise do the linear search. if let Ok(fde) = eh_frame.fde_for_address(&bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } None } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/find_fde/registry.rs
src/unwinder/find_fde/registry.rs
use super::FDESearchResult; use crate::util::get_unlimited_slice; use alloc::boxed::Box; use core::ffi::c_void; use core::mem::MaybeUninit; use core::ops; use core::ptr; use gimli::{BaseAddresses, EhFrame, NativeEndian, UnwindSection}; enum Table { Single(*const c_void), Multiple(*const *const c_void), } struct Object { next: *mut Object, tbase: usize, dbase: usize, table: Table, } struct GlobalState { object: *mut Object, } unsafe impl Send for GlobalState {} pub struct Registry(()); // `unsafe` because there is no protection for reentrance. unsafe fn lock_global_state() -> impl ops::DerefMut<Target = GlobalState> { #[cfg(feature = "libc")] { static mut MUTEX: libc::pthread_mutex_t = libc::PTHREAD_MUTEX_INITIALIZER; unsafe { libc::pthread_mutex_lock(core::ptr::addr_of_mut!(MUTEX)) }; static mut STATE: GlobalState = GlobalState { object: ptr::null_mut(), }; struct LockGuard; impl Drop for LockGuard { fn drop(&mut self) { unsafe { libc::pthread_mutex_unlock(core::ptr::addr_of_mut!(MUTEX)) }; } } impl ops::Deref for LockGuard { type Target = GlobalState; #[allow(static_mut_refs)] fn deref(&self) -> &GlobalState { unsafe { &*core::ptr::addr_of!(STATE) } } } impl ops::DerefMut for LockGuard { fn deref_mut(&mut self) -> &mut GlobalState { unsafe { &mut *core::ptr::addr_of_mut!(STATE) } } } LockGuard } #[cfg(not(feature = "libc"))] { static MUTEX: spin::Mutex<GlobalState> = spin::Mutex::new(GlobalState { object: ptr::null_mut(), }); MUTEX.lock() } #[cfg(not(any(feature = "libc", feature = "spin")))] compile_error!("Either feature \"libc\" or \"spin\" must be enabled to use \"fde-registry\"."); } pub fn get_finder() -> &'static Registry { &Registry(()) } impl super::FDEFinder for Registry { fn find_fde(&self, pc: usize) -> Option<FDESearchResult> { unsafe { let guard = lock_global_state(); let mut cur = guard.object; while !cur.is_null() { let bases = BaseAddresses::default() .set_text((*cur).tbase as _) .set_got((*cur).dbase as _); match (*cur).table { Table::Single(addr) => { let eh_frame = EhFrame::new(get_unlimited_slice(addr as _), NativeEndian); let bases = bases.clone().set_eh_frame(addr as usize as _); if let Ok(fde) = eh_frame.fde_for_address(&bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } } Table::Multiple(mut addrs) => { let mut addr = *addrs; while !addr.is_null() { let eh_frame = EhFrame::new(get_unlimited_slice(addr as _), NativeEndian); let bases = bases.clone().set_eh_frame(addr as usize as _); if let Ok(fde) = eh_frame.fde_for_address(&bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } addrs = addrs.add(1); addr = *addrs; } } } cur = (*cur).next; } } None } } #[unsafe(no_mangle)] unsafe extern "C" fn __register_frame_info_bases( begin: *const c_void, ob: *mut Object, tbase: *const c_void, dbase: *const c_void, ) { if begin.is_null() { return; } unsafe { ob.write(Object { next: core::ptr::null_mut(), tbase: tbase as _, dbase: dbase as _, table: Table::Single(begin), }); let mut guard = lock_global_state(); (*ob).next = guard.object; guard.object = ob; } } #[unsafe(no_mangle)] unsafe extern "C" fn __register_frame_info(begin: *const c_void, ob: *mut Object) { unsafe { __register_frame_info_bases(begin, ob, core::ptr::null_mut(), core::ptr::null_mut()) } } #[unsafe(no_mangle)] unsafe extern "C" fn __register_frame(begin: *const c_void) { if begin.is_null() { return; } let storage = Box::into_raw(Box::new(MaybeUninit::<Object>::uninit())) as *mut Object; unsafe { __register_frame_info(begin, storage) } } #[unsafe(no_mangle)] unsafe extern "C" fn __register_frame_info_table_bases( begin: *const c_void, ob: *mut Object, tbase: *const c_void, dbase: *const c_void, ) { unsafe { ob.write(Object { next: core::ptr::null_mut(), tbase: tbase as _, dbase: dbase as _, table: Table::Multiple(begin as _), }); let mut guard = lock_global_state(); (*ob).next = guard.object; guard.object = ob; } } #[unsafe(no_mangle)] unsafe extern "C" fn __register_frame_info_table(begin: *const c_void, ob: *mut Object) { unsafe { __register_frame_info_table_bases(begin, ob, core::ptr::null_mut(), core::ptr::null_mut()) } } #[unsafe(no_mangle)] unsafe extern "C" fn __register_frame_table(begin: *const c_void) { if begin.is_null() { return; } let storage = Box::into_raw(Box::new(MaybeUninit::<Object>::uninit())) as *mut Object; unsafe { __register_frame_info_table(begin, storage) } } #[unsafe(no_mangle)] extern "C" fn __deregister_frame_info_bases(begin: *const c_void) -> *mut Object { if begin.is_null() { return core::ptr::null_mut(); } let mut guard = unsafe { lock_global_state() }; unsafe { let mut prev = &mut guard.object; let mut cur = *prev; while !cur.is_null() { let found = match (*cur).table { Table::Single(addr) => addr == begin, _ => false, }; if found { *prev = (*cur).next; return cur; } prev = &mut (*cur).next; cur = *prev; } } core::ptr::null_mut() } #[unsafe(no_mangle)] extern "C" fn __deregister_frame_info(begin: *const c_void) -> *mut Object { __deregister_frame_info_bases(begin) } #[unsafe(no_mangle)] unsafe extern "C" fn __deregister_frame(begin: *const c_void) { if begin.is_null() { return; } let storage = __deregister_frame_info(begin); drop(unsafe { Box::from_raw(storage as *mut MaybeUninit<Object>) }) }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/find_fde/mod.rs
src/unwinder/find_fde/mod.rs
#[cfg(feature = "fde-custom")] mod custom; #[cfg(feature = "fde-static")] mod fixed; #[cfg(feature = "fde-gnu-eh-frame-hdr")] mod gnu_eh_frame_hdr; #[cfg(feature = "fde-phdr")] mod phdr; #[cfg(feature = "fde-registry")] mod registry; use crate::util::*; use gimli::{BaseAddresses, EhFrame, FrameDescriptionEntry}; #[cfg(feature = "fde-custom")] pub mod custom_eh_frame_finder { pub use super::custom::{ EhFrameFinder, FrameInfo, FrameInfoKind, SetCustomEhFrameFinderError, set_custom_eh_frame_finder, }; } #[derive(Debug)] pub struct FDESearchResult { pub fde: FrameDescriptionEntry<StaticSlice>, pub bases: BaseAddresses, pub eh_frame: EhFrame<StaticSlice>, } pub trait FDEFinder { fn find_fde(&self, pc: usize) -> Option<FDESearchResult>; } pub struct GlobalFinder(()); impl FDEFinder for GlobalFinder { fn find_fde(&self, pc: usize) -> Option<FDESearchResult> { #[cfg(feature = "fde-custom")] if let Some(v) = custom::get_finder().find_fde(pc) { return Some(v); } #[cfg(feature = "fde-registry")] if let Some(v) = registry::get_finder().find_fde(pc) { return Some(v); } #[cfg(feature = "fde-gnu-eh-frame-hdr")] if let Some(v) = gnu_eh_frame_hdr::get_finder().find_fde(pc) { return Some(v); } #[cfg(feature = "fde-phdr")] if let Some(v) = phdr::get_finder().find_fde(pc) { return Some(v); } #[cfg(feature = "fde-static")] if let Some(v) = fixed::get_finder().find_fde(pc) { return Some(v); } None } } pub fn get_finder() -> &'static GlobalFinder { &GlobalFinder(()) }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/find_fde/custom.rs
src/unwinder/find_fde/custom.rs
use super::{FDEFinder, FDESearchResult}; use crate::util::{deref_pointer, get_unlimited_slice}; use core::sync::atomic::{AtomicU32, Ordering}; use gimli::{BaseAddresses, EhFrame, EhFrameHdr, NativeEndian, UnwindSection}; pub(crate) struct CustomFinder(()); pub(crate) fn get_finder() -> &'static CustomFinder { &CustomFinder(()) } impl FDEFinder for CustomFinder { fn find_fde(&self, pc: usize) -> Option<FDESearchResult> { get_custom_eh_frame_finder().and_then(|eh_frame_finder| find_fde(eh_frame_finder, pc)) } } /// A trait for types whose values can be used as the global EH frame finder set by [`set_custom_eh_frame_finder`]. pub unsafe trait EhFrameFinder { fn find(&self, pc: usize) -> Option<FrameInfo>; } pub struct FrameInfo { pub text_base: Option<usize>, pub kind: FrameInfoKind, } pub enum FrameInfoKind { EhFrameHdr(usize), EhFrame(usize), } static mut CUSTOM_EH_FRAME_FINDER: Option<&(dyn EhFrameFinder + Sync)> = None; static CUSTOM_EH_FRAME_FINDER_STATE: AtomicU32 = AtomicU32::new(UNINITIALIZED); const UNINITIALIZED: u32 = 0; const INITIALIZING: u32 = 1; const INITIALIZED: u32 = 2; /// The type returned by [`set_custom_eh_frame_finder`] if [`set_custom_eh_frame_finder`] has /// already been called. #[derive(Debug)] pub struct SetCustomEhFrameFinderError(()); /// Sets the global EH frame finder. /// /// This function should only be called once during the lifetime of the program. /// /// # Errors /// /// An error is returned if this function has already been called during the lifetime of the /// program. pub fn set_custom_eh_frame_finder( fde_finder: &'static (dyn EhFrameFinder + Sync), ) -> Result<(), SetCustomEhFrameFinderError> { match CUSTOM_EH_FRAME_FINDER_STATE.compare_exchange( UNINITIALIZED, INITIALIZING, Ordering::SeqCst, Ordering::SeqCst, ) { Ok(UNINITIALIZED) => { unsafe { CUSTOM_EH_FRAME_FINDER = Some(fde_finder); } CUSTOM_EH_FRAME_FINDER_STATE.store(INITIALIZED, Ordering::SeqCst); Ok(()) } Err(INITIALIZING) => { while CUSTOM_EH_FRAME_FINDER_STATE.load(Ordering::SeqCst) == INITIALIZING { core::hint::spin_loop(); } Err(SetCustomEhFrameFinderError(())) } Err(INITIALIZED) => Err(SetCustomEhFrameFinderError(())), _ => { unreachable!() } } } fn get_custom_eh_frame_finder() -> Option<&'static dyn EhFrameFinder> { if CUSTOM_EH_FRAME_FINDER_STATE.load(Ordering::SeqCst) == INITIALIZED { Some(unsafe { CUSTOM_EH_FRAME_FINDER.unwrap() }) } else { None } } fn find_fde<T: EhFrameFinder + ?Sized>(eh_frame_finder: &T, pc: usize) -> Option<FDESearchResult> { let info = eh_frame_finder.find(pc)?; let text_base = info.text_base; match info.kind { FrameInfoKind::EhFrameHdr(eh_frame_hdr) => { find_fde_with_eh_frame_hdr(pc, text_base, eh_frame_hdr) } FrameInfoKind::EhFrame(eh_frame) => find_fde_with_eh_frame(pc, text_base, eh_frame), } } fn find_fde_with_eh_frame_hdr( pc: usize, text_base: Option<usize>, eh_frame_hdr: usize, ) -> Option<FDESearchResult> { unsafe { let mut bases = BaseAddresses::default().set_eh_frame_hdr(eh_frame_hdr as _); if let Some(text_base) = text_base { bases = bases.set_text(text_base as _); } let eh_frame_hdr = EhFrameHdr::new(get_unlimited_slice(eh_frame_hdr as _), NativeEndian) .parse(&bases, core::mem::size_of::<usize>() as _) .ok()?; let eh_frame = deref_pointer(eh_frame_hdr.eh_frame_ptr()); let bases = bases.set_eh_frame(eh_frame as _); let eh_frame = EhFrame::new(get_unlimited_slice(eh_frame as _), NativeEndian); // Use binary search table for address if available. if let Some(table) = eh_frame_hdr.table() && let Ok(fde) = table.fde_for_address(&eh_frame, &bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } // Otherwise do the linear search. if let Ok(fde) = eh_frame.fde_for_address(&bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } None } } fn find_fde_with_eh_frame( pc: usize, text_base: Option<usize>, eh_frame: usize, ) -> Option<FDESearchResult> { unsafe { let mut bases = BaseAddresses::default().set_eh_frame(eh_frame as _); if let Some(text_base) = text_base { bases = bases.set_text(text_base as _); } let eh_frame = EhFrame::new(get_unlimited_slice(eh_frame as _), NativeEndian); if let Ok(fde) = eh_frame.fde_for_address(&bases, pc as _, EhFrame::cie_from_offset) { return Some(FDESearchResult { fde, bases, eh_frame, }); } None } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/arch/x86.rs
src/unwinder/arch/x86.rs
use core::fmt; use core::ops; use gimli::{Register, X86}; use super::maybe_cfi; // Match DWARF_FRAME_REGISTERS in libgcc pub const MAX_REG_RULES: usize = 17; #[repr(C)] #[derive(Clone, Default)] pub struct Context { pub registers: [usize; 8], pub ra: usize, pub mcxsr: usize, pub fcw: usize, } impl fmt::Debug for Context { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("Context"); for i in 0..=7 { fmt.field( X86::register_name(Register(i as _)).unwrap(), &self.registers[i], ); } fmt.field("ra", &self.ra) .field("mcxsr", &self.mcxsr) .field("fcw", &self.fcw) .finish() } } impl ops::Index<Register> for Context { type Output = usize; fn index(&self, reg: Register) -> &usize { match reg { Register(0..=7) => &self.registers[reg.0 as usize], X86::RA => &self.ra, X86::MXCSR => &self.mcxsr, _ => unimplemented!(), } } } impl ops::IndexMut<gimli::Register> for Context { fn index_mut(&mut self, reg: Register) -> &mut usize { match reg { Register(0..=7) => &mut self.registers[reg.0 as usize], X86::RA => &mut self.ra, X86::MXCSR => &mut self.mcxsr, _ => unimplemented!(), } } } #[unsafe(naked)] pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), ptr: *mut ()) { // No need to save caller-saved registers here. core::arch::naked_asm!( maybe_cfi!(".cfi_startproc"), "sub esp, 52", maybe_cfi!(".cfi_def_cfa_offset 56"), " mov [esp + 4], ecx mov [esp + 8], edx mov [esp + 12], ebx /* Adjust the stack to account for the return address */ lea eax, [esp + 56] mov [esp + 16], eax mov [esp + 20], ebp mov [esp + 24], esi mov [esp + 28], edi /* Return address */ mov eax, [esp + 52] mov [esp + 32], eax stmxcsr [esp + 36] fnstcw [esp + 40] mov eax, [esp + 60] mov ecx, esp push eax ", maybe_cfi!(".cfi_adjust_cfa_offset 4"), "push ecx", maybe_cfi!(".cfi_adjust_cfa_offset 4"), " call [esp + 64] add esp, 60 ", maybe_cfi!(".cfi_def_cfa_offset 4"), "ret", maybe_cfi!(".cfi_endproc"), ); } pub unsafe fn restore_context(ctx: &Context) -> ! { unsafe { core::arch::asm!( " /* Restore stack */ mov esp, [edx + 16] /* Restore callee-saved control registers */ ldmxcsr [edx + 36] fldcw [edx + 40] /* Restore return address */ mov eax, [edx + 32] push eax /* * Restore general-purpose registers. Non-callee-saved registers are * also restored because sometimes it's used to pass unwind arguments. */ mov eax, [edx + 0] mov ecx, [edx + 4] mov ebx, [edx + 12] mov ebp, [edx + 20] mov esi, [edx + 24] mov edi, [edx + 28] /* EDX restored last */ mov edx, [edx + 8] ret ", in("edx") ctx, options(noreturn) ); } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/arch/riscv64.rs
src/unwinder/arch/riscv64.rs
use core::fmt; use core::ops; use gimli::{Register, RiscV}; use super::maybe_cfi; // Match DWARF_FRAME_REGISTERS in libgcc pub const MAX_REG_RULES: usize = 65; #[cfg(all(target_feature = "f", not(target_feature = "d")))] compile_error!("RISC-V with only F extension is not supported"); #[repr(C)] #[derive(Clone, Default)] pub struct Context { pub gp: [usize; 32], #[cfg(target_feature = "d")] pub fp: [usize; 32], } impl fmt::Debug for Context { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("Context"); for i in 0..=31 { fmt.field(RiscV::register_name(Register(i as _)).unwrap(), &self.gp[i]); } #[cfg(target_feature = "d")] for i in 0..=31 { fmt.field( RiscV::register_name(Register((i + 32) as _)).unwrap(), &self.fp[i], ); } fmt.finish() } } impl ops::Index<Register> for Context { type Output = usize; fn index(&self, reg: Register) -> &usize { match reg { Register(0..=31) => &self.gp[reg.0 as usize], #[cfg(target_feature = "d")] Register(32..=63) => &self.fp[(reg.0 - 32) as usize], _ => unimplemented!(), } } } impl ops::IndexMut<gimli::Register> for Context { fn index_mut(&mut self, reg: Register) -> &mut usize { match reg { Register(0..=31) => &mut self.gp[reg.0 as usize], #[cfg(target_feature = "d")] Register(32..=63) => &mut self.fp[(reg.0 - 32) as usize], _ => unimplemented!(), } } } macro_rules! code { (save_gp) => { " sd x0, 0x00(sp) sd ra, 0x08(sp) sd t0, 0x10(sp) sd gp, 0x18(sp) sd tp, 0x20(sp) sd s0, 0x40(sp) sd s1, 0x48(sp) sd s2, 0x90(sp) sd s3, 0x98(sp) sd s4, 0xA0(sp) sd s5, 0xA8(sp) sd s6, 0xB0(sp) sd s7, 0xB8(sp) sd s8, 0xC0(sp) sd s9, 0xC8(sp) sd s10, 0xD0(sp) sd s11, 0xD8(sp) " }; (save_fp) => { // arch option manipulation needed due to LLVM/Rust bug, see rust-lang/rust#80608 " .option push .option arch, +d fsd fs0, 0x140(sp) fsd fs1, 0x148(sp) fsd fs2, 0x190(sp) fsd fs3, 0x198(sp) fsd fs4, 0x1A0(sp) fsd fs5, 0x1A8(sp) fsd fs6, 0x1B0(sp) fsd fs7, 0x1B8(sp) fsd fs8, 0x1C0(sp) fsd fs9, 0x1C8(sp) fsd fs10, 0x1D0(sp) fsd fs11, 0x1D8(sp) .option pop " }; (restore_gp) => { " ld ra, 0x08(a0) ld sp, 0x10(a0) ld gp, 0x18(a0) ld tp, 0x20(a0) ld t0, 0x28(a0) ld t1, 0x30(a0) ld t2, 0x38(a0) ld s0, 0x40(a0) ld s1, 0x48(a0) ld a1, 0x58(a0) ld a2, 0x60(a0) ld a3, 0x68(a0) ld a4, 0x70(a0) ld a5, 0x78(a0) ld a6, 0x80(a0) ld a7, 0x88(a0) ld s2, 0x90(a0) ld s3, 0x98(a0) ld s4, 0xA0(a0) ld s5, 0xA8(a0) ld s6, 0xB0(a0) ld s7, 0xB8(a0) ld s8, 0xC0(a0) ld s9, 0xC8(a0) ld s10, 0xD0(a0) ld s11, 0xD8(a0) ld t3, 0xE0(a0) ld t4, 0xE8(a0) ld t5, 0xF0(a0) ld t6, 0xF8(a0) " }; (restore_fp) => { " fld ft0, 0x100(a0) fld ft1, 0x108(a0) fld ft2, 0x110(a0) fld ft3, 0x118(a0) fld ft4, 0x120(a0) fld ft5, 0x128(a0) fld ft6, 0x130(a0) fld ft7, 0x138(a0) fld fs0, 0x140(a0) fld fs1, 0x148(a0) fld fa0, 0x150(a0) fld fa1, 0x158(a0) fld fa2, 0x160(a0) fld fa3, 0x168(a0) fld fa4, 0x170(a0) fld fa5, 0x178(a0) fld fa6, 0x180(a0) fld fa7, 0x188(a0) fld fs2, 0x190(a0) fld fs3, 0x198(a0) fld fs4, 0x1A0(a0) fld fs5, 0x1A8(a0) fld fs6, 0x1B0(a0) fld fs7, 0x1B8(a0) fld fs8, 0x1C0(a0) fld fs9, 0x1C8(a0) fld fs10, 0x1D0(a0) fld fs11, 0x1D8(a0) fld ft8, 0x1E0(a0) fld ft9, 0x1E8(a0) fld ft10, 0x1F0(a0) fld ft11, 0x1F8(a0) " }; } #[unsafe(naked)] pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), ptr: *mut ()) { // No need to save caller-saved registers here. #[cfg(target_feature = "d")] core::arch::naked_asm!( maybe_cfi!(".cfi_startproc"), " mv t0, sp add sp, sp, -0x210 ", maybe_cfi!(".cfi_def_cfa_offset 0x210"), "sd ra, 0x200(sp)", maybe_cfi!(".cfi_offset ra, -16"), code!(save_gp), code!(save_fp), " mv t0, a0 mv a0, sp jalr t0 ld ra, 0x200(sp) add sp, sp, 0x210 ", maybe_cfi!(".cfi_def_cfa_offset 0"), maybe_cfi!(".cfi_restore ra"), "ret", maybe_cfi!(".cfi_endproc"), ); #[cfg(not(target_feature = "d"))] core::arch::naked_asm!( maybe_cfi!(".cfi_startproc"), " mv t0, sp add sp, sp, -0x110 ", maybe_cfi!(".cfi_def_cfa_offset 0x110"), "sd ra, 0x100(sp)", maybe_cfi!(".cfi_offset ra, -16"), code!(save_gp), " mv t0, a0 mv a0, sp jalr t0 ld ra, 0x100(sp) add sp, sp, 0x110 ", maybe_cfi!(".cfi_def_cfa_offset 0"), maybe_cfi!(".cfi_restore ra"), "ret", maybe_cfi!(".cfi_endproc"), ); } pub unsafe fn restore_context(ctx: &Context) -> ! { #[cfg(target_feature = "d")] unsafe { core::arch::asm!( code!(restore_fp), code!(restore_gp), " ld a0, 0x50(a0) ret ", in("a0") ctx, options(noreturn) ); } #[cfg(not(target_feature = "d"))] unsafe { core::arch::asm!( code!(restore_gp), " ld a0, 0x50(a0) ret ", in("a0") ctx, options(noreturn) ); } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/arch/x86_64.rs
src/unwinder/arch/x86_64.rs
use core::fmt; use core::ops; use gimli::{Register, X86_64}; use super::maybe_cfi; // Match DWARF_FRAME_REGISTERS in libgcc pub const MAX_REG_RULES: usize = 17; #[repr(C)] #[derive(Clone, Default)] pub struct Context { pub registers: [usize; 16], pub ra: usize, pub mcxsr: usize, pub fcw: usize, } impl fmt::Debug for Context { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("Context"); for i in 0..=15 { fmt.field( X86_64::register_name(Register(i as _)).unwrap(), &self.registers[i], ); } fmt.field("ra", &self.ra) .field("mcxsr", &self.mcxsr) .field("fcw", &self.fcw) .finish() } } impl ops::Index<Register> for Context { type Output = usize; fn index(&self, reg: Register) -> &usize { match reg { Register(0..=15) => &self.registers[reg.0 as usize], X86_64::RA => &self.ra, X86_64::MXCSR => &self.mcxsr, X86_64::FCW => &self.fcw, _ => unimplemented!(), } } } impl ops::IndexMut<gimli::Register> for Context { fn index_mut(&mut self, reg: Register) -> &mut usize { match reg { Register(0..=15) => &mut self.registers[reg.0 as usize], X86_64::RA => &mut self.ra, X86_64::MXCSR => &mut self.mcxsr, X86_64::FCW => &mut self.fcw, _ => unimplemented!(), } } } #[unsafe(naked)] pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), ptr: *mut ()) { // No need to save caller-saved registers here. core::arch::naked_asm!( maybe_cfi!(".cfi_startproc"), "sub rsp, 0x98", maybe_cfi!(".cfi_def_cfa_offset 0xA0"), " mov [rsp + 0x18], rbx mov [rsp + 0x30], rbp /* Adjust the stack to account for the return address */ lea rax, [rsp + 0xA0] mov [rsp + 0x38], rax mov [rsp + 0x60], r12 mov [rsp + 0x68], r13 mov [rsp + 0x70], r14 mov [rsp + 0x78], r15 /* Return address */ mov rax, [rsp + 0x98] mov [rsp + 0x80], rax stmxcsr [rsp + 0x88] fnstcw [rsp + 0x90] mov rax, rdi mov rdi, rsp call rax add rsp, 0x98 ", maybe_cfi!(".cfi_def_cfa_offset 8"), "ret", maybe_cfi!(".cfi_endproc"), ); } pub unsafe fn restore_context(ctx: &Context) -> ! { unsafe { core::arch::asm!( " /* Restore stack */ mov rsp, [rdi + 0x38] /* Restore callee-saved control registers */ ldmxcsr [rdi + 0x88] fldcw [rdi + 0x90] /* Restore return address */ mov rax, [rdi + 0x80] push rax /* * Restore general-purpose registers. Non-callee-saved registers are * also restored because sometimes it's used to pass unwind arguments. */ mov rax, [rdi + 0x00] mov rdx, [rdi + 0x08] mov rcx, [rdi + 0x10] mov rbx, [rdi + 0x18] mov rsi, [rdi + 0x20] mov rbp, [rdi + 0x30] mov r8 , [rdi + 0x40] mov r9 , [rdi + 0x48] mov r10, [rdi + 0x50] mov r11, [rdi + 0x58] mov r12, [rdi + 0x60] mov r13, [rdi + 0x68] mov r14, [rdi + 0x70] mov r15, [rdi + 0x78] /* RDI restored last */ mov rdi, [rdi + 0x28] ret ", in("rdi") ctx, options(noreturn) ); } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/arch/mod.rs
src/unwinder/arch/mod.rs
#[cfg(target_arch = "x86_64")] mod x86_64; #[cfg(target_arch = "x86_64")] pub use x86_64::*; #[cfg(target_arch = "x86")] mod x86; #[cfg(target_arch = "x86")] pub use x86::*; #[cfg(target_arch = "riscv64")] mod riscv64; #[cfg(target_arch = "riscv64")] pub use riscv64::*; #[cfg(target_arch = "riscv32")] mod riscv32; #[cfg(target_arch = "riscv32")] pub use riscv32::*; #[cfg(target_arch = "aarch64")] mod aarch64; #[cfg(target_arch = "aarch64")] pub use aarch64::*; #[cfg(not(any( target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64", target_arch = "riscv32", target_arch = "aarch64" )))] compile_error!("Current architecture is not supported"); // CFI directives cannot be used if neither debuginfo nor panic=unwind is enabled. // We don't have an easy way to check the former, so just check based on panic strategy. #[cfg(panic = "abort")] macro_rules! maybe_cfi { ($x: literal) => { "" }; } #[cfg(panic = "unwind")] macro_rules! maybe_cfi { ($x: literal) => { $x }; } pub(crate) use maybe_cfi;
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/arch/aarch64.rs
src/unwinder/arch/aarch64.rs
use core::fmt; use core::ops; use gimli::{AArch64, Register}; use super::maybe_cfi; // Match DWARF_FRAME_REGISTERS in libgcc pub const MAX_REG_RULES: usize = 97; #[repr(C)] #[derive(Clone, Default)] pub struct Context { pub gp: [usize; 31], pub sp: usize, pub fp: [usize; 32], } impl fmt::Debug for Context { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("Context"); for i in 0..=30 { fmt.field( AArch64::register_name(Register(i as _)).unwrap(), &self.gp[i], ); } fmt.field("sp", &self.sp); for i in 0..=31 { fmt.field( AArch64::register_name(Register((i + 64) as _)).unwrap(), &self.fp[i], ); } fmt.finish() } } impl ops::Index<Register> for Context { type Output = usize; fn index(&self, reg: Register) -> &usize { match reg { Register(0..=30) => &self.gp[reg.0 as usize], AArch64::SP => &self.sp, Register(64..=95) => &self.fp[(reg.0 - 64) as usize], _ => unimplemented!(), } } } impl ops::IndexMut<gimli::Register> for Context { fn index_mut(&mut self, reg: Register) -> &mut usize { match reg { Register(0..=30) => &mut self.gp[reg.0 as usize], AArch64::SP => &mut self.sp, Register(64..=95) => &mut self.fp[(reg.0 - 64) as usize], _ => unimplemented!(), } } } macro_rules! save { (gp$(, $fp:ident)?) => { // No need to save caller-saved registers here. core::arch::naked_asm!( maybe_cfi!(".cfi_startproc"), "stp x29, x30, [sp, -16]!", maybe_cfi!(" .cfi_def_cfa_offset 16 .cfi_offset x29, -16 .cfi_offset x30, -8 "), "sub sp, sp, 512", maybe_cfi!(".cfi_def_cfa_offset 528"), " mov x8, x0 mov x0, sp ", save!(maybesavefp($($fp)?)), " str x19, [sp, 0x98] stp x20, x21, [sp, 0xA0] stp x22, x23, [sp, 0xB0] stp x24, x25, [sp, 0xC0] stp x26, x27, [sp, 0xD0] stp x28, x29, [sp, 0xE0] add x2, sp, 528 stp x30, x2, [sp, 0xF0] blr x8 add sp, sp, 512 ", maybe_cfi!(".cfi_def_cfa_offset 16"), "ldp x29, x30, [sp], 16", maybe_cfi!(" .cfi_def_cfa_offset 0 .cfi_restore x29 .cfi_restore x30 "), "ret", maybe_cfi!(".cfi_endproc"), ); }; (maybesavefp(fp)) => { " stp d8, d9, [sp, 0x140] stp d10, d11, [sp, 0x150] stp d12, d13, [sp, 0x160] stp d14, d15, [sp, 0x170] " }; (maybesavefp()) => { "" }; } #[unsafe(naked)] pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), ptr: *mut ()) { #[cfg(target_feature = "neon")] save!(gp, fp); #[cfg(not(target_feature = "neon"))] save!(gp); } macro_rules! restore { ($ctx:expr, gp$(, $fp:ident)?) => { core::arch::asm!( restore!(mayberestore($($fp)?)), " ldp x2, x3, [x0, 0x10] ldp x4, x5, [x0, 0x20] ldp x6, x7, [x0, 0x30] ldp x8, x9, [x0, 0x40] ldp x10, x11, [x0, 0x50] ldp x12, x13, [x0, 0x60] ldp x14, x15, [x0, 0x70] ldp x16, x17, [x0, 0x80] ldp x18, x19, [x0, 0x90] ldp x20, x21, [x0, 0xA0] ldp x22, x23, [x0, 0xB0] ldp x24, x25, [x0, 0xC0] ldp x26, x27, [x0, 0xD0] ldp x28, x29, [x0, 0xE0] ldp x30, x1, [x0, 0xF0] mov sp, x1 ldp x0, x1, [x0, 0x00] ret ", in("x0") $ctx, options(noreturn) ); }; (mayberestore(fp)) => { " ldp d0, d1, [x0, 0x100] ldp d2, d3, [x0, 0x110] ldp d4, d5, [x0, 0x120] ldp d6, d7, [x0, 0x130] ldp d8, d9, [x0, 0x140] ldp d10, d11, [x0, 0x150] ldp d12, d13, [x0, 0x160] ldp d14, d15, [x0, 0x170] ldp d16, d17, [x0, 0x180] ldp d18, d19, [x0, 0x190] ldp d20, d21, [x0, 0x1A0] ldp d22, d23, [x0, 0x1B0] ldp d24, d25, [x0, 0x1C0] ldp d26, d27, [x0, 0x1D0] ldp d28, d29, [x0, 0x1E0] ldp d30, d31, [x0, 0x1F0] " }; (mayberestore()) => { "" }; } pub unsafe fn restore_context(ctx: &Context) -> ! { unsafe { #[cfg(target_feature = "neon")] restore!(ctx, gp, fp); #[cfg(not(target_feature = "neon"))] restore!(ctx, gp); } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/src/unwinder/arch/riscv32.rs
src/unwinder/arch/riscv32.rs
use core::fmt; use core::ops; use gimli::{Register, RiscV}; use super::maybe_cfi; // Match DWARF_FRAME_REGISTERS in libgcc pub const MAX_REG_RULES: usize = 65; #[cfg(all(target_feature = "f", not(target_feature = "d")))] compile_error!("RISC-V with only F extension is not supported"); #[repr(C)] #[derive(Clone, Default)] pub struct Context { pub gp: [usize; 32], #[cfg(target_feature = "d")] pub fp: [u64; 32], } impl fmt::Debug for Context { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("Context"); for i in 0..=31 { fmt.field(RiscV::register_name(Register(i as _)).unwrap(), &self.gp[i]); } #[cfg(target_feature = "d")] for i in 0..=31 { fmt.field( RiscV::register_name(Register((i + 32) as _)).unwrap(), &self.fp[i], ); } fmt.finish() } } impl ops::Index<Register> for Context { type Output = usize; fn index(&self, reg: Register) -> &usize { match reg { Register(0..=31) => &self.gp[reg.0 as usize], // We cannot support indexing fp here. It is 64-bit if D extension is implemented, // and 32-bit if only F extension is implemented. _ => unimplemented!(), } } } impl ops::IndexMut<gimli::Register> for Context { fn index_mut(&mut self, reg: Register) -> &mut usize { match reg { Register(0..=31) => &mut self.gp[reg.0 as usize], // We cannot support indexing fp here. It is 64-bit if D extension is implemented, // and 32-bit if only F extension is implemented. _ => unimplemented!(), } } } macro_rules! code { (save_gp) => { " sw x0, 0x00(sp) sw ra, 0x04(sp) sw t0, 0x08(sp) sw gp, 0x0C(sp) sw tp, 0x10(sp) sw s0, 0x20(sp) sw s1, 0x24(sp) sw s2, 0x48(sp) sw s3, 0x4C(sp) sw s4, 0x50(sp) sw s5, 0x54(sp) sw s6, 0x58(sp) sw s7, 0x5C(sp) sw s8, 0x60(sp) sw s9, 0x64(sp) sw s10, 0x68(sp) sw s11, 0x6C(sp) " }; (save_fp) => { // arch option manipulation needed due to LLVM/Rust bug, see rust-lang/rust#80608 " .option push .option arch, +d fsd fs0, 0xC0(sp) fsd fs1, 0xC8(sp) fsd fs2, 0x110(sp) fsd fs3, 0x118(sp) fsd fs4, 0x120(sp) fsd fs5, 0x128(sp) fsd fs6, 0x130(sp) fsd fs7, 0x138(sp) fsd fs8, 0x140(sp) fsd fs9, 0x148(sp) fsd fs10, 0x150(sp) fsd fs11, 0x158(sp) .option pop " }; (restore_gp) => { " lw ra, 0x04(a0) lw sp, 0x08(a0) lw gp, 0x0C(a0) lw tp, 0x10(a0) lw t0, 0x14(a0) lw t1, 0x18(a0) lw t2, 0x1C(a0) lw s0, 0x20(a0) lw s1, 0x24(a0) lw a1, 0x2C(a0) lw a2, 0x30(a0) lw a3, 0x34(a0) lw a4, 0x38(a0) lw a5, 0x3C(a0) lw a6, 0x40(a0) lw a7, 0x44(a0) lw s2, 0x48(a0) lw s3, 0x4C(a0) lw s4, 0x50(a0) lw s5, 0x54(a0) lw s6, 0x58(a0) lw s7, 0x5C(a0) lw s8, 0x60(a0) lw s9, 0x64(a0) lw s10, 0x68(a0) lw s11, 0x6C(a0) lw t3, 0x70(a0) lw t4, 0x74(a0) lw t5, 0x78(a0) lw t6, 0x7C(a0) " }; (restore_fp) => { " fld ft0, 0x80(a0) fld ft1, 0x88(a0) fld ft2, 0x90(a0) fld ft3, 0x98(a0) fld ft4, 0xA0(a0) fld ft5, 0xA8(a0) fld ft6, 0xB0(a0) fld ft7, 0xB8(a0) fld fs0, 0xC0(a0) fld fs1, 0xC8(a0) fld fa0, 0xD0(a0) fld fa1, 0xD8(a0) fld fa2, 0xE0(a0) fld fa3, 0xE8(a0) fld fa4, 0xF0(a0) fld fa5, 0xF8(a0) fld fa6, 0x100(a0) fld fa7, 0x108(a0) fld fs2, 0x110(a0) fld fs3, 0x118(a0) fld fs4, 0x120(a0) fld fs5, 0x128(a0) fld fs6, 0x130(a0) fld fs7, 0x138(a0) fld fs8, 0x140(a0) fld fs9, 0x148(a0) fld fs10, 0x150(a0) fld fs11, 0x158(a0) fld ft8, 0x160(a0) fld ft9, 0x168(a0) fld ft10, 0x170(a0) fld ft11, 0x178(a0) " }; } #[unsafe(naked)] pub extern "C-unwind" fn save_context(f: extern "C" fn(&mut Context, *mut ()), ptr: *mut ()) { // No need to save caller-saved registers here. #[cfg(target_feature = "d")] core::arch::naked_asm!( maybe_cfi!(".cfi_startproc"), " mv t0, sp add sp, sp, -0x190 ", maybe_cfi!(".cfi_def_cfa_offset 0x190"), "sw ra, 0x180(sp)", maybe_cfi!(".cfi_offset ra, -16"), code!(save_gp), code!(save_fp), " mv t0, a0 mv a0, sp jalr t0 lw ra, 0x180(sp) add sp, sp, 0x190 ", maybe_cfi!(".cfi_def_cfa_offset 0"), maybe_cfi!(".cfi_restore ra"), "ret", maybe_cfi!(".cfi_endproc"), ); #[cfg(not(target_feature = "d"))] core::arch::naked_asm!( maybe_cfi!(".cfi_startproc"), " mv t0, sp add sp, sp, -0x90 ", maybe_cfi!(".cfi_def_cfa_offset 0x90"), "sw ra, 0x80(sp)", maybe_cfi!(".cfi_offset ra, -16"), code!(save_gp), " mv t0, a0 mv a0, sp jalr t0 lw ra, 0x80(sp) add sp, sp, 0x90 ", maybe_cfi!(".cfi_def_cfa_offset 0"), maybe_cfi!(".cfi_restore ra"), "ret", maybe_cfi!(".cfi_endproc") ); } pub unsafe fn restore_context(ctx: &Context) -> ! { #[cfg(target_feature = "d")] unsafe { core::arch::asm!( code!(restore_fp), code!(restore_gp), " lw a0, 0x28(a0) ret ", in("a0") ctx, options(noreturn) ); } #[cfg(not(target_feature = "d"))] unsafe { core::arch::asm!( code!(restore_gp), " lw a0, 0x28(a0) ret ", in("a0") ctx, options(noreturn) ); } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/tests/compile_tests.rs
tests/compile_tests.rs
use std::process::Command; #[test] fn main() { let dir = env!("CARGO_MANIFEST_DIR"); let tests = [ "throw_and_catch", "catch_std_exception", "std_catch_exception", "panic_abort_no_debuginfo", ]; for test in tests { let status = Command::new("./check.sh") .current_dir(format!("{dir}/test_crates/{test}")) .status() .unwrap(); assert!(status.success()); } }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/test_crates/panic_abort_no_debuginfo/src/main.rs
test_crates/panic_abort_no_debuginfo/src/main.rs
extern crate unwinding; fn main() {}
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/test_crates/std_catch_exception/src/main.rs
test_crates/std_catch_exception/src/main.rs
extern crate unwinding; fn main() { let _ = std::panic::catch_unwind(|| { unwinding::panic::begin_panic(Box::new("test")); }); }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/test_crates/catch_std_exception/src/main.rs
test_crates/catch_std_exception/src/main.rs
extern crate unwinding; fn main() { let _ = unwinding::panic::catch_unwind(|| { panic!(); }); }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
nbdd0121/unwinding
https://github.com/nbdd0121/unwinding/blob/3bc28cec6c30eade0e1caa094b49db78101b19ef/test_crates/throw_and_catch/src/main.rs
test_crates/throw_and_catch/src/main.rs
#![no_std] #![no_main] extern crate alloc; extern crate unwinding; use alloc::{borrow::ToOwned, string::String}; use unwinding::print::*; #[link(name = "c")] unsafe extern "C" {} struct PrintOnDrop(String); impl Drop for PrintOnDrop { fn drop(&mut self) { eprintln!("dropped: {:?}", self.0); } } struct PanicOnDrop; impl Drop for PanicOnDrop { fn drop(&mut self) { panic!("panic on drop"); } } #[track_caller] fn foo() { panic!("panic"); } fn bar() { let _p = PrintOnDrop("string".to_owned()); foo() } fn main() { let _ = unwinding::panic::catch_unwind(|| { bar(); eprintln!("done"); }); eprintln!("caught"); let _p = PanicOnDrop; foo(); } #[unsafe(export_name = "main")] extern "C" fn start(_argc: isize, _argv: *const *const u8) -> isize { unwinding::panic::catch_unwind(|| { main(); 0 }) .unwrap_or(101) }
rust
Apache-2.0
3bc28cec6c30eade0e1caa094b49db78101b19ef
2026-01-04T20:23:52.098121Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/lib.rs
src/lib.rs
/*! A Rust implementation of the [XQuery and XPath Data Model 3.1](https://www.w3.org/TR/xpath-datamodel-31/) and [XSLT 3.0](http://www.w3.org/TR/xslt-30/). The idea is to separate the syntax from the semantics. A [Transform] performs the semantics; an XPath expression or XSL Stylesheet is the syntax that is mapped to a [Transform]. ## Transformation A [Transform] is used to create a [Sequence], starting with a [Context]. A [Sequence] is the basic data type in XPath. It is an ordered collection of zero or more [Item]s, implemented as a Rust vector, i.e. ```Vec<Rc<Item>>```. An [Item] is a [Node], Function, or atomic [Value]. Once a [Context] is configured, it can be used to execute a [Transform] using the evaluate method. The return result is a new [Sequence]. ## Trees The [Transform] engine reads a tree structure as its source document and produces a tree structure as its result document. The tree needs to be both navigable and mutable. Tree nodes are defined by the [Item] module's [Node] trait. The module trees::intmuttree is an implementation of the [Node] trait. ## Parsing XML Parsing XML documents is done using the built-in parser combinator: [parser]. The parser supports XML Namespaces, and DTDs (entities, but not validation). ## XPath Support for XPath involves mapping the XPath syntax to a [Transform]. The XPath parser maps an expression to a [Transform]. ### Patterns XPath [Pattern]s are also supported. These are used to match nodes, mainly when template processing. ### Status Most of functionality for v1.0 is present, with some v2.0 and v3.1 features. ## XSLT Support for XSLT involves mapping an XSL Stylesheet to a [Context]. The [xslt] module provides the ```from_document``` function that returns a [Context] populated with [Template]s, given an XSL Stylesheet document. ### Status The XSLT implementation is functionally equivalent to XSLT 1.0, but is not compliant to v1.0. This is because Xrust implements the v3.0 data model. All the elements and functions in XPath 1.0 and XSLT 1.0 are implemented. It supports basic templating, literal result elements, element, text, attribute, comment and processing instruction creation, sequence, and messages. Also, conditionals (if, choose), repetition (for-each, for-each-group), copying (copy, copy-of), and inclusion/importing. NB, the library has not been extensively tested. ### External Resources One aim of the library is to be usable in a WASM environment. To allow that, the library must not have dependencies on file and network I/O, since that is provided by the host browser environment. Where external resources, i.e. URLs, are required the application must provide a closure. In particular, closures must be provided for stylesheet inclusion and importing, as well as for messages. ## Plan 1. Complete the XPath 1.0 implementation. (Done!) 2. Implement all v1.0 XSLT functionality. (Done!) 3. Implement all XPath 3.1 data model, data types, and functions. 4. Complete the v3.1 XSLT engine. ## Contributions We need your help! - Download the crate and try it out. Tell us what you like or don't like. How can it be improved? - There are definitely gaps and missing parts in the v1.0 XPath and XSLT implementation. Let us know if you need them fixed. [Submit a bug report.](https://github.com/ballsteve/xrust/issues/new/choose) - Let us know what doesn't work. [Submit a bug report.](https://github.com/ballsteve/xrust/issues/new/choose) - Do you need more documentation? There can never be enough! [Submit an RFE.](https://github.com/ballsteve/xrust/issues/new/choose) - Add some tests. - Write some code. The χrust Wiki has a [list of desired features](https://github.com/ballsteve/xrust/wiki/Help-Wanted). - Donate resources (i.e. $$$) */ pub mod xdmerror; pub use xdmerror::{Error, ErrorKind}; pub mod externals; pub mod output; pub mod qname; pub mod xmldecl; pub mod value; pub use value::Value; pub mod item; pub use item::{Item, Node, Sequence, SequenceTrait}; pub mod pattern; pub use pattern::Pattern; #[cfg(feature = "xslt")] pub mod xslt; pub mod parser; pub mod transform; pub use transform::context::Context; pub use transform::template::Template; pub use transform::Transform; pub mod trees; pub mod namespace; pub mod testutils; pub mod validators;
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/pattern.rs
src/pattern.rs
/*! # Support for XPath patterns. This module provides both a parser to compile a [Pattern], and an interpreter to determine if an item matches a compiled pattern. Patterns are defined in XSLT 3.0 5.5.2. A string can be compiled as [Pattern] by using the ```try_from``` associated function. ```rust # use xrust::item::Node; use xrust::pattern::Pattern; # fn compile<N: Node>() { let p: Pattern<N> = Pattern::try_from("child::foobar") .expect("unable to compile pattern"); # () # } ``` An [Item] can then be tested to see if it matches the [Pattern]. To do that, it is necessary to have a transformation [Context]. ```rust # use std::rc::Rc; # use xrust::ErrorKind; # use xrust::xdmerror::Error; # use xrust::item::{Item, NodeType}; # use xrust::pattern::Pattern; # use xrust::transform::context::{Context, StaticContext, StaticContextBuilder}; # use xrust::Node; # use xrust::trees::smite::RNode; # type F = Box<dyn FnMut(&str) -> Result<(), Error>>; let p = Pattern::try_from("/").expect("unable to compile pattern"); let n = Item::Node(RNode::new_document()); // Create a static context let mut static_context = StaticContextBuilder::new() .message(|_| Ok(())) .fetcher(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) .parser(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) .build(); // This pattern matches the root node assert_eq!(p.matches(&Context::new(), &mut static_context, &n), true) ``` ```rust # use std::rc::Rc; # use xrust::xdmerror::{Error, ErrorKind}; # use xrust::item::{Item, NodeType}; # use xrust::pattern::Pattern; # use xrust::transform::context::{Context, StaticContext, StaticContextBuilder}; # use xrust::Node; # use xrust::trees::smite::RNode; # type F = Box<dyn FnMut(&str) -> Result<(), Error>>; let p = Pattern::try_from("child::foobar").expect("unable to compile pattern"); let n = Item::Node(RNode::new_document()); // Create a static context # let mut static_context = StaticContextBuilder::new() # .message(|_| Ok(())) # .fetcher(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) # .parser(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) # .build(); // This pattern will not match because "n" is not an element named "foobar" assert_eq!(p.matches(&Context::new(), &mut static_context, &n), false) ``` */ use std::convert::TryFrom; use std::fmt; use std::fmt::{Debug, Formatter}; use std::rc::Rc; use url::Url; use crate::item::{Item, Node, NodeType, Sequence, SequenceTrait}; use crate::parser::combinators::whitespace::xpwhitespace; use crate::parser::xpath::literals::literal; use crate::parser::xpath::nodetests::{nodetest, qualname_test}; use crate::parser::xpath::predicates::predicate_list; use crate::parser::xpath::variables::variable_reference; use crate::transform::context::{Context, ContextBuilder, StaticContext}; use crate::transform::{Axis, KindTest, NameTest, NodeTest, Transform, WildcardOrName}; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use crate::parser::combinators::alt::{alt2, alt4, alt6}; //use crate::parser::combinators::debug::inspect; use crate::parser::combinators::list::{separated_list0, separated_list1}; use crate::parser::combinators::many::many0; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::pair::pair; use crate::parser::combinators::tag::tag; use crate::parser::combinators::tuple::{tuple2, tuple3}; use crate::parser::{ParseError, ParseInput, ParserState}; /// An XPath pattern. A pattern most frequently appears as the value of a match attribute. /// A pattern is either a predicate pattern or a selection pattern. /// /// A predicate pattern matches the current item if all of the predicates evaluate to true. /// /// A selection pattern is subset of XPath path expressions. #[derive(Clone)] pub enum Pattern<N: Node> { Predicate(Transform<N>), Selection(Path), Error(Error), } impl<N: Node> Pattern<N> { /// Returns whether the Pattern is of type error. pub fn is_err(&self) -> bool { if let Pattern::Selection(s) = self { s.is_err() } else { matches!(self, Pattern::Error(_)) } } pub fn get_err(&self) -> Option<Error> { if let Pattern::Selection(s) = self { s.get_err() } else if let Pattern::Error(e) = self { Some(e.clone()) } else { None } } /// Returns whether the given item matches the pattern. /// TODO: return dynamic errors pub fn matches< F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( &self, ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, i: &Item<N>, ) -> bool { match self { Pattern::Predicate(t) => ContextBuilder::from(ctxt) .context(vec![i.clone()]) .build() .dispatch(stctxt, t) .unwrap_or(vec![Item::Value(Rc::new(Value::from(false)))]) .to_bool(), Pattern::Selection(p) => path_match(p, i), _ => false, // not yet implemented } } /// Find the NodeTest for the terminal step pub fn terminal_node_test(&self) -> (Axis, Axis, NodeTest) { if let Pattern::Selection(sel) = self { branch_terminal_node_test(sel) } else { ( Axis::SelfDocument, Axis::SelfDocument, NodeTest::Kind(KindTest::Document), ) } } } fn branch_terminal_node_test(b: &Branch) -> (Axis, Axis, NodeTest) { match b { Branch::SingleStep(t) => (t.terminal, t.non_terminal, t.nt.clone()), Branch::RelPath(r) => branch_terminal_node_test(&r[0]), Branch::Union(u) => branch_terminal_node_test(&u[0]), // TODO: should be all of the alternatives Branch::Error(_) => ( Axis::SelfDocument, Axis::SelfDocument, NodeTest::Kind(KindTest::Document), ), } } // Entry point for matching a Pattern. // The given Item is the initial context. fn path_match<N: Node>(p: &Path, i: &Item<N>) -> bool { !branch_match(p, vec![i.clone()]).is_empty() } // Match a branch in the Pattern. Each Item in the Sequence is tested. // This results in a new context. fn branch_match<N: Node>(p: &Path, s: Sequence<N>) -> Sequence<N> { // First step is the terminal case, // next steps are non-terminal match p { Branch::SingleStep(t) => s .iter() .filter(|i| is_match(&t.terminal, &t.nt, i)) .flat_map(|i| find_seq(&t.non_terminal, i)) .collect(), Branch::RelPath(r) => { // A series of steps // Each step selects a new context for the next step r.iter().fold(s, |ctxt, b| { let new_ctxt = ctxt .iter() .cloned() .flat_map(|i| branch_match(b, vec![i])) .collect(); new_ctxt }) } Branch::Union(u) => { // If any match, then the whole matches u.iter() .flat_map(|b| { s.iter() .cloned() .flat_map(|i| branch_match(b, vec![i])) .collect::<Sequence<N>>() }) .collect() } Branch::Error(_) => vec![], } } fn find_seq<N: Node>(a: &Axis, i: &Item<N>) -> Sequence<N> { match a { Axis::SelfDocument => match i { Item::Node(n) => { if n.node_type() == NodeType::Document { vec![i.clone()] } else { vec![] } } _ => vec![], }, Axis::SelfAxis => vec![i.clone()], Axis::Parent => match i { Item::Node(n) => n.parent().map_or(vec![], |p| vec![Item::Node(p)]), _ => vec![], }, _ => vec![], // todo } } fn is_match<N: Node>(a: &Axis, nt: &NodeTest, i: &Item<N>) -> bool { match a { Axis::SelfDocument => { // Select item only if it is a document-type node match i { Item::Node(n) => { if n.node_type() == NodeType::Document { nt.matches(i) } else { false } } _ => false, } } Axis::SelfAxis => { // Select item if it is an element-type node nt.matches(i) } Axis::Parent => { // Select the parent node match i { Item::Node(n) => n.parent().map_or(false, |p| nt.matches(&Item::Node(p))), _ => false, } } _ => false, // todo } } impl<N: Node> Debug for Pattern<N> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Pattern::Predicate(t) => write!(f, "Pattern::Predicate t==\"{:?}\"", t), Pattern::Selection(p) => write!(f, "Pattern::Selection path=\"{:?}\"", p), Pattern::Error(e) => write!(f, "Pattern::Error error=\"{:?}\"", e), } } } // A Path is a tree structure, but does not need to be mutable. // It also does not need to be fully navigable. // A Path is a Branch. // A Branch::Union is caused by a union ("|") operator - // if any of the union branches match then the Path matches. // If the vector is empty then there is no match. // A Rel(ative)Path is caused by the "/" character. // The terminal case is a single Step. pub type Path = Branch; #[derive(Clone, Debug)] pub enum Branch { SingleStep(Step), RelPath(Vec<Branch>), Union(Vec<Branch>), Error(Error), } impl Branch { pub fn terminal_node_test(&self) -> (Axis, Axis, NodeTest) { branch_terminal_node_test(self) } /// Check whether the Branch is an error or contains an error pub fn is_err(&self) -> bool { match self { Branch::Error(_) => true, Branch::SingleStep(_) => false, Branch::RelPath(r) => r.iter().any(|f| f.is_err()), Branch::Union(u) => u.iter().any(|f| f.is_err()), } } /// Get any error in the Branch pub fn get_err(&self) -> Option<Error> { match self { Branch::Error(e) => Some(e.clone()), Branch::SingleStep(_) => None, Branch::RelPath(r) => r.iter().fold(None, |v, f| v.or_else(|| f.get_err())), Branch::Union(u) => u.iter().fold(None, |v, f| v.or_else(|| f.get_err())), } } } // * == Branch::SingleStep(*) // *|node() == Branch::Union(vec![Branch::SingleStep(*), Branch::SingleStep(node())]) // a/b == Branch::RelPath(vec![Branch::SingleStep(a), Branch::SingleStep(b)]) // a/b|c/d == Branch::Union(vec![ // Branch::RelPath(vec![Branch::SingleStep(a),Branch::SingleStep(b)]), // Branch::RelPath(vec![Branch::SingleStep(c),Branch::SingleStep(d)]), // ]) // a/(b|c)/d (matches a/b/d or a/c/d) == Branch::RelPath(vec![ // Branch::SingleStep(a), // Branch::Union(vec![Branch::SingleStep(b),Branch::SingleStep(c)]), // Branch::SingleStep(d) // ] // a/ (b/c | (d/e|f/g)) / (h|i) |j == Branch::Union(vec![ // Branch::RelPath(vec![ // Branch::SingleStep(a), // Branch::RelPath(vec![ // Branch::Union(vec![ // Branch::RelPath(vec![Branch::SingleStep(b), Branch::SingleStep(c)]), // Branch::Union(vec![ // Branch::RelPath(vec![Branch::SingleStep(d), Branch::SingleStep(e)]), // Branch::RelPath(vec![Branch::SingleStep(f), Branch::SingleStep(g)]), // ]), // ]), // Branch::Union(vec![ // Branch::SingleStep(h), // Branch::SingleStep(i), // ]) // ]), // ]), // Branch::SingleStep(j), // ] // A step in the Path consists of (terminal, non-terminal) axes and a NodeTest // If this is the last step, then the terminal axis is used. // Otherwise the non-terminal axis applies. #[derive(Clone, Debug)] pub struct Step { terminal: Axis, non_terminal: Axis, nt: NodeTest, } impl Step { pub fn new(terminal: Axis, non_terminal: Axis, nt: NodeTest) -> Self { Step { terminal, non_terminal, nt, } } pub fn get_ref(&self) -> (&Axis, &Axis, &NodeTest) { (&self.terminal, &self.non_terminal, &self.nt) } } /// Compile an XPath pattern. impl<N: Node> TryFrom<&str> for Pattern<N> { type Error = Error; fn try_from(e: &str) -> Result<Self, <crate::pattern::Pattern<N> as TryFrom<&str>>::Error> { if e.is_empty() { Err(Error::new( ErrorKind::TypeError, String::from("empty string is not allowed as an XPath pattern"), )) } else { let state = ParserState::new(None, None, None); match pattern::<N>((e, state)) { Ok(((rem, _), f)) => { if rem.is_empty() { Ok(f) } else { Err(Error::new( ErrorKind::Unknown, format!("extra characters found: \"{:?}\"", rem), )) } } Err(err) => Err(Error::new(ErrorKind::Unknown, format!("{:?}", err))), } } } } /// Compile an XPath pattern. Uses the supplied [Node] to resolve in-scope XML Namespaces. impl<N: Node> TryFrom<(&str, N)> for Pattern<N> { type Error = Error; fn try_from( e: (&str, N), ) -> Result<Self, <crate::pattern::Pattern<N> as TryFrom<&str>>::Error> { if e.0.is_empty() { Err(Error::new( ErrorKind::TypeError, String::from("empty string is not allowed as an XPath pattern"), )) } else { let state = ParserState::new(None, Some(e.1), None); match pattern::<N>((e.0, state)) { Ok(((rem, _), f)) => { if rem.is_empty() { Ok(f) } else { Err(Error::new( ErrorKind::Unknown, format!("extra characters found: \"{:?}\"", rem), )) } } Err(err) => Err(Error::new(ErrorKind::Unknown, format!("{:?}", err))), } } } } impl<'a, N: Node> TryFrom<String> for Pattern<N> { type Error = Error; fn try_from(e: String) -> Result<Self, <Pattern<N> as TryFrom<&'a str>>::Error> { Pattern::try_from(e.as_str()) } } impl<'a, N: Node> TryFrom<(String, N)> for Pattern<N> { type Error = Error; fn try_from(e: (String, N)) -> Result<Self, <Pattern<N> as TryFrom<(&'a str, N)>>::Error> { Pattern::try_from((e.0.as_str(), e.1)) } } // Pattern30 ::= PredicatePattern | UnionExprP ; fn pattern<N: Node>(input: ParseInput<N>) -> Result<(ParseInput<N>, Pattern<N>), ParseError> { alt2(predicate_pattern::<N>(), union_expr_pattern())(input) } // PredicatePattern ::= "." PredicateList // Context must match all predicates fn predicate_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Pattern<N>), ParseError> + 'a> { Box::new(map( pair( map(tuple3(xpwhitespace(), tag("."), xpwhitespace()), |_| ()), predicate_list::<N>(), ), |(_, p)| Pattern::Predicate(p), )) } // UnionExprP ::= IntersectExceptExprP (("union" | "|") IntersectExceptExprP)* // A union expression matches if any of its components is a match. This creates a branching structure in the compilation of the Pattern<N>. fn union_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Pattern<N>), ParseError> + 'a> { Box::new(map( separated_list1( map( tuple3(xpwhitespace(), alt2(tag("union"), tag("|")), xpwhitespace()), |_| (), ), intersect_except_expr_pattern::<N>(), ), |v| { Pattern::Selection(Branch::Union(v)) // if v.len() == 1 { // v.pop().unwrap() // } else { // Pattern::Selection(vec![v]) // } }, )) } // NB. Rust *really* doesn't like recursive types, so we must force it to lazily evaluate arguments to avoid stack overflow. fn union_expr_wrapper<N: Node>( b: bool, ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Pattern<N>), ParseError>> { Box::new(move |input| { if b { union_expr_pattern::<N>()(input) } else { noop()(input) } }) } fn noop<N: Node>() -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Pattern<N>), ParseError>> { Box::new(move |_| Err(ParseError::Combinator)) } // IntersectExceptExprP ::= PathExprP (("intersect" | "except") PathExprP)* // intersect and except not yet supported fn intersect_except_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( separated_list1( map( tuple3( xpwhitespace(), alt2(tag("intersect"), tag("except")), xpwhitespace(), ), |_| (), ), path_expr_pattern::<N>(), ), |mut v| { if v.len() == 1 { v.pop().unwrap() } else { // intersect/except not implemented Branch::Error(Error::new( ErrorKind::NotImplemented, String::from("intersect or except in a pattern has not been implemented"), )) } }, )) } // PathExprP ::= RootedPath | ("/" RelativePathExprP) | ("//" RelativePathExprP) | RelativePathExprP fn path_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(alt4( rooted_path_pattern::<N>(), absolutedescendant_expr_pattern(), absolutepath_expr_pattern(), relativepath_expr_pattern::<N>(), )) } // RootedPath ::= (VarRef | FunctionCallP) PredicateList (("/" | "//") RelativePathExprP)? fn rooted_path_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( tuple3( alt2(variable_reference_pattern::<N>(), function_call_pattern()), predicate_list::<N>(), alt2( absolutedescendant_expr_pattern::<N>(), absolutepath_expr_pattern(), ), ), |(_a, _b, _c)| { Branch::Error(Error::new( ErrorKind::NotImplemented, String::from("rooted path in a pattern has not been implemented"), )) }, )) } // Variable Reference fn variable_reference_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map(variable_reference::<N>(), |_| { Branch::Error(Error::new( ErrorKind::NotImplemented, "variable reference not yet supported", )) })) } // ('//' RelativePathExpr?) fn absolutedescendant_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( pair(tag("//"), relativepath_expr_pattern::<N>()), |(_, _r)| { Branch::Error(Error::new( ErrorKind::NotImplemented, String::from("absolute descendant path in a pattern has not been implemented"), )) }, )) } // ('/' RelativePathExpr?) fn absolutepath_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( pair( map(tag("/"), |_| "/"), opt(relativepath_expr_pattern::<N>()), ), |(d, r)| match (d, r.clone()) { ("/", None) => { // Matches the root node Branch::SingleStep(Step::new( Axis::SelfDocument, Axis::SelfDocument, NodeTest::Kind(KindTest::Document), )) } ("/", Some(Branch::SingleStep(s))) => Branch::RelPath(vec![ Branch::SingleStep(s), Branch::SingleStep(Step::new( Axis::SelfDocument, Axis::SelfDocument, NodeTest::Kind(KindTest::Document), )), ]), ("/", Some(Branch::RelPath(mut a))) => { /*a.insert( 0, Branch::SingleStep(Step::new( Axis::SelfDocument, Axis::SelfDocument, NodeTest::Kind(KindTest::Document), )), );*/ a.push(Branch::SingleStep(Step::new( Axis::SelfDocument, Axis::SelfDocument, NodeTest::Kind(KindTest::Document), ))); Branch::RelPath(a) } ("/", Some(Branch::Union(u))) => Branch::RelPath(vec![ Branch::Union(u), Branch::SingleStep(Step::new( Axis::SelfDocument, Axis::SelfDocument, NodeTest::Kind(KindTest::Document), )), ]), _ => Branch::Error(Error::new( ErrorKind::Unknown, String::from("unable to parse pattern"), )), }, )) } // RelativePathExpr ::= StepExpr (('/' | '//') StepExpr)* fn relativepath_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( pair( step_expr_pattern::<N>(), many0(tuple2( alt2( map(tuple3(xpwhitespace(), tag("//"), xpwhitespace()), |_| "//"), map(tuple3(xpwhitespace(), tag("/"), xpwhitespace()), |_| "/"), ), step_expr_pattern::<N>(), )), ), |(a, b)| { if b.is_empty() { // this is the terminal step a } else { // TODO: handle "//" separator let mut result = vec![a]; for (_c, d) in b { result.insert(0, d); } Branch::RelPath(result) } }, )) } // StepExprP ::= PostfixExprExpr | AxisStepP fn step_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(alt2(postfix_expr_pattern::<N>(), axis_step_pattern::<N>())) } // PostfixExprP ::= ParenthesizedExprP PredicateList // TODO: predicates fn postfix_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( tuple2(paren_expr_pattern(), predicate_list::<N>()), |(p, _)| p, )) } // ParenthesizedExprP ::= "(" UnionExprP ")" fn paren_expr_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( tuple3( tuple3(xpwhitespace(), tag("("), xpwhitespace()), union_expr_wrapper(true), tuple3(xpwhitespace(), tag(")"), xpwhitespace()), ), |(_, u, _)| { if let Pattern::Selection(sel) = u { sel } else { Branch::Error(Error::new( ErrorKind::TypeError, "expression must be a selection", )) } }, )) } // AxisStepP ::= ForwardStepP PredicateList // TODO: predicate fn axis_step_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( tuple2(forward_step_pattern(), predicate_list::<N>()), |(f, _p)| f, // TODO: pass predicate back to caller )) } // ForwardStepP ::= (ForwardAxisP NodeTest) | AbbrevForwardStep // Returns the node test, the terminal axis and the non-terminal axis fn forward_step_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( alt2( tuple2(forward_axis_pattern(), nodetest()), abbrev_forward_step(), ), |((a, c), nt)| Branch::SingleStep(Step::new(a, c, nt)), )) } // AbbrevForwardStep ::= "@"? NodeTest fn abbrev_forward_step<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, ((Axis, Axis), NodeTest)), ParseError> + 'a> { Box::new(map(tuple2(opt(tag("@")), nodetest()), |(a, nt)| { a.map_or_else( || { // not an attribute ((Axis::SelfAxis, Axis::Parent), nt.clone()) }, |_| { // attribute ((Axis::SelfAttribute, Axis::Parent), nt.clone()) }, ) })) } // ForwardAxisP ::= ("child" | "descendant" | "attribute" | "self" | "descendant-or-self" | "namespace" ) "::" // Returns a pair: the axis to match this step, and the axis for the previous step fn forward_axis_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, (Axis, Axis)), ParseError> + 'a> { Box::new(map( tuple2( alt6( map(tag("child"), |_| (Axis::SelfAxis, Axis::Parent)), map(tag("descendant"), |_| (Axis::SelfAxis, Axis::Ancestor)), map(tag("attribute"), |_| (Axis::SelfAttribute, Axis::Parent)), map(tag("self"), |_| (Axis::SelfAxis, Axis::SelfAxis)), map(tag("descendant-or-self"), |_| { (Axis::SelfAxis, Axis::Ancestor) }), map(tag("namespace"), |_| (Axis::SelfNamespace, Axis::Parent)), ), tag("::"), ), |(a, _)| a, )) } // FunctionCallP ::= OuterFunctionName ArgumentListP fn function_call_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( tuple2(outer_function_name(), argument_list_pattern::<N>()), |(_n, _a)| { // TODO Branch::Error(Error::new( ErrorKind::NotImplemented, String::from("function call in a pattern has not been implemented"), )) }, )) } // ArgumentListP ::= "(" (ArgumentP ("," ArgumentP)*)? ")" fn argument_list_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map( tuple3( map(tuple3(xpwhitespace(), tag("("), xpwhitespace()), |_| ()), separated_list0( map(tuple3(xpwhitespace(), tag(","), xpwhitespace()), |_| ()), argument_pattern::<N>(), ), map(tuple3(xpwhitespace(), tag(")"), xpwhitespace()), |_| ()), ), |(_, _a, _)| { // TODO Branch::Error(Error::new( ErrorKind::NotImplemented, String::from("argument list in a pattern has not been implemented"), )) }, )) } // ArgumentP ::= VarRef | Literal fn argument_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(alt2( variable_reference_pattern::<N>(), literal_pattern::<N>(), )) } // literal fn literal_pattern<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Path), ParseError> + 'a> { Box::new(map(literal::<N>(), |_| { Branch::Error(Error::new(ErrorKind::NotImplemented, "not yet implemented")) })) } // OuterFunctionName ::= "doc" | "id" | "element-with-id" | "key" | "root" | URIQualifiedName fn outer_function_name<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, NodeTest), ParseError> + 'a> { Box::new(alt6( map(tag("doc"), |_| { NodeTest::Name(NameTest { ns: None, prefix: None, name: Some(WildcardOrName::Name(Rc::new(Value::from("doc")))), }) }), map(tag("id"), |_| { NodeTest::Name(NameTest { ns: None, prefix: None, name: Some(WildcardOrName::Name(Rc::new(Value::from("id")))), }) }), map(tag("element-with-id"), |_| { NodeTest::Name(NameTest { ns: None, prefix: None, name: Some(WildcardOrName::Name(Rc::new(Value::from( "element-with-id", )))), }) }), map(tag("key"), |_| { NodeTest::Name(NameTest { ns: None, prefix: None, name: Some(WildcardOrName::Name(Rc::new(Value::from("key")))), }) }), map(tag("root"), |_| { NodeTest::Name(NameTest { ns: None, prefix: None, name: Some(WildcardOrName::Name(Rc::new(Value::from("root")))), }) }), map(qualname_test(), |q| q), )) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/externals.rs
src/externals.rs
/*! Defines interfaces for closures and functions that are used to communicate with external processes. */ use crate::xdmerror::Error; /// Resolves a URL, given as a base URI and a relative URL, and returns the content of the resource as a string. pub(crate) type URLResolver = fn(Option<String>, String) -> Result<String, Error>;
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/value.rs
src/value.rs
//! An atomic value. //! //! An atomic value that is an item in a sequence. use crate::qname::QualifiedName; use crate::xdmerror::{Error, ErrorKind}; use chrono::{DateTime, Local, NaiveDate}; use core::fmt; use core::hash::{Hash, Hasher}; use rust_decimal::prelude::ToPrimitive; use rust_decimal::Decimal; #[cfg(test)] use rust_decimal_macros::dec; use std::cmp::Ordering; use std::convert::TryFrom; use std::fmt::Formatter; use std::rc::Rc; /// Comparison operators for values #[derive(Copy, Clone, Debug)] pub enum Operator { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, Is, Before, After, } impl Operator { pub fn to_string(&self) -> &str { match self { Operator::Equal => "=", Operator::NotEqual => "!=", Operator::LessThan => "<", Operator::LessThanEqual => "<=", Operator::GreaterThan => ">", Operator::GreaterThanEqual => ">=", Operator::Is => "is", Operator::Before => "<<", Operator::After => ">>", } } } impl From<String> for Operator { fn from(s: String) -> Self { Operator::from(s.as_str()) } } impl From<&str> for Operator { fn from(s: &str) -> Self { match s { "=" | "eq" => Operator::Equal, "!=" | "ne" => Operator::NotEqual, "<" | "lt" => Operator::LessThan, "<=" | "le" => Operator::LessThanEqual, ">" | "gt" => Operator::GreaterThan, ">=" | "ge" => Operator::GreaterThanEqual, "is" => Operator::Is, "<<" => Operator::Before, ">>" => Operator::After, _ => Operator::After, // TODO: add error value } } } impl fmt::Display for Operator { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } /// A concrete type that implements atomic values. /// These are the 19 predefined types in XSD Schema Part 2, plus five additional types. #[derive(Clone, Debug)] pub enum Value { /// node or simple type AnyType, /// a not-yet-validated anyType Untyped, /// base type of all simple types. i.e. not a node AnySimpleType, /// a list of IDREF IDREFS(Vec<String>), /// a list of NMTOKEN NMTOKENS, /// a list of ENTITY ENTITIES, /// Any numeric type Numeric, /// all atomic values (no lists or unions) AnyAtomicType, /// untyped atomic value UntypedAtomic, Duration, Time(DateTime<Local>), // Ignore the date part. Perhaps use Instant instead? Decimal(Decimal), Float(f32), Double(f64), Integer(i64), NonPositiveInteger(NonPositiveInteger), NegativeInteger(NegativeInteger), Long(i64), Int(i32), Short(i16), Byte(i8), NonNegativeInteger(NonNegativeInteger), UnsignedLong(u64), UnsignedInt(u32), UnsignedShort(u16), UnsignedByte(u8), PositiveInteger(PositiveInteger), DateTime(DateTime<Local>), DateTimeStamp, Date(NaiveDate), // gYearMonth // gYear // gMonthDay // gMonth // gDay String(String), NormalizedString(NormalizedString), /// Like normalizedString, but without leading, trailing and consecutive whitespace Token, /// language identifiers [a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})* Language, /// NameChar+ NMTOKEN, /// NameStartChar NameChar+ Name, /// (Letter | '_') NCNameChar+ (i.e. a Name without the colon) NCName, /// Same format as NCName ID(String), /// Same format as NCName IDREF(String), /// Same format as NCName ENTITY, Boolean(bool), //base64binary, //hexBinary, //anyURI, /// Qualified Name QName(QualifiedName), /// Rc-shared Qualified Name RQName(Rc<QualifiedName>), //NOTATION } impl fmt::Display for Value { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let result = match self { Value::String(s) => s.to_string(), Value::NormalizedString(s) => s.0.to_string(), Value::Decimal(d) => d.to_string(), Value::Float(f) => f.to_string(), Value::Double(d) => d.to_string(), Value::Integer(i) => i.to_string(), Value::Long(l) => l.to_string(), Value::Short(s) => s.to_string(), Value::Int(i) => i.to_string(), Value::Byte(b) => b.to_string(), Value::UnsignedLong(l) => l.to_string(), Value::UnsignedShort(s) => s.to_string(), Value::UnsignedInt(i) => i.to_string(), Value::UnsignedByte(b) => b.to_string(), Value::NonPositiveInteger(i) => i.0.to_string(), Value::NonNegativeInteger(i) => i.0.to_string(), Value::PositiveInteger(i) => i.0.to_string(), Value::NegativeInteger(i) => i.0.to_string(), Value::Time(t) => t.format("%H:%M:%S.%f").to_string(), Value::DateTime(dt) => dt.format("%Y-%m-%dT%H:%M:%S%z").to_string(), Value::Date(d) => d.format("%Y-%m-%d").to_string(), Value::QName(q) => q.to_string(), Value::RQName(q) => q.to_string(), Value::ID(s) => s.to_string(), Value::IDREF(s) => s.to_string(), Value::IDREFS(s) => s.join(" ").to_string(), _ => "".to_string(), }; f.write_str(result.as_str()) } } impl Hash for Value { fn hash<H: Hasher>(&self, state: &mut H) { format!("{:?}", self).hash(state) } } impl Eq for Value {} impl Value { /// Give the effective boolean value. pub fn to_bool(&self) -> bool { match &self { Value::Boolean(b) => *b, Value::String(t) => { //t.is_empty() !t.is_empty() } Value::NormalizedString(s) => !s.0.is_empty(), Value::Double(n) => *n != 0.0, Value::Integer(i) => *i != 0, Value::Int(i) => *i != 0, _ => false, } } /// Convert the value to an integer, if possible. pub fn to_int(&self) -> Result<i64, Error> { match &self { Value::Int(i) => Ok(*i as i64), Value::Integer(i) => Ok(*i), _ => match self.to_string().parse::<i64>() { Ok(i) => Ok(i), Err(e) => Result::Err(Error::new( ErrorKind::Unknown, format!("type conversion error: {}", e), )), }, } } /// Convert the value to a double. If the value cannot be converted, returns Nan. pub fn to_double(&self) -> f64 { match &self { Value::String(s) => s.parse::<f64>().unwrap_or(f64::NAN), Value::Integer(i) => (*i) as f64, Value::Int(i) => (*i) as f64, Value::Double(d) => *d, _ => f64::NAN, } } pub fn value_type(&self) -> &'static str { match &self { Value::AnyType => "AnyType", Value::Untyped => "Untyped", Value::AnySimpleType => "AnySimpleType", Value::IDREFS(_) => "IDREFS", Value::NMTOKENS => "NMTOKENS", Value::ENTITIES => "ENTITIES", Value::Numeric => "Numeric", Value::AnyAtomicType => "AnyAtomicType", Value::UntypedAtomic => "UntypedAtomic", Value::Duration => "Duration", Value::Time(_) => "Time", Value::Decimal(_) => "Decimal", Value::Float(_) => "Float", Value::Double(_) => "Double", Value::Integer(_) => "Integer", Value::NonPositiveInteger(_) => "NonPositiveInteger", Value::NegativeInteger(_) => "NegativeInteger", Value::Long(_) => "Long", Value::Int(_) => "Int", Value::Short(_) => "Short", Value::Byte(_) => "Byte", Value::NonNegativeInteger(_) => "NonNegativeInteger", Value::UnsignedLong(_) => "UnsignedLong", Value::UnsignedInt(_) => "UnsignedInt", Value::UnsignedShort(_) => "UnsignedShort", Value::UnsignedByte(_) => "UnsignedByte", Value::PositiveInteger(_) => "PositiveInteger", Value::DateTime(_) => "DateTime", Value::DateTimeStamp => "DateTimeStamp", Value::Date(_) => "Date", Value::String(_) => "String", Value::NormalizedString(_) => "NormalizedString", Value::Token => "Token", Value::Language => "Language", Value::NMTOKEN => "NMTOKEN", Value::Name => "Name", Value::NCName => "NCName", Value::ID(_) => "ID", Value::IDREF(_) => "IDREF", Value::ENTITY => "ENTITY", Value::Boolean(_) => "boolean", Value::QName(_) => "QName", Value::RQName(_) => "QName", } } pub fn compare(&self, other: &Value, op: Operator) -> Result<bool, Error> { match &self { Value::Boolean(b) => { let c = other.to_bool(); match op { Operator::Equal => Ok(*b == c), Operator::NotEqual => Ok(*b != c), Operator::LessThan => Ok(!(*b) & c), Operator::LessThanEqual => Ok(*b <= c), Operator::GreaterThan => Ok(*b & !c), Operator::GreaterThanEqual => Ok(*b >= c), Operator::Is | Operator::Before | Operator::After => { Err(Error::new(ErrorKind::TypeError, String::from("type error"))) } } } Value::Integer(i) => { let c = other.to_int()?; match op { Operator::Equal => Ok(*i == c), Operator::NotEqual => Ok(*i != c), Operator::LessThan => Ok(*i < c), Operator::LessThanEqual => Ok(*i <= c), Operator::GreaterThan => Ok(*i > c), Operator::GreaterThanEqual => Ok(*i >= c), Operator::Is | Operator::Before | Operator::After => { Err(Error::new(ErrorKind::TypeError, String::from("type error"))) } } } Value::Int(i) => { let c = other.to_int()? as i32; match op { Operator::Equal => Ok(*i == c), Operator::NotEqual => Ok(*i != c), Operator::LessThan => Ok(*i < c), Operator::LessThanEqual => Ok(*i <= c), Operator::GreaterThan => Ok(*i > c), Operator::GreaterThanEqual => Ok(*i >= c), Operator::Is | Operator::Before | Operator::After => { Err(Error::new(ErrorKind::TypeError, String::from("type error"))) } } } Value::Double(i) => { let c = other.to_double(); match op { Operator::Equal => Ok(*i == c), Operator::NotEqual => Ok(*i != c), Operator::LessThan => Ok(*i < c), Operator::LessThanEqual => Ok(*i <= c), Operator::GreaterThan => Ok(*i > c), Operator::GreaterThanEqual => Ok(*i >= c), Operator::Is | Operator::Before | Operator::After => { Err(Error::new(ErrorKind::TypeError, String::from("type error"))) } } } Value::String(i) => { let c = other.to_string(); match op { Operator::Equal => Ok(*i == c), Operator::NotEqual => Ok(*i != c), Operator::LessThan => Ok(*i < c), Operator::LessThanEqual => Ok(*i <= c), Operator::GreaterThan => Ok(*i > c), Operator::GreaterThanEqual => Ok(*i >= c), Operator::Is | Operator::Before | Operator::After => { Err(Error::new(ErrorKind::TypeError, String::from("type error"))) } } } Value::QName(q) => match (op, other) { (Operator::Equal, Value::QName(r)) => Ok(*q == *r), (Operator::Equal, Value::RQName(r)) => Ok(*q == **r), (Operator::NotEqual, Value::QName(r)) => Ok(*q != *r), (Operator::NotEqual, Value::RQName(r)) => Ok(*q != **r), _ => Err(Error::new(ErrorKind::TypeError, String::from("type error"))), }, Value::RQName(q) => match (op, other) { (Operator::Equal, Value::QName(r)) => Ok(**q == *r), (Operator::Equal, Value::RQName(r)) => Ok(**q == **r), (Operator::NotEqual, Value::QName(r)) => Ok(**q != *r), (Operator::NotEqual, Value::RQName(r)) => Ok(**q != **r), _ => Err(Error::new(ErrorKind::TypeError, String::from("type error"))), }, _ => Result::Err(Error::new( ErrorKind::Unknown, format!( "comparing type \"{}\" is not yet implemented", self.value_type() ), )), } } } impl PartialEq for Value { fn eq(&self, other: &Value) -> bool { match self { Value::String(s) => s.eq(&other.to_string()), Value::Boolean(b) => match other { Value::Boolean(c) => b == c, _ => false, // type error? }, Value::Decimal(d) => match other { Value::Decimal(e) => d == e, _ => false, // type error? }, Value::Integer(i) => match other { Value::Integer(j) => i == j, _ => false, // type error? coerce to integer? }, Value::Double(d) => match other { Value::Double(e) => d == e, _ => false, // type error? coerce to integer? }, _ => false, // not yet implemented } } } impl PartialOrd for Value { fn partial_cmp(&self, other: &Value) -> Option<Ordering> { match self { Value::String(s) => { let o: String = other.to_string(); s.partial_cmp(&o) } Value::Boolean(_) => None, Value::Decimal(d) => match other { Value::Decimal(e) => d.partial_cmp(e), _ => None, // type error? }, Value::Integer(d) => match other { Value::Integer(e) => d.partial_cmp(e), _ => None, // type error? }, Value::Double(d) => match other { Value::Double(e) => d.partial_cmp(e), _ => None, // type error? }, _ => None, } } } //This is ONLY being used for namespace node sorting for the purposes of serializing //Feel free to change it. //We can change between versions, so long as each execution on that version is consistent. impl Ord for Value { fn cmp(&self, other: &Value) -> Ordering { match self { Value::String(s) => { let o: String = other.to_string(); s.cmp(&o) } Value::Boolean(_) => Ordering::Equal, Value::Decimal(d) => match other { Value::Decimal(e) => d.cmp(e), _ => Ordering::Equal, // type error? }, Value::Integer(d) => match other { Value::Integer(e) => d.cmp(e), _ => Ordering::Equal, // type error? }, Value::Double(d) => match other { Value::Double(e) => d.partial_cmp(e).unwrap_or(Ordering::Equal), _ => Ordering::Equal, // type error? }, _ => Ordering::Equal, } } } impl From<String> for Value { fn from(s: String) -> Self { Value::String(s) } } impl From<&str> for Value { fn from(s: &str) -> Self { Value::String(String::from(s)) } } impl From<Decimal> for Value { fn from(d: Decimal) -> Self { Value::Decimal(d) } } impl From<f32> for Value { fn from(f: f32) -> Self { Value::Float(f) } } impl From<f64> for Value { fn from(f: f64) -> Self { Value::Double(f) } } impl From<i64> for Value { fn from(i: i64) -> Self { Value::Integer(i) } } impl From<i32> for Value { fn from(i: i32) -> Self { Value::Int(i) } } impl From<i16> for Value { fn from(i: i16) -> Self { Value::Short(i) } } impl From<i8> for Value { fn from(i: i8) -> Self { Value::Byte(i) } } impl From<u64> for Value { fn from(i: u64) -> Self { Value::UnsignedLong(i) } } impl From<u32> for Value { fn from(i: u32) -> Self { Value::UnsignedInt(i) } } impl From<u16> for Value { fn from(i: u16) -> Self { Value::UnsignedShort(i) } } impl From<u8> for Value { fn from(i: u8) -> Self { Value::UnsignedByte(i) } } impl From<usize> for Value { fn from(u: usize) -> Self { Value::UnsignedLong(u.to_u64().unwrap()) } } impl From<bool> for Value { fn from(b: bool) -> Self { Value::Boolean(b) } } impl From<QualifiedName> for Value { fn from(q: QualifiedName) -> Self { Value::QName(q) } } impl From<Rc<QualifiedName>> for Value { fn from(q: Rc<QualifiedName>) -> Self { Value::RQName(q) } } #[derive(Clone, Debug, Hash)] pub struct NonPositiveInteger(i64); impl TryFrom<i64> for NonPositiveInteger { type Error = Error; fn try_from(v: i64) -> Result<Self, Self::Error> { if v > 0 { Err(Error::new( ErrorKind::TypeError, String::from("NonPositiveInteger must be less than zero"), )) } else { Ok(NonPositiveInteger(v)) } } } impl fmt::Display for NonPositiveInteger { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0.to_string()) } } #[derive(Clone, Debug, Hash)] pub struct PositiveInteger(i64); impl TryFrom<i64> for PositiveInteger { type Error = Error; fn try_from(v: i64) -> Result<Self, Self::Error> { if v <= 0 { Err(Error::new( ErrorKind::TypeError, String::from("PositiveInteger must be greater than zero"), )) } else { Ok(PositiveInteger(v)) } } } impl fmt::Display for PositiveInteger { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0.to_string()) } } #[derive(Clone, Debug, Hash)] pub struct NonNegativeInteger(i64); impl TryFrom<i64> for NonNegativeInteger { type Error = Error; fn try_from(v: i64) -> Result<Self, Self::Error> { if v < 0 { Err(Error::new( ErrorKind::TypeError, String::from("NonNegativeInteger must be zero or greater"), )) } else { Ok(NonNegativeInteger(v)) } } } impl fmt::Display for NonNegativeInteger { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0.to_string()) } } #[derive(Clone, Debug, Hash)] pub struct NegativeInteger(i64); impl TryFrom<i64> for NegativeInteger { type Error = Error; fn try_from(v: i64) -> Result<Self, Self::Error> { if v >= 0 { Err(Error::new( ErrorKind::TypeError, String::from("NegativeInteger must be less than zero"), )) } else { Ok(NegativeInteger(v)) } } } impl fmt::Display for NegativeInteger { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0.to_string()) } } #[derive(Clone, Debug, Hash)] pub struct NormalizedString(String); impl TryFrom<&str> for NormalizedString { type Error = Error; fn try_from(v: &str) -> Result<Self, Self::Error> { let n: &[_] = &['\n', '\r', '\t']; if v.find(n).is_none() { Ok(NormalizedString(v.to_string())) } else { Err(Error::new( ErrorKind::TypeError, String::from("value is not a normalized string"), )) } } } impl fmt::Display for NormalizedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0.to_string()) } } #[cfg(test)] mod tests { use super::*; #[test] fn from_string() { assert_eq!(Value::from(String::from("foobar")).to_string(), "foobar"); } #[test] fn from_str() { assert_eq!(Value::from("foobar").to_string(), "foobar"); } #[test] fn from_decimal() { assert_eq!(Value::from(dec!(001.23)).to_string(), "1.23"); } #[test] fn normalizedstring_valid_empty() { assert_eq!( NormalizedString::try_from("") .expect("invalid NormalizedString") .0, "" ); } #[test] fn normalizedstring_valid() { assert_eq!( NormalizedString::try_from("notinvalid") .expect("invalid NormalizedString") .0, "notinvalid" ); } #[test] fn normalizedstring_valid_spaces() { assert_eq!( NormalizedString::try_from("not an invalid string") .expect("invalid NormalizedString") .0, "not an invalid string" ); } #[test] fn normalizedstring_invalid_tab() { let r = NormalizedString::try_from("contains tab character"); assert!(match r { Ok(_) => panic!("string contains tab character"), Err(_) => true, }) } #[test] fn normalizedstring_invalid_newline() { let r = NormalizedString::try_from("contains newline\ncharacter"); assert!(match r { Ok(_) => panic!("string contains newline character"), Err(_) => true, }) } #[test] fn normalizedstring_invalid_cr() { let r = NormalizedString::try_from("contains carriage return\rcharacter"); assert!(match r { Ok(_) => panic!("string contains cr character"), Err(_) => true, }) } #[test] fn normalizedstring_invalid_all() { let r = NormalizedString::try_from("contains all\rforbidden\ncharacters"); assert!(match r { Ok(_) => panic!("string contains at least one forbidden character"), Err(_) => true, }) } // Numeric is in the too hard basket for now // #[test] // fn numeric_float() { // assert_eq!(Numeric::new(f32::0.123).value, 0.123); // } // #[test] // fn numeric_double() { // assert_eq!(Numeric::new(f64::0.456).value, 0.456); // } // #[test] // fn numeric_decimal() { // assert_eq!(Numeric::new(dec!(123.456)), 123.456); // } #[test] fn nonpositiveinteger_valid() { assert_eq!( NonPositiveInteger::try_from(-10) .expect("invalid NonPositiveInteger") .0, -10 ); } #[test] fn nonpositiveinteger_valid_zero() { assert_eq!( NonPositiveInteger::try_from(0) .expect("invalid NonPositiveInteger") .0, 0 ); } #[test] fn nonpositiveinteger_invalid() { let r = NonPositiveInteger::try_from(10); assert!(match r { Ok(_) => panic!("10 is not a nonPositiveInteger"), Err(_) => true, }) } #[test] fn positiveinteger_valid() { assert_eq!( PositiveInteger::try_from(10) .expect("invalid PositiveInteger") .0, 10 ); } #[test] fn positiveinteger_invalid_zero() { let r = PositiveInteger::try_from(0); assert!(match r { Ok(_) => panic!("0 is not a PositiveInteger"), Err(_) => true, }) } #[test] fn positiveinteger_invalid() { let r = PositiveInteger::try_from(-10); assert!(match r { Ok(_) => panic!("-10 is not a PositiveInteger"), Err(_) => true, }) } #[test] fn nonnegativeinteger_valid() { assert_eq!( NonNegativeInteger::try_from(10) .expect("invalid NonNegativeInteger") .0, 10 ); } #[test] fn nonnegativeinteger_valid_zero() { assert_eq!( NonNegativeInteger::try_from(0) .expect("invalid NonNegativeInteger") .0, 0 ); } #[test] fn nonnegativeinteger_invalid() { let r = NonNegativeInteger::try_from(-10); assert!(match r { Ok(_) => panic!("-10 is not a NonNegativeInteger"), Err(_) => true, }) } #[test] fn negativeinteger_valid() { assert_eq!( NegativeInteger::try_from(-10) .expect("invalid NegativeInteger") .0, -10 ); } #[test] fn negativeinteger_invalid_zero() { let r = NegativeInteger::try_from(0); assert!(match r { Ok(_) => panic!("0 is not a NegativeInteger"), Err(_) => true, }) } #[test] fn negativeinteger_invalid() { let r = NegativeInteger::try_from(10); assert!(match r { Ok(_) => panic!("10 is not a NegativeInteger"), Err(_) => true, }) } // String Values #[test] fn string_stringvalue() { assert_eq!(Value::String("foobar".to_string()).to_string(), "foobar") } #[test] fn decimal_stringvalue() { assert_eq!(Value::Decimal(dec!(001.23)).to_string(), "1.23") } #[test] fn float_stringvalue() { assert_eq!(Value::Float(001.2300_f32).to_string(), "1.23") } #[test] fn nonpositiveinteger_stringvalue() { let npi = NonPositiveInteger::try_from(-00123).expect("invalid nonPositiveInteger"); let i = Value::NonPositiveInteger(npi); assert_eq!(i.to_string(), "-123") } #[test] fn nonnegativeinteger_stringvalue() { let nni = NonNegativeInteger::try_from(00123).expect("invalid nonNegativeInteger"); let i = Value::NonNegativeInteger(nni); assert_eq!(i.to_string(), "123") } #[test] fn normalizedstring_stringvalue() { let ns = NormalizedString::try_from("foobar").expect("invalid normalizedString"); let i = Value::NormalizedString(ns); assert_eq!(i.to_string(), "foobar") } // value to_bool #[test] fn value_to_bool_string() { assert!(Value::from("2").to_bool()) } // value to_int #[test] fn value_to_int_string() { assert_eq!( Value::from("2") .to_int() .expect("cannot convert to integer"), 2 ) } // value to_double #[test] fn value_to_double_string() { assert_eq!(Value::from("3.0").to_double(), 3.0) } // value compare #[test] fn value_compare_eq() { assert!(Value::from("3") .compare(&Value::Double(3.0), Operator::Equal) .expect("unable to compare")) } #[test] fn value_compare_ne() { assert!(!Value::from("3") .compare(&Value::Double(3.0), Operator::NotEqual) .expect("unable to compare")) } //#[test] //fn value_atomize() { //let i = Value::Int(123); //assert_eq!(i.atomize().stringvalue(), "123") //} // Operators #[test] fn op_equal() { assert_eq!(Operator::Equal.to_string(), "=") } #[test] fn op_notequal() { assert_eq!(Operator::NotEqual.to_string(), "!=") } #[test] fn op_lt() { assert_eq!(Operator::LessThan.to_string(), "<") } #[test] fn op_ltequal() { assert_eq!(Operator::LessThanEqual.to_string(), "<=") } #[test] fn op_gt() { assert_eq!(Operator::GreaterThan.to_string(), ">") } #[test] fn op_gtequal() { assert_eq!(Operator::GreaterThanEqual.to_string(), ">=") } #[test] fn op_is() { assert_eq!(Operator::Is.to_string(), "is") } #[test] fn op_before() { assert_eq!(Operator::Before.to_string(), "<<") } #[test] fn op_after() { assert_eq!(Operator::After.to_string(), ">>") } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/xdmerror.rs
src/xdmerror.rs
//! XDM, XPath, XQuery, and XSLT errors. use crate::qname::QualifiedName; use core::str; use std::fmt; use std::fmt::Formatter; /// Errors defined in XPath #[derive(Copy, Clone, Debug, PartialEq)] pub enum ErrorKind { StaticAbsent, /// XPST0001 DynamicAbsent, /// XPDY0002 StaticSyntax, /// XPST0003 TypeError, /// XPTY0004 StaticData, /// XPST0005 StaticUndefined, /// XPST0008 StaticNamespace, /// XPST0010 StaticBadFunction, /// XPST0017 MixedTypes, /// XPTY0018 NotNodes, /// XPTY0019 ContextNotNode, /// XPTY0020 Terminated, /// XTMM9000 - (http://)www.w3.org/2005/xqt-errors NotImplemented, ParseError, Unknown, } impl ErrorKind { /// String representation of error pub fn to_string(&self) -> &'static str { match *self { ErrorKind::StaticAbsent => "a component of the static context is absent", ErrorKind::DynamicAbsent => "a component of the dynamic context is absent", ErrorKind::StaticSyntax => "syntax error", ErrorKind::TypeError => "type error", ErrorKind::StaticData => "wrong static type", ErrorKind::StaticUndefined => "undefined name", ErrorKind::StaticNamespace => "namespace axis not supported", ErrorKind::StaticBadFunction => "function call name and arity do not match", ErrorKind::MixedTypes => "result of path operator contains both nodes and non-nodes", ErrorKind::NotNodes => "path expression is not a sequence of nodes", ErrorKind::ContextNotNode => "context item is not a node for an axis step", ErrorKind::Terminated => "application has voluntarily terminated processing", ErrorKind::NotImplemented => "not implemented", ErrorKind::Unknown => "unknown", ErrorKind::ParseError => "XML Parse error", } } } impl fmt::Display for ErrorKind { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } /// An error returned by an XPath, XQuery or XSLT function/method #[derive(Clone)] pub struct Error { pub kind: ErrorKind, pub message: String, pub code: Option<QualifiedName>, } impl std::error::Error for Error {} impl Error { pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self { Error { kind, message: message.into(), code: None, } } pub fn new_with_code( kind: ErrorKind, message: impl Into<String>, code: Option<QualifiedName>, ) -> Self { Error { kind, message: message.into(), code, } } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.message) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.message) } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/xslt.rs
src/xslt.rs
/*! ## An XSLT compiler Compile an XSLT stylesheet into a [Transform]ation. Once the stylesheet has been compiled, it may then be evaluated with an appropriate context. NB. This module, by default, does not resolve include or import statements. See the xrust-net crate for a helper module to do that. ```rust use std::rc::Rc; use xrust::xdmerror::{Error, ErrorKind}; use xrust::qname::QualifiedName; use xrust::item::{Item, Node, NodeType, Sequence, SequenceTrait}; use xrust::transform::Transform; use xrust::transform::context::{StaticContext, StaticContextBuilder}; use xrust::trees::smite::RNode; use xrust::parser::xml::parse; use xrust::xslt::from_document; // A little helper function to parse an XML document fn make_from_str(s: &str) -> Result<RNode, Error> { let doc = RNode::new_document(); let e = parse(doc.clone(), s, None)?; Ok(doc) } // The source document (a tree) let src = Item::Node( make_from_str("<Example><Title>XSLT in Rust</Title><Paragraph>A simple document.</Paragraph></Example>") .expect("unable to parse XML") ); // The XSL stylesheet let style = make_from_str("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match='child::Example'><html><xsl:apply-templates/></html></xsl:template> <xsl:template match='child::Title'><head><title><xsl:apply-templates/></title></head></xsl:template> <xsl:template match='child::Paragraph'><body><p><xsl:apply-templates/></p></body></xsl:template> </xsl:stylesheet>") .expect("unable to parse stylesheet"); // Create a static context (with dummy callbacks) let mut static_context = StaticContextBuilder::new() .message(|_| Ok(())) .fetcher(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) .parser(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) .build(); // Compile the stylesheet let mut ctxt = from_document( style, None, make_from_str, |_| Ok(String::new()) ).expect("failed to compile stylesheet"); // Set the source document as the context item ctxt.context(vec![src], 0); // Make an empty result document ctxt.result_document(RNode::new_document()); // Let 'er rip! // Evaluate the transformation let seq = ctxt.evaluate(&mut static_context) .expect("evaluation failed"); // Serialise the sequence as XML assert_eq!(seq.to_xml(), "<html><head><title>XSLT in Rust</title></head><body><p>A simple document.</p></body></html>") */ use std::collections::HashMap; use std::rc::Rc; use crate::item::{Item, Node, NodeType, Sequence}; use crate::output::*; use crate::parser::avt::parse as parse_avt; use crate::parser::xpath::parse; use crate::pattern::{Branch, Pattern}; use crate::qname::*; use crate::transform::callable::{ActualParameters, Callable, FormalParameters}; use crate::transform::context::{Context, ContextBuilder}; use crate::transform::numbers::{Level, Numbering}; use crate::transform::template::Template; use crate::transform::{ in_scope_namespaces, Axis, Grouping, KindTest, NameTest, NodeMatch, NodeTest, Order, Transform, WildcardOrName, }; use crate::value::*; use crate::xdmerror::*; use std::convert::TryFrom; use url::Url; const XSLTNS: &str = "http://www.w3.org/1999/XSL/Transform"; /// The XSLT trait allows an object to use an XSL Stylesheet to transform a document into a [Sequence]. pub trait XSLT: Node { /// Interpret the object as an XSL Stylesheet and transform a source document. /// The [Node] that is given as the source document becomes the initial context for the transformation. fn transform<N: Node, F, G>( &self, src: Rc<Item<N>>, b: Option<Url>, f: F, g: G, ) -> Result<Sequence<N>, Error> where F: Fn(&str) -> Result<N, Error>, G: Fn(&Url) -> Result<String, Error>; // { // let sc = from_document(self.clone(), b, f, g)?; // let ctxt = ContextBuilder::from(&sc) // .current(vec![src]) // .build(); // ctxt.evaluate() // } } /// Compiles a [Node] into a transformation [Context]. /// NB. Due to whitespace stripping, this is destructive of the stylesheet. /// The argument f is a closure that parses a string to a [Node]. /// The argument g is a closure that resolves a URL to a string. /// These are used for include and import modules. /// They are not included in this module since some environments, in particular Wasm, do not have I/O facilities. pub fn from_document<N: Node, F, G>( styledoc: N, base: Option<Url>, f: F, g: G, ) -> Result<Context<N>, Error> where F: Fn(&str) -> Result<N, Error>, G: Fn(&Url) -> Result<String, Error>, { // Check that this is a valid XSLT stylesheet // There must be a single element as a child of the root node, and it must be named xsl:stylesheet or xsl:transform let mut rnit = styledoc.child_iter(); let stylenode = match rnit.next() { Some(root) => { // TODO: intern strings so that comparison is fast if !(root.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && (root.name().localname_to_string() == "stylesheet" || root.name().localname_to_string() == "transform")) { return Result::Err(Error::new( ErrorKind::TypeError, String::from("not an XSLT stylesheet"), )); } else { root } } None => { return Result::Err(Error::new( ErrorKind::TypeError, String::from("document does not have document element"), )) } }; if rnit.next().is_some() { return Result::Err(Error::new( ErrorKind::TypeError, String::from("extra element: not an XSLT stylesheet"), )); } // TODO: check version attribute // Strip whitespace from the stylesheet strip_whitespace( styledoc.clone(), true, &vec![NodeTest::Name(NameTest { ns: None, prefix: None, name: Some(WildcardOrName::Wildcard), })], &vec![NodeTest::Name(NameTest { ns: Some(WildcardOrName::Name(Rc::new(Value::from(XSLTNS)))), prefix: Some(Rc::new(Value::from("xsl"))), name: Some(WildcardOrName::Name(Rc::new(Value::from("text")))), })], )?; // Setup the serialization of the primary result document let mut od = OutputDefinition::new(); if let Some(c) = stylenode.child_iter().find(|c| { !(c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "output") }) { let b: bool = matches!( c.get_attribute(&QualifiedName::new(None, None, "indent")) .to_string() .as_str(), "yes" | "true" | "1" ); od.set_indent(b); }; // Iterate over children, looking for includes // * resolve href // * fetch document // * parse XML // * replace xsl:include element with content stylenode .child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string().as_str() == "include" }) .try_for_each(|mut c| { let h = c.get_attribute(&QualifiedName::new(None, None, "href")); let url = match base.clone().map_or_else( || Url::parse(h.to_string().as_str()), |full| full.join(h.to_string().as_str()), ) { Ok(u) => u, Err(_) => { return Result::Err(Error::new( ErrorKind::Unknown, format!( "unable to parse href URL \"{}\" baseurl \"{}\"", h, base.clone() .map_or(String::from("--no base--"), |b| b.to_string()) ), )); } }; let xml = g(&url)?; let module = f(xml.as_str().trim())?; // TODO: check that the module is a valid XSLT stylesheet, etc // Copy each top-level element of the module to the main stylesheet, // inserting before the xsl:include node let moddoc = module.first_child().unwrap(); moddoc.child_iter().try_for_each(|mc| { c.insert_before(mc)?; Ok::<(), Error>(()) })?; // Remove the xsl:include element node c.pop()?; Ok(()) })?; // Iterate over children, looking for imports // * resolve href // * fetch document // * parse XML // * replace xsl:import element with content stylenode .child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string().as_str() == "import" }) .try_for_each(|mut c| { let h = c.get_attribute(&QualifiedName::new(None, None, "href")); let url = match base.clone().map_or_else( || Url::parse(h.to_string().as_str()), |full| full.join(h.to_string().as_str()), ) { Ok(u) => u, Err(_) => { return Result::Err(Error::new( ErrorKind::Unknown, format!( "unable to parse href URL \"{}\" baseurl \"{}\"", h, base.clone() .map_or(String::from("--no base--"), |b| b.to_string()) ), )); } }; let xml = g(&url)?; let module = f(xml.as_str().trim())?; // TODO: check that the module is a valid XSLT stylesheet, etc // Copy each top-level element of the module to the main stylesheet, // inserting before the xsl:include node // TODO: Don't Panic let moddoc = module.first_child().unwrap(); moddoc.child_iter().try_for_each(|mc| { if mc.node_type() == NodeType::Element { // Add the import precedence attribute let newnode = mc.deep_copy()?; let newat = styledoc.new_attribute( Rc::new(QualifiedName::new( Some(String::from("http://github.com/ballsteve/xrust")), None, String::from("import"), )), Rc::new(Value::from(1)), )?; newnode.add_attribute(newat)?; c.insert_before(newnode)?; } else { let newnode = mc.deep_copy()?; c.insert_before(newnode)?; } Ok::<(), Error>(()) })?; // Remove the xsl:import element node c.pop()?; Ok::<(), Error>(()) })?; // Find named attribute sets // Store for named attribute sets let mut attr_sets: HashMap<QualifiedName, Vec<Transform<N>>> = HashMap::new(); stylenode .child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "attribute-set" }) .try_for_each(|c| { let name = c.get_attribute(&QualifiedName::new(None, None, "name")); let eqname = QualifiedName::try_from((name.to_string().as_str(), c.clone()))?; if eqname.to_string().is_empty() { return Err(Error::new( ErrorKind::DynamicAbsent, "attribute sets must have a name", )); } // xsl:attribute children // TODO: check that there are no other children let mut attrs = vec![]; c.child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string().as_str() == "attribute" }) .try_for_each(|a| { attrs.push(to_transform(a, &attr_sets)?); Ok(()) })?; attr_sets.insert(eqname, attrs); Ok(()) })?; // Iterate over children, looking for templates // * compile match pattern // * compile content into sequence constructor // * register template in dynamic context let mut templates: Vec<Template<N>> = vec![]; stylenode .child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "template" }) .filter(|c| { !c.get_attribute(&QualifiedName::new(None, None, "match")) .to_string() .is_empty() }) .try_for_each(|c| { let m = c.get_attribute(&QualifiedName::new(None, None, "match")); let pat = Pattern::try_from(m.to_string()).map_err(|e| { Error::new( e.kind, format!( "Error parsing match pattern \"{}\": {}", m.to_string(), e.message ), ) })?; if pat.is_err() { return Err(pat.get_err().unwrap()); } if let Pattern::Selection(Branch::Error(e)) = pat { return Err(e.clone()); } let mut body = vec![]; let mode = c.get_attribute_node(&QualifiedName::new(None, None, "mode")); c.child_iter().try_for_each(|d| { body.push(to_transform(d, &attr_sets)?); Ok::<(), Error>(()) })?; //sc.static_analysis(&mut pat); //sc.static_analysis(&mut body); // Determine the priority of the template let pr = c.get_attribute(&QualifiedName::new(None, None, "priority".to_string())); let prio: f64 = match pr.to_string().as_str() { "" => { // Calculate the default priority // TODO: more work to be done interpreting XSLT 6.5 match &pat { Pattern::Predicate(p) => match p { Transform::Empty => -1.0, _ => 1.0, }, Pattern::Selection(s) => { if let Branch::Error(e) = s { return Err(e.clone()); } let (t, nt, q) = s.terminal_node_test(); // If "/" then -0.5 match (t, nt) { (Axis::SelfAttribute, _) => -0.5, (Axis::SelfAxis, Axis::Parent) | (Axis::SelfAxis, Axis::Ancestor) | (Axis::SelfAxis, Axis::AncestorOrSelf) => match q { NodeTest::Name(nm) => match nm.name { Some(WildcardOrName::Wildcard) => -0.5, Some(_) => 0.0, _ => -0.5, }, NodeTest::Kind(_kt) => -0.5, }, _ => 0.5, } } _ => -1.0, } } _ => pr.to_string().parse::<f64>().unwrap(), // TODO: better error handling }; // Set the import precedence let mut import: usize = 0; let im = c.get_attribute(&QualifiedName::new( Some(String::from("http://github.com/ballsteve/xrust")), None, String::from("import"), )); if im.to_string() != "" { import = im.to_int()? as usize } templates.push(Template::new( pat, Transform::SequenceItems(body), Some(prio), vec![import], None, mode.map(|n| { Rc::new( QualifiedName::try_from((n.to_string().as_str(), n)) .expect("unable to resolve qualified name"), ) }), // TODO: don't panic )); Ok::<(), Error>(()) })?; // Iterate over the children, looking for key declarations. // NB. could combine this with the previous loop, but performance shouldn't be an issue. let mut keys = vec![]; stylenode .child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "key" }) .try_for_each(|c| { let name = c.get_attribute(&QualifiedName::new(None, None, "name")); let m = c.get_attribute(&QualifiedName::new(None, None, "match")); let pat = Pattern::try_from(m.to_string())?; let u = c.get_attribute(&QualifiedName::new(None, None, "use")); keys.push((name, pat, parse::<N>(&u.to_string(), Some(c.clone()))?)); Ok(()) })?; let mut newctxt = ContextBuilder::new() // Define the builtin templates // See XSLT 6.7. This implements text-only-copy. // TODO: Support deep-copy, shallow-copy, deep-skin, shallow-skip and fail // This matches "/" and processes the root element .template(Template::new( Pattern::try_from("/")?, Transform::ApplyTemplates( Box::new(Transform::Step(NodeMatch::new( Axis::Child, NodeTest::Kind(KindTest::Any), ))), None, vec![], ), None, vec![0], None, None, )) // This matches "*" and applies templates to all children .template(Template::new( Pattern::try_from("child::*")?, Transform::ApplyTemplates( Box::new(Transform::Step(NodeMatch::new( Axis::Child, NodeTest::Kind(KindTest::Any), ))), None, vec![], ), None, vec![0], None, None, )) // This matches "text()" and copies content .template(Template::new( Pattern::try_from("child::text()")?, Transform::ContextItem, None, vec![0], None, None, )) .template_all(templates) .output_definition(od) .build(); keys.iter() .for_each(|(name, m, u)| newctxt.declare_key(name.to_string(), m.clone(), u.clone())); // Add named templates stylenode .child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "template" }) .filter(|c| { !c.get_attribute(&QualifiedName::new(None, None, "name")) .to_string() .is_empty() }) .try_for_each(|c| { let name = c.get_attribute(&QualifiedName::new(None, None, "name")); // xsl:param for formal parameters // TODO: validate that xsl:param elements come first in the child list // TODO: validate that xsl:param elements have unique name attributes let mut params: Vec<(QualifiedName, Option<Transform<N>>)> = Vec::new(); c.child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "param" }) .try_for_each(|c| { let p_name = c.get_attribute(&QualifiedName::new(None, None, "name")); if p_name.to_string().is_empty() { Err(Error::new( ErrorKind::StaticAbsent, "name attribute is missing", )) } else { let sel = c.get_attribute(&QualifiedName::new(None, None, "select")); if sel.to_string().is_empty() { // xsl:param content is the sequence constructor let mut body = vec![]; c.child_iter().try_for_each(|d| { body.push(to_transform(d, &attr_sets)?); Ok(()) })?; params.push(( QualifiedName::new(None, None, p_name.to_string()), Some(Transform::SequenceItems(body)), )); Ok(()) } else { // select attribute value is an expression params.push(( QualifiedName::new(None, None, p_name.to_string()), Some(parse::<N>(&sel.to_string(), Some(c.clone()))?), )); Ok(()) } } })?; // Content is the template body let mut body = vec![]; c.child_iter() .filter(|c| { !(c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "param") }) .try_for_each(|d| { body.push(to_transform(d, &attr_sets)?); Ok::<(), Error>(()) })?; newctxt.callable_push( QualifiedName::new(None, None, name.to_string()), Callable::new( Transform::SequenceItems(body), FormalParameters::Named(params), ), ); Ok(()) })?; // Add functions stylenode .child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "function" }) .try_for_each(|c| { let name = c.get_attribute(&QualifiedName::new(None, None, "name")); // Name must have a namespace. See XSLT 10.3.1. let eqname = QualifiedName::try_from((name.to_string().as_str(), c.clone()))?; if eqname.namespace_uri().is_none() { return Err(Error::new_with_code( ErrorKind::StaticAbsent, "function name must have a namespace", Some(QualifiedName::new(None, None, "XTSE0740")), )); } // xsl:param for formal parameters // TODO: validate that xsl:param elements come first in the child list // TODO: validate that xsl:param elements have unique name attributes let mut params: Vec<QualifiedName> = Vec::new(); c.child_iter() .filter(|c| { c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "param" }) .try_for_each(|c| { let p_name = c.get_attribute(&QualifiedName::new(None, None, "name")); if p_name.to_string().is_empty() { Err(Error::new( ErrorKind::StaticAbsent, "name attribute is missing", )) } else { // TODO: validate that xsl:param elements do not specify a default value. See XSLT 10.3.2. params.push(QualifiedName::new(None, None, p_name.to_string())); Ok(()) } })?; // Content is the function body let mut body = vec![]; c.child_iter() .filter(|c| { !(c.is_element() && c.name().namespace_uri_to_string() == Some(XSLTNS.to_string()) && c.name().localname_to_string() == "param") }) .try_for_each(|d| { body.push(to_transform(d, &attr_sets)?); Ok::<(), Error>(()) })?; newctxt.callable_push( eqname, Callable::new( Transform::SequenceItems(body), FormalParameters::Positional(params), ), ); Ok(()) })?; Ok(newctxt) } /// Compile a node in a template to a sequence [Combinator] fn to_transform<N: Node>( n: N, attr_sets: &HashMap<QualifiedName, Vec<Transform<N>>>, ) -> Result<Transform<N>, Error> { // Define the in-scope namespaces once so they can be shared let ns = in_scope_namespaces(Some(n.clone())); match n.node_type() { NodeType::Text => Ok(Transform::Literal(Item::Value(Rc::new(Value::String( n.to_string(), ))))), NodeType::Element => { match ( n.name().namespace_uri_to_string().as_deref(), n.name().localname_to_string().as_str(), ) { (Some(XSLTNS), "text") => { let doe = n.get_attribute(&QualifiedName::new( None, None, "disable-output-escaping".to_string(), )); if !doe.to_string().is_empty() { match &doe.to_string()[..] { "yes" => Ok(Transform::Literal(Item::Value(Rc::new(Value::String( n.to_string(), ))))), "no" => { let text = n .to_string() .replace('&', "&amp;") .replace('>', "&gt;") .replace('<', "&lt;") .replace('\'', "&apos;") .replace('\"', "&quot;"); Ok(Transform::Literal(Item::Value(Rc::new(Value::from(text))))) } _ => Err(Error::new( ErrorKind::TypeError, "disable-output-escaping only accepts values yes or no." .to_string(), )), } } else { let text = n .to_string() .replace('&', "&amp;") .replace('>', "&gt;") .replace('<', "&lt;") .replace('\'', "&apos;") .replace('\"', "&quot;"); Ok(Transform::Literal(Item::Value(Rc::new(Value::from(text))))) } } (Some(XSLTNS), "value-of") => { let sel = n.get_attribute(&QualifiedName::new(None, None, "select".to_string())); let doe = n.get_attribute(&QualifiedName::new( None, None, "disable-output-escaping".to_string(), )); if !doe.to_string().is_empty() { match &doe.to_string()[..] { "yes" => Ok(Transform::LiteralText( Box::new(parse::<N>(&sel.to_string(), Some(n.clone()))?), true, )), "no" => Ok(Transform::LiteralText( Box::new(parse::<N>(&sel.to_string(), Some(n.clone()))?), false, )), _ => Err(Error::new( ErrorKind::TypeError, "disable-output-escaping only accepts values yes or no." .to_string(), )), } } else { Ok(Transform::LiteralText( Box::new(parse::<N>(&sel.to_string(), Some(n.clone()))?), false, )) } } (Some(XSLTNS), "apply-templates") => { let sel = n.get_attribute(&QualifiedName::new(None, None, "select")); let m = n.get_attribute_node(&QualifiedName::new(None, None, "mode")); let sort_keys = get_sort_keys(&n)?; if !sel.to_string().is_empty() { Ok(Transform::ApplyTemplates( Box::new(parse::<N>(&sel.to_string(), Some(n.clone()))?), m.map(|s| { Rc::new( QualifiedName::try_from((s.to_string().as_str(), n)) .expect("unable to resolve qualified name"), ) }), sort_keys, )) // TODO: don't panic } else { // If there is no select attribute, then default is "child::node()" Ok(Transform::ApplyTemplates( Box::new(Transform::Step(NodeMatch::new( Axis::Child, NodeTest::Kind(KindTest::Any), ))), m.map(|s| { Rc::new( QualifiedName::try_from((s.to_string().as_str(), n)) .expect("unable to resolve qualified name"), ) }), sort_keys, )) // TODO: don't panic } } (Some(XSLTNS), "apply-imports") => Ok(Transform::ApplyImports), (Some(XSLTNS), "sequence") => { let s = n.get_attribute(&QualifiedName::new(None, None, "select".to_string())); if !s.to_string().is_empty() { Ok(parse::<N>(&s.to_string(), Some(n.clone()))?) } else { Result::Err(Error::new( ErrorKind::TypeError, "missing select attribute".to_string(), )) } } (Some(XSLTNS), "if") => { let t = n.get_attribute(&QualifiedName::new(None, None, "test"));
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
true
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/xmldecl.rs
src/xmldecl.rs
/*! Defines common features of XML documents. */ use crate::qname::QualifiedName; use std::collections::HashMap; use std::fmt; use std::fmt::Formatter; #[derive(Clone, PartialEq)] pub struct XMLDecl { pub(crate) version: String, pub(crate) encoding: Option<String>, pub(crate) standalone: Option<String>, } impl XMLDecl { pub fn new(version: String, encoding: Option<String>, standalone: Option<String>) -> Self { XMLDecl { version, encoding, standalone, } } pub fn version(&self) -> String { self.version.clone() } pub fn set_encoding(&mut self, e: String) { self.encoding = Some(e) } pub fn encoding(&self) -> String { self.encoding.as_ref().map_or(String::new(), |e| e.clone()) } pub fn set_standalone(&mut self, s: String) { self.standalone = Some(s) } pub fn standalone(&self) -> String { self.standalone .as_ref() .map_or(String::new(), |e| e.clone()) } } impl fmt::Display for XMLDecl { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut result = String::from("<?xml version=\""); result.push_str(self.version.as_str()); result.push('"'); if let Some(e) = self.encoding.as_ref() { result.push_str(" encoding=\""); result.push_str(e.as_str()); result.push('"'); }; if let Some(e) = self.standalone.as_ref() { result.push_str(" standalone=\""); result.push_str(e.as_str()); result.push('"'); }; f.write_str(result.as_str()) } } pub struct XMLDeclBuilder(XMLDecl); impl Default for XMLDeclBuilder { fn default() -> Self { Self::new() } } impl XMLDeclBuilder { pub fn new() -> Self { XMLDeclBuilder(XMLDecl { version: String::new(), encoding: None, standalone: None, }) } pub fn version(mut self, v: String) -> Self { self.0.version = v; self } pub fn encoding(mut self, v: String) -> Self { self.0.encoding = Some(v); self } pub fn standalone(mut self, v: String) -> Self { self.0.standalone = Some(v); self } pub fn build(self) -> XMLDecl { self.0 } } /// DTD declarations. /// Data is not stored in any fashion conformant with any standard and will be adusted to meet /// the needs of any validators implemented. /// #[derive(Clone, PartialEq, Debug)] pub struct DTD { /// This struct is for internal consumption mainly, it holding the DTD in various incomplete forms /// before construction into useful patterns for validation pub(crate) elements: HashMap<QualifiedName, DTDPattern>, pub(crate) attlists: HashMap<QualifiedName, HashMap<QualifiedName, (AttType, DefaultDecl, bool)>>, // Boolean for is_editable; pub(crate) notations: HashMap<String, DTDDecl>, pub(crate) generalentities: HashMap<String, (String, bool)>, // Boolean for is_editable; pub(crate) paramentities: HashMap<String, (String, bool)>, // Boolean for is_editable; publicid: Option<String>, systemid: Option<String>, pub(crate) name: Option<QualifiedName>, pub(crate) patterns: HashMap<QualifiedName, DTDPattern>, } impl DTD { pub fn new() -> DTD { let default_entities = vec![ ("amp".to_string(), ("&".to_string(), false)), ("gt".to_string(), (">".to_string(), false)), ("lt".to_string(), ("<".to_string(), false)), ("apos".to_string(), ("'".to_string(), false)), ("quot".to_string(), ("\"".to_string(), false)), ]; DTD { elements: Default::default(), attlists: Default::default(), notations: Default::default(), generalentities: default_entities.into_iter().collect(), paramentities: HashMap::new(), publicid: None, systemid: None, name: None, patterns: HashMap::new(), } } } impl Default for DTD { fn default() -> Self { Self::new() } } #[derive(Clone, Debug, Eq, PartialEq)] pub enum DTDDecl { Notation(QualifiedName, String), GeneralEntity(QualifiedName, String), ParamEntity(QualifiedName, String), } #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum AttType { CDATA, ID, IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NMTOKENS, NOTATION(Vec<String>), ENUMERATION(Vec<String>), } #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum DefaultDecl { Required, Implied, FIXED(String), Default(String), } #[derive(Clone, PartialEq, Debug)] pub(crate) enum DTDPattern { Choice(Box<DTDPattern>, Box<DTDPattern>), Interleave(Box<DTDPattern>, Box<DTDPattern>), Group(Box<DTDPattern>, Box<DTDPattern>), OneOrMore(Box<DTDPattern>), After(Box<DTDPattern>, Box<DTDPattern>), Empty, NotAllowed, Text, Value(String), Attribute(QualifiedName, Box<DTDPattern>), Element(QualifiedName, Box<DTDPattern>), Ref(QualifiedName), Any, /* This Enum is never used, but it might see application when properly validating ENTITYs. */ #[allow(dead_code)] List(Box<DTDPattern>), }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/qname.rs
src/qname.rs
//! Support for Qualified Names. //! TODO: Intern names for speedy equality checks (compare pointers, rather than characters). use crate::item::Node; use crate::namespace::NamespaceMap; use crate::parser::xml::qname::eqname; use crate::parser::ParserState; use crate::trees::nullo::Nullo; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use core::hash::{Hash, Hasher}; use std::cmp::Ordering; use std::collections::HashMap; use std::fmt; use std::fmt::Debug; use std::fmt::Formatter; use std::rc::Rc; #[derive(Clone)] pub struct QualifiedName { nsuri: Option<Rc<Value>>, prefix: Option<Rc<Value>>, localname: Rc<Value>, } // TODO: we may need methods that return a string slice, rather than a copy of the string impl QualifiedName { /// Builds a QualifiedName from String parts pub fn new( nsuri: Option<String>, prefix: Option<String>, localname: impl Into<String>, ) -> QualifiedName { QualifiedName { nsuri: nsuri.map(|s| Rc::new(Value::from(s))), prefix: prefix.map(|s| Rc::new(Value::from(s))), localname: Rc::new(Value::from(localname.into())), } } /// Builds a QualifiedName from shared components pub fn new_from_values( nsuri: Option<Rc<Value>>, prefix: Option<Rc<Value>>, localname: Rc<Value>, ) -> QualifiedName { QualifiedName { nsuri, prefix, localname, } } pub fn as_ref(&self) -> &Self { self } pub fn namespace_uri(&self) -> Option<Rc<Value>> { self.nsuri.clone() } pub fn namespace_uri_to_string(&self) -> Option<String> { self.nsuri.as_ref().map(|x| x.to_string()) } pub fn prefix(&self) -> Option<Rc<Value>> { self.prefix.clone() } pub fn prefix_to_string(&self) -> Option<String> { self.prefix.as_ref().map(|x| x.to_string()) } pub fn localname(&self) -> Rc<Value> { self.localname.clone() } pub fn localname_to_string(&self) -> String { self.localname.to_string() } /// Fully resolve a qualified name. If the qualified name has a prefix but no namespace URI, /// then find the prefix in the supplied namespaces and use the corresponding URI. /// If the qualified name already has a namespace URI, then this method has no effect. /// If the qualified name has no prefix, then this method has no effect. pub fn resolve<F>(&mut self, mapper: F) -> Result<(), Error> where F: Fn(Option<Rc<Value>>) -> Result<Rc<Value>, Error>, { match (&self.prefix, &self.nsuri) { (Some(p), None) => { self.nsuri = Some(mapper(Some(p.clone()))?.clone()); Ok(()) } _ => Ok(()), } } } impl fmt::Display for QualifiedName { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut result = String::new(); let _ = self.prefix.as_ref().map_or((), |p| { result.push_str(p.to_string().as_str()); result.push(':'); }); result.push_str(self.localname.to_string().as_str()); f.write_str(result.as_str()) } } impl Debug for QualifiedName { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let _ = f.write_str("namespace "); let _ = f.write_str( self.nsuri .as_ref() .map_or("--none--".to_string(), |ns| ns.to_string()) .as_str(), ); let _ = f.write_str(" prefix "); let _ = f.write_str( self.prefix .as_ref() .map_or("--none--".to_string(), |p| p.to_string()) .as_str(), ); let _ = f.write_str(" local part \""); let _ = f.write_str(self.localname.to_string().as_str()); f.write_str("\"") } } pub type QHash<T> = HashMap<QualifiedName, T>; impl PartialEq for QualifiedName { // Only the namespace URI and local name have to match fn eq(&self, other: &QualifiedName) -> bool { self.nsuri.as_ref().map_or_else( || { other .nsuri .as_ref() .map_or_else(|| self.localname.eq(&other.localname), |_| false) }, |ns| { other.nsuri.as_ref().map_or_else( || false, |ons| ns.eq(ons) && self.localname.eq(&other.localname), ) }, ) } } /// A partial ordering for QualifiedNames. Unprefixed names are considered to come before prefixed names. impl PartialOrd for QualifiedName { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { match (&self.nsuri, &other.nsuri) { (None, None) => self.localname.partial_cmp(&other.localname), (Some(_), None) => Some(Ordering::Greater), (None, Some(_)) => Some(Ordering::Less), (Some(n), Some(m)) => { if n == m { self.localname.partial_cmp(&other.localname) } else { n.partial_cmp(m) } } } } } impl Ord for QualifiedName { fn cmp(&self, other: &Self) -> Ordering { self.partial_cmp(other).unwrap() } } impl Eq for QualifiedName {} impl Hash for QualifiedName { fn hash<H: Hasher>(&self, state: &mut H) { if let Some(ns) = self.nsuri.as_ref() { ns.hash(state) } self.localname.hash(state); } } /// Parse a string to create a [QualifiedName]. /// QualifiedName ::= (prefix ":")? local-name impl TryFrom<&str> for QualifiedName { type Error = Error; fn try_from(s: &str) -> Result<Self, Self::Error> { let state: ParserState<Nullo> = ParserState::new(None, None, None); match eqname()((s, state)) { Ok((_, qn)) => Ok(qn), Err(_) => Err(Error::new( ErrorKind::ParseError, String::from("unable to parse qualified name"), )), } } } /// Parse a string to create a [QualifiedName]. /// Resolve prefix against a set of XML Namespace declarations. /// This method can be used when there is no XSL stylesheet to derive the namespaces. /// QualifiedName ::= (prefix ":")? local-name impl TryFrom<(&str, Rc<NamespaceMap>)> for QualifiedName { type Error = Error; fn try_from(s: (&str, Rc<NamespaceMap>)) -> Result<Self, Self::Error> { let state: ParserState<Nullo> = ParserState::new(None, None, None); match eqname()((s.0, state)) { Ok((_, qn)) => { if qn.prefix().is_some() && qn.namespace_uri().is_none() { match s.1.get(&qn.prefix()) { Some(ns) => Ok(QualifiedName::new_from_values( Some(ns), qn.prefix(), qn.localname().clone(), )), _ => Err(Error::new( ErrorKind::Unknown, format!( "unable to match prefix \"{}\"", qn.prefix_to_string().unwrap() ), )), } } else { Ok(qn) } } Err(_) => Err(Error::new( ErrorKind::ParseError, String::from("unable to parse qualified name"), )), } } } /// Parse a string to create a [QualifiedName]. /// Resolve prefix against a set of XML Namespace declarations. /// This method can be used when there is an XSL stylesheet to derive the namespaces. /// QualifiedName ::= (prefix ":")? local-name impl<N: Node> TryFrom<(&str, N)> for QualifiedName { type Error = Error; fn try_from(s: (&str, N)) -> Result<Self, Self::Error> { let state: ParserState<Nullo> = ParserState::new(None, None, None); match eqname()((s.0, state)) { Ok((_, qn)) => { if qn.prefix().is_some() && qn.namespace_uri().is_none() { s.1.namespace_iter() .find(|ns| ns.name().localname() == qn.prefix().unwrap()) .map_or( Err(Error::new( ErrorKind::DynamicAbsent, format!( "no namespace matching prefix \"{}\"", qn.prefix_to_string().unwrap() ), )), |ns| { Ok(QualifiedName::new_from_values( Some(ns.value()), qn.prefix(), qn.localname(), )) }, ) } else { Ok(qn) } } Err(_) => Err(Error::new( ErrorKind::ParseError, String::from("unable to parse qualified name"), )), } } } #[cfg(test)] mod tests { use super::*; #[test] fn unqualified_raw() { assert_eq!(QualifiedName::new(None, None, "foo").to_string(), "foo") } #[test] fn unqualified_rc() { assert_eq!( QualifiedName::new_from_values(None, None, Rc::new(Value::from("foo"))).to_string(), "foo" ) } #[test] fn qualified_raw() { assert_eq!( QualifiedName::new( Some("http://example.org/whatsinaname/".to_string()), Some("x".to_string()), "foo".to_string() ) .to_string(), "x:foo" ) } #[test] fn qualified_rc() { assert_eq!( QualifiedName::new_from_values( Some(Rc::new(Value::from("http://example.org/whatsinaname/"))), Some(Rc::new(Value::from("x"))), Rc::new(Value::from("foo")) ) .to_string(), "x:foo" ) } #[test] fn eqname() { let e = QualifiedName::try_from("Q{http://example.org/bar}foo") .expect("unable to parse EQName"); assert_eq!(e.localname_to_string(), "foo"); assert_eq!( e.namespace_uri_to_string(), Some(String::from("http://example.org/bar")) ); assert_eq!(e.prefix_to_string(), None) } #[test] fn hashmap() { let mut h = QHash::<String>::new(); h.insert( QualifiedName::new(None, None, "foo"), String::from("this is unprefixed foo"), ); h.insert( QualifiedName::new( Some("http://example.org/whatsinaname/".to_string()), Some("x".to_string()), "foo", ), "this is x:foo".to_string(), ); h.insert( QualifiedName::new( Some("http://example.org/whatsinaname/".to_string()), Some("y".to_string()), "bar", ), "this is y:bar".to_string(), ); assert_eq!(h.len(), 3); assert_eq!( h.get(&QualifiedName { nsuri: Some(Rc::new(Value::from("http://example.org/whatsinaname/"))), prefix: Some(Rc::new(Value::from("x"))), localname: Rc::new(Value::from("foo")), }), Some(&"this is x:foo".to_string()) ); assert_eq!( h.get(&QualifiedName { nsuri: None, prefix: None, localname: Rc::new(Value::from("foo")), }), Some(&"this is unprefixed foo".to_string()) ); } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/item.rs
src/item.rs
/*! Sequences and Items. A [Sequence] is the fundamental data type in XPath. It is a series of zero or more [Item]s. An [Item] is a [Node], Function or atomic [Value]. [Node]s are defined as a trait. */ use crate::item; use crate::output::OutputDefinition; use crate::qname::QualifiedName; use crate::validators::{Schema, ValidationError}; use crate::value::{Operator, Value}; use crate::xdmerror::{Error, ErrorKind}; use crate::xmldecl::{XMLDecl, DTD}; use std::cmp::Ordering; use std::fmt; use std::fmt::Formatter; use std::rc::Rc; /// In XPath, the Sequence is the fundamental data structure. /// It is an ordered collection of [Item]s. /// The Rust implementation is a Vector of reference counted [Item]s. /// /// See [SequenceTrait] for methods. pub type Sequence<N> = Vec<Item<N>>; pub trait SequenceTrait<N: Node> { /// Return the string value of the [Sequence]. fn to_string(&self) -> String; /// Return a XML formatted representation of the [Sequence]. fn to_xml(&self) -> String; /// Return a XML formatted representation of the [Sequence], controlled by the supplied output definition. fn to_xml_with_options(&self, od: &OutputDefinition) -> String; /// Return a JSON formatted representation of the [Sequence]. fn to_json(&self) -> String; /// Return the Effective Boolean Value of the [Sequence]. fn to_bool(&self) -> bool; /// Convert the [Sequence] to an integer. The [Sequence] must be a singleton value. fn to_int(&self) -> Result<i64, Error>; /// Push an [Node] to the [Sequence] fn push_node(&mut self, n: &N); /// Push a [Value] to the [Sequence] fn push_value(&mut self, v: &Rc<Value>); /// Push an [Item] to the [Sequence]. This clones the item. fn push_item(&mut self, i: &Item<N>); } impl<N: Node> SequenceTrait<N> for Sequence<N> { /// Returns the string value of the Sequence. fn to_string(&self) -> String { let mut r = String::new(); for i in self { r.push_str(i.to_string().as_str()) } r } /// Renders the Sequence as XML fn to_xml(&self) -> String { let mut r = String::new(); for i in self { r.push_str(i.to_xml().as_str()) } r } /// Renders the Sequence as XML fn to_xml_with_options(&self, od: &OutputDefinition) -> String { let mut r = String::new(); for i in self { r.push_str(i.to_xml_with_options(od).as_str()) } r } /// Renders the Sequence as JSON fn to_json(&self) -> String { let mut r = String::new(); for i in self { r.push_str(i.to_json().as_str()) } r } /// Push a document's [Node] on to the [Sequence]. This clones the node. fn push_node(&mut self, n: &N) { self.push(Item::Node(n.clone())); } /// Push a [Value] on to the [Sequence]. fn push_value(&mut self, v: &Rc<Value>) { self.push(Item::Value(Rc::clone(v))); } //fn new_function(&self, f: Function) -> Sequence { //} /// Push an [Item] on to the [Sequence]. This clones the Item. fn push_item(&mut self, i: &Item<N>) { self.push(i.clone()); } /// Calculate the effective boolean value of the Sequence fn to_bool(&self) -> bool { if self.is_empty() { false } else { match self[0] { Item::Node(..) => true, _ => { if self.len() == 1 { self[0].to_bool() } else { false // should be a type error } } } } } /// Convenience routine for integer value of the [Sequence]. The Sequence must be a singleton; i.e. be a single item. fn to_int(&self) -> Result<i64, Error> { if self.len() == 1 { self[0].to_int() } else { Err(Error::new( ErrorKind::TypeError, String::from("type error: sequence is not a singleton"), )) } } } impl<N: Node> From<Value> for Sequence<N> { fn from(v: Value) -> Self { vec![Item::Value(Rc::new(v))] } } impl<N: Node> From<Item<N>> for Sequence<N> { fn from(i: Item<N>) -> Self { vec![i] } } /// All [Node]s have a type. The type of the [Node] determines what components are meaningful, such as name and content. /// /// Every document must have a single node as it's toplevel node that is of type "Document". /// /// Namespace nodes represent the declaration of an XML Namespace. #[derive(Copy, Clone, Eq, PartialEq, Debug, Default)] pub enum NodeType { Document, Element, Text, Attribute, Comment, ProcessingInstruction, Reference, Namespace, #[default] Unknown, } impl NodeType { /// Return a string representation of the node type. pub fn to_string(&self) -> &'static str { match self { NodeType::Document => "Document", NodeType::Element => "Element", NodeType::Attribute => "Attribute", NodeType::Text => "Text", NodeType::ProcessingInstruction => "Processing-Instruction", NodeType::Comment => "Comment", NodeType::Reference => "Reference", NodeType::Namespace => "Namespace", NodeType::Unknown => "--None--", } } } impl fmt::Display for NodeType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.to_string()) } } /// An Item in a [Sequence]. Can be a node, function or [Value]. /// /// Functions are not yet implemented. #[derive(Clone)] pub enum Item<N: Node> { /// A [Node] in the source document. Node(N), /// Functions are not yet supported Function, /// A scalar value. These are in an Rc since they are frequently shared. Value(Rc<Value>), } impl<N: item::Node> fmt::Display for Item<N> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { // Gives the string value of an item. All items have a string value. let result = match self { Item::Node(n) => n.to_string(), Item::Function => "".to_string(), Item::Value(v) => v.to_string(), }; f.write_str(result.as_str()) } } impl<N: Node> Item<N> { /// Serialize as XML pub fn to_xml(&self) -> String { match self { Item::Node(n) => n.to_xml(), Item::Function => "".to_string(), Item::Value(v) => v.to_string(), } } /// Serialize as XML, with options pub fn to_xml_with_options(&self, od: &OutputDefinition) -> String { match self { Item::Node(n) => n.to_xml_with_options(od), Item::Function => "".to_string(), Item::Value(v) => v.to_string(), } } /// Serialize as JSON pub fn to_json(&self) -> String { match self { Item::Node(n) => n.to_json(), Item::Function => "".to_string(), Item::Value(v) => v.to_string(), } } /// Determine the effective boolean value of the item. /// See XPath 2.4.3. pub fn to_bool(&self) -> bool { match self { Item::Node(..) => true, Item::Function => false, Item::Value(v) => v.to_bool(), } } /// Gives the integer value of the item, if possible. pub fn to_int(&self) -> Result<i64, Error> { match self { Item::Node(..) => Result::Err(Error::new( ErrorKind::TypeError, String::from("type error: item is a node"), )), Item::Function => Result::Err(Error::new( ErrorKind::TypeError, String::from("type error: item is a function"), )), Item::Value(v) => match v.to_int() { Ok(i) => Ok(i), Err(e) => Result::Err(e), }, } } /// Gives the double value of the item. Returns NaN if the value cannot be converted to a double. pub fn to_double(&self) -> f64 { match self { Item::Node(..) => f64::NAN, Item::Function => f64::NAN, Item::Value(v) => v.to_double(), } } /// Gives the name of the item. Certain types of Nodes have names, such as element-type nodes. If the item does not have a name returns an empty string. pub fn name(&self) -> Rc<QualifiedName> { match self { Item::Node(n) => n.name(), _ => Rc::new(QualifiedName::new(None, None, "")), } } // TODO: atomization // fn atomize(&self); /// Compare two items. pub fn compare(&self, other: &Item<N>, op: Operator) -> Result<bool, Error> { match self { Item::Value(v) => match other { Item::Value(w) => v.compare(w, op), Item::Node(..) => v.compare(&Value::String(other.to_string()), op), _ => Result::Err(Error::new(ErrorKind::TypeError, String::from("type error"))), }, Item::Node(..) => { other.compare(&Item::Value(Rc::new(Value::String(self.to_string()))), op) } _ => Result::Err(Error::new(ErrorKind::TypeError, String::from("type error"))), } } /// Is this item a node? pub fn is_node(&self) -> bool { match self { Item::Node(_) => true, _ => false, } } /// Is this item an element-type node? pub fn is_element_node(&self) -> bool { match self { Item::Node(n) => matches!(n.node_type(), NodeType::Element), _ => false, } } /// Convenience method to set an attribute for a Node-type item. /// If the item is not an element-type node, then this method has no effect. pub fn add_attribute(&self, a: N) -> Result<(), Error> { match self { Item::Node(n) => match n.node_type() { NodeType::Element => n.add_attribute(a), _ => Ok(()), }, _ => Ok(()), } } /// Gives the type of the item. pub fn item_type(&self) -> &'static str { match self { Item::Node(..) => "Node", Item::Function => "Function", Item::Value(v) => v.value_type(), } } /// Make a shallow copy of an item. /// That is, the item is duplicated but not it's content, including attributes. pub fn shallow_copy(&self) -> Result<Self, Error> { match self { Item::Value(v) => Ok(Item::Value(v.clone())), Item::Node(n) => Ok(Item::Node(n.shallow_copy()?)), _ => Result::Err(Error::new( ErrorKind::NotImplemented, "not implemented".to_string(), )), } } /// Make a deep copy of an item. pub fn deep_copy(&self) -> Result<Self, Error> { match self { Item::Value(v) => Ok(Item::Value(v.clone())), Item::Node(n) => Ok(Item::Node(n.deep_copy()?)), _ => Result::Err(Error::new( ErrorKind::NotImplemented, "not implemented".to_string(), )), } } } impl<N: Node> fmt::Debug for Item<N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Item::Node(n) => { write!( f, "node type item ({:?})", n // "node type item (node type {}, name \"{}\")", // n.node_type().to_string(), // n.name() ) } Item::Function => { write!(f, "function type item") } Item::Value(v) => { write!(f, "value type item ({})", v) } } } } /// Nodes make up a document tree. Nodes must be fully navigable. The tree must be mutable but also stable (i.e. removing a node from the tree does not invalidate the remaining nodes). /// /// Some nodes have names, such as elements. Some nodes have values, such as text or comments. Some have both a name and a value, such as attributes and processing instructions. /// /// Element nodes have children and attributes. /// /// Element nodes may have a Namespace node attached. This is the declaration of an XML Namespace. /// The namespace-iter() method iterates over all in-scope namespaces, which will include namespaces that are declared on ancestor elements. /// /// Nodes must implement the PartialEq trait. This allows two (sub-)trees to be compared. The comparison is against the XML Infoset of each tree; /// i.e. do the trees contain the same information, but not necessarily the same string representation. /// For example, the order of attributes does not matter. pub trait Node: Clone + PartialEq + fmt::Debug { type NodeIterator: Iterator<Item = Self>; /// Create a Document-type node. /// All other types of nodes are created using type-specific methods (new_element, new_text, etc). fn new_document() -> Self; /// Get the type of the node fn node_type(&self) -> NodeType; /// Get the name of the node. /// If the node doesn't have a name, then returns a [QualifiedName] with an empty string for it's localname. /// If the node is a namespace-type node, then the local part of the name is the namespace prefix. An unprefixed namespace has the empty string as its name. fn name(&self) -> Rc<QualifiedName>; /// Get the value of the node. /// If the node doesn't have a value, then returns a [Value] that is an empty string. /// If the node is a namespace-type node, then the value is the namespace URI. fn value(&self) -> Rc<Value>; /// Get a unique identifier for this node. fn get_id(&self) -> String; /// Get the string value of the node. See XPath ??? fn to_string(&self) -> String; /// Serialise the node as XML fn to_xml(&self) -> String; /// Serialise the node as XML, with options such as indentation. fn to_xml_with_options(&self, od: &OutputDefinition) -> String; /// Serialise the node as JSON fn to_json(&self) -> String { String::new() } /// Check if two Nodes are the same Node fn is_same(&self, other: &Self) -> bool; /// Get the document order of the node. The value returned is relative to the document containing the node. /// Depending on the implementation, this value may be volatile; /// adding or removing nodes to/from the document may invalidate the ordering. fn document_order(&self) -> Vec<usize>; /// Compare the document order of this node with another node in the same document. fn cmp_document_order(&self, other: &Self) -> Ordering; /// Check if a node is an element-type fn is_element(&self) -> bool { self.node_type() == NodeType::Element } /// Check if a node is an XML ID fn is_id(&self) -> bool; /// Check if a node is an XML IDREF or IDREFS fn is_idrefs(&self) -> bool; /// An iterator over the children of the node fn child_iter(&self) -> Self::NodeIterator; /// Get the first child of the node, if there is one fn first_child(&self) -> Option<Self> where Self: Sized, { self.child_iter().next() } /// An iterator over the ancestors of the node fn ancestor_iter(&self) -> Self::NodeIterator; /// Get the parent of the node. Top-level nodes do not have parents, also nodes that have been detached from the tree. fn parent(&self) -> Option<Self> where Self: Sized, { self.ancestor_iter().next() } /// Get the document node fn owner_document(&self) -> Self; /// An iterator over the descendants of the node fn descend_iter(&self) -> Self::NodeIterator; /// An iterator over the following siblings of the node fn next_iter(&self) -> Self::NodeIterator; /// An iterator over the preceding siblings of the node fn prev_iter(&self) -> Self::NodeIterator; /// An iterator over the attributes of an element fn attribute_iter(&self) -> Self::NodeIterator; /// Get an attribute of the node. Returns a copy of the attribute's value. If the node does not have an attribute of the given name, a value containing an empty string is returned. fn get_attribute(&self, a: &QualifiedName) -> Rc<Value>; /// Get an attribute of the node. If the node is not an element returns None. Otherwise returns the attribute node. If the node does not have an attribute of the given name, returns None. fn get_attribute_node(&self, a: &QualifiedName) -> Option<Self>; /// Create a new element-type node in the same document tree. The new node is not attached to the tree. fn new_element(&self, qn: Rc<QualifiedName>) -> Result<Self, Error>; /// Create a new text-type node in the same document tree. The new node is not attached to the tree. fn new_text(&self, v: Rc<Value>) -> Result<Self, Error>; /// Create a new attribute-type node in the same document tree. The new node is not attached to the tree. fn new_attribute(&self, qn: Rc<QualifiedName>, v: Rc<Value>) -> Result<Self, Error>; /// Create a new comment-type node in the same document tree. The new node is not attached to the tree. fn new_comment(&self, v: Rc<Value>) -> Result<Self, Error>; /// Create a new processing-instruction-type node in the same document tree. The new node is not attached to the tree. fn new_processing_instruction( &self, qn: Rc<QualifiedName>, v: Rc<Value>, ) -> Result<Self, Error>; /// Create a namespace node for an XML Namespace declaration. fn new_namespace(&self, ns: Rc<Value>, prefix: Option<Rc<Value>>) -> Result<Self, Error>; /// Append a node to the child list fn push(&mut self, n: Self) -> Result<(), Error>; /// Remove a node from the tree fn pop(&mut self) -> Result<(), Error>; /// Insert a node in the child list before the given node. The node will be detached from it's current position prior to insertion. fn insert_before(&mut self, n: Self) -> Result<(), Error>; /// Set an attribute. self must be an element-type node. att must be an attribute-type node. fn add_attribute(&self, att: Self) -> Result<(), Error>; /// Shallow copy the node, i.e. copy only the node, but not it's attributes or content. fn shallow_copy(&self) -> Result<Self, Error>; /// Deep copy the node, i.e. the node itself and it's attributes and descendants. The resulting top-level node is unattached. fn deep_copy(&self) -> Result<Self, Error>; /// Canonical XML representation of the node. fn get_canonical(&self) -> Result<Self, Error>; /// Get the XML Declaration for the document. fn xmldecl(&self) -> XMLDecl; /// Set the XML Declaration for the document. fn set_xmldecl(&mut self, d: XMLDecl) -> Result<(), Error>; /// Add a namespace declaration to this element-type node. /// NOTE: Does NOT assign a namespace to the element. The element's name defines its namespace. fn add_namespace(&self, ns: Self) -> Result<(), Error>; /// Compare two trees. If a non-document node is used, then the descendant subtrees are compared. fn eq(&self, other: &Self) -> bool { match self.node_type() { NodeType::Document => { if other.node_type() == NodeType::Document { self.child_iter() .zip(other.child_iter()) .fold(true, |mut acc, (c, d)| { if acc { acc = Node::eq(&c, &d); acc } else { acc } }) // TODO: use a method that terminates early on non-equality } else { false } } NodeType::Element => { // names must match, // attributes must match (order doesn't matter), // content must match if other.node_type() == NodeType::Element { if self.name() == other.name() { // Attributes let mut at_names: Vec<Rc<QualifiedName>> = self.attribute_iter().map(|a| a.name()).collect(); if at_names.len() == other.attribute_iter().count() { at_names.sort(); if at_names.iter().fold(true, |mut acc, qn| { if acc { acc = self.get_attribute(qn) == other.get_attribute(qn); acc } else { acc } }) { // Content self.child_iter().zip(other.child_iter()).fold( true, |mut acc, (c, d)| { if acc { acc = Node::eq(&c, &d); acc } else { acc } }, ) // TODO: use a method that terminates early on non-equality } else { false } } else { false } } else { false } } else { false } } NodeType::Text => { if other.node_type() == NodeType::Text { self.value() == other.value() } else { false } } NodeType::ProcessingInstruction => { if other.node_type() == NodeType::ProcessingInstruction { self.name() == other.name() && self.value() == other.value() } else { false } } _ => self.node_type() == other.node_type(), // Other types of node do not affect the equality } } /// An iterator over the in-scope namespace nodes of an element. /// Note: These nodes are calculated at the time the iterator is created. /// It is not guaranteed that the namespace nodes returned /// will specify the current element node as their parent. fn namespace_iter(&self) -> Self::NodeIterator; /// Retrieve the internal representation of the DTD, for use in validation functions. fn get_dtd(&self) -> Option<DTD>; /// Store an internal representation of the DTD. Does not keep a copy of the original text fn set_dtd(&self, dtd: DTD) -> Result<(), Error>; fn validate(&self, schema: Schema) -> Result<(), ValidationError>; }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/output.rs
src/output.rs
/*! How to serialise a tree structure. */ use crate::qname::QualifiedName; use core::fmt; /// An output definition. See XSLT v3.0 26 Serialization #[derive(Clone, Debug)] pub struct OutputDefinition { name: Option<QualifiedName>, // TODO: EQName indent: bool, // TODO: all the other myriad output parameters } impl Default for OutputDefinition { fn default() -> Self { Self::new() } } impl OutputDefinition { pub fn new() -> OutputDefinition { OutputDefinition { name: None, indent: false, } } pub fn get_name(&self) -> Option<QualifiedName> { self.name.clone() } pub fn set_name(&mut self, name: Option<QualifiedName>) { match name { Some(n) => { self.name.replace(n); } None => { self.name = None; } } } pub fn get_indent(&self) -> bool { self.indent } pub fn set_indent(&mut self, ind: bool) { self.indent = ind; } } impl fmt::Display for OutputDefinition { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.indent { f.write_str("indent output") } else { f.write_str("do not indent output") } } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/namespace.rs
src/namespace.rs
//! Support for XML Namespaces //! //! The [NamespaceMap] object represents a static mapping of prefix to namespace URI. Since namespaces don't change once they are declared, this object is usually Rc-shared. use crate::value::Value; use std::collections::hash_map::Iter; use std::collections::HashMap; use std::rc::Rc; /// In some circumstances, a transformation must resolve a qualified name. /// To do this, it must have a copy of the in-scope namespaces. /// This type represents a mapping from prefix to Namespace URI. /// The "None" prefix is for the default namespace. pub struct NamespaceMap(HashMap<Option<Rc<Value>>, Rc<Value>>); // TODO: should be default namespace be represented by the empty string prefix? impl NamespaceMap { /// Create a new namespace mapping. pub fn new() -> Self { let mut map = HashMap::new(); map.insert( Some(Rc::new(Value::from("xml"))), Rc::new(Value::from("http://www.w3.org/XML/1998/namespace")), ); NamespaceMap(map) } /// Insert a mapping into the map. pub fn insert(&mut self, prefix: Option<Rc<Value>>, uri: Rc<Value>) -> Option<Rc<Value>> { self.0.insert(prefix, uri) } /// Lookup a prefix in the map, returning the namespace URI. pub fn get(&self, prefix: &Option<Rc<Value>>) -> Option<Rc<Value>> { self.0.get(prefix).cloned() } /// Iterate over mappings. Each item is a (prefix,namespace URI) pair. pub fn iter(&self) -> Iter<Option<Rc<Value>>, Rc<Value>> { self.0.iter() } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/validators/mod.rs
src/validators/mod.rs
pub mod dtd; use crate::item::{Node, NodeType}; use crate::validators::dtd::validate_dtd; #[derive(Clone)] pub enum Schema { DTD, //Will add the rest as they become available. } #[derive(Debug)] pub enum ValidationError { DocumentError(String), SchemaError(String), } pub(crate) fn validate(doc: &impl Node, schema: Schema) -> Result<(), ValidationError> { match doc.node_type() { NodeType::Document => match schema { Schema::DTD => validate_dtd(doc.clone()), }, _ => Err(ValidationError::DocumentError( "Node provided was not a document".to_string(), )), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/validators/relaxng/pattern.rs
src/validators/relaxng/pattern.rs
use std::collections::HashMap; use crate::xdmerror::Error; use crate::item::{Node, Item}; use crate::trees::smite::RNode; use crate::parser::xml::{parse as xmlparse}; use crate::transform::context::{StaticContextBuilder}; use crate::xslt::from_document; pub(crate) type Param = (String, String); #[derive(Debug)] pub(crate) enum PatternError<'a>{ NotRelaxNG, MissingName, Other(&'a str) } pub(super) fn prepare(schemadoc: &RNode) -> Result<(RNode, HashMap<String,RNode>), PatternError> { //TODO implement let patternprepper = r#"<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="2.0" xmlns:rng="http://relaxng.org/ns/structure/1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="rng" > <xsl:output method="xml" encoding="utf-8" indent="yes" /> <xsl:mode name="Step4.1" on-no-match="shallow-copy"/> <xsl:mode name="Step4.2" on-no-match="shallow-copy"/> <xsl:mode name="Step4.3" on-no-match="shallow-copy"/> <xsl:mode name="Step4.4" on-no-match="shallow-copy"/> <xsl:mode name="Step4.5" on-no-match="shallow-copy"/> <xsl:mode name="Step4.6" on-no-match="shallow-copy"/> <xsl:mode name="Step4.7" on-no-match="shallow-copy"/> <xsl:mode name="Step4.8" on-no-match="shallow-copy"/> <xsl:mode name="Step4.9" on-no-match="shallow-copy"/> <xsl:mode name="Step4.10" on-no-match="shallow-copy"/> <xsl:mode name="Step4.11" on-no-match="shallow-copy"/> <xsl:mode name="Step4.12" on-no-match="shallow-copy"/> <xsl:mode name="Step4.13" on-no-match="shallow-copy"/> <xsl:mode name="Step4.14" on-no-match="shallow-copy"/> <xsl:mode name="Step4.15" on-no-match="shallow-copy"/> <xsl:mode name="Step4.16" on-no-match="shallow-copy"/> <xsl:mode name="Step4.17" on-no-match="shallow-copy"/> <xsl:mode name="Step4.18" on-no-match="shallow-copy"/> <xsl:mode name="Step4.19" on-no-match="shallow-copy"/> <xsl:mode name="Step4.20" on-no-match="shallow-copy"/> <xsl:mode name="Step4.21" on-no-match="shallow-copy"/> <xsl:template match="/"> <xsl:variable name="s4.1" ><xsl:apply-templates mode="Step4.1" select="/" /></xsl:variable> <xsl:variable name="s4.2" ><xsl:apply-templates mode="Step4.2" select="$s4.1" /></xsl:variable> <xsl:variable name="s4.3" ><xsl:apply-templates mode="Step4.3" select="$s4.2" /></xsl:variable> <xsl:variable name="s4.4" ><xsl:apply-templates mode="Step4.4" select="$s4.3" /></xsl:variable> <xsl:variable name="s4.5" ><xsl:apply-templates mode="Step4.5" select="$s4.4" /></xsl:variable> <xsl:variable name="s4.6" ><xsl:apply-templates mode="Step4.6" select="$s4.5" /></xsl:variable> <xsl:variable name="s4.7" ><xsl:apply-templates mode="Step4.7" select="$s4.6" /></xsl:variable> <xsl:variable name="s4.8" ><xsl:apply-templates mode="Step4.8" select="$s4.7" /></xsl:variable> <xsl:variable name="s4.9" ><xsl:apply-templates mode="Step4.9" select="$s4.8" /></xsl:variable> <xsl:variable name="s4.10"><xsl:apply-templates mode="Step4.10" select="$s4.9" /></xsl:variable> <xsl:variable name="s4.11"><xsl:apply-templates mode="Step4.11" select="$s4.10" /></xsl:variable> <xsl:variable name="s4.12"><xsl:apply-templates mode="Step4.12" select="$s4.11" /></xsl:variable> <xsl:variable name="s4.13"><xsl:apply-templates mode="Step4.13" select="$s4.12" /></xsl:variable> <xsl:variable name="s4.14"><xsl:apply-templates mode="Step4.14" select="$s4.13" /></xsl:variable> <xsl:variable name="s4.15"><xsl:apply-templates mode="Step4.15" select="$s4.14" /></xsl:variable> <xsl:variable name="s4.16"><xsl:apply-templates mode="Step4.16" select="$s4.15" /></xsl:variable> <xsl:variable name="s4.17"><xsl:apply-templates mode="Step4.17" select="$s4.16" /></xsl:variable> <xsl:variable name="s4.18"><xsl:apply-templates mode="Step4.18" select="$s4.17" /></xsl:variable> <xsl:variable name="s4.19"><xsl:apply-templates mode="Step4.19" select="$s4.18" /></xsl:variable> <xsl:variable name="s4.20"><xsl:apply-templates mode="Step4.20" select="$s4.19" /></xsl:variable> <xsl:variable name="s4.21"><xsl:apply-templates mode="Step4.21" select="$s4.20" /></xsl:variable> <xsl:copy-of select="$s4.21"/> </xsl:template> <!-- 4.1 Annotations --> <xsl:template mode="Step4.1" match="*[namespace-uri() != 'http://relaxng.org/ns/structure/1.0']"/> <xsl:template mode="Step4.1" match="@*[name() != 'ns' and name() != 'type' and name() != 'href' and name() != 'combine' and name() != 'datatypeLibrary' and name() != 'name']"/> <xsl:template mode="Step4.1" match="comment()"/> <xsl:template mode="Step4.1" match="processing-instruction()"/> <!-- 4.2 Whitespace --> <xsl:template mode="Step4.2" match="text()[normalize-space(.) = '' and ancestor::*[not(self::value or self::param)]]"/> <!-- 4.3 datatypeLibrary attribute --> <xsl:template mode="Step4.3" match="rng:*[name()='data' or name()='value'][not(@datatypeLibrary)]"> <xsl:copy> <!-- Add or inherit "datatypeLibrary" attribute --> <xsl:if test="not(@datatypeLibrary)"> <xsl:attribute name="datatypeLibrary"> <xsl:choose> <!-- If nearest ancestor has the attribute, inherit it --> <xsl:when test="ancestor::rng:*[@datatypeLibrary][1]/@datatypeLibrary"> <xsl:value-of select="ancestor::*[@datatypeLibrary][1]/@datatypeLibrary"/> </xsl:when> <!-- Otherwise, default to a predefined value or remove if desired --> <xsl:otherwise>default_value</xsl:otherwise> </xsl:choose> </xsl:attribute> </xsl:if> <!-- Copy existing attributes --> <xsl:apply-templates mode="Step4.3" select="@*"/> <!-- Process child nodes --> <xsl:apply-templates mode="Step4.3" select="node()"/> </xsl:copy> </xsl:template> <!-- 4.4 type attribute of value element --> <xsl:template mode="Step4.4" match="rng:value[not(@type)]"> <xsl:copy> <xsl:attribute name="type">token</xsl:attribute> <xsl:attribute name="datatypeLibrary"/> <!-- Copy existing attributes --> <xsl:apply-templates mode="Step4.4" select="@*"/> <!-- Process child nodes --> <xsl:apply-templates mode="Step4.4" select="node()"/> </xsl:copy> </xsl:template> <!-- 4.5 href attribute --> <!-- 4.6 externalRef element --> <xsl:template mode="Step4.6" match="rng:externalRef"> <xsl:value-of select="doc(@href)"/> </xsl:template> <!-- 4.7 include element --> <!-- <xsl:template mode="Step1" match="rng:include"/> --> <!-- 4.8 name attribute of element and attribute elements --> <xsl:template mode="Step4.8" match="rng:element"> <xsl:copy> <xsl:apply-templates mode="Step4.8" select="@*[name() != 'name']"/> <rng:name><xsl:value-of select="@name"/></rng:name> <xsl:apply-templates mode="Step4.8" select="node()"/> </xsl:copy> </xsl:template> <xsl:template mode="Step4.8" match="rng:attribute"> <xsl:copy> <xsl:apply-templates mode="Step4.8" select="@*[name() != 'name']"/> <rng:name> <xsl:if test="@name and not(@ns)"> <xsl:attribute name="ns"></xsl:attribute> </xsl:if> <xsl:value-of select="@name"/> </rng:name> <xsl:apply-templates mode="Step4.8" select="node()"/> </xsl:copy> </xsl:template> <!-- 4.9 ns attribute --> <xsl:template mode="Step4.9" match="rng:value[not(@ns)] | rng:name[not(@ns)] | rng:nsname[not(@ns)] "> <xsl:copy> <xsl:attribute name="ns" select="ancestor::*[value|name|nsname][@ns]"/> <xsl:apply-templates mode="Step4.9"/> </xsl:copy> </xsl:template> <xsl:template mode="Step4.9" match="*[not(rng:name or rng:nsname or rng:value) and @ns]"> <xsl:copy> <xsl:attribute name="ns"/> <xsl:apply-templates mode="Step4.9"/> </xsl:copy> </xsl:template> <!-- 4.10 QNames --> <!-- TODO --> <!-- 4.11 div --> <xsl:template mode="Step4.11" match="rng:div"> <xsl:apply-templates mode="Step4.11"/> </xsl:template> <!-- 4.12 number of child elements --> <xsl:template mode="Step4.12" match="*[rng:define|rng:oneOrMore|rng:zeroOrMore|rng:optional|rng:list|rng:mixed][count(*) &gt; 1]"> <xsl:copy> <rng:group> <xsl:apply-templates mode="Step4.12"/> </rng:group> </xsl:copy> </xsl:template> <xsl:template mode="Step41.12" match="rng:element[count(*) &gt; 2]"> <xsl:copy> <xsl:copy select="rng:name"/> <rng:group> <xsl:apply-templates mode="Step4.12" select="*[name() != 'name']"/> </rng:group> </xsl:copy> </xsl:template> <xsl:template mode="Step4.12" match="rng:except[count(*) &gt; 1]"> <xsl:copy> <rng:choice> <xsl:apply-templates mode="Step4.12"/> </rng:choice> </xsl:copy> </xsl:template> <xsl:template mode="Step4.12" match="rng:except[count(*) &gt; 1]"> <xsl:copy> <rng:choice> <xsl:apply-templates mode="Step4.12"/> </rng:choice> </xsl:copy> </xsl:template> <xsl:template mode="Step4.12" match="rng:attribute[count(*) = 1 and name() = 'name']"> <xsl:copy> <rng:text/> </xsl:copy> </xsl:template> <xsl:template mode="Step4.12" match="[rng:choice|rng:group|rng:interleave][count(*) = 1]"> <xsl:apply-templates mode="Step4.12"/> </xsl:template> <xsl:template mode="Step4.12" match="rng:choice[count(*) &gt; 2]"> <xsl:call-template name="choices_splitter"> <xsl:with-param name="choices" select="./child::*"/> </xsl:call-template> </xsl:template> <xsl:template name="choices_splitter"> <xsl:param name="choices"/> <xsl:choose> <xsl:when test="count($choices) = 1"> <xsl:apply-templates mode="Step4.12" select="$choices"/> </xsl:when> <xsl:otherwise> <rng:choice> <xsl:apply-templates mode="Step4.12" select="$choices[position() = 1]"/> <xsl:call-template name="choices_splitter"> <xsl:with-param name="choices" select="$choices[position() &gt; 1]"/> </xsl:call-template> </rng:choice> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template mode="Step4.12" match="rng:group[count(*) &gt; 2]"> <xsl:call-template name="groups_splitter"> <xsl:with-param name="groups" select="./child::*"/> </xsl:call-template> </xsl:template> <xsl:template name="groups_splitter"> <xsl:param name="groups"/> <xsl:choose> <xsl:when test="count($groups) = 1"> <xsl:apply-templates mode="Step4.12" select="$groups"/> </xsl:when> <xsl:otherwise> <rng:group> <xsl:apply-templates mode="Step4.12" select="$groups[position() = 1]"/> <xsl:call-template name="groups_splitter"> <xsl:with-param name="groups" select="$groups[position() &gt; 1]"/> </xsl:call-template> </rng:group> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template mode="Step4.12" match="rng:interleave[count(*) &gt; 2]"> <xsl:call-template name="interleave_splitter"> <xsl:with-param name="interleaves" select="./child::*"/> </xsl:call-template> </xsl:template> <xsl:template name="interleave_splitter"> <xsl:param name="interleaves"/> <xsl:choose> <xsl:when test="count($interleaves) = 1"> <xsl:apply-templates mode="Step4.12" select="$interleaves"/> </xsl:when> <xsl:otherwise> <rng:group> <xsl:apply-templates mode="Step4.12" select="$interleaves[position() = 1]"/> <xsl:call-template name="interleave_splitter"> <xsl:with-param name="interleaves" select="$interleaves[position() &gt; 1]"/> </xsl:call-template> </rng:group> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- 4.13 mixed element --> <xsl:template match="rng:mixed" mode="Step4.13"> <rng:interleave> <xsl:apply-templates mode="Step4.13"/> <rng:text/> </rng:interleave> </xsl:template> <!-- 4.14 optional element --> <xsl:template match="rng:optional" mode="Step4.14"> <rng:choice> <xsl:apply-templates mode="Step4.14"/> <rng:empty/> </rng:choice> </xsl:template> <!-- 4.15 zeroOrMore element --> <xsl:template match="rng:zeroOrMore" mode="Step4.15"> <rng:choice> <rng:oneOrMore> <xsl:apply-templates mode="Step4.15"/> </rng:oneOrMore> <rng:empty/> </rng:choice> </xsl:template> <!-- 4.16 Constraints --> <!-- TODO --> <!-- 4.17 combine attribute --> <xsl:template mode="Step4.17" match="rng:grammar"> <xsl:copy> <xsl:for-each-group select=".//rng:define[@combine='choice']" group-by="@name"> <rng:define> <xsl:attribute name="name" select="@name"/> <rng:choice> <xsl:value-of select="current-group()"/> </rng:choice> </rng:define> </xsl:for-each-group> <xsl:for-each-group select="//rng:define[@combine='interleave']" group-by="@name"> <rng:define> <xsl:attribute name="name" select="@name"/> <rng:interleave> <xsl:value-of select="current-group()"/> </rng:interleave> </rng:define> </xsl:for-each-group> <xsl:apply-templates mode="Step4.17"/> </xsl:copy> </xsl:template> <!-- 4.18 grammar element --> <xsl:template mode="Step4.18" match="/*[not(local-name()='grammar')]"> <rng:grammar> <rng:start> <xsl:copy-of select="."/> </rng:start> <xsl:copy-of select="//rng:define"/> </rng:grammar> </xsl:template> <xsl:template mode="Step4.18" match="/rng:grammar"> <xsl:copy> <xsl:choose> <xsl:when test="rng:group/rng:start"> <xsl:copy-of select="rng:group/rng:start"/> </xsl:when> <xsl:otherwise> <rng:start> <xsl:copy-of select="*"/> </rng:start> </xsl:otherwise> </xsl:choose> <xsl:copy-of select="//rng:define"/> </xsl:copy> </xsl:template> <!-- All except root node --> <xsl:template mode="Step4.18" match="rng:grammar[parent::*]"/> <!-- 4.19. define and ref elements --> <xsl:template mode="Step4.19" match="rng:element[not(ancestor::rng:define)]"> <rng:ref> <xsl:attribute name="name"> <xsl:value-of select="./rng:name"/> </xsl:attribute> </rng:ref> </xsl:template> <xsl:template mode="Step4.19" match="/rng:grammar"> <xsl:copy> <xsl:apply-templates mode="Step4.19"/> <xsl:for-each select="//rng:element[not(ancestor::rng:define)]"> <rng:define> <xsl:attribute name="name"> <xsl:value-of select="./rng:name"/> </xsl:attribute> <xsl:copy-of select="/rng:grammar/rng:start/*"/> </rng:define> </xsl:for-each> </xsl:copy> </xsl:template> <!-- 4.20. notAllowed element --> <xsl:template mode="Step4.20" match="rng:attribute[rng:notAllowed]"><rng:notAllowed/></xsl:template> <xsl:template mode="Step4.20" match="rng:list[rng:notAllowed]"><rng:notAllowed/></xsl:template> <xsl:template mode="Step4.20" match="rng:group[rng:notAllowed]"><rng:notAllowed/></xsl:template> <xsl:template mode="Step4.20" match="rng:interleave[rng:notAllowed]"><rng:notAllowed/></xsl:template> <xsl:template mode="Step4.20" match="rng:oneOrMore[rng:notAllowed]"><rng:notAllowed/></xsl:template> <xsl:template mode="Step4.20" match="rng:choice[count(rng:notAllowed) = 2]"> <rng:notAllowed/> </xsl:template> <xsl:template mode="Step4.20" match="rng:choice[count(rng:notAllowed) != 2]"> <xsl:variable name="child1"> <xsl:apply-templates mode="Step4.20" select="*[1]"/> </xsl:variable> <xsl:variable name="child2"> <xsl:apply-templates mode="Step4.20" select="*[2]"/> </xsl:variable> <xsl:choose> <xsl:when test="name($child1)= 'notAllowed' and name($child2)= 'notAllowed'"> <rng:notAllowed/> </xsl:when> <xsl:otherwise> <rng:choice> <xsl:copy-of select="$child1"/> <xsl:copy-of select="$child2"/> </rng:choice> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template mode="Step4.20" match="rng:except[rng:notAllowed]"/> <!-- 4.21. empty element --> <xsl:template mode="Step4.21" match="rng:group"> <xsl:variable name="child1"> <xsl:apply-templates mode="Step4.21" select="*[1]"/> </xsl:variable> <xsl:variable name="child2"> <xsl:apply-templates mode="Step4.21" select="*[2]"/> </xsl:variable> <xsl:choose> <xsl:when test="name($child1)= 'empty' and name($child2)= 'empty'"> <rng:empty/> </xsl:when> <xsl:when test="name($child1)= 'empty'"> <xsl:copy-of select="$child2"/> </xsl:when> <xsl:when test="name($child2)= 'empty'"> <xsl:copy-of select="$child1"/> </xsl:when> <xsl:otherwise> <rng:group> <xsl:copy-of select="$child1"/> <xsl:copy-of select="$child2"/> </rng:group> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template mode="Step4.21" match="rng:interleave"> <xsl:variable name="child1"> <xsl:apply-templates mode="Step4.21" select="*[1]"/> </xsl:variable> <xsl:variable name="child2"> <xsl:apply-templates mode="Step4.21" select="*[2]"/> </xsl:variable> <xsl:choose> <xsl:when test="name($child1)= 'empty' and name($child2)= 'empty'"> <rng:empty/> </xsl:when> <xsl:when test="name($child1)= 'empty'"> <xsl:copy-of select="$child2"/> </xsl:when> <xsl:when test="name($child2)= 'empty'"> <xsl:copy-of select="$child1"/> </xsl:when> <xsl:otherwise> <rng:interleave> <xsl:copy-of select="$child1"/> <xsl:copy-of select="$child2"/> </rng:interleave> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template mode="Step4.21" match="rng:choice"> <xsl:variable name="child1"> <xsl:apply-templates mode="Step4.21" select="*[1]"/> </xsl:variable> <xsl:variable name="child2"> <xsl:apply-templates mode="Step4.21" select="*[2]"/> </xsl:variable> <xsl:choose> <xsl:when test="name($child1)= 'empty' and name($child2)= 'empty'"> <rng:empty/> </xsl:when> <xsl:when test="name($child2)= 'empty'"> <rng:choice> <xsl:copy-of select="$child2"/> <xsl:copy-of select="$child1"/> </rng:choice> </xsl:when> <xsl:otherwise> <rng:choice> <xsl:copy-of select="$child1"/> <xsl:copy-of select="$child2"/> </rng:choice> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>"#; let styledoc = parse_from_str(patternprepper).expect("TODO: panic message"); let mut stctxt = StaticContextBuilder::new() .message(|_| Ok(())) .parser(|_s| Ok(RNode::new_document())) .fetcher(|_url| Ok(String::new())) .build(); let c = from_document( styledoc, None, |_s| Ok(RNode::new_document()), |_| Ok(String::new()), ); match c { Ok(mut ctxt) => { ctxt.context(vec![Item::Node(schemadoc.clone())], 0); ctxt.result_document(RNode::new_document()); ctxt.populate_key_values(&mut stctxt, schemadoc.clone()).expect("TODO: panic message"); let rest = ctxt.evaluate(&mut stctxt); println!("res-{:?}",rest); } Err(e) => { println!("reserre-{:?}",e); } } /* let mut ci = schemadoc.child_iter(); let pat = ci.next().unwrap(); let mut refs = HashMap::new(); for r in ci { refs.insert(r.name().get_localname(), r); } Ok((pat, refs)) */ //println!("res-{:?}",rest); Ok((RNode::new_document(), HashMap::new())) } fn parse_from_str(s: &str) -> Result<RNode, Error> { let doc = RNode::new_document(); xmlparse(doc.clone(), s, None)?; Ok(doc) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/validators/relaxng/derive.rs
src/validators/relaxng/derive.rs
use crate::item::{Node, NodeType}; use crate::qname::QualifiedName; use crate::trees::smite::RNode; use crate::validators::relaxng::pattern::Param; use crate::value::Value; use std::collections::HashMap; use std::rc::Rc; pub(crate) fn derive(doc: &RNode, pat: RNode, refs: &HashMap<String, RNode>) -> RNode { //println!("deriv-{:?}", doc.clone().child_iter().next().unwrap()); child_deriv(pat, doc.child_iter().next().unwrap(), refs) } pub(crate) fn is_nullable(pat: RNode) -> bool { match pat.name().localname_to_string().as_str() { "empty" => true, "text" => true, "group" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); is_nullable(p1) && is_nullable(p2) } "interleave" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); is_nullable(p1) && is_nullable(p2) } "choice" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); is_nullable(p1) || is_nullable(p2) } "oneOrMore" => is_nullable(pat.first_child().unwrap()), //"element" //"attribute" //"list" //"value" //"data" //"dataExcept" //"notAllowed" //"after" _ => false, } } fn contains(nc: RNode, qn: Rc<QualifiedName>) -> bool { //println!("containsnc-{:?}", nc.clone()); match nc.name().localname_to_string().as_str() { "anyName" => true, "anyNameExcept" => { let name = nc.first_child().unwrap(); !contains(name, qn) } "NSName" => { let nsuri = nc.first_child().unwrap(); Some(nsuri.to_string()) == qn.namespace_uri_to_string() } "NSNameExcept" => { let mut c = nc.child_iter(); let ns1 = c.next().unwrap(); let n = c.next().unwrap(); (Some(ns1.to_string()) == qn.namespace_uri_to_string()) && !contains(n, qn) } "name" => { let ln1 = nc.first_child().unwrap(); let ns1 = nc.get_attribute(&QualifiedName::new(None, None, "ns")); if ns1.to_string().is_empty() { qn.namespace_uri().is_none() && (ln1.to_string() == qn.localname_to_string()) } else { (Some(ns1.to_string()) == qn.namespace_uri_to_string()) && (ln1.to_string() == qn.localname_to_string()) } } "NameClassChoice" => { let mut c = nc.child_iter(); let nc1 = c.next().unwrap(); let nc2 = c.next().unwrap(); contains(nc1, qn.clone()) || contains(nc2, qn) } _ => false, } } fn child_deriv(pat: RNode, cn: RNode, refs: &HashMap<String, RNode>) -> RNode { match cn.node_type() { NodeType::Document | NodeType::Attribute | NodeType::Comment | NodeType::ProcessingInstruction | NodeType::Reference | NodeType::Unknown | NodeType::Namespace => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), NodeType::Text => text_deriv(pat, cn.value().to_string()), NodeType::Element => { //opening deriv //println!("start_tag_open_deriv"); let mut pat1 = start_tag_open_deriv(pat, cn.name(), refs); //println!("pat1-{:?}", pat1.clone()); //println!("att_deriv"); //attsDeriv for attribute in cn.attribute_iter() { pat1 = att_deriv(attribute, pat1); } //println!("pat1-{:?}", pat1.clone()); //println!("start_tag_close_deriv"); //CloseTag pat1 = start_tag_close_deriv(pat1); //println!("pat1-{:?}", pat1.clone()); //println!("children_deriv"); //Children pat1 = children_deriv(pat1, cn.clone(), refs); //println!("pat1-{:?}", pat1.clone()); //println!("end_tag_deriv"); //end_tag_deriv pat1 = end_tag_deriv(pat1); //println!("pat1-{:?}", pat1.clone()); pat1 } } } fn start_tag_open_deriv(pat: RNode, q: Rc<QualifiedName>, refs: &HashMap<String, RNode>) -> RNode { //println!("stod-{:?}",pat.name().get_localname().as_str()); match pat.name().localname_to_string().as_str() { "ref" => { //We lookup the reference, and use that for the pattern going forward let patname = pat.get_attribute(&QualifiedName::new(None, None, "name")); let newpat = refs.get(patname.to_string().as_str()); match newpat { //TODO proper error checking None => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), Some(rn) => start_tag_open_deriv(rn.clone(), q, refs), } } "element" => { let mut pc = pat.child_iter(); let nc = pc.next().unwrap(); let p = pc.next().unwrap(); if contains(nc, q) { after( p, pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap(), ) } else { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed".to_string()))) .unwrap() } } "choice" => { let mut pc = pat.child_iter(); choice( start_tag_open_deriv(pc.next().unwrap(), q.clone(), refs), start_tag_open_deriv(pc.next().unwrap(), q.clone(), refs), ) } "interleave" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice( apply_after( |pat: RNode| { let mut i = pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "interleave"))) .unwrap(); let _ = i.push(pat); let _ = i.push(p2.clone()); i }, start_tag_open_deriv(p1.clone(), q.clone(), refs), ), apply_after( |pat: RNode| { let mut i = pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "interleave"))) .unwrap(); let _ = i.push(pat); let _ = i.push(p1.clone()); i }, start_tag_open_deriv(p2.clone(), q.clone(), refs), ), ) } "oneOrMore" => { let p1 = pat.first_child().unwrap(); apply_after( |pat: RNode| { group( pat.clone(), choice( pat.clone(), pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap(), ), ) }, start_tag_open_deriv(p1, q, refs), ) } "group" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); let x = apply_after( |pat: RNode| group(pat, p2.clone()), start_tag_open_deriv(p1.clone(), q.clone(), refs), ); if is_nullable(p1) { choice(x, start_tag_open_deriv(p2, q, refs)) } else { x } } "after" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); apply_after( |pat: RNode| after(pat, p2.clone()), start_tag_open_deriv(p1, q, refs), ) } _ => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), } } fn att_deriv(pat: RNode, att: RNode) -> RNode { match pat.name().localname_to_string().as_str() { "after" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); after(att_deriv(p1, att), p2) } "choice" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice(att_deriv(p1, att.clone()), att_deriv(p2, att)) } "group" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice( group(att_deriv(p1.clone(), att.clone()), p2.clone()), group(att_deriv(p2, att), p1), ) } "interleave" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice( interleave(att_deriv(p1.clone(), att.clone()), p2.clone()), interleave(att_deriv(p2, att), p1), ) } "oneOrMore" => { let p1 = pat.first_child().unwrap(); group( att_deriv(p1, att), choice( pat.clone(), pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap(), ), ) } "attribute" => { let (qn, av) = (att.name(), att.value()); let mut i = pat.child_iter(); let nc = i.next().unwrap(); let p1 = i.next().unwrap(); if contains(nc, qn) && value_match(p1, av.to_string()) { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap() } else { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap() } } _ => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), } } fn start_tag_close_deriv(pat: RNode) -> RNode { match pat.name().localname_to_string().as_str() { "after" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); after(start_tag_close_deriv(p1), p2) } "choice" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice(start_tag_close_deriv(p1), start_tag_close_deriv(p2)) } "group" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); group(start_tag_close_deriv(p1), start_tag_close_deriv(p2)) } "interleave" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); interleave(start_tag_close_deriv(p1), start_tag_close_deriv(p2)) } "oneOrMore" => { let p = pat.first_child().unwrap(); one_or_more(start_tag_close_deriv(p)) } "attribute" => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), _ => pat, } } fn children_deriv(pat: RNode, cn: RNode, refs: &HashMap<String, RNode>) -> RNode { match cn.clone().child_iter().count() { //match cn.len() { 0 => { //We treat self closed elements as <e></e> choice(pat.clone(), text_deriv(pat, "".to_string())) } 1 => { let n = cn.first_child().unwrap(); match n.node_type() { NodeType::Text => { let p1 = child_deriv(n.clone(), pat.clone(), refs); if whitespace(n.value().to_string()) { choice(pat, p1) } else { p1 } } _ => strip_children_deriv(pat, cn.child_iter(), refs), } } _ => strip_children_deriv(pat, cn.child_iter(), refs), } } fn end_tag_deriv(pat: RNode) -> RNode { match pat.name().localname_to_string().as_str() { "choice" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice(end_tag_deriv(p1), end_tag_deriv(p2)) } "after" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); if is_nullable(p1) { p2 } else { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap() } } _ => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), } } fn text_deriv(pat: RNode, s: String) -> RNode { match pat.name().localname_to_string().as_str() { "choice" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice(text_deriv(p1, s.clone()), text_deriv(p2, s.clone())) } "interleave" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice( interleave(text_deriv(p1.clone(), s.clone()), p2.clone()), interleave(p1, text_deriv(p2, s.clone())), ) } "group" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); let p = group(text_deriv(p1, s.clone()), p2.clone()); if is_nullable(p.clone()) { choice(p.clone(), text_deriv(p2, s)) } else { p } } "after" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); after(text_deriv(p1, s), p2) } "oneOrMore" => { let p = pat.first_child().unwrap(); group( text_deriv(p.clone(), s.clone()), choice( pat.clone(), pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap(), ), ) } "Text" => pat, "Value" => { let dtlib = pat.get_attribute(&QualifiedName::new( None, None, "datatypeLibrary", )); let dtname = pat.get_attribute(&QualifiedName::new(None, None, "type")); let v = pat.value().to_string(); if datatype_equal((dtlib, dtname), v, s) { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap() } else { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap() } } "Data" => { let mut c = pat.child_iter(); let dt = c.next().unwrap(); //let params = c.collect(); let params = vec![]; if data_type_allows(dt, params, s) { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap() } else { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap() } } "DataExcept" => { let mut c = pat.clone().child_iter(); let dt = c.next().unwrap(); //let params = c.collect(); let params = vec![]; if data_type_allows(dt, params, s.clone()) && !is_nullable(text_deriv(pat.clone(), s)) { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap() } else { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap() } } "List" => { let p = pat.first_child().unwrap(); if is_nullable(list_deriv(p, stringsplit(s))) { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "empty"))) .unwrap() } else { pat.owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap() } } _ => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), } } fn list_deriv(p: RNode, vs: Vec<String>) -> RNode { let mut vsi = vs.into_iter(); match vsi.next() { None => p, Some(p1) => list_deriv(text_deriv(p, p1), vsi.collect()), } } fn strip_children_deriv( pat: RNode, mut cn: Box<dyn Iterator<Item = RNode>>, refs: &HashMap<String, RNode>, ) -> RNode { match cn.next() { None => pat, Some(h) => strip_children_deriv( if strip(h.clone()) { pat } else { child_deriv(pat, h, refs) }, cn, refs, ), } } pub fn apply_after<F1>(f: F1, pat: RNode) -> RNode where F1: Fn(RNode) -> RNode + Clone, { match pat.name().localname_to_string().as_str() { "after" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); after(p1, f(p2)) } "choice" => { let mut pc = pat.child_iter(); let p1 = pc.next().unwrap(); let p2 = pc.next().unwrap(); choice(apply_after(f.clone(), p1), apply_after(f, p2)) } "notAllowed" => pat, _ => pat .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "notAllowed"))) .unwrap(), } } fn choice(pat1: RNode, pat2: RNode) -> RNode { /* choice :: Pattern -> Pattern -> Pattern choice p NotAllowed = p choice NotAllowed p = p choice p1 p2 = Choice p1 p2 */ match ( pat1.name().localname_to_string().as_str(), pat2.name().localname_to_string().as_str(), ) { ("notAllowed", _) => pat2, (_, "notAllowed") => pat1, (_, _) => { let mut c = pat1 .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "choice"))) .unwrap(); let _ = c.push(pat1); let _ = c.push(pat2); c } } } fn group(pat1: RNode, pat2: RNode) -> RNode { match ( pat1.name().localname_to_string().as_str(), pat2.name().localname_to_string().as_str(), ) { ("notAllowed", _) => pat1, (_, "notAllowed") => pat2, ("empty", _) => pat2, (_, "empty") => pat1, (_, _) => { let mut g = pat1 .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "group"))) .unwrap(); let _ = g.push(pat1); let _ = g.push(pat2); g } } } fn after(pat1: RNode, pat2: RNode) -> RNode { //println!("afterpat1-{:?}",pat1.name().get_localname().as_str()); //println!("afterpat2-{:?}",pat2.name().get_localname().as_str()); match ( pat1.name().localname_to_string().as_str(), pat2.name().localname_to_string().as_str(), ) { (_, "notAllowed") => pat2, ("notAllowed", _) => pat1, (_, _) => { let mut a = pat1 .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "after"))) .unwrap(); let _ = a.push(pat1); let _ = a.push(pat2); a } } } fn interleave(pat1: RNode, pat2: RNode) -> RNode { match ( pat1.name().localname_to_string().as_str(), pat2.name().localname_to_string().as_str(), ) { ("notAllowed", _) => pat1, (_, "notAllowed") => pat2, ("empty", _) => pat2, (_, "empty") => pat1, (_, _) => { let mut i = pat1 .owner_document() .new_element(Rc::new(QualifiedName::new(None, None, "interleave"))) .unwrap(); let _ = i.push(pat1); let _ = i.push(pat2); i } } } fn value_match(pat: RNode, s: String) -> bool { (is_nullable(pat.clone()) && whitespace(s.clone())) || is_nullable(text_deriv(pat, s)) } fn whitespace(s: String) -> bool { //tests whether a string is contains only whitespace. !s.contains(|c| !char::is_whitespace(c)) } fn strip(c: RNode) -> bool { match c.node_type() { NodeType::Text => whitespace(c.value().to_string()), _ => false, } } fn one_or_more(pat: RNode) -> RNode { match pat.name().localname_to_string().as_str() { "notAllowed" => pat, _ => { let mut o = RNode::new_document() .new_element(Rc::new(QualifiedName::new(None, None, "oneOrMore"))) .unwrap(); let _ = o.push(pat); o } } } fn data_type_allows(dt: RNode, _params: Vec<Param>, _s: String) -> bool { let _datatypens = dt.name().namespace_uri(); let datatype = dt.name().localname_to_string(); match datatype.as_str() { "string" => true, "token" => true, _ => false, } } fn datatype_equal((_d, s): (Rc<Value>, Rc<Value>), s1: String, s2: String) -> bool { match s.as_ref() { Value::String(_) => s1 == s2, Value::Token => normalize_whitespace(s1) == normalize_whitespace(s2), _ => false, } /* match s.as_str() { "string" => {s1 == s2}, "token" => { normalize_whitespace(s1) == normalize_whitespace(s2) } _ => false } */ } fn normalize_whitespace(s: String) -> String { s.trim() .split(' ') .filter(|s| !s.is_empty()) .collect::<Vec<_>>() .join(" ") } fn stringsplit(s: String) -> Vec<String> { let t = s.split(' ').map(|u| u.to_string()).collect(); t }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/validators/relaxng/mod.rs
src/validators/relaxng/mod.rs
mod derive; mod pattern; use crate::trees::smite::RNode; use crate::validators::relaxng::derive::{derive, is_nullable}; use crate::validators::ValidationError; pub fn validate_relaxng(doc: &RNode, schema: &RNode) -> Result<(), ValidationError> { let schemapattern = pattern::prepare(schema); match schemapattern { Err(_) => Err(ValidationError::SchemaError( "Pattern Prep Error".to_string(), )), Ok((pat, refs)) => { if is_nullable(derive(doc, pat, &refs)) { Ok(()) } else { Err(ValidationError::DocumentError("Some Error".to_string())) } } } } //TODO: //Patterns split in two //Pattern and elementrefs hashmap //adjust validator to do lookups against hashmap when it encounters refs
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/validators/dtd/derive.rs
src/validators/dtd/derive.rs
use crate::item::NodeType; use crate::qname::QualifiedName; use crate::Node; use crate::xmldecl::{DTDPattern, DTD}; pub(crate) fn is_nullable(pat: DTDPattern) -> bool { match pat { DTDPattern::Empty => true, DTDPattern::Text => true, DTDPattern::Any => true, //TODO Check DTDPattern::Group(pat1, pat2) => is_nullable(*pat1) && is_nullable(*pat2), DTDPattern::Interleave(pat1, pat2) => is_nullable(*pat1) && is_nullable(*pat2), DTDPattern::Choice(pat1, pat2) => is_nullable(*pat1) || is_nullable(*pat2), DTDPattern::OneOrMore(pat1) => is_nullable(*pat1), _ => false, } } fn contains(nc: QualifiedName, qn: QualifiedName) -> bool { nc.prefix() == qn.prefix() && nc.localname() == qn.localname() } fn after(pat1: DTDPattern, pat2: DTDPattern) -> DTDPattern { if pat1 == DTDPattern::NotAllowed || pat2 == DTDPattern::NotAllowed { DTDPattern::NotAllowed } else { DTDPattern::After(Box::new(pat1), Box::new(pat2)) } } fn choice(pat1: DTDPattern, pat2: DTDPattern) -> DTDPattern { match (pat1, pat2) { (p, DTDPattern::NotAllowed) => p, (DTDPattern::NotAllowed, p) => p, (p1, p2) => DTDPattern::Choice(Box::new(p1), Box::new(p2)), } } fn interleave(pat1: DTDPattern, pat2: DTDPattern) -> DTDPattern { match (pat1, pat2) { (DTDPattern::NotAllowed, _) => DTDPattern::NotAllowed, (_, DTDPattern::NotAllowed) => DTDPattern::NotAllowed, (DTDPattern::Empty, p2) => p2, (p1, DTDPattern::Empty) => p1, (DTDPattern::Any, p2) => p2, //TODO CHECK (p1, DTDPattern::Any) => p1, //TODO CHECK (p1, p2) => DTDPattern::Interleave(Box::new(p1), Box::new(p2)), } } fn group(pat1: DTDPattern, pat2: DTDPattern) -> DTDPattern { match (pat1, pat2) { (DTDPattern::NotAllowed, _) => DTDPattern::NotAllowed, (_, DTDPattern::NotAllowed) => DTDPattern::NotAllowed, (DTDPattern::Empty, p2) => p2, (p1, DTDPattern::Empty) => p1, (p1, p2) => DTDPattern::Group(Box::new(p1), Box::new(p2)), } } pub fn apply_after<F1>(pat: DTDPattern, f: F1) -> DTDPattern where F1: Fn(DTDPattern) -> DTDPattern + Clone, { match pat { DTDPattern::After(pat1, pat2) => after(*pat1, f(*pat2)), DTDPattern::Choice(pat1, pat2) => { choice(apply_after(*pat1, f.clone()), apply_after(*pat2, f)) } _ => DTDPattern::NotAllowed, } } fn value_match(pat: DTDPattern, s: String) -> bool { (is_nullable(pat.clone()) && whitespace(s.clone())) || is_nullable(text_deriv(pat, s)) } fn text_deriv(pat: DTDPattern, s: String) -> DTDPattern { match pat { DTDPattern::Choice(pat1, pat2) => { choice(text_deriv(*pat1, s.clone()), text_deriv(*pat2, s)) } DTDPattern::Interleave(pat1, pat2) => choice( interleave(text_deriv(*pat1.clone(), s.clone()), *pat2.clone()), interleave(*pat1, text_deriv(*pat2, s.clone())), ), DTDPattern::Group(pat1, pat2) => { let p = group(text_deriv(*pat1, s.clone()), *pat2.clone()); if is_nullable(p.clone()) { choice(p, text_deriv(*pat2, s)) } else { p } } DTDPattern::After(pat1, pat2) => after(text_deriv(*pat1, s), *pat2), DTDPattern::OneOrMore(pat1) => group( text_deriv(*pat1.clone(), s), choice(*pat1, DTDPattern::Empty), ), DTDPattern::List(pat1) => { if is_nullable(list_deriv( *pat1, s.split(' ').map(|st| st.to_string()).collect(), )) { DTDPattern::Empty } else { DTDPattern::NotAllowed } } DTDPattern::Value(val) => { if s == val { DTDPattern::Empty } else { DTDPattern::NotAllowed } } //textDeriv cx1 (Value dt value cx2) s = if datatypeEqual dt value cx2 s cx1 then Empty else NotAllowed DTDPattern::Text => pat, DTDPattern::Any => pat, DTDPattern::Empty => DTDPattern::NotAllowed, DTDPattern::NotAllowed => DTDPattern::NotAllowed, DTDPattern::Attribute(_, _) => DTDPattern::NotAllowed, DTDPattern::Element(_, _) => DTDPattern::NotAllowed, DTDPattern::Ref(_) => DTDPattern::NotAllowed, } } fn list_deriv(p: DTDPattern, vs: Vec<String>) -> DTDPattern { let mut vsi = vs.into_iter(); match vsi.next() { None => p, Some(p1) => list_deriv(text_deriv(p, p1), vsi.collect()), } } pub(crate) fn child_deriv(pat: DTDPattern, n: impl Node, dtd: DTD) -> DTDPattern { //println!("child_deriv"); //println!(" {:?}", &pat); //println!(" {:?}", &n); match n.node_type() { NodeType::Document => DTDPattern::NotAllowed, NodeType::Attribute => DTDPattern::NotAllowed, NodeType::Comment => DTDPattern::NotAllowed, NodeType::ProcessingInstruction => DTDPattern::NotAllowed, NodeType::Reference => DTDPattern::NotAllowed, NodeType::Namespace => DTDPattern::NotAllowed, NodeType::Unknown => DTDPattern::NotAllowed, NodeType::Text => text_deriv(pat, n.to_string()), NodeType::Element => { let mut pat1 = start_tag_open_deriv(pat, n.name().as_ref().clone(), dtd.clone()); //at this stage, we check if the DTD is for DTDPattern::Any. If it is present, we build a pattern //based on the child nodes, so that they are all validated individually. match pat1.clone() { DTDPattern::After(a, p) => { match *a { DTDPattern::Any => { let mut newpat = DTDPattern::Empty; let mut children = n .child_iter() .filter(|node| { node.node_type() != NodeType::ProcessingInstruction && node.node_type() != NodeType::Comment && !(node.node_type() == NodeType::Text && node.value().to_string() == *"") }) .collect::<Vec<_>>(); //todo POP VECTOR UNTIL EMPTY children.reverse(); for c in children { match c.node_type() { NodeType::Element => { newpat = DTDPattern::Group( Box::new(DTDPattern::Ref(c.name().as_ref().clone())), Box::new(newpat), ) } NodeType::Text => { newpat = DTDPattern::Group( Box::new(DTDPattern::Text), Box::new(newpat), ) } _ => {} } } pat1 = DTDPattern::After(Box::new(newpat), p) } DTDPattern::Group(an, p1) => { if *an == DTDPattern::Any { let mut newpat = DTDPattern::Empty; let mut children = n .child_iter() .filter(|node| { node.node_type() != NodeType::ProcessingInstruction && node.node_type() != NodeType::Comment && !(node.node_type() == NodeType::Text && node.value().to_string() == *"") }) .collect::<Vec<_>>(); //todo POP VECTOR UNTIL EMPTY children.reverse(); for c in children { match c.node_type() { NodeType::Element => { newpat = DTDPattern::Group( Box::new(DTDPattern::Ref( c.name().as_ref().clone(), )), Box::new(newpat), ) } NodeType::Text => { newpat = DTDPattern::Group( Box::new(DTDPattern::Text), Box::new(newpat), ) } _ => {} } } pat1 = DTDPattern::After( Box::from(DTDPattern::Group(Box::new(newpat), p1)), p, ) } } _ => {} } } _ => {} } for attribute in n.attribute_iter() { pat1 = att_deriv(pat1, attribute) } pat1 = start_tag_close_deriv(pat1); pat1 = children_deriv(pat1, n, dtd); pat1 = end_tag_deriv(pat1); pat1 } } } fn start_tag_open_deriv(pat: DTDPattern, qn: QualifiedName, dtd: DTD) -> DTDPattern { //println!("start_tag_open_deriv"); //println!(" {:?}", &pat); //println!(" {:?}", &qn); match pat { DTDPattern::Ref(q) => match dtd.patterns.get(&q) { None => DTDPattern::NotAllowed, Some(p1) => start_tag_open_deriv(p1.clone(), qn, dtd), }, DTDPattern::Any => after(pat, DTDPattern::Empty), DTDPattern::Element(nc, pat1) => { if contains(nc, qn) { //TODO THE ERROR MIGHT BE HERE???? after(*pat1, DTDPattern::Empty) } else { DTDPattern::NotAllowed } } DTDPattern::Choice(pat1, pat2) => choice( start_tag_open_deriv(*pat1, qn.clone(), dtd.clone()), start_tag_open_deriv(*pat2, qn, dtd), ), DTDPattern::Interleave(pat1, pat2) => choice( apply_after( start_tag_open_deriv(*pat1.clone(), qn.clone(), dtd.clone()), |p: DTDPattern| DTDPattern::Interleave(Box::new(p), pat2.clone()), ), apply_after( start_tag_open_deriv(*pat2.clone(), qn.clone(), dtd), |p: DTDPattern| DTDPattern::Interleave(Box::new(p), pat1.clone()), ), ), DTDPattern::Group(pat1, pat2) => { let x = apply_after( start_tag_open_deriv(*pat1.clone(), qn.clone(), dtd.clone()), |pat| group(pat, *pat2.clone()), ); if is_nullable(*pat1) { choice(x, start_tag_open_deriv(*pat2, qn, dtd)) } else { x } } DTDPattern::OneOrMore(pat1) => { apply_after(start_tag_open_deriv(*pat1.clone(), qn, dtd), |pt| { group( pt, choice(DTDPattern::OneOrMore(pat1.clone()), DTDPattern::Empty), ) }) } DTDPattern::After(pat1, pat2) => apply_after(start_tag_open_deriv(*pat1, qn, dtd), |p| { after(p, *pat2.clone()) }), DTDPattern::Value(_) => DTDPattern::NotAllowed, DTDPattern::Empty => DTDPattern::NotAllowed, DTDPattern::NotAllowed => DTDPattern::NotAllowed, DTDPattern::Text => DTDPattern::NotAllowed, DTDPattern::List(_) => DTDPattern::NotAllowed, DTDPattern::Attribute(_, _) => DTDPattern::NotAllowed, } } fn att_deriv(pat: DTDPattern, att: impl Node) -> DTDPattern { //println!("att_deriv"); //println!(" {:?}", &pat); //println!(" {:?}", &att); match pat { DTDPattern::Choice(pat1, pat2) => { choice(att_deriv(*pat1, att.clone()), att_deriv(*pat2, att.clone())) } DTDPattern::Interleave(pat1, pat2) => choice( interleave(att_deriv(*pat1.clone(), att.clone()), *pat2.clone()), interleave(att_deriv(*pat2.clone(), att), *pat1), ), DTDPattern::Group(pat1, pat2) => choice( group(att_deriv(*pat1.clone(), att.clone()), *pat2.clone()), group(att_deriv(*pat2.clone(), att.clone()), *pat1), ), DTDPattern::OneOrMore(pat1) => group( att_deriv(*pat1.clone(), att), choice(*pat1, DTDPattern::Empty), ), DTDPattern::After(pat1, pat2) => after(att_deriv(*pat1, att), *pat2), DTDPattern::Attribute(nc, pat1) => { if contains(nc, att.name().as_ref().clone()) && value_match(*pat1, att.value().to_string()) { DTDPattern::Empty } else { DTDPattern::NotAllowed } } DTDPattern::Any => DTDPattern::NotAllowed, DTDPattern::Value(_) => DTDPattern::NotAllowed, DTDPattern::Empty => DTDPattern::NotAllowed, DTDPattern::NotAllowed => DTDPattern::NotAllowed, DTDPattern::Text => DTDPattern::NotAllowed, DTDPattern::List(_) => DTDPattern::NotAllowed, DTDPattern::Element(_, _) => DTDPattern::NotAllowed, DTDPattern::Ref(_) => DTDPattern::NotAllowed, } } fn start_tag_close_deriv(pat: DTDPattern) -> DTDPattern { //println!("start_tag_close_deriv"); //println!(" {:?}", &pat); match pat { DTDPattern::Choice(pat1, pat2) => { choice(start_tag_close_deriv(*pat1), start_tag_close_deriv(*pat2)) } DTDPattern::Interleave(pat1, pat2) => { interleave(start_tag_close_deriv(*pat1), start_tag_close_deriv(*pat2)) } DTDPattern::Group(pat1, pat2) => { group(start_tag_close_deriv(*pat1), start_tag_close_deriv(*pat2)) } DTDPattern::OneOrMore(pat1) => match start_tag_close_deriv(*pat1.clone()) { DTDPattern::NotAllowed => DTDPattern::NotAllowed, _ => DTDPattern::OneOrMore(Box::new(start_tag_close_deriv(*pat1))), }, DTDPattern::After(pat1, pat2) => after(start_tag_close_deriv(*pat1), *pat2), DTDPattern::Attribute(_, _) => DTDPattern::NotAllowed, DTDPattern::Any => pat, DTDPattern::Value(_) => pat, DTDPattern::Empty => pat, DTDPattern::NotAllowed => pat, DTDPattern::Text => pat, DTDPattern::List(_) => pat, DTDPattern::Element(_, _) => pat, DTDPattern::Ref(_) => pat, } } fn children_deriv(pat: DTDPattern, cn: impl Node, dtd: DTD) -> DTDPattern { //println!("children_deriv"); //println!(" {:?}", &pat); //println!(" {:?}", cn.child_iter().collect::<Vec<_>>()); //Filter out comments, processing instructions, empty text nodes let children: Vec<_> = cn .child_iter() .filter(|node| { node.node_type() != NodeType::ProcessingInstruction && node.node_type() != NodeType::Comment && !(node.node_type() == NodeType::Text && whitespace(node.value().to_string())) }) .collect(); //println!("children_deriv_children-{:?}", &children); let mut pat1 = pat; match children.len() { 0 => { pat1 = choice(pat1.clone(), text_deriv(pat1, "".to_string())); } _ => { let mut c = children.into_iter().peekable(); while let Some(n) = c.next() { if c.peek().is_none() { match n.node_type() { NodeType::Text => { let p1 = child_deriv(pat1.clone(), n.clone(), dtd.clone()); pat1 = if whitespace(n.value().to_string()) { choice(pat1.clone(), p1) } else { p1 } } _ => pat1 = strip_children_deriv(pat1.clone(), vec![n], dtd.clone()), } } else if !strip(n.clone()) { pat1 = child_deriv(pat1, n.clone(), dtd.clone()) } } } } pat1 } fn end_tag_deriv(pat: DTDPattern) -> DTDPattern { //println!("end_tag_deriv"); //println!(" {:?}", &pat); match pat { DTDPattern::Choice(pat1, pat2) => choice(end_tag_deriv(*pat1), end_tag_deriv(*pat2)), DTDPattern::After(pat1, pat2) => { if is_nullable(*pat1) { *pat2 } else { DTDPattern::NotAllowed } } DTDPattern::Any => pat, _ => DTDPattern::NotAllowed, } } fn strip_children_deriv<T>(pat: DTDPattern, cnodes: Vec<T>, dtd: DTD) -> DTDPattern where T: Node, { let mut ci = cnodes.iter(); match ci.next() { None => pat, Some(h) => { strip_children_deriv( if strip(h.clone()) { pat } else { child_deriv(pat, h.clone(), dtd.clone()) }, ci.cloned().collect(), //ci.map(|c| c.clone()).collect(), dtd, ) } } } fn whitespace(s: String) -> bool { s.chars().all(char::is_whitespace) } fn strip(c: impl Node) -> bool { match c.node_type() { NodeType::Text => whitespace(c.value().to_string()), _ => false, } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/validators/dtd/mod.rs
src/validators/dtd/mod.rs
mod derive; use crate::item::NodeType; use crate::validators::dtd::derive::{child_deriv, is_nullable}; use crate::validators::ValidationError; use crate::Node; pub(crate) fn validate_dtd(doc: impl Node) -> Result<(), ValidationError> { match doc.node_type() { NodeType::Document => { match doc.get_dtd() { None => Err(ValidationError::DocumentError( "No DTD Information on the document".to_string(), )), Some(dtd) => { match &dtd.name { None => Err(ValidationError::DocumentError( "Document name not found in DTD".to_string(), )), Some(n) => { match dtd.patterns.get(n) { None => Err(ValidationError::DocumentError( "Element Declaration not found.".to_string(), )), Some(pat) => { //println!("pat-{:?}", pat); //for pt in &dtd.patterns { // println!("{:?}", pt) //} match is_nullable(child_deriv( pat.clone(), doc.child_iter() .filter(|node| { node.node_type() != NodeType::ProcessingInstruction && node.node_type() != NodeType::Comment && !(node.node_type() == NodeType::Text && node.value().to_string() == *"") }) .next() .unwrap(), dtd, )) { true => Ok(()), false => { Err(ValidationError::SchemaError("Invalid".to_string())) } } } } } } } } } _ => Err(ValidationError::DocumentError( "Node provided was not a document".to_string(), )), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/misc.rs
src/transform/misc.rs
//! Miscellaneous support functions. use crate::item::{Node, Sequence, SequenceTrait}; use crate::qname::QualifiedName; use crate::transform::context::{Context, StaticContext}; use crate::transform::Transform; use crate::xdmerror::Error; use crate::ErrorKind; use url::Url; /// XSLT current function. pub fn current<N: Node>(ctxt: &Context<N>) -> Result<Sequence<N>, Error> { if ctxt.previous_context.is_some() { Ok(vec![ctxt.previous_context.as_ref().unwrap().clone()]) } else { Err(Error::new( ErrorKind::DynamicAbsent, String::from("current item missing"), )) } } /// Emits a message from the stylesheet. /// The transform is evaluated to create the content of the message. pub(crate) fn message< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, body: &Transform<N>, _sel: &Option<Box<Transform<N>>>, // select expression, an alternative to body _e: &Transform<N>, // error code t: &Transform<N>, // terminate ) -> Result<Sequence<N>, Error> { let msg = ctxt.dispatch(stctxt, body)?.to_string(); if let Some(f) = &mut stctxt.message { f(msg.as_str())? } match ctxt.dispatch(stctxt, t)?.to_string().trim() { "yes" => { // TODO: return error code Err(Error { kind: ErrorKind::Terminated, message: msg, code: Some(QualifiedName::new( Some(String::from("http://www.w3.org/2005/xqt-errors")), None, String::from("XTMM9000"), )), }) } _ => Ok(vec![]), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/variables.rs
src/transform/variables.rs
//! Support for variables. use crate::item::{Node, Sequence}; use crate::transform::context::{Context, ContextBuilder, StaticContext}; use crate::transform::Transform; use crate::xdmerror::{Error, ErrorKind}; use url::Url; /// Declare a variable in a new scope and then evaluate the given transformation. /// Returns the result of the transformation. pub fn declare_variable< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, name: String, value: &Transform<N>, f: &Transform<N>, ) -> Result<Sequence<N>, Error> { ContextBuilder::from(ctxt) .variable(name, ctxt.dispatch(stctxt, value)?) .build() .dispatch(stctxt, f) } pub fn reference_variable<N: Node>(ctxt: &Context<N>, name: &String) -> Result<Sequence<N>, Error> { match ctxt.vars.get(name) { Some(u) => match u.last() { Some(t) => Ok(t.clone()), None => Err(Error::new( ErrorKind::Unknown, format!("variable \"{}\" is no longer in scope", name), )), }, None => Err(Error::new( ErrorKind::Unknown, format!("unknown variable \"{}\"", name), )), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/datetime.rs
src/transform/datetime.rs
//! These functions are for features defined in XPath Functions 1.0 and 2.0. use std::rc::Rc; #[allow(unused_imports)] use chrono::{DateTime, Datelike, FixedOffset, Local, Timelike}; use url::Url; use crate::item::{Item, Node, Sequence, SequenceTrait}; use crate::parser::datetime::parse as picture_parse; use crate::transform::context::{Context, StaticContext}; use crate::transform::Transform; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; /// XPath current-date-time function. pub fn current_date_time<N: Node>(_ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::DateTime(Local::now())))]) } /// XPath current-date function. pub fn current_date<N: Node>(_ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::Date( Local::now().date_naive(), )))]) } /// XPath current-time function. pub fn current_time<N: Node>(_ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::Time(Local::now())))]) } /// XPath format-date-time function. /// NB. language, calendar, and place are not implemented. pub fn format_date_time< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, value: &Transform<N>, picture: &Transform<N>, _language: &Option<Box<Transform<N>>>, _calendar: &Option<Box<Transform<N>>>, _place: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { let dt = ctxt.dispatch(stctxt, value)?; let pic = picture_parse::<N>(&ctxt.dispatch(stctxt, picture)?.to_string())?; match dt.len() { 0 => Ok(vec![]), // Empty value returns empty sequence 1 => { match &dt[0] { Item::Value(d) => match **d { Value::DateTime(i) => Ok(vec![Item::Value(Rc::new(Value::String( i.format(&pic).to_string(), )))]), Value::String(ref s) => { // Try and coerce into a DateTime value match DateTime::<FixedOffset>::parse_from_rfc3339(s.as_str()) { Ok(j) => Ok(vec![Item::Value(Rc::new(Value::String( j.format(&pic).to_string(), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("unable to determine date value"), )), } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a dateTime value"), )), }, _ => Err(Error::new( ErrorKind::TypeError, String::from("not a dateTime value"), )), } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } /// XPath format-date function. /// NB. language, calendar, and place are not implemented. pub fn format_date< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, value: &Transform<N>, picture: &Transform<N>, _language: &Option<Box<Transform<N>>>, _calendar: &Option<Box<Transform<N>>>, _place: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { let dt = ctxt.dispatch(stctxt, value)?; let pic = picture_parse::<N>(&ctxt.dispatch(stctxt, picture)?.to_string())?; match dt.len() { 0 => Ok(vec![]), // Empty value returns empty sequence 1 => { match &dt[0] { Item::Value(d) => match **d { Value::Date(i) => Ok(vec![Item::Value(Rc::new(Value::String( i.format(&pic).to_string(), )))]), Value::String(ref s) => { // Try and coerce into a DateTime value let a = format!("{}T00:00:00Z", s); match DateTime::<FixedOffset>::parse_from_rfc3339(a.as_str()) { Ok(j) => Ok(vec![Item::Value(Rc::new(Value::String( j.date_naive().format(&pic).to_string(), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("unable to determine date value"), )), } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a date value"), )), }, _ => Err(Error::new( ErrorKind::TypeError, String::from("not a date value"), )), } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } /// XPath format-time function. /// NB. language, calendar, and place are not implemented. pub fn format_time< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, value: &Transform<N>, picture: &Transform<N>, _language: &Option<Box<Transform<N>>>, _calendar: &Option<Box<Transform<N>>>, _place: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { let dt = ctxt.dispatch(stctxt, value)?; let pic = picture_parse::<N>(&ctxt.dispatch(stctxt, picture)?.to_string())?; match dt.len() { 0 => Ok(vec![]), // Empty value returns empty sequence 1 => { match &dt[0] { Item::Value(d) => match **d { Value::Time(i) => Ok(vec![Item::Value(Rc::new(Value::String( i.format(&pic).to_string(), )))]), Value::String(ref s) => { // Try and coerce into a DateTime value let a = format!("1900-01-01T{}Z", s); match DateTime::<FixedOffset>::parse_from_rfc3339(a.as_str()) { Ok(j) => Ok(vec![Item::Value(Rc::new(Value::String( j.format(&pic).to_string(), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("unable to determine time value"), )), } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a time value"), )), }, _ => Err(Error::new( ErrorKind::TypeError, String::from("not a time value"), )), } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/booleans.rs
src/transform/booleans.rs
//! These functions are for features defined in XPath Functions 1.0 and 2.0. use std::rc::Rc; use url::Url; use crate::item::{Item, Node, Sequence, SequenceTrait}; use crate::transform::context::{Context, StaticContext}; use crate::transform::Transform; use crate::value::Value; use crate::xdmerror::Error; /// XPath boolean function. pub fn boolean< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, b: &Transform<N>, ) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::Boolean( ctxt.dispatch(stctxt, b)?.to_bool(), )))]) } /// XPath not function. pub fn not< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, n: &Transform<N>, ) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::Boolean( !ctxt.dispatch(stctxt, n)?.to_bool(), )))]) } /// XPath true function. pub fn tr_true<N: Node>(_ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::Boolean(true)))]) } /// XPath false function. pub fn tr_false<N: Node>(_ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::Boolean(false)))]) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/callable.rs
src/transform/callable.rs
//! # Callables //! Sequence constructors that are invoked by stylesheet code, such as named templates and functions. //! The difference between them is that named templates have named parameters, //! whereas functions have positional parameters. // TODO: tunneling parameters use crate::item::Node; use crate::qname::QualifiedName; use crate::transform::context::StaticContext; use crate::transform::{NamespaceMap, Transform}; use crate::{Context, Error, ErrorKind, Sequence}; use std::collections::HashMap; use url::Url; #[derive(Clone, Debug)] pub struct Callable<N: Node> { pub(crate) body: Transform<N>, pub(crate) parameters: FormalParameters<N>, // TODO: return type } impl<N: Node> Callable<N> { pub fn new(body: Transform<N>, parameters: FormalParameters<N>) -> Self { Callable { body, parameters } } } // TODO: parameter type ("as" attribute) #[derive(Clone, Debug)] pub enum FormalParameters<N: Node> { Named(Vec<(QualifiedName, Option<Transform<N>>)>), // parameter name, default value Positional(Vec<QualifiedName>), } #[derive(Clone, Debug)] pub enum ActualParameters<N: Node> { Named(Vec<(QualifiedName, Transform<N>)>), // parameter name, value Positional(Vec<Transform<N>>), } /// Invoke a callable component pub(crate) fn invoke< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, qn: &QualifiedName, a: &ActualParameters<N>, ns: &NamespaceMap, ) -> Result<Sequence<N>, Error> { let mut qnr = qn.clone(); qnr.resolve(|p| { ns.get(&p).map_or( Err(Error::new( ErrorKind::DynamicAbsent, "no namespace for prefix", )), |r| Ok(r.clone()), ) })?; match ctxt.callables.get(&qnr) { Some(t) => { match &t.parameters { FormalParameters::Named(v) => { let mut newctxt = ctxt.clone(); // Put the actual parameters in a HashMap for easy access let mut actuals = HashMap::new(); if let ActualParameters::Named(av) = a { av.iter().try_for_each(|(a_name, a_value)| { actuals.insert(a_name, ctxt.dispatch(stctxt, a_value)?); Ok(()) })? } else { return Err(Error::new(ErrorKind::TypeError, "argument mismatch")); } // Match each actual parameter to a formal parameter by name v.iter().try_for_each(|(name, dflt)| { match actuals.get(name) { Some(val) => { newctxt.var_push(name.to_string(), val.clone()); Ok(()) } None => { // Use default value if let Some(d) = dflt { newctxt.var_push(name.to_string(), ctxt.dispatch(stctxt, d)?) } else { newctxt.var_push(name.to_string(), vec![]) } Ok(()) } } })?; newctxt.dispatch(stctxt, &t.body) } FormalParameters::Positional(v) => { if let ActualParameters::Positional(av) = a { // Make sure number of parameters are equal, then set up variables by position if v.len() == av.len() { let mut newctxt = ctxt.clone(); v.iter().zip(av.iter()).try_for_each(|(qn, t)| { newctxt.var_push(qn.to_string(), ctxt.dispatch(stctxt, t)?); Ok(()) })?; newctxt.dispatch(stctxt, &t.body) } else { Err(Error::new(ErrorKind::TypeError, "argument mismatch")) } } else { Err(Error::new(ErrorKind::TypeError, "argument mismatch")) } } } } None => Err(Error::new( ErrorKind::Unknown, format!("unknown callable \"{}\"", qn), )), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/template.rs
src/transform/template.rs
//! # Templates use std::cmp::Ordering; use std::fmt::{Debug, Formatter}; use std::rc::Rc; use url::Url; use crate::qname::QualifiedName; use crate::transform::context::{Context, ContextBuilder, StaticContext}; use crate::transform::{do_sort, Order, Transform}; use crate::xdmerror::Error; use crate::{Node, Pattern, Sequence}; #[derive(Clone)] pub struct Template<N: Node> { pub(crate) pattern: Pattern<N>, pub(crate) body: Transform<N>, pub(crate) priority: Option<f64>, pub(crate) import: Vec<usize>, pub(crate) document_order: Option<usize>, pub(crate) mode: Option<Rc<QualifiedName>>, } impl<N: Node> Template<N> { pub fn new( pattern: Pattern<N>, body: Transform<N>, priority: Option<f64>, import: Vec<usize>, document_order: Option<usize>, mode: Option<Rc<QualifiedName>>, ) -> Self { Template { pattern, body, priority, import, document_order, mode, } } } /// Two templates are equal if they have the same priority, import precedence, and mode. impl<N: Node> PartialEq for Template<N> { fn eq(&self, other: &Self) -> bool { self.priority == other.priority && self.import == other.import && self.mode == other.mode } } impl<N: Node> Eq for Template<N> {} impl<N: Node> PartialOrd for Template<N> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<N: Node> Ord for Template<N> { fn cmp(&self, other: &Self) -> Ordering { self.priority.map_or_else( || { other .priority .map_or_else(|| Ordering::Equal, |_| Ordering::Greater) }, |s| { other.priority.map_or_else( || Ordering::Less, |t| { if s < t { Ordering::Greater } else { Ordering::Less } }, ) }, ) } } impl<N: Node> Debug for Template<N> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "template match \"{:?}\" priority {:?} mode {:?}", self.pattern, self.priority, self.mode ) } } /// Apply templates to the select expression. pub(crate) fn apply_templates< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, m: &Option<Rc<QualifiedName>>, o: &Vec<(Order, Transform<N>)>, // sort keys ) -> Result<Sequence<N>, Error> { // s is the select expression. Evaluate it, and then iterate over its items. // Each iteration becomes an item in the result sequence. let mut seq = ctxt.dispatch(stctxt, s)?; do_sort(&mut seq, o, ctxt, stctxt)?; seq.iter().try_fold(vec![], |mut result, i| { let templates = ctxt.find_templates(stctxt, i, m)?; // If there are two or more templates with the same priority and import level, then take the one that has the higher document order let matching = if templates.len() > 1 { if templates[0].priority == templates[1].priority && templates[0].import.len() == templates[1].import.len() { let mut candidates: Vec<Rc<Template<N>>> = templates .iter() .take_while(|t| { t.priority == templates[0].priority && t.import.len() == templates[0].import.len() }) .cloned() .collect(); candidates.sort_unstable_by(|a, b| { a.document_order.map_or(Ordering::Greater, |v| { b.document_order.map_or(Ordering::Less, |u| v.cmp(&u)) }) }); candidates.last().unwrap().clone() } else { templates[0].clone() } } else { templates[0].clone() }; // Create a new context using the current templates, then evaluate the highest priority and highest import precedence let mut u = ContextBuilder::from(ctxt) .context(vec![i.clone()]) .previous_context(Some(i.clone())) .current_templates(templates) .build() .dispatch(stctxt, &matching.body)?; result.append(&mut u); Ok(result) }) } /// Apply template with a higher import precedence. pub(crate) fn apply_imports< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, ) -> Result<Sequence<N>, Error> { // Find the template with the next highest level within the same import tree // current_templates[0] is the currently matching template let cur = &(ctxt.current_templates[0]); let next: Vec<Rc<Template<N>>> = ctxt .current_templates .iter() .skip(1) .skip_while(|t| t.import.len() == cur.import.len()) // import level is the same (iow, different priority templates in the same import level) .cloned() .collect(); if !next.is_empty() { ContextBuilder::from(ctxt) .current_templates(next.clone()) .build() .dispatch(stctxt, &next[0].body) } else { Ok(vec![]) } } /// Apply the next template that matches. pub(crate) fn next_match< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, ) -> Result<Sequence<N>, Error> { if ctxt.current_templates.len() > 2 { ContextBuilder::from(ctxt) .current_templates(ctxt.current_templates.iter().skip(1).cloned().collect()) .build() .dispatch(stctxt, &ctxt.current_templates[1].body) } else { Ok(vec![]) } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/functions.rs
src/transform/functions.rs
//! These functions are for features defined in XPath Functions 1.0 and 2.0. use pkg_version::*; use std::rc::Rc; use url::Url; use crate::item::{Item, Node, Sequence}; use crate::qname::QualifiedName; use crate::transform::context::{Context, StaticContext}; use crate::transform::{NamespaceMap, Transform}; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use crate::SequenceTrait; /// XPath position function. pub fn position<N: Node>(ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::from(ctxt.i as i64 + 1)))]) } /// XPath last function. pub fn last<N: Node>(ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::from( ctxt.cur.len() as i64 )))]) } /// XPath count function. pub fn tr_count< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, ) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::from( ctxt.dispatch(stctxt, s)?.len() as i64, )))]) } /// XPath generate-id function. pub fn generate_id< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { let i = match s { None => ctxt.cur[ctxt.i].clone(), Some(t) => { let seq = ctxt.dispatch(stctxt, t)?; match seq.len() { 0 => return Ok(vec![Item::Value(Rc::new(Value::from("")))]), 1 => seq[0].clone(), _ => { return Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )) } } } }; match i { Item::Node(n) => Ok(vec![Item::Value(Rc::new(Value::from(n.get_id())))]), _ => Err(Error::new(ErrorKind::TypeError, String::from("not a node"))), } } // TODO: this is copied from the xslt module. Move to a common definitions module. const XSLTNS: &str = "http://www.w3.org/1999/XSL/Transform"; /// XSLT system-property function. pub fn system_property< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Box<Transform<N>>, ns: &Rc<NamespaceMap>, ) -> Result<Sequence<N>, Error> { let prop = ctxt.dispatch(stctxt, s)?; if prop.len() == 1 { let qn = QualifiedName::try_from((prop.to_string().as_str(), ns.clone()))?; match ( qn.namespace_uri_to_string().as_deref(), qn.localname_to_string().as_str(), ) { (Some(XSLTNS), "version") => Ok(vec![Item::Value(Rc::new(Value::from("0.9")))]), (Some(XSLTNS), "vendor") => Ok(vec![Item::Value(Rc::new(Value::from( "Steve Ball, Daniel Murphy", )))]), (Some(XSLTNS), "vendor-url") => Ok(vec![Item::Value(Rc::new(Value::from( "https://github.com/ballsteve/xrust", )))]), (Some(XSLTNS), "product-name") => { Ok(vec![Item::Value(Rc::new(Value::from("\u{03A7}rust")))]) } (Some(XSLTNS), "product-version") => { Ok(vec![Item::Value(Rc::new(Value::from(format!( "{}.{}.{}", pkg_version_major!(), pkg_version_minor!(), pkg_version_patch!() ))))]) } (Some(XSLTNS), "is-schema-aware") => Ok(vec![Item::Value(Rc::new(Value::from("no")))]), (Some(XSLTNS), "supports-serialization") => { Ok(vec![Item::Value(Rc::new(Value::from("no")))]) } (Some(XSLTNS), "supports-backwards-compatibility") => { Ok(vec![Item::Value(Rc::new(Value::from("no")))]) } (Some(XSLTNS), "supports-namespace-axis") => { Ok(vec![Item::Value(Rc::new(Value::from("no")))]) } (Some(XSLTNS), "supports-streaming") => { Ok(vec![Item::Value(Rc::new(Value::from("no")))]) } (Some(XSLTNS), "supports-dynamic-evaluation") => { Ok(vec![Item::Value(Rc::new(Value::from("no")))]) } (Some(XSLTNS), "supports-higher-order-functions") => { Ok(vec![Item::Value(Rc::new(Value::from("no")))]) } (Some(XSLTNS), "xpath-version") => Ok(vec![Item::Value(Rc::new(Value::from(2.9)))]), (Some(XSLTNS), "xsd-version") => Ok(vec![Item::Value(Rc::new(Value::from(1.1)))]), _ => Err(Error::new( ErrorKind::Unknown, format!("unknown property \"{}\"", qn), )), } } else { Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )) } } /// XSLT available-system-property function. pub fn available_system_properties<N: Node>() -> Result<Sequence<N>, Error> { Ok(vec![ Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("version"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("vendor"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("vendor-url"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("product-name"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("product-version"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("is-schema-aware"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("supports-serialization"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("supports-backward-compatibility"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("supports-namspace-axis"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("supports-streaming"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("supports-dynamic-evaluation"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("xpath-version"), )))), Item::Value(Rc::new(Value::from(QualifiedName::new( Some(XSLTNS.to_string()), None, String::from("xsd-version"), )))), ]) } /// XSLT document function. /// The first argument is a sequence of URI references. Each reference is cast to xs:anyURI. /// Relative URIs are resolved against the base URI of the second argument. The default is to use the baseURI of the context (i.e. the XSL stylesheet). pub fn document< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, uris: &Box<Transform<N>>, _base: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { let u_list = ctxt.dispatch(stctxt, uris)?; if let Some(h) = &mut stctxt.fetcher { if let Some(g) = &mut stctxt.parser { u_list.iter().try_fold(vec![], |mut acc, u| { // TODO: resolve relative URI against base URI let url = Url::parse(u.to_string().as_str()) .map_err(|_| Error::new(ErrorKind::TypeError, "unable to parse URL"))?; let docdata = h(&url)?; //let x = g(docdata.as_str())?; //acc.push(Item::Node(x)); acc.push(Item::Node(g(docdata.as_str())?)); Ok(acc) }) } else { Err(Error::new( ErrorKind::StaticAbsent, "function to parse document not supplied", )) } } else { Err(Error::new( ErrorKind::StaticAbsent, "function to resolve URI not supplied", )) } } pub(crate) fn tr_error<N: Node>( _ctxt: &Context<N>, kind: &ErrorKind, msg: &String, ) -> Result<Sequence<N>, Error> { Err(Error::new(*kind, msg.clone())) } pub(crate) fn not_implemented<N: Node>( _ctxt: &Context<N>, msg: &String, ) -> Result<Sequence<N>, Error> { Err(Error::new(ErrorKind::NotImplemented, msg.clone())) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/mod.rs
src/transform/mod.rs
/*! The transformation engine. A [Transform] performs processing, control flow, calculations, navigation, and construction to produce a [Sequence]. It starts with an initial context, the most important component of which is the current [Item]; this is often a [Node] that is the source document. All functions in the [Transform] operate via the [Node] trait. This makes the transformation engine independent of the syntax of the source, stylesheet, and result documents. Any [Node]s created by the transformation use the context's result document object. The following transformation implements the expression "1 + 1". The result is (hopefully) "2". ```rust # use std::rc::Rc; # use xrust::xdmerror::{Error, ErrorKind}; # use xrust::trees::smite::{RNode, Node as SmiteNode}; use xrust::value::Value; use xrust::item::{Item, Node, Sequence, SequenceTrait}; use xrust::transform::{Transform, ArithmeticOperand, ArithmeticOperator}; use xrust::transform::context::{Context, StaticContext, StaticContextBuilder}; let xform = Transform::Arithmetic(vec![ ArithmeticOperand::new( ArithmeticOperator::Noop, Transform::Literal(Item::<RNode>::Value(Rc::new(Value::from(1)))) ), ArithmeticOperand::new( ArithmeticOperator::Add, Transform::Literal(Item::<RNode>::Value(Rc::new(Value::from(1)))) ) ]); let mut static_context = StaticContextBuilder::new() .message(|_| Ok(())) .fetcher(|_| Ok(String::new())) .parser(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) .build(); let sequence = Context::new() .dispatch(&mut static_context, &xform) .expect("evaluation failed"); assert_eq!(sequence.to_string(), "2") ``` */ pub(crate) mod booleans; pub mod callable; pub(crate) mod construct; pub mod context; pub(crate) mod controlflow; pub(crate) mod datetime; pub(crate) mod functions; pub(crate) mod grouping; mod keys; pub(crate) mod logic; pub(crate) mod misc; pub(crate) mod navigate; pub mod numbers; pub(crate) mod strings; pub mod template; pub(crate) mod variables; #[allow(unused_imports)] use crate::item::Sequence; use crate::item::{Item, Node, NodeType, SequenceTrait}; use crate::namespace::NamespaceMap; use crate::qname::QualifiedName; use crate::transform::callable::ActualParameters; use crate::transform::context::{Context, ContextBuilder, StaticContext}; use crate::transform::numbers::Numbering; use crate::value::Operator; #[allow(unused_imports)] use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use std::convert::TryFrom; use std::fmt; use std::fmt::{Debug, Formatter}; use std::rc::Rc; use url::Url; /// Specifies how a [Sequence] is constructed. #[derive(Clone)] pub enum Transform<N: Node> { /// Produces the root node of the tree containing the context item. Root, /// Produces a copy of the context item. ContextItem, /// Produces a copy of the current item (see XSLT 20.4.1). CurrentItem, /// A path in a tree. Each element of the outer vector is a step in the path. /// The result of each step becomes the new context for the next step. Compose(Vec<Transform<N>>), /// A step in a path. Step(NodeMatch), /// /// Filters the selected items. /// Each item in the context is evaluated against the predicate. /// If the resulting sequence has an effective boolean value of 'true' then it is kept, /// otherwise it is discarded. Filter(Box<Transform<N>>), /// An empty sequence Empty, /// A literal, atomic value. Literal(Item<N>), /// A literal element. Consists of the element name and content. LiteralElement(Rc<QualifiedName>, Box<Transform<N>>), /// A constructed element. Consists of the name and content. Element(Box<Transform<N>>, Box<Transform<N>>), /// A literal text node. Consists of the value of the node. Second argument gives whether to disable output escaping. LiteralText(Box<Transform<N>>, bool), /// A literal attribute. Consists of the attribute name and value. /// NB. The value may be produced by an Attribute Value Template, so must be dynamic. LiteralAttribute(Rc<QualifiedName>, Box<Transform<N>>), /// A literal comment. Consists of the value. LiteralComment(Box<Transform<N>>), /// A literal processing instruction. Consists of the name and value. LiteralProcessingInstruction(Box<Transform<N>>, Box<Transform<N>>), /// Produce a [Sequence]. Each element in the vector becomes one, or more, item in the sequence. SequenceItems(Vec<Transform<N>>), /// A shallow copy of an item. Consists of the selector of the item to be copied, /// and the content of the target. Copy(Box<Transform<N>>, Box<Transform<N>>), /// A deep copy of an item. That is, it copies an item including its descendants. DeepCopy(Box<Transform<N>>), /// Logical OR. Each element of the outer vector is an operand. Or(Vec<Transform<N>>), /// Logical AND. Each element of the outer vector is an operand. And(Vec<Transform<N>>), /// XPath general comparison. /// Each item in the first sequence is compared against all items in the second sequence. GeneralComparison(Operator, Box<Transform<N>>, Box<Transform<N>>), /// XPath value comparison. /// The first singleton sequence is compared against the second singleton sequence. ValueComparison(Operator, Box<Transform<N>>, Box<Transform<N>>), /// Concatenate string values Concat(Vec<Transform<N>>), /// Produce a range of integer values. /// Consists of the start value and end value. Range(Box<Transform<N>>, Box<Transform<N>>), /// Perform arithmetic operations Arithmetic(Vec<ArithmeticOperand<N>>), /// A repeating transformation. Consists of variable declarations and the loop body. Loop(Vec<(String, Transform<N>)>, Box<Transform<N>>), /// A branching transformation. Consists of (test, body) clauses and an otherwise clause. Switch(Vec<(Transform<N>, Transform<N>)>, Box<Transform<N>>), /// Evaluate a transformation for each selected item, with possible grouping and sorting. ForEach( Option<Grouping<N>>, Box<Transform<N>>, Box<Transform<N>>, Vec<(Order, Transform<N>)>, ), /// Find a template that matches an item and evaluate its body with the item as the context. /// Consists of the selector for items to be matched, the mode, and sort keys. ApplyTemplates( Box<Transform<N>>, Option<Rc<QualifiedName>>, Vec<(Order, Transform<N>)>, ), /// Find templates at the next import level and evaluate its body. ApplyImports, NextMatch, /// Set union Union(Vec<Transform<N>>), /// Evaluate a named template or function, with arguments. /// Consists of the body of the template/function, the actual arguments (variable declarations), and in-scope namespace declarations. Call(Box<Transform<N>>, Vec<Transform<N>>, Rc<NamespaceMap>), /// Declare a variable in the current context. /// Consists of the variable name, its value, a transformation to perform with the variable in scope, and in-scope namespace declarations. VariableDeclaration( String, Box<Transform<N>>, Box<Transform<N>>, Rc<NamespaceMap>, ), /// Reference a variable. /// The result is the value stored for that variable in the current context and current scope. VariableReference(String, Rc<NamespaceMap>), /// Set the value of an attribute. The context item must be an element-type node. /// Consists of the name of the attribute and its value. The [Sequence] produced will be cast to a [Value]. SetAttribute(Rc<QualifiedName>, Box<Transform<N>>), /// XPath functions Position, Last, Count(Box<Transform<N>>), LocalName(Option<Box<Transform<N>>>), Name(Option<Box<Transform<N>>>), String(Box<Transform<N>>), StartsWith(Box<Transform<N>>, Box<Transform<N>>), EndsWith(Box<Transform<N>>, Box<Transform<N>>), Contains(Box<Transform<N>>, Box<Transform<N>>), Substring( Box<Transform<N>>, Box<Transform<N>>, Option<Box<Transform<N>>>, ), SubstringBefore(Box<Transform<N>>, Box<Transform<N>>), SubstringAfter(Box<Transform<N>>, Box<Transform<N>>), NormalizeSpace(Option<Box<Transform<N>>>), Translate(Box<Transform<N>>, Box<Transform<N>>, Box<Transform<N>>), GenerateId(Option<Box<Transform<N>>>), Boolean(Box<Transform<N>>), Not(Box<Transform<N>>), True, False, Number(Box<Transform<N>>), Sum(Box<Transform<N>>), Avg(Box<Transform<N>>), Min(Box<Transform<N>>), Max(Box<Transform<N>>), Floor(Box<Transform<N>>), Ceiling(Box<Transform<N>>), Round(Box<Transform<N>>, Option<Box<Transform<N>>>), CurrentDateTime, CurrentDate, CurrentTime, FormatDateTime( Box<Transform<N>>, Box<Transform<N>>, Option<Box<Transform<N>>>, Option<Box<Transform<N>>>, Option<Box<Transform<N>>>, ), FormatDate( Box<Transform<N>>, Box<Transform<N>>, Option<Box<Transform<N>>>, Option<Box<Transform<N>>>, Option<Box<Transform<N>>>, ), FormatTime( Box<Transform<N>>, Box<Transform<N>>, Option<Box<Transform<N>>>, Option<Box<Transform<N>>>, Option<Box<Transform<N>>>, ), FormatNumber( Box<Transform<N>>, Box<Transform<N>>, Option<Box<Transform<N>>>, ), /// Convert a number to a string. /// This is one half of the functionality of xsl:number, as well as format-integer(). /// See XSLT 12.4. /// First argument is the integer to be formatted. /// Second argument is the format specification. FormatInteger(Box<Transform<N>>, Box<Transform<N>>), /// Generate a sequence of integers. This is one half of the functionality of xsl:number. /// First argument is the start-at specification. /// Second argument is the select expression. /// Third argument is the level. /// Fourth argument is the count pattern. /// Fifth argument is the from pattern. GenerateIntegers(Box<Transform<N>>, Box<Transform<N>>, Box<Numbering<N>>), CurrentGroup, CurrentGroupingKey, /// Look up a key. The first argument is the key name, the second argument is the key value, /// the third argument is the top of the tree for the resulting nodes, /// the fourth argument is the in-scope namespaces. Key( Box<Transform<N>>, Box<Transform<N>>, Option<Box<Transform<N>>>, Rc<NamespaceMap>, ), /// Get information about the processor SystemProperty(Box<Transform<N>>, Rc<NamespaceMap>), AvailableSystemProperties, /// Read an external document Document(Box<Transform<N>>, Option<Box<Transform<N>>>), /// Invoke a callable component. Consists of a name, an actual argument list, and in-scope namespace declarations. Invoke(Rc<QualifiedName>, ActualParameters<N>, Rc<NamespaceMap>), /// Emit a message. Consists of a select expression, a terminate attribute, an error-code, and a body. Message( Box<Transform<N>>, Option<Box<Transform<N>>>, Box<Transform<N>>, Box<Transform<N>>, ), /// For things that are not yet implemented, such as: /// Union, IntersectExcept, InstanceOf, Treat, Castable, Cast, Arrow, Unary, SimpleMap, Is, Before, After. NotImplemented(String), /// Error condition. Error(ErrorKind, String), } impl<N: Node> Debug for Transform<N> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Transform::Root => write!(f, "root node"), Transform::ContextItem => write!(f, "context item"), Transform::CurrentItem => write!(f, "current item"), Transform::SequenceItems(v) => write!(f, "Sequence of {} items", v.len()), Transform::Compose(v) => { write!(f, "Compose {} steps [", v.len()).expect("unable to format step"); v.iter().for_each(|s| { s.fmt(f).expect("unable to format step"); write!(f, "; ").expect("unable to format step") }); write!(f, "]") } Transform::Step(nm) => write!(f, "Step matching {}", nm), Transform::Filter(_) => write!(f, "Filter"), Transform::Empty => write!(f, "Empty"), Transform::Literal(_) => write!(f, "literal value"), Transform::LiteralElement(qn, _) => write!(f, "literal element named \"{}\"", qn), Transform::Element(_, _) => write!(f, "constructed element"), Transform::LiteralText(_, b) => write!(f, "literal text (disable escaping {})", b), Transform::LiteralAttribute(qn, _) => write!(f, "literal attribute named \"{}\"", qn), Transform::LiteralComment(_) => write!(f, "literal comment"), Transform::LiteralProcessingInstruction(_, _) => { write!(f, "literal processing-instruction") } Transform::Copy(_, _) => write!(f, "shallow copy"), Transform::DeepCopy(_) => write!(f, "deep copy"), Transform::GeneralComparison(o, v, u) => { write!(f, "general comparison {} of {:?} and {:?}", o, v, u) } Transform::ValueComparison(o, v, u) => { write!(f, "value comparison {} of {:?} and {:?}", o, v, u) } Transform::Concat(o) => write!(f, "Concatenate {} operands", o.len()), Transform::Range(_, _) => write!(f, "range"), Transform::Arithmetic(o) => write!(f, "Arithmetic {} operands", o.len()), Transform::And(o) => write!(f, "AND {} operands", o.len()), Transform::Or(o) => write!(f, "OR {} operands", o.len()), Transform::Loop(_, _) => write!(f, "loop"), Transform::Switch(c, _) => write!(f, "switch {} clauses", c.len()), Transform::ForEach(_g, _, _, o) => write!(f, "for-each ({} sort keys)", o.len()), Transform::Union(v) => write!(f, "union of {} operands", v.len()), Transform::ApplyTemplates(_, m, o) => { write!(f, "Apply templates (mode {:?}, {} sort keys)", m, o.len()) } Transform::Call(_, a, _) => write!(f, "Call transform with {} arguments", a.len()), Transform::ApplyImports => write!(f, "Apply imports"), Transform::NextMatch => write!(f, "next-match"), Transform::VariableDeclaration(n, _, _, _) => write!(f, "declare variable \"{}\"", n), Transform::VariableReference(n, _) => write!(f, "reference variable \"{}\"", n), Transform::SetAttribute(n, _) => write!(f, "set attribute named \"{}\"", n), Transform::Position => write!(f, "position"), Transform::Last => write!(f, "last"), Transform::Count(_s) => write!(f, "count()"), Transform::Name(_n) => write!(f, "name()"), Transform::LocalName(_n) => write!(f, "local-name()"), Transform::String(s) => write!(f, "string({:?})", s), Transform::StartsWith(s, t) => write!(f, "starts-with({:?}, {:?})", s, t), Transform::EndsWith(s, t) => write!(f, "ends-with({:?}, {:?})", s, t), Transform::Contains(s, t) => write!(f, "contains({:?}, {:?})", s, t), Transform::Substring(s, t, _l) => write!(f, "substring({:?}, {:?}, ...)", s, t), Transform::SubstringBefore(s, t) => write!(f, "substring-before({:?}, {:?})", s, t), Transform::SubstringAfter(s, t) => write!(f, "substring-after({:?}, {:?})", s, t), Transform::NormalizeSpace(_s) => write!(f, "normalize-space()"), Transform::Translate(s, t, u) => write!(f, "translate({:?}, {:?}, {:?})", s, t, u), Transform::GenerateId(_) => write!(f, "generate-id()"), Transform::Boolean(b) => write!(f, "boolean({:?})", b), Transform::Not(b) => write!(f, "not({:?})", b), Transform::True => write!(f, "true"), Transform::False => write!(f, "false"), Transform::Number(n) => write!(f, "number({:?})", n), Transform::Sum(n) => write!(f, "sum({:?})", n), Transform::Avg(n) => write!(f, "avg({:?})", n), Transform::Min(n) => write!(f, "min({:?})", n), Transform::Max(n) => write!(f, "max({:?})", n), Transform::Floor(n) => write!(f, "floor({:?})", n), Transform::Ceiling(n) => write!(f, "ceiling({:?})", n), Transform::Round(n, _p) => write!(f, "round({:?},...)", n), Transform::CurrentDateTime => write!(f, "current-date-time"), Transform::CurrentDate => write!(f, "current-date"), Transform::CurrentTime => write!(f, "current-time"), Transform::FormatDateTime(p, q, _, _, _) => { write!(f, "format-date-time({:?}, {:?}, ...)", p, q) } Transform::FormatDate(p, q, _, _, _) => write!(f, "format-date({:?}, {:?}, ...)", p, q), Transform::FormatTime(p, q, _, _, _) => write!(f, "format-time({:?}, {:?}, ...)", p, q), Transform::FormatNumber(v, p, _) => write!(f, "format-number({:?}, {:?})", v, p), Transform::FormatInteger(i, s) => write!(f, "format-integer({:?}, {:?})", i, s), Transform::GenerateIntegers(_start_at, _select, _n) => write!(f, "generate-integers"), Transform::CurrentGroup => write!(f, "current-group"), Transform::CurrentGroupingKey => write!(f, "current-grouping-key"), Transform::Key(s, _, _, _) => write!(f, "key({:?}, ...)", s), Transform::SystemProperty(p, _) => write!(f, "system-properties({:?})", p), Transform::AvailableSystemProperties => write!(f, "available-system-properties"), Transform::Document(uris, _) => write!(f, "document({:?})", uris), Transform::Invoke(qn, _a, _) => write!(f, "invoke \"{}\"", qn), Transform::Message(_, _, _, _) => write!(f, "message"), Transform::NotImplemented(s) => write!(f, "Not implemented: \"{}\"", s), Transform::Error(k, s) => write!(f, "Error: {} \"{}\"", k, s), } } } /// A convenience function to create a namespace mapping from a [Node]. pub fn in_scope_namespaces<N: Node>(n: Option<N>) -> Rc<NamespaceMap> { if let Some(nn) = n { Rc::new(nn.namespace_iter().fold(NamespaceMap::new(), |mut hm, ns| { hm.insert(Some(ns.name().localname()), ns.value()); hm })) } else { Rc::new(NamespaceMap::new()) } } /// The sort order #[derive(Clone, PartialEq, Debug)] pub enum Order { Ascending, Descending, } /// Performing sorting of a [Sequence] using the given sort keys. pub(crate) fn do_sort< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( seq: &mut Sequence<N>, o: &Vec<(Order, Transform<N>)>, ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, ) -> Result<(), Error> { // Optionally sort the select sequence // TODO: multiple sort keys if !o.is_empty() { seq.sort_by_cached_key(|k| { // TODO: Don't panic let key_seq = ContextBuilder::from(ctxt) .context(vec![k.clone()]) .build() .dispatch(stctxt, &o[0].1) .expect("unable to determine key value"); // Assume string data type for now // TODO: support number data type // TODO: support all data types key_seq.to_string() }); if o[0].0 == Order::Descending { seq.reverse(); } } Ok(()) } /// Determine how a collection is to be divided into groups. /// This value would normally be inside an Option. /// A None value for the option means that the collection is not to be grouped. #[derive(Clone, Debug)] pub enum Grouping<N: Node> { By(Vec<Transform<N>>), StartingWith(Vec<Transform<N>>), EndingWith(Vec<Transform<N>>), Adjacent(Vec<Transform<N>>), } impl<N: Node> Grouping<N> { fn to_string(&self) -> String { match self { Grouping::By(_) => "group-by".to_string(), Grouping::Adjacent(_) => "group-adjacent".to_string(), Grouping::StartingWith(_) => "group-starting-with".to_string(), Grouping::EndingWith(_) => "group-ending-with".to_string(), } } } impl<N: Node> fmt::Display for Grouping<N> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } #[derive(Clone, Debug)] pub struct NodeMatch { pub axis: Axis, pub nodetest: NodeTest, } impl NodeMatch { pub fn new(axis: Axis, nodetest: NodeTest) -> Self { NodeMatch { axis, nodetest } } pub fn matches_item<N: Node>(&self, i: &Item<N>) -> bool { match i { Item::Node(n) => self.matches(n), _ => false, } } pub fn matches<N: Node>(&self, n: &N) -> bool { match &self.nodetest { NodeTest::Name(t) => { match n.node_type() { NodeType::Element | NodeType::Attribute => { // TODO: namespaces match &t.name { Some(a) => match a { WildcardOrName::Wildcard => true, WildcardOrName::Name(s) => *s == n.name().localname(), }, None => false, } } _ => false, } } NodeTest::Kind(k) => { match k { KindTest::Document => matches!(n.node_type(), NodeType::Document), KindTest::Element => matches!(n.node_type(), NodeType::Element), KindTest::PI => matches!(n.node_type(), NodeType::ProcessingInstruction), KindTest::Comment => matches!(n.node_type(), NodeType::Comment), KindTest::Text => matches!(n.node_type(), NodeType::Text), //Note: This one is matching not NodeType::Document KindTest::Any => !matches!(n.node_type(), NodeType::Document), KindTest::Attribute | KindTest::SchemaElement | KindTest::SchemaAttribute | KindTest::Namespace => false, // TODO: not yet implemented } } } } } impl fmt::Display for NodeMatch { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "node match {} {}", self.axis, self.nodetest) } } #[derive(Clone, Debug)] pub enum NodeTest { Kind(KindTest), Name(NameTest), } impl NodeTest { pub fn matches<N: Node>(&self, i: &Item<N>) -> bool { match i { Item::Node(_) => match self { NodeTest::Kind(k) => k.matches(i), NodeTest::Name(nm) => nm.matches(i), }, _ => false, } } } impl fmt::Display for NodeTest { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { NodeTest::Kind(k) => write!(f, "kind test {}", k), NodeTest::Name(nm) => write!(f, "name test {}", nm), } } } impl TryFrom<&str> for NodeTest { type Error = Error; fn try_from(s: &str) -> Result<Self, Self::Error> { // Import this from xpath.rs? let tok: Vec<&str> = s.split(':').collect(); match tok.len() { 1 => { // unprefixed if tok[0] == "*" { Ok(NodeTest::Name(NameTest { name: Some(WildcardOrName::Wildcard), ns: None, prefix: None, })) } else { Ok(NodeTest::Name(NameTest { name: Some(WildcardOrName::Name(Rc::new(Value::from(tok[0])))), ns: None, prefix: None, })) } } 2 => { // prefixed if tok[0] == "*" { if tok[1] == "*" { Ok(NodeTest::Name(NameTest { name: Some(WildcardOrName::Wildcard), ns: Some(WildcardOrName::Wildcard), prefix: None, })) } else { Ok(NodeTest::Name(NameTest { name: Some(WildcardOrName::Name(Rc::new(Value::from(tok[1])))), ns: Some(WildcardOrName::Wildcard), prefix: None, })) } } else if tok[1] == "*" { Ok(NodeTest::Name(NameTest { name: Some(WildcardOrName::Wildcard), ns: None, prefix: Some(Rc::new(Value::from(tok[0]))), })) } else { Ok(NodeTest::Name(NameTest { name: Some(WildcardOrName::Name(Rc::new(Value::from(tok[1])))), ns: None, prefix: Some(Rc::new(Value::from(tok[0]))), })) } } _ => Result::Err(Error::new( ErrorKind::TypeError, "invalid NodeTest".to_string(), )), } } } #[derive(Copy, Clone, Debug)] pub enum KindTest { Document, Element, Attribute, SchemaElement, SchemaAttribute, PI, Comment, Text, Namespace, Any, } impl fmt::Display for KindTest { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { KindTest::Document => write!(f, "document"), KindTest::Element => write!(f, "element"), KindTest::Attribute => write!(f, "attribute"), KindTest::SchemaElement => write!(f, "schema element"), KindTest::SchemaAttribute => write!(f, "schema attribute"), KindTest::PI => write!(f, "processing instruction"), KindTest::Comment => write!(f, "comment"), KindTest::Text => write!(f, "text"), KindTest::Namespace => write!(f, "namespace"), KindTest::Any => write!(f, "any node"), } } } impl KindTest { /// Does an item match the Kind Test? pub fn matches<N: Node>(&self, i: &Item<N>) -> bool { match i { Item::Node(n) => { match (self, n.node_type()) { (KindTest::Document, NodeType::Document) => true, (KindTest::Document, _) => false, (KindTest::Element, NodeType::Element) => true, (KindTest::Element, _) => false, (KindTest::Attribute, NodeType::Attribute) => true, (KindTest::Attribute, _) => false, (KindTest::SchemaElement, _) => false, // not supported (KindTest::SchemaAttribute, _) => false, // not supported (KindTest::PI, NodeType::ProcessingInstruction) => true, (KindTest::PI, _) => false, (KindTest::Comment, NodeType::Comment) => true, (KindTest::Comment, _) => false, (KindTest::Text, NodeType::Text) => true, (KindTest::Text, _) => false, (KindTest::Namespace, _) => false, // not yet implemented (KindTest::Any, _) => true, } } _ => false, } } pub fn to_string(&self) -> &'static str { match self { KindTest::Document => "DocumentTest", KindTest::Element => "ElementTest", KindTest::Attribute => "AttributeTest", KindTest::SchemaElement => "SchemaElementTest", KindTest::SchemaAttribute => "SchemaAttributeTest", KindTest::PI => "PITest", KindTest::Comment => "CommentTest", KindTest::Text => "TextTest", KindTest::Namespace => "NamespaceNodeTest", KindTest::Any => "AnyKindTest", } } } #[derive(Clone, Debug)] pub struct NameTest { pub ns: Option<WildcardOrName>, pub prefix: Option<Rc<Value>>, pub name: Option<WildcardOrName>, } impl NameTest { pub fn new( ns: Option<WildcardOrName>, prefix: Option<Rc<Value>>, name: Option<WildcardOrName>, ) -> Self { NameTest { ns, prefix, name } } /// Does an Item match this name test? To match, the item must be a node, have a name, /// have the namespace URI and local name be equal or a wildcard pub fn matches<N: Node>(&self, i: &Item<N>) -> bool { match i { Item::Node(n) => { match n.node_type() { NodeType::Element | NodeType::ProcessingInstruction | NodeType::Attribute => { // TODO: avoid converting the values into strings just for comparison // Value interning should fix this match ( self.ns.as_ref(), self.name.as_ref(), n.name().namespace_uri(), n.name().localname_to_string().as_str(), ) { (None, None, _, _) => false, (None, Some(WildcardOrName::Wildcard), None, _) => true, (None, Some(WildcardOrName::Wildcard), Some(_), _) => false, (None, Some(WildcardOrName::Name(_)), None, "") => false, (None, Some(WildcardOrName::Name(wn)), None, qn) => { wn.to_string() == qn } (None, Some(WildcardOrName::Name(_)), Some(_), _) => false, (Some(_), None, _, _) => false, // A namespace URI without a local name doesn't make sense ( Some(WildcardOrName::Wildcard), Some(WildcardOrName::Wildcard), _, _, ) => true, ( Some(WildcardOrName::Wildcard), Some(WildcardOrName::Name(_)), _, "", ) => false, ( Some(WildcardOrName::Wildcard), Some(WildcardOrName::Name(wn)), _, qn, ) => wn.to_string() == qn, (Some(WildcardOrName::Name(_)), Some(_), None, _) => false, ( Some(WildcardOrName::Name(wnsuri)), Some(WildcardOrName::Name(wn)), Some(qnsuri), qn, ) => wnsuri.clone() == qnsuri && wn.to_string() == qn, _ => false, // maybe should panic? } } _ => false, // all other node types don't have names } } _ => false, // other item types don't have names } } } impl fmt::Display for NameTest { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let result = if self.name.is_some() { match self.name.as_ref().unwrap() { WildcardOrName::Wildcard => "*".to_string(), WildcardOrName::Name(n) => n.to_string(), } } else { "--no name--".to_string() }; f.write_str(result.as_str()) } } #[derive(Clone, Debug)] pub enum WildcardOrName { Wildcard, Name(Rc<Value>), } #[derive(Copy, Clone, Debug, PartialEq)] pub enum Axis { Child,
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
true
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/numbers.rs
src/transform/numbers.rs
//! These functions are for features defined in XPath Functions 1.0 and 2.0. use std::rc::Rc; use url::Url; use english_numbers::{convert, Formatting}; use formato::Formato; use italian_numbers::roman_converter; use crate::item::{Item, Node, NodeType, Sequence, SequenceTrait}; use crate::pattern::{Branch, Pattern, Step}; use crate::qname::QualifiedName; use crate::transform::context::{Context, StaticContext}; use crate::transform::{ ArithmeticOperand, ArithmeticOperator, Axis, KindTest, NameTest, NodeTest, Transform, WildcardOrName, }; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; /// Level value for xsl:number. See XSLT 12.3. #[derive(Copy, Clone, Debug, Default, PartialEq)] pub enum Level { #[default] Single, Multiple, Any, } /// Specification for generating numbers. This is avoid recursive types in [Transform] and [Pattern]. #[derive(Clone, Debug)] pub struct Numbering<N: Node> { level: Level, count: Option<Pattern<N>>, from: Option<Pattern<N>>, } impl<N: Node> Numbering<N> { pub fn new(level: Level, count: Option<Pattern<N>>, from: Option<Pattern<N>>) -> Self { Numbering { level, count, from } } } /// Generate a sequence of integers pub fn generate_integers< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, _start_at: &Transform<N>, select: &Transform<N>, num: &Numbering<N>, ) -> Result<Sequence<N>, Error> { // This implements "single" level. "multiple" and "any" are TODO if num.level != Level::Single { return Err(Error::new( ErrorKind::NotImplemented, "only single level is implemented", )); } // The select expression must evaluate to a single node item (XSLT error XTTE1000) let n = ctxt.dispatch(stctxt, select)?; if n.len() == 1 { if let Item::Node(m) = &n[0] { // Determine the count pattern let count_pat = (num.count) .clone() .unwrap_or(Pattern::Selection(Branch::SingleStep( match m.node_type() { NodeType::Element => Step::new( Axis::SelfAxis, Axis::SelfAxis, NodeTest::Name(NameTest::new( m.name().namespace_uri().map(WildcardOrName::Name), None, Some(WildcardOrName::Name(m.name().localname())), )), ), NodeType::Text => Step::new( Axis::SelfAxis, Axis::SelfAxis, NodeTest::Kind(KindTest::Text), ), _ => { return Err(Error::new( ErrorKind::TypeError, "cannot match this type of node", )) } }, ))); // let a = $S/ancestor-or-self::node()[matches-count(.)][1] // TODO: Don't Panic let a = if count_pat.matches(ctxt, stctxt, &Item::Node(m.clone())) { vec![m.clone()] } else { m.ancestor_iter() .filter(|i| count_pat.matches(ctxt, stctxt, &Item::Node(i.clone()))) .take(1) .collect() }; if a.is_empty() { return Ok(vec![]); } // let f = $S/ancestor-or-self::node()[matches-from(.)][1] // TODO: Don't Panic let f: Vec<N> = if let Some(fr) = &num.from.clone() { m.ancestor_iter() .filter(|i| { if i.node_type() == NodeType::Document { true } else { fr.matches(ctxt, stctxt, &Item::Node(i.clone())) } }) .take(1) .collect() } else { // When there is no from pattern specified then use the root node vec![m.owner_document().clone()] }; if f.is_empty() { return Ok(vec![]); } // let af = $a[ancestor-or-self::node()[. is $f]] let af_test: Vec<N> = if a[0].is_same(&f[0]) { vec![a[0].clone()] } else { a[0].ancestor_iter().filter(|i| i.is_same(&f[0])).collect() }; let af = if af_test.is_empty() { vec![] } else { a }; if af.is_empty() { return Ok(vec![]); } // 1 + count($af/preceding-sibling::node()[matches-count(.)]) let result: Vec<N> = af[0] .prev_iter() .filter(|i| count_pat.matches(ctxt, stctxt, &Item::Node(i.clone()))) .collect(); Ok(vec![Item::Value(Rc::new(Value::from(1 + result.len())))]) } else { Err(Error::new_with_code( ErrorKind::TypeError, "not a singleton node", Some(QualifiedName::new(None, None, "XTTE1000")), )) } } else { Err(Error::new_with_code( ErrorKind::TypeError, "not a singleton node", Some(QualifiedName::new(None, None, "XTTE1000")), )) } } /// XPath number function. pub fn number< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, num: &Transform<N>, ) -> Result<Sequence<N>, Error> { let n = ctxt.dispatch(stctxt, num)?; match n.len() { 1 => { // First try converting to an integer match n[0].to_int() { Ok(i) => Ok(vec![Item::Value(Rc::new(Value::Integer(i)))]), _ => { // Otherwise convert to double. // NB. This can't fail. At worst it returns NaN. Ok(vec![Item::Value(Rc::new(Value::Double(n[0].to_double())))]) } } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } /// XPath sum function. pub fn sum< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, ) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::Double( ctxt.dispatch(stctxt, s)?.iter().fold(0.0, |mut acc, i| { acc += i.to_double(); acc }), )))]) } /// XPath 2.0 avg function. pub fn avg< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, ) -> Result<Sequence<N>, Error> { let seq = ctxt.dispatch(stctxt, s)?; if seq.is_empty() { return Ok(seq); } // XPath 2.0 has rules for type conversion let sum = seq.iter().fold(0.0, |mut acc, i| { acc += i.to_double(); acc }); Ok(vec![Item::Value(Rc::new(Value::Double( sum / (seq.len() as f64), )))]) } /// XPath 2.0 min function. pub fn min< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, ) -> Result<Sequence<N>, Error> { let seq = ctxt.dispatch(stctxt, s)?; // XPath 2.0 has rules for type conversion if seq.is_empty() { Ok(seq) } else { Ok(vec![Item::Value(Rc::new(Value::Double( seq.iter().skip(1).fold(seq[0].to_double(), |acc, i| { if acc > i.to_double() { i.to_double() } else { acc } }), )))]) } } /// XPath 2.0 max function. pub fn max< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, ) -> Result<Sequence<N>, Error> { let seq = ctxt.dispatch(stctxt, s)?; // XPath 2.0 has rules for type conversion if seq.is_empty() { Ok(seq) } else { Ok(vec![Item::Value(Rc::new(Value::Double( seq.iter().skip(1).fold(seq[0].to_double(), |acc, i| { if acc < i.to_double() { i.to_double() } else { acc } }), )))]) } } /// XPath floor function. pub fn floor< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, f: &Transform<N>, ) -> Result<Sequence<N>, Error> { let n = ctxt.dispatch(stctxt, f)?; match n.len() { 1 => Ok(vec![Item::Value(Rc::new(Value::Double( n[0].to_double().floor(), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } /// XPath ceiling function. pub fn ceiling< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, c: &Transform<N>, ) -> Result<Sequence<N>, Error> { let n = ctxt.dispatch(stctxt, c)?; match n.len() { 1 => Ok(vec![Item::Value(Rc::new(Value::Double( n[0].to_double().ceil(), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } /// XPath round function. pub fn round< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, r: &Transform<N>, pr: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { match pr { Some(p) => { let n = ctxt.dispatch(stctxt, r)?; let m = ctxt.dispatch(stctxt, p)?; match (n.len(), m.len()) { (1, 1) => Ok(vec![Item::Value(Rc::new(Value::Double( ((n[0].to_double() * (10.0_f64).powi(m[0].to_int().unwrap() as i32)).round()) * (10.0_f64).powi(-m[0].to_int().unwrap() as i32), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } None => { // precision is 0, i.e. round to nearest whole number let n = ctxt.dispatch(stctxt, r)?; match n.len() { 1 => Ok(vec![Item::Value(Rc::new(Value::Double( n[0].to_double().round(), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } } } /// Generate a sequence with a range of integers. pub(crate) fn tr_range< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, start: &Transform<N>, end: &Transform<N>, ) -> Result<Sequence<N>, Error> { let s = ctxt.dispatch(stctxt, start)?; let e = ctxt.dispatch(stctxt, end)?; if s.is_empty() || e.is_empty() { // Empty sequence is the result return Ok(vec![]); } if s.len() != 1 || e.len() != 1 { return Err(Error::new( ErrorKind::TypeError, String::from("operands must be singleton sequence"), )); } let i = s[0].to_int()?; let j = e[0].to_int()?; if i > j { // empty sequence result Ok(vec![]) } else if i == j { let mut seq = Sequence::new(); seq.push_value(&Rc::new(Value::Integer(i))); Ok(seq) } else { let mut result = Sequence::new(); for k in i..=j { result.push_value(&Rc::new(Value::from(k))) } Ok(result) } } /// Perform an arithmetic operation. pub(crate) fn arithmetic< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, ops: &Vec<ArithmeticOperand<N>>, ) -> Result<Sequence<N>, Error> { // Type: the result will be a number, but integer or double? // If all of the operands are integers, then the result is integer otherwise double // TODO: check the type of all operands to determine type of result (can probably do this in static analysis phase) // In the meantime, let's assume the result will be double and convert any integers let mut acc = 0.0; for o in ops { let j = match ctxt.dispatch(stctxt, &o.operand) { Ok(s) => s, Err(_) => { acc = f64::NAN; break; } }; if j.len() != 1 { acc = f64::NAN; break; } let u = j[0].to_double(); match o.op { ArithmeticOperator::Noop => acc = u, ArithmeticOperator::Add => acc += u, ArithmeticOperator::Subtract => acc -= u, ArithmeticOperator::Multiply => acc *= u, ArithmeticOperator::Divide => acc /= u, ArithmeticOperator::IntegerDivide => acc /= u, // TODO: convert to integer ArithmeticOperator::Modulo => acc %= u, } } Ok(vec![Item::Value(Rc::new(Value::from(acc)))]) } /// XPath format-number function. pub fn format_number< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, num: &Transform<N>, picture: &Transform<N>, _name: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { let p = ctxt.dispatch(stctxt, picture)?.to_string(); let n = ctxt.dispatch(stctxt, num)?; match n.len() { 1 => { // First try converting to an integer match n[0].to_int() { Ok(i) => Ok(vec![Item::Value(Rc::new(Value::String( i.formato(p.as_str()), )))]), _ => { // Otherwise convert to double. // NB. This can't fail. At worst it returns NaN. Ok(vec![Item::Value(Rc::new(Value::String( n[0].to_double().formato(p.as_str()), )))]) } } } _ => Err(Error::new( ErrorKind::TypeError, String::from("not a singleton sequence"), )), } } /// XSLT xsl:number and XPath format-integer function. pub fn format_integer< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, num: &Transform<N>, picture: &Transform<N>, ) -> Result<Sequence<N>, Error> { let p = ctxt.dispatch(stctxt, picture)?.to_string(); let numbers = ctxt.dispatch(stctxt, num)?; let mut nit = numbers.iter(); let mut result = String::new(); // Interpret the picture string. // Most of the tokens are one character, except for 'Ww'. let mut pit = p.chars().peekable(); loop { let c = pit.next(); if let Some(d) = c { if d.is_alphanumeric() { match d { '0' => { // 01, 02, 03, 04, ... // length specification // TODO: non-arabic-roman numerals let mut token = String::from(d); loop { if let Some(p) = pit.peek() { if p.eq(&'0') { pit.next(); token.push('0'); } else if p.eq(&'1') { pit.next(); token.push('1'); } else { break; } } else { break; } } if let Some(num) = nit.next() { result.push_str( format!("{:0>1$}", num.to_int()?.to_string(), token.len()).as_str(), ); } else { break; } } '1' => { // 1, 2, 3, ... if let Some(num) = nit.next() { result.push_str(num.to_int()?.to_string().as_str()) } else { break; } } 'A' => { // A, B, C, ..., AA, BB, CC, ... } 'a' => { // a, b, c, ..., aa, bb, cc, ... } 'i' => { // i, ii, iii, iv, v, vi, ... if let Some(num) = nit.next() { result.push_str( roman_converter(u16::try_from(num.to_int()?).map_err(|e| { Error::new(ErrorKind::ParseError, e.to_string()) })?) .map_err(|e| Error::new(ErrorKind::ParseError, e))? .to_lowercase() .as_str(), ) } else { break; } } 'I' => { // I, II, III, IV, V, VI, ... if let Some(num) = nit.next() { result.push_str( roman_converter(u16::try_from(num.to_int()?).map_err(|e| { Error::new(ErrorKind::ParseError, e.to_string()) })?) .map_err(|e| Error::new(ErrorKind::ParseError, e))? .as_str(), ) } else { break; } } 'w' => { // one, two, three, ... if let Some(num) = nit.next() { result.push_str( convert( num.to_int()?, Formatting { title_case: false, spaces: true, conjunctions: false, commas: false, dashes: false, }, ) .to_string() .as_str(), ) } else { break; } } 'W' => { // 'Ww' if let Some('w') = pit.peek() { // One, Two, Three, ... pit.next(); if let Some(num) = nit.next() { result.push_str( convert( num.to_int()?, Formatting { title_case: true, spaces: true, conjunctions: false, commas: false, dashes: false, }, ) .to_string() .as_str(), ) } else { break; } } else { // ONE, TWO, THREE, ... if let Some(num) = nit.next() { result.push_str( convert( num.to_int()?, Formatting { title_case: false, spaces: true, conjunctions: false, commas: false, dashes: false, }, ) .to_string() .to_uppercase() .as_str(), ) } else { break; } } } // TODO: non-English words // Use french-numbers crate // Use italian-numbers crate _ => {} } } else { result.push(d) } } else { break; } } Ok(vec![Item::Value(Rc::new(Value::from(result)))]) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/grouping.rs
src/transform/grouping.rs
//! These functions are for features defined in XPath Functions 1.0 and 2.0. use crate::item::{Item, Node, Sequence}; use crate::transform::context::Context; use crate::xdmerror::{Error, ErrorKind}; /// XSLT current-group function. pub fn current_group<N: Node>(ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(ctxt.current_group.clone()) } /// XSLT current-grouping-key function. pub fn current_grouping_key<N: Node>(ctxt: &Context<N>) -> Result<Sequence<N>, Error> { ctxt.current_grouping_key.clone().map_or_else( || { Err(Error::new( ErrorKind::TypeError, String::from("no current grouping key"), )) }, |k| Ok(vec![Item::Value(k)]), ) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/strings.rs
src/transform/strings.rs
//! These functions are for features defined in XPath Functions 1.0 and 2.0. use std::rc::Rc; use unicode_segmentation::UnicodeSegmentation; use url::Url; use crate::item::{Item, Node, Sequence, SequenceTrait}; use crate::transform::context::{Context, StaticContext}; use crate::transform::Transform; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; /// XPath local-name function. pub fn local_name< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { s.as_ref().map_or_else( || { // Get the name of the context item // TODO: handle the case of there not being a context item match ctxt.cur[ctxt.i] { Item::Node(ref m) => Ok(vec![Item::Value(m.name().localname().clone())]), _ => Err(Error::new( ErrorKind::TypeError, String::from("type error: not a node"), )), } }, |t| { // Get the name of the singleton node let n = ctxt.dispatch(stctxt, t)?; match n.len() { 0 => Ok(vec![Item::Value(Rc::new(Value::from("")))]), 1 => match n[0] { Item::Node(ref m) => Ok(vec![Item::Value(m.name().localname())]), _ => Err(Error::new( ErrorKind::TypeError, String::from("type error: not a node"), )), }, _ => Err(Error::new( ErrorKind::TypeError, String::from("type error: not a singleton node"), )), } }, ) } /// XPath name function. pub fn name< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { s.as_ref().map_or_else( || { // Get the name of the context item // TODO: handle the case of there being no context item match ctxt.cur[ctxt.i] { Item::Node(ref m) => Ok(vec![Item::Value(Rc::new(Value::from(m.name().clone())))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("type error: not a node"), )), } }, |t| { // Get the name of the singleton node let n = ctxt.dispatch(stctxt, t)?; match n.len() { 0 => Ok(vec![Item::Value(Rc::new(Value::from("")))]), 1 => match n[0] { Item::Node(ref m) => Ok(vec![Item::Value(Rc::new(Value::from( m.name().to_string(), )))]), _ => Err(Error::new( ErrorKind::TypeError, String::from("type error: not a node"), )), }, _ => Err(Error::new( ErrorKind::TypeError, String::from("type error: not a singleton node"), )), } }, ) } /// XPath string function. pub fn string< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, ) -> Result<Sequence<N>, Error> { Ok(vec![Item::Value(Rc::new(Value::from( ctxt.dispatch(stctxt, s)?.to_string(), )))]) } /// XPath starts-with function. pub fn starts_with< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { // s is the string to search, t is what to search for Ok(vec![Item::Value(Rc::new(Value::from( ctxt.dispatch(stctxt, s)? .to_string() .starts_with(ctxt.dispatch(stctxt, t)?.to_string().as_str()), )))]) } /// XPath ends-with function. pub fn ends_with< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { // s is the string to search, t is what to search for Ok(vec![Item::Value(Rc::new(Value::from( ctxt.dispatch(stctxt, s)? .to_string() .ends_with(ctxt.dispatch(stctxt, t)?.to_string().as_str()), )))]) } /// XPath contains function. pub fn contains< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { // s is the string to search, t is what to search for Ok(vec![Item::Value(Rc::new(Value::from( ctxt.dispatch(stctxt, s)? .to_string() .contains(ctxt.dispatch(stctxt, t)?.to_string().as_str()), )))]) } /// XPath substring function. pub fn substring< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, t: &Transform<N>, l: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { // must have two or three arguments. // s is the string to search, // t is the index to start at, // l is the length of the substring at extract (or the rest of the string if missing) match l { Some(m) => Ok(vec![Item::Value(Rc::new(Value::from( ctxt.dispatch(stctxt, s)? .to_string() .graphemes(true) .skip(ctxt.dispatch(stctxt, t)?.to_int()? as usize - 1) .take(ctxt.dispatch(stctxt, m)?.to_int()? as usize) .collect::<String>(), )))]), None => Ok(vec![Item::Value(Rc::new(Value::from( ctxt.dispatch(stctxt, s)? .to_string() .graphemes(true) .skip(ctxt.dispatch(stctxt, t)?.to_int()? as usize - 1) .collect::<String>(), )))]), } } /// XPath substring-before function. pub fn substring_before< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { // s is the string to search, // t is the string to find. let u = ctxt.dispatch(stctxt, s)?.to_string(); match u.find(ctxt.dispatch(stctxt, t)?.to_string().as_str()) { Some(i) => { match u.get(0..i) { Some(v) => Ok(vec![Item::Value(Rc::new(Value::from(v)))]), None => { // This shouldn't happen! Err(Error::new( ErrorKind::Unknown, String::from("unable to extract substring"), )) } } } None => Ok(vec![]), } } /// XPath substring-after function. pub fn substring_after< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { // s is the string to search, // t is the string to find. let u = ctxt.dispatch(stctxt, s)?.to_string(); let v = ctxt.dispatch(stctxt, t)?.to_string(); match u.find(v.as_str()) { Some(i) => { match u.get(i + v.len()..u.len()) { Some(w) => Ok(vec![Item::Value(Rc::new(Value::from(w)))]), None => { // This shouldn't happen! Err(Error::new( ErrorKind::Unknown, String::from("unable to extract substring"), )) } } } None => Ok(vec![]), } } /// XPath normalize-space function. pub fn normalize_space< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, n: &Option<Box<Transform<N>>>, ) -> Result<Sequence<N>, Error> { let s: Result<String, Error> = n.as_ref().map_or_else( || { // Use the current item Ok(ctxt.cur[ctxt.i].to_string()) }, |m| { let t = ctxt.dispatch(stctxt, m)?; Ok(t.to_string()) }, ); // intersperse is the right iterator to use, but it is only available in nightly at the moment s.map(|u| { vec![Item::Value(Rc::new(Value::from( u.split_whitespace().collect::<Vec<&str>>().join(" "), )))] }) } /// XPath translate function. pub fn translate< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, map: &Transform<N>, trn: &Transform<N>, ) -> Result<Sequence<N>, Error> { // s is the string to search // map are the map chars // trn are the translate chars let o = ctxt.dispatch(stctxt, map)?.to_string(); let m: Vec<&str> = o.graphemes(true).collect(); let u = ctxt.dispatch(stctxt, trn)?.to_string(); let t: Vec<&str> = u.graphemes(true).collect(); let mut result: String = String::new(); for c in ctxt.dispatch(stctxt, s)?.to_string().graphemes(true) { let mut a: Option<Option<usize>> = Some(None); for (i, _item) in m.iter().enumerate() { if c == m[i] { if i < t.len() { a = Some(Some(i)); break; } else { // omit this character a = None } } else { // keep looking for a match } } match a { Some(None) => { result.push_str(c); } Some(Some(j)) => result.push_str(t[j]), None => { // omit char } } } Ok(vec![Item::Value(Rc::new(Value::from(result)))]) } /// XPath concat function. All arguments are concatenated into a single string value. pub(crate) fn tr_concat< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, arguments: &Vec<Transform<N>>, ) -> Result<Sequence<N>, Error> { match arguments .iter() .try_fold(String::new(), |mut acc, a| match ctxt.dispatch(stctxt, a) { Ok(b) => { acc.push_str(b.to_string().as_str()); Ok(acc) } Err(err) => Err(err), }) { Ok(r) => Ok(vec![Item::Value(Rc::new(Value::from(r)))]), Err(err) => Err(err), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/controlflow.rs
src/transform/controlflow.rs
//! These functions are for features that control program flow. use std::collections::HashMap; use std::rc::Rc; use url::Url; use crate::item::{Node, Sequence, SequenceTrait}; use crate::transform::context::{Context, ContextBuilder, StaticContext}; use crate::transform::{do_sort, Grouping, Order, Transform}; use crate::value::{Operator, Value}; use crate::xdmerror::{Error, ErrorKind}; /// Iterate over the items in a sequence. // TODO: Allow multiple variables pub(crate) fn tr_loop< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, v: &Vec<(String, Transform<N>)>, b: &Transform<N>, ) -> Result<Sequence<N>, Error> { if v.is_empty() { return Ok(vec![]); } // This implementation only supports one variable let mut result = vec![]; for i in ctxt.dispatch(stctxt, &v[0].1)? { // Define a new context with all of the variables declared let lctxt = ContextBuilder::from(ctxt) .variable(v[0].0.clone(), vec![i.clone()]) .build(); let mut t = lctxt.dispatch(stctxt, b)?; result.append(&mut t); } Ok(result) } /// Choose a sequence to return. pub(crate) fn switch< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, v: &Vec<(Transform<N>, Transform<N>)>, o: &Transform<N>, ) -> Result<Sequence<N>, Error> { let mut candidate = ctxt.dispatch(stctxt, o)?; for (t, w) in v { let r = ctxt.dispatch(stctxt, t)?; if r.to_bool() { candidate = ctxt.dispatch(stctxt, w)?; break; } } Ok(candidate) } /// Evaluate a combinator for each item. pub fn for_each< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, g: &Option<Grouping<N>>, s: &Transform<N>, body: &Transform<N>, o: &Vec<(Order, Transform<N>)>, ) -> Result<Sequence<N>, Error> { match g { None => { let mut result: Sequence<N> = Vec::new(); let mut seq = ctxt.dispatch(stctxt, s)?; do_sort(&mut seq, o, ctxt, stctxt)?; for i in seq { let mut v = ContextBuilder::from(ctxt) .context(vec![i.clone()]) .previous_context(Some(i)) .build() .dispatch(stctxt, body)?; result.append(&mut v); } Ok(result) } Some(Grouping::By(b)) => group_by(ctxt, stctxt, b, s, body, o), Some(Grouping::Adjacent(a)) => group_adjacent(ctxt, stctxt, a, s, body, o), Some(Grouping::StartingWith(v)) => group_starting_with(ctxt, stctxt, v, s, body, o), Some(Grouping::EndingWith(v)) => group_ending_with(ctxt, stctxt, v, s, body, o), } } /// Evaluate a combinator for each group of items. fn group_by< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, by: &Vec<Transform<N>>, s: &Transform<N>, body: &Transform<N>, o: &Vec<(Order, Transform<N>)>, ) -> Result<Sequence<N>, Error> { // Each 'by' expression is evaluated to a string key and stored in the hashmap // TODO: this implementation is only supporting a single key let t = by[0].clone(); let mut groups = HashMap::new(); ctxt.dispatch(stctxt, s)?.iter().try_for_each(|i| { // There may be multiple keys returned. // For each one, add this item into the group for that key ContextBuilder::from(ctxt) .context(vec![i.clone()]) .previous_context(Some(i.clone())) .build() .dispatch(stctxt, &t)? .iter() .for_each(|k| { let e: &mut Sequence<N> = groups.entry(k.to_string()).or_default(); e.push(i.clone()); }); Ok(()) })?; if !o.is_empty() { // Build a vector of the groups, and then sort the vector // TODO: support multiple sort keys let mut gr_vec: Vec<(String, Sequence<N>)> = groups.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); gr_vec.sort_by_cached_key(|(k, v)| { // TODO: Don't panic let key_seq = ContextBuilder::from(ctxt) .context(v.clone()) .current_grouping_key(Rc::new(Value::from(k.clone()))) .current_group(v.clone()) .build() .dispatch(stctxt, &o[0].1) .expect("unable to determine key value"); // Assume string data type for now // TODO: support number data type // TODO: support all data types key_seq.to_string() }); if o[0].0 == Order::Descending { gr_vec.reverse(); } // Now evaluate the body for each group gr_vec.iter().try_fold(vec![], |mut result, (k, v)| { // Set current-group and current-grouping-key let mut r = ContextBuilder::from(ctxt) .current_grouping_key(Rc::new(Value::from(k.clone()))) .current_group(v.clone()) .build() .dispatch(stctxt, body)?; result.append(&mut r); Ok(result) }) } else { // Now evaluate the body for each group groups.iter().try_fold(vec![], |mut result, (k, v)| { // Set current-group and current-grouping-key let mut r = ContextBuilder::from(ctxt) .current_grouping_key(Rc::new(Value::from(k.clone()))) .current_group(v.clone()) .build() .dispatch(stctxt, body)?; result.append(&mut r); Ok(result) }) } } /// Evaluate a combinator for each group of items. 'adj' is an expression that is evaluated for each selected item. It must resolve to a singleton item. The first item starts the first group. For the second and subsequent items, if the 'adj' item is the same as the previous item then the item is added to the same group. Otherwise a new group is started. fn group_adjacent< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, adj: &Vec<Transform<N>>, s: &Transform<N>, body: &Transform<N>, o: &Vec<(Order, Transform<N>)>, ) -> Result<Sequence<N>, Error> { // TODO: this implementation is only supporting a single key let t = adj[0].clone(); let mut groups = Vec::new(); let sel = ctxt.dispatch(stctxt, s)?; if sel.is_empty() { return Ok(vec![]); } else { let mut curgrp = vec![sel[0].clone()]; let mut curkey = ContextBuilder::from(ctxt) .context(vec![sel[1].clone()]) .build() .dispatch(stctxt, &t)?; if curkey.len() != 1 { return Err(Error::new( ErrorKind::Unknown, String::from("group-adjacent attribute must evaluate to a single item"), )); } sel.iter().skip(1).try_for_each(|i| { let thiskey = ContextBuilder::from(ctxt) .context(vec![i.clone()]) .previous_context(Some(i.clone())) .build() .dispatch(stctxt, &t)?; if thiskey.len() == 1 { if curkey[0].compare(&thiskey[0], Operator::Equal)? { // Append to the current group curgrp.push(i.clone()) } else { // Close the previous group, start a new group with this item as its first member groups.push((curkey.to_string(), curgrp.clone())); curgrp = vec![i.clone()]; curkey = thiskey; } Ok(()) } else { Err(Error::new( ErrorKind::Unknown, String::from("group-adjacent attribute must evaluate to a single item"), )) } })?; // Close the last group groups.push((curkey.to_string(), curgrp)) } if !o.is_empty() { // Build a vector of the groups, and then sort the vector // TODO: support multiple sort keys let mut gr_vec: Vec<(String, Sequence<N>)> = groups.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); gr_vec.sort_by_cached_key(|(k, v)| { // TODO: Don't panic let key_seq = ContextBuilder::from(ctxt) .context(v.clone()) .current_grouping_key(Rc::new(Value::from(k.clone()))) .current_group(v.clone()) .build() .dispatch(stctxt, &o[0].1) .expect("unable to determine key value"); // Assume string data type for now // TODO: support number data type // TODO: support all data types key_seq.to_string() }); if o[0].0 == Order::Descending { gr_vec.reverse(); } // Now evaluate the body for each group gr_vec.iter().try_fold(vec![], |mut result, (k, v)| { // Set current-group and current-grouping-key let mut r = ContextBuilder::from(ctxt) .current_grouping_key(Rc::new(Value::from(k.clone()))) .current_group(v.clone()) .build() .dispatch(stctxt, body)?; result.append(&mut r); Ok(result) }) } else { // Now evaluate the body for each group groups.iter().try_fold(vec![], |mut result, (k, v)| { // Set current-group and current-grouping-key let mut r = ContextBuilder::from(ctxt) .current_grouping_key(Rc::new(Value::from(k.clone()))) .current_group(v.clone()) .build() .dispatch(stctxt, body)?; result.append(&mut r); Ok(result) }) } } /// Evaluate a combinator for each group of items. fn group_starting_with< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( _ctxt: &Context<N>, _stctxt: &mut StaticContext<N, F, G, H>, _pat: &Vec<Transform<N>>, _s: &Transform<N>, _body: &Transform<N>, _o: &Vec<(Order, Transform<N>)>, ) -> Result<Sequence<N>, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } /// Evaluate a combinator for each group of items. pub fn group_ending_with< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( _ctxt: &Context<N>, _stctxt: &mut StaticContext<N, F, G, H>, _pat: &Vec<Transform<N>>, _s: &Transform<N>, _body: &Transform<N>, _o: &Vec<(Order, Transform<N>)>, ) -> Result<Sequence<N>, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/construct.rs
src/transform/construct.rs
//! These functions construct nodes, possibly destined for the result document. use crate::item::{Node, NodeType, Sequence, SequenceTrait}; use crate::qname::QualifiedName; use crate::transform::context::{Context, StaticContext}; use crate::transform::Transform; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use crate::Item; use std::rc::Rc; use url::Url; /// An empty sequence. pub(crate) fn empty<N: Node>(_ctxt: &Context<N>) -> Result<Sequence<N>, Error> { Ok(Sequence::new()) } /// Creates a singleton sequence with the given value pub(crate) fn literal<N: Node>(_ctxt: &Context<N>, val: &Item<N>) -> Result<Sequence<N>, Error> { Ok(vec![val.clone()]) } /// Creates a singleton sequence with a new element node. /// Also create a Namespace node, if required. /// The transform is evaluated to create the content of the element. pub(crate) fn literal_element< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, qn: &Rc<QualifiedName>, c: &Transform<N>, ) -> Result<Sequence<N>, Error> { if ctxt.rd.is_none() { return Err(Error::new( ErrorKind::Unknown, String::from("context has no result document"), )); } let r = ctxt.rd.clone().unwrap(); let mut e = r.new_element(qn.clone())?; // If the element is in a namespace, check if the namespace is in scope. // If not, create and add a Namespace node for that namespace. // Issue: the tree is being created from the bottom up, so we can't know if an ancestor will declare the namespace. // This will result in lots of redundant Namespace nodes. if let Some(ns) = qn.namespace_uri() { e.add_namespace(r.new_namespace(ns, qn.prefix())?)?; } // Create the content of the new element ctxt.dispatch(stctxt, c)?.iter().try_for_each(|i| { // Item could be a Node or text match i { Item::Node(t) => { match t.node_type() { NodeType::Attribute => e.add_attribute(t.clone()), // TODO: Also check namespace of attribute NodeType::Namespace => e.add_namespace(t.clone()), _ => e.push(t.deep_copy()?), } } _ => { // Add the Value as a text node let n = r.new_text(Rc::new(Value::from(i.to_string())))?; e.push(n) } } })?; // TODO: remove redundant namespace declarations from the newly added child elements Ok(vec![Item::Node(e)]) } /// Creates a singleton sequence with a new element node. /// The name is interpreted as an AVT to determine the element name. /// The transform is evaluated to create the content of the element. pub(crate) fn element< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, qn: &Transform<N>, c: &Transform<N>, ) -> Result<Sequence<N>, Error> { if ctxt.rd.is_none() { return Err(Error::new( ErrorKind::Unknown, String::from("context has no result document"), )); } let r = ctxt.rd.clone().unwrap(); let qnavt = QualifiedName::try_from(ctxt.dispatch(stctxt, qn)?.to_string().as_str())?; let mut e = r.new_element(Rc::new(qnavt))?; ctxt.dispatch(stctxt, c)?.iter().try_for_each(|i| { // Item could be a Node or text match i { Item::Node(t) => match t.node_type() { NodeType::Attribute => e.add_attribute(t.clone()), _ => e.push(t.deep_copy()?), }, _ => { // Add the Value as a text node let n = r.new_text(Rc::new(Value::from(i.to_string())))?; e.push(n) } } })?; Ok(vec![Item::Node(e)]) } /// Creates a new text node. /// The transform is evaluated to create the value of the text node. /// Special characters are escaped, unless disabled. pub(crate) fn literal_text< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, t: &Transform<N>, b: &bool, ) -> Result<Sequence<N>, Error> { if ctxt.rd.is_none() { return Err(Error::new( ErrorKind::Unknown, String::from("context has no result document"), )); } let v = ctxt.dispatch(stctxt, t)?.to_string(); if *b { Ok(vec![Item::Node( ctxt.rd.clone().unwrap().new_text(Rc::new(Value::from(v)))?, )]) } else { Ok(vec![Item::Node( ctxt.rd.clone().unwrap().new_text(Rc::new(Value::from( v.replace('&', "&amp;") .replace('>', "&gt;") .replace('<', "&lt;") .replace('\'', "&apos;") .replace('\"', "&quot;"), )))?, )]) } } /// Creates a singleton sequence with a new attribute node. /// The transform is evaluated to create the value of the attribute. /// TODO: AVT for attribute name pub(crate) fn literal_attribute< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, qn: &Rc<QualifiedName>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { if ctxt.rd.is_none() { return Err(Error::new( ErrorKind::Unknown, String::from("context has no result document"), )); } let a = ctxt.rd.clone().unwrap().new_attribute( qn.clone(), Rc::new(Value::from(ctxt.dispatch(stctxt, t)?.to_string())), )?; Ok(vec![Item::Node(a)]) } /// Creates a singleton sequence with a new comment node. /// The transform is evaluated to create the value of the comment. pub(crate) fn literal_comment< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { if ctxt.rd.is_none() { return Err(Error::new( ErrorKind::Unknown, String::from("context has no result document"), )); } let a = ctxt .rd .clone() .unwrap() .new_comment(Rc::new(Value::from(ctxt.dispatch(stctxt, t)?.to_string())))?; Ok(vec![Item::Node(a)]) } /// Creates a singleton sequence with a new processing instruction node. /// The transform is evaluated to create the value of the PI. pub(crate) fn literal_processing_instruction< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, name: &Transform<N>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { if ctxt.rd.is_none() { return Err(Error::new( ErrorKind::Unknown, String::from("context has no result document"), )); } let pi = ctxt.rd.clone().unwrap().new_processing_instruction( Rc::new(QualifiedName::new( None, None, ctxt.dispatch(stctxt, name)?.to_string(), )), Rc::new(Value::from(ctxt.dispatch(stctxt, t)?.to_string())), )?; Ok(vec![Item::Node(pi)]) } /// Set an attribute on the context item, which must be an element-type node. /// (TODO: use an expression to select the element) /// If the element does not have an attribute with the given name, create it. /// Otherwise replace the attribute's value with the supplied value. /// Returns an empty sequence. pub(crate) fn set_attribute< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, atname: &Rc<QualifiedName>, v: &Transform<N>, ) -> Result<Sequence<N>, Error> { if ctxt.rd.is_none() { return Err(Error::new( ErrorKind::Unknown, String::from("context has no result document"), )); } match &ctxt.cur[ctxt.i] { Item::Node(n) => match n.node_type() { NodeType::Element => { let od = n.owner_document(); let attval = ctxt.dispatch(stctxt, v)?; if attval.len() == 1 { match attval.first() { Some(Item::Value(av)) => { n.add_attribute(od.new_attribute(atname.clone(), av.clone())?)?; } _ => { n.add_attribute(od.new_attribute( atname.clone(), Rc::new(Value::from(attval.to_string())), )?)?; } } } else { n.add_attribute(od.new_attribute( atname.clone(), Rc::new(Value::from(attval.to_string())), )?)?; } } _ => { return Err(Error::new( ErrorKind::Unknown, String::from("context item is not an element-type node"), )) } }, _ => { return Err(Error::new( ErrorKind::Unknown, String::from("context item is not a node"), )) } } Ok(vec![]) } /// Construct a [Sequence] of items pub(crate) fn make_sequence< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, items: &Vec<Transform<N>>, ) -> Result<Sequence<N>, Error> { items.iter().try_fold(vec![], |mut acc, i| { let mut r = ctxt.dispatch(stctxt, i)?; acc.append(&mut r); Ok(acc) }) } /// Shallow copy of an item. /// The first argument selects the items to be copied. /// The second argument creates the content of the target item. pub(crate) fn copy< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, c: &Transform<N>, ) -> Result<Sequence<N>, Error> { let sel = ctxt.dispatch(stctxt, s)?; let mut result: Sequence<N> = Vec::new(); for k in sel { let cp = k.shallow_copy()?; result.push(cp.clone()); match cp { Item::Node(mut im) => { for j in ctxt.dispatch(stctxt, c)? { match &j { Item::Value(v) => im.push(im.new_text(v.clone())?)?, Item::Node(n) => match n.node_type() { NodeType::Attribute => im.add_attribute(n.clone())?, _ => im.push(n.clone())?, }, _ => { return Err(Error::new( ErrorKind::NotImplemented, String::from("not yet implemented"), )) } } } } _ => {} } } Ok(result) } /// Deep copy of an item. /// The first argument selects the items to be copied. If not specified then the context item is copied. pub(crate) fn deep_copy< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, s: &Transform<N>, ) -> Result<Sequence<N>, Error> { let sel = ctxt.dispatch(stctxt, s)?; let mut result: Sequence<N> = Vec::new(); for k in sel { result.push(k.deep_copy()?); } Ok(result) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/context.rs
src/transform/context.rs
/*! Context for a transformation A dynamic and static context for a transformation. These are both necessary to give the transformation all the data it needs to performs its functions. The dynamic [Context] stores data that changes. It is frequently cloned to create a new context. A [ContextBuilder] can be used to create the dynamic context incrementally. The [StaticContext] stores immutable data and is not cloneable. A [StaticContextBuilder] can be used to create the static context incrementally. A [Context] is used to evaluate a [Transform]. The evaluate method matches the current item to a template and then evaluates the body of that template. The dispatch method directly evaluates a given [Transform]. */ use crate::item::{Node, Sequence}; use crate::output::OutputDefinition; #[allow(unused_imports)] use crate::pattern::Pattern; use crate::qname::QualifiedName; use crate::transform::booleans::*; use crate::transform::callable::{invoke, Callable}; use crate::transform::construct::*; use crate::transform::controlflow::*; use crate::transform::datetime::*; use crate::transform::functions::*; use crate::transform::grouping::*; use crate::transform::keys::{key, populate_key_values}; use crate::transform::logic::*; use crate::transform::misc::*; use crate::transform::navigate::*; use crate::transform::numbers::*; use crate::transform::strings::*; use crate::transform::template::{apply_imports, apply_templates, next_match, Template}; use crate::transform::variables::{declare_variable, reference_variable}; use crate::transform::Transform; use crate::xdmerror::Error; use crate::{ErrorKind, Item, SequenceTrait, Value}; use std::cmp::Ordering; use std::collections::HashMap; use std::rc::Rc; use url::Url; //pub type Message = FnMut(&str) -> Result<(), Error>; /// The transformation context. This is the dynamic context. /// The static parts of the context are in a separate structure. /// Contexts are immutable, but frequently are cloned to provide a new context. /// Although it is optional, it would be very unusual not to set a result document in a context since nodes cannot be created in the result without one. #[derive(Clone, Debug)] pub struct Context<N: Node> { pub(crate) cur: Sequence<N>, // The current context pub(crate) i: usize, // The index to the item that is the current context item pub(crate) previous_context: Option<Item<N>>, // The "current" XPath item, which is really the context item for the invoking context. See XSLT 20.4.1. pub(crate) depth: usize, // Depth of evaluation pub(crate) rd: Option<N>, // Result document // There is no distinction between built-in and user-defined templates // Built-in templates have no priority and no document order pub(crate) templates: Vec<Rc<Template<N>>>, pub(crate) current_templates: Vec<Rc<Template<N>>>, // Named templates and functions pub(crate) callables: HashMap<QualifiedName, Callable<N>>, // Variables, with scoping pub(crate) vars: HashMap<String, Vec<Sequence<N>>>, // Grouping pub(crate) current_grouping_key: Option<Rc<Value>>, pub(crate) current_group: Sequence<N>, // Keys // The declaration of a key. Keys are named, and each key can have multiple definitions. // Each definition is the pattern that matches nodes and the expression that computes the key value. pub(crate) keys: HashMap<String, Vec<(Pattern<N>, Transform<N>)>>, // The calculated values of keys. pub(crate) key_values: HashMap<String, HashMap<String, Vec<N>>>, // Output control pub(crate) od: OutputDefinition, pub(crate) base_url: Option<Url>, // Namespace resolution. If any transforms contain a QName that needs to be resolved to an EQName, // then these prefix -> URI mappings are used. These are usually derived from the stylesheet document. //pub(crate) namespaces: Vec<HashMap<Option<String>, String>>, } impl<N: Node> Context<N> { pub fn new() -> Self { Context { cur: Sequence::new(), i: 0, previous_context: None, depth: 0, rd: None, templates: vec![], current_templates: vec![], callables: HashMap::new(), vars: HashMap::new(), current_grouping_key: None, current_group: Sequence::new(), keys: HashMap::new(), key_values: HashMap::new(), od: OutputDefinition::new(), base_url: None, } } /// Sets the context item. pub fn context(&mut self, s: Sequence<N>, i: usize) { self.cur = s; self.i = i; } /// Sets the "current" item. pub fn previous_context(&mut self, i: Item<N>) { self.previous_context = Some(i); } /// Sets the result document. Any nodes created by the transformation are owned by this document. pub fn result_document(&mut self, rd: N) { self.rd = Some(rd); } /// Declare a key pub fn declare_key(&mut self, name: String, m: Pattern<N>, u: Transform<N>) { if let Some(v) = self.keys.get_mut(&name) { v.push((m, u)) } else { self.keys.insert(name.clone(), vec![(m, u)]); } // Initialise the key values store with an empty hashmap if self.key_values.get_mut(&name).is_some() { // Already initialised } else { self.key_values.insert(name, HashMap::new()); } } /// Calculate the key values for a source document pub fn populate_key_values< F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( &mut self, stctxt: &mut StaticContext<N, F, G, H>, sd: N, ) -> Result<(), Error> { populate_key_values(self, stctxt, sd) } pub fn dump_key_values(&self) { self.key_values.iter().for_each(|(k, v)| { println!("key \"{}\":", k); v.iter() .for_each(|(kk, vv)| println!("\tvalue \"{}\" {} nodes", kk, vv.len())) }) } /// Add a named attribute set. This replaces any previously declared attribute set with the same name pub fn attribute_set(&mut self, _name: QualifiedName, _body: Vec<Transform<N>>) {} /// Set the value of a variable. If the variable already exists, then this creates a new inner scope. pub(crate) fn var_push(&mut self, name: String, value: Sequence<N>) { match self.vars.get_mut(name.as_str()) { Some(u) => { // If the variable already has a value, then this is a new, inner scope u.push(value); } None => { // Otherwise this is the first scope for the variable self.vars.insert(name, vec![value]); } } } /// Remove a variable #[allow(dead_code)] fn var_pop(&mut self, name: String) { self.vars.get_mut(name.as_str()).map(|u| u.pop()); } #[allow(dead_code)] pub(crate) fn dump_vars(&self) -> String { self.vars.iter().fold(String::new(), |mut acc, (k, v)| { acc.push_str(format!("{}==\"{}\", ", k, v[0].to_string()).as_str()); acc }) } /// Callable components: named templates and user-defined functions pub fn callable_push(&mut self, qn: QualifiedName, c: Callable<N>) { self.callables.insert(qn, c); } /// Returns the Base URL. #[allow(dead_code)] fn baseurl(&self) -> Option<Url> { self.base_url.clone() } /// Set the Base URL. This is used to resolve relative URLs. #[allow(dead_code)] fn set_baseurl(&mut self, url: Url) { self.base_url = Some(url); } /// Evaluate finds a template matching the current item and evaluates the body of the template, /// returning the resulting [Sequence]. /// ```rust /// use std::rc::Rc; /// use url::Url; /// use xrust::ErrorKind; /// use xrust::xdmerror::Error; /// use xrust::item::{Item, Sequence, SequenceTrait, Node, NodeType}; /// use xrust::transform::Transform; /// use xrust::transform::context::{Context, StaticContext, StaticContextBuilder}; /// use xrust::trees::smite::RNode; /// use xrust::parser::xml::parse; /// use xrust::xslt::from_document; /// /// // A little helper function to parse a string to a Document Node /// fn make_from_str(s: &str) -> RNode { /// let mut d = RNode::new_document(); /// parse(d.clone(), s, None) /// .expect("failed to parse XML"); /// d /// } /// /// let sd = Item::Node(make_from_str("<Example/>")); /// let style = make_from_str("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> /// <xsl:template match='/'><xsl:apply-templates/></xsl:template> /// <xsl:template match='child::Example'>This template will match</xsl:template> /// </xsl:stylesheet>"); /// let mut stctxt = StaticContextBuilder::new() /// .message(|_| Ok(())) /// .fetcher(|_| Ok(String::new())) /// .parser(|s| Ok(make_from_str(s))) /// .build(); /// let mut context = from_document(style, None, |s| Ok(make_from_str(s)), |_| Ok(String::new())).expect("unable to compile stylesheet"); /// context.context(vec![sd], 0); /// context.result_document(make_from_str("<Result/>")); /// let sequence = context.evaluate(&mut stctxt).expect("evaluation failed"); /// assert_eq!(sequence.to_string(), "This template will match") /// ``` pub fn evaluate< F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( &self, stctxt: &mut StaticContext<N, F, G, H>, ) -> Result<Sequence<N>, Error> { if self.cur.is_empty() { Ok(Sequence::new()) } else { self.cur.get(self.i).map_or_else( || { Err(Error::new( ErrorKind::DynamicAbsent, String::from("bad index into current sequence"), )) }, |i| { // There may be 0, 1, or more matching templates. // If there are more than one with the same priority and import level, // then take the one with the higher document order. let templates = self.find_templates(stctxt, i, &None)?; match templates.len() { 0 => Err(Error::new( ErrorKind::DynamicAbsent, String::from("no matching template"), )), 1 => self.dispatch(stctxt, &templates[0].body), _ => { if templates[0].priority == templates[1].priority && templates[0].import.len() == templates[1].import.len() { let mut candidates: Vec<Rc<Template<N>>> = templates .iter() .take_while(|t| { t.priority == templates[0].priority && t.import.len() == templates[0].import.len() }) .cloned() .collect(); candidates.sort_unstable_by(|a, b| { a.document_order.map_or(Ordering::Greater, |v| { b.document_order.map_or(Ordering::Less, |u| v.cmp(&u)) }) }); self.dispatch(stctxt, &candidates.last().unwrap().body) } else { self.dispatch(stctxt, &templates[0].body) } } } }, ) } } /// Find a template with a matching [Pattern] in the given mode. pub fn find_templates< F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( &self, stctxt: &mut StaticContext<N, F, G, H>, i: &Item<N>, m: &Option<Rc<QualifiedName>>, ) -> Result<Vec<Rc<Template<N>>>, Error> { let mut candidates = self.templates .iter() .filter(|t| t.mode == *m) .try_fold(vec![], |mut cand, t| { let e = t.pattern.matches(self, stctxt, i); if e { cand.push(t.clone()) } Ok(cand) })?; if !candidates.is_empty() { // Find the template(s) with the lowest priority. candidates.sort_unstable_by(|a, b| (*a).cmp(b)); Ok(candidates) } else { Err(Error::new( ErrorKind::Unknown, format!("no matching template for item {:?} in mode \"{:?}\"", i, m), )) } } /// Interpret the given [Transform] object /// ```rust /// use std::rc::Rc; /// use url::Url; /// use xrust::xdmerror::{Error, ErrorKind}; /// use xrust::item::{Item, Sequence, SequenceTrait, Node, NodeType}; /// use xrust::transform::{Transform, NodeMatch, NodeTest, KindTest, Axis}; /// use xrust::transform::context::{Context, ContextBuilder, StaticContext, StaticContextBuilder}; /// use xrust::trees::smite::RNode; /// use xrust::parser::xml::parse; /// /// // A little helper function to parse a string to a Document Node /// fn make_from_str(s: &str) -> RNode { /// let mut d = RNode::new_document(); /// parse(d.clone(), s, None) /// .expect("failed to parse XML"); /// d /// } /// /// // Equivalent to "child::*" /// let t = Transform::Step(NodeMatch {axis: Axis::Child, nodetest: NodeTest::Kind(KindTest::Any)}); /// let sd = Item::Node(make_from_str("<Example/>")); /// let mut stctxt = StaticContextBuilder::new() /// .message(|_| Ok(())) /// .fetcher(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) /// .parser(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) /// .build(); /// let context = ContextBuilder::new() /// .context(vec![sd]) /// .build(); /// let sequence = context.dispatch(&mut stctxt, &t).expect("evaluation failed"); /// assert_eq!(sequence.to_xml(), "<Example></Example>") /// ``` pub fn dispatch< F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( &self, stctxt: &mut StaticContext<N, F, G, H>, t: &Transform<N>, ) -> Result<Sequence<N>, Error> { match t { Transform::Root => root(self), Transform::ContextItem => context(self), Transform::CurrentItem => current(self), Transform::Compose(v) => compose(self, stctxt, v), Transform::Step(nm) => step(self, nm), Transform::Filter(t) => filter(self, stctxt, t), Transform::Empty => empty(self), Transform::Literal(v) => literal(self, v), Transform::LiteralElement(qn, t) => literal_element(self, stctxt, qn, t), Transform::Element(qn, t) => element(self, stctxt, qn, t), Transform::LiteralText(t, b) => literal_text(self, stctxt, t, b), Transform::LiteralAttribute(qn, t) => literal_attribute(self, stctxt, qn, t), Transform::LiteralComment(t) => literal_comment(self, stctxt, t), Transform::LiteralProcessingInstruction(n, t) => { literal_processing_instruction(self, stctxt, n, t) } Transform::SetAttribute(qn, v) => set_attribute(self, stctxt, qn, v), Transform::SequenceItems(v) => make_sequence(self, stctxt, v), Transform::Copy(f, t) => copy(self, stctxt, f, t), Transform::DeepCopy(d) => deep_copy(self, stctxt, d), Transform::Or(v) => tr_or(self, stctxt, v), Transform::And(v) => tr_and(self, stctxt, v), Transform::Union(b) => union(self, stctxt, b), Transform::GeneralComparison(o, l, r) => general_comparison(self, stctxt, o, l, r), Transform::ValueComparison(o, l, r) => value_comparison(self, stctxt, o, l, r), Transform::Concat(v) => tr_concat(self, stctxt, v), Transform::Range(s, e) => tr_range(self, stctxt, s, e), Transform::Arithmetic(v) => arithmetic(self, stctxt, v), Transform::Loop(v, b) => tr_loop(self, stctxt, v, b), Transform::Switch(c, o) => switch(self, stctxt, c, o), Transform::ForEach(g, s, b, o) => for_each(self, stctxt, g, s, b, o), Transform::ApplyTemplates(s, m, o) => apply_templates(self, stctxt, s, m, o), Transform::ApplyImports => apply_imports(self, stctxt), Transform::NextMatch => next_match(self, stctxt), Transform::VariableDeclaration(n, v, f, _) => { declare_variable(self, stctxt, n.clone(), v, f) } Transform::VariableReference(n, _) => reference_variable(self, n), Transform::Position => position(self), Transform::Last => last(self), Transform::Count(s) => tr_count(self, stctxt, s), Transform::LocalName(s) => local_name(self, stctxt, s), Transform::Name(s) => name(self, stctxt, s), Transform::String(s) => string(self, stctxt, s), Transform::StartsWith(s, t) => starts_with(self, stctxt, s, t), Transform::EndsWith(s, t) => ends_with(self, stctxt, s, t), Transform::Contains(s, t) => contains(self, stctxt, s, t), Transform::Substring(s, t, l) => substring(self, stctxt, s, t, l), Transform::SubstringBefore(s, t) => substring_before(self, stctxt, s, t), Transform::SubstringAfter(s, t) => substring_after(self, stctxt, s, t), Transform::NormalizeSpace(s) => normalize_space(self, stctxt, s), Transform::Translate(s, m, t) => translate(self, stctxt, s, m, t), Transform::GenerateId(s) => generate_id(self, stctxt, s), Transform::Boolean(b) => boolean(self, stctxt, b), Transform::Not(b) => not(self, stctxt, b), Transform::True => tr_true(self), Transform::False => tr_false(self), Transform::Number(n) => number(self, stctxt, n), Transform::Sum(s) => sum(self, stctxt, s), Transform::Avg(s) => avg(self, stctxt, s), Transform::Min(s) => min(self, stctxt, s), Transform::Max(s) => max(self, stctxt, s), Transform::Floor(n) => floor(self, stctxt, n), Transform::Ceiling(n) => ceiling(self, stctxt, n), Transform::Round(n, p) => round(self, stctxt, n, p), Transform::CurrentGroup => current_group(self), Transform::CurrentGroupingKey => current_grouping_key(self), Transform::CurrentDateTime => current_date_time(self), Transform::CurrentDate => current_date(self), Transform::CurrentTime => current_time(self), Transform::FormatDateTime(t, p, l, c, q) => { format_date_time(self, stctxt, t, p, l, c, q) } Transform::FormatDate(t, p, l, c, q) => format_date(self, stctxt, t, p, l, c, q), Transform::FormatTime(t, p, l, c, q) => format_time(self, stctxt, t, p, l, c, q), Transform::FormatNumber(v, p, d) => format_number(self, stctxt, v, p, d), Transform::FormatInteger(i, s) => format_integer(self, stctxt, i, s), Transform::GenerateIntegers(start_at, select, n) => { generate_integers(self, stctxt, start_at, select, n) } Transform::Key(n, v, _, _) => key(self, stctxt, n, v), Transform::SystemProperty(p, ns) => system_property(self, stctxt, p, ns), Transform::AvailableSystemProperties => available_system_properties(), Transform::Document(uris, base) => document(self, stctxt, uris, base), Transform::Invoke(qn, a, ns) => invoke(self, stctxt, qn, a, ns), Transform::Message(b, s, e, t) => message(self, stctxt, b, s, e, t), Transform::Error(k, m) => tr_error(self, k, m), Transform::NotImplemented(s) => not_implemented(self, s), _ => Err(Error::new( ErrorKind::NotImplemented, "not implemented".to_string(), )), } } } impl<N: Node> From<Sequence<N>> for Context<N> { fn from(value: Sequence<N>) -> Self { Context { cur: value, i: 0, previous_context: None, depth: 0, rd: None, templates: vec![], current_templates: vec![], callables: HashMap::new(), vars: HashMap::new(), keys: HashMap::new(), key_values: HashMap::new(), current_grouping_key: None, current_group: Sequence::new(), od: OutputDefinition::new(), base_url: None, } } } /// Builder for a [Context] pub struct ContextBuilder<N: Node>(Context<N>); impl<N: Node> ContextBuilder<N> { pub fn new() -> Self { ContextBuilder(Context::new()) } pub fn context(mut self, s: Sequence<N>) -> Self { self.0.cur = s; self } pub fn index(mut self, i: usize) -> Self { self.0.i = i; self } pub fn previous_context(mut self, i: Option<Item<N>>) -> Self { self.0.previous_context = i; self } pub fn depth(mut self, d: usize) -> Self { self.0.depth = d; self } pub fn variable(mut self, n: String, v: Sequence<N>) -> Self { self.0.var_push(n, v); self } pub fn variables(mut self, v: HashMap<String, Vec<Sequence<N>>>) -> Self { self.0.vars = v; self } pub fn result_document(mut self, rd: N) -> Self { self.0.rd = Some(rd); self } pub fn template(mut self, t: Template<N>) -> Self { self.0.templates.push(Rc::new(t)); self } pub fn template_all(mut self, v: Vec<Template<N>>) -> Self { for t in v { self.0.templates.push(Rc::new(t)) } self } pub fn current_templates(mut self, c: Vec<Rc<Template<N>>>) -> Self { self.0.current_templates = c; self } pub fn current_group(mut self, c: Sequence<N>) -> Self { self.0.current_group = c; self } pub fn current_grouping_key(mut self, k: Rc<Value>) -> Self { self.0.current_grouping_key = Some(k); self } pub fn output_definition(mut self, od: OutputDefinition) -> Self { self.0.od = od; self } pub fn base_url(mut self, b: Url) -> Self { self.0.base_url = Some(b); self } pub fn callable(mut self, qn: QualifiedName, c: Callable<N>) -> Self { self.0.callables.insert(qn, c); self } pub fn build(self) -> Context<N> { self.0 } } /// Derive a new [Context] from an old [Context]. The context item in the old context becomes the "current" item in the new context. impl<N: Node> From<&Context<N>> for ContextBuilder<N> { fn from(c: &Context<N>) -> Self { if c.cur.len() > c.i { ContextBuilder(c.clone()).previous_context(Some(c.cur[c.i].clone())) } else { ContextBuilder(c.clone()).previous_context(None) } } } /// The static context. This is not cloneable, since it includes the storage of a closure. /// The main feature of the static context is the ability to set up a callback for messages. /// See [StaticContextBuilder] for details. pub struct StaticContext<N: Node, F, G, H> where F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, // Parses a string into a tree H: FnMut(&Url) -> Result<String, Error>, // Fetches the data from a URL { pub(crate) message: Option<F>, pub(crate) parser: Option<G>, pub(crate) fetcher: Option<H>, } impl<N: Node, F, G, H> StaticContext<N, F, G, H> where F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, { pub fn new() -> Self { StaticContext { message: None, parser: None, fetcher: None, } } } /// Builder for a [StaticContext]. /// The main feature of the static context is the ability to set up a callback for messages. /// ```rust /// use std::rc::Rc; /// use xrust::{Error, ErrorKind}; /// use xrust::qname::QualifiedName; /// use xrust::value::Value; /// use xrust::item::{Item, Sequence, SequenceTrait, Node, NodeType}; /// use xrust::trees::smite::RNode; /// use xrust::transform::Transform; /// use xrust::transform::context::{Context, ContextBuilder, StaticContext, StaticContextBuilder}; /// /// let mut message = String::from("no message received"); /// let xform = Transform::LiteralElement( /// Rc::new(QualifiedName::new(None, None, String::from("Example"))), /// Box::new(Transform::SequenceItems(vec![ /// Transform::Message( /// Box::new(Transform::Literal(Item::Value(Rc::new(Value::from("a message from the transformation"))))), /// None, /// Box::new(Transform::Empty), /// Box::new(Transform::Empty), /// ), /// Transform::Literal(Item::Value(Rc::new(Value::from("element content")))), /// ])) /// ); /// let mut context = ContextBuilder::new() /// .result_document(RNode::new_document()) /// .build(); /// let mut static_context = StaticContextBuilder::new() /// .message(|m| {message = String::from(m); Ok(())}) /// .fetcher(|_| Ok(String::new())) /// .parser(|_| Err(Error::new(ErrorKind::NotImplemented, "not implemented"))) /// .build(); /// let sequence = context.dispatch(&mut static_context, &xform).expect("evaluation failed"); /// /// assert_eq!(sequence.to_xml(), "<Example>element content</Example>"); /// assert_eq!(message, "a message from the transformation") /// ``` pub struct StaticContextBuilder< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >(StaticContext<N, F, G, H>); impl<N: Node, F, G, H> StaticContextBuilder<N, F, G, H> where F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, { pub fn new() -> Self { StaticContextBuilder(StaticContext::new()) } pub fn message(mut self, f: F) -> Self { self.0.message = Some(f); self } pub fn parser(mut self, p: G) -> Self { self.0.parser = Some(p); self } pub fn fetcher(mut self, f: H) -> Self { self.0.fetcher = Some(f); self } pub fn build(self) -> StaticContext<N, F, G, H> { self.0 } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/keys.rs
src/transform/keys.rs
//! Support for keys. use crate::item::{Node, Sequence}; use crate::transform::context::{Context, ContextBuilder, StaticContext}; use crate::transform::Transform; use crate::xdmerror::Error; use crate::{Item, SequenceTrait}; use std::collections::HashMap; use url::Url; /// For each key declaration: /// 1. find the nodes in the document that match the pattern /// 2. Evaluate the expression to calculate the key value /// 3. Store the key value -> Node mapping /// NB. an optimisation is to calculate a key's value the first time that key is accessed /// TODO: support composite keys pub(crate) fn populate_key_values< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &mut Context<N>, stctxt: &mut StaticContext<N, F, G, H>, sd: N, ) -> Result<(), Error> { // We have to visit N nodes to compute K keys. // In a typical scenario, N >> K so we want to perform a single pass over the nodes. for n in sd.owner_document().descend_iter() { // Descend visits all nodes except attributes // TODO: support attributes for (name, d) in &ctxt.keys { for (m, u) in d { if m.matches(ctxt, stctxt, &Item::Node(n.clone())) { let newctxt = ContextBuilder::from(&*ctxt) .context(vec![Item::Node(n.clone())]) .build(); let values = newctxt.dispatch(stctxt, u)?; // Each item in values is a value for this key values.iter().for_each(|v| { if let Some(kv) = ctxt.key_values.get_mut(name) { // We've already seen this value, so append to existing mapping if let Some(vv) = kv.get_mut(&v.to_string()) { // This value for this key already has a mapping, so append this node vv.push(n.clone()); } else { // This value for this ley has not been seen before, so create new mapping kv.insert(v.to_string(), vec![n.clone()]); } } else { // Haven't seen this key before, so create new mapping let mut new = HashMap::new(); new.insert(v.to_string(), vec![n.clone()]); ctxt.key_values.insert(name.clone(), new); } }) } } } } Ok(()) } /// Look up the value of a key. The value is evaluated to a Sequence. The interpretation of the sequence depends on the key's composite setting. /// TODO: support composite keys pub fn key< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, name: &Box<Transform<N>>, v: &Box<Transform<N>>, ) -> Result<Sequence<N>, Error> { let keyname = ctxt.dispatch(stctxt, name)?.to_string(); Ok(ctxt.dispatch(stctxt, v)?.iter().fold(vec![], |mut acc, s| { if let Some(u) = ctxt.key_values.get(&keyname) { if let Some(a) = u.get(&s.to_string()) { let mut b: Sequence<N> = a.iter().map(|n| Item::Node(n.clone())).collect(); acc.append(&mut b); acc } else { acc } } else { acc } })) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/navigate.rs
src/transform/navigate.rs
//! Navigation routines use crate::item::{Node, NodeType, Sequence, SequenceTrait}; use crate::transform::context::{Context, ContextBuilder, StaticContext}; use crate::transform::{Axis, NodeMatch, Transform}; use crate::xdmerror::{Error, ErrorKind}; use crate::Item; use url::Url; /// The root node of the context item. pub(crate) fn root<N: Node>(ctxt: &Context<N>) -> Result<Sequence<N>, Error> { if ctxt.cur.is_empty() { Err(Error::new( ErrorKind::ContextNotNode, String::from("no context"), )) } else { // TODO: check all context items. // If any of them is not a Node then error. match &ctxt.cur[0] { Item::Node(n) => match n.node_type() { NodeType::Document => Ok(vec![Item::Node(n.clone())]), _ => n .ancestor_iter() .last() .map_or(Ok(vec![]), |m| Ok(vec![Item::Node(m)])), }, _ => Err(Error::new( ErrorKind::ContextNotNode, String::from("context item is not a node"), )), } } } /// The context item. pub(crate) fn context<N: Node>(ctxt: &Context<N>) -> Result<Sequence<N>, Error> { ctxt.cur.get(ctxt.i).map_or( Err(Error::new( ErrorKind::DynamicAbsent, String::from("no context"), )), |i| Ok(vec![i.clone()]), ) } /// Each transform in the supplied vector is evaluated. /// The sequence returned by a transform is used as the context for the next transform. /// See also XSLT 20.4.1 for how the current item is set. pub(crate) fn compose< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, steps: &Vec<Transform<N>>, ) -> Result<Sequence<N>, Error> { let mut context = ctxt.cur.clone(); let mut current; if ctxt.previous_context.is_none() { if ctxt.cur.is_empty() { current = None } else { current = Some(context[ctxt.i].clone()) } } else { current = ctxt.previous_context.clone() } let mut it = steps.iter(); loop { if let Some(t) = it.next() { // previous context is the last step's context. // If the initial previous context is None, then the current context is also the previous context (XSLT 20.4.1) let new = ContextBuilder::from(ctxt) .context(context.clone()) .previous_context(current) .build() .dispatch(stctxt, t)?; if context.len() > ctxt.i { current = Some(context[ctxt.i].clone()); } else { current = None } context = new; } else { break; } } Ok(context) // steps.iter().try_fold(ctxt.cur.clone(), |seq, t| { // ContextBuilder::from(ctxt) // .current(seq) // .build() // .dispatch(stctxt, t) // }) } /// For each item in the current context, evaluate the given node matching operation. pub(crate) fn step<N: Node>(ctxt: &Context<N>, nm: &NodeMatch) -> Result<Sequence<N>, Error> { match ctxt.cur.iter().try_fold(vec![], |mut acc, i| { match i { Item::Node(n) => { match nm.axis { Axis::SelfAxis => { if nm.matches(n) { acc.push(i.clone()); Ok(acc) } else { Ok(acc) } } Axis::SelfDocument => { if n.node_type() == NodeType::Document { acc.push(i.clone()); Ok(acc) } else { Ok(acc) } } Axis::Child => { let mut s = n.child_iter().filter(|c| nm.matches(c)).fold( Sequence::new(), |mut c, a| { c.push_node(&a); c }, ); acc.append(&mut s); Ok(acc) } Axis::Parent => match n.parent() { Some(p) => { acc.push_node(&p); Ok(acc) } None => Ok(acc), }, Axis::ParentDocument => { // Only matches the Document. // If no parent then return the Document // NB. Document is a special kind of Node match n.node_type() { NodeType::Document => { // The context is the document acc.push(i.clone()); Ok(acc) } _ => Ok(acc), } } Axis::Descendant => { n.descend_iter() .filter(|c| nm.matches(c)) .for_each(|c| acc.push_node(&c)); Ok(acc) } Axis::DescendantOrSelf => { if nm.matches(n) { acc.push(i.clone()) } n.descend_iter() .filter(|c| nm.matches(c)) .for_each(|c| acc.push_node(&c)); Ok(acc) } Axis::DescendantOrSelfOrRoot => { acc.push_node(&n.owner_document()); if nm.matches(n) { acc.push(i.clone()) } n.descend_iter() .filter(|c| nm.matches(c)) .for_each(|c| acc.push_node(&c)); Ok(acc) } Axis::Ancestor => { n.ancestor_iter() .filter(|c| nm.matches(c)) .for_each(|c| acc.push_node(&c)); Ok(acc) } Axis::AncestorOrSelf => { n.ancestor_iter() .filter(|c| nm.matches(c)) .for_each(|c| acc.push_node(&c)); if nm.matches(n) { acc.push(i.clone()) } Ok(acc) } Axis::FollowingSibling => { n.next_iter() .filter(|c| nm.matches(c)) .for_each(|c| acc.push_node(&c)); Ok(acc) } Axis::PrecedingSibling => { n.prev_iter() .filter(|c| nm.matches(c)) .for_each(|c| acc.push_node(&c)); Ok(acc) } Axis::Following => { // XPath 3.3.2.1: the following axis contains all nodes that are descendants of the root of the tree in which the context node is found, are not descendants of the context node, and occur after the context node in document order. // iow, for each ancestor-or-self node, include every next sibling and its descendants let mut bcc = vec![]; // Start with following siblings of self n.next_iter().for_each(|a| { bcc.push(a.clone()); a.descend_iter().for_each(|b| bcc.push(b.clone())); }); // Now traverse ancestors n.ancestor_iter().for_each(|a| { a.next_iter().for_each(|b| { bcc.push(b.clone()); b.descend_iter().for_each(|c| bcc.push(c.clone())); }) }); bcc.iter().filter(|e| nm.matches(*e)).for_each(|g| { acc.push_node(g); }); Ok(acc) } Axis::Preceding => { // XPath 3.3.2.1: the preceding axis contains all nodes that are descendants of the root of the tree in which the context node is found, are not ancestors of the context node, and occur before the context node in document order. // iow, for each ancestor-or-self node, include every previous sibling and its descendants let mut bcc = vec![]; // Start with preceding siblings of self n.prev_iter().for_each(|a| { bcc.push(a.clone()); a.descend_iter().for_each(|b| bcc.push(b.clone())); }); // Now traverse ancestors n.ancestor_iter().for_each(|a| { a.prev_iter().for_each(|b| { bcc.push(b.clone()); b.descend_iter().for_each(|c| bcc.push(c.clone())); }) }); bcc.iter().filter(|e| nm.matches(*e)).for_each(|g| { acc.push_node(g); }); Ok(acc) } Axis::Attribute => { n.attribute_iter() .filter(|a| nm.matches(a)) .for_each(|a| acc.push_node(&a)); Ok(acc) } Axis::SelfAttribute => { if n.node_type() == NodeType::Attribute { acc.push_node(n) } Ok(acc) } _ => Err(Error::new( ErrorKind::NotImplemented, String::from("coming soon"), )), } } _ => Err(Error::new( ErrorKind::Unknown, String::from("context item is not a node"), )), } }) { Ok(mut r) => { // Sort in document order r.sort_unstable_by(|a, b| { get_node_unchecked(a).cmp_document_order(get_node_unchecked(b)) }); // Eliminate duplicates r.dedup_by(|a, b| { get_node(a).map_or(false, |aa| get_node(b).map_or(false, |bb| aa.is_same(bb))) }); Ok(r) } Err(err) => Err(err), } } fn get_node_unchecked<N: Node>(i: &Item<N>) -> &N { match i { Item::Node(n) => n, _ => panic!("not a node"), } } fn get_node<N: Node>(i: &Item<N>) -> Result<&N, Error> { match i { Item::Node(n) => Ok(n), _ => Err(Error::new(ErrorKind::Unknown, String::from("not a node"))), } } /// Remove items that don't match the predicate. pub(crate) fn filter< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, predicate: &Transform<N>, ) -> Result<Sequence<N>, Error> { ctxt.cur.iter().try_fold(vec![], |mut acc, i| { if ContextBuilder::from(ctxt) .context(vec![i.clone()]) .previous_context(ctxt.previous_context.clone()) .build() .dispatch(stctxt, predicate)? .to_bool() { acc.push(i.clone()) } Ok(acc) }) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/transform/logic.rs
src/transform/logic.rs
//! These functions are for features defined in XPath Functions 1.0 and 2.0. use std::rc::Rc; use url::Url; use crate::item::{Item, Node, Sequence, SequenceTrait}; use crate::transform::context::{Context, StaticContext}; use crate::transform::Transform; use crate::value::{Operator, Value}; use crate::xdmerror::{Error, ErrorKind}; /// Return the disjunction of all of the given functions. pub(crate) fn tr_or< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, v: &Vec<Transform<N>>, ) -> Result<Sequence<N>, Error> { // Future: Evaluate every operand to check for dynamic errors let mut b = false; let mut i = 0; loop { match v.get(i) { Some(a) => { if ctxt.dispatch(stctxt, a)?.to_bool() { b = true; break; } i += 1; } None => break, } } Ok(vec![Item::Value(Rc::new(Value::from(b)))]) } /// Return the conjunction of all of the given functions. pub(crate) fn tr_and< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, v: &Vec<Transform<N>>, ) -> Result<Sequence<N>, Error> { // Future: Evaluate every operand to check for dynamic errors let mut b = true; let mut i = 0; loop { match v.get(i) { Some(a) => { if !ctxt.dispatch(stctxt, a)?.to_bool() { b = false; break; } i += 1; } None => break, } } Ok(vec![Item::Value(Rc::new(Value::from(b)))]) } /// General comparison of two sequences. pub(crate) fn general_comparison< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, o: &Operator, l: &Transform<N>, r: &Transform<N>, ) -> Result<Sequence<N>, Error> { let left = ctxt.dispatch(stctxt, l)?; let right = ctxt.dispatch(stctxt, r)?; let mut b = false; for i in left { for j in &right { b = i.compare(j, *o).unwrap(); if b { break; } } if b { break; } } Ok(vec![Item::Value(Rc::new(Value::from(b)))]) } /// Value comparison of two singleton sequences. pub(crate) fn value_comparison< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, o: &Operator, l: &Transform<N>, r: &Transform<N>, ) -> Result<Sequence<N>, Error> { let left = ctxt.dispatch(stctxt, l)?; if left.len() != 1 { return Err(Error::new( ErrorKind::TypeError, String::from("left-hand sequence is not a singleton sequence"), )); } let right = ctxt.dispatch(stctxt, r)?; if right.len() != 1 { return Err(Error::new( ErrorKind::TypeError, String::from("right-hand sequence is not a singleton sequence"), )); } Ok(vec![Item::Value(Rc::new(Value::from( left[0].compare(&right[0], *o)?, )))]) } /// Each function in the supplied vector is evaluated, and the resulting sequences are combined into a single sequence. /// All items must be nodes. /// TODO: eliminate duplicates, sort by document order (XPath 3.1 3.4.2). pub(crate) fn union< N: Node, F: FnMut(&str) -> Result<(), Error>, G: FnMut(&str) -> Result<N, Error>, H: FnMut(&Url) -> Result<String, Error>, >( ctxt: &Context<N>, stctxt: &mut StaticContext<N, F, G, H>, branches: &Vec<Transform<N>>, ) -> Result<Sequence<N>, Error> { let mut result = vec![]; for b in branches { let mut c = ctxt.dispatch(stctxt, b)?; if c.iter().any(|f| !f.is_node()) { return Err(Error::new( ErrorKind::TypeError, "all operands must be nodes", )); } result.append(&mut c) } // TODO: eliminate duplicates and sort into document order Ok(result) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/testutils/item_value.rs
src/testutils/item_value.rs
#[macro_export] macro_rules! item_value_tests ( ( $x:ty ) => { use std::rc::Rc; use xrust::value::Value; use xrust::item::{Sequence, SequenceTrait, Item}; #[test] fn item_value_string_empty_to_bool() { assert_eq!(Item::<$x>::Value(Rc::new(Value::from(""))).to_bool(), false) } #[test] fn item_value_string_nonempty_to_bool() { assert_eq!(Item::<$x>::Value(Rc::new(Value::from("false"))).to_bool(), true) } #[test] fn item_value_int_zero_to_bool() { assert_eq!(Item::<$x>::Value(Rc::new(Value::from(0))).to_bool(), false) } #[test] fn item_value_int_nonzero_to_bool() { assert_eq!(Item::<$x>::Value(Rc::new(Value::from(42))).to_bool(), true) } #[test] fn item_value_string_to_int() { match (Item::<$x>::Value(Rc::new(Value::from("1"))).to_int()) { Ok(i) => assert_eq!(i, 1), Err(_) => { panic!("to_int() failed") } } } #[test] fn item_value_string_to_double() { assert_eq!(Item::<$x>::Value(Rc::new(Value::from("2.0"))).to_double(), 2.0) } #[test] fn sequence() { let _s = Sequence::<$x>::new(); assert!(true) } } );
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/testutils/pattern_tests.rs
src/testutils/pattern_tests.rs
#[macro_export] macro_rules! pattern_tests ( ( $t:ty , $x:expr , $y:expr ) => { use xrust::pattern::Pattern; #[test] #[should_panic] fn pattern_empty() { let p: Pattern<$t> = Pattern::try_from("").expect("unable to parse empty string"); } #[test] fn pattern_predicate_1_pos() { let p: Pattern<$t> = Pattern::try_from(".[self::a]").expect("unable to parse \".[self::a]\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(a))), true); } #[test] fn pattern_predicate_1_neg() { let p: Pattern<$t> = Pattern::try_from(".[self::a]").expect("unable to parse \".[self::a]\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(b))), false); } #[test] fn pattern_sel_root_pos() { let p: Pattern<$t> = Pattern::try_from("/").expect("unable to parse \"/\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(sd))), true); } #[test] fn pattern_sel_root_neg() { let p: Pattern<$t> = Pattern::try_from("/").expect("unable to parse \"/\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(a))), false); } #[test] fn pattern_sel_1_pos() { let p: Pattern<$t> = Pattern::try_from("child::a").expect("unable to parse \"child::a\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(a))), true); } #[test] fn pattern_sel_1_neg() { let p: Pattern<$t> = Pattern::try_from("child::a").expect("unable to parse \"child::a\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(b))), false); } #[test] fn pattern_sel_2_pos() { let p: Pattern<$t> = Pattern::try_from("child::Test/child::a") .expect("unable to parse \"child::Test/child::a\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(a))), true); } #[test] fn pattern_sel_2_neg() { let p: Pattern<$t> = Pattern::try_from("child::Test/child::a").expect("unable to parse \"child::Test/child::a\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("NotATest"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(a))), false); } #[test] fn pattern_sel_text_kind_1_pos() { let p: Pattern<$t> = Pattern::try_from("child::text()").expect("unable to parse \"child::text()\""); // Setup a source document let mut sd = $x(); let mut t = sd.new_element(QualifiedName::new(None, None, String::from("Test"))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut a = sd.new_element(QualifiedName::new(None, None, String::from("a"))) .expect("unable to create element"); t.push(a.clone()) .expect("unable to append child"); let t_a = sd.new_text(Rc::new(Value::from("first"))) .expect("unable to create text node"); a.push(t_a.clone()) .expect("unable to append text node"); let mut b = sd.new_element(QualifiedName::new(None, None, String::from("b"))) .expect("unable to create element"); t.push(b.clone()) .expect("unable to append child"); let t_b = sd.new_text(Rc::new(Value::from("second"))) .expect("unable to create text node"); b.push(t_b) .expect("unable to append text node"); assert_eq!(p.matches(&Context::new(), &mut StaticContext::<F>::new(), &Rc::new(Item::Node(t_a))), true); } } );
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/testutils/item_node.rs
src/testutils/item_node.rs
#[macro_export] macro_rules! item_node_tests ( ( $x:expr, $y:expr, $z:expr ) => { use std::cmp::Ordering; #[test] fn node_push_content() { let mut d = $x(); let n = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element node"); d.push(n) .expect("unable to add node"); assert_eq!(d.to_xml(), "<Test></Test>") } // This test expects the document to have a single toplevel element // TODO: filter nodes to get elements and check there is only one #[test] fn item_node_type() { assert_eq!( $y(Rc::new(QualifiedName::new(None, None, String::from("Test"))), Value::from("foobar")).node_type(), NodeType::Document ) } #[test] fn item_node_name() { let d = $y(Rc::new(QualifiedName::new(None, None, String::from("Test"))), Value::from("foobar")); match d.child_iter().nth(0) { Some(c) => { assert_eq!(c.node_type(), NodeType::Element); assert_eq!(c.name().to_string(), "Test") } None => panic!("no toplevel element") } } #[test] fn item_node_value() { let d = $y(Rc::new(QualifiedName::new(None, None, String::from("Test"))), Value::from("foobar")); match d.child_iter().nth(0) { Some(c) => { assert_eq!(c.node_type(), NodeType::Element); assert_eq!(c.name().to_string(), "Test"); let mut it = c.child_iter(); match it.next() { Some(t) => { assert_eq!(t.node_type(), NodeType::Text); assert_eq!(t.value().to_string(), "foobar"); match it.next() { Some(_) => panic!("unexpected child node"), None => assert!(true) } } None => panic!("root element does not have child node") } } None => panic!("no toplevel element") } } #[test] fn item_node_pop() { let mut d = $x(); let mut new = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element node"); d.push(new.clone()) .expect("unable to add node"); assert_eq!(d.to_xml(), "<Test></Test>"); let mut e = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Foo")))) .expect("unable to create element node"); new.push(e.clone()) .expect("unable to add node"); let mut f = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Bar")))) .expect("unable to create element node"); e.push(f) .expect("unable to add node"); assert_eq!(d.to_xml(), "<Test><Foo><Bar></Bar></Foo></Test>"); e.pop() .expect("unable to remove node"); assert_eq!(d.to_xml(), "<Test></Test>") } #[test] fn item_node_insert_before() { let mut d = $x(); let mut new = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element node"); d.push(new.clone()) .expect("unable to add node"); assert_eq!(d.to_xml(), "<Test></Test>"); let mut e = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Foo")))) .expect("unable to create element node"); new.push(e.clone()) .expect("unable to add node"); let mut f = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Bar")))) .expect("unable to create element node"); e.push(f.clone()) .expect("unable to add node"); assert_eq!(d.to_xml(), "<Test><Foo><Bar></Bar></Foo></Test>"); let g = d.new_element(Rc::new(QualifiedName::new(None, None, String::from("Inserted")))) .expect("unable to create element node"); f.insert_before(g) .expect("unable to insert element"); assert_eq!(d.to_xml(), "<Test><Foo><Inserted></Inserted><Bar></Bar></Foo></Test>") } #[test] fn item_node_to_string_doc() { let d = $y(Rc::new(QualifiedName::new(None, None, String::from("Test"))), Value::from("foobar")); assert_eq!(d.to_string(), "foobar") } #[test] fn item_node_to_xml_doc() { let d = $y(Rc::new(QualifiedName::new(None, None, String::from("Test"))), Value::from("foobar")); assert_eq!(d.to_xml(), "<Test>foobar</Test>") } #[test] fn item_node_parent() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); l1.push(l2.clone()) .expect("unable to append child"); assert_eq!(l2.parent().unwrap().name().to_string(), "Level-1") } #[test] fn item_node_ancestor() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let mut l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); l1.push(l2.clone()) .expect("unable to append child"); let leaf = sd.new_text(Rc::new(Value::from("leaf node"))) .expect("unable to create text node"); l2.push(leaf.clone()) .expect("unable to append child"); let mut aiter = leaf.ancestor_iter(); assert_eq!(aiter.next().unwrap().name().to_string(), "Level-2"); assert_eq!(aiter.next().unwrap().name().to_string(), "Level-1"); assert_eq!(aiter.next().unwrap().name().to_string(), "Test"); assert_eq!(aiter.next().unwrap().node_type(), NodeType::Document); match aiter.next() { None => {}, _ => panic!("iterator should have no more items") } } #[test] fn item_node_owner_doc() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let mut l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); l1.push(l2.clone()) .expect("unable to append child"); let leaf = sd.new_text(Rc::new(Value::from("leaf node"))) .expect("unable to create text node"); l2.push(leaf.clone()) .expect("unable to append child"); let od = leaf.owner_document(); assert_eq!(od.node_type(), NodeType::Document); } #[test] fn item_node_owner_doc_root() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let mut l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); l1.push(l2.clone()) .expect("unable to append child"); let leaf = sd.new_text(Rc::new(Value::from("leaf node"))) .expect("unable to create text node"); l2.push(leaf.clone()) .expect("unable to append child"); let od = sd.owner_document(); assert_eq!(od.node_type(), NodeType::Document); } #[test] fn item_node_children() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let mut l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); t.push(l2.clone()) .expect("unable to append child"); let leaf = sd.new_text(Rc::new(Value::from("leaf node"))) .expect("unable to create text node"); t.push(leaf.clone()) .expect("unable to append child"); let mut citer = t.child_iter(); assert_eq!(citer.next().unwrap().name().to_string(), "Level-1"); assert_eq!(citer.next().unwrap().name().to_string(), "Level-2"); assert_eq!(citer.next().unwrap().value().to_string(), "leaf node"); match citer.next() { None => {}, _ => panic!("iterator should have no more items") } } #[test] fn item_node_first_child() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let mut l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); t.push(l2.clone()) .expect("unable to append child"); let leaf = sd.new_text(Rc::new(Value::from("leaf node"))) .expect("unable to create text node"); t.push(leaf.clone()) .expect("unable to append child"); match t.first_child() { Some(f) => assert_eq!(f.name().to_string(), "Level-1"), None => panic!("no first child") } } #[test] fn item_node_descend() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1a = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("A")))) .expect("unable to create element"); t.push(l1a.clone()) .expect("unable to append child"); let mut l1b = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("B")))) .expect("unable to create element"); t.push(l1b.clone()) .expect("unable to append child"); let mut l2aa = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("A")))) .expect("unable to create element"); l1a.push(l2aa.clone()) .expect("unable to append child"); l2aa.push( sd.new_text(Rc::new(Value::from("AA"))) .expect("unable to create text") ).expect("unable to append text"); let mut l2ab = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("B")))) .expect("unable to create element"); l1a.push(l2ab.clone()) .expect("unable to append child"); l2ab.push( sd.new_text(Rc::new(Value::from("AB"))) .expect("unable to create text") ).expect("unable to append text"); let mut l2ba = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("A")))) .expect("unable to create element"); l1b.push(l2ba.clone()) .expect("unable to append child"); l2ba.push( sd.new_text(Rc::new(Value::from("BA"))) .expect("unable to create text") ).expect("unable to append text"); let mut l2bb = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("B")))) .expect("unable to create element"); l1b.push(l2bb.clone()) .expect("unable to append child"); l2bb.push( sd.new_text(Rc::new(Value::from("BB"))) .expect("unable to create text") ).expect("unable to append text"); let mut diter = t.descend_iter(); assert_eq!(diter.next().unwrap().name().to_string(), "A"); assert_eq!(diter.next().unwrap().name().to_string(), "A"); assert_eq!(diter.next().unwrap().value().to_string(), "AA"); assert_eq!(diter.next().unwrap().name().to_string(), "B"); assert_eq!(diter.next().unwrap().value().to_string(), "AB"); assert_eq!(diter.next().unwrap().name().to_string(), "B"); assert_eq!(diter.next().unwrap().name().to_string(), "A"); assert_eq!(diter.next().unwrap().value().to_string(), "BA"); assert_eq!(diter.next().unwrap().name().to_string(), "B"); assert_eq!(diter.next().unwrap().value().to_string(), "BB"); match diter.next() { None => {}, _ => panic!("iterator should have no more items") } } #[test] fn item_node_next() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let mut l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); t.push(l2.clone()) .expect("unable to append child"); let leaf = sd.new_text(Rc::new(Value::from("leaf node"))) .expect("unable to create text node"); t.push(leaf.clone()) .expect("unable to append child"); let mut niter = l1.next_iter(); assert_eq!(niter.next().unwrap().name().to_string(), "Level-2"); assert_eq!(niter.next().unwrap().value().to_string(), "leaf node"); match niter.next() { None => {}, _ => panic!("iterator should have no more items") } } #[test] fn item_node_prev() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let mut l1 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-1")))) .expect("unable to create element"); t.push(l1.clone()) .expect("unable to append child"); let mut l2 = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Level-2")))) .expect("unable to create element"); t.push(l2.clone()) .expect("unable to append child"); let leaf = sd.new_text(Rc::new(Value::from("leaf node"))) .expect("unable to create text node"); t.push(leaf.clone()) .expect("unable to append child"); let mut piter = leaf.prev_iter(); assert_eq!(piter.next().unwrap().name().to_string(), "Level-2"); assert_eq!(piter.next().unwrap().name().to_string(), "Level-1"); match piter.next() { None => {}, _ => panic!("iterator should have no more items") } } #[test] fn item_node_attr() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let a1 = sd.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("role"))), Rc::new(Value::from("testing")) ).expect("unable to create attribute"); t.add_attribute(a1) .expect("unable to add attribute"); let a2 = sd.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("phase"))), Rc::new(Value::from("one")) ).expect("unable to create element"); t.add_attribute(a2) .expect("unable to add attribute"); // NB. attributes could be returned in a different order assert!( sd.to_xml() == "<Test role='testing' phase='one'></Test>" || sd.to_xml() == "<Test phase='one' role='testing'></Test>" ); let mut aiter = t.attribute_iter(); let v = aiter.next().unwrap().name().to_string(); if v == "role" { assert_eq!(aiter.next().unwrap().name().to_string(), "phase"); } else if v == "phase" { assert_eq!(aiter.next().unwrap().name().to_string(), "role"); } else { panic!("unexpected attribute value") } match aiter.next() { None => {}, _ => panic!("iterator should have no more items") } } #[test] fn item_node_shallow_copy_element() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let l = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("content")))) .expect("unable to create element"); t.push(l) .expect("unable to append child"); let it = Item::Node(t.clone()); let u = it.shallow_copy().expect("unable to shallow copy element"); assert_eq!(t.to_xml(), "<Test><content></content></Test>"); assert_eq!(u.to_xml(), "<Test></Test>"); } #[test] fn item_node_cmp_doc_order_1() { let sd = $z(); let b1: Vec<RNode> = sd.descend_iter().filter(|n| n.get_attribute(&Rc::new(QualifiedName::new(None, None, String::from("id")))).to_string() == String::from("b1")).collect(); let b9: Vec<RNode> = sd.descend_iter().filter(|n| n.get_attribute(&Rc::new(QualifiedName::new(None, None, String::from("id")))).to_string() == String::from("b9")).collect(); assert_eq!(b1[0].cmp_document_order(&b9[0]), Ordering::Less) } #[test] fn item_node_cmp_doc_order_2() { let sd = $z(); let b10: Vec<RNode> = sd.descend_iter().filter(|n| n.get_attribute(&Rc::new(QualifiedName::new(None, None, String::from("id")))).to_string() == String::from("b10")).collect(); let b6: Vec<RNode> = sd.descend_iter().filter(|n| n.get_attribute(&Rc::new(QualifiedName::new(None, None, String::from("id")))).to_string() == String::from("b6")).collect(); assert_eq!(b10[0].cmp_document_order(&b6[0]), Ordering::Greater) } #[test] fn item_node_partialeq_1_pos() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let a1 = sd.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("role"))), Rc::new(Value::from("testing")) ).expect("unable to create attribute"); t.add_attribute(a1) .expect("unable to add attribute"); let a2 = sd.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("phase"))), Rc::new(Value::from("one")) ).expect("unable to create element"); t.add_attribute(a2) .expect("unable to add attribute"); t.push(sd.new_text(Rc::new(Value::from("my test document"))).expect("unable to create text node")) .expect("unable to add text node"); // The same document as above, but with attributes in a different order let mut od = $x(); let mut u = od.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); od.push(u.clone()) .expect("unable to append child"); let b1 = od.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("role"))), Rc::new(Value::from("testing")) ).expect("unable to create attribute"); let b2 = od.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("phase"))), Rc::new(Value::from("one")) ).expect("unable to create element"); u.add_attribute(b2) .expect("unable to add attribute"); u.push(od.new_text(Rc::new(Value::from("my test document"))).expect("unable to create text node")) .expect("unable to add text node"); u.add_attribute(b1) .expect("unable to add attribute"); assert_eq!(sd == od, true) } #[test] fn item_node_partialeq_1_neg() { let mut sd = $x(); let mut t = sd.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); sd.push(t.clone()) .expect("unable to append child"); let a1 = sd.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("role"))), Rc::new(Value::from("testing")) ).expect("unable to create attribute"); t.add_attribute(a1) .expect("unable to add attribute"); let a2 = sd.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("phase"))), Rc::new(Value::from("one")) ).expect("unable to create element"); t.add_attribute(a2) .expect("unable to add attribute"); t.push(sd.new_text(Rc::new(Value::from("my test document"))).expect("unable to create text node")) .expect("unable to add text node"); // The same document as above, but with attributes in a different order let mut od = $x(); let mut u = od.new_element(Rc::new(QualifiedName::new(None, None, String::from("Test")))) .expect("unable to create element"); od.push(u.clone()) .expect("unable to append child"); let b1 = od.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("role"))), Rc::new(Value::from("testing")) ).expect("unable to create attribute"); let b2 = od.new_attribute( Rc::new(QualifiedName::new(None, None, String::from("phase"))), Rc::new(Value::from("one")) ).expect("unable to create element"); u.add_attribute(b2) .expect("unable to add attribute"); u.push(od.new_text(Rc::new(Value::from("not the same document"))).expect("unable to create text node")) .expect("unable to add text node"); u.add_attribute(b1) .expect("unable to add attribute"); assert_eq!(sd == od, false) } } );
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/testutils/mod.rs
src/testutils/mod.rs
/*! A generic test suite. Most of xrust's modules are written to use the generic Node trait. However, to test their functionality a concrete implementation must be used. Rather than writing, and rewriting, the same set of tests for each concrete implementation, all of the tests have been written as macros. An implementation can then be tested by calling the macros using the type that implements Node. */ pub mod item_node; pub mod item_value; //pub mod pattern_tests;
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/trees/rctree.rs
src/trees/rctree.rs
//! # A tree structure for XDM //! //! Uses Rc and Weak for a fully navigable tree structure, without using interior mutability. //! //! The tree structure has two phases: //! //! * Tree construction and mutation - the tree is built and can be mutated, but is not fully navigable. It can only be traversed in a recursive descent. //! * Tree navigation - the tree is rebuilt using Rc nodes and Weak pointers. The tree is now fully navigable, but cannot be mutated. //! //! The first phase uses [ADoc] and [ANode] objects. The second phase uses [BNode] objects. use std::convert::TryFrom; use std::rc::{Rc, Weak}; use std::collections::HashMap; use crate::xdmerror::*; use crate::qname::*; use crate::output::OutputDefinition; use crate::value::Value; use crate::item::{NodeType, INode, MNode}; use crate::parsexml::content; /// Phase A document. These contain [ANode]s. /// /// A document can have multiple top-level [ANode]s, but to be a well-formed XML document it must have one and only one element-type node. #[derive(Clone, Default, PartialEq)] pub struct ADoc { pub xmldecl: Option<XMLDecl>, pub prologue: Vec<RANode>, pub content: Vec<RANode>, pub epilogue: Vec<RANode>, } impl ADoc { fn new() -> Self { ADoc{..Default::default()} } pub fn set_xmldecl(&mut self, x: XMLDecl) { self.xmldecl = Some(x) } pub fn get_xmldecl(&self) -> &Option<XMLDecl> { &self.xmldecl } fn push_content(&mut self, n: RANode) { self.content.push(n) } // fn push_prologue(&mut self, n: RANode) { // self.prologue.push(n) // } // fn push_epilogue(&mut self, n: RANode) { // self.epilogue.push(n) // } fn to_xml(&self) -> String { // TODO: XML Decl, prologue, epilogue let mut result = String::new(); self.content.iter() .for_each(|c| { result.push_str(c.to_xml().as_str()) }); result } } pub struct ADocBuilder(ADoc); impl ADocBuilder { pub fn new() -> Self { ADocBuilder(ADoc::new()) } pub fn xmldecl(mut self, x: XMLDecl) -> Self { self.0.xmldecl = Some(x); self } pub fn prologue(mut self, p: Vec<Rc<ANode>>) -> Self { self.0.prologue = p; self } pub fn content(mut self, p: Vec<Rc<ANode>>) -> Self { self.0.content = p; self } pub fn epilogue(mut self, p: Vec<Rc<ANode>>) -> Self { self.0.epilogue = p; self } pub fn build(self) -> ADoc { self.0 } } /// A node in a mutable document. #[derive(Clone, Default, PartialEq)] pub struct ANode { node_type: NodeType, children: Vec<RANode>, attributes: HashMap<QualifiedName, Rc<ANode>>, name: Option<QualifiedName>, value: Option<Value>, pi_name: Option<String>, dtd: Option<DTDDecl>, reference: Option<QualifiedName>, // Element(QualifiedName, Vec<ANode>, Vec<ANode>), // Element name, attributes, content // Attribute(QualifiedName, Value), // Text(Value), // PI(String, Value), // Comment(Value), // Comment value is a string // DTD(DTDDecl), // These only occur in the prologue // Reference(QualifiedName), // General entity reference. These need to be resolved before presentation to the application } impl ANode { fn new(n: NodeType) -> Self { ANode{ node_type: n, children: vec![], attributes: HashMap::new(), name: None, value: None, pi_name: None, dtd: None, reference: None, } } pub fn name(&self) -> Option<QualifiedName> { self.name.clone() } pub fn value(&self) -> Option<Value> { self.value.clone() } pub fn pi_name(&self) -> Option<String> { self.pi_name.clone() } pub fn reference(&self) -> Option<QualifiedName> { self.reference.clone() } } pub struct ANodeBuilder(ANode); impl ANodeBuilder { pub fn new(n: NodeType) -> Self { ANodeBuilder(ANode::new(n)) } pub fn name(mut self, qn: QualifiedName) -> Self { self.0.name = Some(qn); self } pub fn value(mut self, v: Value) -> Self { self.0.value = Some(v); self } pub fn pi_name(mut self, pi: String) -> Self { self.0.pi_name = Some(pi); self } pub fn dtd(mut self, d: DTDDecl) -> Self { self.0.dtd = Some(d); self } pub fn reference(mut self, qn: QualifiedName) -> Self { self.0.reference = Some(qn); self } pub fn build(self) -> ANode { self.0 } } pub type RANode = Rc<ANode>; impl MNode for RANode { type NodeIterator = Box<dyn Iterator<Item = RANode>>; type Immutable = RBNode; fn new_element(&self, qn: QualifiedName) -> Result<Self, Error> { Ok(Rc::new( ANodeBuilder::new(NodeType::Element) .name(qn) .build() )) } fn new_text(&self, v: Value) -> Result<Self, Error> { Ok(Rc::new( ANodeBuilder::new(NodeType::Text) .value(v) .build() )) } fn new_attribute(&self, qn: QualifiedName, v: Value) -> Result<Self, Error> { Ok(Rc::new( ANodeBuilder::new(NodeType::Attribute) .name(qn) .value(v) .build() )) } //fn to_inode(&self) -> Self::Immutable { // RBNode::try_from(self).expect("unable to create INode") //} fn node_type(&self) -> NodeType { self.node_type.clone() } fn name(&self) -> QualifiedName { self.name.as_ref().map_or( QualifiedName::new(None, None, String::new()), |n| n.clone() ) } fn value(&self) -> Value { self.value.as_ref().map_or( Value::from(""), |v| v.clone(), ) } fn to_string(&self) -> String { String::from("not yet implemented") } fn to_xml(&self) -> String { match self.node_type { NodeType::Document => { self.children.iter() .fold( String::new(), |mut result, c| { result.push_str(c.to_xml().as_str()); result } ) } NodeType::Element => { let mut result = String::from("<"); result.push_str(self.name().as_ref().to_string().as_str()); result.push_str(">"); self.child_iter() .for_each(|c| { result.push_str(c.to_xml().as_str()) }); result.push_str("</"); result.push_str(self.name().as_ref().to_string().as_str()); result.push_str(">"); result } NodeType::Text => self.value().to_string(), _ => String::new(), // TODO } } fn to_xml_with_options(&self, _od: &OutputDefinition) -> String { String::from("TODO") } fn child_iter(&self) -> Self::NodeIterator { Box::new(ANodeChildren::new(self)) } fn push(&mut self, n: Rc<ANode>) -> Result<(), Error> { match Rc::get_mut(self) { Some(p) => { p.children.push(n); Ok(()) } None => Result::Err(Error::new(ErrorKind::Unknown, String::from("unable to mutate node"))) } } fn add_attribute(&mut self, _att: Rc<ANode>) -> Result<(), Error> { Result::Err(Error::new(ErrorKind::NotImplemented, String::from("not implemented"))) } } pub struct ANodeChildren { v: Vec<Rc<ANode>>, i: usize, } impl ANodeChildren { fn new(n: &Rc<ANode>) -> Self { match n.node_type() { NodeType::Element => { ANodeChildren{v: n.children.clone(), i: 0} } _ => { ANodeChildren{v: vec![], i: 0} } } } } impl Iterator for ANodeChildren { type Item = RANode; fn next(&mut self) -> Option<RANode> { match self.v.get(self.i) { Some(c) => { self.i += 1; Some(c.clone()) } None => None, } } } #[derive(Clone, PartialEq)] pub struct XMLDecl { version: String, encoding: Option<String>, standalone: Option<String> } impl XMLDecl { pub fn new(version: String, encoding: Option<String>, standalone: Option<String>) -> Self { XMLDecl{version, encoding, standalone} } pub fn version(&self) -> String { self.version.clone() } pub fn set_encoding(&mut self, e: String) { self.encoding = Some(e) } pub fn encoding(&self) -> String { self.encoding.as_ref().map_or(String::new(), |e| e.clone()) } pub fn set_standalone(&mut self, s: String) { self.standalone = Some(s) } pub fn standalone(&self) -> String { self.standalone.as_ref().map_or(String::new(), |e| e.clone()) } pub fn to_string(&self) -> String { let mut result = String::from("<?xml version=\""); result.push_str(self.version.as_str()); result.push('"'); self.encoding.as_ref().map(|e| { result.push_str(" encoding=\""); result.push_str(e.as_str()); result.push('"'); }); self.standalone.as_ref().map(|e| { result.push_str(" standalone=\""); result.push_str(e.as_str()); result.push('"'); }); result } } pub struct XMLDeclBuilder(XMLDecl); impl XMLDeclBuilder { pub fn new() -> Self { XMLDeclBuilder(XMLDecl{version: String::new(), encoding: None, standalone: None}) } pub fn version(mut self, v: String) -> Self { self.0.version = v; self } pub fn encoding(mut self, v: String) -> Self { self.0.encoding = Some(v); self } pub fn standalone(mut self, v: String) -> Self { self.0.standalone = Some(v); self } pub fn build(self) -> XMLDecl { self.0 } } /// DTD declarations. /// Only general entities are supported, so far. /// TODO: element, attribute declarations #[derive(Clone, PartialEq)] pub enum DTDDecl { GeneralEntity(QualifiedName, String), } /// A Rc<BNode> is a tree structure that is fully navigable, but immutable. pub type RBNode = Rc<BNode>; /// Convert an [ADoc], which is mutable but not navigable, to a [RBNode]. /// /// Includes entity expansion. impl TryFrom<ADoc> for RBNode { type Error = Error; fn try_from(a: ADoc) -> Result<Self, Self::Error> { let mut ent: HashMap<QualifiedName, Vec<Rc<ANode>>> = HashMap::new(); // Process general entity declarations and store the result in the HashMap. for p in &a.prologue { if p.node_type() == NodeType::Unknown { let DTDDecl::GeneralEntity(n, c) = p.dtd.as_ref().unwrap(); let (rest, e) = content(c.as_str()).map_err(|e| Error::new(ErrorKind::Unknown, e.to_string()))?; if rest.len() != 0 { return Result::Err(Error::new(ErrorKind::Unknown, format!("unable to parse general entity \"{}\"", n.to_string()))) } match ent.insert(n.clone(), e) { Some(_) => { return Result::Err(Error::new(ErrorKind::Unknown, format!("general entity \"{}\" already defined", n.to_string()))) } None => {} } } } Ok(Rc::new_cyclic(|weak_self| { // Descend the A tree, replacing references with their content. // At the same time, convert ANodes to BNodes. let mut new: Vec<RBNode> = vec![]; let mut prologue = a.prologue.into_iter() .map(|n| { BNode::from_anode(n, Some(weak_self.clone()), &ent) }) .collect(); new.append(&mut prologue); let mut content = a.content.into_iter() .map(|n| { BNode::from_anode(n, Some(weak_self.clone()), &ent) }) .collect(); new.append(&mut content); let mut epilogue = a.epilogue.into_iter() .map(|n| { BNode::from_anode(n, Some(weak_self.clone()), &ent) }) .collect(); new.append(&mut epilogue); BNode{ node_type: NodeType::Document, parent: None, children: new, // attributes: HashMap::new(), name: None, value: None, } })) } } /// A node in a phase 2 document. pub struct BNode { node_type: NodeType, parent: Option<Weak<BNode>>, children: Vec<Rc<BNode>>, // attributes: HashMap<QualifiedName, Rc<BNode>>, name: Option<QualifiedName>, value: Option<Value>, } impl BNode { fn from_anode( n: Rc<ANode>, parent: Option<Weak<BNode>>, entities: &HashMap<QualifiedName, Vec<Rc<ANode>>> ) -> Rc<Self> { Rc::new_cyclic(|weak_self| { match n.node_type() { // TODO: attributes NodeType::Element => { let children: Vec<_> = n.child_iter() .map(|child| { BNode::from_anode(child, Some(weak_self.clone()), entities) }) .collect(); BNode{ node_type: NodeType::Element, parent, children, // attributes: HashMap::new(), name: Some(n.name()), value: None } } NodeType::Attribute => { BNode{ node_type: NodeType::Attribute, parent, children: vec![], // attributes: HashMap::new(), name: Some(n.name()), value: Some(n.value()) } } NodeType::Text => { BNode{ node_type: NodeType::Text, parent, children: vec![], // attributes: HashMap::new(), name: None, value: Some(n.value()) } } NodeType::ProcessingInstruction => { BNode{ node_type: NodeType::ProcessingInstruction, parent, children: vec![], // attributes: HashMap::new(), name: Some(QualifiedName::new(None, None, n.pi_name().unwrap())), value: Some(n.value()) } } NodeType::Comment => { BNode{ node_type: NodeType::Comment, parent, children: vec![], // attributes: HashMap::new(), name: None, value: Some(n.value()) } } // a reference will resolve to a vector of BNodes // TODO _ => { BNode{ node_type: NodeType::Unknown, parent, children: vec![], // attributes: HashMap::new(), name: None, value: None } } } }) } } impl INode for RBNode { type NodeIterator = Box<dyn Iterator<Item = RBNode>>; type Mutable = RANode; fn node_type(&self) -> NodeType { self.node_type.clone() } fn name(&self) -> QualifiedName { self.name.as_ref().map_or( QualifiedName::new(None, None, String::new()), |n| n.clone() ) } fn value(&self) -> Value { self.value.as_ref().map_or( Value::from(""), |n| n.clone() ) } fn to_mnode(&self) -> Self::Mutable { Rc::new(ANode{ node_type: self.node_type().clone(), name: Some(self.name()), value: Some(self.value()), children: vec![], attributes: HashMap::new(), // TODO pi_name: None, dtd: None, reference: None, }) } // String value of the node fn to_string(&self) -> String { let mut result = String::new(); match self.node_type { NodeType::Document | NodeType::Element => { self.descend_iter() .filter(|n| n.node_type() == NodeType::Text) .for_each(|n| result.push_str(n.value().to_string().as_str())) } _ => { result.push_str(self.value().to_string().as_str()) } } result } fn to_xml(&self) -> String { let mut result = String::new(); match self.node_type { NodeType::Document => { self.children.iter() .for_each(|c| result.push_str(c.to_xml().as_str())); } NodeType::Element => { let name = self.name.as_ref().unwrap(); result.push_str("<"); result.push_str(name.to_string().as_str()); result.push_str(">"); self.children.iter() .for_each(|c| result.push_str(c.to_xml().as_str())); result.push_str("</"); result.push_str(name.to_string().as_str()); result.push_str(">"); } NodeType::Text => { result.push_str(self.value.as_ref().unwrap().to_string().as_str()) } // TODO: all other types _ => {} } result } fn to_xml_with_options(&self, _od: &OutputDefinition) -> String { String::from("not yet implemented") } fn to_json(&self) -> String { String::from("not yet implemented") } fn child_iter(&self) -> Self::NodeIterator { Box::new(Children::new(self.clone())) } fn ancestor_iter(&self) -> Self::NodeIterator { Box::new(Ancestors::new(self.clone())) } fn descend_iter(&self) -> Self::NodeIterator { Box::new(Descendants::new(self.clone())) } fn next_iter(&self) -> Self::NodeIterator { Box::new(Siblings::new(self.clone(), 1)) } fn prev_iter(&self) -> Self::NodeIterator { Box::new(Siblings::new(self.clone(), -1)) } fn attribute_iter(&self) -> Self::NodeIterator { Box::new(Attributes::new(self.clone())) } } pub struct Children { v: Vec<RBNode>, i: usize, } impl Children { fn new(n: RBNode) -> Self { Children{v: n.children.clone(), i: 0} } } impl Iterator for Children { type Item = RBNode; // TODO fn next(&mut self) -> Option<RBNode> { match self.v.get(self.i) { Some(c) => { self.i += 1; Some(c.clone()) } None => None, } } } pub struct Ancestors { cur: RBNode, } impl Ancestors { fn new(n: RBNode) -> Self { Ancestors{cur: n.clone()} } } impl Iterator for Ancestors { type Item = RBNode; fn next(&mut self) -> Option<RBNode> { let p = self.cur.parent.as_ref(); match p { None => None, Some(q) => { match Weak::upgrade(q) { None => None, Some(r) => { self.cur = r.clone(); Some(r) } } } } } } // A BDoc is immutable, so the descendants will not change. // This implementation eagerly constructs a list of nodes // to traverse. // An alternative would be to lazily traverse the descendants. pub struct Descendants{ v: Vec<RBNode>, cur: usize, } impl Descendants { fn new(n: RBNode) -> Self { Descendants{ v: n.children.iter() .fold( vec![], |mut acc, c| { let mut d = descendant_add(c); acc.append(&mut d); acc } ), cur: 0, } } } fn descendant_add(n: &RBNode) -> Vec<RBNode> { let mut result = vec![n.clone()]; n.children.iter() .for_each(|c| { let mut l = descendant_add(c); result.append(&mut l); }); result } impl Iterator for Descendants { type Item = RBNode; fn next(&mut self) -> Option<RBNode> { match self.v.get(self.cur) { Some(n) => { self.cur += 1; Some(n.clone()) } None => None, } } } pub struct Siblings(RBNode); impl Siblings { fn new(n: RBNode, _dir: i32) -> Self { Siblings(n.clone()) } } impl Iterator for Siblings { type Item = RBNode; // TODO fn next(&mut self) -> Option<RBNode> { None } } pub struct Attributes(RBNode); impl Attributes { fn new(n: RBNode) -> Self { Attributes(n.clone()) } } impl Iterator for Attributes { type Item = RBNode; // TODO fn next(&mut self) -> Option<RBNode> { None } } #[cfg(test)] mod tests { use super::*; #[test] fn new_a() { let ad = ADocBuilder::new() .content(vec![ Rc::new( ANodeBuilder::new(NodeType::Element) .name(QualifiedName::new(None, None, String::from("Test"))) .build() ) ]) .build(); assert_eq!(ad.to_xml(), "<Test></Test>") } #[test] fn b_from_a() { let ad = ADocBuilder::new() .content(vec![ Rc::new( ANodeBuilder::new(NodeType::Element) .name(QualifiedName::new(None, None, String::from("Test"))) .build() ) ]) .build(); let bd = RBNode::try_from(ad).expect("unable to convert ADoc to BNode document"); assert_eq!(bd.to_xml(), "<Test></Test>") } #[test] fn b_descend() { let mut an1 = Rc::new( ANodeBuilder::new(NodeType::Element) .name(QualifiedName::new(None, None, String::from("Test"))) .build() ); an1.push(Rc::new( ANodeBuilder::new(NodeType::Text) .value(Value::from("one-1")) .build() )) .expect("unable to add node"); let mut an2 = Rc::new( ANodeBuilder::new(NodeType::Element) .name(QualifiedName::new(None, None, String::from("Level1"))) .build() ); let an3 = Rc::new( ANodeBuilder::new(NodeType::Text) .value(Value::from("two")) .build() ); an2.push(an3) .expect("unable to add node"); an1.push(an2) .expect("unable to add node"); let an4 = Rc::new( ANodeBuilder::new(NodeType::Text) .value(Value::from("one-2")) .build() ); an1.push(an4) .expect("unable to add node"); let ad = ADocBuilder::new() .content(vec![an1]) .build(); let bd = RBNode::try_from(ad).expect("unable to convert ADoc to BNode document"); let dit = bd.descend_iter(); assert_eq!(dit.count(), 5) } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/trees/intmuttree.rs
src/trees/intmuttree.rs
/*! # A tree structure for XDM This module implements the Item module's [Node](crate::item::Node) trait. This implementation uses interior mutability to create and manage a tree structure that is both mutable and fully navigable. To create a tree, use [NodeBuilder](crate::trees::intmuttree::NodeBuilder) to make a Document-type node. To add a node, first create it using [NodeBuilder](crate::trees::intmuttree::NodeBuilder), then use a trait method to attach it to the tree. NB. The Item module's Node trait is implemented for Rc\<intmuttree::Node\>. For convenience, this is defined as the type [RNode](crate::trees::intmuttree::RNode). ```rust use std::rc::Rc; use xrust::trees::intmuttree::{Document, NodeBuilder, RNode}; use xrust::item::{Node, NodeType}; use xrust::qname::QualifiedName; use xrust::value::Value; use xrust::xdmerror::Error; pub(crate) type ExtDTDresolver = fn(Option<String>, String) -> Result<String, Error>; // A document always has a NodeType::Document node as the toplevel node. let mut doc = NodeBuilder::new(NodeType::Document).build(); let mut top = NodeBuilder::new(NodeType::Element) .name(QualifiedName::new(None, None, String::from("Top-Level"))) .build(); // Nodes are Rc-shared, so it is cheap to clone them doc.push(top.clone()) .expect("unable to append child node"); top.push( NodeBuilder::new(NodeType::Text) .value(Rc::new(Value::from("content of the element"))) .build() ).expect("unable to append child node"); assert_eq!(doc.to_xml(), "<Top-Level>content of the element</Top-Level>") */ use crate::externals::URLResolver; use crate::item::{Node as ItemNode, NodeType}; use crate::output::OutputDefinition; use crate::parser::xml::parse; use crate::parser::ParserConfig; use crate::qname::QualifiedName; use crate::value::Value; use crate::xdmerror::*; use std::cell::RefCell; use std::cmp::Ordering; use std::collections::hash_map::IntoIter; use std::collections::HashMap; use std::fmt; use std::fmt::{Debug, Formatter}; use std::rc::{Rc, Weak}; //pub(crate) type ExtDTDresolver = fn(Option<String>, String) -> Result<String, Error>; /// An XML document. #[derive(Clone, Default)] pub struct Document { pub xmldecl: Option<XMLDecl>, pub prologue: Vec<RNode>, pub content: Vec<RNode>, pub epilogue: Vec<RNode>, } impl Document { fn new() -> Self { Document { ..Default::default() } } pub fn set_xmldecl(&mut self, x: XMLDecl) { self.xmldecl = Some(x) } pub fn get_xmldecl(&self) -> &Option<XMLDecl> { &self.xmldecl } pub fn push_content(&mut self, n: RNode) { self.content.push(n) } pub fn to_xml(&self) -> String { // TODO: XML Decl, prologue, epilogue let mut result = String::new(); self.content .iter() .for_each(|c| result.push_str(c.to_xml().as_str())); result } pub fn canonical(self) -> Document { let d = match self.xmldecl { None => XMLDecl { version: "1.0".to_string(), encoding: Some("UTF-8".to_string()), standalone: None, }, Some(x) => XMLDecl { version: x.version, encoding: Some("UTF-8".to_string()), standalone: None, }, }; let mut p = vec![]; for pn in self.prologue { if let Ok(pcn) = pn.get_canonical() { p.push(pcn) } } let mut c = vec![]; for cn in self.content { if let Ok(ccn) = cn.get_canonical() { c.push(ccn) } } let mut e = vec![]; for en in self.epilogue { if let Ok(ecn) = en.get_canonical() { e.push(ecn) } } Document { xmldecl: Some(d), prologue: p, content: c, epilogue: e, } } /* /// Expand the general entities in the document content. pub fn expand(&self) -> Result<(), Error> { let mut ent: HashMap<QualifiedName, Vec<RNode>> = HashMap::new(); // Process general entity declarations and store the result in the HashMap. for p in &self.prologue { if p.node_type() == NodeType::Unknown { let DTDDecl::GeneralEntity(n, c) = p.dtd.as_ref().unwrap(); let (rest, e) = content(c.as_str()) .map_err(|e| Error::new(ErrorKind::Unknown, e.to_string()))?; if rest.len() != 0 { return Result::Err(Error::new( ErrorKind::Unknown, format!("unable to parse general entity \"{}\"", n.to_string()), )); } match ent.insert(n.clone(), e) { Some(_) => { return Result::Err(Error::new( ErrorKind::Unknown, format!("general entity \"{}\" already defined", n.to_string()), )) } None => {} } } } // Descend the tree, replacing reference nodes with their content // TODO: Don't Panic self.content .iter() .for_each(|c| expand_node(c.clone(), &ent).expect("unable to expand node")); Ok(()) } */ } impl TryFrom<(String, Option<URLResolver>, Option<String>)> for Document { type Error = Error; fn try_from(s: (String, Option<URLResolver>, Option<String>)) -> Result<Self, Self::Error> { let mut pc = ParserConfig::new(); pc.ext_dtd_resolver = s.1; pc.docloc = s.2; let doc = NodeBuilder::new(NodeType::Document).build(); parse(doc.clone(), s.0.as_str(), Some(pc))?; let result = DocumentBuilder::new().content(vec![doc]).build(); Ok(result) } } impl TryFrom<(&str, Option<URLResolver>, Option<String>)> for Document { type Error = Error; fn try_from(s: (&str, Option<URLResolver>, Option<String>)) -> Result<Self, Self::Error> { let mut pc = ParserConfig::new(); pc.ext_dtd_resolver = s.1; pc.docloc = s.2; let doc = NodeBuilder::new(NodeType::Document).build(); parse(doc.clone(), s.0, Some(pc))?; let result = DocumentBuilder::new().content(vec![doc]).build(); Ok(result) } } impl PartialEq for Document { fn eq(&self, other: &Document) -> bool { self.xmldecl == other.xmldecl && self .content .iter() .zip(other.content.iter()) .fold(true, |acc, (a, b)| acc && a == b) } } impl PartialEq for Node { // TODO: attributes fn eq(&self, other: &Node) -> bool { self.node_type == other.node_type && self.name == other.name && self.value == other.value && self .children .borrow() .iter() .zip(other.children.borrow().iter()) .fold(true, |acc, (a, b)| acc && a == b) } } /* fn expand_node(mut n: RNode, ent: &HashMap<QualifiedName, Vec<RNode>>) -> Result<(), Error> { // TODO: Don't Panic match n.node_type() { NodeType::Reference => ent .get(&n.name()) .map(|d| { for e in d { n.insert_before(e.clone()).expect("unable to insert node") } n.pop().expect("unable to remove node") }) .ok_or(Error::new( ErrorKind::Unknown, String::from("reference to unknown entity"), )), _ => Ok(()), } } */ pub struct DocumentBuilder(Document); impl Default for DocumentBuilder { fn default() -> Self { Self::new() } } impl DocumentBuilder { pub fn new() -> Self { DocumentBuilder(Document::new()) } pub fn xmldecl(mut self, x: XMLDecl) -> Self { self.0.xmldecl = Some(x); self } pub fn prologue(mut self, p: Vec<RNode>) -> Self { self.0.prologue = p; self } pub fn content(mut self, p: Vec<RNode>) -> Self { self.0.content = p; self } pub fn epilogue(mut self, p: Vec<RNode>) -> Self { self.0.epilogue = p; self } pub fn build(self) -> Document { self.0 } } /// A node in a tree. #[derive(Clone, Default)] pub struct Node { node_type: NodeType, parent: RefCell<Option<Weak<Node>>>, children: RefCell<Vec<RNode>>, attributes: RefCell<HashMap<QualifiedName, RNode>>, // name is mutable only so that the namespace URI can be set once the document is parsed. // If we can build a better parser then the RefCell can be removed. name: RefCell<Option<QualifiedName>>, value: Option<Rc<Value>>, pi_name: Option<String>, dtd: Option<DTD>, reference: Option<QualifiedName>, } impl Node { /// Create an empty, unattached node pub fn new(n: NodeType) -> Self { Node { node_type: n, parent: RefCell::new(None), children: RefCell::new(vec![]), attributes: RefCell::new(HashMap::new()), ..Default::default() } } pub fn pi_name(&self) -> Option<String> { self.pi_name.clone() } pub fn reference(&self) -> Option<QualifiedName> { self.reference.clone() } pub fn set_nsuri(&self, uri: String) { let new = match &*self.name.borrow() { Some(old) => QualifiedName::new(Some(uri), old.get_prefix(), old.get_localname()), None => panic!("no node name"), }; let _ = self.name.borrow_mut().insert(new); } } pub type RNode = Rc<Node>; impl ItemNode for RNode { type NodeIterator = Box<dyn Iterator<Item = RNode>>; fn node_type(&self) -> NodeType { self.node_type } fn name(&self) -> QualifiedName { self.name .borrow() .as_ref() .map_or(QualifiedName::new(None, None, String::new()), |n| n.clone()) } fn value(&self) -> Rc<Value> { self.value .as_ref() .map_or(Rc::new(Value::from("")), |v| v.clone()) } fn get_id(&self) -> String { format!("{:p}", &**self as *const Node) } fn to_string(&self) -> String { match self.node_type() { NodeType::Document | NodeType::Element => self .descend_iter() .filter(|c| c.node_type() == NodeType::Text) .fold(String::new(), |mut acc, c| { acc.push_str(c.to_string().as_str()); acc }), NodeType::Text | NodeType::Attribute | NodeType::Comment | NodeType::ProcessingInstruction => self.value().to_string(), _ => String::new(), } } /// Serialise as XML fn to_xml(&self) -> String { to_xml_int(self, &OutputDefinition::new(), vec![], 0) } /// Serialise the node as XML, with options such as indentation. fn to_xml_with_options(&self, od: &OutputDefinition) -> String { to_xml_int(self, od, vec![], 0) } fn is_same(&self, other: &Self) -> bool { Rc::ptr_eq(self, other) } fn document_order(&self) -> Vec<usize> { doc_order(self) } fn cmp_document_order(&self, other: &Self) -> Ordering { let this_order = self.document_order(); let other_order = other.document_order(); // zip the two iterators and compare usizes // let mut it = this_order.iter().zip(other_order.iter()); // Implementation note: fold seems to be consuming all of the items, so try an explicit loop instead // let m = (&mut it).fold( // Ordering::Equal, // |acc, (t, o)| { // if acc == Ordering::Equal { t.cmp(o) } else { acc } // } // ); // and then unzip and compare the remaining vectors, at least one of which should be empty let mut this_it = this_order.iter(); let mut other_it = other_order.iter(); for _i in 0.. { match (this_it.next(), other_it.next()) { (Some(t), Some(o)) => { if t < o { return Ordering::Less; } else if t > o { return Ordering::Greater; } // otherwise continue the loop } (Some(_), None) => return Ordering::Greater, (None, Some(_)) => return Ordering::Less, (None, None) => return Ordering::Equal, } } // Will never reach here Ordering::Equal } fn child_iter(&self) -> Self::NodeIterator { Box::new(Children::new(self)) } fn ancestor_iter(&self) -> Self::NodeIterator { Box::new(Ancestors::new(self)) } fn owner_document(&self) -> Self { if self.node_type() == NodeType::Document { self.clone() } else { self.ancestor_iter().last().unwrap() } } fn descend_iter(&self) -> Self::NodeIterator { Box::new(Descendants::new(self)) } fn next_iter(&self) -> Self::NodeIterator { Box::new(Siblings::new(self, 1)) } fn prev_iter(&self) -> Self::NodeIterator { Box::new(Siblings::new(self, -1)) } fn attribute_iter(&self) -> Self::NodeIterator { Box::new(Attributes::new(self)) } fn get_attribute(&self, a: &QualifiedName) -> Rc<Value> { self.attributes .borrow() .get(a) .map_or(Rc::new(Value::from("")), |v| { v.value.as_ref().unwrap().clone() }) } fn get_attribute_node(&self, a: &QualifiedName) -> Option<RNode> { self.attributes .borrow() .get(a) .map_or(None, |v| Some(v.clone())) } fn new_element(&self, qn: QualifiedName) -> Result<Self, Error> { Ok(NodeBuilder::new(NodeType::Element).name(qn).build()) } fn new_text(&self, v: Rc<Value>) -> Result<Self, Error> { Ok(NodeBuilder::new(NodeType::Text).value(v).build()) } fn new_attribute(&self, qn: QualifiedName, v: Rc<Value>) -> Result<Self, Error> { Ok(NodeBuilder::new(NodeType::Attribute) .name(qn) .value(v) .build()) } fn new_comment(&self, v: Rc<Value>) -> Result<Self, Error> { Ok(NodeBuilder::new(NodeType::Comment).value(v).build()) } fn new_processing_instruction(&self, qn: QualifiedName, v: Rc<Value>) -> Result<Self, Error> { Ok(NodeBuilder::new(NodeType::ProcessingInstruction) .name(qn) .value(v) .build()) } fn new_namespace(&self, _ns: String, _prefix: Option<String>) -> Result<Self, Error> { Err(Error::new(ErrorKind::NotImplemented, "not supported")) } /// Append a node to the child list fn push(&mut self, n: RNode) -> Result<(), Error> { if n.node_type() == NodeType::Document { return Err(Error::new( ErrorKind::TypeError, String::from("document type nodes cannot be inserted into a tree"), )); } *n.parent.borrow_mut() = Some(Rc::downgrade(self)); self.children.borrow_mut().push(n); Ok(()) } /// Remove a node from the tree. If the node is unattached (i.e. does not have a parent), then this has no effect. fn pop(&mut self) -> Result<(), Error> { // Find this node in the parent's node list let parent = self.parent().ok_or_else(|| { Error::new( ErrorKind::Unknown, String::from("unable to insert before: node is an orphan"), ) })?; let idx = find_index(&parent, self)?; parent.children.borrow_mut().remove(idx); Ok(()) } /// Add an attribute to this element-type node fn add_attribute(&self, att: Self) -> Result<(), Error> { if self.node_type() != NodeType::Element { return Result::Err(Error::new( ErrorKind::Unknown, String::from("must be an element node"), )); } if att.node_type() != NodeType::Attribute { return Result::Err(Error::new( ErrorKind::Unknown, String::from("must be an attribute node"), )); } self.attributes.borrow_mut().insert(att.name(), att.clone()); *att.parent.borrow_mut() = Some(Rc::downgrade(self)); Ok(()) } /// Insert a node into the child list immediately before this node. fn insert_before(&mut self, mut insert: Self) -> Result<(), Error> { if insert.node_type() == NodeType::Document { return Err(Error::new( ErrorKind::TypeError, String::from("document type nodes cannot be inserted into a tree"), )); } // Detach the node first. Ignore any error, it's OK if the node is not attached anywhere. _ = insert.pop(); // Get the parent of this node. It is an error if there is no parent. let parent = self.parent().ok_or_else(|| { Error::new( ErrorKind::Unknown, String::from("unable to insert before: node is an orphan"), ) })?; // Find the child node's index in the parent's child list let idx = find_index(&parent, self)?; // Insert the node at position of self, shifting insert right parent.children.borrow_mut().insert(idx, insert); // All done Ok(()) } /// Shallow copy the node. Returned node is unattached. fn shallow_copy(&self) -> Result<Self, Error> { Ok(NodeBuilder::new(self.node_type()) .name(self.name()) .value(self.value()) .build()) } /// Deep copy the node. Returned node is unattached. fn deep_copy(&self) -> Result<Self, Error> { let mut result = NodeBuilder::new(self.node_type()) .name(self.name()) .value(self.value()) .build(); self.attribute_iter().try_for_each(|a| { result.add_attribute(a.deep_copy()?)?; Ok::<(), Error>(()) })?; self.child_iter().try_for_each(|c| { result.push(c.deep_copy()?)?; Ok::<(), Error>(()) })?; Ok(result) } fn get_canonical(&self) -> Result<Self, Error> { match self.node_type() { NodeType::Comment => Err(Error::new(ErrorKind::TypeError, "".to_string())), NodeType::Text => { let mut v: Rc<Value> = self.value(); if let Value::String(s) = &*v { v = Rc::new(Value::String(s.replace("\r\n", "\n").replace("\n\n", "\n"))) } let result = NodeBuilder::new(self.node_type()) .name(self.name()) .value(v) .build(); Ok(result) } _ => { let mut result = NodeBuilder::new(self.node_type()) .name(self.name()) .value(self.value()) .build(); self.attribute_iter().try_for_each(|a| { result.add_attribute(a.deep_copy()?)?; Ok::<(), Error>(()) })?; self.child_iter().try_for_each(|c| { result.push(c.get_canonical()?)?; Ok::<(), Error>(()) })?; Ok(result) } } } fn xmldecl(&self) -> crate::xmldecl::XMLDecl { crate::xmldecl::XMLDeclBuilder::new().build() } fn set_xmldecl(&mut self, _: crate::xmldecl::XMLDecl) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn add_namespace(&self, _ns: Self) -> Result<(), Error> { todo!() } fn namespace_iter(&self) -> Self::NodeIterator { todo!() } } impl Debug for Node { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, "type {} name {:?} value {:?}", self.node_type, self.name, self.value ) } } // Find the document order of ancestors fn doc_order(n: &RNode) -> Vec<usize> { match n.node_type { NodeType::Document => vec![1 as usize], NodeType::Element | NodeType::Text | NodeType::Comment | NodeType::ProcessingInstruction => { let p = n.parent.borrow(); match &*p { Some(q) => match Weak::upgrade(&q) { Some(r) => { let idx = find_index(&r, &n).expect("unable to locate node in parent"); let mut a = doc_order(&r); a.push(idx + 2); a } None => vec![1 as usize], }, None => vec![1 as usize], } } NodeType::Attribute => { // Namespace nodes are first, then attributes let mut a = doc_order(&n.parent().unwrap()); a.push(2); a } _ => vec![0], } } // This handles the XML serialisation of the document. // "ns" is the list of XML Namespaces that have been declared in an ancestor: (URI, prefix). // "indent" is the current level of indentation. fn to_xml_int( node: &RNode, od: &OutputDefinition, ns: Vec<(String, Option<String>)>, indent: usize, ) -> String { match node.node_type { NodeType::Document => node .children .borrow() .iter() .fold(String::new(), |mut result, c| { result.push_str(to_xml_int(c, od, ns.clone(), indent + 2).as_str()); result }), NodeType::Element => { let mut result = String::from("<"); // Elements must have a name, so unpack it let qn = node.name.borrow().as_ref().unwrap().clone(); result.push_str(qn.to_string().as_str()); // Check if any XML Namespaces need to be declared // newns is a vector of (prefix, namespace URI) pairs let mut declared = ns.clone(); let mut newns: Vec<(String, Option<String>)> = vec![]; // First, the element itself namespace_check(&qn, &declared).iter().for_each(|m| { newns.push(m.clone()); declared.push(m.clone()) }); // Next, it's attributes node.attributes.borrow().iter().for_each(|(k, _)| { namespace_check(k, &declared).iter().for_each(|m| { newns.push(m.clone()); declared.push(m.clone()) }) }); // Finally, it's child elements node.child_iter() .filter(|c| c.node_type == NodeType::Element) .for_each(|c| { c.name.borrow().as_ref().map(|d| { namespace_check(d, &declared).iter().for_each(|m| { newns.push(m.clone()); declared.push(m.clone()) }) }); }); newns.iter().for_each(|(u, p)| { result.push_str(" xmlns"); if let Some(q) = p { result.push(':'); result.push_str(q.as_str()); } result.push_str("='"); result.push_str(u); result.push('\''); }); node.attributes .borrow() .iter() .for_each(|(k, v)| result.push_str(format!(" {}='{}'", k, v.value()).as_str())); result.push('>'); // Content of the element. // If the indent option is enabled, then if no child is a text node then add spacing. let do_indent: bool = od .get_indent() .then(|| { node.child_iter().fold(true, |mut acc, c| { if acc && c.node_type == NodeType::Text { acc = false } acc }) }) .map_or(false, |b| b); node.children.borrow().iter().for_each(|c| { if do_indent { result.push('\n'); (0..indent).for_each(|_| result.push(' ')) } result.push_str(to_xml_int(c, od, newns.clone(), indent + 2).as_str()) }); if do_indent && indent > 1 { result.push('\n'); (0..(indent - 2)).for_each(|_| result.push(' ')) } result.push_str("</"); result.push_str( node.name .borrow() .as_ref() .map_or(String::new(), |n| n.to_string()) .as_str(), ); result.push('>'); result } NodeType::Text => node.value().to_string(), NodeType::Comment => { let mut result = String::from("<!--"); let s = node .value .as_ref() .map_or("".to_string(), |n| n.to_string()); result.push_str(s.as_str()); result.push_str("-->"); result } NodeType::ProcessingInstruction => { let mut result = String::from("<?"); let s = node .name .borrow() .as_ref() .map_or("".to_string(), |n| n.to_string()); result.push_str(s.as_str()); result.push(' '); let t = node.value.clone().map_or("".to_string(), |n| n.to_string()); result.push_str(t.as_str()); result.push_str("?>"); result } _ => String::new(), } } // Checks if this node's name is in a namespace that has already been declared. // Returns a namespace to be declared if required, (URI, prefix). fn namespace_check( qn: &QualifiedName, ns: &Vec<(String, Option<String>)>, ) -> Option<(String, Option<String>)> { let mut result = None; if let Some(qnuri) = qn.get_nsuri_ref() { // Has this namespace already been declared? if ns.iter().find(|(u, _)| u == qnuri).is_some() { // Namespace has been declared, but with the same prefix? // TODO: see forest.rs for example implementation } else { // Namespace has not been declared, so this element must declare it result = Some((qnuri.to_string(), qn.get_prefix())) } } result } // Find the position of this node in the parent's child list. fn find_index(p: &RNode, c: &RNode) -> Result<usize, Error> { let idx = p .children .borrow() .iter() .enumerate() .fold(None, |mut acc, (i, v)| { if Rc::ptr_eq(c, v) { acc = Some(i); // TODO: stop here } acc }); idx.map_or( Err(Error::new( ErrorKind::Unknown, String::from("unable to find child"), )), Ok, ) } pub struct Children { v: Vec<RNode>, i: usize, } impl Children { fn new(n: &RNode) -> Self { match n.node_type() { NodeType::Document | NodeType::Element => Children { v: n.children.borrow().clone(), i: 0, }, _ => Children { v: vec![], i: 0 }, } } } impl Iterator for Children { type Item = RNode; fn next(&mut self) -> Option<RNode> { match self.v.get(self.i) { Some(c) => { self.i += 1; Some(c.clone()) } None => None, } } } pub struct Ancestors { cur: RNode, } impl Ancestors { fn new(n: &RNode) -> Self { Ancestors { cur: n.clone() } } } impl Iterator for Ancestors { type Item = RNode; fn next(&mut self) -> Option<RNode> { let s = self.cur.clone(); let p = s.parent.borrow(); match &*p { None => None, Some(q) => match Weak::upgrade(q) { None => None, Some(r) => { self.cur = r.clone(); Some(r) } }, } } } // This implementation eagerly constructs a list of nodes // to traverse. // An alternative would be to lazily traverse the descendants. // Also, rewrite this iterator in terms of child_iter. pub struct Descendants { v: Vec<RNode>, cur: usize, } impl Descendants { fn new(n: &RNode) -> Self { Descendants { v: n.children.borrow().iter().fold(vec![], |mut acc, c| { let mut d = descendant_add(c); acc.append(&mut d); acc }), cur: 0, } } } fn descendant_add(n: &RNode) -> Vec<RNode> { let mut result = vec![n.clone()]; n.children.borrow().iter().for_each(|c| { let mut l = descendant_add(c); result.append(&mut l); }); result } impl Iterator for Descendants { type Item = RNode; fn next(&mut self) -> Option<RNode> { match self.v.get(self.cur) { Some(n) => { self.cur += 1; Some(n.clone()) } None => None, } } } // Store the parent node and the index of the child node that we want the sibling of. // TODO: Don't Panic. If anything fails, then the iterator's next method should return None. pub struct Siblings(RNode, usize, i32); impl Siblings { fn new(n: &RNode, dir: i32) -> Self { match n.parent() { Some(p) => { let (j, _) = p .children .borrow() .iter() .enumerate() .find(|&(_, j)| Rc::ptr_eq(j, n)) .unwrap(); Siblings(p.clone(), j, dir) } None => { // Document nodes don't have siblings Siblings(n.clone(), 0, -1) } } } } impl Iterator for Siblings { type Item = RNode; fn next(&mut self) -> Option<RNode> { if self.1 == 0 && self.2 < 0 { None } else { let newidx = if self.2 < 0 { self.1 - self.2.wrapping_abs() as usize } else { self.1 + self.2 as usize }; match self.0.children.borrow().get(newidx) { Some(n) => { self.1 = newidx; Some(n.clone()) } None => None, } } } } pub struct Attributes { it: IntoIter<QualifiedName, RNode>, } impl Attributes { fn new(n: &RNode) -> Self { let b = n.attributes.borrow(); Attributes { it: b.clone().into_iter(), } } } impl Iterator for Attributes { type Item = RNode; fn next(&mut self) -> Option<RNode> { self.it.next().map(|(_, n)| n) } } pub struct NodeBuilder(Node); impl NodeBuilder { pub fn new(n: NodeType) -> Self { NodeBuilder(Node::new(n)) } pub fn name(self, qn: QualifiedName) -> Self { *self.0.name.borrow_mut() = Some(qn); self } pub fn value(mut self, v: Rc<Value>) -> Self { self.0.value = Some(v); self } pub fn pi_name(mut self, pi: String) -> Self { self.0.pi_name = Some(pi); self } pub fn dtd(mut self, d: DTD) -> Self { self.0.dtd = Some(d); self } pub fn reference(mut self, qn: QualifiedName) -> Self { self.0.reference = Some(qn); self } pub fn build(self) -> Rc<Node> { Rc::new(self.0) } } #[derive(Clone, PartialEq)] pub struct XMLDecl {
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
true
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/trees/forest.rs
src/trees/forest.rs
//! # xrust::forest //! //! A forest is a collection of [Tree]s. A [Tree] is a collection of [Node]s. A [Node] is an index into the [Tree]. //! //! Both [Forest]s and [Tree]s use an arena allocator, so the object itself is simply an index that may be copied and cloned. However, in order to dererence the [Tree] or [Node] the [Forest] must be passed as an argument. This also makes deallocating memory difficult; the objects will persist until the entire [Forest] is freed. use std::convert::TryFrom; use std::collections::HashMap; use std::collections::hash_map::Iter; use generational_arena::{Arena, Index}; use crate::qname::QualifiedName; use crate::output::OutputDefinition; use crate::xdmerror::{Error, ErrorKind}; use crate::value::Value; use crate::item::NodeType; //use crate::parsexml::{XMLDocument, XMLNode}; /// A Forest. Forests contain [Tree]s. Each [Tree] is identified by a copyable value, similar to a Node value, that can be easily stored and passed as a parameter. #[derive(Clone)] pub struct Forest { a: Vec<Tree>, } pub type TreeIndex = usize; impl Forest { /// Create a new, empty forest. pub fn new() -> Forest { Forest{a: vec![]} } /// Start a [Tree] in the forest. The [Tree] will have a single node, which is a Document type [Node]. pub fn plant_tree(&mut self) -> TreeIndex { let i = self.a.len(); self.a.push(Tree::new(i)); i } /// Borrow a [Tree], given a [TreeIndex]. Return None if no suh [Tree] exists. pub fn get_ref(&self, i: TreeIndex) -> Option<&Tree> { self.a.get(i) } /// Mutably borrow a [Tree], given a [TreeIndex]. Return None if no suh [Tree] exists. pub fn get_ref_mut(&mut self, i: TreeIndex) -> Option<&mut Tree> { self.a.get_mut(i) } /// Parse a string as XML to create a [Tree]. /// ///```rust ///let mut f = Forest::new(); ///let src = f.grow_tree("<Example>document</Example>") /// .expect("unable to parse XML"); pub fn grow_tree(&mut self, s: &str) -> Result<TreeIndex, Error> { Result::Err(Error::new(ErrorKind::NotImplemented, String::from("not implemented yet"))) // let d = XMLDocument::try_from(s)?; // if d.content.len() == 0 { // Result::Err(Error::new(ErrorKind::Unknown, String::from("unable to parse XML"))) // } else { // let mut ns: HashMap<String, String> = HashMap::new(); // let ti = self.plant_tree(); // for c in d.content { // let e = make_node(c, self, ti, &mut ns)?; // self.get_ref_mut(ti).unwrap().push_doc_node(e)?; // } // Ok(ti) // } } } /// A Tree, using an Arena Allocator. /// Nodes can be detached, but not deleted #[derive(Clone)] pub struct Tree { i: TreeIndex, // The index in the Forest a: Arena<NodeContent>, d: Index, // The document node } impl Tree { /// Create a tree with the given [TreeIndex]. /// /// The newly created tree has a single [Node], of type Document. pub fn new(i: TreeIndex) -> Self { let mut a = Arena::new(); let d = a.insert( NodeBuilder::new(NodeType::Document).build() ); Tree { i: i, a: a, d: d, } } fn get(&self, i: Index) -> Option<&NodeContent> { self.a.get(i) } fn get_mut(&mut self, i: Index) -> Option<&mut NodeContent> { self.a.get_mut(i) } /// Return the Document-type [Node]. pub fn get_doc_node(&self) -> Node { Node::new(self.d, self.i) } /// Append a [Node] as a child of the Document-type [Node]. pub fn push_doc_node(&mut self, n: Node) -> Result<(), Error> { // Set the parent to the document node self.get_mut(n.0).unwrap().parent = Some(Node::new(self.d, self.i)); // Push the node onto the doc node's children self.get_mut(self.d) .map_or_else( || Result::Err(Error::new(ErrorKind::Unknown, String::from("no document node"))), |e| { e.children.push(n); Ok(()) } ) } /// Create a new Element-type [Node] in this tree. The newly created [Node] is not attached to the tree, i.e. it has no parent. pub fn new_element(&mut self, name: QualifiedName) -> Result<Node, Error> { Ok( Node::new( self.a .insert(NodeBuilder::new(NodeType::Element).name(name).build()), self.i ) ) } /// Create a new Text-type [Node] in this tree. The newly created [Node] is not attached to the tree, i.e. it has no parent. pub fn new_text(&mut self, c: Value) -> Result<Node, Error> { Ok( Node::new( self.a .insert(NodeBuilder::new(NodeType::Text).value(c).build()), self.i ) ) } /// Create a new Attribute-type [Node] in this tree. The newly created [Node] is not attached to the tree, i.e. it has no parent. pub fn new_attribute(&mut self, name: QualifiedName, v: Value) -> Result<Node, Error> { Ok( Node::new( self.a .insert( NodeBuilder::new(NodeType::Attribute) .name(name) .value(v) .build() ), self.i ) ) } /// Create a new Comment-type [Node] in this tree. The newly created [Node] is not attached to the tree, i.e. it has no parent. pub fn new_comment(&mut self, v: Value) -> Result<Node, Error> { Ok( Node::new( self.a .insert(NodeBuilder::new(NodeType::Comment).value(v).build()), self.i ), ) } /// Create a new ProcessingInstruction-type [Node] in this tree. The newly created [Node] is not attached to the tree, i.e. it has no parent. pub fn new_processing_instruction(&mut self, name: QualifiedName, v: Value) -> Result<Node, Error> { Ok( Node::new(self.a .insert( NodeBuilder::new(NodeType::ProcessingInstruction) .name(name) .value(v) .build() ), self.i ), ) } } // TODO: replace XMLNode with ANode //fn make_node( // n: XMLNode, // f: &mut Forest, // ti: TreeIndex, // ns: &mut HashMap<String, String>, //) -> Result<Node, Error> { // match n { // XMLNode::Element(m, a, c) => { // a.iter() // .filter(|b| { // match b { // XMLNode::Attribute(qn, _) => { // match qn.get_prefix() { // Some(p) => { // p == "xmlns" // } // _ => false, // } // } // _ => false, // } // }) // .for_each(|b| { // if let XMLNode::Attribute(qn, v) = b { // // add map from prefix to uri in hashmap // ns.insert(qn.get_localname(), v.to_string()).map(|_| {}); // } // }); // Add element to the tree // let newns = match m.get_prefix() { // Some(p) => { // match ns.get(&p) { // Some(q) => Some(q.clone()), // None => { // return Result::Err(Error::new(ErrorKind::Unknown, String::from("namespace URI not found for prefix"))) // } // } // } // None => None, // }; // let new = f.get_ref_mut(ti).unwrap().new_element( // QualifiedName::new( // newns, // m.get_prefix(), // m.get_localname(), // ) // )?; // Attributes // a.iter() // .for_each(|b| { // if let XMLNode::Attribute(qn, v) = b { // match qn.get_prefix() { // Some(p) => { // if p != "xmlns" { // let ans = ns.get(&p).unwrap_or(&"".to_string()).clone(); // match f.get_ref_mut(ti).unwrap().new_attribute( // QualifiedName::new(Some(ans), Some(p), qn.get_localname()), // v.clone() // ) { // Ok(c) => { // new.add_attribute(f, c).expect("unable to add attribute"); // TODO: Don't Panic // } // Err(_) => { //return Result::Err(e); // } // }; // } // otherwise it is a namespace declaration, see above // } // _ => { // Unqualified name // match f.get_ref_mut(ti).unwrap().new_attribute(qn.clone(), v.clone()) { // Ok(c) => { // new.add_attribute(f, c).expect("unable to add attribute"); // TODO: Don't Panic // } // Err(_) => { //return Result::Err(e); // } // } // } // } // } // } // ); // Element content // for h in c.iter().cloned() { // let g = make_node(h, f, ti, ns)?; // new.append_child(f, g)? // } // Ok(new) // } // XMLNode::Attribute(_qn, _v) => { // Handled in element arm // Result::Err(Error::new(ErrorKind::NotImplemented, String::from("not implemented"))) // } // XMLNode::Text(v) => { // Ok(f.get_ref_mut(ti).unwrap().new_text(v)?) // } // XMLNode::Comment(v) => { // Ok(f.get_ref_mut(ti).unwrap().new_comment(v)?) // } // XMLNode::PI(m, v) => { // Ok(f.get_ref_mut(ti).unwrap().new_processing_instruction(QualifiedName::new(None, None, m), v)?) // } // XMLNode::Reference(_) | // XMLNode::DTD(_) => { // Result::Err(Error::new(ErrorKind::TypeError, String::from("not expected"))) // } // } //} /// A node in the [Tree]. Depending on the type of the node, it may have a name, value, content, or attributes. #[derive(Copy, Clone, PartialEq, Debug)] pub struct Node(Index, TreeIndex); impl Node { /// Wrap the given Arena Index and [TreeIndex] to create a new node. NB. this does not create a node in the [Tree] (i.e. [Forest] or arena allocator) fn new(i: Index, t: TreeIndex) -> Self { Node(i, t) } fn get<'a>(&self, f: &'a Forest) -> Option<&'a NodeContent> { f.get_ref(self.1).unwrap().get(self.0) } /// Programmer view of the Node. This is needed since the std::fmt::Debug trait cannot be implemented (because the Forest is required to gather the necessary data). pub fn fmt_debug(&self, f: &Forest) -> String { let mut result = String::from(self.node_type(f).to_string()); result.push_str("-type node"); match self.node_type(f) { NodeType::Element => { result.push_str(" \""); result.push_str(self.to_name(f).to_string().as_str()); result.push_str("\""); } NodeType::Text => { result.push_str(" \""); result.push_str(self.to_value(f).to_string().as_str()); // TODO: limit to at most, say, 10 chars result.push_str("\""); } _ => {} // TODO: attribute, comment, PI, etc } result } /// Return the string representation of the node. pub fn to_string(&self, f: &Forest) -> String { match f.get_ref(self.1) { Some(e) => e, None => return String::from(""), }; match self.node_type(f) { NodeType::Element => { // TODO: string value of all descendant text nodes String::new() } NodeType::Text | NodeType::Attribute | NodeType::Comment => { self.get(f).unwrap().value().as_ref().map_or( String::new(), |v| v.to_string() ) } _ => String::new(), } } /// Serialise the node as XML. pub fn to_xml(&self, f: &Forest) -> String { let mut ns: HashMap<String, Option<String>> = HashMap::new(); self.to_xml_int(f, &OutputDefinition::new(), 0, &mut ns) } fn to_xml_int( &self, f: &Forest, od: &OutputDefinition, indent: usize, ns: &mut HashMap<String, Option<String>> ) -> String { let d = match f.get_ref(self.1) { Some(e) => e, None => return String::from(""), }; let nc = match d.get(self.0) { Some(e) => e, None => return String::from(""), }; match nc.node_type() { NodeType::Element => { let mut result = String::from("<"); let name = nc.name().as_ref().unwrap(); // Check if any XML Namespaces need to be declared, // Either for the element for any of its attributes. let mut newns: Vec<(Option<String>, String)> = vec![]; if let Some(uri) = name.get_nsuri() { match name.get_prefix() { Some(p) => { match ns.get(uri.as_str()) { Some(op) => { // Already declared, but with the same prefix? match op { Some(q) => { if p != *q { ns.insert(uri.clone(), Some(p.clone())); newns.push((Some(p), uri)); } // else already declared } None => { // Was declared with default namespace, now has a prefix ns.insert(uri.clone(), Some(p.clone())); newns.push((Some(p), uri)); } } } None => { ns.insert(uri.clone(), Some(p.clone())); newns.push((Some(p), uri)); } } } None => { // Default namespace match ns.get(uri.as_str()) { Some(_) => { ns.insert(uri.clone(), None); newns.push((None, uri)); } None => { // Already declared } } } } } result.push_str(name.to_string().as_str()); newns.iter().for_each(|(p, u)| { result.push_str(" xmlns"); if let Some(q) = p { result.push(':'); result.push_str(q.as_str()); } result.push_str("='"); result.push_str(u); result.push('\''); }); nc.attributes.iter().for_each(|(k, v)| { // Declare namespace for attribute, if not already declared if let Some(uri) = k.get_nsuri() { if ns.get(uri.as_str()).is_none() { ns.insert(uri.clone(), k.get_prefix()); result.push_str(" xmlns:"); result.push_str(k.get_prefix().unwrap().as_str()); result.push_str("='"); result.push_str(uri.as_str()); result.push('\''); } } result.push(' '); result.push_str(k.to_string().as_str()); result.push_str("='"); result.push_str(v.to_string(f).as_str()); result.push('\''); }); result.push_str(">"); // Content of the element. // If the indent option is enabled, then if no child is a text node then add spacing let do_indent: bool = if od.get_indent() { let mut acc = true; let mut children = self.child_iter(); loop { match children.next(f) { Some(c) => { if c.node_type(f) == NodeType::Text { acc = false } } None => break, } } acc } else { false }; let mut children = self.child_iter(); loop { match children.next(f) { Some(c) => { if do_indent { result.push('\n'); (0..indent).for_each(|_| result.push(' ')); }; result.push_str(c.to_xml_int(f, od, indent, ns).as_str()); } None => break, } }; if do_indent { result.push('\n'); (0..(indent - 2)).for_each(|_| result.push(' ')); }; result.push_str("</"); result.push_str(name.to_string().as_str()); result.push_str(">"); result } NodeType::Text => { nc.value().as_ref().unwrap().to_string() } NodeType::Comment => { let mut result = String::from("<!--"); result.push_str(nc.value().as_ref().unwrap().to_string().as_str()); result.push_str("-->"); result } NodeType::ProcessingInstruction => { let mut result = String::from("<?"); result.push_str(nc.name().as_ref().unwrap().to_string().as_str()); result.push(' '); result.push_str(nc.value().as_ref().unwrap().to_string().as_str()); result.push_str("?>"); result } _ => { // TODO String::from("-- not implemented --") } } } /// Serialise the node as XML, under the control of the given OutputDefinition. The usual use is to perform indenting, i.e. "pretty-printing". pub fn to_xml_with_options(&self, f: &Forest, od: &OutputDefinition) -> String { let mut ns: HashMap<String, Option<String>> = HashMap::new(); self.to_xml_int(f, od, 2, &mut ns) } /// Serialise the node as JSON. pub fn to_json(&self, _f: &Forest) -> String { String::from("not implemented yet") } /// A convenience method that converts the value to a string and then converts the string to an integer. pub fn to_int(&self, f: &Forest) -> Result<i64, Error> { // Convert to a string, then try parsing that as an integer self.to_string(f).parse::<i64>() .map_err(|e| Error::new(ErrorKind::Unknown, e.to_string())) } /// A convenience method that converts the value to a string and then converts the string to a double. pub fn to_double(&self, f: &Forest) -> f64 { // Convert to a string, then try parsing that as a double match self.to_string(f).parse::<f64>() { Ok(g) => g, Err(_) => f64::NAN, } } /// Get the name of the node. If the node is of a type that doesn't have a name, returns a name with an empty local name, URI, and prefix. pub fn to_name(&self, f: &Forest) -> QualifiedName { f.get_ref(self.1) .map_or( QualifiedName::new(None, None, String::from("")), |d| d.get(self.0) .map_or( QualifiedName::new(None, None, String::from("")), |o| o.name().as_ref().map_or( QualifiedName::new(None, None, String::from("")), |p| p.clone(), ) ), ) } /// Get the value of the node. If the node is of a type that doesn't have a value, returns an empty string value. pub fn to_value(&self, f: &Forest) -> Value { f.get_ref(self.1) .map_or( Value::from(""), |d| d.get(self.0) .map_or( Value::from(""), |o| o.value().as_ref().map_or( Value::from(""), |p| p.clone() ) ) ) } /// Returns the node's type. pub fn node_type(&self, f: &Forest) -> NodeType { f.get_ref(self.1) .map_or( NodeType::Unknown, |d| d.get(self.0) .map_or( NodeType::Unknown, |m| m.node_type(), ), ) } /// Append the given node to this node's child list. This node must be an element-type node. The node to be appended must not be an attribute-type node. /// /// If the given node is not in the same [Tree] as this node, makes a deep copy of the given node and appends that to this node's child list. pub fn append_child(&self, f: &mut Forest, c: Node) -> Result<(), Error> { // Check that self is an element and that c is not an attribute if self.node_type(f) != NodeType::Element { return Result::Err(Error::new( ErrorKind::Unknown, String::from("must be an element"), )); } if c.node_type(f) == NodeType::Attribute { return Result::Err(Error::new( ErrorKind::Unknown, String::from("cannot append an attribute as a child"), )); } // Is c in a different Tree? if self.1 == c.1 { // Detach from its current position, then append to self's child list c.remove(f)?; // self will now be c's parent f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))? .get_mut(c.0) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find node"), ))? .parent = Some(self.clone()); // Push c onto self's child list f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))? .get_mut(self.0) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find node"), ))? .children.push(c); } else { // c is in a different Tree, so deep copy let cp = c.deep_copy(f, Some(self.1))?; // self will now be cp's parent f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))? .get_mut(cp.0) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find node"), ))? .parent = Some(self.clone()); // Push cp onto self's child list f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))? .get_mut(self.0) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find node"), ))? .children.push(cp); } Ok(()) } /// Insert the given node before this node in the parent's child list. This node must be an element-type node. The given node must not be an attribute-type node. /// If the given node is in the same tree, then it is removed from the tree and then inserted so that it becomes the first preceding of this node. /// If the given node is in a different tree, then it is deep copied. The copied node will then become the first preceding sibling of this node. pub fn insert_before(&self, f: &mut Forest, insert: Node) -> Result<(), Error> { let p = self.parent(f) .ok_or(Error::new(ErrorKind::Unknown, String::from("unable to insert before document node")))?; if self.1 == insert.1 { // Given node is in the same tree. Detach from it's current position, and then insert before this node. insert.remove(f)?; let d = f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))?; let cl = &mut d.get_mut(p.0).unwrap().children; let i = cl.iter() .enumerate() .skip_while(|(_, x)| x.0 != self.0) .nth(0) .map(|(e, _)| e) .unwrap(); cl.insert(i, insert); d.get_mut(insert.0).unwrap().parent = Some(p); } else { // Given node is in a different tree. Deep copy the node. // First find where to insert the copied node let d = f.get_ref(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))?; let i = d.get(p.0).unwrap().children.iter() .enumerate() .skip_while(|(_, x)| x.0 != self.0) .nth(0) .map(|(e, _)| e) .unwrap(); // Then do the copy and insert it let cp = insert.deep_copy(f, Some(self.1))?; let clm = &mut f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))? .get_mut(p.0).unwrap().children; clm.insert(i, cp); // Update the copied node with it's new parent f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))? .get_mut(cp.0).unwrap().parent = Some(p); } Ok(()) } /// Detach the node from the tree pub fn remove(&self, f: &mut Forest) -> Result<(), Error> { let d = f.get_ref_mut(self.1) .ok_or(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), ))?; // Is this node in the tree? If not, then do nothing let p = match d.get(self.0).unwrap().parent { Some(q) => q.0, None => return Ok(()), }; // Remove from parent's child list let cl = &mut d.get_mut(p).unwrap().children; let i = cl.iter() .enumerate() .skip_while(|(_, x)| x.0 != self.0) .nth(0) .map(|(e, _)| e) .unwrap(); cl.remove(i); // This node now has no parent d.get_mut(self.0).unwrap().parent = None; Ok(()) } /// Add the given node as an attribute of this node. This node must be an element-type node. The given node must be an attribute-type node. The given node is detached from it's current parent and then attached as an attribute of this node. If the given node is in a different [Tree] to this node, then it is deep-copied and the given node remains untouched. pub fn add_attribute(&self, f: &mut Forest, a: Node) -> Result<(), Error> { if self.node_type(f) != NodeType::Element { return Result::Err(Error::new( ErrorKind::Unknown, String::from("must be an element"), )); } if a.node_type(f) != NodeType::Attribute { return Result::Err(Error::new( ErrorKind::Unknown, String::from("argument must be an attribute"), )); } let d = match f.get_ref_mut(self.1) { Some(e) => e, None => return Result::Err(Error::new( ErrorKind::Unknown, String::from("unable to find tree"), )) }; // TODO: detach a from wherever it is currently located // self will now be a's parent d.get_mut(a.0).unwrap().parent = Some(self.clone()); // Add a to self's attribute hashmap let qn = d.get(a.0).unwrap().name().as_ref().unwrap().clone(); d.get_mut(self.0).unwrap().attributes.insert(qn, a); Ok(()) } /// Creates an iterator for the ancestors of this node. pub fn ancestor_iter(&self) -> Ancestors { Ancestors::new(self.0, self.1) } /// Returns the parent node. /// /// The Document-type node of the [Tree] does not have a parent. If the node is not attached to the [Tree], it will not have a parent. pub fn parent(&self, f: &Forest) -> Option<Node> { self.ancestor_iter().next(f).map(|p| p) } /// Creates an iterator over the children of this node. pub fn child_iter(&self) -> Children { Children::new(self.0, self.1) } /// Returns the first child node of this node. pub fn get_first_element(&self, f: &Forest) -> Option<Node> { let mut cit = self.child_iter(); let mut ret = None; loop { match cit.next(f) { Some(n) => { match n.node_type(f) { NodeType::Element => { ret = Some(n); break } _ => {} } } None => break, } } ret } /// Creates an iterator over the following siblings of this node. pub fn next_iter(&self, f: &Forest) -> Siblings { Siblings::new(self.0, self.1, 1, f) } /// Creates an iterator over the preceding siblings of this node. pub fn prev_iter(&self, f: &Forest) -> Siblings { Siblings::new(self.0, self.1, -1, f) } /// Creates an iterator over the descendants of this node. pub fn descend_iter(&self, f: &Forest) -> Descendants { Descendants::new(self.0, self.1, f) } /// Creates an iterator over the attributes of this node. pub fn attribute_iter<'a>(&self, f: &'a Forest) -> Attributes<'a> { Attributes::new(self.0, f.get_ref(self.1).unwrap()) } /// Returns an attribute. pub fn get_attribute(&self, f: &Forest, qn: &QualifiedName) -> Option<Node> { match f.get_ref(self.1) { Some(d) => { match d.get(self.0) { Some(nc) => { match nc.attributes.get(qn) { Some(m) => Some(m.clone()), None => None, } } None => None, } } None => None, } } /// Convenience method that returns if this node is an element-type node pub fn is_element(&self, f: &Forest) -> bool { match f.get_ref(self.1) { Some(d) => { match d.get(self.0) { Some(nc) => { nc.t == NodeType::Element } None => false, } } None => false, } } /// Make a recursive copy of the node, i.e. a "deep" copy. /// /// The new node will be created in a different tree if one is supplied. pub fn deep_copy(&self, f: &mut Forest, t: Option<TreeIndex>) -> Result<Node, Error> { let cptreeidx = t.map_or_else( || self.1, |u| u, ); // TODO: check that this is a valid tree index match self.node_type(f) { NodeType::Element => { let nm = self.to_name(f); let new = f.get_ref_mut(cptreeidx).unwrap().new_element(nm)?; let mut attrs = vec![]; let mut ait = self.attribute_iter(f); loop { match ait.next() { Some(a) => { attrs.push(a) } None => break, } } attrs.iter().for_each(|a| { let cp = a.deep_copy(f, t).expect("unable to copy attribute"); new.add_attribute(f, cp).expect("unable to add attribute"); }); let mut cit = self.child_iter(); loop { match cit.next(f) { Some(d) => { let cp = d.deep_copy(f, t)?; new.append_child(f, cp)?; } None => break, } } Ok(new) } NodeType::Attribute => { let nm = self.to_name(f); let v = self.to_value(f); f.get_ref_mut(cptreeidx).unwrap().new_attribute(nm, v) } NodeType::Text => { let v = self.to_value(f); f.get_ref_mut(cptreeidx).unwrap().new_text(v) } NodeType::Comment => { let v = self.to_value(f); f.get_ref_mut(cptreeidx).unwrap().new_comment(v) } NodeType::ProcessingInstruction => { let nm = self.to_name(f); let v = self.to_value(f); f.get_ref_mut(cptreeidx).unwrap().new_processing_instruction(nm, v) } _ => Result::Err(Error::new(ErrorKind::Unknown, String::from("unable to copy node"))) } } } /// Navigate the ancestors of a [Node]. pub struct Ancestors { t: TreeIndex, cur: Index, } impl Ancestors { fn new(cur: Index, t: TreeIndex) -> Ancestors { Ancestors{t, cur} } pub fn next(&mut self, f: &Forest) -> Option<Node> { if let Some(d) = f.get_ref(self.t) { if let Some(c) = d.get(self.cur) { if let Some(p) = c.parent { if p.node_type(f) == NodeType::Document { None } else { self.cur = p.0; Some(p) } } else { None } } else { None } } else { None } } } /// Navigate the descendants of a [Node]. pub struct Descendants { t: TreeIndex, start: Index, cur: Index, stack: Vec<(Index, usize)>, } impl Descendants { fn new(cur: Index, t: TreeIndex, f: &Forest) -> Descendants { // Find cur in the parent's child list let d = f.get_ref(t).unwrap(); let pi = d.get(cur).unwrap().parent.unwrap().0; let p = d.get(pi).unwrap(); let q = p.children.iter().enumerate() .skip_while(|(_, i)| i.0 != cur) .nth(0) .map(|(e, _)| e) .unwrap(); Descendants{ t, start: cur, cur: cur, stack: vec![(pi, q)], } } pub fn next(&mut self, f: &Forest) -> Option<Node> { if self.stack.is_empty() { None } else { // Return the first child, // otherwise return the next sibling // otherwise return an ancestor's next sibling // (don't go past start) match Node::new(self.cur, self.t).child_iter().next(f) { Some(n) => { self.stack.push((self.cur, 0)); self.cur = n.0; Some(n) } None => { let d = f.get_ref(self.t).unwrap(); let (i, mut s) = self.stack.last_mut().unwrap(); let pnc = d.get(*i).unwrap(); if pnc.children.len() < s { // have a next sibling s += 1; self.cur = pnc.children.get(s).unwrap().0; Some(Node::new(self.cur, self.t)) } else { // ancestor next sibling let result: Option<Node>; loop { self.stack.pop(); if self.stack.is_empty() { result = None; break } else { let l = self.stack.last_mut().unwrap(); let (j, mut t) = l; let qnc = d.get(*j).unwrap(); if qnc.children.len() > t + 1 { t += 1; *l = (*j, t); self.cur = qnc.children.get(t).unwrap().0; result = Some(Node::new(self.cur, self.t)); break } else { if *j == self.start { result = None; break } } } } result } } } } } } /// Navigate the children of a [Node]. pub struct Children { t: TreeIndex, parent: Index, cur: usize, } impl Children { fn new(parent: Index, t: TreeIndex) -> Children { Children{t, parent, cur: 0} } pub fn next(&mut self, f: &Forest) -> Option<Node> { if let Some(d) = f.get_ref(self.t) { if let Some(n) = d.get(self.parent) { if n.children.len() > self.cur { self.cur += 1; Some(n.children[self.cur - 1]) } else { None } } else { None } } else { None } } } /// Navigate the siblings of a [Node]. Nodes may be navigated before (preceding) or after (following) the current [Node]. pub struct Siblings { t: TreeIndex, parent: Index, cur: usize, dir: i16, } impl Siblings { fn new(n: Index, t: TreeIndex, dir: i16, f: &Forest) -> Siblings { let d = f.get_ref(t).unwrap(); let nc = d.get(n).unwrap(); let pnc = d.get(nc.parent.unwrap().0).unwrap(); let cur = pnc.children.iter().enumerate() .skip_while(|(_, i)| i.0 != n) .nth(0) .map(|(e, _)| e) .unwrap(); Siblings{ t, parent: nc.parent.unwrap().0, dir, cur: cur, } } pub fn next(&mut self, f: &Forest) -> Option<Node> { if let Some(d) = f.get_ref(self.t) { if let Some(n) = d.get(self.parent) { if self.dir > 0 && n.children.len() > self.cur + 1 { self.cur += 1; Some(n.children[self.cur]) } else if self.dir < 0 && self.cur > 0 { self.cur -= 1; Some(n.children[self.cur]) } else { None } } else { None } } else { None } } } /// Navigate the attributes of a [Node]. The order in which the attributes are visited is undefined. pub struct Attributes<'a>{ it: Iter<'a, QualifiedName, Node>, } impl<'a> Attributes<'a> { fn new(i: Index, d: &'a Tree) -> Attributes { Attributes{ it: d.get(i).unwrap().attributes.iter() } } pub fn next(&mut self) -> Option<Node> { self.it.next().map(|(_, n)| *n) } } /// The content of a [Node]. #[derive(Clone, Default)] pub struct NodeContent { t: NodeType, name: Option<QualifiedName>, v: Option<Value>, parent: Option<Node>, // The document node has no parent
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
true
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/trees/mod.rs
src/trees/mod.rs
//! Various implementations of tree data structures. /// Interior Mutability Tree. This tree implementation is both mutable and fully navigable. //pub mod intmuttree; pub(crate) mod nullo; /// Interior Mutability Tuple-Struct with Enum. /// This tree implementation is an evolution of intmuttree that represents each type of node as variants in an enum, wrapped in a tuple struct. pub mod smite;
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/trees/nullo.rs
src/trees/nullo.rs
use crate::item::{Node, NodeType}; use crate::output::OutputDefinition; use crate::qname::QualifiedName; use crate::validators::{Schema, ValidationError}; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use crate::xmldecl::{XMLDecl, XMLDeclBuilder, DTD}; /// A null tree implementation /// /// This tree implementation implements nothing. /// The parser combinator is generic in [Node]. /// Occasionally, a module using the parser, but not needing a [Node], /// nevertheless requires a concrete type that has the [Node] trait. use std::cmp::Ordering; use std::fmt; use std::rc::Rc; #[derive(Clone)] pub struct Nullo(); impl Node for Nullo { type NodeIterator = Box<dyn Iterator<Item = Nullo>>; fn new_document() -> Self { Nullo() } fn node_type(&self) -> NodeType { NodeType::Unknown } fn name(&self) -> Rc<QualifiedName> { Rc::new(QualifiedName::new(None, None, String::new())) } fn value(&self) -> Rc<Value> { Rc::new(Value::from("")) } fn get_id(&self) -> String { String::from("") } fn to_string(&self) -> String { String::new() } fn to_xml(&self) -> String { String::new() } fn to_xml_with_options(&self, _: &OutputDefinition) -> String { String::new() } fn to_json(&self) -> String { String::new() } fn is_same(&self, _: &Self) -> bool { false } fn document_order(&self) -> Vec<usize> { vec![] } fn cmp_document_order(&self, _: &Self) -> Ordering { Ordering::Equal } fn is_element(&self) -> bool { false } fn child_iter(&self) -> Self::NodeIterator { Box::new(NulloIter::new()) } fn namespace_iter(&self) -> Self::NodeIterator { Box::new(NulloIter::new()) } fn ancestor_iter(&self) -> Self::NodeIterator { Box::new(NulloIter::new()) } fn descend_iter(&self) -> Self::NodeIterator { Box::new(NulloIter::new()) } fn next_iter(&self) -> Self::NodeIterator { Box::new(NulloIter::new()) } fn prev_iter(&self) -> Self::NodeIterator { Box::new(NulloIter::new()) } fn attribute_iter(&self) -> Self::NodeIterator { Box::new(NulloIter::new()) } fn get_attribute(&self, _: &QualifiedName) -> Rc<Value> { Rc::new(Value::from("")) } fn get_attribute_node(&self, _: &QualifiedName) -> Option<Self> { None } fn owner_document(&self) -> Self { self.clone() } fn get_canonical(&self) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn new_element(&self, _: Rc<QualifiedName>) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn new_text(&self, _: Rc<Value>) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn new_attribute(&self, _: Rc<QualifiedName>, _: Rc<Value>) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn new_comment(&self, _: Rc<Value>) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn new_processing_instruction( &self, _: Rc<QualifiedName>, _: Rc<Value>, ) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn new_namespace(&self, _ns: Rc<Value>, _prefix: Option<Rc<Value>>) -> Result<Self, Error> { Err(Error::new(ErrorKind::NotImplemented, "not implemented")) } fn push(&mut self, _: Self) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn pop(&mut self) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn insert_before(&mut self, _: Self) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn add_attribute(&self, _: Self) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn shallow_copy(&self) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn deep_copy(&self) -> Result<Self, Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn xmldecl(&self) -> XMLDecl { XMLDeclBuilder::new().build() } fn set_xmldecl(&mut self, _: XMLDecl) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn add_namespace(&self, _: Self) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn is_id(&self) -> bool { false } fn is_idrefs(&self) -> bool { false } fn get_dtd(&self) -> Option<DTD> { None } fn set_dtd(&self, _dtd: DTD) -> Result<(), Error> { Err(Error::new( ErrorKind::NotImplemented, String::from("not implemented"), )) } fn validate(&self, _sch: Schema) -> Result<(), ValidationError> { Err(ValidationError::SchemaError("Not Implemented".to_string())) } } pub struct NulloIter(); impl NulloIter { fn new() -> Self { NulloIter() } } impl Iterator for NulloIter { type Item = Nullo; fn next(&mut self) -> Option<Self::Item> { None } } impl fmt::Debug for Nullo { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Nullo node") } } impl PartialEq for Nullo { fn eq(&self, other: &Self) -> bool { Node::eq(self, other) } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/trees/smite.rs
src/trees/smite.rs
/*! # A tree structure for XDM This module implements the Item module's [Node](crate::item::Node) trait. This implementation uses interior mutability to create and manage a tree structure that is both mutable and fully navigable. To create a tree, use [Node::new()](crate::trees::smite::Node) to make a Document-type node. To add a node, first create it using a creation method, defined by the [Node](crate::item::Node) trait, such as new_element() or new_text(), then use the push(), insert_before(), or add_attribute() method to attach it to a node in the tree. NB. The Item module's Node trait is implemented for Rc\<smite::Node\>. For convenience, this is defined as the type [RNode](crate::trees::smite::RNode). ```rust use std::rc::Rc; use xrust::trees::smite::RNode; use xrust::item::{Node as ItemNode, NodeType}; use xrust::qname::QualifiedName; use xrust::value::Value; use xrust::xdmerror::Error; pub(crate) type ExtDTDresolver = fn(Option<String>, String) -> Result<String, Error>; // A document always has a NodeType::Document node as the toplevel node. let mut doc = RNode::new_document(); // Create an element-type node. Upon creation, it is *not* attached to the tree. let mut top = doc.new_element( Rc::new(QualifiedName::new(None, None, "Top-Level")) ).expect("unable to create element node"); // Nodes are Rc-shared, so it is cheap to clone them. // Now attach the element node to the tree. // In this case, it is being attached to the document node, so it will become the root element. doc.push(top.clone()) .expect("unable to append child node"); // Now create a text node and attach it to the root element. top.push( doc.new_text(Rc::new(Value::from("content of the element"))) .expect("unable to create text node") ).expect("unable to append child node"); assert_eq!(doc.to_xml(), "<Top-Level>content of the element</Top-Level>") */ use crate::item::{Node as ItemNode, NodeType}; use crate::output::OutputDefinition; use crate::qname; use crate::qname::QualifiedName; use crate::trees::smite; use crate::validators::{Schema, ValidationError}; use crate::value::Value; use crate::xdmerror::*; use crate::xmldecl::{XMLDecl, XMLDeclBuilder, DTD}; use regex::Regex; use std::cell::RefCell; use std::cmp::Ordering; use std::collections::btree_map::IntoIter; use std::collections::BTreeMap; use std::fmt; use std::fmt::{Debug, Formatter}; use std::rc::{Rc, Weak}; /// A node in a tree. pub type RNode = Rc<Node>; enum NodeInner { Document( RefCell<Option<XMLDecl>>, RefCell<Vec<RNode>>, // Child nodes RefCell<Vec<RNode>>, // Unattached nodes RefCell<Option<DTD>>, ), // to be well-formed, only one of the child nodes can be an element-type node Element( RefCell<Weak<Node>>, // Parent: must be a Document or an Element Rc<QualifiedName>, // name RefCell<BTreeMap<Rc<QualifiedName>, RNode>>, // attributes RefCell<Vec<RNode>>, // children Rc<RefCell<BTreeMap<Option<Rc<Value>>, RNode>>>, // namespace declarations ), Text(RefCell<Weak<Node>>, Rc<Value>), Attribute(RefCell<Weak<Node>>, Rc<QualifiedName>, Rc<Value>), Comment(RefCell<Weak<Node>>, Rc<Value>), ProcessingInstruction(RefCell<Weak<Node>>, Rc<QualifiedName>, Rc<Value>), Namespace( RefCell<Weak<Node>>, // Parent Option<Rc<Value>>, // Prefix Rc<Value>, // URI ), } pub struct Node(NodeInner); impl Node { /// Only documents are created new. All other types of nodes are created using new_* methods. fn new() -> Self { Node(NodeInner::Document( RefCell::new(None), RefCell::new(vec![]), RefCell::new(vec![]), None.into(), )) } pub fn set_nsuri(&mut self, uri: Rc<Value>) -> Result<(), Error> { match &self.0 { NodeInner::Element(p, qn, att, c, ns) => { self.0 = NodeInner::Element( p.clone(), Rc::new(QualifiedName::new_from_values( Some(uri), qn.prefix(), qn.localname(), )), att.clone(), c.clone(), ns.clone(), ); Ok(()) } _ => Err(Error::new( ErrorKind::TypeError, String::from("not an Element node"), )), } } } impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { match (&self.0, &other.0) { (NodeInner::Document(_, c, _, _), NodeInner::Document(_, d, _, _)) => { c.borrow() .iter() .zip(d.borrow().iter()) .fold(true, |mut acc, (c, d)| { if acc { acc = c == d; acc } else { acc } }) // TODO: use a method that terminates early on non-equality } ( NodeInner::Element(_, name, atts, c, _), NodeInner::Element(_, o_name, o_atts, d, _), ) => { if name == o_name { // Attributes must match let b_atts = atts.borrow(); let b_o_atts = o_atts.borrow(); if b_atts.len() == b_o_atts.len() { let mut at_names: Vec<Rc<QualifiedName>> = b_atts.keys().cloned().collect(); at_names.sort(); if at_names.iter().fold(true, |mut acc, qn| { if acc { acc = b_atts.get(qn) == b_o_atts.get(qn); acc } else { acc } }) { // Content c.borrow().iter().zip(d.borrow().iter()).fold( true, |mut acc, (c, d)| { if acc { acc = c == d; acc } else { acc } }, ) // TODO: use a method that terminates early on non-equality } else { false } } else { false } // Content must match } else { false } } (NodeInner::Text(_, v), NodeInner::Text(_, u)) => v == u, (NodeInner::Attribute(_, name, v), NodeInner::Attribute(_, o_name, o_v)) => { if name == o_name { v == o_v } else { false } } ( NodeInner::ProcessingInstruction(_, name, v), NodeInner::ProcessingInstruction(_, o_name, o_v), ) => name == o_name && v == o_v, _ => false, } } } impl ItemNode for RNode { type NodeIterator = Box<dyn Iterator<Item = RNode>>; fn new_document() -> Self { Rc::new(Node::new()) } fn node_type(&self) -> NodeType { match &self.0 { NodeInner::Document(_, _, _, _) => NodeType::Document, NodeInner::Element(_, _, _, _, _) => NodeType::Element, NodeInner::Attribute(_, _, _) => NodeType::Attribute, NodeInner::Text(_, _) => NodeType::Text, NodeInner::Comment(_, _) => NodeType::Comment, NodeInner::ProcessingInstruction(_, _, _) => NodeType::ProcessingInstruction, NodeInner::Namespace(_, _, _) => NodeType::Namespace, } } fn name(&self) -> Rc<QualifiedName> { match &self.0 { NodeInner::Element(_, qn, _, _, _) | NodeInner::ProcessingInstruction(_, qn, _) | NodeInner::Attribute(_, qn, _) => qn.clone(), NodeInner::Namespace(_, p, _) => match p { None => Rc::new(QualifiedName::new(None, None, "")), Some(pf) => Rc::new(QualifiedName::new(None, None, pf.to_string())), }, _ => Rc::new(QualifiedName::new(None, None, "")), } } fn value(&self) -> Rc<Value> { match &self.0 { NodeInner::Text(_, v) | NodeInner::Comment(_, v) | NodeInner::ProcessingInstruction(_, _, v) | NodeInner::Attribute(_, _, v) => v.clone(), NodeInner::Namespace(_, _, ns) => ns.clone(), _ => Rc::new(Value::from("")), } } fn get_id(&self) -> String { format!("{:#p}", &(self).0 as *const NodeInner) } fn to_string(&self) -> String { match &self.0 { NodeInner::Document(_, c, _, _) | NodeInner::Element(_, _, _, c, _) => { c.borrow().iter().fold(String::new(), |mut acc, n| { acc.push_str(n.to_string().as_str()); acc }) } NodeInner::Attribute(_, _, v) | NodeInner::Text(_, v) | NodeInner::Comment(_, v) | NodeInner::ProcessingInstruction(_, _, v) => v.to_string(), NodeInner::Namespace(_, _, uri) => uri.to_string(), } } fn to_xml(&self) -> String { to_xml_int(self, &OutputDefinition::new(), 0) } fn to_xml_with_options(&self, od: &OutputDefinition) -> std::string::String { to_xml_int(self, od, 0) } fn is_same(&self, other: &Self) -> bool { Rc::ptr_eq(self, other) } fn document_order(&self) -> Vec<usize> { doc_order(self) } // Find the document node, given an arbitrary node in the tree. // There is always a document node, so this will not panic. fn owner_document(&self) -> Self { match &self.0 { NodeInner::Document(_, _, _, _) => self.clone(), _ => self.ancestor_iter().last().unwrap(), } } fn cmp_document_order(&self, other: &Self) -> Ordering { let this_order = self.document_order(); let other_order = other.document_order(); let mut this_it = this_order.iter(); let mut other_it = other_order.iter(); for _i in 0.. { match (this_it.next(), other_it.next()) { (Some(t), Some(o)) => { if t < o { return Ordering::Less; } else if t > o { return Ordering::Greater; } // otherwise continue the loop } (Some(_), None) => return Ordering::Greater, (None, Some(_)) => return Ordering::Less, (None, None) => return Ordering::Equal, } } // Will never reach here Ordering::Equal } fn child_iter(&self) -> Self::NodeIterator { Box::new(Children::new(self)) } fn ancestor_iter(&self) -> Self::NodeIterator { Box::new(Ancestors::new(self)) } fn descend_iter(&self) -> Self::NodeIterator { Box::new(Descendants::new(self)) } fn next_iter(&self) -> Self::NodeIterator { Box::new(Siblings::new(self, 1)) } fn prev_iter(&self) -> Self::NodeIterator { Box::new(Siblings::new(self, -1)) } fn attribute_iter(&self) -> Self::NodeIterator { Box::new(Attributes::new(self)) } fn namespace_iter(&self) -> Self::NodeIterator { Box::new(NamespaceNodes::new(self.clone())) } fn get_attribute(&self, a: &QualifiedName) -> Rc<Value> { match &self.0 { NodeInner::Element(_, _, att, _, _) => att .borrow() .get(a) .map_or(Rc::new(Value::from(String::new())), |v| v.value()), _ => Rc::new(Value::from(String::new())), } } fn get_attribute_node(&self, a: &QualifiedName) -> Option<Self> { match &self.0 { NodeInner::Element(_, _, att, _, _) => att.borrow().get(a).cloned(), _ => None, } } fn new_element(&self, qn: Rc<QualifiedName>) -> Result<Self, Error> { let child = Rc::new(Node(NodeInner::Element( RefCell::new(Rc::downgrade(&self.owner_document())), qn, RefCell::new(BTreeMap::new()), RefCell::new(vec![]), Rc::new(RefCell::new(BTreeMap::new())), ))); unattached(self, child.clone()); Ok(child) } fn new_namespace(&self, ns: Rc<Value>, prefix: Option<Rc<Value>>) -> Result<Self, Error> { let ns_node = Rc::new(Node(NodeInner::Namespace( RefCell::new(Rc::downgrade(&self.owner_document())), prefix, ns, ))); unattached(self, ns_node.clone()); Ok(ns_node) } fn new_text(&self, v: Rc<Value>) -> Result<Self, Error> { let child = Rc::new(Node(NodeInner::Text( RefCell::new(Rc::downgrade(&self.owner_document())), v, ))); unattached(self, child.clone()); Ok(child) } fn new_attribute(&self, qn: Rc<QualifiedName>, v: Rc<Value>) -> Result<Self, Error> { //TODO if the attribute is xml:id then type needs to be set as ID, regardless of DTD. let att = Rc::new(Node(NodeInner::Attribute( RefCell::new(Rc::downgrade(self)), qn.clone(), v, ))); unattached(self, att.clone()); Ok(att) } fn new_comment(&self, v: Rc<Value>) -> Result<Self, Error> { let child = Rc::new(Node(NodeInner::Comment( RefCell::new(Rc::downgrade(&self.owner_document())), v, ))); unattached(self, child.clone()); Ok(child) } fn new_processing_instruction( &self, qn: Rc<QualifiedName>, v: Rc<Value>, ) -> Result<Self, Error> { let child = Rc::new(Node(NodeInner::ProcessingInstruction( RefCell::new(Rc::downgrade(&self.owner_document())), qn.clone(), v, ))); unattached(self, child.clone()); Ok(child) } // Append a node to the child list of the new parent. // Must first detach the node from its current position in the tree. fn push(&mut self, n: Self) -> Result<(), Error> { if n.node_type() == NodeType::Document || n.node_type() == NodeType::Attribute || n.node_type() == NodeType::Namespace { return Err(Error::new( ErrorKind::TypeError, String::from( "document, namespace, or attribute type nodes cannot be inserted as a child", ), )); } let mut m = n.clone(); m.pop()?; push_node(self, n)?; Ok(()) } // Remove a node from the tree. If the node is unattached, then this has no effect. // The node is added to the unattached list of the owner document. fn pop(&mut self) -> Result<(), Error> { match &self.0 { NodeInner::Document(_, _, _, _) => { return Err(Error::new( ErrorKind::TypeError, String::from("cannot remove document node"), )) } NodeInner::Attribute(parent, qn, _) => { // Remove this node from the attribute hashmap let myp = Weak::upgrade(&parent.borrow()); // make borrow temporary match myp { Some(p) => { match &p.0 { NodeInner::Element(_, _, att, _, _) => { att.borrow_mut().remove(qn).ok_or(Error::new( ErrorKind::DynamicAbsent, String::from("unable to find attribute"), ))?; let doc = self.owner_document(); unattached(&doc, self.clone()); } NodeInner::Document(_, _, _, _) => {} // attr was in the unattached list _ => { return Err(Error::new( ErrorKind::TypeError, String::from("parent is not an element"), )) } } } None => { return Err(Error::new( ErrorKind::Unknown, String::from("unable to find parent"), )) } } } NodeInner::Namespace(parent, prefix, _) => { // Remove this node from the attribute hashmap match Weak::upgrade(&parent.borrow()) { Some(p) => { match &p.0 { NodeInner::Element(_, _, _, _, namespaces) => { namespaces .borrow_mut() .remove_entry(prefix) .ok_or(Error::new( ErrorKind::DynamicAbsent, String::from("unable to find namespace"), ))?; let doc = self.owner_document(); unattached(&doc, self.clone()); } NodeInner::Document(_, _, _, _) => {} // attr was in the unattached list _ => { return Err(Error::new( ErrorKind::TypeError, String::from("parent is not an element"), )) } } } None => { return Err(Error::new( ErrorKind::Unknown, String::from("unable to find parent"), )) } } } NodeInner::Element(parent, _, _, _, _) | NodeInner::Text(parent, _) | NodeInner::Comment(parent, _) | NodeInner::ProcessingInstruction(parent, _, _) => { // Remove this node from the old parent's child list let p = if let Some(q) = Weak::upgrade(&parent.borrow()) { q } else { return Err(Error::new( ErrorKind::Unknown, String::from("unable to access parent"), )); }; match &p.0 { NodeInner::Element(_, _, _, c, _) => { let idx = find_index(&p, self)?; c.borrow_mut().remove(idx); let doc = self.owner_document(); unattached(&doc, self.clone()) } NodeInner::Document(_, _, _, _) => {} // node was in the unattached list _ => { return Err(Error::new( ErrorKind::TypeError, String::from("parent is not an element"), )) } } } }; Ok(()) } fn add_attribute(&self, att: Self) -> Result<(), Error> { if att.node_type() != NodeType::Attribute { return Err(Error::new( ErrorKind::TypeError, String::from("node is not an attribute"), )); } match &self.0 { NodeInner::Element(_, _, patt, _, _) => { // Short-circuit: Is this attribute already attached to this element? if let Some(b) = patt.borrow().get(&self.name()) { if att.is_same(b) { return Ok(()); } } // Firstly, make sure the node is removed from its old parent let mut m = att.clone(); m.pop()?; // Popping will put the node in the unattached list, // so remove it from there detach(m.clone()); // Now add to this parent // TODO: deal with same name being redefined if let NodeInner::Attribute(_, qn, _) = &m.0 { let _ = patt.borrow_mut().insert(qn.clone(), m.clone()); } make_parent(m, self.clone()); Ok(()) } _ => Err(Error::new( ErrorKind::TypeError, String::from("cannot add an attribute to this type of node"), )), } } /// Add a namespace to this element-type node. /// NOTE: does NOT update the namespace values of the element itself. // TODO: confirm what the behaviour of this should be. fn add_namespace(&self, ns: Self) -> Result<(), Error> { if ns.node_type() != NodeType::Namespace { return Err(Error::new( ErrorKind::TypeError, String::from("node is not a namespace"), )); } match &self.0 { NodeInner::Element(_, _, _, _, n) => { // Firstly, make sure the node is removed from its old parent let mut m = ns.clone(); m.pop()?; // Popping will put the node in the unattached list, // so remove it from there detach(ns.clone()); // Now add to this parent // TODO: deal with same name being redefined if let NodeInner::Namespace(_, alias, _) = &m.0 { let _ = n.borrow_mut().insert(alias.clone(), ns.clone()); } make_parent(ns, self.clone()); Ok(()) } _ => Err(Error::new( ErrorKind::TypeError, String::from("cannot add a namespace to this type of node"), )), } } fn insert_before(&mut self, n: Self) -> Result<(), Error> { if n.node_type() == NodeType::Document || n.node_type() == NodeType::Attribute { return Err(Error::new( ErrorKind::TypeError, String::from("cannot insert document or attribute node"), )); } // Detach from current location let mut m = n.clone(); m.pop()?; detach(n.clone()); // Now insert into parent's child list match &self.0 { NodeInner::Element(p, _, _, _, _) | NodeInner::Text(p, _) | NodeInner::Comment(p, _) | NodeInner::ProcessingInstruction(p, _, _) => { let parent = Weak::upgrade(&p.borrow()).unwrap(); let idx = find_index(&parent, self)?; match &parent.0 { NodeInner::Document(_, children, _, _) | NodeInner::Element(_, _, _, children, _) => { children.borrow_mut().insert(idx, n.clone()); make_parent(n, parent.clone()) } _ => { return Err(Error::new( ErrorKind::TypeError, String::from("parent is not an element"), )) } } } _ => { return Err(Error::new( ErrorKind::TypeError, String::from("unable to find parent"), )) } } Ok(()) } fn shallow_copy(&self) -> Result<Self, Error> { // All new nodes are parentless, i.e. they are unattached to the tree // The new element will have the same set of in-scope namespaces as the original element. match &self.0 { NodeInner::Document(x, _, _, _) => Ok(Rc::new(Node(NodeInner::Document( x.clone(), RefCell::new(vec![]), RefCell::new(vec![]), None.into(), )))), NodeInner::Element(p, qn, _, _, ns) => { let new = Rc::new(Node(NodeInner::Element( p.clone(), qn.clone(), RefCell::new(BTreeMap::new()), RefCell::new(vec![]), ns.clone(), ))); unattached(self, new.clone()); Ok(new) } NodeInner::Attribute(p, qn, v) => Ok(Rc::new(Node(NodeInner::Attribute( p.clone(), qn.clone(), v.clone(), )))), NodeInner::Text(p, v) => { let new = Rc::new(Node(NodeInner::Text(p.clone(), v.clone()))); unattached(&self.parent().unwrap(), new.clone()); Ok(new) } NodeInner::Comment(p, v) => { let new = Rc::new(Node(NodeInner::Comment(p.clone(), v.clone()))); unattached(&self.parent().unwrap(), new.clone()); Ok(new) } NodeInner::ProcessingInstruction(p, qn, v) => { let new = Rc::new(Node(NodeInner::ProcessingInstruction( p.clone(), qn.clone(), v.clone(), ))); unattached(&self.parent().unwrap(), new.clone()); Ok(new) } NodeInner::Namespace(p, pre, uri) => { let new = Rc::new(Node(NodeInner::Namespace( p.clone(), pre.clone(), uri.clone(), ))); unattached(&self.parent().unwrap(), new.clone()); Ok(new) } } } fn deep_copy(&self) -> Result<Self, Error> { let mut new = self.shallow_copy()?; self.attribute_iter().try_for_each(|a| { new.add_attribute(a.deep_copy()?)?; Ok(()) })?; self.child_iter().try_for_each(|c| { new.push(c.deep_copy()?)?; Ok(()) })?; Ok(new) } // For special character escaping rules, see section 3.4. fn get_canonical(&self) -> Result<Self, Error> { match &self.0 { NodeInner::Document(_, e, _, _) => { let mut result = self.shallow_copy()?; for n in e.borrow_mut().iter() { if let Ok(rn) = n.get_canonical() { result.push(rn)? } } Ok(result) } NodeInner::ProcessingInstruction(_, qn, v) => { let d = self.owner_document(); let mut w = v.clone(); if let Value::String(s) = (*v.clone()).clone() { w = Rc::new(Value::String( s.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("\r", "&#D;"), )) } Ok(d.new_processing_instruction(qn.clone(), w)?) } NodeInner::Comment(_, _) | NodeInner::Namespace(_, _, _) => Err(Error::new( ErrorKind::TypeError, "invalid node type".to_string(), )), NodeInner::Text(_, v) => { let d = self.owner_document(); let mut w = v.clone(); if let Value::String(s) = (*v.clone()).clone() { w = Rc::new(Value::String( s.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("\r", "&#xD;"), )) } Ok(d.new_text(w)?) } NodeInner::Attribute(_, qn, v) => { //self.shallow_copy() let d = self.owner_document(); let w = v.to_string(); Ok(d.new_attribute( qn.clone(), Rc::new(Value::String( w.replace("&", "&amp;") .replace("<", "&lt;") .replace("\"", "&quot;") .replace("\r", "&#xD;") .replace("\t", "&#x9;") .replace("\n", "&#xA;"), )), )?) } NodeInner::Element(_, _, _, _, _) => { let mut result = self.shallow_copy()?; let d = result.owner_document(); self.attribute_iter().try_for_each(|a| { //Replace any number of spaces with a single space. let re = Regex::new(r"\s+").unwrap(); result.add_attribute( d.new_attribute( a.name(), Rc::new(Value::String( re.replace_all(a.clone().value().to_string().trim(), " ") .to_string(), )), )?, )?; //result.add_attribute(a.get_canonical()?)?; Ok::<(), Error>(()) })?; self.child_iter().try_for_each(|c| { if let Ok(rn) = c.get_canonical() { result.push(rn)? } Ok::<(), Error>(()) })?; Ok(result) } } } fn set_xmldecl(&mut self, decl: XMLDecl) -> Result<(), Error> { match &self.0 { NodeInner::Document(x, _, _, _) => { *x.borrow_mut() = Some(decl); Ok(()) } // TODO: traverse to the document node _ => Err(Error::new( ErrorKind::TypeError, String::from("not a Document node"), )), } } fn xmldecl(&self) -> XMLDecl { match &self.0 { NodeInner::Document(d, _, _, _) => d .borrow() .clone() .map_or_else(|| XMLDeclBuilder::new().build(), |x| x.clone()), _ => self.owner_document().xmldecl(), } } fn is_id(&self) -> bool { match &self.0 { //TODO Add Element XML ID support NodeInner::Attribute(_, _, v) => match v.as_ref() { Value::ID(_) => true, _ => false, }, _ => false, } } fn is_idrefs(&self) -> bool { match &self.0 { //TODO Add Element XML ID REF support NodeInner::Attribute(_, _, v) => match v.as_ref() { Value::IDREF(_) => true, Value::IDREFS(_) => true, _ => false, }, _ => false, } } fn get_dtd(&self) -> Option<DTD> { match &self.0 { NodeInner::Document(_, _, _, dtd) => dtd.borrow().clone(), _ => self.owner_document().get_dtd(), } } fn set_dtd(&self, dtd: DTD) -> Result<(), Error> { match &self.0 { NodeInner::Document(_, _, _, d) => { *d.borrow_mut() = Some(dtd); Ok(()) } // TODO: traverse to the document node _ => Err(Error::new( ErrorKind::TypeError, String::from("not a Document node"),
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
true
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/mod.rs
src/parser/mod.rs
/*! A parser combinator, inspired by nom. This parser combinator passes a context into the function, which includes the string being parsed. This supports resolving context-based constructs such as general entities and XML Namespaces. */ use crate::externals::URLResolver; use crate::item::Node; use crate::namespace::NamespaceMap; use crate::qname::QualifiedName; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use crate::xmldecl::DTD; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::fmt; use std::rc::Rc; pub(crate) mod avt; pub mod combinators; pub(crate) mod common; pub mod xml; pub mod xpath; pub mod datetime; #[allow(type_alias_bounds)] pub type ParseInput<'a, N: Node> = (&'a str, ParserState<N>); #[allow(type_alias_bounds)] pub type ParseResult<'a, N: Node, Output> = Result<(ParseInput<'a, N>, Output), ParseError>; #[derive(Clone, Debug, PartialEq)] pub enum ParseError { // The "Combinator" error just means a parser hasn't matched, its not serious necessarily. // Every other error should get returned. Combinator, // Combinator isn't correct, not a serious error. //InvalidChar{ row:usize, col:usize }, //MissingClosingElement{ row:usize, col:usize, element: String}, //IncorrectClosingElement{ row:usize, col:usize, open: String, close:String}, MissingGenEntity { row: usize, col: usize }, MissingParamEntity { row: usize, col: usize }, EntityDepth { row: usize, col: usize }, Validation { row: usize, col: usize }, //Unknown { row: usize, col: usize }, MissingNameSpace, IncorrectArguments, // An unexpected character has been encountered NotWellFormed(String), Unbalanced, Notimplemented, ExtDTDLoadError, IDError(String), } pub struct ParserConfig { /// If you need to resolve external DTDs, you will need to provide your own resolver. pub ext_dtd_resolver: Option<URLResolver>, /// The location of the string being parsed, which can be provided to your resolver to work out /// relative URLs pub docloc: Option<String>, /// Recursive entity depth, please note that setting this to a high value may leave /// you prone to the "billion laughs" attack. Set to eight by default. pub entitydepth: usize, /// Creates attributes as specified in ATTLIST declarations in the DTD. Currently only adds /// attributes where a default or fixed value is declared, does not enforce anything. /// Set to true by default. pub attr_defaults: bool, /// Track and assign XML IDs based on the DTDs. pub id_tracking: bool, } impl Default for ParserConfig { fn default() -> Self { Self::new() } } impl ParserConfig { pub fn new() -> Self { ParserConfig { ext_dtd_resolver: None, docloc: None, entitydepth: 8, attr_defaults: true, id_tracking: true, } } } #[derive(Clone)] pub struct ParserState<N: Node> { // Document node to use to create nodes doc: Option<N>, // Element to use to determine in-scope namespaces cur: Option<N>, dtd: DTD, // Do we add DTD specified attributes or not attr_defaults: bool, /* ID tracking: ids_read covers all IDs for duplicate checking. Where an IDREF is found and the ID is not yet encountered, we pull into ids_pending and will review those when we have finished parsing the document. */ id_tracking: bool, ids_read: HashSet<String>, ids_pending: HashSet<String>, /* The in-scope namespaces are tracked in a hashmap. This is used during XML document creation. The HashMap is Rc-shared. If an element does not declare any new namespaces then it shares its parent's HashMap. NOTE: the "None" key in this hashmap is used to track the namespace when no alias is declared, i.e. unprefixed names. */ namespace: Rc<NamespaceMap>, // (prefix, namespace node) /* Interning of values. Strings (represented in xrust as a Value) are often repeated. To cut down on data copying, we will intern the string and reuse it. NB. in a future version, we will intern values globally so that equality can be tested by comparing pointers. */ interned_values: Rc<RefCell<HashMap<String, Rc<Value>>>>, // Intern QualifiedNames. Map (Option<Namespace URI>, local-part) -> QN interned_names: Rc<RefCell<HashMap<(Option<Rc<Value>>, Rc<Value>), Rc<QualifiedName>>>>, standalone: bool, xmlversion: String, /* The below will track Entity Expansion, ensuring that there are no recursive entities and some protections from zip bombs */ maxentitydepth: usize, currententitydepth: usize, /* eventual error location reporting */ currentcol: usize, currentrow: usize, /* For tracking down stack overflows */ //stack: Vec<String>, //limit: Option<usize>, /* entity downloader function */ ext_dtd_resolver: Option<URLResolver>, ext_entities_to_parse: Vec<String>, docloc: Option<String>, /* ParamEntities are not allowed in internal subsets, but they are allowed in external DTDs, so we need to track when we are currently in the main document or outside it. */ currentlyexternal: bool, } impl<N: Node> ParserState<N> { pub fn new(doc: Option<N>, cur: Option<N>, parser_config: Option<ParserConfig>) -> Self { let pc = if parser_config.is_some() { parser_config.unwrap() } else { ParserConfig::new() }; let xnsprefix = Rc::new(Value::from("xml")); let xnsuri = Rc::new(Value::from("http://www.w3.org/XML/1998/namespace")); let mut ns_map = NamespaceMap::new(); ns_map.insert(Some(xnsprefix.clone()), xnsuri.clone()); ParserState { doc, cur, dtd: DTD::new(), standalone: false, xmlversion: "1.0".to_string(), // Always assume 1.0 namespace: Rc::new(ns_map), interned_values: Rc::new(RefCell::new(HashMap::from([ (String::from("xml"), xnsprefix.clone()), ( String::from("http://www.w3.org/XML/1998/namespace"), xnsuri.clone(), ), ]))), id_tracking: pc.id_tracking, ids_read: Default::default(), ids_pending: Default::default(), interned_names: Rc::new(RefCell::new(HashMap::new())), maxentitydepth: pc.entitydepth, attr_defaults: pc.attr_defaults, currententitydepth: 1, currentcol: 1, currentrow: 1, //stack: vec![], //limit: None, ext_dtd_resolver: pc.ext_dtd_resolver, ext_entities_to_parse: vec![], docloc: pc.docloc, currentlyexternal: false, } } /// Get the result document pub fn doc(&self) -> Option<N> { self.doc.clone() } /// Get the current node pub fn current(&self) -> Option<N> { self.cur.clone() } /// Get a copy of all namespaces pub fn namespaces_ref(&self) -> &NamespaceMap { &self.namespace } pub fn resolve(self, locdir: Option<String>, uri: String) -> Result<String, Error> { match self.ext_dtd_resolver { None => Err(Error::new( ErrorKind::Unknown, "No external DTD resolver provided.".to_string(), )), Some(e) => e(locdir, uri), } } pub fn get_value(&self, s: String) -> Rc<Value> { { if let Some(u) = self.interned_values.borrow().get(&s) { return u.clone(); } } // Otherwise this is a new entry let v = Rc::new(Value::from(s.clone())); self.interned_values.borrow_mut().insert(s, v.clone()); v } /// Find a QualifiedName. If the name exists in the interned names. then return a reference to the interned name. /// Otherwise, add this name to the interned names and return its reference. pub fn get_qualified_name( &self, nsuri: Option<Rc<Value>>, prefix: Option<Rc<Value>>, local_part: Rc<Value>, ) -> Rc<QualifiedName> { { if let Some(qn) = self .interned_names .borrow() .get(&(nsuri.clone(), local_part.clone())) { return qn.clone(); } } // Otherwise this is a new entry let newqn = Rc::new(QualifiedName::new_from_values( nsuri.clone(), prefix.clone(), local_part.clone(), )); self.interned_names .borrow_mut() .insert((nsuri, local_part), newqn.clone()); newqn } } impl<N: Node> PartialEq for ParserState<N> { fn eq(&self, _: &ParserState<N>) -> bool { true } } impl<N: Node> fmt::Debug for ParserState<N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ParserState").finish() } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/common.rs
src/parser/common.rs
pub(crate) fn is_namechar(ch: &char) -> bool { if is_namestartchar(ch) { true } else { matches!(ch, '.' | '-' | '0'..='9' | '\u{B7}' | '\u{0300}'..='\u{036F}' | '\u{203F}'..='\u{2040}' ) } } pub(crate) fn is_ncnamechar(ch: &char) -> bool { if is_ncnamestartchar(ch) { true } else { matches!(ch, '.' | '-' | '0'..='9' | '\u{B7}' | '\u{0300}'..='\u{036F}' | '\u{203F}'..='\u{2040}' ) } } pub(crate) fn is_namestartchar(ch: &char) -> bool { match ch { ':' => true, _ => is_ncnamestartchar(ch), } } pub(crate) fn is_ncnamestartchar(ch: &char) -> bool { matches!(ch, '\u{0041}'..='\u{005A}' // A-Z | '\u{005F}' // _ | '\u{0061}'..='\u{007A}' // a-z | '\u{00C0}'..='\u{00D6}' // [#xC0-#xD6] | '\u{00D8}'..='\u{00F6}' // [#xD8-#xF6] | '\u{00F8}'..='\u{02FF}' // [#xF8-#x2FF] | '\u{0370}'..='\u{037D}' // [#x370-#x37D] | '\u{037F}'..='\u{1FFF}' // [#x37F-#x1FFF] | '\u{200C}'..='\u{200D}' // [#x200C-#x200D] | '\u{2070}'..='\u{218F}' // [#x2070-#x218F] | '\u{2C00}'..='\u{2FEF}' // [#x2C00-#x2FEF] | '\u{3001}'..='\u{D7FF}' // [#x3001-#xD7FF] | '\u{F900}'..='\u{FDCF}' // [#xF900-#xFDCF] | '\u{FDF0}'..='\u{FFFD}' // [#xFDF0-#xFFFD] | '\u{10000}'..='\u{EFFFF}' // [#x10000-#xEFFFF] ) } pub fn is_char10(ch: &char) -> bool { matches!(ch, '\u{0009}' // #x9 | '\u{000A}' // #xA | '\u{000D}' // #xD | '\u{0020}'..='\u{D7FF}' // [#x0020-#xD7FF] | '\u{E000}'..='\u{FFFD}' // [#xE000-#xFFFD] | '\u{10000}'..='\u{10FFFF}' // [#x10000-#10FFFF] ) } pub fn is_char11(ch: &char) -> bool { matches!(ch, '\u{0001}'..='\u{D7FF}' // [#x0001-#xD7FF] | '\u{E000}'..='\u{FFFD}' // [#xE000-#xFFFD] | '\u{10000}'..='\u{10FFFF}' // [#x10000-#10FFFF] ) } pub fn is_restricted_char11(ch: &char) -> bool { matches!(ch, '\u{0001}'..='\u{0008}' // [#x0001-#x0008] | '\u{000B}'..='\u{000C}' // [#x000B-#x000C] | '\u{000E}'..='\u{001F}' // [#x000E-#x001F] | '\u{007F}'..='\u{0084}' // [#x007F-#x0084] | '\u{0086}'..='\u{009F}' // [#x007F-#x0084] ) } pub fn is_unrestricted_char11(ch: &char) -> bool { is_char11(ch) && !is_restricted_char11(ch) } pub(crate) fn is_pubid_charwithapos(ch: &char) -> bool { match ch { '\'' => true, _ => is_pubid_char(ch), } } pub(crate) fn is_pubid_char(ch: &char) -> bool { matches!(ch, '\u{0020}' // #x0020 | '\u{000A}' // #xA | '\u{000D}' // #xD | 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '(' | ')' | '+' | ',' | '.' | '/' | ':' | '=' | '?' | ';' | '!' | '*' | '#' | '@' | '$' | '_' | '%' ) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/avt/mod.rs
src/parser/avt/mod.rs
/*! Parse an Attribute Value Template. See XSL Transformations v3.0 5.6.1. */ use crate::item::{Item, Node}; use crate::parser::combinators::alt::alt2; use crate::parser::combinators::many::{many0, many1}; use crate::parser::combinators::map::map; use crate::parser::{ParseError, ParseInput, ParserState}; use crate::value::Value; use crate::xdmerror::{Error, ErrorKind}; use std::rc::Rc; //use crate::parser::combinators::debug::inspect; use crate::parser::combinators::support::none_of; use crate::parser::xpath::expr; use crate::transform::Transform; /// AVT ::= text* "{" xpath "}" text* /// A [Node] is required to resolve in-scope XML Namespaces pub fn parse<N: Node>(input: &str, n: Option<N>) -> Result<Transform<N>, Error> { let state = ParserState::new(None, n, None); match avt_expr((input, state)) { Ok((_, x)) => Ok(x), Err(err) => match err { ParseError::Combinator => Result::Err(Error::new( ErrorKind::ParseError, "Unrecoverable parser error.".to_string(), )), ParseError::NotWellFormed(e) => Result::Err(Error::new( ErrorKind::ParseError, format!("Unrecognised extra characters: \"{}\"", e), )), ParseError::Notimplemented => Result::Err(Error::new( ErrorKind::ParseError, "Unimplemented feature.".to_string(), )), _ => Err(Error::new(ErrorKind::Unknown, "Unknown error".to_string())), }, } } fn avt_expr<N: Node>(input: ParseInput<N>) -> Result<(ParseInput<N>, Transform<N>), ParseError> { match avt::<N>()(input) { Err(err) => Err(err), Ok(((input1, state1), e)) => { //Check nothing remaining in iterator, nothing after the end of the AVT. if input1.is_empty() { Ok(((input1, state1), e)) } else { Err(ParseError::NotWellFormed(format!( "unexpected extra characters: \"{}\"", input1 ))) } } } } fn avt<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Transform<N>), ParseError> + 'a> { Box::new(map( many0(alt2( map(many1(none_of("{")), |v| { Transform::Literal(Item::Value(Rc::new(Value::from( v.iter().collect::<String>(), )))) }), braced_expr(), )), |mut v| { if v.len() == 1 { v.pop().unwrap() } else { Transform::SequenceItems(v) } }, )) } /// A XPath expression in the AVT. Braces do not nest. fn braced_expr<'a, N: Node + 'a>( ) -> Box<dyn Fn(ParseInput<N>) -> Result<(ParseInput<N>, Transform<N>), ParseError> + 'a> { // Can't use combinator directly, since the close brace will be unexpected. // Instead, extract the string up to the close brace, then feed that to the combinator. // Box::new(map( // tuple3( // inspect("brace-open", tag("{")), // inspect("expr",expr()), // inspect("brace-close", tag("}")), // ), // |(_, e, _)| e // )) Box::new(move |(input, state)| match input.get(0..1) { Some("{") => match input.find('}') { None => Err(ParseError::Combinator), Some(ind) => match expr()((input.get(1..ind).unwrap(), state.clone())) { Ok((_, result)) => Ok(((input.get(ind..).map_or("", |r| r), state), result)), Err(e) => Err(e), }, }, _ => Err(ParseError::Combinator), }) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/datetime/mod.rs
src/parser/datetime/mod.rs
//! # parsepicture //! //! A parser for XPath format picture strings, as a parser combinator. //! //! This implementation is a quick-and-dirty translation to strftime format. //! //! TODO: presentation modifiers, and width modifiers use crate::item::Node; use crate::parser::combinators::alt::alt4; use crate::parser::combinators::many::many0; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::support::none_of; use crate::parser::combinators::tag::anychar; use crate::parser::combinators::tuple::{tuple2, tuple6}; use crate::parser::{ParseError, ParseInput, ParserState}; use crate::xdmerror::*; // This implementation translates an XPath picture string to a strftime format #[allow(dead_code)] fn picture<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map( many0(alt4(open_escape(), close_escape(), literal(), marker())), |v| v.iter().cloned().collect::<String>(), ) } #[allow(dead_code)] fn literal<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map(none_of("[]"), String::from) } #[allow(dead_code)] fn marker<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map( tuple6( anychar('['), none_of("]"), opt(none_of(",]")), opt(none_of(",]")), opt(tuple2(anychar(','), none_of("]"))), anychar(']'), ), |(_, c, _p1, _p2, _w, _)| { match c { 'Y' => String::from("%Y"), 'M' => String::from("%m"), 'D' => String::from("%d"), 'd' => String::from("%j"), 'F' => String::from("%A"), 'W' => String::from("%U"), 'w' => String::from(""), // not supported 'H' => String::from("%H"), 'h' => String::from("%I"), 'P' => String::from("%P"), 'm' => String::from("%M"), 's' => String::from("%S"), 'f' => String::from("%f"), 'Z' => String::from("%Z"), 'z' => String::from("%:z"), // partial support 'C' => String::from(""), // not supported 'E' => String::from(""), // not supported _ => String::from(""), // error } }, ) } #[allow(dead_code)] fn open_escape<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map(tuple2(anychar('['), anychar('[')), |_| String::from("[")) } #[allow(dead_code)] fn close_escape<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map(tuple2(anychar(']'), anychar(']')), |_| String::from("]")) } pub fn parse<N: Node>(e: &str) -> Result<String, Error> { let state: ParserState<N> = ParserState::new(None, None, None); match picture()((e, state)) { Ok(((rem, _), value)) => { if rem.is_empty() { Ok(value) } else { Err(Error::new( ErrorKind::Unknown, format!("extra characters after expression: \"{}\"", rem), )) } } Err(_) => Err(Error::new( ErrorKind::ParseError, String::from("unable to parse picture"), )), } } #[cfg(test)] mod tests { use super::*; use crate::trees::nullo::Nullo; #[test] fn picture_empty() { let pic = parse::<Nullo>("").expect("failed to parse picture \"\""); assert_eq!(pic, ""); } #[test] fn picture_date() { let pic = parse::<Nullo>("[D] [M] [Y]").expect("failed to parse picture \"[D] [M] [Y]\""); assert_eq!(pic, "%d %m %Y"); } #[test] fn picture_time() { let pic = parse::<Nullo>("Hr [h][P] Mins [m] secs [s],[f]") .expect("failed to parse picture \"Hr [h][P] Mins [m] secs [s],[f]\""); assert_eq!(pic, "Hr %I%P Mins %M secs %S,%f"); } #[test] fn picture_datetime() { let pic = parse::<Nullo>("[D]/[M]/[Y] [H]:[m]:[s]") .expect("failed to parse picture \"[D]/[M]/[Y] [H]:[m]:[s]\""); assert_eq!(pic, "%d/%m/%Y %H:%M:%S"); } #[test] fn picture_escapes() { let pic = parse::<Nullo>("[[[D]/[M]/[Y]]] [[[H]:[m]:[s]]]") .expect("failed to parse picture \"[D]/[M]/[Y] [H]:[m]:[s]\""); assert_eq!(pic, "[%d/%m/%Y] [%H:%M:%S]"); } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/reference.rs
src/parser/xml/reference.rs
use crate::item::{Node, NodeType}; use crate::parser::combinators::delimited::delimited; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::take_until; use crate::parser::xml::dtd::extsubset::extsubset; use crate::parser::xml::element::content; use crate::parser::{ParseError, ParseInput}; use crate::value::Value; use std::rc::Rc; // Reference ::= EntityRef | CharRef // \Its important to note, we pre-populate the standard char references in the DTD. pub(crate) fn reference<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, Vec<N>), ParseError> { move |(input, state)| { let e = delimited(tag("&"), take_until(";"), tag(";"))((input, state.clone())); match e { Err(e) => Err(e), Ok(((input1, mut state1), entitykey)) => { match entitykey.as_str() { "amp" => Ok(( (input1, state1), vec![state .doc .clone() .unwrap() .new_text(Rc::new(Value::String("&".to_string()))) .expect("unable to create text node")], )), "gt" => Ok(( (input1, state1), vec![state .doc .clone() .unwrap() .new_text(Rc::new(Value::String(">".to_string()))) .expect("unable to create text node")], )), "lt" => Ok(( (input1, state1), vec![state .doc .clone() .unwrap() .new_text(Rc::new(Value::String("<".to_string()))) .expect("unable to create text node")], )), "quot" => Ok(( (input1, state1), vec![state .doc .clone() .unwrap() .new_text(Rc::new(Value::String("\"".to_string()))) .expect("unable to create text node")], )), "apos" => Ok(( (input1, state1), vec![state .doc .clone() .unwrap() .new_text(Rc::new(Value::String("'".to_string()))) .expect("unable to create text node")], )), _ => { match state1.clone().dtd.generalentities.get(&entitykey as &str) { Some((entval, _)) => { if state1.currententitydepth >= state1.maxentitydepth { //attempting to exceed expansion depth Err(ParseError::EntityDepth { col: state1.currentcol, row: state1.currentrow, }) } else { //Parse the entity, using the parserstate which has information on namespaces let mut tempstate = state1.clone(); tempstate.currententitydepth += 1; /* We want to reuse the "Content" combinator to parse the entity, but that function parses everything up until the closing tag of an XML element. The fix? We append a < character and the parser will stop as if its hit that closing tag. Then we check that that closing tag is all that remained on the parsing. */ let mut e2 = entval.clone(); e2.push('<'); match content()((e2.as_str(), tempstate)) { Ok(((outstr, _), nodes)) => { if outstr != "<" { Err(ParseError::NotWellFormed(outstr.to_string())) } else { Ok(((input1, state1), nodes)) } } Err(_) => Err(ParseError::NotWellFormed(e2)), } } } None => { /* Check if any unparsed DTDs, if so parse and try again. */ match state1.ext_entities_to_parse.pop() { None => Err(ParseError::MissingGenEntity { col: state1.currentcol, row: state1.currentrow, }), Some(sid) => { match state1.clone().resolve(state1.docloc.clone(), sid) { Err(_) => Err(ParseError::ExtDTDLoadError), Ok(s) => { match extsubset()((s.as_str(), state1)) { Err(e) => Err(e), Ok(((_, state2), _)) => { match state2 .clone() .dtd .generalentities .get(&entitykey as &str) { Some((entval, _)) => { if state2.currententitydepth >= state2.maxentitydepth { //attempting to exceed expansion depth Err(ParseError::EntityDepth { col: state2.currentcol, row: state2.currentrow, }) } else { //Parse the entity, using the parserstate which has information on namespaces let mut tempstate = state2.clone(); tempstate.currententitydepth += 1; /* We want to reuse the "Content" combinator to parse the entity, but that function parses everything up until the closing tag of an XML element. The fix? We append a < character and the parser will stop as if its hit that closing tag. Then we check that that closing tag is all that remained on the parsing. */ let mut e2 = entval.clone(); e2.push('<'); match content()((e2.as_str(), tempstate)) { Ok(((outstr, _), nodes)) => { if outstr != "<" { Err(ParseError::NotWellFormed(outstr.to_string())) } else { Ok(((input1, state2), nodes)) } } Err(_) => Err(ParseError::NotWellFormed(e2)), } } } None => { Err(ParseError::MissingGenEntity { col: state2.currentcol, row: state2.currentrow, }) } } } } } } } } } } } } } } } } pub(crate) fn textreference<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { move |(input, state)| { let e = delimited(tag("&"), take_until(";"), tag(";"))((input, state)); match e { Err(e) => Err(e), Ok(((input1, state1), entitykey)) => { //if !["lt", "gt", "apos", "amp", "quot"].contains(&entitykey.as_str()){ match entitykey.as_str() { "amp" => Ok(((input1, state1), "&".to_string())), "gt" => Ok(((input1, state1), ">".to_string())), "lt" => Ok(((input1, state1), "<".to_string())), "quot" => Ok(((input1, state1), "\"".to_string())), "apos" => Ok(((input1, state1), "'".to_string())), _ => { match state1.clone().dtd.generalentities.get(&entitykey as &str) { Some((entval, _)) => { if state1.currententitydepth >= state1.maxentitydepth { //attempting to exceed expansion depth Err(ParseError::EntityDepth { col: state1.currentcol, row: state1.currentrow, }) } else { //Parse the entity, using the parserstate which has information on namespaces let mut tempstate = state1.clone(); tempstate.currententitydepth += 1; /* We want to reuse the "Content" combinator to parse the entity, but that function parses everything up until the closing tag of an XML element. The fix? We append a < character and the parser will stop as if its hit that closing tag. Then we check that that closing tag is all that remained on the parsing. */ let mut e2 = entval.clone(); e2.push('<'); match content()((e2.as_str(), tempstate)) { Ok(((outstr, _), nodes)) => { if outstr != "<" { Err(ParseError::NotWellFormed(outstr.to_string())) } else { let mut res = vec![]; for rn in nodes { match rn.node_type() { NodeType::Text => res.push(rn.to_string()), _ => { return Err(ParseError::NotWellFormed( String::from("not a text node"), )) } } } Ok(((input1, state1), res.concat())) } } Err(_) => Err(ParseError::NotWellFormed(e2)), } } } None => Err(ParseError::MissingGenEntity { col: state1.currentcol, row: state1.currentrow, }), } //} else { // Err(ParseError::Combinator) //} } } } } } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/attribute.rs
src/parser/xml/attribute.rs
use crate::item::Node; use crate::namespace::NamespaceMap; use crate::parser::combinators::alt::{alt2, alt3}; use crate::parser::combinators::delimited::delimited; use crate::parser::combinators::many::many0; use crate::parser::combinators::map::map; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::take_while; use crate::parser::combinators::tuple::tuple6; use crate::parser::combinators::wellformed::wellformed; use crate::parser::combinators::whitespace::{whitespace0, whitespace1}; use crate::parser::common::{is_char10, is_char11}; use crate::parser::xml::chardata::chardata_unicode_codepoint; use crate::parser::xml::qname::qualname; use crate::parser::xml::reference::textreference; use crate::parser::{ParseError, ParseInput}; use crate::qname::QualifiedName; use crate::{Error, ErrorKind}; use std::collections::HashSet; use std::rc::Rc; /// Parse all of the attributes in an element's start tag. /// Returns (attribute nodes, namespace declaration nodes). pub(crate) fn attributes<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, (Vec<(QualifiedName, String)>, Vec<N>)), ParseError> { move |input| match many0(attribute())(input) { Ok(((input1, mut state1), nodes)) => { let doc = state1.doc.clone().unwrap().clone(); // If new namespaces are declared, then construct a new namespace hashmap // with the old entries overlaid with the new entries. // Otherwise, use the existing hashmap. // To do this, we need to know whether new namespaces are being declared, // so put these in a vector. let mut new_namespaces = vec![]; let mut new_namespace_prefixes = HashSet::new(); for (qn, val) in nodes.clone() { // Cache qn, val string values for faster comparison let qn_str = qn.to_string(); let qn_prefix = qn.prefix_to_string(); let qn_prefix_str = qn_prefix.map_or(String::from(""), |p| p); let qn_localname = qn.localname_to_string(); let val_str = val.to_string(); //Return error if someone attempts to redefine namespaces. if qn_prefix_str == "xmlns" && qn_localname == "xmlns" { return Err(ParseError::NotWellFormed(String::from( "cannot redefine namespace", ))); } //xml prefix must always be set to http://www.w3.org/XML/1998/namespace if qn_prefix_str == "xmlns" && qn_localname == "xml" && val_str != "http://www.w3.org/XML/1998/namespace" { return Err(ParseError::NotWellFormed(String::from( "xml namespace URI must be http://www.w3.org/XML/1998/namespace", ))); } // http://www.w3.org/XML/1998/namespace must always be bound to xml if qn_prefix_str == "xmlns" && qn_localname != "xml" && val_str == "http://www.w3.org/XML/1998/namespace" { return Err(ParseError::NotWellFormed(String::from( "XML namespace must be bound to xml prefix", ))); } // http://www.w3.org/2000/xmlns/ must always be bound to xmlns if qn_prefix_str == "xmlns" && qn_localname != "xmlns" && val_str == "http://www.w3.org/2000/xmlns/" { return Err(ParseError::NotWellFormed(String::from( "XMLNS namespace must be bound to xmlns prefix", ))); } // Default namespace cannot be http://www.w3.org/XML/1998/namespace // Default namespace cannot be http://www.w3.org/2000/xmlns/ if qn_prefix_str.is_empty() && qn_localname == "xmlns" && (val_str == "http://www.w3.org/XML/1998/namespace" || val_str == "http://www.w3.org/2000/xmlns/") { return Err(ParseError::NotWellFormed(String::from( "invalid default namespace", ))); } // XML 1.0 documents cannot redefine an alias to "" if qn_prefix_str == "xmlns" && !qn_localname.is_empty() && val_str.is_empty() && state1.xmlversion == *"1.0" { return Err(ParseError::NotWellFormed(String::from( "cannot redefine alias to empty", ))); } if qn_prefix_str == "xmlns" { new_namespaces.push( doc.new_namespace(state1.get_value(val), Some(qn.localname())) .expect("unable to create namespace node"), ); match new_namespace_prefixes.insert(Some(qn.localname())) { true => {} false => { return Err(ParseError::NotWellFormed(String::from( "duplicate namespace declaration", ))); } } //namespaces.insert(Some(qn.get_localname()), val.to_string()); //resnsnodes.insert(Some(qn.get_localname()), val.to_string()); } else if qn_localname == "xmlns" && !val_str.is_empty() { new_namespaces.push( doc.new_namespace(state1.get_value(val), None) .expect("unable to create default namespace node"), ); match new_namespace_prefixes.insert(None) { true => {} false => { return Err(ParseError::NotWellFormed(String::from( "duplicate namespace declaration", ))); } } //namespaces.insert(None, val.to_string()); //resnsnodes.insert(None, val.to_string()); }; // If the namespace is set like xmlns="", we remove from the list // TODO: improve handling of undeclaring the default namespace if qn_localname == "xmlns" && val_str.is_empty() { //namespaces.remove(&None); //resnsnodes.remove(&None); }; //Check if the xml:space attribute is present and if so, does it have //"Preserved" or "Default" as its value. We'll actually handle in a future release. if qn_prefix_str == "xml" && qn_localname == "space" && !(qn_str == "Default" || qn_str == "Preserve") { return Err(ParseError::Validation { row: state1.currentrow, col: state1.currentcol, }); } } // Now construct the namespace hashmap, if required //state1.namespace.push(namespaces.clone()); if !new_namespaces.is_empty() { // We will build a new namespace hashmap let mut new_ns_hm = NamespaceMap::new(); state1.namespace.iter().for_each(|(old_prefix, old_nsuri)| { new_ns_hm.insert(old_prefix.clone(), old_nsuri.clone()); }); new_namespaces.iter().for_each(|nsnode| { let prefix = nsnode.name().localname(); let o = if prefix.to_string().is_empty() { None } else { Some(prefix) }; new_ns_hm.insert(o, nsnode.value()); }); state1.namespace = Rc::new(new_ns_hm); } // else just reuse the existing hashmap //Why loop through the nodes a second time? XML attributes are not in any order, so the //namespace declaration can happen after the attribute if it has a namespace prefix. // SRB: TODO: partition the nodes vector based on whether the attribute has a prefix (and is not a namespace declaration) // Then loop through the prefixed attributes after the namespaces have been processed let mut resnodes = vec![]; //This vec tracks duplicate attrs let mut resnodenames = vec![]; for (mut qn, attrval) in nodes { let qn_prefix = qn.prefix_to_string().map_or(String::from(""), |s| s); let qn_localname = qn.localname_to_string(); if qn_prefix != "xmlns" && qn_localname != "xmlns" { if qn .resolve(|p| { state1.namespace.get(&p).map_or( Err(Error::new( ErrorKind::DynamicAbsent, "no namespace for prefix", )), |r| Ok(r.clone()), ) }) .is_err() { return Err(ParseError::MissingNameSpace); } if qn_prefix != "xmlns" && !qn_prefix.is_empty() { match qn.namespace_uri() { None => { return Err(ParseError::MissingNameSpace); } Some(u) => { if u.to_string().is_empty() { return Err(ParseError::MissingNameSpace); } } } } /* We don't return fully completed attributes here because we need to do some DTD checking on the element to manage IDs. */ resnodes.push((qn.clone(), attrval)); /* Why not just use resnodes.contains() ? I don't know how to do partial matching */ if resnodenames.contains(&(qn.namespace_uri(), qn.localname())) { return Err(ParseError::NotWellFormed(String::from( "duplicate attributes", ))); } else { resnodenames.push((qn.namespace_uri(), qn.localname())); } } } Ok(((input1, state1), (resnodes, new_namespaces))) } Err(err) => Err(err), } } // Attribute ::= Name '=' AttValue fn attribute<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, (QualifiedName, String)), ParseError> { move |(input, state)| match tuple6( whitespace1(), qualname(), whitespace0(), tag("="), whitespace0(), attribute_value(), )((input, state)) { Ok(((input1, state1), (_, n, _, _, _, s))) => Ok(((input1, state1.clone()), (n, s))), Err(e) => Err(e), } } fn attribute_value<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { move |(input, state)| { let parse = alt2( delimited( tag("'"), many0(alt3( map(chardata_unicode_codepoint(), |c| c.to_string()), textreference(), wellformed(take_while(|c| c != '&' && c != '\''), |c| !c.contains('<')), )), tag("'"), ), delimited( tag("\""), many0(alt3( map(chardata_unicode_codepoint(), |c| c.to_string()), textreference(), wellformed(take_while(|c| c != '&' && c != '\"'), |c| !c.contains('<')), )), tag("\""), ), )((input, state)); match parse { Err(e) => Err(e), Ok(((input1, state1), rn)) => { /* For each character, entity reference, or character reference in the unnormalized attribute value, beginning with the first and continuing to the last, do the following: For a character reference, append the referenced character to the normalized value. For an entity reference, recursively apply step 3 of this algorithm to the replacement text of the entity. For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value. For another character, append the character to the normalized value. */ let r = rn .concat() .replace(['\n', '\r', '\t', '\n'], " ") .trim() .to_string(); //NEL character cannot be in attributes. if state1.xmlversion == "1.1" && r.find(|c| !is_char11(&c)).is_some() { Err(ParseError::NotWellFormed(r)) } else if r.find(|c| !is_char10(&c)).is_some() { Err(ParseError::NotWellFormed(r)) } else if r.contains('\u{0085}') { Err(ParseError::NotWellFormed(r)) } else { Ok(((input1, state1), r)) } } } } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/misc.rs
src/parser/xml/misc.rs
use crate::item::{Node, NodeType}; use crate::parser::combinators::alt::alt2; use crate::parser::combinators::delimited::delimited; use crate::parser::combinators::many::many0; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::take_until; use crate::parser::combinators::tuple::{tuple2, tuple5}; use crate::parser::combinators::wellformed::wellformed_ver; use crate::parser::combinators::whitespace::{whitespace0, whitespace1}; use crate::parser::common::{is_char10, is_char11}; use crate::parser::xml::qname::name; use crate::parser::{ParseError, ParseInput}; // PI ::= '<?' PITarget (char* - '?>') '?>' pub(crate) fn processing_instruction<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, N), ParseError> { move |(input, state)| { wellformed_ver( map( tuple5( tag("<?"), name(), opt(tuple2(whitespace1(), take_until("?>"))), whitespace0(), tag("?>"), ), |(_, n, vt, _, _)| match vt { None => state .doc .as_ref() .unwrap() .new_processing_instruction( state.get_qualified_name(None, None, state.get_value(n)), state.get_value("".to_string()), ) .expect("unable to create processing instruction"), Some((_, v)) => state .doc .as_ref() .unwrap() .new_processing_instruction( state.get_qualified_name(None, None, state.get_value(n)), state.get_value(v), ) .expect("unable to create processing instruction"), }, ), //XML 1.0 |v| match v.node_type() { NodeType::ProcessingInstruction => { if v.to_string().contains(|c: char| !is_char10(&c)) { false } else if v.name().to_string().contains(':') { //"No entity names, processing instruction targets, or notation names contain any colons." false } else { v.name().to_string().to_lowercase() != *"xml" } } _ => false, }, //XML 1.1 |v| match v.node_type() { NodeType::ProcessingInstruction => { if v.to_string().contains(|c: char| !is_char11(&c)) { false } else if v.name().to_string().contains(':') { // "No entity names, processing instruction targets, or notation names contain any colons." false } else { v.name().to_string().to_lowercase() != *"xml" } } _ => false, }, )((input, state.clone())) } } // Comment ::= '<!--' (char* - '--') '-->' pub(crate) fn comment<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, N), ParseError> { |(input, state)| { wellformed_ver( map( delimited(tag("<!--"), take_until("--"), tag("-->")), |v: String| { state .doc .as_ref() .unwrap() .new_comment(state.get_value(v)) .expect("unable to create comment") }, ), //XML 1.0 |v| match v.node_type() { NodeType::Comment => !v.to_string().contains(|c: char| !is_char10(&c)), _ => false, }, //XML 1.1 |v| match v.node_type() { NodeType::Comment => !v.to_string().contains(|c: char| !is_char11(&c)), _ => false, }, )((input, state.clone())) } } // Misc ::= Comment | PI | S pub(crate) fn misc<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, Vec<N>), ParseError> { map( tuple2( many0(map( alt2( tuple2(whitespace0(), comment()), tuple2(whitespace0(), processing_instruction()), ), |(_ws, xn)| xn, )), whitespace0(), ), |(v, _)| v, ) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/element.rs
src/parser/xml/element.rs
use crate::item::{Node, NodeType}; use crate::parser::combinators::alt::{alt2, alt4}; use crate::parser::combinators::many::many0nsreset; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::tag::tag; use crate::parser::combinators::tuple::{tuple10, tuple2, tuple5}; use crate::parser::combinators::wellformed::wellformed; use crate::parser::combinators::whitespace::whitespace0; use crate::parser::xml::attribute::attributes; use crate::parser::xml::chardata::chardata; use crate::parser::xml::misc::{comment, processing_instruction}; use crate::parser::xml::qname::qualname; use crate::parser::xml::reference::reference; use crate::parser::{ParseError, ParseInput}; use crate::qname::QualifiedName; use crate::xmldecl::{AttType, DefaultDecl}; use crate::{Error, ErrorKind, Value}; use std::rc::Rc; // Element ::= EmptyElemTag | STag content ETag pub(crate) fn element<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, N), ParseError> { move |input| match alt2( //Empty element map( tuple5( tag("<"), wellformed(qualname(), |qn| { qn.prefix_to_string() != Some("xmlns".to_string()) }), attributes(), //many0(attribute), whitespace0(), tag("/>"), ), |(_, n, (at, ns), _, _)| ((), n.clone(), (at, ns), (), (), vec![], (), n, (), ()), ), //tagged element wellformed( tuple10( tag("<"), wellformed(qualname(), |qn| { qn.prefix_to_string() != Some("xmlns".to_string()) }), attributes(), //many0(attribute), whitespace0(), tag(">"), content(), tag("</"), wellformed(qualname(), |qn| { qn.prefix_to_string() != Some("xmlns".to_string()) }), whitespace0(), tag(">"), ), |(_, n, _a, _, _, _c, _, e, _, _)| n.to_string() == e.to_string(), ), )(input) { Err(err) => Err(err), Ok(((input1, mut state1), (_, mut n, (av, namespaces), _, _, c, _, _, _, _))) => { if n.resolve(|p| { state1.namespace.get(&p).map_or( Err(Error::new( ErrorKind::DynamicAbsent, "no namespace for prefix", )), |r| Ok(r.clone()), ) }) .is_err() { return Err(ParseError::MissingNameSpace); } let elementname = state1.get_qualified_name(n.namespace_uri(), n.prefix(), n.localname()); if state1.xmlversion == "1.1" && elementname.namespace_uri_to_string() == Some("".to_string()) && elementname.prefix_to_string().is_some() { return Err(ParseError::MissingNameSpace); } let d = state1.doc.clone().unwrap(); let mut e = d .new_element(elementname) .expect("unable to create element"); //Looking up the DTD, seeing if there are any attributes we should populate //Remember, DTDs don't have namespaces, you need to lookup based on prefix and local name! // We generate the attributes in two sweeps: // Once for attributes declared on the element and once for the DTD default attribute values. let attlist = state1.dtd.attlists.get(&QualifiedName::new_from_values( None, n.prefix(), n.localname(), )); match attlist { None => { //No Attribute DTD, just insert all attributes. for (attname, attval) in av.into_iter() { //Ordinarily, you'll just treat attributes as CDATA and not normalize, however we need to check xml:id let av: String; let a: N; if attname.prefix_to_string() == Some("xml".to_string()) && attname.localname_to_string() == "id" { av = attval.trim().replace(" ", " "); a = d .new_attribute(Rc::new(attname), Rc::new(Value::ID(av))) .expect("unable to create attribute"); } else { av = attval; a = d .new_attribute(Rc::new(attname), state1.get_value(av)) .expect("unable to create attribute"); }; e.add_attribute(a).expect("unable to add attribute") } } Some(atts) => { if state1.attr_defaults { for (attname, (atttype, defdecl, _)) in atts.iter() { match defdecl { DefaultDecl::Default(s) | DefaultDecl::FIXED(s) => { let mut at = attname.clone(); match at.prefix() { None => {} Some(_) => { if at .resolve(|p| { state1.namespace.get(&p).map_or( Err(Error::new( ErrorKind::DynamicAbsent, "no namespace for prefix", )), |r| Ok(r.clone()), ) }) .is_err() { return Err(ParseError::MissingNameSpace); } } } //https://www.w3.org/TR/xml11/#AVNormalize let attval = match atttype { AttType::CDATA => s.clone(), _ => s.trim().replace(" ", " "), }; let a = d .new_attribute(Rc::new(at), state1.get_value(attval)) .expect("unable to create attribute"); e.add_attribute(a).expect("unable to add attribute") } _ => {} } } } for (attname, attval) in av.into_iter() { match atts.get(&QualifiedName::new( None, attname.prefix_to_string(), attname.localname_to_string(), )) { //No DTD found, we just create the value None => { //Ordinarily, you'll just treat attributes as CDATA and not normalize, however we need to check xml:id let av = if attname.prefix_to_string() == Some("xml".to_string()) && attname.localname_to_string() == "id" { attval.trim().replace(" ", " ") } else { attval }; let a = d .new_attribute(Rc::new(attname), state1.get_value(av)) .expect("unable to create attribute"); e.add_attribute(a).expect("unable to add attribute") } Some((atttype, _, _)) => { //https://www.w3.org/TR/xml11/#AVNormalize let av = match atttype { AttType::CDATA => attval, _ => attval.trim().replace(" ", " "), }; //Assign IDs only if we are tracking. let v = match (atttype, state1.id_tracking) { (AttType::ID, true) => Rc::new(Value::ID(av)), (AttType::IDREF, true) => Rc::new(Value::IDREF(av)), (AttType::IDREFS, true) => Rc::new(Value::IDREFS( av.split(' ').map(|s| s.to_string()).collect(), )), (_, _) => state1.get_value(av), }; let a = d .new_attribute(Rc::new(attname), v) .expect("unable to create attribute"); e.add_attribute(a).expect("unable to add attribute") } } } } } //we've added the IDs and IDRefs, but we need to track all that. if state1.id_tracking { for attribute in e.attribute_iter() { if attribute.is_id() { match state1.ids_read.insert(attribute.to_string()) { true => {} false => { //Value already existed! return Err(ParseError::IDError(String::from( "Diplicate ID found", ))); } } } if attribute.is_idrefs() { /* If the IDRef matches a previously loaded ID, we're all good. If not, that ID may exist further along, we'll make a note of it to check when we have completely parsed the document. */ for idref in attribute.value().to_string().split_whitespace() { match state1.ids_read.get(idref) { Some(_) => {} None => { state1.ids_pending.insert(idref.to_string()); } } } } } } namespaces .iter() .for_each(|b| e.add_namespace(b.clone()).expect("unable to add namespace")); // Add child nodes c.iter().for_each(|d| { e.push(d.clone()).expect("unable to add node"); }); Ok(((input1, state1.clone()), e)) } } } // content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)* pub(crate) fn content<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, Vec<N>), ParseError> { move |(input, state)| match tuple2( opt(chardata()), many0nsreset(tuple2( alt4( map(processing_instruction(), |e| vec![e]), map(comment(), |e| vec![e]), map(element(), |e| vec![e]), reference(), ), opt(chardata()), )), )((input, state.clone())) { Ok((state1, (c, v))) => { let mut new: Vec<N> = Vec::new(); let mut notex: Vec<String> = Vec::new(); if c.is_some() { notex.push(c.unwrap()); } if !v.is_empty() { for (w, d) in v { for x in w { match x.node_type() { NodeType::Text => notex.push(x.to_string()), _ => { if !notex.is_empty() { new.push( state .doc .clone() .unwrap() .new_text(Rc::new(Value::String(notex.concat()))) .expect("unable to create text node"), ); notex.clear(); } new.push(x); } } } if d.is_some() { notex.push(d.unwrap()) } } } if !notex.is_empty() { new.push( state .doc .clone() .unwrap() .new_text(Rc::new(Value::String(notex.concat()))) .expect("unable to create text node"), ); } Ok((state1, new)) } Err(e) => Err(e), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/mod.rs
src/parser/xml/mod.rs
mod attribute; mod chardata; mod dtd; mod element; mod misc; pub mod qname; mod reference; mod strings; mod xmldecl; use crate::item::Node; use crate::namespace::NamespaceMap; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::tag::tag; use crate::parser::combinators::tuple::tuple4; use crate::parser::xml::dtd::doctypedecl; use crate::parser::xml::element::element; use crate::parser::xml::misc::misc; use crate::parser::xml::xmldecl::xmldecl; use crate::parser::{ParseError, ParseInput, ParserConfig, ParserState}; use crate::xdmerror::{Error, ErrorKind}; use crate::xmldecl::XMLDecl; use std::rc::Rc; pub fn parse<N: Node>(doc: N, input: &str, config: Option<ParserConfig>) -> Result<N, Error> { let (xmldoc, _) = parse_with_ns(doc, input, config)?; Ok(xmldoc) } pub fn parse_with_ns<N: Node>( doc: N, input: &str, config: Option<ParserConfig>, ) -> Result<(N, Rc<NamespaceMap>), Error> { let state = ParserState::new(Some(doc), None, config); match document((input, state)) { Ok(((_, state1), xmldoc)) => Ok((xmldoc, state1.namespace.clone())), Err(err) => { match err { ParseError::Combinator => Err(Error::new( ErrorKind::ParseError, format!( "Unrecoverable parser error while parsing XML \"{}\"", input.chars().take(80).collect::<String>() ), )), /* ParseError::InvalidChar { row, col } => { Result::Err(Error { kind: ErrorKind::ParseError, message: "Invalid character in document.".to_string(), }) } */ ParseError::MissingGenEntity { .. } => Err(Error::new( ErrorKind::ParseError, "Missing Gen Entity.".to_string(), )), ParseError::MissingParamEntity { .. } => Err(Error::new( ErrorKind::ParseError, "Missing Param Entity.".to_string(), )), ParseError::EntityDepth { .. } => Err(Error::new( ErrorKind::ParseError, "Entity depth limit exceeded".to_string(), )), ParseError::Validation { .. } => Err(Error::new( ErrorKind::ParseError, "Validation error.".to_string(), )), ParseError::MissingNameSpace => Err(Error::new( ErrorKind::ParseError, "Missing namespace declaration.".to_string(), )), ParseError::NotWellFormed(s) => Err(Error::new( ErrorKind::ParseError, format!("XML document not well formed at \"{}\".", s), )), ParseError::ExtDTDLoadError => Err(Error::new( ErrorKind::ParseError, "Unable to open external DTD.".to_string(), )), ParseError::Notimplemented => Err(Error::new( ErrorKind::ParseError, "Unimplemented feature.".to_string(), )), _ => Err(Error::new(ErrorKind::Unknown, "Unknown error.".to_string())), } } } } fn document<N: Node>(input: ParseInput<N>) -> Result<(ParseInput<N>, N), ParseError> { match tuple4(opt(utf8bom()), opt(prolog()), element(), opt(misc()))(input) { Err(err) => Err(err), Ok(((input1, state1), (_, p, e, m))) => { //Check nothing remaining in iterator, nothing after the end of the root node. if input1.is_empty() { /* We were checking XML IDRefs as we parsed, but sometimes an ID comes after the IDREF, we now check those cases to ensure that all IDs needed were reported. */ if state1.id_tracking { for idref in state1.ids_pending.iter() { match state1.ids_read.get(idref) { None => return Err(ParseError::IDError(String::from("ID missing"))), Some(_) => {} } } } let pr = p.unwrap_or((None, vec![])); let mut d = state1.doc.clone().unwrap(); pr.1.iter() .for_each(|n| d.push(n.clone()).expect("unable to add node")); d.push(e).expect("unable to add node"); m.unwrap_or_default() .iter() .for_each(|n| d.push(n.clone()).expect("unable to add node")); if let Some(x) = pr.0 { let _ = d.set_xmldecl(x); } if !state1.dtd.patterns.is_empty() { let _ = d.set_dtd(state1.dtd.clone()); }; Ok(( (input1, state1.clone()), state1.doc.clone().unwrap().clone(), )) } else { Err(ParseError::NotWellFormed(format!( "unexpected extra characters: \"{}\"", input1 ))) } } } } // prolog ::= XMLDecl misc* (doctypedecl Misc*)? fn prolog<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, (Option<XMLDecl>, Vec<N>)), ParseError> { map( tuple4(opt(xmldecl()), misc(), opt(doctypedecl()), misc()), |(xmld, mut m1, _dtd, mut m2)| { m1.append(&mut m2); (xmld, m1) }, ) } fn utf8bom<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, ()), ParseError> { tag("\u{feff}") }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/xmldecl.rs
src/parser/xml/xmldecl.rs
use crate::item::Node; use crate::parser::combinators::alt::alt2; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::{take_one, take_while}; use crate::parser::combinators::tuple::{tuple2, tuple3, tuple5, tuple6, tuple8}; use crate::parser::combinators::wellformed::wellformed; use crate::parser::combinators::whitespace::{whitespace0, whitespace1}; use crate::parser::xml::strings::delimited_string; use crate::parser::{ParseError, ParseInput}; use crate::xmldecl::XMLDecl; fn xmldeclversion<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { move |input| match tuple5( tag("version"), whitespace0(), tag("="), whitespace0(), delimited_string(), )(input) { Ok((input1, (_, _, _, _, v))) => { if v.parse::<f64>().is_ok() { if v == *"1.1" { Ok((input1, v)) } else if v.starts_with("1.") { Ok((input1, "1.0".to_string())) } else { Err(ParseError::Notimplemented) } } else { Err(ParseError::NotWellFormed(v)) } } Err(err) => Err(err), } } fn xmldeclstandalone<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { move |(input, state)| match map( wellformed( tuple6( whitespace1(), tag("standalone"), whitespace0(), tag("="), whitespace0(), delimited_string(), ), |(_, _, _, _, _, s)| ["yes".to_string(), "no".to_string()].contains(s), ), |(_, _, _, _, _, s)| s, )((input, state)) { Err(e) => Err(e), Ok(((input2, mut state2), sta)) => { if &sta == "yes" { state2.standalone = true; } Ok(((input2, state2), sta)) } } } pub(crate) fn encodingdecl<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map( tuple6( whitespace1(), tag("encoding"), whitespace0(), tag("="), whitespace0(), //delimited_string(), alt2( tuple3( tag("'"), map( tuple2( wellformed(take_one(), |c| is_encname_startchar(*c)), take_while(is_encname_char), ), |(s, r)| [s.to_string(), r].concat(), ), tag("'"), ), tuple3( tag("\""), map( tuple2( wellformed(take_one(), |c| is_encname_startchar(*c)), take_while(is_encname_char), ), |(s, r)| [s.to_string(), r].concat(), ), tag("\""), ), ), ), |(_, _, _, _, _, (_, e, _))| e, ) } pub(crate) fn xmldecl<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, XMLDecl), ParseError> { move |(input, state)| match tuple8( tag("<?xml"), whitespace1(), xmldeclversion(), opt(encodingdecl()), opt(xmldeclstandalone()), whitespace0(), tag("?>"), whitespace0(), )((input, state)) { Ok(((input1, mut state1), (_, _, ver, enc, sta, _, _, _))) => { state1.xmlversion.clone_from(&ver); let res = XMLDecl { version: ver, encoding: enc, standalone: sta, }; Ok(((input1, state1), res)) } Err(e) => Err(e), } } pub(crate) fn is_encname_char(ch: char) -> bool { matches!(ch, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' ) } pub(crate) fn is_encname_startchar(ch: char) -> bool { ch.is_ascii_alphabetic() }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/chardata.rs
src/parser/xml/chardata.rs
use crate::item::Node; use crate::parser::combinators::alt::{alt2, alt3}; use crate::parser::combinators::delimited::delimited; use crate::parser::combinators::many::many1; use crate::parser::combinators::map::{map, map_ver}; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::{take_until, take_while}; use crate::parser::combinators::wellformed::{wellformed, wellformed_ver}; use crate::parser::common::{is_char10, is_char11, is_unrestricted_char11}; use crate::parser::{ParseError, ParseInput}; use std::str::FromStr; // CharData ::= [^<&]* - (']]>') pub(crate) fn chardata<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { move |(input, state)| { map( many1(alt3( map_ver( wellformed_ver( chardata_cdata(), |s| !s.contains(|c: char| !is_char10(&c)), //XML 1.0 |s| !s.contains(|c: char| !is_unrestricted_char11(&c)), //XML 1.1 ), |s: String| s.replace("\r\n", "\n").replace("\r", "\n"), |s: String| { s.replace("\r\n", "\n") .replace("\r\u{85}", "\n") .replace("\u{85}", "\n") .replace("\u{2028}", "\n") .replace("\r", "\n") }, ), map( wellformed_ver( chardata_unicode_codepoint(), is_char10, //XML 1.0 is_char11, ), //XML 1.1 |c| c.to_string(), ), map_ver( wellformed_ver( chardata_literal(), |s| !s.contains("]]>") && !s.contains(|c: char| !is_char10(&c)), //XML 1.0 |s| { !s.contains("]]>") && !s.contains(|c: char| !is_unrestricted_char11(&c)) }, //XML 1.1 ), |s: String| s.replace("\r\n", "\n").replace("\r", "\n"), |s: String| { s.replace("\r\n", "\n") .replace("\r\u{85}", "\n") .replace("\u{85}", "\n") .replace("\u{2028}", "\n") .replace("\r", "\n") }, ), // |s| { !s.contains("]]>") && !s.contains(|c: char| !is_char11(&c)) }, // XML 1.1 )), |v| v.concat(), )((input, state)) } } fn chardata_cdata<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { delimited(tag("<![CDATA["), take_until("]]>"), tag("]]>")) } pub(crate) fn chardata_escapes<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { move |input| match chardata_unicode_codepoint()(input.clone()) { Ok((inp, s)) => Ok((inp, s.to_string())), Err(e) => Err(e), } } pub(crate) fn chardata_unicode_codepoint<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, char), ParseError> { map( wellformed( alt2( delimited(tag("&#x"), parse_hex(), tag(";")), delimited(tag("&#"), parse_decimal(), tag(";")), ), |value| { std::char::from_u32(*value).is_some() //match std::char::from_u32(*value) { // None => false, // _ => true //} }, ), |value| std::char::from_u32(value).unwrap(), ) } fn parse_hex<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, u32), ParseError> { move |input| match take_while(|c: char| c.is_ascii_hexdigit())(input) { Ok((input1, hex)) => { //eprintln!("parse_hex \"{}\"", &hex); match u32::from_str_radix(&hex, 16) { Ok(r) => { //eprintln!("Ok"); Ok((input1, r)) } Err(_) => { //eprintln!("Err"); Err(ParseError::NotWellFormed(hex)) } } } Err(e) => Err(e), } } fn parse_decimal<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, u32), ParseError> { move |input| match take_while(|c: char| c.is_ascii_digit())(input) { Ok((input1, dec)) => match u32::from_str(&dec) { Ok(r) => Ok((input1, r)), Err(_) => Err(ParseError::NotWellFormed(dec)), }, Err(e) => Err(e), } } fn chardata_literal<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { take_while(|c| c != '<' && c != '&') }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/qname.rs
src/parser/xml/qname.rs
use crate::item::Node; use crate::parser::combinators::alt::alt2; use crate::parser::combinators::many::many1; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::pair::pair; use crate::parser::combinators::support::none_of; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::{take_one, take_while}; use crate::parser::combinators::tuple::{tuple2, tuple3}; //use crate::parser::combinators::debug::inspect; use crate::parser::combinators::wellformed::wellformed; use crate::parser::common::{is_namechar, is_namestartchar, is_ncnamechar, is_ncnamestartchar}; use crate::parser::xml::dtd::pereference::petextreference; use crate::parser::{ParseError, ParseInput}; use crate::qname::QualifiedName; // QualifiedName pub(crate) fn qualname<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, QualifiedName), ParseError> { alt2(prefixed_name(), unprefixed_name()) } // Expanded Qualified Name // EQName ::= QName | URIQualifiedName pub(crate) fn eqname<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, QualifiedName), ParseError> { alt2(uriqualname(), qualname()) } // URIQualifiedName ::= "Q" "{" [^{}]* "}" NCName pub(crate) fn uriqualname<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, QualifiedName), ParseError> { map( pair( tuple3( tag("Q{"), map(many1(none_of("{}")), |v| v.iter().collect()), tag("}"), ), ncname(), ), |((_, uri, _), localpart)| QualifiedName::new(Some(uri), None, localpart), ) } fn unprefixed_name<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, QualifiedName), ParseError> { map(alt2(petextreference(), ncname()), |localpart| { QualifiedName::new(None, None, localpart) }) } fn prefixed_name<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, QualifiedName), ParseError> { map( tuple3( alt2(petextreference(), ncname()), tag(":"), alt2(petextreference(), ncname()), ), |(prefix, _, localpart)| QualifiedName::new(None, Some(prefix), localpart), ) } // NCName ::= Name - (Char* ':' Char*) // Name ::= NameStartChar NameChar* // NameStartChar ::= ':' | [A-Z] | '_' | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] // NameChar ::= NameStartChar | '-' | '.' | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] pub(crate) fn ncname<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map( tuple2( wellformed(take_one(), is_ncnamestartchar), opt(take_while(|c| is_ncnamechar(&c))), ), |(a, b)| [a.to_string(), b.unwrap_or_default()].concat(), ) } pub(crate) fn name<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map( tuple2( wellformed(take_one(), is_namestartchar), opt(take_while(|c| is_namechar(&c))), ), |(nsc, nc)| match nc { None => nsc.to_string(), Some(nc) => [nsc.to_string(), nc].concat(), }, ) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/strings.rs
src/parser/xml/strings.rs
use crate::item::Node; use crate::parser::combinators::alt::{alt2, alt3}; use crate::parser::combinators::delimited::delimited; use crate::parser::combinators::many::many0; use crate::parser::combinators::map::map; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::take_while; use crate::parser::xml::chardata::chardata_escapes; use crate::parser::xml::chardata::chardata_unicode_codepoint; use crate::parser::{ParseError, ParseInput}; pub(crate) fn delimited_string<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { alt2(string_single(), string_double()) } fn string_single<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { delimited( tag("\'"), map( many0(alt3( chardata_escapes(), map(chardata_unicode_codepoint(), |c| c.to_string()), take_while(|c| !"&\'<".contains(c)), )), |v| v.concat(), ), tag("\'"), ) } fn string_double<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { delimited( tag("\""), map( many0(alt2( chardata_escapes(), take_while(|c| !"&\"<".contains(c)), )), |v| v.concat(), ), tag("\""), ) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/dtd/misc.rs
src/parser/xml/dtd/misc.rs
use crate::item::Node; use crate::parser::combinators::alt::{alt2, alt3, alt4}; use crate::parser::combinators::many::{many0, many1}; use crate::parser::combinators::map::map; use crate::parser::combinators::opt::opt; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::take_while; use crate::parser::combinators::tuple::{tuple2, tuple3, tuple4, tuple5, tuple6}; use crate::parser::combinators::value::value; use crate::parser::combinators::whitespace::whitespace0; use crate::parser::common::is_namechar; use crate::parser::xml::dtd::pereference::petextreference; use crate::parser::xml::dtd::Occurances; use crate::parser::xml::qname::name; use crate::parser::{ParseError, ParseInput}; use crate::qname::QualifiedName; use crate::xmldecl::DTDPattern; pub(crate) fn nmtoken<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, String), ParseError> { map(many1(take_while(|c| is_namechar(&c))), |x| x.join("")) } pub(crate) fn contentspec<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, DTDPattern), ParseError> { alt4( value(tag("EMPTY"), DTDPattern::Empty), value(tag("ANY"), DTDPattern::Any), mixed(), children(), ) } //Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')' pub(crate) fn mixed<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, DTDPattern), ParseError> { alt2( map( tuple6( tag("("), whitespace0(), tag("#PCDATA"), many0(tuple4( whitespace0(), tag("|"), whitespace0(), alt2(petextreference(), name()), )), whitespace0(), tag(")*"), ), |(_, _, _, vn, _, _)| { let mut r = DTDPattern::Text; for (_, _, _, name) in vn { let q: QualifiedName = if name.contains(':') { let mut nameparts = name.split(':'); QualifiedName::new( None, Some(nameparts.next().unwrap().parse().unwrap()), nameparts.next().unwrap(), ) } else { QualifiedName::new(None, None, name) }; r = DTDPattern::Choice(Box::new(DTDPattern::Ref(q)), Box::new(r)) } //Zero or More DTDPattern::Choice( Box::new(DTDPattern::OneOrMore(Box::new(r))), Box::new(DTDPattern::Empty), ) }, ), map( tuple5( tag("("), whitespace0(), tag("#PCDATA"), whitespace0(), tag(")"), ), |_x| DTDPattern::Text, ), ) } // children ::= (choice | seq) ('?' | '*' | '+')? pub(crate) fn children<N: Node>( ) -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, DTDPattern), ParseError> { move |(input, state)| { map( tuple2( alt3( |(input1, state1)| match petextreference()((input1, state1)) { Err(e) => Err(e), Ok(((input2, state2), s)) => { match tuple3(whitespace0(), alt2(choice(), seq()), whitespace0())(( s.as_str(), state2, )) { Err(e) => Err(e), Ok(((_input3, state3), (_, d, _))) => Ok(((input2, state3), d)), } } }, choice(), seq(), ), opt(alt3( value(tag("?"), Occurances::ZeroOrOne), value(tag("*"), Occurances::ZeroOrMore), value(tag("+"), Occurances::OneOrMore), )), ), |(dtdp, occ)| match occ { None => dtdp, Some(o) => match o { Occurances::ZeroOrMore => DTDPattern::Choice( Box::new(DTDPattern::OneOrMore(Box::new(dtdp))), Box::new(DTDPattern::Empty), ), Occurances::OneOrMore => DTDPattern::OneOrMore(Box::new(dtdp)), Occurances::One => dtdp, Occurances::ZeroOrOne => { DTDPattern::Choice(Box::new(dtdp), Box::new(DTDPattern::Empty)) } }, }, )((input, state)) } } // cp ::= (Name | choice | seq) ('?' | '*' | '+')? fn cp<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, DTDPattern), ParseError> { move |(input1, state1)| { map( tuple2( alt4( |(input1, state1)| match petextreference()((input1, state1)) { Err(e) => Err(e), Ok(((input2, state2), s)) => { match tuple3( whitespace0(), alt3( map(name(), |n| { if n.contains(':') { let mut nameparts = n.split(':'); DTDPattern::Ref(QualifiedName::new( None, Some(nameparts.next().unwrap().to_string()), nameparts.next().unwrap(), )) } else { DTDPattern::Ref(QualifiedName::new(None, None, n)) } }), choice(), seq(), ), whitespace0(), )((s.as_str(), state2)) { Err(e) => Err(e), Ok(((_input3, state3), (_, d, _))) => Ok(((input2, state3), d)), } } }, map(name(), |n| { if n.contains(':') { let mut nameparts = n.split(':'); DTDPattern::Ref(QualifiedName::new( None, Some(nameparts.next().unwrap().to_string()), nameparts.next().unwrap(), )) } else { DTDPattern::Ref(QualifiedName::new(None, None, n)) } }), choice(), seq(), ), map( opt(alt3( value(tag("?"), Occurances::ZeroOrOne), value(tag("*"), Occurances::ZeroOrMore), value(tag("+"), Occurances::OneOrMore), )), |o| match o { None => Occurances::One, Some(oc) => oc, }, ), ), |(cs, occ)| match occ { Occurances::ZeroOrMore => DTDPattern::Choice( Box::new(DTDPattern::OneOrMore(Box::new(cs))), Box::new(DTDPattern::Empty), ), Occurances::OneOrMore => DTDPattern::OneOrMore(Box::new(cs)), Occurances::One => cs, Occurances::ZeroOrOne => { DTDPattern::Choice(Box::new(cs), Box::new(DTDPattern::Empty)) } }, )((input1, state1)) } } //choice ::= '(' S? cp ( S? '|' S? cp )+ S? ')' fn choice<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, DTDPattern), ParseError> { move |(input, state)| { map( tuple6( tag("("), whitespace0(), cp(), many0(alt2( |(input1, state1)| match petextreference()((input1, state1)) { Err(e) => Err(e), Ok(((input2, state2), s)) => { match tuple3(whitespace0(), cp(), whitespace0())((s.as_str(), state2)) { Err(e) => Err(e), Ok(((_input3, state3), (_, d, _))) => { Ok(((input2, state3), ((), (), (), d))) } } } }, tuple4(whitespace0(), tag("|"), whitespace0(), cp()), )), whitespace0(), tag(")"), ), |(_, _, c1, vc1, _, _)| { let mut res = c1; for (_, _, _, c) in vc1 { res = DTDPattern::Choice(Box::new(res), Box::new(c)) } res }, )((input, state)) } } //seq ::= '(' S? cp ( S? ',' S? cp )* S? ')' fn seq<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, DTDPattern), ParseError> { map( tuple6( tag("("), whitespace0(), cp(), many0(tuple4(whitespace0(), tag(","), whitespace0(), cp())), whitespace0(), tag(")"), ), |(_, _, cp, mut veccp, _, _)| { let groupstart = cp; let mut prev: Option<DTDPattern> = None; veccp.reverse(); for (_, _, _, c) in veccp { if prev.is_none() { prev = Some(c); } else { prev = Some(DTDPattern::Group(Box::new(c), Box::new(prev.unwrap()))) } } if prev.is_none() { groupstart } else { DTDPattern::Group(Box::new(groupstart), Box::new(prev.unwrap())) } }, ) }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false
ballsteve/xrust
https://github.com/ballsteve/xrust/blob/4b8681166cc9894c2bf068afe79a8414d7a13970/src/parser/xml/dtd/pedecl.rs
src/parser/xml/dtd/pedecl.rs
use crate::item::Node; use crate::parser::combinators::alt::{alt3, alt4}; use crate::parser::combinators::delimited::delimited; use crate::parser::combinators::many::many0; use crate::parser::combinators::map::map; use crate::parser::combinators::tag::tag; use crate::parser::combinators::take::{take_until, take_until_either_or_min1, take_until_end}; use crate::parser::combinators::tuple::{tuple2, tuple9}; use crate::parser::combinators::wellformed::{wellformed, wellformed_ver}; use crate::parser::combinators::whitespace::{whitespace0, whitespace1}; use crate::parser::common::{is_char10, is_unrestricted_char11}; use crate::parser::xml::chardata::chardata_unicode_codepoint; use crate::parser::xml::dtd::externalid::textexternalid; use crate::parser::xml::dtd::intsubset::intsubset; use crate::parser::xml::dtd::pereference::petextreference; use crate::parser::xml::qname::qualname; use crate::parser::{ParseError, ParseInput}; pub(crate) fn pedecl<N: Node>() -> impl Fn(ParseInput<N>) -> Result<(ParseInput<N>, ()), ParseError> { move |input| match wellformed_ver( tuple9( tag("<!ENTITY"), whitespace1(), tag("%"), whitespace1(), wellformed(qualname(), |n| !n.to_string().contains(':')), whitespace1(), alt3( textexternalid(), delimited(tag("'"), take_until("'"), tag("'")), delimited(tag("\""), take_until("\""), tag("\"")), ), whitespace0(), tag(">"), ), |(_, _, _, _, _, _, s, _, _)| !s.contains(|c: char| !is_char10(&c)), //XML 1.0 |(_, _, _, _, _, _, s, _, _)| !s.contains(|c: char| !is_unrestricted_char11(&c)), //XML 1.1 )(input) { Ok(((input2, mut state2), (_, _, _, _, n, _, s, _, _))) => { /* Numeric entities expanded immediately, since there'll be namespaces and the like to deal with later, after that we just store the entity as a string and parse again when called. */ if !state2.currentlyexternal && s.contains('%') { return Err(ParseError::NotWellFormed(s)); } let entityparse = map( tuple2( map( many0(alt4( map(chardata_unicode_codepoint(), |c| c.to_string()), petextreference(), //General entity is ignored. map(delimited(tag("&"), take_until(";"), tag(";")), |s| { ["&".to_string(), s, ";".to_string()].concat() }), //textreference(), //map(tag("&"), |_| "&".to_string()), //take_until("&"), take_until_either_or_min1("&", "%"), )), |ve| ve.concat(), ), wellformed(take_until_end(), |s| !s.contains('&') && !s.contains('%')), ), |(a, b)| [a, b].concat(), )((s.as_str(), state2.clone())); match entityparse { Ok(((_, _), res)) => { if !state2.currentlyexternal { match intsubset()((res.as_str(), state2.clone())) { Ok(((_i, _s), _)) => {} Err(_) => return Err(ParseError::NotWellFormed(res)), } }; /* Entities should always bind to the first value */ let replaceable = state2.currentlyexternal; match state2.dtd.paramentities.get(n.to_string().as_str()) { None => { state2 .dtd .paramentities .insert(n.to_string(), (res, replaceable)); Ok(((input2, state2), ())) } Some((_, true)) => { state2 .dtd .paramentities .entry(n.to_string()) .or_insert((res, replaceable)); Ok(((input2, state2), ())) } _ => Ok(((input2, state2), ())), } //state2.dtd // .generalentities.entry(n.to_string()) // .or_insert(res); } Err(e) => Err(e), } } Err(err) => Err(err), } }
rust
Apache-2.0
4b8681166cc9894c2bf068afe79a8414d7a13970
2026-01-04T20:23:44.719720Z
false