narust_158/language/conversion/
from.rs

1//! 词项→其它类型
2
3use super::{super::base::*, lexical_fold};
4use anyhow::Result;
5use narsese::{conversion::inter_type::lexical_fold::TryFoldInto, lexical::Term as TermLexical};
6use std::str::FromStr;
7
8impl Term {
9    /// 尝试从「词法Narsese」转换
10    /// * 💭【2024-04-21 14:44:15】目前此中方法「相较保守」
11    /// * 📌与词法Narsese基本对应(ASCII)
12    /// * ✅基本保证「解析结果均保证『合法』」
13    /// * 🚩【2024-06-13 18:39:33】现在是「词法折叠」使用本处实现
14    /// * ⚠️在「词法折叠」的过程中,即开始「变量匿名化」
15    ///   * 📌【2024-07-02 00:40:39】需要保证「格式化」的是个「整体」:变量只在「整体」范围内有意义
16    /// * 🚩【2024-09-06 17:32:12】在「词法折叠」的过程中,即开始使用`make`系列方法
17    ///   * 🎯应对类似「`(&&, A, A)` => `(&&, A)`」的「不完整简化」现象
18    #[inline]
19    pub fn from_lexical(lexical: TermLexical) -> Result<Self> {
20        lexical_fold::lexical_fold(lexical)
21    }
22
23    /// 尝试从「方言」转换
24    /// * 🎯支持「方言解析」
25    /// * 📌【2024-05-15 02:33:13】目前仍只有「从字符串到词项」这一种形式
26    /// * 🆕附加功能,与核心「数据算法」「推理控制」无关
27    #[inline]
28    #[cfg(feature = "dialect_parser")]
29    pub fn from_dialect(input: &str) -> Result<Self> {
30        use super::super::dialect::parse_term;
31        parse_term(input)
32    }
33}
34
35/// 词法折叠
36impl TryFoldInto<'_, Term, anyhow::Error> for TermLexical {
37    /// 类型占位符
38    type Folder = ();
39
40    fn try_fold_into(self, _: &'_ Self::Folder) -> Result<Term> {
41        Term::from_lexical(self)
42    }
43}
44
45/// 基于「词法折叠」实现[`TryFrom`]
46impl TryFrom<TermLexical> for Term {
47    type Error = anyhow::Error;
48
49    #[inline]
50    fn try_from(value: TermLexical) -> Result<Self, Self::Error> {
51        value.try_fold_into(&())
52    }
53}
54
55///  字符串解析
56/// * 🎯同时兼容[`str::parse`]与[`str::try_into`]
57impl FromStr for Term {
58    type Err = anyhow::Error;
59
60    fn from_str(s: &str) -> Result<Self, Self::Err> {
61        s.try_into()
62    }
63}
64
65/// 字符串解析路线:词法解析 ⇒ 词法折叠
66/// * 🎯同时兼容[`str::parse`]与[`str::try_into`]
67/// * 📌使用标准OpenNARS ASCII语法
68impl TryFrom<&str> for Term {
69    type Error = anyhow::Error;
70
71    fn try_from(s: &str) -> Result<Self, Self::Error> {
72        use narsese::conversion::string::impl_lexical::format_instances::FORMAT_ASCII;
73        // 词法解析
74        let lexical = FORMAT_ASCII.parse(s)?;
75        // 词法转换 | ⚠️对「语句」「任务」报错
76        let term = lexical.try_into_term()?;
77        // 词法折叠
78        let term = term.try_into()?;
79        // 返回
80        Ok(term)
81    }
82}