expr.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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. #[derive(Clone, Debug, PartialEq, SerialEncodable, SerialDecodable)]
  27. pub enum SExprVal {
  28. Null,
  29. Bool(bool),
  30. Uint32(u32),
  31. Float32(f32),
  32. Str(String),
  33. }
  34. impl SExprVal {
  35. fn is_null(&self) -> bool {
  36. match self {
  37. Self::Null => true,
  38. _ => false,
  39. }
  40. }
  41. fn is_bool(&self) -> bool {
  42. match self {
  43. Self::Bool(_) => true,
  44. _ => false,
  45. }
  46. }
  47. fn is_u32(&self) -> bool {
  48. match self {
  49. Self::Uint32(_) => true,
  50. _ => false,
  51. }
  52. }
  53. fn is_f32(&self) -> bool {
  54. match self {
  55. Self::Float32(_) => true,
  56. _ => false,
  57. }
  58. }
  59. fn is_str(&self) -> bool {
  60. match self {
  61. Self::Str(_) => true,
  62. _ => false,
  63. }
  64. }
  65. fn as_bool(&self) -> Result<bool> {
  66. match self {
  67. Self::Bool(v) => Ok(*v),
  68. _ => Err(Error::PropertyWrongType),
  69. }
  70. }
  71. pub fn as_u32(&self) -> Result<u32> {
  72. match self {
  73. Self::Uint32(v) => Ok(*v),
  74. _ => Err(Error::PropertyWrongType),
  75. }
  76. }
  77. pub fn as_f32(&self) -> Result<f32> {
  78. match self {
  79. Self::Float32(v) => Ok(*v),
  80. _ => Err(Error::PropertyWrongType),
  81. }
  82. }
  83. fn as_str(&self) -> Result<String> {
  84. match self {
  85. Self::Str(v) => Ok(v.clone()),
  86. _ => Err(Error::PropertyWrongType),
  87. }
  88. }
  89. pub fn coerce_f32(&self) -> Result<f32> {
  90. match self {
  91. Self::Uint32(v) => Ok(*v as f32),
  92. Self::Float32(v) => Ok(*v),
  93. _ => Err(Error::PropertyWrongType),
  94. }
  95. }
  96. }
  97. #[derive(Debug, PartialEq)]
  98. pub struct SExprMachine<'a> {
  99. pub globals: Vec<(String, SExprVal)>,
  100. pub stmts: &'a SExprCode,
  101. }
  102. // Each item is a statement
  103. pub type SExprCode = Vec<Op>;
  104. #[derive(Debug, PartialEq)]
  105. pub enum Op {
  106. Null,
  107. Add((Box<Op>, Box<Op>)),
  108. Sub((Box<Op>, Box<Op>)),
  109. Mul((Box<Op>, Box<Op>)),
  110. Div((Box<Op>, Box<Op>)),
  111. ConstBool(bool),
  112. ConstUint32(u32),
  113. ConstFloat32(f32),
  114. ConstStr(String),
  115. LoadVar(String),
  116. //StoreVar((String, Box<Op>)),
  117. Min((Box<Op>, Box<Op>)),
  118. Max((Box<Op>, Box<Op>)),
  119. IsEqual((Box<Op>, Box<Op>)),
  120. LessThan((Box<Op>, Box<Op>)),
  121. Float32ToUint32(Box<Op>),
  122. }
  123. impl<'a> SExprMachine<'a> {
  124. pub fn call(&self) -> Result<SExprVal> {
  125. if self.stmts.is_empty() {
  126. return Ok(SExprVal::Null)
  127. }
  128. for i in 0..(self.stmts.len() - 1) {
  129. self.eval(&self.stmts[i])?;
  130. }
  131. self.eval(self.stmts.last().unwrap())
  132. }
  133. fn eval(&self, op: &Op) -> Result<SExprVal> {
  134. match op {
  135. Op::Null => Ok(SExprVal::Null),
  136. Op::Add((lhs, rhs)) => self.add(lhs, rhs),
  137. Op::Sub((lhs, rhs)) => self.sub(lhs, rhs),
  138. Op::Mul((lhs, rhs)) => self.mul(lhs, rhs),
  139. Op::Div((lhs, rhs)) => self.div(lhs, rhs),
  140. Op::ConstBool(val) => Ok(SExprVal::Bool(*val)),
  141. Op::ConstUint32(val) => Ok(SExprVal::Uint32(*val)),
  142. Op::ConstFloat32(val) => Ok(SExprVal::Float32(*val)),
  143. Op::ConstStr(val) => Ok(SExprVal::Str(val.clone())),
  144. Op::LoadVar(var) => self.load_var(var),
  145. //Op::StoreVar((var, val)) => self.store_var(var, val),
  146. Op::Min((lhs, rhs)) => self.min(lhs, rhs),
  147. Op::Max((lhs, rhs)) => self.max(lhs, rhs),
  148. Op::IsEqual((lhs, rhs)) => self.is_equal(lhs, rhs),
  149. Op::LessThan((lhs, rhs)) => self.less_than(lhs, rhs),
  150. Op::Float32ToUint32(val) => self.float32_to_uint32(val),
  151. }
  152. }
  153. fn add(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  154. let lhs = self.eval(lhs)?;
  155. let rhs = self.eval(rhs)?;
  156. if lhs.is_u32() && rhs.is_u32() {
  157. return Ok(SExprVal::Uint32(lhs.as_u32().unwrap() + rhs.as_u32().unwrap()))
  158. }
  159. let lhs = lhs.coerce_f32()?;
  160. let rhs = rhs.coerce_f32()?;
  161. Ok(SExprVal::Float32(lhs + rhs))
  162. }
  163. fn sub(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  164. let lhs = self.eval(lhs)?;
  165. let rhs = self.eval(rhs)?;
  166. if lhs.is_u32() && rhs.is_u32() {
  167. return Ok(SExprVal::Uint32(lhs.as_u32().unwrap() - rhs.as_u32().unwrap()))
  168. }
  169. let lhs = lhs.coerce_f32()?;
  170. let rhs = rhs.coerce_f32()?;
  171. Ok(SExprVal::Float32(lhs - rhs))
  172. }
  173. fn mul(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  174. let lhs = self.eval(lhs)?;
  175. let rhs = self.eval(rhs)?;
  176. if lhs.is_u32() && rhs.is_u32() {
  177. return Ok(SExprVal::Uint32(lhs.as_u32().unwrap() * rhs.as_u32().unwrap()))
  178. }
  179. let lhs = lhs.coerce_f32()?;
  180. let rhs = rhs.coerce_f32()?;
  181. Ok(SExprVal::Float32(lhs * rhs))
  182. }
  183. fn div(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  184. let lhs = self.eval(lhs)?;
  185. let rhs = self.eval(rhs)?;
  186. // Always coerce
  187. let lhs = lhs.coerce_f32()?;
  188. let rhs = rhs.coerce_f32()?;
  189. Ok(SExprVal::Float32(lhs / rhs))
  190. }
  191. fn load_var(&self, var: &str) -> Result<SExprVal> {
  192. for (name, val) in &self.globals {
  193. if name == var {
  194. return Ok(val.clone())
  195. }
  196. }
  197. Err(Error::SExprGlobalNotFound)
  198. }
  199. //fn store_var(&mut self, var, val) {
  200. //}
  201. fn min(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  202. let lhs = self.eval(lhs)?;
  203. let rhs = self.eval(rhs)?;
  204. if lhs.is_u32() && rhs.is_u32() {
  205. let lhs = lhs.as_u32().unwrap();
  206. let rhs = rhs.as_u32().unwrap();
  207. let min = if lhs < rhs { lhs } else { rhs };
  208. return Ok(SExprVal::Uint32(min))
  209. }
  210. let lhs = lhs.coerce_f32()?;
  211. let rhs = rhs.coerce_f32()?;
  212. let min = if lhs < rhs { lhs } else { rhs };
  213. Ok(SExprVal::Float32(min))
  214. }
  215. fn max(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  216. let lhs = self.eval(lhs)?;
  217. let rhs = self.eval(rhs)?;
  218. if lhs.is_u32() && rhs.is_u32() {
  219. let lhs = lhs.as_u32().unwrap();
  220. let rhs = rhs.as_u32().unwrap();
  221. let max = if lhs > rhs { lhs } else { rhs };
  222. return Ok(SExprVal::Uint32(max))
  223. }
  224. let lhs = lhs.coerce_f32()?;
  225. let rhs = rhs.coerce_f32()?;
  226. let max = if lhs > rhs { lhs } else { rhs };
  227. Ok(SExprVal::Float32(max))
  228. }
  229. fn is_equal(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  230. let lhs = self.eval(lhs)?;
  231. let rhs = self.eval(rhs)?;
  232. if lhs.is_u32() && rhs.is_u32() {
  233. return Ok(SExprVal::Bool(lhs.as_u32().unwrap() == rhs.as_u32().unwrap()))
  234. }
  235. let lhs = lhs.coerce_f32()?;
  236. let rhs = rhs.coerce_f32()?;
  237. let is_equal = (lhs - rhs).abs() < f32::EPSILON;
  238. Ok(SExprVal::Bool(is_equal))
  239. }
  240. fn less_than(&self, lhs: &Op, rhs: &Op) -> Result<SExprVal> {
  241. let lhs = self.eval(lhs)?;
  242. let rhs = self.eval(rhs)?;
  243. if lhs.is_u32() && rhs.is_u32() {
  244. return Ok(SExprVal::Bool(lhs.as_u32().unwrap() < rhs.as_u32().unwrap()))
  245. }
  246. let lhs = lhs.coerce_f32()?;
  247. let rhs = rhs.coerce_f32()?;
  248. Ok(SExprVal::Bool(lhs < rhs))
  249. }
  250. fn float32_to_uint32(&self, val: &Op) -> Result<SExprVal> {
  251. let val = self.eval(val)?;
  252. if val.is_u32() {
  253. return Ok(SExprVal::Uint32(val.as_u32()?))
  254. }
  255. Ok(SExprVal::Uint32(val.as_f32()? as u32))
  256. }
  257. }
  258. impl Encodable for Op {
  259. fn encode<S: Write>(&self, s: &mut S) -> std::result::Result<usize, std::io::Error> {
  260. let mut len = 0;
  261. match self {
  262. Self::Null => {
  263. len += 0u8.encode(s)?;
  264. }
  265. Self::Add((lhs, rhs)) => {
  266. len += 1u8.encode(s)?;
  267. len += lhs.encode(s)?;
  268. len += rhs.encode(s)?;
  269. }
  270. Self::Sub((lhs, rhs)) => {
  271. len += 2u8.encode(s)?;
  272. len += lhs.encode(s)?;
  273. len += rhs.encode(s)?;
  274. }
  275. Self::Mul((lhs, rhs)) => {
  276. len += 3u8.encode(s)?;
  277. len += lhs.encode(s)?;
  278. len += rhs.encode(s)?;
  279. }
  280. Self::Div((lhs, rhs)) => {
  281. len += 4u8.encode(s)?;
  282. len += lhs.encode(s)?;
  283. len += rhs.encode(s)?;
  284. }
  285. Self::ConstBool(val) => {
  286. len += 5u8.encode(s)?;
  287. len += val.encode(s)?;
  288. }
  289. Self::ConstUint32(val) => {
  290. len += 6u8.encode(s)?;
  291. len += val.encode(s)?;
  292. }
  293. Self::ConstFloat32(val) => {
  294. len += 7u8.encode(s)?;
  295. len += val.encode(s)?;
  296. }
  297. Self::ConstStr(val) => {
  298. len += 8u8.encode(s)?;
  299. len += val.encode(s)?;
  300. }
  301. Self::LoadVar(var) => {
  302. len += 9u8.encode(s)?;
  303. len += var.encode(s)?;
  304. }
  305. // StoreVar
  306. Self::Min((lhs, rhs)) => {
  307. len += 11u8.encode(s)?;
  308. len += lhs.encode(s)?;
  309. len += rhs.encode(s)?;
  310. }
  311. Self::Max((lhs, rhs)) => {
  312. len += 12u8.encode(s)?;
  313. len += lhs.encode(s)?;
  314. len += rhs.encode(s)?;
  315. }
  316. Self::IsEqual((lhs, rhs)) => {
  317. len += 13u8.encode(s)?;
  318. len += lhs.encode(s)?;
  319. len += rhs.encode(s)?;
  320. }
  321. Self::LessThan((lhs, rhs)) => {
  322. len += 14u8.encode(s)?;
  323. len += lhs.encode(s)?;
  324. len += rhs.encode(s)?;
  325. }
  326. Self::Float32ToUint32(val) => {
  327. len += 15u8.encode(s)?;
  328. len += val.encode(s)?;
  329. }
  330. }
  331. Ok(len)
  332. }
  333. }
  334. impl Decodable for Op {
  335. fn decode<D: Read>(d: &mut D) -> std::result::Result<Self, std::io::Error> {
  336. let op_type = d.read_u8()?;
  337. let self_ = match op_type {
  338. 0 => Self::Null,
  339. 1 => Self::Add((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  340. 2 => Self::Sub((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  341. 3 => Self::Mul((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  342. 4 => Self::Div((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  343. 5 => Self::ConstBool(d.read_bool()?),
  344. 6 => Self::ConstUint32(d.read_u32()?),
  345. 7 => Self::ConstFloat32(d.read_f32()?),
  346. 8 => Self::ConstStr(String::decode(d)?),
  347. 9 => Self::LoadVar(String::decode(d)?),
  348. // StoreVar
  349. 11 => Self::Min((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  350. 12 => Self::Max((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  351. 13 => Self::IsEqual((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  352. 14 => Self::LessThan((Box::new(Self::decode(d)?), Box::new(Self::decode(d)?))),
  353. 15 => Self::Float32ToUint32(Box::new(Self::decode(d)?)),
  354. _ => return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid Op type")),
  355. };
  356. Ok(self_)
  357. }
  358. }
  359. #[cfg(test)]
  360. mod tests {
  361. use super::*;
  362. use darkfi_serial::{deserialize, serialize};
  363. #[test]
  364. fn seval() {
  365. let machine = SExprMachine {
  366. globals: vec![
  367. ("sw".to_string(), SExprVal::Uint32(110u32)),
  368. ("sh".to_string(), SExprVal::Uint32(4u32)),
  369. ],
  370. stmts: &vec![Op::Add((
  371. Box::new(Op::ConstUint32(5)),
  372. Box::new(Op::Div((
  373. Box::new(Op::LoadVar("sw".to_string())),
  374. Box::new(Op::ConstUint32(2)),
  375. ))),
  376. ))],
  377. };
  378. assert_eq!(machine.call().unwrap(), SExprVal::Float32(60.));
  379. }
  380. #[test]
  381. fn encdec_code() {
  382. let code = Op::Add((
  383. Box::new(Op::ConstUint32(5)),
  384. Box::new(Op::Div((
  385. Box::new(Op::LoadVar("sw".to_string())),
  386. Box::new(Op::ConstUint32(2)),
  387. ))),
  388. ));
  389. let code_s = serialize(&code);
  390. let code2 = deserialize::<Op>(&code_s).unwrap();
  391. assert_eq!(code, code2);
  392. }
  393. }