expr.rs 13 KB

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