mod.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use crate::{
  19. error::{Error, Result},
  20. //prop::{Property, PropertySubType, PropertyType, PropertySExprValue},
  21. };
  22. use darkfi_serial::{
  23. async_trait, Decodable, Encodable, FutAsyncWriteExt, ReadExt, SerialDecodable, SerialEncodable,
  24. };
  25. use std::io::{Read, Write};
  26. mod compile;
  27. pub use compile::Compiler;
  28. pub fn const_f32(x: f32) -> SExprCode {
  29. vec![Op::ConstFloat32(x)]
  30. }
  31. pub fn load_var<S: Into<String>>(var: S) -> SExprCode {
  32. vec![Op::LoadVar(var.into())]
  33. }
  34. #[derive(Clone, Debug, PartialEq, SerialEncodable, SerialDecodable)]
  35. pub enum SExprVal {
  36. Null,
  37. Bool(bool),
  38. Uint32(u32),
  39. Float32(f32),
  40. Str(String),
  41. }
  42. impl SExprVal {
  43. #[allow(dead_code)]
  44. fn is_null(&self) -> bool {
  45. match self {
  46. Self::Null => true,
  47. _ => false,
  48. }
  49. }
  50. #[allow(dead_code)]
  51. fn is_bool(&self) -> bool {
  52. match self {
  53. Self::Bool(_) => true,
  54. _ => false,
  55. }
  56. }
  57. fn is_u32(&self) -> bool {
  58. match self {
  59. Self::Uint32(_) => true,
  60. _ => false,
  61. }
  62. }
  63. #[allow(dead_code)]
  64. fn is_f32(&self) -> bool {
  65. match self {
  66. Self::Float32(_) => true,
  67. _ => false,
  68. }
  69. }
  70. #[allow(dead_code)]
  71. fn is_str(&self) -> bool {
  72. match self {
  73. Self::Str(_) => true,
  74. _ => false,
  75. }
  76. }
  77. #[allow(dead_code)]
  78. fn as_bool(&self) -> Result<bool> {
  79. match self {
  80. Self::Bool(v) => Ok(*v),
  81. _ => Err(Error::PropertyWrongType),
  82. }
  83. }
  84. pub fn as_u32(&self) -> Result<u32> {
  85. match self {
  86. Self::Uint32(v) => Ok(*v),
  87. _ => Err(Error::PropertyWrongType),
  88. }
  89. }
  90. pub fn as_f32(&self) -> Result<f32> {
  91. match self {
  92. Self::Float32(v) => Ok(*v),
  93. _ => Err(Error::PropertyWrongType),
  94. }
  95. }
  96. #[allow(dead_code)]
  97. fn as_str(&self) -> Result<String> {
  98. match self {
  99. Self::Str(v) => Ok(v.clone()),
  100. _ => Err(Error::PropertyWrongType),
  101. }
  102. }
  103. pub fn coerce_f32(&self) -> Result<f32> {
  104. match self {
  105. Self::Uint32(v) => Ok(*v as f32),
  106. Self::Float32(v) => Ok(*v),
  107. _ => Err(Error::PropertyWrongType),
  108. }
  109. }
  110. }
  111. #[derive(Debug, PartialEq)]
  112. pub struct SExprMachine<'a> {
  113. pub globals: Vec<(String, SExprVal)>,
  114. pub stmts: &'a SExprCode,
  115. }
  116. // Each item is a statement
  117. pub type SExprCode = Vec<Op>;
  118. #[derive(Clone, Debug, PartialEq)]
  119. pub enum Op {
  120. Null,
  121. Add((Box<Op>, Box<Op>)),
  122. Sub((Box<Op>, Box<Op>)),
  123. Mul((Box<Op>, Box<Op>)),
  124. Div((Box<Op>, Box<Op>)),
  125. ConstBool(bool),
  126. ConstUint32(u32),
  127. ConstFloat32(f32),
  128. ConstStr(String),
  129. LoadVar(String),
  130. StoreVar((String, Box<Op>)),
  131. Min((Box<Op>, Box<Op>)),
  132. Max((Box<Op>, Box<Op>)),
  133. IsEqual((Box<Op>, Box<Op>)),
  134. LessThan((Box<Op>, Box<Op>)),
  135. Float32ToUint32(Box<Op>),
  136. IfElse((Box<Op>, SExprCode, SExprCode)),
  137. }
  138. impl<'a> SExprMachine<'a> {
  139. pub fn call(&mut self) -> Result<SExprVal> {
  140. if self.stmts.is_empty() {
  141. return Ok(SExprVal::Null)
  142. }
  143. for i in 0..(self.stmts.len() - 1) {
  144. self.eval(&self.stmts[i])?;
  145. }
  146. self.eval(self.stmts.last().unwrap())
  147. }
  148. fn eval(&mut self, op: &Op) -> Result<SExprVal> {
  149. match op {
  150. Op::Null => Ok(SExprVal::Null),
  151. Op::Add((lhs, rhs)) => self.add(lhs, rhs),
  152. Op::Sub((lhs, rhs)) => self.sub(lhs, rhs),
  153. Op::Mul((lhs, rhs)) => self.mul(lhs, rhs),
  154. Op::Div((lhs, rhs)) => self.div(lhs, rhs),
  155. Op::ConstBool(val) => Ok(SExprVal::Bool(*val)),
  156. Op::ConstUint32(val) => Ok(SExprVal::Uint32(*val)),
  157. Op::ConstFloat32(val) => Ok(SExprVal::Float32(*val)),
  158. Op::ConstStr(val) => Ok(SExprVal::Str(val.clone())),
  159. Op::LoadVar(var) => self.load_var(var),
  160. Op::StoreVar((var, val)) => self.store_var(var, val),
  161. Op::Min((lhs, rhs)) => self.min(lhs, rhs),
  162. Op::Max((lhs, rhs)) => self.max(lhs, rhs),
  163. Op::IsEqual((lhs, rhs)) => self.is_equal(lhs, rhs),
  164. Op::LessThan((lhs, rhs)) => self.less_than(lhs, rhs),
  165. Op::Float32ToUint32(val) => self.float32_to_uint32(val),
  166. Op::IfElse((cond, if_val, else_val)) => self.if_else(cond, if_val, else_val),
  167. }
  168. }
  169. fn add(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  170. let lhs = self.eval(lhs)?;
  171. let rhs = self.eval(rhs)?;
  172. if lhs.is_u32() && rhs.is_u32() {
  173. return Ok(SExprVal::Uint32(lhs.as_u32().unwrap() + rhs.as_u32().unwrap()))
  174. }
  175. let lhs = lhs.coerce_f32()?;
  176. let rhs = rhs.coerce_f32()?;
  177. Ok(SExprVal::Float32(lhs + rhs))
  178. }
  179. fn sub(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  180. let lhs = self.eval(lhs)?;
  181. let rhs = self.eval(rhs)?;
  182. if lhs.is_u32() && rhs.is_u32() {
  183. return Ok(SExprVal::Uint32(lhs.as_u32().unwrap() - rhs.as_u32().unwrap()))
  184. }
  185. let lhs = lhs.coerce_f32()?;
  186. let rhs = rhs.coerce_f32()?;
  187. Ok(SExprVal::Float32(lhs - rhs))
  188. }
  189. fn mul(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  190. let lhs = self.eval(lhs)?;
  191. let rhs = self.eval(rhs)?;
  192. if lhs.is_u32() && rhs.is_u32() {
  193. return Ok(SExprVal::Uint32(lhs.as_u32().unwrap() * rhs.as_u32().unwrap()))
  194. }
  195. let lhs = lhs.coerce_f32()?;
  196. let rhs = rhs.coerce_f32()?;
  197. Ok(SExprVal::Float32(lhs * rhs))
  198. }
  199. fn div(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  200. let lhs = self.eval(lhs)?;
  201. let rhs = self.eval(rhs)?;
  202. // Always coerce
  203. let lhs = lhs.coerce_f32()?;
  204. let rhs = rhs.coerce_f32()?;
  205. Ok(SExprVal::Float32(lhs / rhs))
  206. }
  207. fn load_var(&self, var: &str) -> Result<SExprVal> {
  208. for (name, val) in &self.globals {
  209. if name == var {
  210. return Ok(val.clone())
  211. }
  212. }
  213. Err(Error::SExprGlobalNotFound)
  214. }
  215. fn store_var(&mut self, var: &str, val: &Op) -> Result<SExprVal> {
  216. let val = self.eval(val)?;
  217. self.globals.push((var.to_string(), val));
  218. Ok(SExprVal::Null)
  219. }
  220. fn min(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  221. let lhs = self.eval(lhs)?;
  222. let rhs = self.eval(rhs)?;
  223. if lhs.is_u32() && rhs.is_u32() {
  224. let lhs = lhs.as_u32().unwrap();
  225. let rhs = rhs.as_u32().unwrap();
  226. let min = if lhs < rhs { lhs } else { rhs };
  227. return Ok(SExprVal::Uint32(min))
  228. }
  229. let lhs = lhs.coerce_f32()?;
  230. let rhs = rhs.coerce_f32()?;
  231. let min = if lhs < rhs { lhs } else { rhs };
  232. Ok(SExprVal::Float32(min))
  233. }
  234. fn max(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  235. let lhs = self.eval(lhs)?;
  236. let rhs = self.eval(rhs)?;
  237. if lhs.is_u32() && rhs.is_u32() {
  238. let lhs = lhs.as_u32().unwrap();
  239. let rhs = rhs.as_u32().unwrap();
  240. let max = if lhs > rhs { lhs } else { rhs };
  241. return Ok(SExprVal::Uint32(max))
  242. }
  243. let lhs = lhs.coerce_f32()?;
  244. let rhs = rhs.coerce_f32()?;
  245. let max = if lhs > rhs { lhs } else { rhs };
  246. Ok(SExprVal::Float32(max))
  247. }
  248. fn is_equal(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  249. let lhs = self.eval(lhs)?;
  250. let rhs = self.eval(rhs)?;
  251. if lhs.is_u32() && rhs.is_u32() {
  252. return Ok(SExprVal::Bool(lhs.as_u32().unwrap() == rhs.as_u32().unwrap()))
  253. }
  254. let lhs = lhs.coerce_f32()?;
  255. let rhs = rhs.coerce_f32()?;
  256. let is_equal = (lhs - rhs).abs() < f32::EPSILON;
  257. Ok(SExprVal::Bool(is_equal))
  258. }
  259. fn less_than(&mut self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  260. let lhs = self.eval(lhs)?;
  261. let rhs = self.eval(rhs)?;
  262. if lhs.is_u32() && rhs.is_u32() {
  263. return Ok(SExprVal::Bool(lhs.as_u32().unwrap() < rhs.as_u32().unwrap()))
  264. }
  265. let lhs = lhs.coerce_f32()?;
  266. let rhs = rhs.coerce_f32()?;
  267. Ok(SExprVal::Bool(lhs < rhs))
  268. }
  269. fn float32_to_uint32(&mut self, val: &Op) -> Result<SExprVal> {
  270. let val = self.eval(val)?;
  271. if val.is_u32() {
  272. return Ok(SExprVal::Uint32(val.as_u32()?))
  273. }
  274. Ok(SExprVal::Uint32(val.as_f32()? as u32))
  275. }
  276. fn if_else(&mut self, cond: &Op, if_val: &SExprCode, else_val: &SExprCode) -> Result<SExprVal> {
  277. let cond = self.eval(cond)?;
  278. let cond = cond.as_bool()?;
  279. if cond {
  280. let mut machine = SExprMachine { globals: self.globals.clone(), stmts: if_val };
  281. machine.call()
  282. } else {
  283. let mut machine = SExprMachine { globals: self.globals.clone(), stmts: else_val };
  284. machine.call()
  285. }
  286. }
  287. }
  288. impl Encodable for Op {
  289. fn encode<S: Write>(&self, s: &mut S) -> std::result::Result<usize, std::io::Error> {
  290. let mut len = 0;
  291. match self {
  292. Self::Null => {
  293. len += 0u8.encode(s)?;
  294. }
  295. Self::Add((lhs, rhs)) => {
  296. len += 1u8.encode(s)?;
  297. len += lhs.encode(s)?;
  298. len += rhs.encode(s)?;
  299. }
  300. Self::Sub((lhs, rhs)) => {
  301. len += 2u8.encode(s)?;
  302. len += lhs.encode(s)?;
  303. len += rhs.encode(s)?;
  304. }
  305. Self::Mul((lhs, rhs)) => {
  306. len += 3u8.encode(s)?;
  307. len += lhs.encode(s)?;
  308. len += rhs.encode(s)?;
  309. }
  310. Self::Div((lhs, rhs)) => {
  311. len += 4u8.encode(s)?;
  312. len += lhs.encode(s)?;
  313. len += rhs.encode(s)?;
  314. }
  315. Self::ConstBool(val) => {
  316. len += 5u8.encode(s)?;
  317. len += val.encode(s)?;
  318. }
  319. Self::ConstUint32(val) => {
  320. len += 6u8.encode(s)?;
  321. len += val.encode(s)?;
  322. }
  323. Self::ConstFloat32(val) => {
  324. len += 7u8.encode(s)?;
  325. len += val.encode(s)?;
  326. }
  327. Self::ConstStr(val) => {
  328. len += 8u8.encode(s)?;
  329. len += val.encode(s)?;
  330. }
  331. Self::LoadVar(var) => {
  332. len += 9u8.encode(s)?;
  333. len += var.encode(s)?;
  334. }
  335. Self::StoreVar((var, val)) => {
  336. len += 10u8.encode(s)?;
  337. len += var.encode(s)?;
  338. len += val.encode(s)?;
  339. }
  340. Self::Min((lhs, rhs)) => {
  341. len += 11u8.encode(s)?;
  342. len += lhs.encode(s)?;
  343. len += rhs.encode(s)?;
  344. }
  345. Self::Max((lhs, rhs)) => {
  346. len += 12u8.encode(s)?;
  347. len += lhs.encode(s)?;
  348. len += rhs.encode(s)?;
  349. }
  350. Self::IsEqual((lhs, rhs)) => {
  351. len += 13u8.encode(s)?;
  352. len += lhs.encode(s)?;
  353. len += rhs.encode(s)?;
  354. }
  355. Self::LessThan((lhs, rhs)) => {
  356. len += 14u8.encode(s)?;
  357. len += lhs.encode(s)?;
  358. len += rhs.encode(s)?;
  359. }
  360. Self::Float32ToUint32(val) => {
  361. len += 15u8.encode(s)?;
  362. len += val.encode(s)?;
  363. }
  364. Self::IfElse((cond, if_val, else_val)) => {
  365. len += 16u8.encode(s)?;
  366. len += cond.encode(s)?;
  367. len += if_val.encode(s)?;
  368. len += else_val.encode(s)?;
  369. }
  370. }
  371. Ok(len)
  372. }
  373. }
  374. impl Decodable for Op {
  375. fn decode<D: Read>(d: &mut D) -> std::result::Result<Self, std::io::Error> {
  376. let op_type = d.read_u8()?;
  377. let self_ = match op_type {
  378. 0 => Self::Null,
  379. 1 => Self::Add((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  380. 2 => Self::Sub((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  381. 3 => Self::Mul((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  382. 4 => Self::Div((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  383. 5 => Self::ConstBool(d.read_bool()?),
  384. 6 => Self::ConstUint32(d.read_u32()?),
  385. 7 => Self::ConstFloat32(d.read_f32()?),
  386. 8 => Self::ConstStr(String::decode(d)?),
  387. 9 => Self::LoadVar(String::decode(d)?),
  388. 10 => Self::StoreVar((String::decode(d)?, Box::new(Self::decode(d)?))),
  389. 11 => Self::Min((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  390. 12 => Self::Max((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  391. 13 => Self::IsEqual((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  392. 14 => Self::LessThan((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  393. 15 => Self::Float32ToUint32(Box::new(Self::decode(d)?)),
  394. 16 => Self::IfElse((
  395. Box::new(Self::decode(d)?),
  396. Decodable::decode(d)?,
  397. Decodable::decode(d)?,
  398. )),
  399. _ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid Op type")),
  400. };
  401. Ok(self_)
  402. }
  403. }
  404. #[cfg(test)]
  405. mod tests {
  406. use super::*;
  407. use darkfi_serial::{deserialize, serialize};
  408. #[test]
  409. fn seval() {
  410. let mut machine = SExprMachine {
  411. globals: vec![
  412. ("sw".to_string(), SExprVal::Uint32(110u32)),
  413. ("sh".to_string(), SExprVal::Uint32(4u32)),
  414. ],
  415. stmts: &vec![Op::Add((
  416. Box::new(Op::ConstUint32(5)),
  417. Box::new(Op::Div((
  418. Box::new(Op::LoadVar("sw".to_string())),
  419. Box::new(Op::ConstUint32(2)),
  420. ))),
  421. ))],
  422. };
  423. assert_eq!(machine.call().unwrap(), SExprVal::Float32(60.));
  424. }
  425. #[test]
  426. fn encdec_code() {
  427. let code = Op::Add((
  428. Box::new(Op::ConstUint32(5)),
  429. Box::new(Op::Div((
  430. Box::new(Op::LoadVar("sw".to_string())),
  431. Box::new(Op::ConstUint32(2)),
  432. ))),
  433. ));
  434. let code_s = serialize(&code);
  435. let code2 = deserialize::<Op>(&code_s).unwrap();
  436. assert_eq!(code, code2);
  437. }
  438. #[test]
  439. fn if_store() {
  440. let code = vec![
  441. Op::StoreVar((
  442. "s".to_string(),
  443. Box::new(Op::IfElse((
  444. Box::new(Op::ConstBool(false)),
  445. vec![Op::ConstUint32(4)],
  446. vec![Op::ConstUint32(110)],
  447. ))),
  448. )),
  449. Op::LoadVar("s".to_string()),
  450. ];
  451. let mut machine = SExprMachine { globals: vec![], stmts: &code };
  452. assert_eq!(machine.call().unwrap(), SExprVal::Uint32(110));
  453. }
  454. }