expression.rs 93 KB

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