| 1 | //! OWL / RDFS 文件的解析与**投影**。 |
| 2 | //! |
| 3 | //! 分工按 0001 定的三层:本模块只做第二层(投影),第一层(原文保真进 blob) |
| 4 | //! 由调用方负责。**这里读不懂的东西不是错误,是"暂未投影"**——原文留着, |
| 5 | //! 将来补上消费者时重跑即可。 |
| 6 | //! |
| 7 | //! 只解析,不推理:Oxigraph 那两个小解析器给出三元组,我们按名单挑走能用的。 |
| 8 | //! 不引 horned-owl——推理机是 0002 的事,而且它读的是原文不是投影。 |
| 9 | |
| 10 | use std::collections::{BTreeMap, BTreeSet}; |
| 11 | |
| 12 | /// 投影出来的一个类。 |
| 13 | #[derive(Debug, Clone, Default, PartialEq)] |
| 14 | pub struct OwlClass { |
| 15 | pub iri: String, |
| 16 | /// 从 IRI 派生的短标签(模型读写的令牌);调用方负责去重加后缀 |
| 17 | pub key: String, |
| 18 | pub label: String, |
| 19 | /// `rdfs:comment` —— 承重字段,逐字进抽取提示词 |
| 20 | pub description: String, |
| 21 | /// `rdfs:subClassOf` 的全部父类 IRI(多继承在这里是常态) |
| 22 | pub parents: Vec<String>, |
| 23 | /// `owl:disjointWith` 的对端 IRI。**两个方向都收**——公理是对称的, |
| 24 | /// 而词表通常只写一遍 |
| 25 | pub disjoint_with: Vec<String>, |
| 26 | } |
| 27 | |
| 28 | /// 投影出来的一个属性(对象属性 → 关系,数据属性 → 属性)。 |
| 29 | #[derive(Debug, Clone, Default, PartialEq)] |
| 30 | pub struct OwlProperty { |
| 31 | pub iri: String, |
| 32 | pub key: String, |
| 33 | pub label: String, |
| 34 | pub description: String, |
| 35 | /// true = 走属性通道(字面值),false = 走关系通道。 |
| 36 | /// 来源有二:显式的 `owl:DatatypeProperty`,或者 range 全是数据类型 |
| 37 | pub is_datatype: bool, |
| 38 | pub functional: bool, |
| 39 | pub inverse_functional: bool, |
| 40 | /// OWL 属性公理。一致性检查(0002 R0)的判定依据:没有它们, |
| 41 | /// `A part_of B` 与 `B part_of A` 同时存在到底是矛盾还是正常,无从判起 |
| 42 | pub transitive: bool, |
| 43 | pub symmetric: bool, |
| 44 | pub asymmetric: bool, |
| 45 | pub irreflexive: bool, |
| 46 | /// `owl:inverseOf` 的对端 IRI。**只按写的方向收**——归一化(补上反向) |
| 47 | /// 在读取公理时做(`reasoning::axioms`),那里绕不过去; |
| 48 | /// 在这里补会让「本体自己写了什么」和「我们推出来的」分不开 |
| 49 | pub inverse_of: Option<String>, |
| 50 | /// `rdfs:subPropertyOf` 的父属性 IRI。多写几条只留第一条—— |
| 51 | /// OWL 允许多父,而 R1 的规则一次只升一级,多父要另一套形状 |
| 52 | pub sub_property_of: Option<String>, |
| 53 | pub domains: Vec<String>, |
| 54 | pub ranges: Vec<String>, |
| 55 | /// **多条 range 是并集还是交集**。`rdfs:range` 写多条是交集 |
| 56 | ///("必须同时是两者"),`schema:rangeIncludes` 写多条是并集 |
| 57 | ///("哪个都行")。倒进同一个 Vec 而不记这一位, |
| 58 | /// `author rangeIncludes Organization, Person` 就会被读成 |
| 59 | /// "必须既是组织又是人",然后降级成 text——一条边就这么没了 |
| 60 | pub ranges_union: bool, |
| 61 | } |
| 62 | |
| 63 | /// 一次解析的结果。`unprojected` 是**报告**不是错误——见模块文档。 |
| 64 | #[derive(Debug, Default)] |
| 65 | pub struct OwlProjection { |
| 66 | pub classes: Vec<OwlClass>, |
| 67 | pub properties: Vec<OwlProperty>, |
| 68 | /// 出现过但我们今天不消费的谓词 → 次数。给预览页"暂未投影"那一栏 |
| 69 | pub unprojected: BTreeMap<String, usize>, |
| 70 | /// 三元组总数,让人对"这个文件有多大"有个数 |
| 71 | pub triples: usize, |
| 72 | /// **这份文件自己声明为数据类型的那些 IRI** → 我们的四种之一。 |
| 73 | /// schema.org 把 Text/Number/Date… 声明成 `a rdfs:Class, schema:DataType`, |
| 74 | /// 只看 `rdfs:Class` 会把它们当成实体类建出来(`text`、`boolean` 成了实体类型) |
| 75 | pub vocab_datatypes: VocabDatatypes, |
| 76 | } |
| 77 | |
| 78 | /// 词汇表自己声明的数据类型 IRI → 我们的四种(`text`/`number`/`date`/`bool`)。 |
| 79 | pub type VocabDatatypes = BTreeMap<String, &'static str>; |
| 80 | |
| 81 | const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; |
| 82 | const RDFS: &str = "http://www.w3.org/2000/01/rdf-schema#"; |
| 83 | const OWL: &str = "http://www.w3.org/2002/07/owl#"; |
| 84 | |
| 85 | /// schema.org 自己那套 domain/range。**不是标准词汇**,所以写死在这里, |
| 86 | /// 但值得认:schema.org 及派生词汇表一个 `rdfs:domain` 都没有, |
| 87 | /// 不认这两个谓词就等于把它整个类型系统当成没看见——1600 多个属性 |
| 88 | /// 会全变成无约束的关系。 |
| 89 | /// 两种 scheme 都收:同一份词汇表的新旧版本分别用 https 与 http 发布。 |
| 90 | const SCHEMA_NS: [&str; 2] = ["https://schema.org/", "http://schema.org/"]; |
| 91 | |
| 92 | /// 谓词/类是不是 schema.org 那个名字下的某一个。 |
| 93 | fn is_schema(iri: &str, local: &str) -> bool { |
| 94 | SCHEMA_NS.iter().any(|ns| { |
| 95 | iri.len() == ns.len() + local.len() && iri.starts_with(ns) && iri.ends_with(local) |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | /// 支持的输入格式。v1 只做这两个——Protégé 导出的绝大多数是它们, |
| 100 | /// OWL/XML 与 Manchester 语法刻意砍掉(见 0001 P2 的 "v1 砍掉")。 |
| 101 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 102 | pub enum RdfFormat { |
| 103 | Turtle, |
| 104 | RdfXml, |
| 105 | } |
| 106 | |
| 107 | impl RdfFormat { |
| 108 | /// 扩展名是强信号,内容只在**明确矛盾**时推翻它。 |
| 109 | /// |
| 110 | /// 曾经反过来(`.rdf` 探不到 XML 标志就退回 Turtle),结果 FOAF 的官方文件 |
| 111 | /// 一开头是几十行 `<!--` 注释、`<rdf:` 在嗅探窗口之外,于是被当成 Turtle |
| 112 | /// 送进解析器,第一行就报 "Invalid IRI code point"。 |
| 113 | pub fn detect(filename: &str, bytes: &[u8]) -> Self { |
| 114 | let lower = filename.to_ascii_lowercase(); |
| 115 | // Turtle 的指纹很硬:只有它以 @prefix / @base / PREFIX 开头 |
| 116 | let looks_turtle = { |
| 117 | let head = &bytes[..bytes.len().min(4096)]; |
| 118 | let s = String::from_utf8_lossy(head); |
| 119 | s.lines() |
| 120 | .map(str::trim_start) |
| 121 | .find(|l| !l.is_empty() && !l.starts_with('#')) |
| 122 | .is_some_and(|l| { |
| 123 | l.starts_with("@prefix") |
| 124 | || l.starts_with("@base") |
| 125 | || l.starts_with("PREFIX") |
| 126 | || l.starts_with("BASE") |
| 127 | }) |
| 128 | }; |
| 129 | if lower.ends_with(".ttl") || lower.ends_with(".turtle") || lower.ends_with(".n3") { |
| 130 | return Self::Turtle; |
| 131 | } |
| 132 | if lower.ends_with(".rdf") || lower.ends_with(".owl") || lower.ends_with(".xml") { |
| 133 | // .owl 两种编码都常见,所以内容说了算——但只有"确实像 Turtle"才推翻 |
| 134 | return if looks_turtle { |
| 135 | Self::Turtle |
| 136 | } else { |
| 137 | Self::RdfXml |
| 138 | }; |
| 139 | } |
| 140 | if looks_turtle { |
| 141 | Self::Turtle |
| 142 | } else { |
| 143 | Self::RdfXml |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /// 三元组的中间形态:只留我们看得懂的部分。 |
| 149 | struct Triple { |
| 150 | subject: String, |
| 151 | predicate: String, |
| 152 | /// 宾语是 IRI 时为 Some |
| 153 | object_iri: Option<String>, |
| 154 | /// 宾语是字面量时为 Some(值, 语言标记) |
| 155 | object_lit: Option<(String, Option<String>)>, |
| 156 | } |
| 157 | |
| 158 | fn read_triples(bytes: &[u8], format: RdfFormat) -> anyhow::Result<Vec<Triple>> { |
| 159 | use oxrdf::Term; |
| 160 | let mut out = Vec::new(); |
| 161 | let mut push = |t: oxrdf::Triple| { |
| 162 | let subject = match &t.subject { |
| 163 | oxrdf::NamedOrBlankNode::NamedNode(n) => n.as_str().to_string(), |
| 164 | // 空节点是匿名类表达式(owl:Restriction 之类)——投影不碰它们, |
| 165 | // 原文里留着等推理机 |
| 166 | oxrdf::NamedOrBlankNode::BlankNode(_) => return, |
| 167 | }; |
| 168 | let (object_iri, object_lit) = match &t.object { |
| 169 | Term::NamedNode(n) => (Some(n.as_str().to_string()), None), |
| 170 | Term::Literal(l) => ( |
| 171 | None, |
| 172 | Some(( |
| 173 | l.value().to_string(), |
| 174 | l.language().map(|s| s.to_ascii_lowercase()), |
| 175 | )), |
| 176 | ), |
| 177 | _ => (None, None), |
| 178 | }; |
| 179 | out.push(Triple { |
| 180 | subject, |
| 181 | predicate: t.predicate.as_str().to_string(), |
| 182 | object_iri, |
| 183 | object_lit, |
| 184 | }); |
| 185 | }; |
| 186 | // **相对 IRI 需要 base 才能解析。** 从字节读没有文档 URL,而 Turtle 规范说 |
| 187 | // base 默认取文档自身的地址。给一个占位符:本体文件里的相对 IRI 几乎都是 |
| 188 | // 文档级元数据(PROV-O 的 `<#> a owl:Ontology`),我们不消费 owl:Ontology 节点, |
| 189 | // 解析得过去就行。不给的话整个文件在第一个 `<#>` 上报 |
| 190 | // "No scheme found in an absolute IRI" 而全军覆没 |
| 191 | const BASE: &str = "urn:utopia:import"; |
| 192 | match format { |
| 193 | RdfFormat::Turtle => { |
| 194 | let p = oxttl::TurtleParser::new() |
| 195 | .with_base_iri(BASE) |
| 196 | .map_err(|e| anyhow::anyhow!("base IRI 无效:{e}"))?; |
| 197 | for r in p.for_reader(bytes) { |
| 198 | push(r?); |
| 199 | } |
| 200 | } |
| 201 | RdfFormat::RdfXml => { |
| 202 | let p = oxrdfxml::RdfXmlParser::new() |
| 203 | .with_base_iri(BASE) |
| 204 | .map_err(|e| anyhow::anyhow!("base IRI 无效:{e}"))?; |
| 205 | for r in p.for_reader(bytes) { |
| 206 | push(r?); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | Ok(out) |
| 211 | } |
| 212 | |
| 213 | /// 解析并投影。语言标记优先 `@en`/`@zh`,其次无标记,最后随便一个。 |
| 214 | pub fn project(bytes: &[u8], format: RdfFormat) -> anyhow::Result<OwlProjection> { |
| 215 | let triples = read_triples(bytes, format)?; |
| 216 | let mut proj = OwlProjection { |
| 217 | triples: triples.len(), |
| 218 | ..Default::default() |
| 219 | }; |
| 220 | |
| 221 | // 先分类:谁是类、谁是对象属性、谁是数据属性、谁带函数性标记 |
| 222 | let mut classes: BTreeSet<String> = BTreeSet::new(); |
| 223 | let mut obj_props: BTreeSet<String> = BTreeSet::new(); |
| 224 | let mut data_props: BTreeSet<String> = BTreeSet::new(); |
| 225 | let mut functional: BTreeSet<String> = BTreeSet::new(); |
| 226 | let mut inverse_functional: BTreeSet<String> = BTreeSet::new(); |
| 227 | let mut transitive: BTreeSet<String> = BTreeSet::new(); |
| 228 | let mut symmetric: BTreeSet<String> = BTreeSet::new(); |
| 229 | // 属性之间的两条关系(不是类型声明,所以单独收) |
| 230 | let mut inverse_of: BTreeMap<String, String> = BTreeMap::new(); |
| 231 | let mut sub_property_of: BTreeMap<String, String> = BTreeMap::new(); |
| 232 | let mut asymmetric: BTreeSet<String> = BTreeSet::new(); |
| 233 | let mut irreflexive: BTreeSet<String> = BTreeSet::new(); |
| 234 | let mut plain_props: BTreeSet<String> = BTreeSet::new(); |
| 235 | let mut datatype_roots: BTreeSet<String> = BTreeSet::new(); |
| 236 | for t in &triples { |
| 237 | if t.predicate != RDF_TYPE { |
| 238 | continue; |
| 239 | } |
| 240 | let Some(o) = t.object_iri.as_deref() else { |
| 241 | continue; |
| 242 | }; |
| 243 | match o { |
| 244 | x if x == format!("{OWL}Class") || x == format!("{RDFS}Class") => { |
| 245 | classes.insert(t.subject.clone()); |
| 246 | } |
| 247 | x if x == format!("{OWL}ObjectProperty") => { |
| 248 | obj_props.insert(t.subject.clone()); |
| 249 | } |
| 250 | x if x == format!("{OWL}DatatypeProperty") => { |
| 251 | data_props.insert(t.subject.clone()); |
| 252 | } |
| 253 | // rdf:Property **没说**是对象还是数据。跟显式 owl:ObjectProperty |
| 254 | // 分开存:那个是"说了",不该被 range 改判;这个是"没说", |
| 255 | // 下面按 range 定通道,range 也没有才兜底当关系 |
| 256 | "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property" => { |
| 257 | plain_props.insert(t.subject.clone()); |
| 258 | } |
| 259 | x if x == format!("{OWL}FunctionalProperty") => { |
| 260 | functional.insert(t.subject.clone()); |
| 261 | } |
| 262 | x if x == format!("{OWL}InverseFunctionalProperty") => { |
| 263 | inverse_functional.insert(t.subject.clone()); |
| 264 | } |
| 265 | // 属性公理:R0 的一致性检查靠它们才谈得上判定。 |
| 266 | // |
| 267 | // **五个随包词表只覆盖了其中一半**(TransitiveProperty 14 条、 |
| 268 | // SymmetricProperty 1 条,而 Asymmetric 与 Irreflexive 一条没有), |
| 269 | // 但那五个只是冷启动的底座。这条线的终点是把**企业自己的本体** |
| 270 | // 导进来(0001 开篇:FIBO、行业标准、Protégé 自建),那些里 |
| 271 | // 反对称与非自反是常见声明。按 OWL 收全,而不是按手上这几个包收。 |
| 272 | x if x == format!("{OWL}TransitiveProperty") => { |
| 273 | transitive.insert(t.subject.clone()); |
| 274 | } |
| 275 | x if x == format!("{OWL}SymmetricProperty") => { |
| 276 | symmetric.insert(t.subject.clone()); |
| 277 | } |
| 278 | x if x == format!("{OWL}AsymmetricProperty") => { |
| 279 | asymmetric.insert(t.subject.clone()); |
| 280 | } |
| 281 | x if x == format!("{OWL}IrreflexiveProperty") => { |
| 282 | irreflexive.insert(t.subject.clone()); |
| 283 | } |
| 284 | // 词汇表自报的数据类型。这里只收显式声明的那几个根, |
| 285 | // 子类(Integer ⊂ Number、URL ⊂ Text)等父类图收完再往下传。 |
| 286 | // **标记类自己也收**:schema:DataType 的声明是 `a rdfs:Class`, |
| 287 | // 不收就会剩下一个叫 data_type 的实体类型;顺带让 |
| 288 | // `rdfs:subClassOf schema:DataType` 这种写法也落进闭包 |
| 289 | x if is_schema(x, "DataType") => { |
| 290 | datatype_roots.insert(t.subject.clone()); |
| 291 | datatype_roots.insert(x.to_string()); |
| 292 | } |
| 293 | _ => {} |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | // 再收集标签、注释、父类、domain/range |
| 298 | let mut labels: BTreeMap<String, Vec<(String, Option<String>)>> = BTreeMap::new(); |
| 299 | let mut comments: BTreeMap<String, Vec<(String, Option<String>)>> = BTreeMap::new(); |
| 300 | let mut parents: BTreeMap<String, Vec<String>> = BTreeMap::new(); |
| 301 | let mut disjoint: BTreeMap<String, Vec<String>> = BTreeMap::new(); |
| 302 | let mut domains: BTreeMap<String, Vec<String>> = BTreeMap::new(); |
| 303 | let mut ranges: BTreeMap<String, Vec<String>> = BTreeMap::new(); |
| 304 | // rangeIncludes 用过的属性,它的 range 按并集读 |
| 305 | let mut union_ranged: BTreeSet<String> = BTreeSet::new(); |
| 306 | let known = |p: &str| { |
| 307 | p == RDF_TYPE |
| 308 | || p == format!("{RDFS}label") |
| 309 | || p == format!("{RDFS}comment") |
| 310 | || p == format!("{RDFS}subClassOf") |
| 311 | || p == format!("{RDFS}subPropertyOf") |
| 312 | || p == format!("{RDFS}domain") |
| 313 | || p == format!("{RDFS}range") |
| 314 | || is_schema(p, "domainIncludes") |
| 315 | || is_schema(p, "rangeIncludes") |
| 316 | || p == format!("{OWL}disjointWith") |
| 317 | || p == format!("{OWL}inverseOf") |
| 318 | }; |
| 319 | for t in &triples { |
| 320 | let p = t.predicate.as_str(); |
| 321 | if p == format!("{RDFS}label") { |
| 322 | if let Some(l) = &t.object_lit { |
| 323 | labels.entry(t.subject.clone()).or_default().push(l.clone()); |
| 324 | } |
| 325 | } else if p == format!("{RDFS}comment") { |
| 326 | if let Some(l) = &t.object_lit { |
| 327 | comments |
| 328 | .entry(t.subject.clone()) |
| 329 | .or_default() |
| 330 | .push(l.clone()); |
| 331 | } |
| 332 | } else if p == format!("{OWL}disjointWith") { |
| 333 | // **两个方向都记。** `owl:disjointWith` 是对称的,而词表通常只写一遍 |
| 334 | // (W3C Org 的 Role/Membership/Site/ChangeEvent 四者两两互斥,只写了六行)。 |
| 335 | // 只按写的方向存,查"A 与 B 互斥吗"就得看调用方碰巧从哪一头问 |
| 336 | if let Some(o) = &t.object_iri { |
| 337 | disjoint |
| 338 | .entry(t.subject.clone()) |
| 339 | .or_default() |
| 340 | .push(o.clone()); |
| 341 | disjoint |
| 342 | .entry(o.clone()) |
| 343 | .or_default() |
| 344 | .push(t.subject.clone()); |
| 345 | } |
| 346 | } else if p == format!("{OWL}inverseOf") { |
| 347 | // **只按写的方向收。** OWL 里 `p owl:inverseOf q` 蕴含反向, |
| 348 | // 而词表通常只写一遍。补反向是在读取公理时做的 |
| 349 | //(`reasoning::axioms`,那一处绕不过去)——在这里补会让 |
| 350 | // 「本体自己写了什么」和「我们推出来的」分不开,而 R0 有一条 |
| 351 | // `inverse_not_mutual` 检查恰恰要区分这两者 |
| 352 | if let Some(o) = &t.object_iri { |
| 353 | inverse_of.entry(t.subject.clone()).or_insert(o.clone()); |
| 354 | } |
| 355 | } else if p == format!("{RDFS}subPropertyOf") { |
| 356 | // 从前这条只出现在 `known()` 白名单里——认得出、不报警、**然后扔掉**。 |
| 357 | // 导一份带 subPropertyOf 的本体进来,那部分信息当场消失且没有提示 |
| 358 | if let Some(o) = &t.object_iri { |
| 359 | sub_property_of |
| 360 | .entry(t.subject.clone()) |
| 361 | .or_insert(o.clone()); |
| 362 | } |
| 363 | } else if p == format!("{RDFS}subClassOf") { |
| 364 | if let Some(o) = &t.object_iri { |
| 365 | parents |
| 366 | .entry(t.subject.clone()) |
| 367 | .or_default() |
| 368 | .push(o.clone()); |
| 369 | } |
| 370 | } else if p == format!("{RDFS}domain") { |
| 371 | if let Some(o) = &t.object_iri { |
| 372 | domains |
| 373 | .entry(t.subject.clone()) |
| 374 | .or_default() |
| 375 | .push(o.clone()); |
| 376 | } |
| 377 | } else if p == format!("{RDFS}range") { |
| 378 | if let Some(o) = &t.object_iri { |
| 379 | ranges.entry(t.subject.clone()).or_default().push(o.clone()); |
| 380 | } |
| 381 | } else if is_schema(p, "domainIncludes") { |
| 382 | // domainIncludes 是并集("可以用在这些类型上"),而我们的 domain |
| 383 | // 列表本来就是并集语义(签名 `person|organization`),直接进 |
| 384 | if let Some(o) = &t.object_iri { |
| 385 | domains |
| 386 | .entry(t.subject.clone()) |
| 387 | .or_default() |
| 388 | .push(o.clone()); |
| 389 | } |
| 390 | } else if is_schema(p, "rangeIncludes") { |
| 391 | if let Some(o) = &t.object_iri { |
| 392 | ranges.entry(t.subject.clone()).or_default().push(o.clone()); |
| 393 | union_ranged.insert(t.subject.clone()); |
| 394 | } |
| 395 | } else if !known(p) { |
| 396 | // 报告而不是丢弃:预览页要能说清"这个文件里还有什么我们没消费" |
| 397 | *proj.unprojected.entry(p.to_string()).or_insert(0) += 1; |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // 数据类型闭包:根是显式 `a schema:DataType` 的那几个,子类沿 subClassOf |
| 402 | // 往下传(Integer ⊂ Number、URL ⊂ Text)。 |
| 403 | // **哪些 IRI 是数据类型由文件自己说**,写死的只有"这个数据类型算我们四种里的 |
| 404 | // 哪一种"——那一半是命名约定,RDF 里推不出来 |
| 405 | let mut datatype_classes = datatype_roots.clone(); |
| 406 | loop { |
| 407 | let grown: Vec<String> = parents |
| 408 | .iter() |
| 409 | .filter(|(child, ps)| { |
| 410 | !datatype_classes.contains(*child) |
| 411 | && ps.iter().any(|p| datatype_classes.contains(p)) |
| 412 | }) |
| 413 | .map(|(child, _)| child.clone()) |
| 414 | .collect(); |
| 415 | if grown.is_empty() { |
| 416 | break; |
| 417 | } |
| 418 | datatype_classes.extend(grown); |
| 419 | } |
| 420 | for iri in &datatype_classes { |
| 421 | if let Some(dt) = name_datatype(iri, &parents, &datatype_classes) { |
| 422 | proj.vocab_datatypes.insert(iri.clone(), dt); |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | for iri in &classes { |
| 427 | // **数据类型不是实体类型。** schema:Text 声明的是 |
| 428 | // `a rdfs:Class, schema:DataType`,只看前半截就会建出叫 |
| 429 | // `text`、`number`、`boolean` 的实体类型来 |
| 430 | if datatype_classes.contains(iri) { |
| 431 | continue; |
| 432 | } |
| 433 | proj.classes.push(OwlClass { |
| 434 | key: key_from_iri(iri), |
| 435 | label: pick_lang(labels.get(iri)).unwrap_or_else(|| local_name(iri).to_string()), |
| 436 | description: pick_lang(comments.get(iri)).unwrap_or_default(), |
| 437 | parents: parents.get(iri).cloned().unwrap_or_default(), |
| 438 | disjoint_with: { |
| 439 | // 去重:两个方向都收之后,词表若两边都写过就会重复 |
| 440 | let mut d = disjoint.get(iri).cloned().unwrap_or_default(); |
| 441 | d.sort(); |
| 442 | d.dedup(); |
| 443 | d |
| 444 | }, |
| 445 | iri: iri.clone(), |
| 446 | }); |
| 447 | } |
| 448 | // **并集去重,不是两个集合首尾相接**:词汇表常把同一个属性既声明为 |
| 449 | // rdf:Property 又声明为 owl:DatatypeProperty(FOAF 的 name、age、nick… 都这样), |
| 450 | // 两个集合各收一次,chain 就会把它吐两遍。分类看 data_props 就够了。 |
| 451 | let all_props: BTreeSet<&String> = obj_props |
| 452 | .iter() |
| 453 | .chain(data_props.iter()) |
| 454 | .chain(plain_props.iter()) |
| 455 | .collect(); |
| 456 | for iri in all_props { |
| 457 | let rs = ranges.get(iri).cloned().unwrap_or_default(); |
| 458 | // 走属性通道还是关系通道。显式声明说了算;没说的看 range: |
| 459 | // **全是数据类型才算属性**。并集里只要有一个类就走关系—— |
| 460 | // `address` 的 range 是 `PostalAddress|Text`,判成属性就把那条边 |
| 461 | // 永久丢了,而关系总能给一个新实体起名字。富的那一侧可回退, |
| 462 | // 穷的那一侧回不去 |
| 463 | let is_datatype = if data_props.contains(iri) { |
| 464 | true |
| 465 | } else if obj_props.contains(iri) { |
| 466 | false |
| 467 | } else { |
| 468 | !rs.is_empty() && rs.iter().all(|r| datatype_classes.contains(r)) |
| 469 | }; |
| 470 | proj.properties.push(OwlProperty { |
| 471 | key: key_from_iri(iri), |
| 472 | label: pick_lang(labels.get(iri)) |
| 473 | .unwrap_or_else(|| local_name(iri).replace('_', " ").to_string()), |
| 474 | description: pick_lang(comments.get(iri)).unwrap_or_default(), |
| 475 | is_datatype, |
| 476 | functional: functional.contains(iri), |
| 477 | inverse_functional: inverse_functional.contains(iri), |
| 478 | transitive: transitive.contains(iri), |
| 479 | symmetric: symmetric.contains(iri), |
| 480 | asymmetric: asymmetric.contains(iri), |
| 481 | inverse_of: inverse_of.get(iri).cloned(), |
| 482 | sub_property_of: sub_property_of.get(iri).cloned(), |
| 483 | irreflexive: irreflexive.contains(iri), |
| 484 | domains: domains.get(iri).cloned().unwrap_or_default(), |
| 485 | ranges: rs, |
| 486 | ranges_union: union_ranged.contains(iri), |
| 487 | iri: iri.clone(), |
| 488 | }); |
| 489 | } |
| 490 | order_by_home_namespace(&mut proj); |
| 491 | Ok(proj) |
| 492 | } |
| 493 | |
| 494 | /// 把**这份文件自己的**词汇表排到前面。 |
| 495 | /// |
| 496 | /// 撞 key 时调用方是先到先得(`owl_import::plan` 里那个 `claimed`),而"先" |
| 497 | /// 此前来自 IRI 的字典序——于是 `http://` 排在 `https://` 前面,被引用的 |
| 498 | /// 小词汇表系统性地压过主词汇表。schema.org 那份文件里合了 50 个命名空间, |
| 499 | /// 主词汇表声明了其中 94% 的词,却输掉了 141 场撞车里的 114 场: |
| 500 | /// `location` 输给 OMG Commons、`country` 输给 unece.org、 |
| 501 | /// `organization` 输给 purl.org。丢的正是最该用的那批词。 |
| 502 | /// |
| 503 | /// 判据是**声明得最多的那个命名空间就是文件的主人**——不认 schema.org |
| 504 | /// 这个名字,任何词汇表都适用。同数时取字典序小的,保证可重复。 |
| 505 | fn order_by_home_namespace(proj: &mut OwlProjection) { |
| 506 | let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); |
| 507 | for iri in proj |
| 508 | .classes |
| 509 | .iter() |
| 510 | .map(|c| c.iri.as_str()) |
| 511 | .chain(proj.properties.iter().map(|p| p.iri.as_str())) |
| 512 | { |
| 513 | *counts.entry(namespace_of(iri)).or_insert(0) += 1; |
| 514 | } |
| 515 | // max_by_key 取的是最后一个最大值,而 BTreeMap 按 key 升序—— |
| 516 | // 于是同数时拿到字典序最大的那个。要的是最小的,所以自己比 |
| 517 | let Some(home) = counts |
| 518 | .into_iter() |
| 519 | .fold(None::<(&str, usize)>, |best, (ns, n)| match best { |
| 520 | Some((_, bn)) if bn >= n => best, |
| 521 | _ => Some((ns, n)), |
| 522 | }) |
| 523 | .map(|(ns, _)| ns.to_string()) |
| 524 | else { |
| 525 | return; |
| 526 | }; |
| 527 | // 稳定排序:只把主词汇表提到前面,其余保持原有的字典序 |
| 528 | proj.classes.sort_by_key(|c| namespace_of(&c.iri) != home); |
| 529 | proj.properties |
| 530 | .sort_by_key(|p| namespace_of(&p.iri) != home); |
| 531 | } |
| 532 | |
| 533 | /// IRI 去掉局部名剩下的那段(含结尾的 `#` 或 `/`)。 |
| 534 | fn namespace_of(iri: &str) -> &str { |
| 535 | match iri.rfind(['#', '/']) { |
| 536 | Some(i) => &iri[..=i], |
| 537 | None => iri, |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | /// 数据类型 IRI → 我们的四种。自身叫得上名就用自身,否则沿 `rdfs:subClassOf` |
| 542 | /// 上溯(Integer → Number、URL → Text)。 |
| 543 | /// |
| 544 | /// 叫不上名的返回 `None`——比如 `schema:Time`,它只有时刻没有日期, |
| 545 | /// 跟 `xsd:time` 同样待遇:由 [`map_range`] 走 [`RangeMapping::Degraded`], |
| 546 | /// 按 text 建**并报告**。 |
| 547 | fn name_datatype( |
| 548 | iri: &str, |
| 549 | parents: &BTreeMap<String, Vec<String>>, |
| 550 | datatypes: &BTreeSet<String>, |
| 551 | ) -> Option<&'static str> { |
| 552 | let mut seen: BTreeSet<&str> = BTreeSet::new(); |
| 553 | let mut stack: Vec<&str> = vec![iri]; |
| 554 | while let Some(cur) = stack.pop() { |
| 555 | if !seen.insert(cur) { |
| 556 | continue; |
| 557 | } |
| 558 | if let Some(dt) = well_known_datatype(cur) { |
| 559 | return Some(dt); |
| 560 | } |
| 561 | // 只沿数据类型往上走:数据类型的父类可能是普通的 rdfs:Class |
| 562 | //(schema:DataType ⊂ rdfs:Class),越过去就走进整个类层次了 |
| 563 | for p in parents.get(cur).into_iter().flatten() { |
| 564 | if datatypes.contains(p) { |
| 565 | stack.push(p); |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | None |
| 570 | } |
| 571 | |
| 572 | /// 写死的那一半:数据类型的**名字**对应我们哪一种。 |
| 573 | /// |
| 574 | /// 这从 RDF 里推不出来——文件说得出"Integer 是个数据类型", |
| 575 | /// 说不出"它是数字不是日期"。表里只放根,子类靠 subClassOf 上溯够到。 |
| 576 | /// |
| 577 | /// 这里按局部名匹配是安全的,跟 [`datatype_of`] 那条"必须按完整 IRI 匹配" |
| 578 | /// 不冲突:能走到这儿的 IRI,是**这份文件自己**声明成数据类型的, |
| 579 | /// 一个文件说 "Date 是数据类型" 就不会同时拿 Date 当实体类。 |
| 580 | fn well_known_datatype(iri: &str) -> Option<&'static str> { |
| 581 | [ |
| 582 | ("Text", "text"), |
| 583 | ("Number", "number"), |
| 584 | ("Date", "date"), |
| 585 | ("DateTime", "date"), |
| 586 | ("Boolean", "bool"), |
| 587 | ] |
| 588 | .into_iter() |
| 589 | .find(|(local, _)| is_schema(iri, local)) |
| 590 | .map(|(_, dt)| dt) |
| 591 | } |
| 592 | |
| 593 | /// 多语言标签里挑一个:优先 en / zh,其次无语言标记,最后第一个。 |
| 594 | fn pick_lang(vals: Option<&Vec<(String, Option<String>)>>) -> Option<String> { |
| 595 | let vals = vals?; |
| 596 | for want in ["en", "zh"] { |
| 597 | if let Some((v, _)) = vals |
| 598 | .iter() |
| 599 | .find(|(_, l)| l.as_deref().is_some_and(|l| l.starts_with(want))) |
| 600 | { |
| 601 | return Some(v.clone()); |
| 602 | } |
| 603 | } |
| 604 | vals.iter() |
| 605 | .find(|(_, l)| l.is_none()) |
| 606 | .or_else(|| vals.first()) |
| 607 | .map(|(v, _)| v.clone()) |
| 608 | } |
| 609 | |
| 610 | /// IRI 的局部名:最后一个 `#` 或 `/` 之后的部分。 |
| 611 | pub fn local_name(iri: &str) -> &str { |
| 612 | iri.rsplit(['#', '/']).next().unwrap_or(iri) |
| 613 | } |
| 614 | |
| 615 | /// 从 IRI 派生 key。**IRI 是身份,key 是给模型读的标签**(见 0001 P2): |
| 616 | /// 只允许 `[a-z0-9_]`、最长 40,所以 IRI 本身进不去。 |
| 617 | /// 驼峰拆成下划线:`hasEmployee` → `has_employee`。 |
| 618 | pub fn key_from_iri(iri: &str) -> String { |
| 619 | let local = local_name(iri); |
| 620 | let mut out = String::with_capacity(local.len() + 4); |
| 621 | let mut prev_lower = false; |
| 622 | for c in local.chars() { |
| 623 | if c.is_ascii_uppercase() { |
| 624 | if prev_lower && !out.is_empty() { |
| 625 | out.push('_'); |
| 626 | } |
| 627 | out.push(c.to_ascii_lowercase()); |
| 628 | prev_lower = false; |
| 629 | } else if c.is_ascii_alphanumeric() { |
| 630 | out.push(c); |
| 631 | prev_lower = true; |
| 632 | } else if !out.ends_with('_') && !out.is_empty() { |
| 633 | out.push('_'); |
| 634 | prev_lower = false; |
| 635 | } |
| 636 | } |
| 637 | while out.ends_with('_') { |
| 638 | out.pop(); |
| 639 | } |
| 640 | out.chars().take(40).collect() |
| 641 | } |
| 642 | |
| 643 | const XSD: &str = "http://www.w3.org/2001/XMLSchema#"; |
| 644 | const RDF_NS: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; |
| 645 | |
| 646 | /// `rdfs:range` 映射到我们的四种 datatype 的结果。**三路,不是两路**。 |
| 647 | #[derive(Debug, Clone, PartialEq)] |
| 648 | pub enum RangeMapping { |
| 649 | /// 能映射到 `text` / `number` / `date` / `bool` |
| 650 | Datatype(&'static str), |
| 651 | /// 压根没写 range:词汇表没做任何声明,只知道是字面量。 |
| 652 | /// `text` 是诚实的超集(它接受任何字符串,从不拦),所以建、并在预览里列出 |
| 653 | Absent, |
| 654 | /// 写了 range,值是**短的可读字面量**,但我们的四种类型表达不了它 |
| 655 | ///(`time` 没有年、`duration` 是时长不是时点)。按 `text` 建**并报告**: |
| 656 | /// 只丢了排序语义,值还在;跳过则是这条知识彻底不会被捕获,那更糟 |
| 657 | Degraded(String), |
| 658 | /// 写了 range,而**抽取器永远不可能从散文里读出这个值**:二进制块、 |
| 659 | /// XML 片段、XML 内部标识。跳过它保护不了任何数据(本来就不会有值), |
| 660 | /// 省掉的是提示词——每个属性都是抽取提示词里的一行,每个文本块付一遍 |
| 661 | Unusable(String), |
| 662 | } |
| 663 | |
| 664 | /// 数据属性的 `rdfs:range` → datatype。 |
| 665 | /// |
| 666 | /// 按**完整 IRI** 匹配而不是局部名:自定义词汇表完全可能有个叫 `date` 的类, |
| 667 | /// 按尾巴匹配会把它当成 `xsd:date`。 |
| 668 | /// |
| 669 | /// 多条 range 一律 [`RangeMapping::Degraded`]——RDFS 里那是**交集**语义 |
| 670 | ///("必须同时是两者"),几乎总是建模笔误,但规范如此,不猜。 |
| 671 | pub fn map_range(ranges: &[String]) -> RangeMapping { |
| 672 | resolve_range(ranges, false, &VocabDatatypes::new()) |
| 673 | } |
| 674 | |
| 675 | /// 按属性**自己的** range 语义来解。 |
| 676 | /// |
| 677 | /// `rdfs:range` 写多条是交集,`schema:rangeIncludes` 写多条是并集,两者都落在 |
| 678 | /// 同一个 `ranges` 里——不看 [`OwlProperty::ranges_union`] 这一位就会把 |
| 679 | /// `author rangeIncludes Organization, Person` 读成"必须既是组织又是人"。 |
| 680 | pub fn map_range_of(p: &OwlProperty, vocab: &VocabDatatypes) -> RangeMapping { |
| 681 | resolve_range(&p.ranges, p.ranges_union, vocab) |
| 682 | } |
| 683 | |
| 684 | fn resolve_range(ranges: &[String], union: bool, vocab: &VocabDatatypes) -> RangeMapping { |
| 685 | // 词汇表自报的数据类型先查(schema:Text → text),查不到再走 xsd/owl 那套标准的 |
| 686 | let named = |iri: &String| vocab.get(iri).copied().or_else(|| datatype_of(iri)); |
| 687 | match ranges { |
| 688 | [] => RangeMapping::Absent, |
| 689 | [one] => match named(one) { |
| 690 | Some(dt) => RangeMapping::Datatype(dt), |
| 691 | None if unusable(one) => RangeMapping::Unusable(one.clone()), |
| 692 | None => RangeMapping::Degraded(one.clone()), |
| 693 | }, |
| 694 | many if union => { |
| 695 | // 并集:全指向同一种就是那一种(Text ∪ URL 都是 text)。 |
| 696 | // 不一致则降级成 text 并报告——text 是任意并集的诚实上界 |
| 697 | let dts: Vec<Option<&'static str>> = many.iter().map(named).collect(); |
| 698 | match dts[0] { |
| 699 | Some(dt) if dts.iter().all(|d| *d == Some(dt)) => RangeMapping::Datatype(dt), |
| 700 | _ if many.iter().all(|r| unusable(r)) => RangeMapping::Unusable(many.join(" ∪ ")), |
| 701 | _ => RangeMapping::Degraded(many.join(" ∪ ")), |
| 702 | } |
| 703 | } |
| 704 | // rdfs:range 写多条是交集语义,不猜类型——但值仍是字面量,所以按 text 建 |
| 705 | many => RangeMapping::Degraded(many.join(" ∩ ")), |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | /// 抽取器不可能从散文里读出来的那些:二进制块与 XML 内部管道。 |
| 710 | /// |
| 711 | /// 判据不是"这个值该不该存"——属性值本来就存在图谱里(走 `facts.object_value`, |
| 712 | /// 证据、时态、审阅全套)。判据是**会不会有值**:「门店每天 9:00 开门」里有 |
| 713 | /// `09:00`,而一张 base64 平面图不会出现在散文里;就算文档里真有一段 base64, |
| 714 | /// 把它当成事实抽出来也是错的。 |
| 715 | /// |
| 716 | /// **其余一律降级成 text**——一个抽得出来的值,宁可类型糙一点也别让它没处可去。 |
| 717 | fn unusable(iri: &str) -> bool { |
| 718 | if let Some(local) = iri.strip_prefix(XSD) { |
| 719 | return matches!( |
| 720 | local, |
| 721 | "base64Binary" |
| 722 | | "hexBinary" |
| 723 | | "QName" |
| 724 | | "NOTATION" |
| 725 | | "ID" |
| 726 | | "IDREF" |
| 727 | | "IDREFS" |
| 728 | | "ENTITY" |
| 729 | | "ENTITIES" |
| 730 | ); |
| 731 | } |
| 732 | if let Some(local) = iri.strip_prefix(RDF_NS) { |
| 733 | return local == "XMLLiteral"; |
| 734 | } |
| 735 | false |
| 736 | } |
| 737 | |
| 738 | fn datatype_of(iri: &str) -> Option<&'static str> { |
| 739 | if let Some(local) = iri.strip_prefix(XSD) { |
| 740 | return match local { |
| 741 | // 有界与无符号变体全部收进 number:区别在取值范围,不在语义 |
| 742 | "decimal" | "integer" | "int" | "long" | "short" | "byte" | "nonNegativeInteger" |
| 743 | | "positiveInteger" | "nonPositiveInteger" | "negativeInteger" | "unsignedLong" |
| 744 | | "unsignedInt" | "unsignedShort" | "unsignedByte" | "double" | "float" => { |
| 745 | Some("number") |
| 746 | } |
| 747 | // 我们的日期格式本就是 YYYY[-MM[-DD]],逐级可省,所以 gYear / gYearMonth 装得下 |
| 748 | "date" | "dateTime" | "dateTimeStamp" | "gYear" | "gYearMonth" => Some("date"), |
| 749 | "boolean" => Some("bool"), |
| 750 | "string" | "normalizedString" | "token" | "language" | "Name" | "NCName" |
| 751 | | "NMTOKEN" | "anyURI" => Some("text"), |
| 752 | // time / gMonth / gDay / gMonthDay 缺年,duration 系列是时长不是时点 —— |
| 753 | // 落到 None,再由 unusable() 分流:它们是可读字面量,降级成 text; |
| 754 | // 二进制与 XML 内部标识才是真的不收 |
| 755 | _ => None, |
| 756 | }; |
| 757 | } |
| 758 | if let Some(local) = iri.strip_prefix(RDF_NS) { |
| 759 | // XMLLiteral 是 XML 片段,不收 |
| 760 | return matches!(local, "PlainLiteral" | "langString").then_some("text"); |
| 761 | } |
| 762 | if let Some(local) = iri.strip_prefix(RDFS) { |
| 763 | return (local == "Literal").then_some("text"); |
| 764 | } |
| 765 | if let Some(local) = iri.strip_prefix(OWL) { |
| 766 | return matches!(local, "real" | "rational").then_some("number"); |
| 767 | } |
| 768 | None |
| 769 | } |
| 770 | |
| 771 | #[cfg(test)] |
| 772 | mod tests { |
| 773 | use super::*; |
| 774 | |
| 775 | #[test] |
| 776 | fn range_maps_every_numeric_variant() { |
| 777 | for local in [ |
| 778 | "decimal", |
| 779 | "integer", |
| 780 | "int", |
| 781 | "long", |
| 782 | "short", |
| 783 | "byte", |
| 784 | "nonNegativeInteger", |
| 785 | "positiveInteger", |
| 786 | "nonPositiveInteger", |
| 787 | "negativeInteger", |
| 788 | "unsignedLong", |
| 789 | "unsignedInt", |
| 790 | "unsignedShort", |
| 791 | "unsignedByte", |
| 792 | "double", |
| 793 | "float", |
| 794 | ] { |
| 795 | assert_eq!( |
| 796 | map_range(&[format!("{XSD}{local}")]), |
| 797 | RangeMapping::Datatype("number"), |
| 798 | "{local}" |
| 799 | ); |
| 800 | } |
| 801 | // owl:real / owl:rational 也在 OWL 2 的 datatype map 里 |
| 802 | assert_eq!( |
| 803 | map_range(&[format!("{OWL}rational")]), |
| 804 | RangeMapping::Datatype("number") |
| 805 | ); |
| 806 | } |
| 807 | |
| 808 | /// 我们的日期格式是 YYYY[-MM[-DD]],逐级可省,所以只缺低位的 g 类型装得下 |
| 809 | #[test] |
| 810 | fn partial_dates_fit_only_when_the_year_is_there() { |
| 811 | for local in ["date", "dateTime", "dateTimeStamp", "gYear", "gYearMonth"] { |
| 812 | assert_eq!( |
| 813 | map_range(&[format!("{XSD}{local}")]), |
| 814 | RangeMapping::Datatype("date"), |
| 815 | "{local}" |
| 816 | ); |
| 817 | } |
| 818 | // 缺年的进不了 date —— 但它们是可读字面量,降级成 text 而不是丢掉 |
| 819 | for local in ["gMonth", "gDay", "gMonthDay", "time"] { |
| 820 | assert!( |
| 821 | matches!( |
| 822 | map_range(&[format!("{XSD}{local}")]), |
| 823 | RangeMapping::Degraded(_) |
| 824 | ), |
| 825 | "{local} 该降级成 text,不该丢" |
| 826 | ); |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | /// 分界不是"能不能精确映射",而是**"这个取值该不该进图谱"**。 |
| 831 | /// 存得下的一律留下来——类型糙一点,好过这条知识彻底不被捕获。 |
| 832 | #[test] |
| 833 | fn a_value_we_can_store_is_kept_even_when_we_cannot_type_it() { |
| 834 | // 没写 range:没有声明可丢,text 是诚实的超集 |
| 835 | assert_eq!(map_range(&[]), RangeMapping::Absent); |
| 836 | // 写了但表达不了:时长是可读字面量,降级成 text 并报告 |
| 837 | assert!(matches!( |
| 838 | map_range(&[format!("{XSD}duration")]), |
| 839 | RangeMapping::Degraded(_) |
| 840 | )); |
| 841 | // 取值本就不该进图谱:二进制块与 XML 片段,这才是真的跳过 |
| 842 | assert!(matches!( |
| 843 | map_range(&[format!("{XSD}base64Binary")]), |
| 844 | RangeMapping::Unusable(_) |
| 845 | )); |
| 846 | assert!(matches!( |
| 847 | map_range(&[format!("{RDF_NS}XMLLiteral")]), |
| 848 | RangeMapping::Unusable(_) |
| 849 | )); |
| 850 | } |
| 851 | |
| 852 | /// 多条 range 在 RDFS 里是**交集**("必须同时是两者"),不是并集。 |
| 853 | /// 几乎总是建模笔误,但规范如此 —— 不猜。 |
| 854 | #[test] |
| 855 | fn several_ranges_are_an_intersection_we_refuse_to_guess() { |
| 856 | let m = map_range(&[format!("{XSD}string"), format!("{XSD}integer")]); |
| 857 | match m { |
| 858 | // 交集不猜类型,但值仍是字面量,所以按 text 落下来 |
| 859 | RangeMapping::Degraded(s) => assert!(s.contains('∩')), |
| 860 | other => panic!("多条 range 不该被精确映射: {other:?}"), |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | /// 按完整 IRI 匹配:自定义词汇表里叫 date 的**类**不是 xsd:date |
| 865 | #[test] |
| 866 | fn a_class_that_happens_to_be_called_date_is_not_a_date() { |
| 867 | assert!(matches!( |
| 868 | map_range(&["http://acme.example/hr#date".into()]), |
| 869 | RangeMapping::Degraded(_) |
| 870 | )); |
| 871 | } |
| 872 | |
| 873 | const TTL: &str = r#" |
| 874 | @prefix owl: <http://www.w3.org/2002/07/owl#> . |
| 875 | @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . |
| 876 | @prefix ex: <http://acme.example/hr#> . |
| 877 | |
| 878 | ex:Employee a owl:Class ; |
| 879 | rdfs:label "Employee"@en ; |
| 880 | rdfs:label "员工"@zh ; |
| 881 | rdfs:comment "A person on the payroll."@en ; |
| 882 | rdfs:subClassOf ex:Person . |
| 883 | ex:Person a owl:Class ; rdfs:label "Person" . |
| 884 | ex:hasManager a owl:ObjectProperty, owl:FunctionalProperty ; |
| 885 | rdfs:label "has manager" ; |
| 886 | rdfs:domain ex:Employee ; |
| 887 | rdfs:range ex:Person . |
| 888 | ex:salary a owl:DatatypeProperty ; rdfs:domain ex:Employee . |
| 889 | ex:Employee owl:disjointWith ex:Contractor . |
| 890 | ex:Employee owl:equivalentClass ex:Staff . |
| 891 | "#; |
| 892 | |
| 893 | #[test] |
| 894 | fn projects_classes_properties_and_reports_the_rest() { |
| 895 | let p = project(TTL.as_bytes(), RdfFormat::Turtle).unwrap(); |
| 896 | let emp = p.classes.iter().find(|c| c.key == "employee").unwrap(); |
| 897 | // 多语言标签取 en 优先 |
| 898 | assert_eq!(emp.label, "Employee"); |
| 899 | assert_eq!(emp.description, "A person on the payroll."); |
| 900 | assert_eq!(emp.parents, vec!["http://acme.example/hr#Person"]); |
| 901 | |
| 902 | let mgr = p |
| 903 | .properties |
| 904 | .iter() |
| 905 | .find(|x| x.key == "has_manager") |
| 906 | .unwrap(); |
| 907 | assert!(mgr.functional && !mgr.is_datatype); |
| 908 | assert_eq!(mgr.ranges, vec!["http://acme.example/hr#Person"]); |
| 909 | |
| 910 | let sal = p.properties.iter().find(|x| x.key == "salary").unwrap(); |
| 911 | assert!(sal.is_datatype); |
| 912 | |
| 913 | // 消费不了的公理进报告,不是丢弃也不是报错。 |
| 914 | // |
| 915 | // `disjointWith` 曾经在这份名单上,现在被消费了(它是一致性检查的判定 |
| 916 | // 依据)——所以这里改用一个仍然消费不了的公理来守这条性质本身 |
| 917 | assert!(p |
| 918 | .unprojected |
| 919 | .contains_key("http://www.w3.org/2002/07/owl#equivalentClass")); |
| 920 | } |
| 921 | |
| 922 | #[test] |
| 923 | fn detects_rdfxml_that_opens_with_comments() { |
| 924 | // FOAF 的官方文件就长这样:几十行 <!-- --> 之后才见 <rdf:RDF>。 |
| 925 | // 早先版本嗅不到 XML 标志就退回 Turtle,结果第一行就解析失败 |
| 926 | let head = b"<!-- This is the FOAF vocabulary, expressed using RDFS and OWL. -->\n\ |
| 927 | <!-- padding padding padding padding padding padding padding -->\n"; |
| 928 | assert_eq!(RdfFormat::detect("index.rdf", head), RdfFormat::RdfXml); |
| 929 | // 反过来:.owl 里放 Turtle 也常见,内容说了算 |
| 930 | assert_eq!( |
| 931 | RdfFormat::detect("x.owl", b"@prefix owl: <http://x#> .\n"), |
| 932 | RdfFormat::Turtle |
| 933 | ); |
| 934 | // 注释开头的 Turtle 同样认得出(# 行先跳过) |
| 935 | assert_eq!( |
| 936 | RdfFormat::detect("x", b"# a note\n\n@base <http://x> .\n"), |
| 937 | RdfFormat::Turtle |
| 938 | ); |
| 939 | } |
| 940 | |
| 941 | #[test] |
| 942 | fn key_derives_from_the_iri_local_name() { |
| 943 | assert_eq!(key_from_iri("http://x/hr#hasEmployee"), "has_employee"); |
| 944 | assert_eq!(key_from_iri("http://x/ns/Person"), "person"); |
| 945 | assert_eq!(key_from_iri("http://x#HTTP_Server"), "http_server"); |
| 946 | } |
| 947 | |
| 948 | /// schema.org 那一套的最小复刻:数据类型自报家门,属性用 |
| 949 | /// domainIncludes / rangeIncludes,全部只声明成 rdf:Property。 |
| 950 | const SCHEMA_ISH: &str = r#" |
| 951 | @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . |
| 952 | @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . |
| 953 | @prefix schema: <https://schema.org/> . |
| 954 | |
| 955 | schema:DataType a rdfs:Class . |
| 956 | schema:Text a rdfs:Class, schema:DataType . |
| 957 | schema:Number a rdfs:Class, schema:DataType . |
| 958 | schema:Date a rdfs:Class, schema:DataType . |
| 959 | schema:Time a rdfs:Class, schema:DataType . |
| 960 | schema:URL a rdfs:Class ; rdfs:subClassOf schema:Text . |
| 961 | schema:Integer a rdfs:Class ; rdfs:subClassOf schema:Number . |
| 962 | |
| 963 | schema:Organization a rdfs:Class ; rdfs:label "Organization" . |
| 964 | schema:Person a rdfs:Class ; rdfs:label "Person" . |
| 965 | schema:PostalAddress a rdfs:Class ; rdfs:label "PostalAddress" . |
| 966 | |
| 967 | schema:foundingDate a rdf:Property ; |
| 968 | schema:domainIncludes schema:Organization ; |
| 969 | schema:rangeIncludes schema:Date . |
| 970 | schema:author a rdf:Property ; |
| 971 | schema:domainIncludes schema:Organization ; |
| 972 | schema:rangeIncludes schema:Organization, schema:Person . |
| 973 | schema:address a rdf:Property ; |
| 974 | schema:domainIncludes schema:Organization ; |
| 975 | schema:rangeIncludes schema:PostalAddress, schema:Text . |
| 976 | schema:homepage a rdf:Property ; |
| 977 | schema:domainIncludes schema:Person ; |
| 978 | schema:rangeIncludes schema:Text, schema:URL . |
| 979 | schema:opens a rdf:Property ; |
| 980 | schema:domainIncludes schema:Organization ; |
| 981 | schema:rangeIncludes schema:Time . |
| 982 | schema:knows a rdf:Property ; |
| 983 | schema:domainIncludes schema:Person . |
| 984 | "#; |
| 985 | |
| 986 | fn schema_ish() -> OwlProjection { |
| 987 | project(SCHEMA_ISH.as_bytes(), RdfFormat::Turtle).unwrap() |
| 988 | } |
| 989 | |
| 990 | fn prop<'a>(p: &'a OwlProjection, key: &str) -> &'a OwlProperty { |
| 991 | p.properties.iter().find(|x| x.key == key).unwrap() |
| 992 | } |
| 993 | |
| 994 | #[test] |
| 995 | fn schema_org_datatypes_are_not_entity_types() { |
| 996 | let p = schema_ish(); |
| 997 | let keys: Vec<&str> = p.classes.iter().map(|c| c.key.as_str()).collect(); |
| 998 | // Text / Number / Date / Time 声明的是 `a rdfs:Class, schema:DataType`, |
| 999 | // 只看前半截就会建出叫 text、number 的实体类型来 |
| 1000 | for gone in [ |
| 1001 | "text", |
| 1002 | "number", |
| 1003 | "date", |
| 1004 | "time", |
| 1005 | "url", |
| 1006 | "integer", |
| 1007 | "data_type", |
| 1008 | ] { |
| 1009 | assert!(!keys.contains(&gone), "{gone} 不该是实体类型:{keys:?}"); |
| 1010 | } |
| 1011 | assert!(keys.contains(&"organization") && keys.contains(&"person")); |
| 1012 | } |
| 1013 | |
| 1014 | #[test] |
| 1015 | fn domain_includes_feeds_the_signature() { |
| 1016 | let p = schema_ish(); |
| 1017 | // 不认 schema:domainIncludes 的话这里是空的,签名就成了 (* → *) |
| 1018 | assert_eq!( |
| 1019 | prop(&p, "founding_date").domains, |
| 1020 | vec!["https://schema.org/Organization".to_string()] |
| 1021 | ); |
| 1022 | } |
| 1023 | |
| 1024 | #[test] |
| 1025 | fn a_union_range_of_classes_stays_a_relation() { |
| 1026 | let p = schema_ish(); |
| 1027 | // rangeIncludes Organization, Person —— 并集,两个都是类 |
| 1028 | assert!(!prop(&p, "author").is_datatype); |
| 1029 | // rangeIncludes PostalAddress, Text —— schema.org 的常见写法, |
| 1030 | // Text 是"懒得建实体就写个字符串"。判成属性就把这条边永久丢了 |
| 1031 | assert!(!prop(&p, "address").is_datatype); |
| 1032 | } |
| 1033 | |
| 1034 | #[test] |
| 1035 | fn a_union_range_of_datatypes_becomes_an_attribute() { |
| 1036 | let p = schema_ish(); |
| 1037 | let fd = prop(&p, "founding_date"); |
| 1038 | assert!(fd.is_datatype); |
| 1039 | assert_eq!( |
| 1040 | map_range_of(fd, &p.vocab_datatypes), |
| 1041 | RangeMapping::Datatype("date") |
| 1042 | ); |
| 1043 | // Text ∪ URL:URL ⊂ Text,两个都解到 text,所以不用降级也不用报告 |
| 1044 | let hp = prop(&p, "homepage"); |
| 1045 | assert!(hp.is_datatype); |
| 1046 | assert_eq!( |
| 1047 | map_range_of(hp, &p.vocab_datatypes), |
| 1048 | RangeMapping::Datatype("text") |
| 1049 | ); |
| 1050 | } |
| 1051 | |
| 1052 | #[test] |
| 1053 | fn a_union_is_not_an_intersection() { |
| 1054 | let p = schema_ish(); |
| 1055 | // 这是整件事最容易错的一步:两个 range 倒进同一个 Vec 之后, |
| 1056 | // 不看 ranges_union 就会当成 rdfs:range 的交集语义 |
| 1057 | assert!(prop(&p, "author").ranges_union); |
| 1058 | assert_eq!(prop(&p, "author").ranges.len(), 2); |
| 1059 | // 而 rdfs:range 写两条仍然是交集 |
| 1060 | assert!(matches!( |
| 1061 | map_range(&[format!("{XSD}string"), format!("{XSD}integer")]), |
| 1062 | RangeMapping::Degraded(ref s) if s.contains('∩') |
| 1063 | )); |
| 1064 | } |
| 1065 | |
| 1066 | #[test] |
| 1067 | fn an_unnamed_datatype_degrades_and_is_reported() { |
| 1068 | let p = schema_ish(); |
| 1069 | // schema:Time 只有时刻没有日期,跟 xsd:time 一个待遇:是数据类型 |
| 1070 | //(所以走属性通道、不当实体类型),但叫不上名 → 按 text 建**并报告** |
| 1071 | let o = prop(&p, "opens"); |
| 1072 | assert!(o.is_datatype); |
| 1073 | assert!(matches!( |
| 1074 | map_range_of(o, &p.vocab_datatypes), |
| 1075 | RangeMapping::Degraded(ref s) if s.ends_with("Time") |
| 1076 | )); |
| 1077 | } |
| 1078 | |
| 1079 | #[test] |
| 1080 | fn a_bare_rdf_property_without_range_is_still_a_relation() { |
| 1081 | let p = schema_ish(); |
| 1082 | // 没有 range 就没有判据,兜底仍是关系——宾语是 IRI 的远多于字面值 |
| 1083 | let k = prop(&p, "knows"); |
| 1084 | assert!(!k.is_datatype); |
| 1085 | assert!(k.ranges.is_empty()); |
| 1086 | } |
| 1087 | |
| 1088 | #[test] |
| 1089 | fn schema_predicates_are_consumed_not_reported_as_unprojected() { |
| 1090 | let p = schema_ish(); |
| 1091 | // 认了就不该再出现在"暂未投影"里,否则预览页会说 |
| 1092 | // "还有 2312 条 domainIncludes 没消费",而其实消费了 |
| 1093 | for consumed in ["domainIncludes", "rangeIncludes"] { |
| 1094 | assert!( |
| 1095 | !p.unprojected.keys().any(|k| k.ends_with(consumed)), |
| 1096 | "{consumed} 应已消费:{:?}", |
| 1097 | p.unprojected |
| 1098 | ); |
| 1099 | } |
| 1100 | } |
| 1101 | |
| 1102 | /// 一份文件里合了两个词汇表,主词汇表的 IRI 用 https、被引用的用 http—— |
| 1103 | /// 字典序下 http 在前,主词汇表就输了。这是 schema.org 那份文件的形状。 |
| 1104 | const TWO_VOCABS: &str = r#" |
| 1105 | @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . |
| 1106 | @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . |
| 1107 | @prefix home: <https://home.example/> . |
| 1108 | @prefix cited: <http://cited.example/> . |
| 1109 | |
| 1110 | home:Location a rdfs:Class ; rdfs:label "Location" . |
| 1111 | home:Country a rdfs:Class ; rdfs:label "Country" . |
| 1112 | home:Person a rdfs:Class ; rdfs:label "Person" . |
| 1113 | home:Organization a rdfs:Class ; rdfs:label "Organization" . |
| 1114 | cited:Location a rdfs:Class ; rdfs:label "Location (cited)" . |
| 1115 | |
| 1116 | home:worksAt a rdf:Property ; rdfs:label "worksAt" . |
| 1117 | home:knows a rdf:Property ; rdfs:label "knows" . |
| 1118 | cited:worksAt a rdf:Property ; rdfs:label "worksAt (cited)" . |
| 1119 | "#; |
| 1120 | |
| 1121 | #[test] |
| 1122 | fn the_files_own_vocabulary_wins_a_key_collision() { |
| 1123 | let p = project(TWO_VOCABS.as_bytes(), RdfFormat::Turtle).unwrap(); |
| 1124 | // 撞车由调用方先到先得地裁决,所以顺序就是裁决。 |
| 1125 | // 主词汇表声明得最多,它必须排在前面——否则 `http://` < `https://` |
| 1126 | // 这条字典序会让被引用的词汇表赢走 location、country、organization |
| 1127 | let first_location = p.classes.iter().find(|c| c.key == "location").unwrap(); |
| 1128 | assert!( |
| 1129 | first_location.iri.starts_with("https://home.example/"), |
| 1130 | "输给了 {}", |
| 1131 | first_location.iri |
| 1132 | ); |
| 1133 | let first_works = p.properties.iter().find(|x| x.key == "works_at").unwrap(); |
| 1134 | assert!(first_works.iri.starts_with("https://home.example/")); |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | #[cfg(test)] |
| 1139 | mod axioms { |
| 1140 | use super::*; |
| 1141 | |
| 1142 | /// OWL 的属性公理与类互斥都要投影出来——它们是一致性检查(0002 R0)的**判定 |
| 1143 | /// 依据**。没有它们,`A part_of B` 与 `B part_of A` 同时成立到底是矛盾还是 |
| 1144 | /// 正常,无从判起:`alias_of` 双向是对的,`produces` 双向几乎肯定是错的, |
| 1145 | /// 而区分这两者的东西只能来自本体。 |
| 1146 | const AX: &str = r#" |
| 1147 | @prefix owl: <http://www.w3.org/2002/07/owl#> . |
| 1148 | @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . |
| 1149 | @prefix ex: <http://acme.example/ax#> . |
| 1150 | |
| 1151 | ex:Person a owl:Class ; owl:disjointWith ex:Organization . |
| 1152 | ex:Organization a owl:Class . |
| 1153 | ex:Document a owl:Class . |
| 1154 | |
| 1155 | ex:partOf a owl:ObjectProperty, owl:TransitiveProperty, owl:AsymmetricProperty . |
| 1156 | ex:aliasOf a owl:ObjectProperty, owl:SymmetricProperty . |
| 1157 | ex:reportsTo a owl:ObjectProperty, owl:IrreflexiveProperty . |
| 1158 | ex:plain a owl:ObjectProperty . |
| 1159 | "#; |
| 1160 | |
| 1161 | fn proj() -> OwlProjection { |
| 1162 | project(AX.as_bytes(), RdfFormat::Turtle).unwrap() |
| 1163 | } |
| 1164 | |
| 1165 | #[test] |
| 1166 | fn property_axioms_survive_the_projection() { |
| 1167 | let p = proj(); |
| 1168 | let by = |k: &str| p.properties.iter().find(|x| x.key == k).unwrap().clone(); |
| 1169 | |
| 1170 | let part_of = by("part_of"); |
| 1171 | assert!(part_of.transitive, "TransitiveProperty 要落到属性上"); |
| 1172 | assert!(part_of.asymmetric, "AsymmetricProperty 同上"); |
| 1173 | assert!(!part_of.symmetric); |
| 1174 | |
| 1175 | assert!( |
| 1176 | by("alias_of").symmetric, |
| 1177 | "对称属性双向出现是正确的,不是矛盾" |
| 1178 | ); |
| 1179 | assert!(by("reports_to").irreflexive, "非自反:自己汇报给自己是矛盾"); |
| 1180 | |
| 1181 | // 没声明的一律为假——**默认不是"未知"而是"没这条公理"**。 |
| 1182 | // OWL 是开放世界,但一致性检查只能按写下来的判:没写就是没有依据, |
| 1183 | // 而没有依据时不报矛盾,比猜一个公理出来安全 |
| 1184 | let plain = by("plain"); |
| 1185 | assert!(!plain.transitive && !plain.symmetric); |
| 1186 | assert!(!plain.asymmetric && !plain.irreflexive); |
| 1187 | } |
| 1188 | |
| 1189 | /// **两个方向都要有。** 词表通常只写一遍(W3C Org 把四个类两两互斥写成六行), |
| 1190 | /// 只按书写方向存,查"A 与 B 互斥吗"就取决于调用方碰巧从哪一头问。 |
| 1191 | #[test] |
| 1192 | fn disjointness_is_recorded_from_both_ends() { |
| 1193 | let p = proj(); |
| 1194 | let d = |k: &str| { |
| 1195 | p.classes |
| 1196 | .iter() |
| 1197 | .find(|c| c.key == k) |
| 1198 | .unwrap() |
| 1199 | .disjoint_with |
| 1200 | .clone() |
| 1201 | }; |
| 1202 | assert_eq!(d("person"), vec!["http://acme.example/ax#Organization"]); |
| 1203 | assert_eq!(d("organization"), vec!["http://acme.example/ax#Person"]); |
| 1204 | assert!(d("document").is_empty(), "没声明互斥的类不该凭空多出来"); |
| 1205 | } |
| 1206 | } |
| 1207 | |
| 1208 | /// 拿**真包**验一遍,而不只是夹具。 |
| 1209 | /// |
| 1210 | /// 先例在 `pack_alignment::against_real_packs`:那一版靠真包抓出了四个凭记忆 |
| 1211 | /// 写错的 IRI。夹具只能证明"我写的 Turtle 我自己解析得了",真包能证明 |
| 1212 | /// "官方文件里那些写法我们接得住"——两者不是一回事。 |
| 1213 | #[cfg(test)] |
| 1214 | mod against_real_packs { |
| 1215 | use super::*; |
| 1216 | use std::io::Read; |
| 1217 | |
| 1218 | fn load(name: &str) -> Vec<u8> { |
| 1219 | let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../utopia-server/packs/"); |
| 1220 | let f = std::fs::File::open(format!("{path}{name}")).expect("包文件在"); |
| 1221 | let mut out = Vec::new(); |
| 1222 | flate2::read::GzDecoder::new(f) |
| 1223 | .read_to_end(&mut out) |
| 1224 | .expect("解压"); |
| 1225 | out |
| 1226 | } |
| 1227 | |
| 1228 | /// W3C Org 把 Organization / Role / Membership / Site / ChangeEvent 五者两两 |
| 1229 | /// 互斥,官方文件里每对只写一次。**五个类每个都该看到四个对端**——只按书写 |
| 1230 | /// 方向存的话,先被写到的那几个会缺对端,而缺哪个取决于文件里的行序。 |
| 1231 | /// |
| 1232 | /// (写这条断言时我按 grep 目测数成了"四者",真包当场纠正:`Organization` |
| 1233 | /// 也在互斥集里。夹具证明不了这种事。) |
| 1234 | #[test] |
| 1235 | fn w3c_org_declares_four_mutually_disjoint_classes() { |
| 1236 | let p = project(&load("w3c-org.ttl.gz"), RdfFormat::Turtle).unwrap(); |
| 1237 | for key in ["organization", "role", "membership", "site", "change_event"] { |
| 1238 | let c = p |
| 1239 | .classes |
| 1240 | .iter() |
| 1241 | .find(|c| c.key == key) |
| 1242 | .unwrap_or_else(|| panic!("{key} 该被投影出来")); |
| 1243 | assert_eq!( |
| 1244 | c.disjoint_with.len(), |
| 1245 | 4, |
| 1246 | "{key} 该与另外四个互斥,实得 {:?}", |
| 1247 | c.disjoint_with |
| 1248 | ); |
| 1249 | } |
| 1250 | } |
| 1251 | |
| 1252 | /// IOF Core 声明了一批传递属性(before/after/occursDuring…)。 |
| 1253 | /// 这是 R0 环检测唯一有真实依据的地方 |
| 1254 | #[test] |
| 1255 | fn iof_core_declares_transitive_properties() { |
| 1256 | let p = project(&load("iof-core.rdf.gz"), RdfFormat::RdfXml).unwrap(); |
| 1257 | let n = p.properties.iter().filter(|x| x.transitive).count(); |
| 1258 | assert!(n >= 8, "IOF 该有一批传递属性,实得 {n}"); |
| 1259 | } |
| 1260 | |
| 1261 | /// FOAF 的 Person ⊥ Organization / Document —— **最常撞的那一对**。 |
| 1262 | /// `classify_type_drift` 里那张手写表(person vs organization 判 Disjoint) |
| 1263 | /// 想表达的就是它,注释里也写着"公理落库后这张表应改从本体读" |
| 1264 | #[test] |
| 1265 | fn foaf_says_a_person_is_not_an_organization() { |
| 1266 | let p = project(&load("foaf.rdf.gz"), RdfFormat::RdfXml).unwrap(); |
| 1267 | let person = p |
| 1268 | .classes |
| 1269 | .iter() |
| 1270 | .find(|c| c.key == "person") |
| 1271 | .expect("foaf:Person"); |
| 1272 | assert!( |
| 1273 | person |
| 1274 | .disjoint_with |
| 1275 | .iter() |
| 1276 | .any(|d| d.ends_with("Organization")), |
| 1277 | "foaf:Person 该与 Organization 互斥,实得 {:?}", |
| 1278 | person.disjoint_with |
| 1279 | ); |
| 1280 | } |
| 1281 | } |
| 1282 | |
| 1283 | #[cfg(test)] |
| 1284 | mod property_axiom_tests { |
| 1285 | use super::*; |
| 1286 | |
| 1287 | /// `owl:inverseOf` 与 `rdfs:subPropertyOf` 要被读出来。 |
| 1288 | /// |
| 1289 | /// 从前 `subPropertyOf` 只出现在 `known()` 白名单里——认得出、不报警、 |
| 1290 | /// **然后扔掉**;`inverseOf` 连白名单都没进,被算进「暂未投影」。 |
| 1291 | /// 两种都是导一份本体进来,那部分信息当场消失。 |
| 1292 | #[test] |
| 1293 | fn the_two_property_relations_survive_projection() { |
| 1294 | let ttl = include_str!("../tests/inverse_and_sub.ttl"); |
| 1295 | let p = project(ttl.as_bytes(), RdfFormat::Turtle).expect("解析"); |
| 1296 | let by = |k: &str| { |
| 1297 | p.properties |
| 1298 | .iter() |
| 1299 | .find(|x| x.key == k) |
| 1300 | .unwrap_or_else(|| panic!("没有 {k}")) |
| 1301 | }; |
| 1302 | assert_eq!( |
| 1303 | by("employs").inverse_of.as_deref(), |
| 1304 | Some("http://example.org/worksAt"), |
| 1305 | "**逆要按写的方向收**——补反向是读取公理时的事" |
| 1306 | ); |
| 1307 | assert_eq!( |
| 1308 | by("ceo_of").sub_property_of.as_deref(), |
| 1309 | Some("http://example.org/worksAt") |
| 1310 | ); |
| 1311 | // 反方向没写,就该是空的:本体写了什么与我们推了什么要分得开, |
| 1312 | // R0 的 inverse_not_mutual 检查靠这个区分 |
| 1313 | assert!( |
| 1314 | by("works_at").inverse_of.is_none(), |
| 1315 | "没写的方向不该在导入时被补上" |
| 1316 | ); |
| 1317 | assert!( |
| 1318 | !p.unprojected.keys().any(|k| k.contains("inverseOf")), |
| 1319 | "**认了就不该再算进「暂未投影」**" |
| 1320 | ); |
| 1321 | } |
| 1322 | } |