expression.rs 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378
  1. use super::storage::{
  2. array_offset, array_pop, array_push, storage_slots_array_pop, storage_slots_array_push,
  3. };
  4. use super::Options;
  5. use super::{
  6. cfg::{ControlFlowGraph, Instr, InternalCallTy},
  7. vartable::Vartable,
  8. };
  9. use crate::codegen::unused_variable::should_remove_assignment;
  10. use crate::parser::pt;
  11. use crate::sema::ast::{
  12. Builtin, CallTy, Expression, FormatArg, Function, Namespace, Parameter, StringLocation, Type,
  13. };
  14. use crate::sema::eval::{eval_const_number, eval_const_rational};
  15. use crate::sema::expression::{bigint_to_expression, cast, cast_shift_arg, ResolveTo};
  16. use crate::Target;
  17. use num_bigint::BigInt;
  18. use num_traits::{FromPrimitive, One, ToPrimitive, Zero};
  19. use std::ops::Mul;
  20. pub fn expression(
  21. expr: &Expression,
  22. cfg: &mut ControlFlowGraph,
  23. contract_no: usize,
  24. func: Option<&Function>,
  25. ns: &Namespace,
  26. vartab: &mut Vartable,
  27. opt: &Options,
  28. ) -> Expression {
  29. match expr {
  30. Expression::StorageVariable(_, _, var_contract_no, var_no) => {
  31. // base storage variables should precede contract variables, not overlap
  32. ns.contracts[contract_no].get_storage_slot(*var_contract_no, *var_no, ns)
  33. }
  34. Expression::StorageLoad(loc, ty, expr) => {
  35. let storage = expression(expr, cfg, contract_no, func, ns, vartab, opt);
  36. load_storage(loc, ty, storage, cfg, vartab, opt)
  37. }
  38. Expression::Add(loc, ty, unchecked, left, right) => add(
  39. loc,
  40. ty,
  41. unchecked,
  42. left,
  43. cfg,
  44. contract_no,
  45. func,
  46. ns,
  47. vartab,
  48. right,
  49. opt,
  50. ),
  51. Expression::Subtract(loc, ty, unchecked, left, right) => substract(
  52. loc,
  53. ty,
  54. unchecked,
  55. left,
  56. cfg,
  57. contract_no,
  58. func,
  59. ns,
  60. vartab,
  61. right,
  62. opt,
  63. ),
  64. Expression::Multiply(loc, ty, unchecked, left, right) => {
  65. if ty.is_rational() {
  66. let (_, r) = eval_const_rational(expr, Some(contract_no), ns).unwrap();
  67. Expression::NumberLiteral(*loc, ty.clone(), r.to_integer())
  68. } else {
  69. Expression::Multiply(
  70. *loc,
  71. ty.clone(),
  72. *unchecked,
  73. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  74. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  75. )
  76. }
  77. }
  78. Expression::Divide(loc, ty, left, right) => Expression::Divide(
  79. *loc,
  80. ty.clone(),
  81. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  82. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  83. ),
  84. Expression::Modulo(loc, ty, left, right) => Expression::Modulo(
  85. *loc,
  86. ty.clone(),
  87. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  88. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  89. ),
  90. Expression::Power(loc, ty, unchecked, left, right) => Expression::Power(
  91. *loc,
  92. ty.clone(),
  93. *unchecked,
  94. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  95. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  96. ),
  97. Expression::BitwiseOr(loc, ty, left, right) => Expression::BitwiseOr(
  98. *loc,
  99. ty.clone(),
  100. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  101. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  102. ),
  103. Expression::BitwiseAnd(loc, ty, left, right) => Expression::BitwiseAnd(
  104. *loc,
  105. ty.clone(),
  106. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  107. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  108. ),
  109. Expression::BitwiseXor(loc, ty, left, right) => Expression::BitwiseXor(
  110. *loc,
  111. ty.clone(),
  112. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  113. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  114. ),
  115. Expression::ShiftLeft(loc, ty, left, right) => Expression::ShiftLeft(
  116. *loc,
  117. ty.clone(),
  118. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  119. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  120. ),
  121. Expression::ShiftRight(loc, ty, left, right, sign) => Expression::ShiftRight(
  122. *loc,
  123. ty.clone(),
  124. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  125. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  126. *sign,
  127. ),
  128. Expression::Equal(loc, left, right) => Expression::Equal(
  129. *loc,
  130. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  131. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  132. ),
  133. Expression::NotEqual(loc, left, right) => Expression::NotEqual(
  134. *loc,
  135. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  136. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  137. ),
  138. Expression::More(loc, left, right) => Expression::More(
  139. *loc,
  140. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  141. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  142. ),
  143. Expression::MoreEqual(loc, left, right) => Expression::MoreEqual(
  144. *loc,
  145. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  146. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  147. ),
  148. Expression::Less(loc, left, right) => Expression::Less(
  149. *loc,
  150. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  151. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  152. ),
  153. Expression::LessEqual(loc, left, right) => Expression::LessEqual(
  154. *loc,
  155. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  156. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  157. ),
  158. Expression::ConstantVariable(_, _, Some(var_contract_no), var_no) => expression(
  159. ns.contracts[*var_contract_no].variables[*var_no]
  160. .initializer
  161. .as_ref()
  162. .unwrap(),
  163. cfg,
  164. contract_no,
  165. func,
  166. ns,
  167. vartab,
  168. opt,
  169. ),
  170. Expression::ConstantVariable(_, _, None, var_no) => expression(
  171. ns.constants[*var_no].initializer.as_ref().unwrap(),
  172. cfg,
  173. contract_no,
  174. func,
  175. ns,
  176. vartab,
  177. opt,
  178. ),
  179. Expression::Not(loc, expr) => Expression::Not(
  180. *loc,
  181. Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  182. ),
  183. Expression::Complement(loc, ty, expr) => Expression::Complement(
  184. *loc,
  185. ty.clone(),
  186. Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  187. ),
  188. Expression::UnaryMinus(loc, ty, expr) => Expression::UnaryMinus(
  189. *loc,
  190. ty.clone(),
  191. Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  192. ),
  193. Expression::StructLiteral(loc, ty, exprs) => Expression::StructLiteral(
  194. *loc,
  195. ty.clone(),
  196. exprs
  197. .iter()
  198. .map(|e| expression(e, cfg, contract_no, func, ns, vartab, opt))
  199. .collect(),
  200. ),
  201. Expression::ArrayLiteral(loc, ty, lengths, args) => Expression::ArrayLiteral(
  202. *loc,
  203. ty.clone(),
  204. lengths.clone(),
  205. args.iter()
  206. .map(|e| expression(e, cfg, contract_no, func, ns, vartab, opt))
  207. .collect(),
  208. ),
  209. Expression::ConstArrayLiteral(loc, ty, lengths, args) => Expression::ConstArrayLiteral(
  210. *loc,
  211. ty.clone(),
  212. lengths.clone(),
  213. args.iter()
  214. .map(|e| expression(e, cfg, contract_no, func, ns, vartab, opt))
  215. .collect(),
  216. ),
  217. Expression::Assign(_, _, left, right) => {
  218. // If we reach this condition, the assignment is inside an expression.
  219. if let Some(function) = func {
  220. if should_remove_assignment(ns, left, function, opt) {
  221. return expression(right, cfg, contract_no, func, ns, vartab, opt);
  222. }
  223. }
  224. assign_single(left, right, cfg, contract_no, func, ns, vartab, opt)
  225. }
  226. Expression::PreDecrement(loc, ty, unchecked, var)
  227. | Expression::PreIncrement(loc, ty, unchecked, var) => pre_incdec(
  228. vartab,
  229. ty,
  230. var,
  231. cfg,
  232. contract_no,
  233. func,
  234. ns,
  235. loc,
  236. expr,
  237. unchecked,
  238. opt,
  239. ),
  240. Expression::PostDecrement(loc, ty, unchecked, var)
  241. | Expression::PostIncrement(loc, ty, unchecked, var) => post_incdec(
  242. vartab,
  243. ty,
  244. var,
  245. cfg,
  246. contract_no,
  247. func,
  248. ns,
  249. loc,
  250. expr,
  251. unchecked,
  252. opt,
  253. ),
  254. Expression::Constructor {
  255. loc,
  256. contract_no,
  257. constructor_no,
  258. args,
  259. value,
  260. gas,
  261. salt,
  262. space,
  263. } => {
  264. let address_res = vartab.temp_anonymous(&Type::Contract(*contract_no));
  265. let args = args
  266. .iter()
  267. .map(|v| expression(v, cfg, *contract_no, func, ns, vartab, opt))
  268. .collect();
  269. let gas = if let Some(gas) = gas {
  270. expression(gas, cfg, *contract_no, func, ns, vartab, opt)
  271. } else {
  272. default_gas(ns)
  273. };
  274. let value = value
  275. .as_ref()
  276. .map(|value| expression(value, cfg, *contract_no, func, ns, vartab, opt));
  277. let salt = salt
  278. .as_ref()
  279. .map(|salt| expression(salt, cfg, *contract_no, func, ns, vartab, opt));
  280. let space = space
  281. .as_ref()
  282. .map(|space| expression(space, cfg, *contract_no, func, ns, vartab, opt));
  283. cfg.add(
  284. vartab,
  285. Instr::Constructor {
  286. success: None,
  287. res: address_res,
  288. contract_no: *contract_no,
  289. constructor_no: *constructor_no,
  290. args,
  291. value,
  292. gas,
  293. salt,
  294. space,
  295. },
  296. );
  297. Expression::Variable(*loc, Type::Contract(*contract_no), address_res)
  298. }
  299. Expression::InternalFunction {
  300. function_no,
  301. signature,
  302. ..
  303. } => {
  304. let function_no = if let Some(signature) = signature {
  305. &ns.contracts[contract_no].virtual_functions[signature]
  306. } else {
  307. function_no
  308. };
  309. Expression::InternalFunctionCfg(ns.contracts[contract_no].all_functions[function_no])
  310. }
  311. Expression::StorageArrayLength {
  312. loc,
  313. ty,
  314. array,
  315. elem_ty,
  316. } => {
  317. let array_ty = array.ty().deref_into();
  318. let array = expression(array, cfg, contract_no, func, ns, vartab, opt);
  319. match array_ty {
  320. Type::Bytes(length) => bigint_to_expression(
  321. loc,
  322. &BigInt::from_u8(length).unwrap(),
  323. ns,
  324. &mut Vec::new(),
  325. ResolveTo::Type(ty),
  326. )
  327. .unwrap(),
  328. Type::DynamicBytes => Expression::StorageArrayLength {
  329. loc: *loc,
  330. ty: ty.clone(),
  331. array: Box::new(array),
  332. elem_ty: elem_ty.clone(),
  333. },
  334. Type::Array(_, dim) => match dim.last().unwrap() {
  335. None => {
  336. if ns.target == Target::Solana {
  337. Expression::StorageArrayLength {
  338. loc: *loc,
  339. ty: ty.clone(),
  340. array: Box::new(array),
  341. elem_ty: elem_ty.clone(),
  342. }
  343. } else {
  344. load_storage(loc, &ns.storage_type(), array, cfg, vartab, opt)
  345. }
  346. }
  347. Some(length) => {
  348. bigint_to_expression(loc, length, ns, &mut Vec::new(), ResolveTo::Type(ty))
  349. .unwrap()
  350. }
  351. },
  352. _ => unreachable!(),
  353. }
  354. }
  355. Expression::Builtin(loc, returns, Builtin::ExternalFunctionAddress, func_expr) => {
  356. if let Expression::ExternalFunction { address, .. } = &func_expr[0] {
  357. expression(address, cfg, contract_no, func, ns, vartab, opt)
  358. } else {
  359. let func_expr = expression(&func_expr[0], cfg, contract_no, func, ns, vartab, opt);
  360. Expression::Builtin(
  361. *loc,
  362. returns.clone(),
  363. Builtin::ExternalFunctionAddress,
  364. vec![func_expr],
  365. )
  366. }
  367. }
  368. Expression::Builtin(loc, returns, Builtin::FunctionSelector, func_expr) => match &func_expr
  369. [0]
  370. {
  371. Expression::ExternalFunction { function_no, .. }
  372. | Expression::InternalFunction { function_no, .. } => {
  373. let selector = ns.functions[*function_no].selector();
  374. Expression::NumberLiteral(*loc, Type::Bytes(4), BigInt::from(selector))
  375. }
  376. _ => {
  377. let func_expr = expression(&func_expr[0], cfg, contract_no, func, ns, vartab, opt);
  378. Expression::Builtin(
  379. *loc,
  380. returns.clone(),
  381. Builtin::FunctionSelector,
  382. vec![func_expr],
  383. )
  384. }
  385. },
  386. Expression::InternalFunctionCall { .. }
  387. | Expression::ExternalFunctionCall { .. }
  388. | Expression::Builtin(_, _, Builtin::AbiDecode, _) => {
  389. let mut returns = emit_function_call(expr, contract_no, cfg, func, ns, vartab, opt);
  390. assert_eq!(returns.len(), 1);
  391. returns.remove(0)
  392. }
  393. Expression::ExternalFunction {
  394. loc,
  395. ty,
  396. address,
  397. function_no,
  398. } => {
  399. let address = expression(address, cfg, contract_no, func, ns, vartab, opt);
  400. Expression::ExternalFunction {
  401. loc: *loc,
  402. ty: ty.clone(),
  403. address: Box::new(address),
  404. function_no: *function_no,
  405. }
  406. }
  407. Expression::Subscript(loc, ty, array, index) => array_subscript(
  408. loc,
  409. ty,
  410. array,
  411. index,
  412. cfg,
  413. contract_no,
  414. func,
  415. ns,
  416. vartab,
  417. opt,
  418. ),
  419. Expression::StructMember(loc, ty, var, field_no) if ty.is_contract_storage() => {
  420. if let Type::Struct(struct_no) = var.ty().deref_any() {
  421. let offset = if ns.target == Target::Solana {
  422. ns.structs[*struct_no].storage_offsets[*field_no].clone()
  423. } else {
  424. ns.structs[*struct_no].fields[..*field_no]
  425. .iter()
  426. .map(|field| field.ty.storage_slots(ns))
  427. .sum()
  428. };
  429. Expression::Add(
  430. *loc,
  431. ty.clone(),
  432. true,
  433. Box::new(expression(var, cfg, contract_no, func, ns, vartab, opt)),
  434. Box::new(Expression::NumberLiteral(*loc, ns.storage_type(), offset)),
  435. )
  436. } else {
  437. unreachable!();
  438. }
  439. }
  440. Expression::StructMember(loc, ty, var, member) => Expression::StructMember(
  441. *loc,
  442. ty.clone(),
  443. Box::new(expression(var, cfg, contract_no, func, ns, vartab, opt)),
  444. *member,
  445. ),
  446. Expression::StorageBytesSubscript(loc, var, index) => Expression::StorageBytesSubscript(
  447. *loc,
  448. Box::new(expression(var, cfg, contract_no, func, ns, vartab, opt)),
  449. Box::new(expression(index, cfg, contract_no, func, ns, vartab, opt)),
  450. ),
  451. Expression::StringCompare(loc, left, right) => Expression::StringCompare(
  452. *loc,
  453. string_location(left, cfg, contract_no, func, ns, vartab, opt),
  454. string_location(right, cfg, contract_no, func, ns, vartab, opt),
  455. ),
  456. Expression::StringConcat(loc, ty, left, right) => Expression::StringConcat(
  457. *loc,
  458. ty.clone(),
  459. string_location(left, cfg, contract_no, func, ns, vartab, opt),
  460. string_location(right, cfg, contract_no, func, ns, vartab, opt),
  461. ),
  462. Expression::Or(loc, left, right) => {
  463. expr_or(left, cfg, contract_no, func, ns, vartab, loc, right, opt)
  464. }
  465. Expression::And(loc, left, right) => {
  466. and(left, cfg, contract_no, func, ns, vartab, loc, right, opt)
  467. }
  468. Expression::Trunc(loc, ty, e) => Expression::Trunc(
  469. *loc,
  470. ty.clone(),
  471. Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  472. ),
  473. Expression::ZeroExt(loc, ty, e) => Expression::ZeroExt(
  474. *loc,
  475. ty.clone(),
  476. Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  477. ),
  478. Expression::SignExt(loc, ty, e) => Expression::SignExt(
  479. *loc,
  480. ty.clone(),
  481. Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  482. ),
  483. Expression::Cast(loc, ty @ Type::Address(_), e) => {
  484. if let Ok((_, address)) = eval_const_number(e, Some(contract_no), ns) {
  485. Expression::NumberLiteral(*loc, ty.clone(), address)
  486. } else {
  487. Expression::Cast(
  488. *loc,
  489. ty.clone(),
  490. Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  491. )
  492. }
  493. }
  494. Expression::Cast(loc, ty, e) => {
  495. if matches!(ty, Type::String | Type::DynamicBytes)
  496. && matches!(expr.ty(), Type::String | Type::DynamicBytes)
  497. {
  498. expression(e, cfg, contract_no, func, ns, vartab, opt)
  499. } else {
  500. Expression::Cast(
  501. *loc,
  502. ty.clone(),
  503. Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  504. )
  505. }
  506. }
  507. Expression::BytesCast(loc, ty, from, e) => Expression::BytesCast(
  508. *loc,
  509. ty.clone(),
  510. from.clone(),
  511. Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  512. ),
  513. Expression::Load(loc, ty, e) => Expression::Load(
  514. *loc,
  515. ty.clone(),
  516. Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  517. ),
  518. // for some built-ins, we have to inline special case code
  519. Expression::Builtin(loc, ty, Builtin::ArrayPush, args) => {
  520. if args[0].ty().is_contract_storage() {
  521. if ns.target == Target::Solana || args[0].ty().is_storage_bytes() {
  522. array_push(loc, args, cfg, contract_no, func, ns, vartab, opt)
  523. } else {
  524. storage_slots_array_push(loc, args, cfg, contract_no, func, ns, vartab, opt)
  525. }
  526. } else {
  527. memory_array_push(
  528. &ty[0],
  529. vartab,
  530. &args[0],
  531. cfg,
  532. contract_no,
  533. func,
  534. ns,
  535. &args[1],
  536. loc,
  537. opt,
  538. )
  539. }
  540. }
  541. Expression::Builtin(loc, ty, Builtin::ArrayPop, args) => {
  542. if args[0].ty().is_contract_storage() {
  543. if ns.target == Target::Solana || args[0].ty().is_storage_bytes() {
  544. array_pop(loc, args, &ty[0], cfg, contract_no, func, ns, vartab, opt)
  545. } else {
  546. storage_slots_array_pop(
  547. loc,
  548. args,
  549. &ty[0],
  550. cfg,
  551. contract_no,
  552. func,
  553. ns,
  554. vartab,
  555. opt,
  556. )
  557. }
  558. } else {
  559. let address_res = vartab.temp_anonymous(&ty[0]);
  560. let address_arr =
  561. match expression(&args[0], cfg, contract_no, func, ns, vartab, opt) {
  562. Expression::Variable(_, _, pos) => pos,
  563. _ => unreachable!(),
  564. };
  565. cfg.add(
  566. vartab,
  567. Instr::PopMemory {
  568. res: address_res,
  569. ty: args[0].ty(),
  570. array: address_arr,
  571. },
  572. );
  573. Expression::Variable(*loc, ty[0].clone(), address_res)
  574. }
  575. }
  576. Expression::Builtin(_, _, Builtin::Assert, args) => {
  577. expr_assert(cfg, &args[0], contract_no, func, ns, vartab, opt)
  578. }
  579. Expression::Builtin(_, _, Builtin::Print, args) => {
  580. let expr = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  581. cfg.add(vartab, Instr::Print { expr });
  582. Expression::Poison
  583. }
  584. Expression::Builtin(_, _, Builtin::Require, args) => {
  585. require(cfg, args, contract_no, func, ns, vartab, opt)
  586. }
  587. Expression::Builtin(_, _, Builtin::Revert, args) => {
  588. revert(args, cfg, contract_no, func, ns, vartab, opt)
  589. }
  590. Expression::Builtin(_, _, Builtin::SelfDestruct, args) => {
  591. self_destruct(args, cfg, contract_no, func, ns, vartab, opt)
  592. }
  593. Expression::Builtin(loc, _, Builtin::PayableSend, args) => {
  594. payable_send(args, cfg, contract_no, func, ns, vartab, loc, opt)
  595. }
  596. Expression::Builtin(loc, _, Builtin::PayableTransfer, args) => {
  597. payable_transfer(args, cfg, contract_no, func, ns, vartab, loc, opt)
  598. }
  599. Expression::Builtin(loc, _, Builtin::AbiEncode, args) => {
  600. abi_encode(args, cfg, contract_no, func, ns, vartab, loc, opt)
  601. }
  602. Expression::Builtin(loc, _, Builtin::AbiEncodePacked, args) => {
  603. abi_encode_packed(args, cfg, contract_no, func, ns, vartab, loc, opt)
  604. }
  605. Expression::Builtin(loc, _, Builtin::AbiEncodeWithSelector, args) => {
  606. abi_encode_with_selector(args, cfg, contract_no, func, ns, vartab, loc, opt)
  607. }
  608. Expression::Builtin(loc, _, Builtin::AbiEncodeWithSignature, args) => {
  609. abi_encode_with_signature(args, loc, cfg, contract_no, func, ns, vartab, opt)
  610. }
  611. // The Substrate gas price builtin takes an argument; the others do not
  612. Expression::Builtin(loc, _, Builtin::Gasprice, expr)
  613. if expr.len() == 1 && ns.target == Target::Ewasm =>
  614. {
  615. builtin_ewasm_gasprice(loc, expr, cfg, contract_no, func, ns, vartab, opt)
  616. }
  617. Expression::Builtin(loc, tys, builtin, args) => expr_builtin(
  618. args,
  619. cfg,
  620. contract_no,
  621. func,
  622. ns,
  623. vartab,
  624. loc,
  625. tys,
  626. builtin,
  627. opt,
  628. ),
  629. Expression::FormatString(loc, args) => {
  630. format_string(args, cfg, contract_no, func, ns, vartab, loc, opt)
  631. }
  632. Expression::AllocDynamicArray(loc, ty, size, init) => {
  633. alloc_dynamic_array(size, cfg, contract_no, func, ns, vartab, loc, ty, init, opt)
  634. }
  635. Expression::Ternary(loc, ty, cond, left, right) => ternary(
  636. loc,
  637. ty,
  638. cond,
  639. cfg,
  640. contract_no,
  641. func,
  642. ns,
  643. vartab,
  644. left,
  645. right,
  646. opt,
  647. ),
  648. Expression::InterfaceId(loc, contract_no) => interfaceid(ns, contract_no, loc),
  649. _ => expr.clone(),
  650. }
  651. }
  652. fn memory_array_push(
  653. ty: &Type,
  654. vartab: &mut Vartable,
  655. array: &Expression,
  656. cfg: &mut ControlFlowGraph,
  657. contract_no: usize,
  658. func: Option<&Function>,
  659. ns: &Namespace,
  660. value: &Expression,
  661. loc: &pt::Loc,
  662. opt: &Options,
  663. ) -> Expression {
  664. let address_res = vartab.temp_anonymous(ty);
  665. let address_arr = match expression(array, cfg, contract_no, func, ns, vartab, opt) {
  666. Expression::Variable(_, _, pos) => pos,
  667. _ => unreachable!(),
  668. };
  669. let value = expression(value, cfg, contract_no, func, ns, vartab, opt);
  670. cfg.add(
  671. vartab,
  672. Instr::PushMemory {
  673. res: address_res,
  674. ty: array.ty(),
  675. array: address_arr,
  676. value: Box::new(value),
  677. },
  678. );
  679. Expression::Variable(*loc, ty.clone(), address_res)
  680. }
  681. fn post_incdec(
  682. vartab: &mut Vartable,
  683. ty: &Type,
  684. var: &Expression,
  685. cfg: &mut ControlFlowGraph,
  686. contract_no: usize,
  687. func: Option<&Function>,
  688. ns: &Namespace,
  689. loc: &pt::Loc,
  690. expr: &Expression,
  691. unchecked: &bool,
  692. opt: &Options,
  693. ) -> Expression {
  694. let res = vartab.temp_anonymous(ty);
  695. let v = expression(var, cfg, contract_no, func, ns, vartab, opt);
  696. let v = match var.ty() {
  697. Type::Ref(ty) => Expression::Load(var.loc(), ty.as_ref().clone(), Box::new(v)),
  698. Type::StorageRef(_, ty) => load_storage(&var.loc(), ty.as_ref(), v, cfg, vartab, opt),
  699. _ => v,
  700. };
  701. cfg.add(
  702. vartab,
  703. Instr::Set {
  704. loc: pt::Loc(0, 0, 0),
  705. res,
  706. expr: v,
  707. },
  708. );
  709. let one = Box::new(Expression::NumberLiteral(*loc, ty.clone(), BigInt::one()));
  710. let expr = match expr {
  711. Expression::PostDecrement(..) => Expression::Subtract(
  712. *loc,
  713. ty.clone(),
  714. *unchecked,
  715. Box::new(Expression::Variable(*loc, ty.clone(), res)),
  716. one,
  717. ),
  718. Expression::PostIncrement(..) => Expression::Add(
  719. *loc,
  720. ty.clone(),
  721. *unchecked,
  722. Box::new(Expression::Variable(*loc, ty.clone(), res)),
  723. one,
  724. ),
  725. _ => unreachable!(),
  726. };
  727. match var {
  728. Expression::Variable(loc, _, pos) => {
  729. cfg.add(
  730. vartab,
  731. Instr::Set {
  732. loc: *loc,
  733. res: *pos,
  734. expr,
  735. },
  736. );
  737. }
  738. _ => {
  739. let dest = expression(var, cfg, contract_no, func, ns, vartab, opt);
  740. let res = vartab.temp_anonymous(ty);
  741. cfg.add(
  742. vartab,
  743. Instr::Set {
  744. loc: pt::Loc(0, 0, 0),
  745. res,
  746. expr,
  747. },
  748. );
  749. match var.ty() {
  750. Type::StorageRef(_, _) => {
  751. cfg.add(
  752. vartab,
  753. Instr::SetStorage {
  754. value: Expression::Variable(*loc, ty.clone(), res),
  755. ty: ty.clone(),
  756. storage: dest,
  757. },
  758. );
  759. }
  760. Type::Ref(_) => {
  761. cfg.add(vartab, Instr::Store { pos: res, dest });
  762. }
  763. _ => unreachable!(),
  764. }
  765. }
  766. }
  767. Expression::Variable(*loc, ty.clone(), res)
  768. }
  769. fn pre_incdec(
  770. vartab: &mut Vartable,
  771. ty: &Type,
  772. var: &Expression,
  773. cfg: &mut ControlFlowGraph,
  774. contract_no: usize,
  775. func: Option<&Function>,
  776. ns: &Namespace,
  777. loc: &pt::Loc,
  778. expr: &Expression,
  779. unchecked: &bool,
  780. opt: &Options,
  781. ) -> Expression {
  782. let res = vartab.temp_anonymous(ty);
  783. let v = expression(var, cfg, contract_no, func, ns, vartab, opt);
  784. let v = match var.ty() {
  785. Type::Ref(ty) => Expression::Load(var.loc(), ty.as_ref().clone(), Box::new(v)),
  786. Type::StorageRef(_, ty) => load_storage(&var.loc(), ty.as_ref(), v, cfg, vartab, opt),
  787. _ => v,
  788. };
  789. let one = Box::new(Expression::NumberLiteral(*loc, ty.clone(), BigInt::one()));
  790. let expr = match expr {
  791. Expression::PreDecrement(..) => {
  792. Expression::Subtract(*loc, ty.clone(), *unchecked, Box::new(v), one)
  793. }
  794. Expression::PreIncrement(..) => {
  795. Expression::Add(*loc, ty.clone(), *unchecked, Box::new(v), one)
  796. }
  797. _ => unreachable!(),
  798. };
  799. cfg.add(
  800. vartab,
  801. Instr::Set {
  802. loc: pt::Loc(0, 0, 0),
  803. res,
  804. expr,
  805. },
  806. );
  807. match var {
  808. Expression::Variable(loc, _, pos) => {
  809. cfg.add(
  810. vartab,
  811. Instr::Set {
  812. loc: *loc,
  813. res: *pos,
  814. expr: Expression::Variable(*loc, ty.clone(), res),
  815. },
  816. );
  817. }
  818. _ => {
  819. let dest = expression(var, cfg, contract_no, func, ns, vartab, opt);
  820. match var.ty() {
  821. Type::StorageRef(_, _) => {
  822. cfg.add(
  823. vartab,
  824. Instr::SetStorage {
  825. value: Expression::Variable(*loc, ty.clone(), res),
  826. ty: ty.clone(),
  827. storage: dest,
  828. },
  829. );
  830. }
  831. Type::Ref(_) => {
  832. cfg.add(vartab, Instr::Store { pos: res, dest });
  833. }
  834. _ => unreachable!(),
  835. }
  836. }
  837. }
  838. Expression::Variable(*loc, ty.clone(), res)
  839. }
  840. fn expr_or(
  841. left: &Expression,
  842. cfg: &mut ControlFlowGraph,
  843. contract_no: usize,
  844. func: Option<&Function>,
  845. ns: &Namespace,
  846. vartab: &mut Vartable,
  847. loc: &pt::Loc,
  848. right: &Expression,
  849. opt: &Options,
  850. ) -> Expression {
  851. let boolty = Type::Bool;
  852. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  853. vartab.new_dirty_tracker(ns.next_id);
  854. let pos = vartab.temp(
  855. &pt::Identifier {
  856. name: "or".to_owned(),
  857. loc: *loc,
  858. },
  859. &Type::Bool,
  860. );
  861. let right_side = cfg.new_basic_block("or_right_side".to_string());
  862. let end_or = cfg.new_basic_block("or_end".to_string());
  863. cfg.add(
  864. vartab,
  865. Instr::Set {
  866. loc: pt::Loc(0, 0, 0),
  867. res: pos,
  868. expr: Expression::BoolLiteral(*loc, true),
  869. },
  870. );
  871. cfg.add(
  872. vartab,
  873. Instr::BranchCond {
  874. cond: l,
  875. true_block: end_or,
  876. false_block: right_side,
  877. },
  878. );
  879. cfg.set_basic_block(right_side);
  880. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  881. cfg.add(
  882. vartab,
  883. Instr::Set {
  884. loc: pt::Loc(0, 0, 0),
  885. res: pos,
  886. expr: r,
  887. },
  888. );
  889. let mut phis = vartab.pop_dirty_tracker();
  890. phis.insert(pos);
  891. cfg.set_phis(end_or, phis);
  892. cfg.add(vartab, Instr::Branch { block: end_or });
  893. cfg.set_basic_block(end_or);
  894. Expression::Variable(*loc, boolty, pos)
  895. }
  896. fn and(
  897. left: &Expression,
  898. cfg: &mut ControlFlowGraph,
  899. contract_no: usize,
  900. func: Option<&Function>,
  901. ns: &Namespace,
  902. vartab: &mut Vartable,
  903. loc: &pt::Loc,
  904. right: &Expression,
  905. opt: &Options,
  906. ) -> Expression {
  907. let boolty = Type::Bool;
  908. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  909. vartab.new_dirty_tracker(ns.next_id);
  910. let pos = vartab.temp(
  911. &pt::Identifier {
  912. name: "and".to_owned(),
  913. loc: *loc,
  914. },
  915. &Type::Bool,
  916. );
  917. let right_side = cfg.new_basic_block("and_right_side".to_string());
  918. let end_and = cfg.new_basic_block("and_end".to_string());
  919. cfg.add(
  920. vartab,
  921. Instr::Set {
  922. loc: pt::Loc(0, 0, 0),
  923. res: pos,
  924. expr: Expression::BoolLiteral(*loc, false),
  925. },
  926. );
  927. cfg.add(
  928. vartab,
  929. Instr::BranchCond {
  930. cond: l,
  931. true_block: right_side,
  932. false_block: end_and,
  933. },
  934. );
  935. cfg.set_basic_block(right_side);
  936. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  937. cfg.add(
  938. vartab,
  939. Instr::Set {
  940. loc: pt::Loc(0, 0, 0),
  941. res: pos,
  942. expr: r,
  943. },
  944. );
  945. let mut phis = vartab.pop_dirty_tracker();
  946. phis.insert(pos);
  947. cfg.set_phis(end_and, phis);
  948. cfg.add(vartab, Instr::Branch { block: end_and });
  949. cfg.set_basic_block(end_and);
  950. Expression::Variable(*loc, boolty, pos)
  951. }
  952. fn expr_assert(
  953. cfg: &mut ControlFlowGraph,
  954. args: &Expression,
  955. contract_no: usize,
  956. func: Option<&Function>,
  957. ns: &Namespace,
  958. vartab: &mut Vartable,
  959. opt: &Options,
  960. ) -> Expression {
  961. let true_ = cfg.new_basic_block("noassert".to_owned());
  962. let false_ = cfg.new_basic_block("doassert".to_owned());
  963. let cond = expression(args, cfg, contract_no, func, ns, vartab, opt);
  964. cfg.add(
  965. vartab,
  966. Instr::BranchCond {
  967. cond,
  968. true_block: true_,
  969. false_block: false_,
  970. },
  971. );
  972. cfg.set_basic_block(false_);
  973. cfg.add(vartab, Instr::AssertFailure { expr: None });
  974. cfg.set_basic_block(true_);
  975. Expression::Poison
  976. }
  977. fn require(
  978. cfg: &mut ControlFlowGraph,
  979. args: &[Expression],
  980. contract_no: usize,
  981. func: Option<&Function>,
  982. ns: &Namespace,
  983. vartab: &mut Vartable,
  984. opt: &Options,
  985. ) -> Expression {
  986. let true_ = cfg.new_basic_block("noassert".to_owned());
  987. let false_ = cfg.new_basic_block("doassert".to_owned());
  988. let cond = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  989. cfg.add(
  990. vartab,
  991. Instr::BranchCond {
  992. cond,
  993. true_block: true_,
  994. false_block: false_,
  995. },
  996. );
  997. cfg.set_basic_block(false_);
  998. let expr = args
  999. .get(1)
  1000. .map(|s| expression(s, cfg, contract_no, func, ns, vartab, opt));
  1001. if ns.target == Target::Solana {
  1002. // On Solana, print the reason, do not abi encoding it
  1003. if let Some(expr) = expr {
  1004. cfg.add(vartab, Instr::Print { expr });
  1005. }
  1006. cfg.add(vartab, Instr::AssertFailure { expr: None });
  1007. } else {
  1008. cfg.add(vartab, Instr::AssertFailure { expr });
  1009. }
  1010. cfg.set_basic_block(true_);
  1011. Expression::Poison
  1012. }
  1013. fn revert(
  1014. args: &[Expression],
  1015. cfg: &mut ControlFlowGraph,
  1016. contract_no: usize,
  1017. func: Option<&Function>,
  1018. ns: &Namespace,
  1019. vartab: &mut Vartable,
  1020. opt: &Options,
  1021. ) -> Expression {
  1022. let expr = args
  1023. .get(0)
  1024. .map(|s| expression(s, cfg, contract_no, func, ns, vartab, opt));
  1025. cfg.add(vartab, Instr::AssertFailure { expr });
  1026. Expression::Poison
  1027. }
  1028. fn self_destruct(
  1029. args: &[Expression],
  1030. cfg: &mut ControlFlowGraph,
  1031. contract_no: usize,
  1032. func: Option<&Function>,
  1033. ns: &Namespace,
  1034. vartab: &mut Vartable,
  1035. opt: &Options,
  1036. ) -> Expression {
  1037. let recipient = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1038. cfg.add(vartab, Instr::SelfDestruct { recipient });
  1039. Expression::Poison
  1040. }
  1041. fn payable_send(
  1042. args: &[Expression],
  1043. cfg: &mut ControlFlowGraph,
  1044. contract_no: usize,
  1045. func: Option<&Function>,
  1046. ns: &Namespace,
  1047. vartab: &mut Vartable,
  1048. loc: &pt::Loc,
  1049. opt: &Options,
  1050. ) -> Expression {
  1051. let address = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1052. let value = expression(&args[1], cfg, contract_no, func, ns, vartab, opt);
  1053. let success = vartab.temp(
  1054. &pt::Identifier {
  1055. loc: *loc,
  1056. name: "success".to_owned(),
  1057. },
  1058. &Type::Bool,
  1059. );
  1060. if ns.target != Target::Ewasm {
  1061. cfg.add(
  1062. vartab,
  1063. Instr::ValueTransfer {
  1064. success: Some(success),
  1065. address,
  1066. value,
  1067. },
  1068. );
  1069. } else {
  1070. // Ethereum can only transfer via external call
  1071. cfg.add(
  1072. vartab,
  1073. Instr::ExternalCall {
  1074. success: Some(success),
  1075. address: Some(address),
  1076. payload: Expression::BytesLiteral(*loc, Type::DynamicBytes, vec![]),
  1077. value,
  1078. gas: Expression::NumberLiteral(*loc, Type::Uint(64), BigInt::from(i64::MAX)),
  1079. callty: CallTy::Regular,
  1080. },
  1081. );
  1082. }
  1083. Expression::Variable(*loc, Type::Bool, success)
  1084. }
  1085. fn payable_transfer(
  1086. args: &[Expression],
  1087. cfg: &mut ControlFlowGraph,
  1088. contract_no: usize,
  1089. func: Option<&Function>,
  1090. ns: &Namespace,
  1091. vartab: &mut Vartable,
  1092. loc: &pt::Loc,
  1093. opt: &Options,
  1094. ) -> Expression {
  1095. let address = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1096. let value = expression(&args[1], cfg, contract_no, func, ns, vartab, opt);
  1097. if ns.target != Target::Ewasm {
  1098. cfg.add(
  1099. vartab,
  1100. Instr::ValueTransfer {
  1101. success: None,
  1102. address,
  1103. value,
  1104. },
  1105. );
  1106. } else {
  1107. // Ethereum can only transfer via external call
  1108. cfg.add(
  1109. vartab,
  1110. Instr::ExternalCall {
  1111. success: None,
  1112. address: Some(address),
  1113. payload: Expression::BytesLiteral(*loc, Type::DynamicBytes, vec![]),
  1114. value,
  1115. gas: Expression::NumberLiteral(*loc, Type::Uint(64), BigInt::from(i64::MAX)),
  1116. callty: CallTy::Regular,
  1117. },
  1118. );
  1119. }
  1120. Expression::Poison
  1121. }
  1122. fn abi_encode(
  1123. args: &[Expression],
  1124. cfg: &mut ControlFlowGraph,
  1125. contract_no: usize,
  1126. func: Option<&Function>,
  1127. ns: &Namespace,
  1128. vartab: &mut Vartable,
  1129. loc: &pt::Loc,
  1130. opt: &Options,
  1131. ) -> Expression {
  1132. let tys = args.iter().map(|a| a.ty()).collect();
  1133. let args = args
  1134. .iter()
  1135. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1136. .collect();
  1137. let res = vartab.temp(
  1138. &pt::Identifier {
  1139. loc: *loc,
  1140. name: "encoded".to_owned(),
  1141. },
  1142. &Type::DynamicBytes,
  1143. );
  1144. cfg.add(
  1145. vartab,
  1146. Instr::Set {
  1147. loc: *loc,
  1148. res,
  1149. expr: Expression::AbiEncode {
  1150. loc: *loc,
  1151. tys,
  1152. packed: vec![],
  1153. args,
  1154. },
  1155. },
  1156. );
  1157. Expression::Variable(*loc, Type::DynamicBytes, res)
  1158. }
  1159. fn abi_encode_packed(
  1160. args: &[Expression],
  1161. cfg: &mut ControlFlowGraph,
  1162. contract_no: usize,
  1163. func: Option<&Function>,
  1164. ns: &Namespace,
  1165. vartab: &mut Vartable,
  1166. loc: &pt::Loc,
  1167. opt: &Options,
  1168. ) -> Expression {
  1169. let tys = args.iter().map(|a| a.ty()).collect();
  1170. let packed = args
  1171. .iter()
  1172. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1173. .collect();
  1174. let res = vartab.temp(
  1175. &pt::Identifier {
  1176. loc: *loc,
  1177. name: "encoded".to_owned(),
  1178. },
  1179. &Type::DynamicBytes,
  1180. );
  1181. cfg.add(
  1182. vartab,
  1183. Instr::Set {
  1184. loc: *loc,
  1185. res,
  1186. expr: Expression::AbiEncode {
  1187. loc: *loc,
  1188. tys,
  1189. packed,
  1190. args: vec![],
  1191. },
  1192. },
  1193. );
  1194. Expression::Variable(*loc, Type::DynamicBytes, res)
  1195. }
  1196. fn abi_encode_with_selector(
  1197. args: &[Expression],
  1198. cfg: &mut ControlFlowGraph,
  1199. contract_no: usize,
  1200. func: Option<&Function>,
  1201. ns: &Namespace,
  1202. vartab: &mut Vartable,
  1203. loc: &pt::Loc,
  1204. opt: &Options,
  1205. ) -> Expression {
  1206. let mut tys: Vec<Type> = args.iter().skip(1).map(|a| a.ty()).collect();
  1207. let mut args_iter = args.iter();
  1208. let selector = expression(
  1209. args_iter.next().unwrap(),
  1210. cfg,
  1211. contract_no,
  1212. func,
  1213. ns,
  1214. vartab,
  1215. opt,
  1216. );
  1217. let args = args_iter
  1218. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1219. .collect();
  1220. let res = vartab.temp(
  1221. &pt::Identifier {
  1222. loc: *loc,
  1223. name: "encoded".to_owned(),
  1224. },
  1225. &Type::DynamicBytes,
  1226. );
  1227. tys.insert(0, Type::Bytes(4));
  1228. cfg.add(
  1229. vartab,
  1230. Instr::Set {
  1231. loc: *loc,
  1232. res,
  1233. expr: Expression::AbiEncode {
  1234. loc: *loc,
  1235. tys,
  1236. packed: vec![selector],
  1237. args,
  1238. },
  1239. },
  1240. );
  1241. Expression::Variable(*loc, Type::DynamicBytes, res)
  1242. }
  1243. fn abi_encode_with_signature(
  1244. args: &[Expression],
  1245. loc: &pt::Loc,
  1246. cfg: &mut ControlFlowGraph,
  1247. contract_no: usize,
  1248. func: Option<&Function>,
  1249. ns: &Namespace,
  1250. vartab: &mut Vartable,
  1251. opt: &Options,
  1252. ) -> Expression {
  1253. let mut tys: Vec<Type> = args.iter().skip(1).map(|a| a.ty()).collect();
  1254. let mut args_iter = args.iter();
  1255. let hash = Expression::Builtin(
  1256. *loc,
  1257. vec![Type::Bytes(32)],
  1258. Builtin::Keccak256,
  1259. vec![args_iter.next().unwrap().clone()],
  1260. );
  1261. let hash = expression(&hash, cfg, contract_no, func, ns, vartab, opt);
  1262. let selector = cast(loc, hash, &Type::Bytes(4), false, ns, &mut Vec::new()).unwrap();
  1263. let args = args_iter
  1264. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1265. .collect();
  1266. let res = vartab.temp(
  1267. &pt::Identifier {
  1268. loc: *loc,
  1269. name: "encoded".to_owned(),
  1270. },
  1271. &Type::DynamicBytes,
  1272. );
  1273. tys.insert(0, Type::Bytes(4));
  1274. cfg.add(
  1275. vartab,
  1276. Instr::Set {
  1277. loc: *loc,
  1278. res,
  1279. expr: Expression::AbiEncode {
  1280. loc: *loc,
  1281. tys,
  1282. packed: vec![selector],
  1283. args,
  1284. },
  1285. },
  1286. );
  1287. Expression::Variable(*loc, Type::DynamicBytes, res)
  1288. }
  1289. fn builtin_ewasm_gasprice(
  1290. loc: &pt::Loc,
  1291. expr: &[Expression],
  1292. cfg: &mut ControlFlowGraph,
  1293. contract_no: usize,
  1294. func: Option<&Function>,
  1295. ns: &Namespace,
  1296. vartab: &mut Vartable,
  1297. opt: &Options,
  1298. ) -> Expression {
  1299. let ty = Type::Value;
  1300. let gasprice = Expression::Builtin(*loc, vec![ty.clone()], Builtin::Gasprice, vec![]);
  1301. let units = expression(&expr[0], cfg, contract_no, func, ns, vartab, opt);
  1302. Expression::Multiply(*loc, ty, true, Box::new(units), Box::new(gasprice))
  1303. }
  1304. fn expr_builtin(
  1305. args: &[Expression],
  1306. cfg: &mut ControlFlowGraph,
  1307. contract_no: usize,
  1308. func: Option<&Function>,
  1309. ns: &Namespace,
  1310. vartab: &mut Vartable,
  1311. loc: &pt::Loc,
  1312. tys: &[Type],
  1313. builtin: &Builtin,
  1314. opt: &Options,
  1315. ) -> Expression {
  1316. let args = args
  1317. .iter()
  1318. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1319. .collect();
  1320. Expression::Builtin(*loc, tys.to_vec(), *builtin, args)
  1321. }
  1322. fn format_string(
  1323. args: &[(FormatArg, Expression)],
  1324. cfg: &mut ControlFlowGraph,
  1325. contract_no: usize,
  1326. func: Option<&Function>,
  1327. ns: &Namespace,
  1328. vartab: &mut Vartable,
  1329. loc: &pt::Loc,
  1330. opt: &Options,
  1331. ) -> Expression {
  1332. let args = args
  1333. .iter()
  1334. .map(|(spec, arg)| {
  1335. (
  1336. *spec,
  1337. expression(arg, cfg, contract_no, func, ns, vartab, opt),
  1338. )
  1339. })
  1340. .collect();
  1341. Expression::FormatString(*loc, args)
  1342. }
  1343. fn alloc_dynamic_array(
  1344. size: &Expression,
  1345. cfg: &mut ControlFlowGraph,
  1346. contract_no: usize,
  1347. func: Option<&Function>,
  1348. ns: &Namespace,
  1349. vartab: &mut Vartable,
  1350. loc: &pt::Loc,
  1351. ty: &Type,
  1352. init: &Option<Vec<u8>>,
  1353. opt: &Options,
  1354. ) -> Expression {
  1355. let size = expression(size, cfg, contract_no, func, ns, vartab, opt);
  1356. Expression::AllocDynamicArray(*loc, ty.clone(), Box::new(size), init.clone())
  1357. }
  1358. fn ternary(
  1359. loc: &pt::Loc,
  1360. ty: &Type,
  1361. cond: &Expression,
  1362. cfg: &mut ControlFlowGraph,
  1363. contract_no: usize,
  1364. func: Option<&Function>,
  1365. ns: &Namespace,
  1366. vartab: &mut Vartable,
  1367. left: &Expression,
  1368. right: &Expression,
  1369. opt: &Options,
  1370. ) -> Expression {
  1371. Expression::Ternary(
  1372. *loc,
  1373. ty.clone(),
  1374. Box::new(expression(cond, cfg, contract_no, func, ns, vartab, opt)),
  1375. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  1376. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  1377. )
  1378. }
  1379. fn interfaceid(ns: &Namespace, contract_no: &usize, loc: &pt::Loc) -> Expression {
  1380. let mut id: u32 = 0;
  1381. for func_no in &ns.contracts[*contract_no].functions {
  1382. let func = &ns.functions[*func_no];
  1383. if func.ty == pt::FunctionTy::Function {
  1384. id ^= func.selector();
  1385. }
  1386. }
  1387. Expression::NumberLiteral(*loc, Type::Bytes(4), BigInt::from(id))
  1388. }
  1389. fn add(
  1390. loc: &pt::Loc,
  1391. ty: &Type,
  1392. unchecked: &bool,
  1393. left: &Expression,
  1394. cfg: &mut ControlFlowGraph,
  1395. contract_no: usize,
  1396. func: Option<&Function>,
  1397. ns: &Namespace,
  1398. vartab: &mut Vartable,
  1399. right: &Expression,
  1400. opt: &Options,
  1401. ) -> Expression {
  1402. Expression::Add(
  1403. *loc,
  1404. ty.clone(),
  1405. *unchecked,
  1406. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  1407. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  1408. )
  1409. }
  1410. fn substract(
  1411. loc: &pt::Loc,
  1412. ty: &Type,
  1413. unchecked: &bool,
  1414. left: &Expression,
  1415. cfg: &mut ControlFlowGraph,
  1416. contract_no: usize,
  1417. func: Option<&Function>,
  1418. ns: &Namespace,
  1419. vartab: &mut Vartable,
  1420. right: &Expression,
  1421. opt: &Options,
  1422. ) -> Expression {
  1423. Expression::Subtract(
  1424. *loc,
  1425. ty.clone(),
  1426. *unchecked,
  1427. Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  1428. Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  1429. )
  1430. }
  1431. pub fn assign_single(
  1432. left: &Expression,
  1433. right: &Expression,
  1434. cfg: &mut ControlFlowGraph,
  1435. contract_no: usize,
  1436. func: Option<&Function>,
  1437. ns: &Namespace,
  1438. vartab: &mut Vartable,
  1439. opt: &Options,
  1440. ) -> Expression {
  1441. match left {
  1442. Expression::Variable(loc, _, pos) => {
  1443. let expr = expression(right, cfg, contract_no, func, ns, vartab, opt);
  1444. cfg.add(
  1445. vartab,
  1446. Instr::Set {
  1447. loc: *loc,
  1448. res: *pos,
  1449. expr,
  1450. },
  1451. );
  1452. left.clone()
  1453. }
  1454. _ => {
  1455. let left_ty = left.ty();
  1456. let ty = left_ty.deref_memory();
  1457. let pos = vartab.temp_anonymous(ty);
  1458. let dest = expression(left, cfg, contract_no, func, ns, vartab, opt);
  1459. let right = expression(right, cfg, contract_no, func, ns, vartab, opt);
  1460. cfg.add(
  1461. vartab,
  1462. Instr::Set {
  1463. loc: pt::Loc(0, 0, 0),
  1464. res: pos,
  1465. expr: right,
  1466. },
  1467. );
  1468. match left_ty {
  1469. Type::StorageRef(_, _) => {
  1470. if let Expression::StorageBytesSubscript(_, array, index) = dest {
  1471. // Set a byte in a byte array
  1472. cfg.add(
  1473. vartab,
  1474. Instr::SetStorageBytes {
  1475. value: Expression::Variable(left.loc(), ty.clone(), pos),
  1476. storage: *array,
  1477. offset: *index,
  1478. },
  1479. );
  1480. } else {
  1481. cfg.add(
  1482. vartab,
  1483. Instr::SetStorage {
  1484. value: Expression::Variable(left.loc(), ty.clone(), pos),
  1485. ty: ty.deref_any().clone(),
  1486. storage: dest,
  1487. },
  1488. );
  1489. }
  1490. }
  1491. Type::Ref(_) => {
  1492. cfg.add(vartab, Instr::Store { pos, dest });
  1493. }
  1494. _ => unreachable!(),
  1495. }
  1496. Expression::Variable(left.loc(), ty.clone(), pos)
  1497. }
  1498. }
  1499. }
  1500. /// Convert a function call expression to CFG in expression context
  1501. pub fn emit_function_call(
  1502. expr: &Expression,
  1503. callee_contract_no: usize,
  1504. cfg: &mut ControlFlowGraph,
  1505. func: Option<&Function>,
  1506. ns: &Namespace,
  1507. vartab: &mut Vartable,
  1508. opt: &Options,
  1509. ) -> Vec<Expression> {
  1510. match expr {
  1511. Expression::InternalFunctionCall { function, args, .. } => {
  1512. if let Expression::InternalFunction {
  1513. function_no,
  1514. signature,
  1515. ..
  1516. } = function.as_ref()
  1517. {
  1518. let args = args
  1519. .iter()
  1520. .map(|a| expression(a, cfg, callee_contract_no, func, ns, vartab, opt))
  1521. .collect();
  1522. let function_no = if let Some(signature) = signature {
  1523. &ns.contracts[callee_contract_no].virtual_functions[signature]
  1524. } else {
  1525. function_no
  1526. };
  1527. let cfg_no = ns.contracts[callee_contract_no].all_functions[function_no];
  1528. let ftype = &ns.functions[*function_no];
  1529. if !ftype.returns.is_empty() {
  1530. let mut res = Vec::new();
  1531. let mut returns = Vec::new();
  1532. let mut return_tys = Vec::new();
  1533. for ret in &ftype.returns {
  1534. let id = pt::Identifier {
  1535. loc: ret.loc,
  1536. name: ret.name.to_owned(),
  1537. };
  1538. let temp_pos = vartab.temp(&id, &ret.ty);
  1539. return_tys.push(ret.ty.clone());
  1540. res.push(temp_pos);
  1541. returns.push(Expression::Variable(id.loc, ret.ty.clone(), temp_pos));
  1542. }
  1543. cfg.add(
  1544. vartab,
  1545. Instr::Call {
  1546. res,
  1547. call: InternalCallTy::Static(cfg_no),
  1548. args,
  1549. return_tys,
  1550. },
  1551. );
  1552. returns
  1553. } else {
  1554. cfg.add(
  1555. vartab,
  1556. Instr::Call {
  1557. res: Vec::new(),
  1558. return_tys: Vec::new(),
  1559. call: InternalCallTy::Static(cfg_no),
  1560. args,
  1561. },
  1562. );
  1563. vec![Expression::Poison]
  1564. }
  1565. } else if let Type::InternalFunction { returns, .. } = function.ty().deref_any() {
  1566. let cfg_expr = expression(function, cfg, callee_contract_no, func, ns, vartab, opt);
  1567. let args = args
  1568. .iter()
  1569. .map(|a| expression(a, cfg, callee_contract_no, func, ns, vartab, opt))
  1570. .collect();
  1571. if !returns.is_empty() {
  1572. let mut res = Vec::new();
  1573. let mut return_values = Vec::new();
  1574. let mut return_tys = Vec::new();
  1575. for ty in returns {
  1576. let id = pt::Identifier {
  1577. loc: pt::Loc(0, 0, 0),
  1578. name: String::new(),
  1579. };
  1580. let temp_pos = vartab.temp(&id, ty);
  1581. res.push(temp_pos);
  1582. return_tys.push(ty.clone());
  1583. return_values.push(Expression::Variable(id.loc, ty.clone(), temp_pos));
  1584. }
  1585. cfg.add(
  1586. vartab,
  1587. Instr::Call {
  1588. res,
  1589. call: InternalCallTy::Dynamic(cfg_expr),
  1590. return_tys,
  1591. args,
  1592. },
  1593. );
  1594. return_values
  1595. } else {
  1596. cfg.add(
  1597. vartab,
  1598. Instr::Call {
  1599. res: Vec::new(),
  1600. return_tys: Vec::new(),
  1601. call: InternalCallTy::Dynamic(cfg_expr),
  1602. args,
  1603. },
  1604. );
  1605. vec![Expression::Poison]
  1606. }
  1607. } else {
  1608. unreachable!();
  1609. }
  1610. }
  1611. Expression::ExternalFunctionCallRaw {
  1612. loc,
  1613. address,
  1614. args,
  1615. value,
  1616. gas,
  1617. ty,
  1618. } => {
  1619. let args = expression(args, cfg, callee_contract_no, func, ns, vartab, opt);
  1620. let address = expression(address, cfg, callee_contract_no, func, ns, vartab, opt);
  1621. let gas = if let Some(gas) = gas {
  1622. expression(gas, cfg, callee_contract_no, func, ns, vartab, opt)
  1623. } else {
  1624. default_gas(ns)
  1625. };
  1626. let value = if let Some(value) = value {
  1627. expression(value, cfg, callee_contract_no, func, ns, vartab, opt)
  1628. } else {
  1629. Expression::NumberLiteral(pt::Loc(0, 0, 0), Type::Value, BigInt::zero())
  1630. };
  1631. let success = vartab.temp_name("success", &Type::Bool);
  1632. let (payload, address) = if ns.target == Target::Solana {
  1633. (
  1634. Expression::AbiEncode {
  1635. loc: *loc,
  1636. packed: vec![
  1637. address,
  1638. Expression::Builtin(
  1639. *loc,
  1640. vec![Type::Address(false)],
  1641. Builtin::GetAddress,
  1642. Vec::new(),
  1643. ),
  1644. value.clone(),
  1645. Expression::NumberLiteral(*loc, Type::Bytes(4), BigInt::zero()),
  1646. Expression::NumberLiteral(*loc, Type::Bytes(1), BigInt::zero()),
  1647. args,
  1648. ],
  1649. args: Vec::new(),
  1650. tys: vec![
  1651. Type::Address(false),
  1652. Type::Address(false),
  1653. Type::Uint(64),
  1654. Type::Bytes(4),
  1655. Type::Bytes(1),
  1656. Type::DynamicBytes,
  1657. ],
  1658. },
  1659. None,
  1660. )
  1661. } else {
  1662. (args, Some(address))
  1663. };
  1664. cfg.add(
  1665. vartab,
  1666. Instr::ExternalCall {
  1667. success: Some(success),
  1668. address,
  1669. payload,
  1670. value,
  1671. gas,
  1672. callty: ty.clone(),
  1673. },
  1674. );
  1675. vec![
  1676. Expression::Variable(*loc, Type::Bool, success),
  1677. Expression::ReturnData(*loc),
  1678. ]
  1679. }
  1680. Expression::ExternalFunctionCall {
  1681. loc,
  1682. function,
  1683. args,
  1684. value,
  1685. gas,
  1686. ..
  1687. } => {
  1688. if let Expression::ExternalFunction {
  1689. function_no,
  1690. address,
  1691. ..
  1692. } = function.as_ref()
  1693. {
  1694. let ftype = &ns.functions[*function_no];
  1695. let mut tys: Vec<Type> = args.iter().map(|a| a.ty()).collect();
  1696. let args = args
  1697. .iter()
  1698. .map(|a| expression(a, cfg, callee_contract_no, func, ns, vartab, opt))
  1699. .collect();
  1700. let address = expression(address, cfg, callee_contract_no, func, ns, vartab, opt);
  1701. let gas = if let Some(gas) = gas {
  1702. expression(gas, cfg, callee_contract_no, func, ns, vartab, opt)
  1703. } else {
  1704. default_gas(ns)
  1705. };
  1706. let value = if let Some(value) = value {
  1707. expression(value, cfg, callee_contract_no, func, ns, vartab, opt)
  1708. } else {
  1709. Expression::NumberLiteral(pt::Loc(0, 0, 0), Type::Value, BigInt::zero())
  1710. };
  1711. let dest_func = &ns.functions[*function_no];
  1712. tys.insert(0, Type::Bytes(4));
  1713. let (payload, address) = if ns.target == Target::Solana {
  1714. tys.insert(0, Type::Address(false));
  1715. tys.insert(1, Type::Address(false));
  1716. tys.insert(2, Type::Uint(64));
  1717. tys.insert(3, Type::Bytes(4));
  1718. tys.insert(4, Type::Bytes(1));
  1719. (
  1720. Expression::AbiEncode {
  1721. loc: *loc,
  1722. tys,
  1723. packed: vec![
  1724. address,
  1725. Expression::Builtin(
  1726. *loc,
  1727. vec![Type::Address(false)],
  1728. Builtin::GetAddress,
  1729. Vec::new(),
  1730. ),
  1731. value.clone(),
  1732. Expression::NumberLiteral(*loc, Type::Bytes(4), BigInt::zero()),
  1733. Expression::NumberLiteral(*loc, Type::Bytes(1), BigInt::zero()),
  1734. Expression::NumberLiteral(
  1735. *loc,
  1736. Type::Bytes(4),
  1737. BigInt::from(dest_func.selector()),
  1738. ),
  1739. ],
  1740. args,
  1741. },
  1742. None,
  1743. )
  1744. } else {
  1745. (
  1746. Expression::AbiEncode {
  1747. loc: *loc,
  1748. tys,
  1749. packed: vec![Expression::NumberLiteral(
  1750. *loc,
  1751. Type::Bytes(4),
  1752. BigInt::from(dest_func.selector()),
  1753. )],
  1754. args,
  1755. },
  1756. Some(address),
  1757. )
  1758. };
  1759. cfg.add(
  1760. vartab,
  1761. Instr::ExternalCall {
  1762. success: None,
  1763. address,
  1764. payload,
  1765. value,
  1766. gas,
  1767. callty: CallTy::Regular,
  1768. },
  1769. );
  1770. if !ftype.returns.is_empty() {
  1771. let mut returns = Vec::new();
  1772. let mut res = Vec::new();
  1773. for ret in &ftype.returns {
  1774. let id = pt::Identifier {
  1775. loc: ret.loc,
  1776. name: ret.name.to_owned(),
  1777. };
  1778. let temp_pos = vartab.temp(&id, &ret.ty);
  1779. res.push(temp_pos);
  1780. returns.push(Expression::Variable(id.loc, ret.ty.clone(), temp_pos));
  1781. }
  1782. cfg.add(
  1783. vartab,
  1784. Instr::AbiDecode {
  1785. res,
  1786. selector: None,
  1787. exception_block: None,
  1788. tys: ftype.returns.clone(),
  1789. data: Expression::ReturnData(*loc),
  1790. },
  1791. );
  1792. returns
  1793. } else {
  1794. vec![Expression::Poison]
  1795. }
  1796. } else if let Type::ExternalFunction {
  1797. returns: func_returns,
  1798. ..
  1799. } = function.ty()
  1800. {
  1801. let mut tys: Vec<Type> = args.iter().map(|a| a.ty()).collect();
  1802. let args = args
  1803. .iter()
  1804. .map(|a| expression(a, cfg, callee_contract_no, func, ns, vartab, opt))
  1805. .collect();
  1806. let function = expression(function, cfg, callee_contract_no, func, ns, vartab, opt);
  1807. let gas = if let Some(gas) = gas {
  1808. expression(gas, cfg, callee_contract_no, func, ns, vartab, opt)
  1809. } else {
  1810. default_gas(ns)
  1811. };
  1812. let value = if let Some(value) = value {
  1813. expression(value, cfg, callee_contract_no, func, ns, vartab, opt)
  1814. } else {
  1815. Expression::NumberLiteral(pt::Loc(0, 0, 0), Type::Value, BigInt::zero())
  1816. };
  1817. let selector = Expression::Builtin(
  1818. *loc,
  1819. vec![Type::Bytes(4)],
  1820. Builtin::FunctionSelector,
  1821. vec![function.clone()],
  1822. );
  1823. let address = Expression::Builtin(
  1824. *loc,
  1825. vec![Type::Address(false)],
  1826. Builtin::ExternalFunctionAddress,
  1827. vec![function],
  1828. );
  1829. tys.insert(0, Type::Bytes(4));
  1830. let payload = Expression::AbiEncode {
  1831. loc: *loc,
  1832. tys,
  1833. packed: vec![selector],
  1834. args,
  1835. };
  1836. cfg.add(
  1837. vartab,
  1838. Instr::ExternalCall {
  1839. success: None,
  1840. address: Some(address),
  1841. payload,
  1842. value,
  1843. gas,
  1844. callty: CallTy::Regular,
  1845. },
  1846. );
  1847. if !func_returns.is_empty() {
  1848. let mut returns = Vec::new();
  1849. let mut res = Vec::new();
  1850. let mut tys = Vec::new();
  1851. for ty in func_returns {
  1852. let temp_pos = vartab.temp_anonymous(&ty);
  1853. res.push(temp_pos);
  1854. returns.push(Expression::Variable(pt::Loc(0, 0, 0), ty.clone(), temp_pos));
  1855. tys.push(Parameter {
  1856. loc: pt::Loc(0, 0, 0),
  1857. ty,
  1858. ty_loc: pt::Loc(0, 0, 0),
  1859. name: String::new(),
  1860. name_loc: None,
  1861. indexed: false,
  1862. });
  1863. }
  1864. cfg.add(
  1865. vartab,
  1866. Instr::AbiDecode {
  1867. res,
  1868. selector: None,
  1869. exception_block: None,
  1870. tys,
  1871. data: Expression::ReturnData(*loc),
  1872. },
  1873. );
  1874. returns
  1875. } else {
  1876. vec![Expression::Poison]
  1877. }
  1878. } else {
  1879. unreachable!();
  1880. }
  1881. }
  1882. Expression::Builtin(loc, tys, Builtin::AbiDecode, args) => {
  1883. let data = expression(&args[0], cfg, callee_contract_no, func, ns, vartab, opt);
  1884. let mut returns = Vec::new();
  1885. let mut res = Vec::new();
  1886. for ret in tys {
  1887. let temp_pos = vartab.temp_anonymous(ret);
  1888. res.push(temp_pos);
  1889. returns.push(Expression::Variable(*loc, ret.clone(), temp_pos));
  1890. }
  1891. cfg.add(
  1892. vartab,
  1893. Instr::AbiDecode {
  1894. res,
  1895. selector: None,
  1896. exception_block: None,
  1897. tys: tys
  1898. .iter()
  1899. .map(|ty| Parameter {
  1900. name: "".to_owned(),
  1901. name_loc: None,
  1902. loc: *loc,
  1903. ty: ty.clone(),
  1904. ty_loc: *loc,
  1905. indexed: false,
  1906. })
  1907. .collect(),
  1908. data,
  1909. },
  1910. );
  1911. returns
  1912. }
  1913. _ => unreachable!(),
  1914. }
  1915. }
  1916. pub fn default_gas(ns: &Namespace) -> Expression {
  1917. Expression::NumberLiteral(
  1918. pt::Loc(0, 0, 0),
  1919. Type::Uint(64),
  1920. // See EIP150
  1921. if ns.target == Target::Ewasm {
  1922. BigInt::from(i64::MAX)
  1923. } else {
  1924. BigInt::zero()
  1925. },
  1926. )
  1927. }
  1928. /// Codegen for an array subscript expression
  1929. fn array_subscript(
  1930. loc: &pt::Loc,
  1931. array_ty: &Type,
  1932. array: &Expression,
  1933. index: &Expression,
  1934. cfg: &mut ControlFlowGraph,
  1935. contract_no: usize,
  1936. func: Option<&Function>,
  1937. ns: &Namespace,
  1938. vartab: &mut Vartable,
  1939. opt: &Options,
  1940. ) -> Expression {
  1941. if array_ty.is_mapping() {
  1942. let array = expression(array, cfg, contract_no, func, ns, vartab, opt);
  1943. let index = expression(index, cfg, contract_no, func, ns, vartab, opt);
  1944. return if ns.target == Target::Solana {
  1945. Expression::Subscript(*loc, array_ty.clone(), Box::new(array), Box::new(index))
  1946. } else {
  1947. Expression::Keccak256(*loc, array_ty.clone(), vec![array, index])
  1948. };
  1949. }
  1950. let mut array = expression(array, cfg, contract_no, func, ns, vartab, opt);
  1951. let index_ty = index.ty();
  1952. let index = expression(index, cfg, contract_no, func, ns, vartab, opt);
  1953. let index_loc = index.loc();
  1954. let index_width = index_ty.bits(ns);
  1955. let array_length = match array_ty.deref_any() {
  1956. Type::Bytes(n) => bigint_to_expression(
  1957. &array.loc(),
  1958. &BigInt::from(*n),
  1959. ns,
  1960. &mut Vec::new(),
  1961. ResolveTo::Unknown,
  1962. )
  1963. .unwrap(),
  1964. Type::Array(_, _) => match array_ty.array_length() {
  1965. None => {
  1966. if let Type::StorageRef(_, _) = array_ty {
  1967. if ns.target == Target::Solana {
  1968. Expression::StorageArrayLength {
  1969. loc: *loc,
  1970. ty: ns.storage_type(),
  1971. array: Box::new(array.clone()),
  1972. elem_ty: array_ty.storage_array_elem().deref_into(),
  1973. }
  1974. } else {
  1975. let array_length =
  1976. load_storage(loc, &Type::Uint(256), array.clone(), cfg, vartab, opt);
  1977. array = Expression::Keccak256(*loc, Type::Uint(256), vec![array]);
  1978. array_length
  1979. }
  1980. } else {
  1981. Expression::Builtin(
  1982. *loc,
  1983. vec![Type::Uint(32)],
  1984. Builtin::ArrayLength,
  1985. vec![array.clone()],
  1986. )
  1987. }
  1988. }
  1989. Some(l) => {
  1990. bigint_to_expression(loc, l, ns, &mut Vec::new(), ResolveTo::Unknown).unwrap()
  1991. }
  1992. },
  1993. Type::DynamicBytes => Expression::Builtin(
  1994. *loc,
  1995. vec![Type::Uint(32)],
  1996. Builtin::ArrayLength,
  1997. vec![array.clone()],
  1998. ),
  1999. _ => {
  2000. unreachable!();
  2001. }
  2002. };
  2003. let array_width = array_length.ty().bits(ns);
  2004. let width = std::cmp::max(array_width, index_width);
  2005. let coerced_ty = Type::Uint(width);
  2006. let pos = vartab.temp(
  2007. &pt::Identifier {
  2008. name: "index".to_owned(),
  2009. loc: *loc,
  2010. },
  2011. &coerced_ty,
  2012. );
  2013. cfg.add(
  2014. vartab,
  2015. Instr::Set {
  2016. loc: pt::Loc(0, 0, 0),
  2017. res: pos,
  2018. expr: cast(&index.loc(), index, &coerced_ty, false, ns, &mut Vec::new()).unwrap(),
  2019. },
  2020. );
  2021. // If the array is fixed length and the index also constant, the
  2022. // branch will be optimized away.
  2023. let out_of_bounds = cfg.new_basic_block("out_of_bounds".to_string());
  2024. let in_bounds = cfg.new_basic_block("in_bounds".to_string());
  2025. cfg.add(
  2026. vartab,
  2027. Instr::BranchCond {
  2028. cond: Expression::MoreEqual(
  2029. *loc,
  2030. Box::new(Expression::Variable(index_loc, coerced_ty.clone(), pos)),
  2031. Box::new(
  2032. cast(
  2033. &array.loc(),
  2034. array_length.clone(),
  2035. &coerced_ty,
  2036. false,
  2037. ns,
  2038. &mut Vec::new(),
  2039. )
  2040. .unwrap(),
  2041. ),
  2042. ),
  2043. true_block: out_of_bounds,
  2044. false_block: in_bounds,
  2045. },
  2046. );
  2047. cfg.set_basic_block(out_of_bounds);
  2048. cfg.add(vartab, Instr::AssertFailure { expr: None });
  2049. cfg.set_basic_block(in_bounds);
  2050. if let Type::StorageRef(_, ty) = &array_ty {
  2051. let elem_ty = ty.storage_array_elem();
  2052. let slot_ty = ns.storage_type();
  2053. if ns.target == Target::Solana {
  2054. if ty.array_length().is_some() && ty.is_sparse_solana(ns) {
  2055. let index = cast(
  2056. &index_loc,
  2057. Expression::Variable(index_loc, coerced_ty, pos),
  2058. &Type::Uint(256),
  2059. false,
  2060. ns,
  2061. &mut Vec::new(),
  2062. )
  2063. .unwrap();
  2064. Expression::Subscript(*loc, array_ty.clone(), Box::new(array), Box::new(index))
  2065. } else {
  2066. let index = cast(
  2067. &index_loc,
  2068. Expression::Variable(index_loc, coerced_ty, pos),
  2069. &slot_ty,
  2070. false,
  2071. ns,
  2072. &mut Vec::new(),
  2073. )
  2074. .unwrap();
  2075. if ty.array_length().is_some() {
  2076. // fixed length array
  2077. let elem_size = elem_ty.deref_any().size_of(ns);
  2078. Expression::Add(
  2079. *loc,
  2080. elem_ty,
  2081. true,
  2082. Box::new(array),
  2083. Box::new(Expression::Multiply(
  2084. *loc,
  2085. slot_ty.clone(),
  2086. true,
  2087. Box::new(index),
  2088. Box::new(Expression::NumberLiteral(*loc, slot_ty, elem_size)),
  2089. )),
  2090. )
  2091. } else {
  2092. Expression::Subscript(*loc, array_ty.clone(), Box::new(array), Box::new(index))
  2093. }
  2094. }
  2095. } else {
  2096. let elem_size = elem_ty.storage_slots(ns);
  2097. if let Ok(array_length) = eval_const_number(&array_length, Some(contract_no), ns) {
  2098. if array_length.1.mul(elem_size.clone()).to_u64().is_some() {
  2099. // we need to calculate the storage offset. If this can be done with 64 bit
  2100. // arithmetic it will be much more efficient on wasm
  2101. return Expression::Add(
  2102. *loc,
  2103. elem_ty,
  2104. true,
  2105. Box::new(array),
  2106. Box::new(Expression::ZeroExt(
  2107. *loc,
  2108. slot_ty,
  2109. Box::new(Expression::Multiply(
  2110. *loc,
  2111. Type::Uint(64),
  2112. true,
  2113. Box::new(
  2114. cast(
  2115. &index_loc,
  2116. Expression::Variable(index_loc, coerced_ty, pos),
  2117. &Type::Uint(64),
  2118. false,
  2119. ns,
  2120. &mut Vec::new(),
  2121. )
  2122. .unwrap(),
  2123. ),
  2124. Box::new(Expression::NumberLiteral(
  2125. *loc,
  2126. Type::Uint(64),
  2127. elem_size,
  2128. )),
  2129. )),
  2130. )),
  2131. );
  2132. }
  2133. }
  2134. array_offset(
  2135. loc,
  2136. array,
  2137. cast(
  2138. &index_loc,
  2139. Expression::Variable(index_loc, coerced_ty, pos),
  2140. &ns.storage_type(),
  2141. false,
  2142. ns,
  2143. &mut Vec::new(),
  2144. )
  2145. .unwrap(),
  2146. elem_ty,
  2147. ns,
  2148. )
  2149. }
  2150. } else {
  2151. match array_ty.deref_memory() {
  2152. Type::Bytes(array_length) => {
  2153. let res_ty = Type::Bytes(1);
  2154. let from_ty = Type::Bytes(*array_length);
  2155. let index_ty = Type::Uint(*array_length as u16 * 8);
  2156. Expression::Trunc(
  2157. *loc,
  2158. res_ty,
  2159. Box::new(Expression::ShiftRight(
  2160. *loc,
  2161. from_ty,
  2162. Box::new(array),
  2163. // shift by (array_length - 1 - index) * 8
  2164. Box::new(Expression::ShiftLeft(
  2165. *loc,
  2166. index_ty.clone(),
  2167. Box::new(Expression::Subtract(
  2168. *loc,
  2169. index_ty.clone(),
  2170. true,
  2171. Box::new(Expression::NumberLiteral(
  2172. *loc,
  2173. index_ty.clone(),
  2174. BigInt::from_u8(array_length - 1).unwrap(),
  2175. )),
  2176. Box::new(cast_shift_arg(
  2177. loc,
  2178. Expression::Variable(index_loc, coerced_ty, pos),
  2179. index_width,
  2180. array_ty,
  2181. ns,
  2182. )),
  2183. )),
  2184. Box::new(Expression::NumberLiteral(
  2185. *loc,
  2186. index_ty,
  2187. BigInt::from_u8(3).unwrap(),
  2188. )),
  2189. )),
  2190. false,
  2191. )),
  2192. )
  2193. }
  2194. Type::Array(_, dim) if dim.last().unwrap().is_some() => Expression::Subscript(
  2195. *loc,
  2196. array_ty.clone(),
  2197. Box::new(array),
  2198. Box::new(Expression::Variable(index_loc, coerced_ty, pos)),
  2199. ),
  2200. Type::DynamicBytes | Type::Array(_, _) => Expression::Subscript(
  2201. *loc,
  2202. array_ty.clone(),
  2203. Box::new(array),
  2204. Box::new(Expression::Variable(index_loc, coerced_ty, pos)),
  2205. ),
  2206. _ => {
  2207. // should not happen as type-checking already done
  2208. unreachable!();
  2209. }
  2210. }
  2211. }
  2212. }
  2213. fn string_location(
  2214. loc: &StringLocation,
  2215. cfg: &mut ControlFlowGraph,
  2216. contract_no: usize,
  2217. func: Option<&Function>,
  2218. ns: &Namespace,
  2219. vartab: &mut Vartable,
  2220. opt: &Options,
  2221. ) -> StringLocation {
  2222. match loc {
  2223. StringLocation::RunTime(s) => StringLocation::RunTime(Box::new(expression(
  2224. s,
  2225. cfg,
  2226. contract_no,
  2227. func,
  2228. ns,
  2229. vartab,
  2230. opt,
  2231. ))),
  2232. _ => loc.clone(),
  2233. }
  2234. }
  2235. // Generate a load from storage instruction
  2236. pub fn load_storage(
  2237. loc: &pt::Loc,
  2238. ty: &Type,
  2239. storage: Expression,
  2240. cfg: &mut ControlFlowGraph,
  2241. vartab: &mut Vartable,
  2242. _opt: &Options,
  2243. ) -> Expression {
  2244. let res = vartab.temp_anonymous(ty);
  2245. cfg.add(
  2246. vartab,
  2247. Instr::LoadStorage {
  2248. res,
  2249. ty: ty.clone(),
  2250. storage,
  2251. },
  2252. );
  2253. Expression::Variable(*loc, ty.clone(), res)
  2254. }