expression.rs 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647
  1. // SPDX-License-Identifier: Apache-2.0
  2. use super::encoding::{abi_decode, abi_encode};
  3. use super::storage::{
  4. array_offset, array_pop, array_push, storage_slots_array_pop, storage_slots_array_push,
  5. };
  6. use super::Options;
  7. use super::{
  8. cfg::{ControlFlowGraph, Instr, InternalCallTy},
  9. vartable::Vartable,
  10. };
  11. use crate::codegen::array_boundary::handle_array_assign;
  12. use crate::codegen::constructor::call_constructor;
  13. use crate::codegen::error_msg_with_loc;
  14. use crate::codegen::unused_variable::should_remove_assignment;
  15. use crate::codegen::{Builtin, Expression};
  16. use crate::sema::{
  17. ast,
  18. ast::{
  19. ArrayLength, CallTy, FormatArg, Function, Namespace, RetrieveType, StringLocation,
  20. StructType, Type,
  21. },
  22. diagnostics::Diagnostics,
  23. eval::{eval_const_number, eval_const_rational},
  24. expression::integers::bigint_to_expression,
  25. expression::ResolveTo,
  26. };
  27. use crate::Target;
  28. use num_bigint::BigInt;
  29. use num_traits::{FromPrimitive, One, ToPrimitive, Zero};
  30. use solang_parser::pt;
  31. use solang_parser::pt::{CodeLocation, Loc};
  32. use std::{cmp::Ordering, ops::Mul};
  33. pub fn expression(
  34. expr: &ast::Expression,
  35. cfg: &mut ControlFlowGraph,
  36. contract_no: usize,
  37. func: Option<&Function>,
  38. ns: &Namespace,
  39. vartab: &mut Vartable,
  40. opt: &Options,
  41. ) -> Expression {
  42. match expr {
  43. ast::Expression::StorageVariable {
  44. loc,
  45. contract_no: var_contract_no,
  46. var_no,
  47. ..
  48. } => {
  49. // base storage variables should precede contract variables, not overlap
  50. ns.contracts[contract_no].get_storage_slot(*loc, *var_contract_no, *var_no, ns, None)
  51. }
  52. ast::Expression::StorageLoad { loc, ty, expr } => {
  53. let storage = expression(expr, cfg, contract_no, func, ns, vartab, opt);
  54. load_storage(loc, ty, storage, cfg, vartab)
  55. }
  56. ast::Expression::Add {
  57. loc,
  58. ty,
  59. unchecked,
  60. left,
  61. right,
  62. } => add(
  63. loc,
  64. ty,
  65. *unchecked,
  66. left,
  67. cfg,
  68. contract_no,
  69. func,
  70. ns,
  71. vartab,
  72. right,
  73. opt,
  74. ),
  75. ast::Expression::Subtract {
  76. loc,
  77. ty,
  78. unchecked,
  79. left,
  80. right,
  81. } => subtract(
  82. loc,
  83. ty,
  84. *unchecked,
  85. left,
  86. cfg,
  87. contract_no,
  88. func,
  89. ns,
  90. vartab,
  91. right,
  92. opt,
  93. ),
  94. ast::Expression::Multiply {
  95. loc,
  96. ty,
  97. unchecked,
  98. left,
  99. right,
  100. } => {
  101. if ty.is_rational() {
  102. let (_, r) = eval_const_rational(expr, ns).unwrap();
  103. Expression::NumberLiteral {
  104. loc: *loc,
  105. ty: ty.clone(),
  106. value: r.to_integer(),
  107. }
  108. } else {
  109. Expression::Multiply {
  110. loc: *loc,
  111. ty: ty.clone(),
  112. overflowing: *unchecked,
  113. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  114. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  115. }
  116. }
  117. }
  118. ast::Expression::Divide {
  119. loc,
  120. ty,
  121. left,
  122. right,
  123. } => {
  124. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  125. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  126. if ty.is_signed_int(ns) {
  127. Expression::SignedDivide {
  128. loc: *loc,
  129. ty: ty.clone(),
  130. left: Box::new(l),
  131. right: Box::new(r),
  132. }
  133. } else {
  134. Expression::UnsignedDivide {
  135. loc: *loc,
  136. ty: ty.clone(),
  137. left: Box::new(l),
  138. right: Box::new(r),
  139. }
  140. }
  141. }
  142. ast::Expression::Modulo {
  143. loc,
  144. ty,
  145. left,
  146. right,
  147. } => {
  148. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  149. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  150. if ty.is_signed_int(ns) {
  151. Expression::SignedModulo {
  152. loc: *loc,
  153. ty: ty.clone(),
  154. left: Box::new(l),
  155. right: Box::new(r),
  156. }
  157. } else {
  158. Expression::UnsignedModulo {
  159. loc: *loc,
  160. ty: ty.clone(),
  161. left: Box::new(l),
  162. right: Box::new(r),
  163. }
  164. }
  165. }
  166. ast::Expression::Power {
  167. loc,
  168. ty,
  169. unchecked,
  170. base,
  171. exp,
  172. } => Expression::Power {
  173. loc: *loc,
  174. ty: ty.clone(),
  175. overflowing: *unchecked,
  176. base: Box::new(expression(base, cfg, contract_no, func, ns, vartab, opt)),
  177. exp: Box::new(expression(exp, cfg, contract_no, func, ns, vartab, opt)),
  178. },
  179. ast::Expression::BitwiseOr {
  180. loc,
  181. ty,
  182. left,
  183. right,
  184. } => Expression::BitwiseOr {
  185. loc: *loc,
  186. ty: ty.clone(),
  187. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  188. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  189. },
  190. ast::Expression::BitwiseAnd {
  191. loc,
  192. ty,
  193. left,
  194. right,
  195. } => Expression::BitwiseAnd {
  196. loc: *loc,
  197. ty: ty.clone(),
  198. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  199. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  200. },
  201. ast::Expression::BitwiseXor {
  202. loc,
  203. ty,
  204. left,
  205. right,
  206. } => Expression::BitwiseXor {
  207. loc: *loc,
  208. ty: ty.clone(),
  209. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  210. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  211. },
  212. ast::Expression::ShiftLeft {
  213. loc,
  214. ty,
  215. left,
  216. right,
  217. } => Expression::ShiftLeft {
  218. loc: *loc,
  219. ty: ty.clone(),
  220. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  221. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  222. },
  223. ast::Expression::ShiftRight {
  224. loc,
  225. ty,
  226. left,
  227. right,
  228. sign,
  229. } => Expression::ShiftRight {
  230. loc: *loc,
  231. ty: ty.clone(),
  232. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  233. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  234. signed: *sign,
  235. },
  236. ast::Expression::Equal { loc, left, right } => Expression::Equal {
  237. loc: *loc,
  238. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  239. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  240. },
  241. ast::Expression::NotEqual { loc, left, right } => Expression::NotEqual {
  242. loc: *loc,
  243. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  244. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  245. },
  246. ast::Expression::More { loc, left, right } => {
  247. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  248. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  249. Expression::More {
  250. loc: *loc,
  251. signed: l.ty().is_signed_int(ns),
  252. left: Box::new(l),
  253. right: Box::new(r),
  254. }
  255. }
  256. ast::Expression::MoreEqual { loc, left, right } => Expression::MoreEqual {
  257. loc: *loc,
  258. signed: left.ty().is_signed_int(ns),
  259. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  260. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  261. },
  262. ast::Expression::Less { loc, left, right } => {
  263. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  264. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  265. Expression::Less {
  266. loc: *loc,
  267. signed: l.ty().is_signed_int(ns),
  268. left: Box::new(l),
  269. right: Box::new(r),
  270. }
  271. }
  272. ast::Expression::LessEqual { loc, left, right } => Expression::LessEqual {
  273. loc: *loc,
  274. signed: left.ty().is_signed_int(ns),
  275. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  276. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  277. },
  278. ast::Expression::ConstantVariable {
  279. contract_no: Some(var_contract_no),
  280. var_no,
  281. ..
  282. } => expression(
  283. ns.contracts[*var_contract_no].variables[*var_no]
  284. .initializer
  285. .as_ref()
  286. .unwrap(),
  287. cfg,
  288. contract_no,
  289. func,
  290. ns,
  291. vartab,
  292. opt,
  293. ),
  294. ast::Expression::ConstantVariable {
  295. contract_no: None,
  296. var_no,
  297. ..
  298. } => expression(
  299. ns.constants[*var_no].initializer.as_ref().unwrap(),
  300. cfg,
  301. contract_no,
  302. func,
  303. ns,
  304. vartab,
  305. opt,
  306. ),
  307. ast::Expression::Not { loc, expr } => Expression::Not {
  308. loc: *loc,
  309. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  310. },
  311. ast::Expression::BitwiseNot { loc, ty, expr } => Expression::BitwiseNot {
  312. loc: *loc,
  313. ty: ty.clone(),
  314. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  315. },
  316. ast::Expression::Negate { loc, ty, expr } => Expression::Negate {
  317. loc: *loc,
  318. ty: ty.clone(),
  319. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  320. },
  321. ast::Expression::StructLiteral { loc, ty, values } => Expression::StructLiteral {
  322. loc: *loc,
  323. ty: ty.clone(),
  324. values: values
  325. .iter()
  326. .map(|e| expression(e, cfg, contract_no, func, ns, vartab, opt))
  327. .collect(),
  328. },
  329. ast::Expression::ArrayLiteral {
  330. loc,
  331. ty,
  332. dimensions,
  333. values,
  334. } => Expression::ArrayLiteral {
  335. loc: *loc,
  336. ty: ty.clone(),
  337. dimensions: dimensions.clone(),
  338. values: values
  339. .iter()
  340. .map(|e| expression(e, cfg, contract_no, func, ns, vartab, opt))
  341. .collect(),
  342. },
  343. ast::Expression::ConstArrayLiteral {
  344. loc,
  345. ty,
  346. dimensions,
  347. values,
  348. } => Expression::ConstArrayLiteral {
  349. loc: *loc,
  350. ty: ty.clone(),
  351. dimensions: dimensions.clone(),
  352. values: values
  353. .iter()
  354. .map(|e| expression(e, cfg, contract_no, func, ns, vartab, opt))
  355. .collect(),
  356. },
  357. ast::Expression::Assign { left, right, .. } => {
  358. // If we reach this condition, the assignment is inside an expression.
  359. if let Some(function) = func {
  360. if should_remove_assignment(ns, left, function, opt) {
  361. return expression(right, cfg, contract_no, func, ns, vartab, opt);
  362. }
  363. }
  364. let mut cfg_right = expression(right, cfg, contract_no, func, ns, vartab, opt);
  365. // If an assignment where the left hand side is an array, call a helper function that updates the temp variable.
  366. if let ast::Expression::Variable {
  367. ty: Type::Array(..),
  368. var_no,
  369. ..
  370. } = &**left
  371. {
  372. // If cfg_right is an AllocDynamicArray(_,_,size,_), update it such that it becomes AllocDynamicArray(_,_,temp_var,_) to avoid repetitive expressions in the cfg.
  373. cfg_right = handle_array_assign(cfg_right, cfg, vartab, *var_no);
  374. }
  375. assign_single(left, cfg_right, cfg, contract_no, func, ns, vartab, opt)
  376. }
  377. ast::Expression::PreDecrement {
  378. loc,
  379. ty,
  380. unchecked,
  381. expr: var,
  382. }
  383. | ast::Expression::PreIncrement {
  384. loc,
  385. ty,
  386. unchecked,
  387. expr: var,
  388. } => pre_incdec(
  389. vartab,
  390. ty,
  391. var,
  392. cfg,
  393. contract_no,
  394. func,
  395. ns,
  396. loc,
  397. expr,
  398. *unchecked,
  399. opt,
  400. ),
  401. ast::Expression::PostDecrement {
  402. loc,
  403. ty,
  404. unchecked,
  405. expr: var,
  406. }
  407. | ast::Expression::PostIncrement {
  408. loc,
  409. ty,
  410. unchecked,
  411. expr: var,
  412. } => post_incdec(
  413. vartab,
  414. ty,
  415. var,
  416. cfg,
  417. contract_no,
  418. func,
  419. ns,
  420. loc,
  421. expr,
  422. *unchecked,
  423. opt,
  424. ),
  425. ast::Expression::Constructor {
  426. loc,
  427. contract_no: constructor_contract,
  428. constructor_no,
  429. args,
  430. call_args,
  431. } => {
  432. let address_res = vartab.temp_anonymous(&Type::Contract(*constructor_contract));
  433. call_constructor(
  434. loc,
  435. *constructor_contract,
  436. contract_no,
  437. constructor_no,
  438. args,
  439. call_args,
  440. address_res,
  441. None,
  442. func,
  443. ns,
  444. vartab,
  445. cfg,
  446. opt,
  447. );
  448. Expression::Variable {
  449. loc: *loc,
  450. ty: Type::Contract(*constructor_contract),
  451. var_no: address_res,
  452. }
  453. }
  454. ast::Expression::InternalFunction {
  455. function_no,
  456. signature,
  457. ..
  458. } => {
  459. let function_no = if let Some(signature) = signature {
  460. &ns.contracts[contract_no].virtual_functions[signature]
  461. } else {
  462. function_no
  463. };
  464. Expression::InternalFunctionCfg {
  465. cfg_no: ns.contracts[contract_no].all_functions[function_no],
  466. }
  467. }
  468. ast::Expression::StorageArrayLength {
  469. loc,
  470. ty,
  471. array,
  472. elem_ty,
  473. } => {
  474. let array_ty = array.ty().deref_into();
  475. let array = expression(array, cfg, contract_no, func, ns, vartab, opt);
  476. match array_ty {
  477. Type::Bytes(length) => {
  478. let ast_expr = bigint_to_expression(
  479. loc,
  480. &BigInt::from_u8(length).unwrap(),
  481. ns,
  482. &mut Diagnostics::default(),
  483. ResolveTo::Type(ty),
  484. None,
  485. )
  486. .unwrap();
  487. expression(&ast_expr, cfg, contract_no, func, ns, vartab, opt)
  488. }
  489. Type::DynamicBytes | Type::String => Expression::StorageArrayLength {
  490. loc: *loc,
  491. ty: ty.clone(),
  492. array: Box::new(array),
  493. elem_ty: elem_ty.clone(),
  494. },
  495. Type::Array(_, dim) => match dim.last().unwrap() {
  496. ArrayLength::Dynamic => {
  497. if ns.target == Target::Solana {
  498. Expression::StorageArrayLength {
  499. loc: *loc,
  500. ty: ty.clone(),
  501. array: Box::new(array),
  502. elem_ty: elem_ty.clone(),
  503. }
  504. } else {
  505. load_storage(loc, &ns.storage_type(), array, cfg, vartab)
  506. }
  507. }
  508. ArrayLength::Fixed(length) => {
  509. let ast_expr = bigint_to_expression(
  510. loc,
  511. length,
  512. ns,
  513. &mut Diagnostics::default(),
  514. ResolveTo::Type(ty),
  515. None,
  516. )
  517. .unwrap();
  518. expression(&ast_expr, cfg, contract_no, func, ns, vartab, opt)
  519. }
  520. _ => unreachable!(),
  521. },
  522. _ => unreachable!(),
  523. }
  524. }
  525. ast::Expression::Builtin {
  526. kind: ast::Builtin::ExternalFunctionAddress,
  527. args: func_expr,
  528. ..
  529. } => {
  530. if let ast::Expression::ExternalFunction { address, .. } = &func_expr[0] {
  531. expression(address, cfg, contract_no, func, ns, vartab, opt)
  532. } else {
  533. let func_expr = expression(&func_expr[0], cfg, contract_no, func, ns, vartab, opt);
  534. func_expr.external_function_address()
  535. }
  536. }
  537. ast::Expression::Builtin {
  538. loc,
  539. kind: ast::Builtin::FunctionSelector,
  540. args: func_expr,
  541. ..
  542. } => match &func_expr[0] {
  543. ast::Expression::ExternalFunction { function_no, .. }
  544. | ast::Expression::InternalFunction { function_no, .. } => {
  545. let selector = ns.functions[*function_no].selector(ns, &contract_no);
  546. Expression::BytesLiteral {
  547. loc: *loc,
  548. ty: Type::Bytes(selector.len() as u8),
  549. value: selector,
  550. }
  551. }
  552. _ => {
  553. let func_expr = expression(&func_expr[0], cfg, contract_no, func, ns, vartab, opt);
  554. func_expr.external_function_selector()
  555. }
  556. },
  557. ast::Expression::InternalFunctionCall { .. }
  558. | ast::Expression::ExternalFunctionCall { .. }
  559. | ast::Expression::ExternalFunctionCallRaw { .. }
  560. | ast::Expression::Builtin {
  561. kind: ast::Builtin::AbiDecode,
  562. ..
  563. } => {
  564. let mut returns = emit_function_call(expr, contract_no, cfg, func, ns, vartab, opt);
  565. returns.remove(0)
  566. }
  567. ast::Expression::ExternalFunction {
  568. loc,
  569. ty,
  570. address,
  571. function_no,
  572. } => {
  573. let address = expression(address, cfg, contract_no, func, ns, vartab, opt);
  574. let selector = Expression::BytesLiteral {
  575. loc: *loc,
  576. ty: Type::Uint(32),
  577. value: ns.functions[*function_no].selector(ns, &contract_no),
  578. };
  579. let struct_literal = Expression::StructLiteral {
  580. loc: *loc,
  581. ty: Type::Struct(StructType::ExternalFunction),
  582. values: vec![selector, address],
  583. };
  584. Expression::Cast {
  585. loc: *loc,
  586. ty: ty.clone(),
  587. expr: Box::new(struct_literal),
  588. }
  589. }
  590. ast::Expression::Subscript {
  591. loc,
  592. ty: elem_ty,
  593. array_ty,
  594. array,
  595. index,
  596. } => array_subscript(
  597. loc,
  598. elem_ty,
  599. array_ty,
  600. array,
  601. index,
  602. cfg,
  603. contract_no,
  604. func,
  605. ns,
  606. vartab,
  607. opt,
  608. ),
  609. ast::Expression::StructMember {
  610. loc,
  611. ty,
  612. expr: var,
  613. field: field_no,
  614. } if ty.is_contract_storage() => {
  615. if let Type::Struct(struct_ty) = var.ty().deref_any() {
  616. let offset = if ns.target == Target::Solana {
  617. struct_ty.definition(ns).storage_offsets[*field_no].clone()
  618. } else {
  619. struct_ty.definition(ns).fields[..*field_no]
  620. .iter()
  621. .filter(|field| !field.infinite_size)
  622. .map(|field| field.ty.storage_slots(ns))
  623. .sum()
  624. };
  625. Expression::Add {
  626. loc: *loc,
  627. ty: ns.storage_type(),
  628. overflowing: true,
  629. left: Box::new(expression(var, cfg, contract_no, func, ns, vartab, opt)),
  630. right: Box::new(Expression::NumberLiteral {
  631. loc: *loc,
  632. ty: ns.storage_type(),
  633. value: offset,
  634. }),
  635. }
  636. } else {
  637. unreachable!();
  638. }
  639. }
  640. ast::Expression::StructMember {
  641. loc,
  642. ty,
  643. expr: var,
  644. field: member,
  645. } => Expression::StructMember {
  646. loc: *loc,
  647. ty: ty.clone(),
  648. expr: Box::new(expression(var, cfg, contract_no, func, ns, vartab, opt)),
  649. member: *member,
  650. },
  651. ast::Expression::StringCompare { loc, left, right } => Expression::StringCompare {
  652. loc: *loc,
  653. left: string_location(left, cfg, contract_no, func, ns, vartab, opt),
  654. right: string_location(right, cfg, contract_no, func, ns, vartab, opt),
  655. },
  656. ast::Expression::StringConcat {
  657. loc,
  658. ty,
  659. left,
  660. right,
  661. } => Expression::StringConcat {
  662. loc: *loc,
  663. ty: ty.clone(),
  664. left: string_location(left, cfg, contract_no, func, ns, vartab, opt),
  665. right: string_location(right, cfg, contract_no, func, ns, vartab, opt),
  666. },
  667. ast::Expression::Or { loc, left, right } => {
  668. expr_or(left, cfg, contract_no, func, ns, vartab, loc, right, opt)
  669. }
  670. ast::Expression::And { loc, left, right } => {
  671. and(left, cfg, contract_no, func, ns, vartab, loc, right, opt)
  672. }
  673. ast::Expression::CheckingTrunc { loc, to, expr } => {
  674. checking_trunc(loc, expr, to, cfg, contract_no, func, ns, vartab, opt)
  675. }
  676. ast::Expression::Trunc { loc, to, expr } => Expression::Trunc {
  677. loc: *loc,
  678. ty: to.clone(),
  679. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  680. },
  681. ast::Expression::ZeroExt { loc, to, expr } => Expression::ZeroExt {
  682. loc: *loc,
  683. ty: to.clone(),
  684. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  685. },
  686. ast::Expression::SignExt { loc, to, expr } => Expression::SignExt {
  687. loc: *loc,
  688. ty: to.clone(),
  689. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  690. },
  691. ast::Expression::Cast { loc, to, expr } if matches!(to, Type::Address(_)) => {
  692. if let Ok((_, address)) = eval_const_number(expr, ns) {
  693. Expression::NumberLiteral {
  694. loc: *loc,
  695. ty: to.clone(),
  696. value: address,
  697. }
  698. } else {
  699. Expression::Cast {
  700. loc: *loc,
  701. ty: to.clone(),
  702. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  703. }
  704. }
  705. }
  706. ast::Expression::Cast { to, expr, .. }
  707. if matches!((expr.ty(), to), (Type::Address(_), Type::Contract(_))) =>
  708. {
  709. // Address and Contract have the same underlying type. CSE will create
  710. // a temporary to replace multiple casts from address to Contract, which have no
  711. // real purpose.
  712. expression(expr, cfg, contract_no, func, ns, vartab, opt)
  713. }
  714. ast::Expression::Cast { loc, to, expr }
  715. if matches!(to, Type::Array(..))
  716. && matches!(**expr, ast::Expression::ArrayLiteral { .. }) =>
  717. {
  718. let codegen_expr = expression(expr, cfg, contract_no, func, ns, vartab, opt);
  719. array_literal_to_memory_array(loc, &codegen_expr, to, cfg, vartab)
  720. }
  721. ast::Expression::Cast { loc, to, expr } => {
  722. if expr.ty() == Type::Rational {
  723. let (_, n) = eval_const_rational(expr, ns).unwrap();
  724. Expression::NumberLiteral {
  725. loc: *loc,
  726. ty: to.clone(),
  727. value: n.to_integer(),
  728. }
  729. } else if matches!(to, Type::String | Type::DynamicBytes)
  730. && matches!(expr.ty(), Type::String | Type::DynamicBytes)
  731. {
  732. expression(expr, cfg, contract_no, func, ns, vartab, opt)
  733. } else {
  734. Expression::Cast {
  735. loc: *loc,
  736. ty: to.clone(),
  737. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  738. }
  739. }
  740. }
  741. ast::Expression::BytesCast {
  742. loc,
  743. to,
  744. from,
  745. expr,
  746. } => Expression::BytesCast {
  747. loc: *loc,
  748. ty: to.clone(),
  749. from: from.clone(),
  750. expr: Box::new(expression(expr, cfg, contract_no, func, ns, vartab, opt)),
  751. },
  752. ast::Expression::Load { loc, ty, expr: e } => Expression::Load {
  753. loc: *loc,
  754. ty: ty.clone(),
  755. expr: Box::new(expression(e, cfg, contract_no, func, ns, vartab, opt)),
  756. },
  757. // for some built-ins, we have to inline special case code
  758. ast::Expression::Builtin {
  759. kind: ast::Builtin::UserTypeWrap,
  760. args,
  761. ..
  762. }
  763. | ast::Expression::Builtin {
  764. kind: ast::Builtin::UserTypeUnwrap,
  765. args,
  766. ..
  767. } => expression(&args[0], cfg, contract_no, func, ns, vartab, opt),
  768. ast::Expression::Builtin {
  769. loc,
  770. tys: ty,
  771. kind: ast::Builtin::ArrayPush,
  772. args,
  773. } => {
  774. if args[0].ty().is_contract_storage() {
  775. if ns.target == Target::Solana || args[0].ty().is_storage_bytes() {
  776. array_push(loc, args, cfg, contract_no, func, ns, vartab, opt)
  777. } else {
  778. storage_slots_array_push(loc, args, cfg, contract_no, func, ns, vartab, opt)
  779. }
  780. } else {
  781. let second_arg = if args.len() > 1 {
  782. expression(&args[1], cfg, contract_no, func, ns, vartab, opt)
  783. } else {
  784. ty[0].default(ns).unwrap()
  785. };
  786. memory_array_push(
  787. &ty[0],
  788. vartab,
  789. &args[0],
  790. cfg,
  791. contract_no,
  792. func,
  793. ns,
  794. second_arg,
  795. loc,
  796. opt,
  797. )
  798. }
  799. }
  800. ast::Expression::Builtin {
  801. loc,
  802. tys: ty,
  803. kind: ast::Builtin::ArrayPop,
  804. args,
  805. } => {
  806. if args[0].ty().is_contract_storage() {
  807. if ns.target == Target::Solana || args[0].ty().is_storage_bytes() {
  808. array_pop(loc, args, &ty[0], cfg, contract_no, func, ns, vartab, opt)
  809. } else {
  810. storage_slots_array_pop(
  811. loc,
  812. args,
  813. &ty[0],
  814. cfg,
  815. contract_no,
  816. func,
  817. ns,
  818. vartab,
  819. opt,
  820. )
  821. }
  822. } else {
  823. let address_res = vartab.temp_anonymous(&ty[0]);
  824. let array_pos = match expression(&args[0], cfg, contract_no, func, ns, vartab, opt)
  825. {
  826. Expression::Variable { var_no, .. } => {
  827. vartab.set_dirty(var_no);
  828. var_no
  829. }
  830. _ => unreachable!(),
  831. };
  832. cfg.add(
  833. vartab,
  834. Instr::PopMemory {
  835. res: address_res,
  836. ty: args[0].ty(),
  837. array: array_pos,
  838. loc: *loc,
  839. },
  840. );
  841. cfg.modify_temp_array_length(*loc, true, array_pos, vartab);
  842. Expression::Variable {
  843. loc: *loc,
  844. ty: ty[0].clone(),
  845. var_no: address_res,
  846. }
  847. }
  848. }
  849. ast::Expression::Builtin {
  850. kind: ast::Builtin::Assert,
  851. args,
  852. ..
  853. } => expr_assert(cfg, &args[0], contract_no, func, ns, vartab, opt),
  854. ast::Expression::Builtin {
  855. kind: ast::Builtin::Print,
  856. args,
  857. ..
  858. } => {
  859. if opt.log_prints {
  860. let expr = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  861. let to_print = if ns.target.is_substrate() {
  862. add_prefix_and_delimiter_to_print(expr)
  863. } else {
  864. expr
  865. };
  866. cfg.add(vartab, Instr::Print { expr: to_print });
  867. }
  868. Expression::Poison
  869. }
  870. ast::Expression::Builtin {
  871. kind: ast::Builtin::Require,
  872. args,
  873. ..
  874. } => require(cfg, args, contract_no, func, ns, vartab, opt, expr.loc()),
  875. ast::Expression::Builtin {
  876. kind: ast::Builtin::SelfDestruct,
  877. args,
  878. ..
  879. } => self_destruct(args, cfg, contract_no, func, ns, vartab, opt),
  880. ast::Expression::Builtin {
  881. loc,
  882. kind: ast::Builtin::PayableSend,
  883. args,
  884. ..
  885. } => payable_send(args, cfg, contract_no, func, ns, vartab, loc, opt),
  886. ast::Expression::Builtin {
  887. loc,
  888. kind: ast::Builtin::PayableTransfer,
  889. args,
  890. ..
  891. } => payable_transfer(args, cfg, contract_no, func, ns, vartab, loc, opt),
  892. ast::Expression::Builtin {
  893. loc,
  894. kind: ast::Builtin::AbiEncode,
  895. args,
  896. ..
  897. } => abi_encode_many(args, cfg, contract_no, func, ns, vartab, loc, opt),
  898. ast::Expression::Builtin {
  899. loc,
  900. kind: ast::Builtin::AbiEncodePacked,
  901. args,
  902. ..
  903. } => abi_encode_packed(args, cfg, contract_no, func, ns, vartab, loc, opt),
  904. ast::Expression::Builtin {
  905. loc,
  906. kind: ast::Builtin::AbiEncodeWithSelector,
  907. args,
  908. ..
  909. } => abi_encode_with_selector(args, cfg, contract_no, func, ns, vartab, loc, opt),
  910. ast::Expression::Builtin {
  911. loc,
  912. kind: ast::Builtin::AbiEncodeWithSignature,
  913. args,
  914. ..
  915. } => abi_encode_with_signature(args, loc, cfg, contract_no, func, ns, vartab, opt),
  916. ast::Expression::Builtin {
  917. loc,
  918. kind: ast::Builtin::AbiEncodeCall,
  919. args,
  920. ..
  921. } => abi_encode_call(args, cfg, contract_no, func, ns, vartab, loc, opt),
  922. // The Substrate gas price builtin takes an argument; the others do not
  923. ast::Expression::Builtin {
  924. loc,
  925. kind: ast::Builtin::Gasprice,
  926. args: expr,
  927. ..
  928. } if expr.len() == 1 && ns.target == Target::EVM => {
  929. builtin_evm_gasprice(loc, expr, cfg, contract_no, func, ns, vartab, opt)
  930. }
  931. ast::Expression::Builtin {
  932. loc,
  933. tys,
  934. kind,
  935. args,
  936. } => expr_builtin(
  937. args,
  938. cfg,
  939. contract_no,
  940. func,
  941. ns,
  942. vartab,
  943. loc,
  944. tys,
  945. *kind,
  946. opt,
  947. ),
  948. ast::Expression::FormatString { loc, format: args } => {
  949. format_string(args, cfg, contract_no, func, ns, vartab, loc, opt)
  950. }
  951. ast::Expression::AllocDynamicBytes {
  952. loc,
  953. ty,
  954. length: size,
  955. init,
  956. } => alloc_dynamic_array(size, cfg, contract_no, func, ns, vartab, loc, ty, init, opt),
  957. ast::Expression::ConditionalOperator {
  958. loc,
  959. ty,
  960. cond,
  961. true_option: left,
  962. false_option: right,
  963. } => conditional_operator(
  964. loc,
  965. ty,
  966. cond,
  967. cfg,
  968. contract_no,
  969. func,
  970. ns,
  971. vartab,
  972. left,
  973. right,
  974. opt,
  975. ),
  976. ast::Expression::InterfaceId { loc, contract_no } => interfaceid(ns, *contract_no, loc),
  977. ast::Expression::BoolLiteral { loc, value } => Expression::BoolLiteral {
  978. loc: *loc,
  979. value: *value,
  980. },
  981. ast::Expression::BytesLiteral { loc, ty, value } => Expression::BytesLiteral {
  982. loc: *loc,
  983. ty: ty.clone(),
  984. value: value.clone(),
  985. },
  986. ast::Expression::CodeLiteral {
  987. loc, contract_no, ..
  988. } => code(loc, *contract_no, ns, opt),
  989. ast::Expression::NumberLiteral { loc, ty, value } => Expression::NumberLiteral {
  990. loc: *loc,
  991. ty: ty.clone(),
  992. value: value.clone(),
  993. },
  994. ast::Expression::RationalNumberLiteral { loc, ty, value } => {
  995. Expression::RationalNumberLiteral {
  996. loc: *loc,
  997. ty: ty.clone(),
  998. rational: value.clone(),
  999. }
  1000. }
  1001. ast::Expression::Variable { loc, ty, var_no } => Expression::Variable {
  1002. loc: *loc,
  1003. ty: ty.clone(),
  1004. var_no: *var_no,
  1005. },
  1006. ast::Expression::List {
  1007. loc,
  1008. list: elements,
  1009. } => Expression::List {
  1010. loc: *loc,
  1011. exprs: elements
  1012. .iter()
  1013. .map(|e| expression(e, cfg, contract_no, func, ns, vartab, opt))
  1014. .collect::<Vec<Expression>>(),
  1015. },
  1016. ast::Expression::GetRef { loc, ty, expr: exp } => Expression::GetRef {
  1017. loc: *loc,
  1018. ty: ty.clone(),
  1019. expr: Box::new(expression(exp, cfg, contract_no, func, ns, vartab, opt)),
  1020. },
  1021. ast::Expression::UserDefinedOperator {
  1022. loc,
  1023. ty,
  1024. function_no,
  1025. args,
  1026. ..
  1027. } => {
  1028. let var = vartab.temp_anonymous(ty);
  1029. let cfg_no = ns.contracts[contract_no].all_functions[function_no];
  1030. let args = args
  1031. .iter()
  1032. .map(|a| expression(a, cfg, contract_no, func, ns, vartab, opt))
  1033. .collect::<Vec<Expression>>();
  1034. cfg.add(
  1035. vartab,
  1036. Instr::Call {
  1037. res: vec![var],
  1038. call: InternalCallTy::Static { cfg_no },
  1039. args,
  1040. return_tys: vec![ty.clone()],
  1041. },
  1042. );
  1043. Expression::Variable {
  1044. loc: *loc,
  1045. ty: ty.clone(),
  1046. var_no: var,
  1047. }
  1048. }
  1049. }
  1050. }
  1051. fn memory_array_push(
  1052. ty: &Type,
  1053. vartab: &mut Vartable,
  1054. array: &ast::Expression,
  1055. cfg: &mut ControlFlowGraph,
  1056. contract_no: usize,
  1057. func: Option<&Function>,
  1058. ns: &Namespace,
  1059. value: Expression,
  1060. loc: &pt::Loc,
  1061. opt: &Options,
  1062. ) -> Expression {
  1063. let address_res = vartab.temp_anonymous(ty);
  1064. let array_pos = match expression(array, cfg, contract_no, func, ns, vartab, opt) {
  1065. Expression::Variable { var_no, .. } => {
  1066. vartab.set_dirty(var_no);
  1067. var_no
  1068. }
  1069. _ => unreachable!(),
  1070. };
  1071. cfg.add(
  1072. vartab,
  1073. Instr::PushMemory {
  1074. res: address_res,
  1075. ty: array.ty(),
  1076. array: array_pos,
  1077. value: Box::new(value),
  1078. },
  1079. );
  1080. cfg.modify_temp_array_length(*loc, false, array_pos, vartab);
  1081. Expression::Variable {
  1082. loc: *loc,
  1083. ty: ty.clone(),
  1084. var_no: address_res,
  1085. }
  1086. }
  1087. fn post_incdec(
  1088. vartab: &mut Vartable,
  1089. ty: &Type,
  1090. var: &ast::Expression,
  1091. cfg: &mut ControlFlowGraph,
  1092. contract_no: usize,
  1093. func: Option<&Function>,
  1094. ns: &Namespace,
  1095. loc: &pt::Loc,
  1096. expr: &ast::Expression,
  1097. overflowing: bool,
  1098. opt: &Options,
  1099. ) -> Expression {
  1100. let res = vartab.temp_anonymous(ty);
  1101. let v = expression(var, cfg, contract_no, func, ns, vartab, opt);
  1102. let v = match var.ty() {
  1103. Type::Ref(ty) => Expression::Load {
  1104. loc: var.loc(),
  1105. ty: ty.as_ref().clone(),
  1106. expr: Box::new(v),
  1107. },
  1108. Type::StorageRef(_, ty) => load_storage(&var.loc(), ty.as_ref(), v, cfg, vartab),
  1109. _ => v,
  1110. };
  1111. cfg.add(
  1112. vartab,
  1113. Instr::Set {
  1114. loc: v.loc(),
  1115. res,
  1116. expr: v,
  1117. },
  1118. );
  1119. let one = Box::new(Expression::NumberLiteral {
  1120. loc: *loc,
  1121. ty: ty.clone(),
  1122. value: BigInt::one(),
  1123. });
  1124. let expr = match expr {
  1125. ast::Expression::PostDecrement { .. } => Expression::Subtract {
  1126. loc: *loc,
  1127. ty: ty.clone(),
  1128. overflowing,
  1129. left: Box::new(Expression::Variable {
  1130. loc: *loc,
  1131. ty: ty.clone(),
  1132. var_no: res,
  1133. }),
  1134. right: one,
  1135. },
  1136. ast::Expression::PostIncrement { .. } => Expression::Add {
  1137. loc: *loc,
  1138. ty: ty.clone(),
  1139. overflowing,
  1140. left: Box::new(Expression::Variable {
  1141. loc: *loc,
  1142. ty: ty.clone(),
  1143. var_no: res,
  1144. }),
  1145. right: one,
  1146. },
  1147. _ => unreachable!(),
  1148. };
  1149. match var {
  1150. ast::Expression::Variable { var_no, .. } => {
  1151. cfg.add(
  1152. vartab,
  1153. Instr::Set {
  1154. loc: expr.loc(),
  1155. res: *var_no,
  1156. expr,
  1157. },
  1158. );
  1159. }
  1160. _ => {
  1161. let dest = expression(var, cfg, contract_no, func, ns, vartab, opt);
  1162. let res = vartab.temp_anonymous(ty);
  1163. cfg.add(
  1164. vartab,
  1165. Instr::Set {
  1166. loc: expr.loc(),
  1167. res,
  1168. expr,
  1169. },
  1170. );
  1171. match var.ty() {
  1172. Type::StorageRef(..) => {
  1173. cfg.add(
  1174. vartab,
  1175. Instr::SetStorage {
  1176. value: Expression::Variable {
  1177. loc: *loc,
  1178. ty: ty.clone(),
  1179. var_no: res,
  1180. },
  1181. ty: ty.clone(),
  1182. storage: dest,
  1183. },
  1184. );
  1185. }
  1186. Type::Ref(_) => {
  1187. cfg.add(
  1188. vartab,
  1189. Instr::Store {
  1190. dest,
  1191. data: Expression::Variable {
  1192. loc: Loc::Codegen,
  1193. ty: ty.clone(),
  1194. var_no: res,
  1195. },
  1196. },
  1197. );
  1198. }
  1199. _ => unreachable!(),
  1200. }
  1201. }
  1202. }
  1203. Expression::Variable {
  1204. loc: *loc,
  1205. ty: ty.clone(),
  1206. var_no: res,
  1207. }
  1208. }
  1209. fn pre_incdec(
  1210. vartab: &mut Vartable,
  1211. ty: &Type,
  1212. var: &ast::Expression,
  1213. cfg: &mut ControlFlowGraph,
  1214. contract_no: usize,
  1215. func: Option<&Function>,
  1216. ns: &Namespace,
  1217. loc: &pt::Loc,
  1218. expr: &ast::Expression,
  1219. overflowing: bool,
  1220. opt: &Options,
  1221. ) -> Expression {
  1222. let res = vartab.temp_anonymous(ty);
  1223. let v = expression(var, cfg, contract_no, func, ns, vartab, opt);
  1224. let v = match var.ty() {
  1225. Type::Ref(ty) => Expression::Load {
  1226. loc: var.loc(),
  1227. ty: ty.as_ref().clone(),
  1228. expr: Box::new(v),
  1229. },
  1230. Type::StorageRef(_, ty) => load_storage(&var.loc(), ty.as_ref(), v, cfg, vartab),
  1231. _ => v,
  1232. };
  1233. let one = Box::new(Expression::NumberLiteral {
  1234. loc: *loc,
  1235. ty: ty.clone(),
  1236. value: BigInt::one(),
  1237. });
  1238. let expr = match expr {
  1239. ast::Expression::PreDecrement { .. } => Expression::Subtract {
  1240. loc: *loc,
  1241. ty: ty.clone(),
  1242. overflowing,
  1243. left: Box::new(v),
  1244. right: one,
  1245. },
  1246. ast::Expression::PreIncrement { .. } => Expression::Add {
  1247. loc: *loc,
  1248. ty: ty.clone(),
  1249. overflowing,
  1250. left: Box::new(v),
  1251. right: one,
  1252. },
  1253. _ => unreachable!(),
  1254. };
  1255. cfg.add(
  1256. vartab,
  1257. Instr::Set {
  1258. loc: expr.loc(),
  1259. res,
  1260. expr,
  1261. },
  1262. );
  1263. match var {
  1264. ast::Expression::Variable { loc, var_no, .. } => {
  1265. cfg.add(
  1266. vartab,
  1267. Instr::Set {
  1268. loc: *loc,
  1269. res: *var_no,
  1270. expr: Expression::Variable {
  1271. loc: *loc,
  1272. ty: ty.clone(),
  1273. var_no: res,
  1274. },
  1275. },
  1276. );
  1277. }
  1278. _ => {
  1279. let dest = expression(var, cfg, contract_no, func, ns, vartab, opt);
  1280. match var.ty() {
  1281. Type::StorageRef(..) => {
  1282. cfg.add(
  1283. vartab,
  1284. Instr::SetStorage {
  1285. value: Expression::Variable {
  1286. loc: *loc,
  1287. ty: ty.clone(),
  1288. var_no: res,
  1289. },
  1290. ty: ty.clone(),
  1291. storage: dest,
  1292. },
  1293. );
  1294. }
  1295. Type::Ref(_) => {
  1296. cfg.add(
  1297. vartab,
  1298. Instr::Store {
  1299. dest,
  1300. data: Expression::Variable {
  1301. loc: Loc::Codegen,
  1302. ty: ty.clone(),
  1303. var_no: res,
  1304. },
  1305. },
  1306. );
  1307. }
  1308. _ => unreachable!(),
  1309. }
  1310. }
  1311. }
  1312. Expression::Variable {
  1313. loc: *loc,
  1314. ty: ty.clone(),
  1315. var_no: res,
  1316. }
  1317. }
  1318. fn expr_or(
  1319. left: &ast::Expression,
  1320. cfg: &mut ControlFlowGraph,
  1321. contract_no: usize,
  1322. func: Option<&Function>,
  1323. ns: &Namespace,
  1324. vartab: &mut Vartable,
  1325. loc: &pt::Loc,
  1326. right: &ast::Expression,
  1327. opt: &Options,
  1328. ) -> Expression {
  1329. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  1330. let pos = vartab.temp(
  1331. &pt::Identifier {
  1332. name: "or".to_owned(),
  1333. loc: *loc,
  1334. },
  1335. &Type::Bool,
  1336. );
  1337. vartab.new_dirty_tracker();
  1338. let right_side = cfg.new_basic_block("or_right_side".to_string());
  1339. let end_or = cfg.new_basic_block("or_end".to_string());
  1340. cfg.add(
  1341. vartab,
  1342. Instr::Set {
  1343. loc: *loc,
  1344. res: pos,
  1345. expr: Expression::BoolLiteral {
  1346. loc: *loc,
  1347. value: true,
  1348. },
  1349. },
  1350. );
  1351. cfg.add(
  1352. vartab,
  1353. Instr::BranchCond {
  1354. cond: l,
  1355. true_block: end_or,
  1356. false_block: right_side,
  1357. },
  1358. );
  1359. cfg.set_basic_block(right_side);
  1360. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  1361. cfg.add(
  1362. vartab,
  1363. Instr::Set {
  1364. loc: r.loc(),
  1365. res: pos,
  1366. expr: r,
  1367. },
  1368. );
  1369. cfg.add(vartab, Instr::Branch { block: end_or });
  1370. cfg.set_basic_block(end_or);
  1371. cfg.set_phis(end_or, vartab.pop_dirty_tracker());
  1372. Expression::Variable {
  1373. loc: *loc,
  1374. ty: Type::Bool,
  1375. var_no: pos,
  1376. }
  1377. }
  1378. fn and(
  1379. left: &ast::Expression,
  1380. cfg: &mut ControlFlowGraph,
  1381. contract_no: usize,
  1382. func: Option<&Function>,
  1383. ns: &Namespace,
  1384. vartab: &mut Vartable,
  1385. loc: &pt::Loc,
  1386. right: &ast::Expression,
  1387. opt: &Options,
  1388. ) -> Expression {
  1389. let l = expression(left, cfg, contract_no, func, ns, vartab, opt);
  1390. let pos = vartab.temp(
  1391. &pt::Identifier {
  1392. name: "and".to_owned(),
  1393. loc: *loc,
  1394. },
  1395. &Type::Bool,
  1396. );
  1397. vartab.new_dirty_tracker();
  1398. let right_side = cfg.new_basic_block("and_right_side".to_string());
  1399. let end_and = cfg.new_basic_block("and_end".to_string());
  1400. cfg.add(
  1401. vartab,
  1402. Instr::Set {
  1403. loc: *loc,
  1404. res: pos,
  1405. expr: Expression::BoolLiteral {
  1406. loc: *loc,
  1407. value: false,
  1408. },
  1409. },
  1410. );
  1411. cfg.add(
  1412. vartab,
  1413. Instr::BranchCond {
  1414. cond: l,
  1415. true_block: right_side,
  1416. false_block: end_and,
  1417. },
  1418. );
  1419. cfg.set_basic_block(right_side);
  1420. let r = expression(right, cfg, contract_no, func, ns, vartab, opt);
  1421. cfg.add(
  1422. vartab,
  1423. Instr::Set {
  1424. loc: r.loc(),
  1425. res: pos,
  1426. expr: r,
  1427. },
  1428. );
  1429. cfg.add(vartab, Instr::Branch { block: end_and });
  1430. cfg.set_basic_block(end_and);
  1431. cfg.set_phis(end_and, vartab.pop_dirty_tracker());
  1432. Expression::Variable {
  1433. loc: *loc,
  1434. ty: Type::Bool,
  1435. var_no: pos,
  1436. }
  1437. }
  1438. fn expr_assert(
  1439. cfg: &mut ControlFlowGraph,
  1440. args: &ast::Expression,
  1441. contract_no: usize,
  1442. func: Option<&Function>,
  1443. ns: &Namespace,
  1444. vartab: &mut Vartable,
  1445. opt: &Options,
  1446. ) -> Expression {
  1447. let true_ = cfg.new_basic_block("noassert".to_owned());
  1448. let false_ = cfg.new_basic_block("doassert".to_owned());
  1449. let cond = expression(args, cfg, contract_no, func, ns, vartab, opt);
  1450. cfg.add(
  1451. vartab,
  1452. Instr::BranchCond {
  1453. cond,
  1454. true_block: true_,
  1455. false_block: false_,
  1456. },
  1457. );
  1458. cfg.set_basic_block(false_);
  1459. log_runtime_error(
  1460. opt.log_runtime_errors,
  1461. "assert failure",
  1462. args.loc(),
  1463. cfg,
  1464. vartab,
  1465. ns,
  1466. );
  1467. assert_failure(&Loc::Codegen, None, ns, cfg, vartab);
  1468. cfg.set_basic_block(true_);
  1469. Expression::Poison
  1470. }
  1471. fn require(
  1472. cfg: &mut ControlFlowGraph,
  1473. args: &[ast::Expression],
  1474. contract_no: usize,
  1475. func: Option<&Function>,
  1476. ns: &Namespace,
  1477. vartab: &mut Vartable,
  1478. opt: &Options,
  1479. loc: Loc,
  1480. ) -> Expression {
  1481. let true_ = cfg.new_basic_block("noassert".to_owned());
  1482. let false_ = cfg.new_basic_block("doassert".to_owned());
  1483. let cond = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1484. cfg.add(
  1485. vartab,
  1486. Instr::BranchCond {
  1487. cond,
  1488. true_block: true_,
  1489. false_block: false_,
  1490. },
  1491. );
  1492. cfg.set_basic_block(false_);
  1493. let expr = args
  1494. .get(1)
  1495. .map(|s| expression(s, cfg, contract_no, func, ns, vartab, opt));
  1496. match ns.target {
  1497. // On Solana and Substrate, print the reason, do not abi encode it
  1498. Target::Solana | Target::Substrate { .. } => {
  1499. if opt.log_runtime_errors {
  1500. if let Some(expr) = expr {
  1501. let prefix = b"runtime_error: ";
  1502. let error_string = format!(
  1503. " require condition failed in {},\n",
  1504. ns.loc_to_string(false, &expr.loc())
  1505. );
  1506. let print_expr = Expression::FormatString {
  1507. loc: Loc::Codegen,
  1508. args: vec![
  1509. (
  1510. FormatArg::StringLiteral,
  1511. Expression::BytesLiteral {
  1512. loc: Loc::Codegen,
  1513. ty: Type::Bytes(prefix.len() as u8),
  1514. value: prefix.to_vec(),
  1515. },
  1516. ),
  1517. (FormatArg::Default, expr),
  1518. (
  1519. FormatArg::StringLiteral,
  1520. Expression::BytesLiteral {
  1521. loc: Loc::Codegen,
  1522. ty: Type::Bytes(error_string.as_bytes().len() as u8),
  1523. value: error_string.as_bytes().to_vec(),
  1524. },
  1525. ),
  1526. ],
  1527. };
  1528. cfg.add(vartab, Instr::Print { expr: print_expr });
  1529. } else {
  1530. log_runtime_error(
  1531. opt.log_runtime_errors,
  1532. "require condition failed",
  1533. loc,
  1534. cfg,
  1535. vartab,
  1536. ns,
  1537. );
  1538. }
  1539. }
  1540. assert_failure(&Loc::Codegen, None, ns, cfg, vartab);
  1541. }
  1542. _ => assert_failure(&Loc::Codegen, expr, ns, cfg, vartab),
  1543. }
  1544. cfg.set_basic_block(true_);
  1545. Expression::Poison
  1546. }
  1547. fn self_destruct(
  1548. args: &[ast::Expression],
  1549. cfg: &mut ControlFlowGraph,
  1550. contract_no: usize,
  1551. func: Option<&Function>,
  1552. ns: &Namespace,
  1553. vartab: &mut Vartable,
  1554. opt: &Options,
  1555. ) -> Expression {
  1556. let recipient = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1557. cfg.add(vartab, Instr::SelfDestruct { recipient });
  1558. Expression::Poison
  1559. }
  1560. fn payable_send(
  1561. args: &[ast::Expression],
  1562. cfg: &mut ControlFlowGraph,
  1563. contract_no: usize,
  1564. func: Option<&Function>,
  1565. ns: &Namespace,
  1566. vartab: &mut Vartable,
  1567. loc: &pt::Loc,
  1568. opt: &Options,
  1569. ) -> Expression {
  1570. let address = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1571. let value = expression(&args[1], cfg, contract_no, func, ns, vartab, opt);
  1572. let success = vartab.temp(
  1573. &pt::Identifier {
  1574. loc: *loc,
  1575. name: "success".to_owned(),
  1576. },
  1577. &Type::Bool,
  1578. );
  1579. if ns.target != Target::EVM {
  1580. cfg.add(
  1581. vartab,
  1582. Instr::ValueTransfer {
  1583. success: Some(success),
  1584. address,
  1585. value,
  1586. },
  1587. );
  1588. } else {
  1589. // Ethereum can only transfer via external call
  1590. cfg.add(
  1591. vartab,
  1592. Instr::ExternalCall {
  1593. success: Some(success),
  1594. address: Some(address),
  1595. accounts: None,
  1596. seeds: None,
  1597. payload: Expression::AllocDynamicBytes {
  1598. loc: *loc,
  1599. ty: Type::DynamicBytes,
  1600. size: Box::new(Expression::NumberLiteral {
  1601. loc: *loc,
  1602. ty: Type::Uint(32),
  1603. value: BigInt::from(0),
  1604. }),
  1605. initializer: Some(vec![]),
  1606. },
  1607. value,
  1608. gas: Expression::NumberLiteral {
  1609. loc: *loc,
  1610. ty: Type::Uint(64),
  1611. value: BigInt::from(i64::MAX),
  1612. },
  1613. callty: CallTy::Regular,
  1614. contract_function_no: None,
  1615. },
  1616. );
  1617. }
  1618. Expression::Variable {
  1619. loc: *loc,
  1620. ty: Type::Bool,
  1621. var_no: success,
  1622. }
  1623. }
  1624. fn payable_transfer(
  1625. args: &[ast::Expression],
  1626. cfg: &mut ControlFlowGraph,
  1627. contract_no: usize,
  1628. func: Option<&Function>,
  1629. ns: &Namespace,
  1630. vartab: &mut Vartable,
  1631. loc: &pt::Loc,
  1632. opt: &Options,
  1633. ) -> Expression {
  1634. let address = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1635. let value = expression(&args[1], cfg, contract_no, func, ns, vartab, opt);
  1636. if ns.target != Target::EVM {
  1637. cfg.add(
  1638. vartab,
  1639. Instr::ValueTransfer {
  1640. success: None,
  1641. address,
  1642. value,
  1643. },
  1644. );
  1645. } else {
  1646. // Ethereum can only transfer via external call
  1647. cfg.add(
  1648. vartab,
  1649. Instr::ExternalCall {
  1650. success: None,
  1651. accounts: None,
  1652. seeds: None,
  1653. address: Some(address),
  1654. payload: Expression::AllocDynamicBytes {
  1655. loc: *loc,
  1656. ty: Type::DynamicBytes,
  1657. size: Box::new(Expression::NumberLiteral {
  1658. loc: *loc,
  1659. ty: Type::Uint(32),
  1660. value: BigInt::from(0),
  1661. }),
  1662. initializer: Some(vec![]),
  1663. },
  1664. value,
  1665. gas: Expression::NumberLiteral {
  1666. loc: *loc,
  1667. ty: Type::Uint(64),
  1668. value: BigInt::from(i64::MAX),
  1669. },
  1670. callty: CallTy::Regular,
  1671. contract_function_no: None,
  1672. },
  1673. );
  1674. }
  1675. Expression::Poison
  1676. }
  1677. fn abi_encode_many(
  1678. args: &[ast::Expression],
  1679. cfg: &mut ControlFlowGraph,
  1680. contract_no: usize,
  1681. func: Option<&Function>,
  1682. ns: &Namespace,
  1683. vartab: &mut Vartable,
  1684. loc: &pt::Loc,
  1685. opt: &Options,
  1686. ) -> Expression {
  1687. let args = args
  1688. .iter()
  1689. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1690. .collect::<Vec<Expression>>();
  1691. abi_encode(loc, args, ns, vartab, cfg, false).0
  1692. }
  1693. fn abi_encode_packed(
  1694. args: &[ast::Expression],
  1695. cfg: &mut ControlFlowGraph,
  1696. contract_no: usize,
  1697. func: Option<&Function>,
  1698. ns: &Namespace,
  1699. vartab: &mut Vartable,
  1700. loc: &pt::Loc,
  1701. opt: &Options,
  1702. ) -> Expression {
  1703. let packed = args
  1704. .iter()
  1705. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1706. .collect::<Vec<Expression>>();
  1707. let (encoded, _) = abi_encode(loc, packed, ns, vartab, cfg, true);
  1708. encoded
  1709. }
  1710. fn encode_many_with_selector(
  1711. loc: &pt::Loc,
  1712. selector: Expression,
  1713. mut args: Vec<Expression>,
  1714. ns: &Namespace,
  1715. vartab: &mut Vartable,
  1716. cfg: &mut ControlFlowGraph,
  1717. ) -> Expression {
  1718. let mut encoder_args: Vec<Expression> = Vec::with_capacity(args.len() + 1);
  1719. encoder_args.push(selector);
  1720. encoder_args.append(&mut args);
  1721. abi_encode(loc, encoder_args, ns, vartab, cfg, false).0
  1722. }
  1723. fn abi_encode_with_selector(
  1724. args: &[ast::Expression],
  1725. cfg: &mut ControlFlowGraph,
  1726. contract_no: usize,
  1727. func: Option<&Function>,
  1728. ns: &Namespace,
  1729. vartab: &mut Vartable,
  1730. loc: &pt::Loc,
  1731. opt: &Options,
  1732. ) -> Expression {
  1733. let mut args_iter = args.iter();
  1734. let selector = expression(
  1735. args_iter.next().unwrap(),
  1736. cfg,
  1737. contract_no,
  1738. func,
  1739. ns,
  1740. vartab,
  1741. opt,
  1742. );
  1743. let args = args_iter
  1744. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1745. .collect::<Vec<Expression>>();
  1746. encode_many_with_selector(loc, selector, args, ns, vartab, cfg)
  1747. }
  1748. fn abi_encode_with_signature(
  1749. args: &[ast::Expression],
  1750. loc: &pt::Loc,
  1751. cfg: &mut ControlFlowGraph,
  1752. contract_no: usize,
  1753. func: Option<&Function>,
  1754. ns: &Namespace,
  1755. vartab: &mut Vartable,
  1756. opt: &Options,
  1757. ) -> Expression {
  1758. let mut args_iter = args.iter();
  1759. let hash_algorithm = if ns.target == Target::Solana {
  1760. ast::Builtin::Sha256
  1761. } else {
  1762. ast::Builtin::Keccak256
  1763. };
  1764. let hash = ast::Expression::Builtin {
  1765. loc: *loc,
  1766. tys: vec![Type::Bytes(32)],
  1767. kind: hash_algorithm,
  1768. args: vec![args_iter.next().unwrap().clone()],
  1769. };
  1770. let hash = expression(&hash, cfg, contract_no, func, ns, vartab, opt);
  1771. let selector = hash.cast(&Type::FunctionSelector, ns);
  1772. let args = args_iter
  1773. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1774. .collect::<Vec<Expression>>();
  1775. encode_many_with_selector(loc, selector, args, ns, vartab, cfg)
  1776. }
  1777. fn abi_encode_call(
  1778. args: &[ast::Expression],
  1779. cfg: &mut ControlFlowGraph,
  1780. contract_no: usize,
  1781. func: Option<&Function>,
  1782. ns: &Namespace,
  1783. vartab: &mut Vartable,
  1784. loc: &pt::Loc,
  1785. opt: &Options,
  1786. ) -> Expression {
  1787. let mut args_iter = args.iter();
  1788. let selector = expression(
  1789. &ast::Expression::Builtin {
  1790. loc: *loc,
  1791. tys: vec![Type::FunctionSelector],
  1792. kind: ast::Builtin::FunctionSelector,
  1793. args: vec![args_iter.next().unwrap().clone()],
  1794. },
  1795. cfg,
  1796. contract_no,
  1797. func,
  1798. ns,
  1799. vartab,
  1800. opt,
  1801. );
  1802. let args = args_iter
  1803. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  1804. .collect::<Vec<Expression>>();
  1805. encode_many_with_selector(loc, selector, args, ns, vartab, cfg)
  1806. }
  1807. fn builtin_evm_gasprice(
  1808. loc: &pt::Loc,
  1809. expr: &[ast::Expression],
  1810. cfg: &mut ControlFlowGraph,
  1811. contract_no: usize,
  1812. func: Option<&Function>,
  1813. ns: &Namespace,
  1814. vartab: &mut Vartable,
  1815. opt: &Options,
  1816. ) -> Expression {
  1817. let ty = Type::Value;
  1818. let gasprice = Expression::Builtin {
  1819. loc: *loc,
  1820. tys: vec![ty.clone()],
  1821. kind: Builtin::Gasprice,
  1822. args: vec![],
  1823. };
  1824. let units = expression(&expr[0], cfg, contract_no, func, ns, vartab, opt);
  1825. Expression::Multiply {
  1826. loc: *loc,
  1827. ty,
  1828. overflowing: true,
  1829. left: Box::new(units),
  1830. right: Box::new(gasprice),
  1831. }
  1832. }
  1833. fn expr_builtin(
  1834. args: &[ast::Expression],
  1835. cfg: &mut ControlFlowGraph,
  1836. contract_no: usize,
  1837. func: Option<&Function>,
  1838. ns: &Namespace,
  1839. vartab: &mut Vartable,
  1840. loc: &pt::Loc,
  1841. tys: &[Type],
  1842. builtin: ast::Builtin,
  1843. opt: &Options,
  1844. ) -> Expression {
  1845. match builtin {
  1846. ast::Builtin::WriteInt8
  1847. | ast::Builtin::WriteInt16LE
  1848. | ast::Builtin::WriteInt32LE
  1849. | ast::Builtin::WriteInt64LE
  1850. | ast::Builtin::WriteInt128LE
  1851. | ast::Builtin::WriteInt256LE
  1852. | ast::Builtin::WriteAddress
  1853. | ast::Builtin::WriteUint16LE
  1854. | ast::Builtin::WriteUint32LE
  1855. | ast::Builtin::WriteUint64LE
  1856. | ast::Builtin::WriteUint128LE
  1857. | ast::Builtin::WriteUint256LE => {
  1858. let buf = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1859. let offset = expression(&args[2], cfg, contract_no, func, ns, vartab, opt);
  1860. // range check
  1861. let cond = Expression::LessEqual {
  1862. loc: *loc,
  1863. signed: false,
  1864. left: Box::new(Expression::Add {
  1865. loc: *loc,
  1866. ty: Type::Uint(32),
  1867. overflowing: false,
  1868. left: Box::new(offset.clone()),
  1869. right: Box::new(Expression::NumberLiteral {
  1870. loc: *loc,
  1871. ty: Type::Uint(32),
  1872. value: BigInt::from(args[1].ty().bits(ns) / 8),
  1873. }),
  1874. }),
  1875. right: Box::new(Expression::Builtin {
  1876. loc: *loc,
  1877. tys: vec![Type::Uint(32)],
  1878. kind: Builtin::ArrayLength,
  1879. args: vec![buf.clone()],
  1880. }),
  1881. };
  1882. let out_of_bounds = cfg.new_basic_block("out_of_bounds".to_string());
  1883. let in_bounds = cfg.new_basic_block("in_bounds".to_string());
  1884. cfg.add(
  1885. vartab,
  1886. Instr::BranchCond {
  1887. cond,
  1888. true_block: in_bounds,
  1889. false_block: out_of_bounds,
  1890. },
  1891. );
  1892. cfg.set_basic_block(out_of_bounds);
  1893. log_runtime_error(
  1894. opt.log_runtime_errors,
  1895. "integer too large to write in buffer",
  1896. *loc,
  1897. cfg,
  1898. vartab,
  1899. ns,
  1900. );
  1901. assert_failure(loc, None, ns, cfg, vartab);
  1902. cfg.set_basic_block(in_bounds);
  1903. let value = expression(&args[1], cfg, contract_no, func, ns, vartab, opt);
  1904. cfg.add(vartab, Instr::WriteBuffer { buf, value, offset });
  1905. Expression::Undefined { ty: tys[0].clone() }
  1906. }
  1907. ast::Builtin::WriteBytes | ast::Builtin::WriteString => {
  1908. let buffer = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1909. let data = expression(&args[1], cfg, contract_no, func, ns, vartab, opt);
  1910. let offset = expression(&args[2], cfg, contract_no, func, ns, vartab, opt);
  1911. let size = Expression::Builtin {
  1912. loc: *loc,
  1913. tys: vec![Type::Uint(32)],
  1914. kind: Builtin::ArrayLength,
  1915. args: vec![data.clone()],
  1916. };
  1917. let cond = Expression::LessEqual {
  1918. loc: *loc,
  1919. signed: false,
  1920. left: Box::new(Expression::Add {
  1921. loc: *loc,
  1922. ty: Type::Uint(32),
  1923. overflowing: false,
  1924. left: Box::new(offset.clone()),
  1925. right: Box::new(size.clone()),
  1926. }),
  1927. right: Box::new(Expression::Builtin {
  1928. loc: *loc,
  1929. tys: vec![Type::Uint(32)],
  1930. kind: Builtin::ArrayLength,
  1931. args: vec![buffer.clone()],
  1932. }),
  1933. };
  1934. let in_bounds = cfg.new_basic_block("in_bounds".to_string());
  1935. let out_ouf_bounds = cfg.new_basic_block("out_of_bounds".to_string());
  1936. cfg.add(
  1937. vartab,
  1938. Instr::BranchCond {
  1939. cond,
  1940. true_block: in_bounds,
  1941. false_block: out_ouf_bounds,
  1942. },
  1943. );
  1944. cfg.set_basic_block(out_ouf_bounds);
  1945. log_runtime_error(
  1946. opt.log_runtime_errors,
  1947. "data does not fit into buffer",
  1948. *loc,
  1949. cfg,
  1950. vartab,
  1951. ns,
  1952. );
  1953. assert_failure(loc, None, ns, cfg, vartab);
  1954. cfg.set_basic_block(in_bounds);
  1955. let advanced_ptr = Expression::AdvancePointer {
  1956. pointer: Box::new(buffer),
  1957. bytes_offset: Box::new(offset),
  1958. };
  1959. cfg.add(
  1960. vartab,
  1961. Instr::MemCopy {
  1962. source: data,
  1963. destination: advanced_ptr,
  1964. bytes: size,
  1965. },
  1966. );
  1967. Expression::Undefined { ty: tys[0].clone() }
  1968. }
  1969. ast::Builtin::ReadInt8
  1970. | ast::Builtin::ReadInt16LE
  1971. | ast::Builtin::ReadInt32LE
  1972. | ast::Builtin::ReadInt64LE
  1973. | ast::Builtin::ReadInt128LE
  1974. | ast::Builtin::ReadInt256LE
  1975. | ast::Builtin::ReadAddress
  1976. | ast::Builtin::ReadUint16LE
  1977. | ast::Builtin::ReadUint32LE
  1978. | ast::Builtin::ReadUint64LE
  1979. | ast::Builtin::ReadUint128LE
  1980. | ast::Builtin::ReadUint256LE => {
  1981. let buf = expression(&args[0], cfg, contract_no, func, ns, vartab, opt);
  1982. let offset = expression(&args[1], cfg, contract_no, func, ns, vartab, opt);
  1983. // range check
  1984. let cond = Expression::LessEqual {
  1985. loc: *loc,
  1986. signed: false,
  1987. left: Box::new(Expression::Add {
  1988. loc: *loc,
  1989. ty: Type::Uint(32),
  1990. overflowing: false,
  1991. left: Box::new(offset.clone()),
  1992. right: Box::new(Expression::NumberLiteral {
  1993. loc: *loc,
  1994. ty: Type::Uint(32),
  1995. value: BigInt::from(tys[0].bits(ns) / 8),
  1996. }),
  1997. }),
  1998. right: Box::new(Expression::Builtin {
  1999. loc: *loc,
  2000. tys: vec![Type::Uint(32)],
  2001. kind: Builtin::ArrayLength,
  2002. args: vec![buf.clone()],
  2003. }),
  2004. };
  2005. let out_of_bounds = cfg.new_basic_block("out_of_bounds".to_string());
  2006. let in_bounds = cfg.new_basic_block("in_bounds".to_string());
  2007. cfg.add(
  2008. vartab,
  2009. Instr::BranchCond {
  2010. cond,
  2011. true_block: in_bounds,
  2012. false_block: out_of_bounds,
  2013. },
  2014. );
  2015. cfg.set_basic_block(out_of_bounds);
  2016. log_runtime_error(
  2017. opt.log_runtime_errors,
  2018. "read integer out of bounds",
  2019. *loc,
  2020. cfg,
  2021. vartab,
  2022. ns,
  2023. );
  2024. assert_failure(loc, None, ns, cfg, vartab);
  2025. cfg.set_basic_block(in_bounds);
  2026. Expression::Builtin {
  2027. loc: *loc,
  2028. tys: tys.to_vec(),
  2029. kind: (&builtin).into(),
  2030. args: vec![buf, offset],
  2031. }
  2032. }
  2033. ast::Builtin::AddMod | ast::Builtin::MulMod => {
  2034. let arguments: Vec<Expression> = args
  2035. .iter()
  2036. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  2037. .collect();
  2038. let temp = vartab.temp_anonymous(&tys[0]);
  2039. let zero = Expression::NumberLiteral {
  2040. loc: *loc,
  2041. ty: tys[0].clone(),
  2042. value: BigInt::zero(),
  2043. };
  2044. let cond = Expression::NotEqual {
  2045. loc: *loc,
  2046. left: Box::new(zero.clone()),
  2047. right: Box::new(arguments[2].clone()),
  2048. };
  2049. let true_block = cfg.new_basic_block("builtin_call".to_string());
  2050. let false_block = cfg.new_basic_block("zero".to_string());
  2051. let end_if = cfg.new_basic_block("end_if".to_string());
  2052. cfg.add(
  2053. vartab,
  2054. Instr::BranchCond {
  2055. cond,
  2056. true_block,
  2057. false_block,
  2058. },
  2059. );
  2060. cfg.set_basic_block(true_block);
  2061. vartab.new_dirty_tracker();
  2062. cfg.add(
  2063. vartab,
  2064. Instr::Set {
  2065. loc: *loc,
  2066. res: temp,
  2067. expr: Expression::Builtin {
  2068. loc: *loc,
  2069. tys: tys.to_vec(),
  2070. kind: (&builtin).into(),
  2071. args: arguments,
  2072. },
  2073. },
  2074. );
  2075. cfg.add(vartab, Instr::Branch { block: end_if });
  2076. cfg.set_basic_block(false_block);
  2077. cfg.add(
  2078. vartab,
  2079. Instr::Set {
  2080. loc: *loc,
  2081. res: temp,
  2082. expr: zero,
  2083. },
  2084. );
  2085. cfg.add(vartab, Instr::Branch { block: end_if });
  2086. cfg.set_phis(end_if, vartab.pop_dirty_tracker());
  2087. cfg.set_basic_block(end_if);
  2088. Expression::Variable {
  2089. loc: *loc,
  2090. ty: tys[0].clone(),
  2091. var_no: temp,
  2092. }
  2093. }
  2094. _ => {
  2095. let arguments: Vec<Expression> = args
  2096. .iter()
  2097. .map(|v| expression(v, cfg, contract_no, func, ns, vartab, opt))
  2098. .collect();
  2099. if !arguments.is_empty() && builtin == ast::Builtin::ArrayLength {
  2100. // If an array length instruction is called
  2101. // Get the variable it is assigned with
  2102. if let Expression::Variable { var_no, .. } = &arguments[0] {
  2103. // Now that we have its temp in the map, retrieve the temp var res from the map
  2104. if let Some(array_length_var) = cfg.array_lengths_temps.get(var_no) {
  2105. // If it's there, replace ArrayLength with the temp var
  2106. return Expression::Variable {
  2107. loc: *loc,
  2108. ty: Type::Uint(32),
  2109. var_no: *array_length_var,
  2110. };
  2111. }
  2112. }
  2113. }
  2114. Expression::Builtin {
  2115. loc: *loc,
  2116. tys: tys.to_vec(),
  2117. kind: (&builtin).into(),
  2118. args: arguments,
  2119. }
  2120. }
  2121. }
  2122. }
  2123. fn alloc_dynamic_array(
  2124. size: &ast::Expression,
  2125. cfg: &mut ControlFlowGraph,
  2126. contract_no: usize,
  2127. func: Option<&Function>,
  2128. ns: &Namespace,
  2129. vartab: &mut Vartable,
  2130. loc: &pt::Loc,
  2131. ty: &Type,
  2132. init: &Option<Vec<u8>>,
  2133. opt: &Options,
  2134. ) -> Expression {
  2135. let size = expression(size, cfg, contract_no, func, ns, vartab, opt);
  2136. Expression::AllocDynamicBytes {
  2137. loc: *loc,
  2138. ty: ty.clone(),
  2139. size: Box::new(size),
  2140. initializer: init.clone(),
  2141. }
  2142. }
  2143. fn add(
  2144. loc: &pt::Loc,
  2145. ty: &Type,
  2146. overflowing: bool,
  2147. left: &ast::Expression,
  2148. cfg: &mut ControlFlowGraph,
  2149. contract_no: usize,
  2150. func: Option<&Function>,
  2151. ns: &Namespace,
  2152. vartab: &mut Vartable,
  2153. right: &ast::Expression,
  2154. opt: &Options,
  2155. ) -> Expression {
  2156. Expression::Add {
  2157. loc: *loc,
  2158. ty: ty.clone(),
  2159. overflowing,
  2160. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  2161. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  2162. }
  2163. }
  2164. fn subtract(
  2165. loc: &pt::Loc,
  2166. ty: &Type,
  2167. overflowing: bool,
  2168. left: &ast::Expression,
  2169. cfg: &mut ControlFlowGraph,
  2170. contract_no: usize,
  2171. func: Option<&Function>,
  2172. ns: &Namespace,
  2173. vartab: &mut Vartable,
  2174. right: &ast::Expression,
  2175. opt: &Options,
  2176. ) -> Expression {
  2177. Expression::Subtract {
  2178. loc: *loc,
  2179. ty: ty.clone(),
  2180. overflowing,
  2181. left: Box::new(expression(left, cfg, contract_no, func, ns, vartab, opt)),
  2182. right: Box::new(expression(right, cfg, contract_no, func, ns, vartab, opt)),
  2183. }
  2184. }
  2185. fn checking_trunc(
  2186. loc: &pt::Loc,
  2187. expr: &ast::Expression,
  2188. ty: &Type,
  2189. cfg: &mut ControlFlowGraph,
  2190. contract_no: usize,
  2191. func: Option<&Function>,
  2192. ns: &Namespace,
  2193. vartab: &mut Vartable,
  2194. opt: &Options,
  2195. ) -> Expression {
  2196. let bits = match ty {
  2197. Type::Uint(bits) => *bits as u32,
  2198. Type::Value => ns.value_length as u32 * 8,
  2199. _ => unreachable!(),
  2200. };
  2201. let source_ty = expr.ty();
  2202. let overflow = Expression::NumberLiteral {
  2203. loc: *loc,
  2204. ty: source_ty.clone(),
  2205. value: BigInt::from(2u32).pow(bits),
  2206. };
  2207. let pos = vartab.temp(
  2208. &pt::Identifier {
  2209. name: "value".to_owned(),
  2210. loc: *loc,
  2211. },
  2212. &source_ty,
  2213. );
  2214. let expr = expression(expr, cfg, contract_no, func, ns, vartab, opt);
  2215. cfg.add(
  2216. vartab,
  2217. Instr::Set {
  2218. loc: expr.loc(),
  2219. res: pos,
  2220. expr,
  2221. },
  2222. );
  2223. let out_of_bounds = cfg.new_basic_block("out_of_bounds".to_string());
  2224. let in_bounds = cfg.new_basic_block("in_bounds".to_string());
  2225. cfg.add(
  2226. vartab,
  2227. Instr::BranchCond {
  2228. cond: Expression::MoreEqual {
  2229. loc: *loc,
  2230. signed: false,
  2231. left: Box::new(Expression::Variable {
  2232. loc: *loc,
  2233. ty: source_ty.clone(),
  2234. var_no: pos,
  2235. }),
  2236. right: Box::new(overflow),
  2237. },
  2238. true_block: out_of_bounds,
  2239. false_block: in_bounds,
  2240. },
  2241. );
  2242. cfg.set_basic_block(out_of_bounds);
  2243. log_runtime_error(
  2244. opt.log_runtime_errors,
  2245. "truncated type overflows",
  2246. *loc,
  2247. cfg,
  2248. vartab,
  2249. ns,
  2250. );
  2251. assert_failure(loc, None, ns, cfg, vartab);
  2252. cfg.set_basic_block(in_bounds);
  2253. Expression::Trunc {
  2254. loc: *loc,
  2255. ty: ty.clone(),
  2256. expr: Box::new(Expression::Variable {
  2257. loc: *loc,
  2258. ty: source_ty,
  2259. var_no: pos,
  2260. }),
  2261. }
  2262. }
  2263. fn format_string(
  2264. args: &[(FormatArg, ast::Expression)],
  2265. cfg: &mut ControlFlowGraph,
  2266. contract_no: usize,
  2267. func: Option<&Function>,
  2268. ns: &Namespace,
  2269. vartab: &mut Vartable,
  2270. loc: &pt::Loc,
  2271. opt: &Options,
  2272. ) -> Expression {
  2273. let args = args
  2274. .iter()
  2275. .map(|(spec, arg)| {
  2276. (
  2277. *spec,
  2278. expression(arg, cfg, contract_no, func, ns, vartab, opt),
  2279. )
  2280. })
  2281. .collect();
  2282. Expression::FormatString { loc: *loc, args }
  2283. }
  2284. fn conditional_operator(
  2285. loc: &pt::Loc,
  2286. ty: &Type,
  2287. cond: &ast::Expression,
  2288. cfg: &mut ControlFlowGraph,
  2289. contract_no: usize,
  2290. func: Option<&Function>,
  2291. ns: &Namespace,
  2292. vartab: &mut Vartable,
  2293. left: &ast::Expression,
  2294. right: &ast::Expression,
  2295. opt: &Options,
  2296. ) -> Expression {
  2297. let cond = expression(cond, cfg, contract_no, func, ns, vartab, opt);
  2298. let pos = vartab.temp(
  2299. &pt::Identifier {
  2300. name: "ternary_result".to_owned(),
  2301. loc: *loc,
  2302. },
  2303. ty,
  2304. );
  2305. vartab.new_dirty_tracker();
  2306. let left_block = cfg.new_basic_block("left_value".to_string());
  2307. let right_block = cfg.new_basic_block("right_value".to_string());
  2308. let done_block = cfg.new_basic_block("conditional_done".to_string());
  2309. cfg.add(
  2310. vartab,
  2311. Instr::BranchCond {
  2312. cond,
  2313. true_block: left_block,
  2314. false_block: right_block,
  2315. },
  2316. );
  2317. cfg.set_basic_block(left_block);
  2318. let expr = expression(left, cfg, contract_no, func, ns, vartab, opt);
  2319. cfg.add(
  2320. vartab,
  2321. Instr::Set {
  2322. loc: expr.loc(),
  2323. res: pos,
  2324. expr,
  2325. },
  2326. );
  2327. cfg.add(vartab, Instr::Branch { block: done_block });
  2328. cfg.set_basic_block(right_block);
  2329. let expr = expression(right, cfg, contract_no, func, ns, vartab, opt);
  2330. cfg.add(
  2331. vartab,
  2332. Instr::Set {
  2333. loc: expr.loc(),
  2334. res: pos,
  2335. expr,
  2336. },
  2337. );
  2338. cfg.add(vartab, Instr::Branch { block: done_block });
  2339. cfg.set_basic_block(done_block);
  2340. cfg.set_phis(done_block, vartab.pop_dirty_tracker());
  2341. Expression::Variable {
  2342. loc: *loc,
  2343. ty: ty.clone(),
  2344. var_no: pos,
  2345. }
  2346. }
  2347. fn interfaceid(ns: &Namespace, contract_no: usize, loc: &pt::Loc) -> Expression {
  2348. let selector_len = ns.target.selector_length();
  2349. let mut id = vec![0u8; selector_len as usize];
  2350. for func_no in &ns.contracts[contract_no].functions {
  2351. let func = &ns.functions[*func_no];
  2352. if func.ty == pt::FunctionTy::Function {
  2353. let selector = func.selector(ns, &contract_no);
  2354. debug_assert_eq!(id.len(), selector.len());
  2355. for (i, e) in id.iter_mut().enumerate() {
  2356. *e ^= selector[i];
  2357. }
  2358. }
  2359. }
  2360. Expression::BytesLiteral {
  2361. loc: *loc,
  2362. ty: Type::Bytes(selector_len),
  2363. value: id.to_vec(),
  2364. }
  2365. }
  2366. pub fn assign_single(
  2367. left: &ast::Expression,
  2368. cfg_right: Expression,
  2369. cfg: &mut ControlFlowGraph,
  2370. contract_no: usize,
  2371. func: Option<&Function>,
  2372. ns: &Namespace,
  2373. vartab: &mut Vartable,
  2374. opt: &Options,
  2375. ) -> Expression {
  2376. match left {
  2377. ast::Expression::Variable { loc, ty, var_no } => {
  2378. cfg.add(
  2379. vartab,
  2380. Instr::Set {
  2381. loc: *loc,
  2382. res: *var_no,
  2383. expr: cfg_right,
  2384. },
  2385. );
  2386. Expression::Variable {
  2387. loc: *loc,
  2388. ty: ty.clone(),
  2389. var_no: *var_no,
  2390. }
  2391. }
  2392. _ => {
  2393. let left_ty = left.ty();
  2394. let ty = left_ty.deref_memory();
  2395. let pos = vartab.temp_anonymous(ty);
  2396. // Set a subscript in storage bytes needs special handling
  2397. let set_storage_bytes = if let ast::Expression::Subscript { array_ty, .. } = &left {
  2398. array_ty.is_storage_bytes()
  2399. } else {
  2400. false
  2401. };
  2402. let dest = expression(left, cfg, contract_no, func, ns, vartab, opt);
  2403. let cfg_right =
  2404. if !left_ty.is_contract_storage() && cfg_right.ty().is_fixed_reference_type(ns) {
  2405. Expression::Load {
  2406. loc: pt::Loc::Codegen,
  2407. ty: cfg_right.ty(),
  2408. expr: Box::new(cfg_right),
  2409. }
  2410. } else {
  2411. cfg_right
  2412. };
  2413. cfg.add(
  2414. vartab,
  2415. Instr::Set {
  2416. loc: pt::Loc::Codegen,
  2417. res: pos,
  2418. expr: cfg_right,
  2419. },
  2420. );
  2421. match left_ty {
  2422. Type::StorageRef(..) if set_storage_bytes => {
  2423. if let Expression::Subscript {
  2424. expr: array, index, ..
  2425. } = dest
  2426. {
  2427. // Set a byte in a byte array
  2428. cfg.add(
  2429. vartab,
  2430. Instr::SetStorageBytes {
  2431. value: Expression::Variable {
  2432. loc: left.loc(),
  2433. ty: ty.clone(),
  2434. var_no: pos,
  2435. },
  2436. storage: *array,
  2437. offset: *index,
  2438. },
  2439. );
  2440. } else {
  2441. unreachable!();
  2442. }
  2443. }
  2444. Type::StorageRef(..) => {
  2445. cfg.add(
  2446. vartab,
  2447. Instr::SetStorage {
  2448. value: Expression::Variable {
  2449. loc: left.loc(),
  2450. ty: ty.clone(),
  2451. var_no: pos,
  2452. },
  2453. ty: ty.deref_any().clone(),
  2454. storage: dest,
  2455. },
  2456. );
  2457. }
  2458. Type::Ref(_) => {
  2459. cfg.add(
  2460. vartab,
  2461. Instr::Store {
  2462. dest,
  2463. data: Expression::Variable {
  2464. loc: Loc::Codegen,
  2465. ty: ty.clone(),
  2466. var_no: pos,
  2467. },
  2468. },
  2469. );
  2470. }
  2471. _ => unreachable!(),
  2472. }
  2473. Expression::Variable {
  2474. loc: left.loc(),
  2475. ty: ty.clone(),
  2476. var_no: pos,
  2477. }
  2478. }
  2479. }
  2480. }
  2481. /// Convert a function call expression to CFG in expression context
  2482. pub fn emit_function_call(
  2483. expr: &ast::Expression,
  2484. caller_contract_no: usize,
  2485. cfg: &mut ControlFlowGraph,
  2486. func: Option<&Function>,
  2487. ns: &Namespace,
  2488. vartab: &mut Vartable,
  2489. opt: &Options,
  2490. ) -> Vec<Expression> {
  2491. match expr {
  2492. ast::Expression::InternalFunctionCall { function, args, .. } => {
  2493. if let ast::Expression::InternalFunction {
  2494. function_no,
  2495. signature,
  2496. ..
  2497. } = function.as_ref()
  2498. {
  2499. let args = args
  2500. .iter()
  2501. .map(|a| expression(a, cfg, caller_contract_no, func, ns, vartab, opt))
  2502. .collect();
  2503. let function_no = if let Some(signature) = signature {
  2504. ns.contracts[caller_contract_no].virtual_functions[signature]
  2505. } else {
  2506. *function_no
  2507. };
  2508. let ftype = &ns.functions[function_no];
  2509. let call = if ns.functions[function_no].loc == pt::Loc::Builtin {
  2510. InternalCallTy::Builtin {
  2511. ast_func_no: function_no,
  2512. }
  2513. } else {
  2514. let cfg_no = ns.contracts[caller_contract_no].all_functions[&function_no];
  2515. InternalCallTy::Static { cfg_no }
  2516. };
  2517. if !ftype.returns.is_empty() {
  2518. let mut res = Vec::new();
  2519. let mut returns = Vec::new();
  2520. let mut return_tys = Vec::new();
  2521. for ret in &*ftype.returns {
  2522. let id = pt::Identifier {
  2523. loc: ret.loc,
  2524. name: ret.name_as_str().to_owned(),
  2525. };
  2526. let temp_pos = vartab.temp(&id, &ret.ty);
  2527. return_tys.push(ret.ty.clone());
  2528. res.push(temp_pos);
  2529. returns.push(Expression::Variable {
  2530. loc: id.loc,
  2531. ty: ret.ty.clone(),
  2532. var_no: temp_pos,
  2533. });
  2534. }
  2535. cfg.add(
  2536. vartab,
  2537. Instr::Call {
  2538. res,
  2539. call,
  2540. args,
  2541. return_tys,
  2542. },
  2543. );
  2544. returns
  2545. } else {
  2546. cfg.add(
  2547. vartab,
  2548. Instr::Call {
  2549. res: Vec::new(),
  2550. return_tys: Vec::new(),
  2551. call,
  2552. args,
  2553. },
  2554. );
  2555. vec![Expression::Poison]
  2556. }
  2557. } else if let Type::InternalFunction { returns, .. } = function.ty().deref_any() {
  2558. let cfg_expr = expression(function, cfg, caller_contract_no, func, ns, vartab, opt);
  2559. let args = args
  2560. .iter()
  2561. .map(|a| expression(a, cfg, caller_contract_no, func, ns, vartab, opt))
  2562. .collect();
  2563. if !returns.is_empty() {
  2564. let mut res = Vec::new();
  2565. let mut return_values = Vec::new();
  2566. let mut return_tys = Vec::new();
  2567. for ty in returns {
  2568. let id = pt::Identifier {
  2569. loc: pt::Loc::Codegen,
  2570. name: String::new(),
  2571. };
  2572. let temp_pos = vartab.temp(&id, ty);
  2573. res.push(temp_pos);
  2574. return_tys.push(ty.clone());
  2575. return_values.push(Expression::Variable {
  2576. loc: id.loc,
  2577. ty: ty.clone(),
  2578. var_no: temp_pos,
  2579. });
  2580. }
  2581. cfg.add(
  2582. vartab,
  2583. Instr::Call {
  2584. res,
  2585. call: InternalCallTy::Dynamic(cfg_expr),
  2586. return_tys,
  2587. args,
  2588. },
  2589. );
  2590. return_values
  2591. } else {
  2592. cfg.add(
  2593. vartab,
  2594. Instr::Call {
  2595. res: Vec::new(),
  2596. return_tys: Vec::new(),
  2597. call: InternalCallTy::Dynamic(cfg_expr),
  2598. args,
  2599. },
  2600. );
  2601. vec![Expression::Poison]
  2602. }
  2603. } else {
  2604. unreachable!();
  2605. }
  2606. }
  2607. ast::Expression::ExternalFunctionCallRaw {
  2608. loc,
  2609. address,
  2610. args,
  2611. call_args,
  2612. ty,
  2613. } => {
  2614. let args = expression(args, cfg, caller_contract_no, func, ns, vartab, opt);
  2615. let address = expression(address, cfg, caller_contract_no, func, ns, vartab, opt);
  2616. let gas = if let Some(gas) = &call_args.gas {
  2617. expression(gas, cfg, caller_contract_no, func, ns, vartab, opt)
  2618. } else {
  2619. default_gas(ns)
  2620. };
  2621. let value = if let Some(value) = &call_args.value {
  2622. expression(value, cfg, caller_contract_no, func, ns, vartab, opt)
  2623. } else {
  2624. Expression::NumberLiteral {
  2625. loc: pt::Loc::Codegen,
  2626. ty: Type::Value,
  2627. value: BigInt::zero(),
  2628. }
  2629. };
  2630. let accounts = call_args
  2631. .accounts
  2632. .as_ref()
  2633. .map(|expr| expression(expr, cfg, caller_contract_no, func, ns, vartab, opt));
  2634. let seeds = call_args
  2635. .seeds
  2636. .as_ref()
  2637. .map(|expr| expression(expr, cfg, caller_contract_no, func, ns, vartab, opt));
  2638. let success = vartab.temp_name("success", &Type::Bool);
  2639. cfg.add(
  2640. vartab,
  2641. Instr::ExternalCall {
  2642. success: Some(success),
  2643. address: Some(address),
  2644. payload: args,
  2645. value,
  2646. accounts,
  2647. seeds,
  2648. gas,
  2649. callty: ty.clone(),
  2650. contract_function_no: None,
  2651. },
  2652. );
  2653. vec![
  2654. Expression::Variable {
  2655. loc: *loc,
  2656. ty: Type::Bool,
  2657. var_no: success,
  2658. },
  2659. Expression::ReturnData { loc: *loc },
  2660. ]
  2661. }
  2662. ast::Expression::ExternalFunctionCall {
  2663. loc,
  2664. function,
  2665. args,
  2666. returns,
  2667. call_args,
  2668. ..
  2669. } => {
  2670. if let ast::Expression::ExternalFunction {
  2671. function_no,
  2672. address,
  2673. ..
  2674. } = function.as_ref()
  2675. {
  2676. let dest_func = &ns.functions[*function_no];
  2677. let contract_function_no = dest_func
  2678. .contract_no
  2679. .map(|contract_no| (contract_no, *function_no));
  2680. let mut tys: Vec<Type> = args.iter().map(|a| a.ty()).collect();
  2681. let mut args: Vec<Expression> = args
  2682. .iter()
  2683. .map(|a| expression(a, cfg, caller_contract_no, func, ns, vartab, opt))
  2684. .collect();
  2685. let address = expression(address, cfg, caller_contract_no, func, ns, vartab, opt);
  2686. let gas = if let Some(gas) = &call_args.gas {
  2687. expression(gas, cfg, caller_contract_no, func, ns, vartab, opt)
  2688. } else {
  2689. default_gas(ns)
  2690. };
  2691. let accounts = call_args
  2692. .accounts
  2693. .as_ref()
  2694. .map(|expr| expression(expr, cfg, caller_contract_no, func, ns, vartab, opt));
  2695. let seeds = call_args
  2696. .seeds
  2697. .as_ref()
  2698. .map(|expr| expression(expr, cfg, caller_contract_no, func, ns, vartab, opt));
  2699. let value = if let Some(value) = &call_args.value {
  2700. expression(value, cfg, caller_contract_no, func, ns, vartab, opt)
  2701. } else {
  2702. Expression::NumberLiteral {
  2703. loc: pt::Loc::Codegen,
  2704. ty: Type::Value,
  2705. value: BigInt::zero(),
  2706. }
  2707. };
  2708. let selector = dest_func.selector(ns, &caller_contract_no);
  2709. tys.insert(0, Type::Bytes(selector.len() as u8));
  2710. args.insert(
  2711. 0,
  2712. Expression::BytesLiteral {
  2713. loc: *loc,
  2714. ty: Type::Bytes(selector.len() as u8),
  2715. value: selector,
  2716. },
  2717. );
  2718. let (payload, _) = abi_encode(loc, args, ns, vartab, cfg, false);
  2719. cfg.add(
  2720. vartab,
  2721. Instr::ExternalCall {
  2722. success: None,
  2723. accounts,
  2724. address: Some(address),
  2725. payload,
  2726. seeds,
  2727. value,
  2728. gas,
  2729. callty: CallTy::Regular,
  2730. contract_function_no,
  2731. },
  2732. );
  2733. // If the first element of returns is Void, we can discard the returns
  2734. if !dest_func.returns.is_empty() && returns[0] != Type::Void {
  2735. let tys = dest_func
  2736. .returns
  2737. .iter()
  2738. .map(|e| e.ty.clone())
  2739. .collect::<Vec<Type>>();
  2740. abi_decode(
  2741. loc,
  2742. &Expression::ReturnData { loc: *loc },
  2743. &tys,
  2744. ns,
  2745. vartab,
  2746. cfg,
  2747. None,
  2748. )
  2749. } else {
  2750. vec![Expression::Poison]
  2751. }
  2752. } else if let Type::ExternalFunction {
  2753. returns: func_returns,
  2754. ..
  2755. } = function.ty()
  2756. {
  2757. let mut tys: Vec<Type> = args.iter().map(|a| a.ty()).collect();
  2758. let mut args = args
  2759. .iter()
  2760. .map(|a| expression(a, cfg, caller_contract_no, func, ns, vartab, opt))
  2761. .collect::<Vec<Expression>>();
  2762. let function = expression(function, cfg, caller_contract_no, func, ns, vartab, opt);
  2763. let gas = if let Some(gas) = &call_args.gas {
  2764. expression(gas, cfg, caller_contract_no, func, ns, vartab, opt)
  2765. } else {
  2766. default_gas(ns)
  2767. };
  2768. let value = if let Some(value) = &call_args.value {
  2769. expression(value, cfg, caller_contract_no, func, ns, vartab, opt)
  2770. } else {
  2771. Expression::NumberLiteral {
  2772. loc: pt::Loc::Codegen,
  2773. ty: Type::Value,
  2774. value: BigInt::zero(),
  2775. }
  2776. };
  2777. let selector = function.external_function_selector();
  2778. let address = function.external_function_address();
  2779. tys.insert(0, Type::Bytes(ns.target.selector_length()));
  2780. args.insert(0, selector);
  2781. let (payload, _) = abi_encode(loc, args, ns, vartab, cfg, false);
  2782. cfg.add(
  2783. vartab,
  2784. Instr::ExternalCall {
  2785. success: None,
  2786. accounts: None,
  2787. seeds: None,
  2788. address: Some(address),
  2789. payload,
  2790. value,
  2791. gas,
  2792. callty: CallTy::Regular,
  2793. contract_function_no: None,
  2794. },
  2795. );
  2796. if !func_returns.is_empty() && returns[0] != Type::Void {
  2797. abi_decode(
  2798. loc,
  2799. &Expression::ReturnData { loc: *loc },
  2800. returns,
  2801. ns,
  2802. vartab,
  2803. cfg,
  2804. None,
  2805. )
  2806. } else {
  2807. vec![Expression::Poison]
  2808. }
  2809. } else {
  2810. unreachable!();
  2811. }
  2812. }
  2813. ast::Expression::Builtin {
  2814. loc,
  2815. tys,
  2816. kind: ast::Builtin::AbiDecode,
  2817. args,
  2818. } => {
  2819. let data = expression(&args[0], cfg, caller_contract_no, func, ns, vartab, opt);
  2820. abi_decode(loc, &data, tys, ns, vartab, cfg, None)
  2821. }
  2822. _ => unreachable!(),
  2823. }
  2824. }
  2825. pub fn default_gas(ns: &Namespace) -> Expression {
  2826. Expression::NumberLiteral {
  2827. loc: pt::Loc::Codegen,
  2828. ty: Type::Uint(64),
  2829. // See EIP150
  2830. value: if ns.target == Target::EVM {
  2831. BigInt::from(i64::MAX)
  2832. } else {
  2833. BigInt::zero()
  2834. },
  2835. }
  2836. }
  2837. /// Codegen for an array subscript expression
  2838. fn array_subscript(
  2839. loc: &pt::Loc,
  2840. elem_ty: &Type,
  2841. array_ty: &Type,
  2842. array: &ast::Expression,
  2843. index: &ast::Expression,
  2844. cfg: &mut ControlFlowGraph,
  2845. contract_no: usize,
  2846. func: Option<&Function>,
  2847. ns: &Namespace,
  2848. vartab: &mut Vartable,
  2849. opt: &Options,
  2850. ) -> Expression {
  2851. if array_ty.is_storage_bytes() {
  2852. return Expression::Subscript {
  2853. loc: *loc,
  2854. ty: elem_ty.clone(),
  2855. array_ty: array_ty.clone(),
  2856. expr: Box::new(expression(array, cfg, contract_no, func, ns, vartab, opt)),
  2857. index: Box::new(expression(index, cfg, contract_no, func, ns, vartab, opt)),
  2858. };
  2859. }
  2860. if array_ty.is_mapping() {
  2861. let array = expression(array, cfg, contract_no, func, ns, vartab, opt);
  2862. let index = expression(index, cfg, contract_no, func, ns, vartab, opt);
  2863. return if ns.target == Target::Solana {
  2864. Expression::Subscript {
  2865. loc: *loc,
  2866. ty: elem_ty.clone(),
  2867. array_ty: array_ty.clone(),
  2868. expr: Box::new(array),
  2869. index: Box::new(index),
  2870. }
  2871. } else {
  2872. Expression::Keccak256 {
  2873. loc: *loc,
  2874. ty: array_ty.clone(),
  2875. exprs: vec![array, index],
  2876. }
  2877. };
  2878. }
  2879. let mut array = expression(array, cfg, contract_no, func, ns, vartab, opt);
  2880. let index_ty = index.ty();
  2881. let index = expression(index, cfg, contract_no, func, ns, vartab, opt);
  2882. let index_loc = index.loc();
  2883. let index_width = index_ty.bits(ns);
  2884. let array_length = match array_ty.deref_any() {
  2885. Type::Bytes(n) => {
  2886. let ast_bigint = bigint_to_expression(
  2887. &array.loc(),
  2888. &BigInt::from(*n),
  2889. ns,
  2890. &mut Diagnostics::default(),
  2891. ResolveTo::Unknown,
  2892. None,
  2893. )
  2894. .unwrap();
  2895. expression(&ast_bigint, cfg, contract_no, func, ns, vartab, opt)
  2896. }
  2897. Type::Array(..) => match array_ty.array_length() {
  2898. None => {
  2899. if let Type::StorageRef(..) = array_ty {
  2900. if ns.target == Target::Solana {
  2901. Expression::StorageArrayLength {
  2902. loc: *loc,
  2903. ty: ns.storage_type(),
  2904. array: Box::new(array.clone()),
  2905. elem_ty: array_ty.storage_array_elem().deref_into(),
  2906. }
  2907. } else {
  2908. let array_length =
  2909. load_storage(loc, &Type::Uint(256), array.clone(), cfg, vartab);
  2910. array = Expression::Keccak256 {
  2911. loc: *loc,
  2912. ty: Type::Uint(256),
  2913. exprs: vec![array],
  2914. };
  2915. array_length
  2916. }
  2917. } else {
  2918. // If a subscript is encountered array length will be called
  2919. // Return array length by default
  2920. let mut returned = Expression::Builtin {
  2921. loc: *loc,
  2922. tys: vec![Type::Uint(32)],
  2923. kind: Builtin::ArrayLength,
  2924. args: vec![array.clone()],
  2925. };
  2926. if let Expression::Variable {
  2927. loc, var_no: num, ..
  2928. } = &array
  2929. {
  2930. // If the size is known (is in cfg.array_length_map), do the replacement
  2931. if let Some(array_length_var) = cfg.array_lengths_temps.get(num) {
  2932. returned = Expression::Variable {
  2933. loc: *loc,
  2934. ty: Type::Uint(32),
  2935. var_no: *array_length_var,
  2936. };
  2937. }
  2938. }
  2939. returned
  2940. }
  2941. }
  2942. Some(l) => {
  2943. let ast_big_int = bigint_to_expression(
  2944. loc,
  2945. l,
  2946. ns,
  2947. &mut Diagnostics::default(),
  2948. ResolveTo::Unknown,
  2949. None,
  2950. )
  2951. .unwrap();
  2952. expression(&ast_big_int, cfg, contract_no, func, ns, vartab, opt)
  2953. }
  2954. },
  2955. Type::DynamicBytes => Expression::Builtin {
  2956. loc: *loc,
  2957. tys: vec![Type::Uint(32)],
  2958. kind: Builtin::ArrayLength,
  2959. args: vec![array.clone()],
  2960. },
  2961. _ => {
  2962. unreachable!();
  2963. }
  2964. };
  2965. let array_width = array_length.ty().bits(ns);
  2966. let width = std::cmp::max(array_width, index.ty().bits(ns));
  2967. let coerced_ty = Type::Uint(width);
  2968. let pos = vartab.temp(
  2969. &pt::Identifier {
  2970. name: "index".to_owned(),
  2971. loc: *loc,
  2972. },
  2973. &coerced_ty,
  2974. );
  2975. let expr = index.cast(&coerced_ty, ns);
  2976. cfg.add(
  2977. vartab,
  2978. Instr::Set {
  2979. loc: expr.loc(),
  2980. res: pos,
  2981. expr,
  2982. },
  2983. );
  2984. // If the array is fixed length and the index also constant, the
  2985. // branch will be optimized away.
  2986. let out_of_bounds = cfg.new_basic_block("out_of_bounds".to_string());
  2987. let in_bounds = cfg.new_basic_block("in_bounds".to_string());
  2988. cfg.add(
  2989. vartab,
  2990. Instr::BranchCond {
  2991. cond: Expression::MoreEqual {
  2992. loc: *loc,
  2993. signed: false,
  2994. left: Box::new(Expression::Variable {
  2995. loc: index_loc,
  2996. ty: coerced_ty.clone(),
  2997. var_no: pos,
  2998. }),
  2999. right: Box::new(array_length.cast(&coerced_ty, ns)),
  3000. },
  3001. true_block: out_of_bounds,
  3002. false_block: in_bounds,
  3003. },
  3004. );
  3005. cfg.set_basic_block(out_of_bounds);
  3006. log_runtime_error(
  3007. opt.log_runtime_errors,
  3008. "array index out of bounds",
  3009. *loc,
  3010. cfg,
  3011. vartab,
  3012. ns,
  3013. );
  3014. assert_failure(loc, None, ns, cfg, vartab);
  3015. cfg.set_basic_block(in_bounds);
  3016. if let Type::Bytes(array_length) = array_ty.deref_any() {
  3017. let res_ty = Type::Bytes(1);
  3018. let from_ty = Type::Bytes(*array_length);
  3019. let index_ty = Type::Uint(*array_length as u16 * 8);
  3020. let to_width = array_ty.bits(ns);
  3021. let shift_arg_raw = Expression::Variable {
  3022. loc: index_loc,
  3023. ty: coerced_ty.clone(),
  3024. var_no: pos,
  3025. };
  3026. let shift_arg = match index_width.cmp(&to_width) {
  3027. Ordering::Equal => shift_arg_raw,
  3028. Ordering::Less => Expression::ZeroExt {
  3029. loc: *loc,
  3030. ty: index_ty.clone(),
  3031. expr: shift_arg_raw.into(),
  3032. },
  3033. Ordering::Greater => Expression::Trunc {
  3034. loc: *loc,
  3035. ty: index_ty.clone(),
  3036. expr: shift_arg_raw.into(),
  3037. },
  3038. };
  3039. return Expression::Trunc {
  3040. loc: *loc,
  3041. ty: res_ty,
  3042. expr: Expression::ShiftRight {
  3043. loc: *loc,
  3044. ty: from_ty,
  3045. left: array.into(),
  3046. right: Expression::ShiftLeft {
  3047. loc: *loc,
  3048. ty: index_ty.clone(),
  3049. left: Box::new(Expression::Subtract {
  3050. loc: *loc,
  3051. ty: index_ty.clone(),
  3052. overflowing: true,
  3053. left: Expression::NumberLiteral {
  3054. loc: *loc,
  3055. ty: index_ty.clone(),
  3056. value: BigInt::from_u8(array_length - 1).unwrap(),
  3057. }
  3058. .into(),
  3059. right: shift_arg.into(),
  3060. }),
  3061. right: Expression::NumberLiteral {
  3062. loc: *loc,
  3063. ty: index_ty,
  3064. value: BigInt::from_u8(3).unwrap(),
  3065. }
  3066. .into(),
  3067. }
  3068. .into(),
  3069. signed: false,
  3070. }
  3071. .into(),
  3072. };
  3073. }
  3074. if let Type::StorageRef(_, ty) = &array_ty {
  3075. let elem_ty = ty.storage_array_elem();
  3076. let slot_ty = ns.storage_type();
  3077. if ns.target == Target::Solana {
  3078. if ty.array_length().is_some() && ty.is_sparse_solana(ns) {
  3079. let index = Expression::Variable {
  3080. loc: index_loc,
  3081. ty: coerced_ty,
  3082. var_no: pos,
  3083. }
  3084. .cast(&Type::Uint(256), ns);
  3085. Expression::Subscript {
  3086. loc: *loc,
  3087. ty: elem_ty,
  3088. array_ty: array_ty.clone(),
  3089. expr: Box::new(array),
  3090. index: Box::new(index),
  3091. }
  3092. } else {
  3093. let index = Expression::Variable {
  3094. loc: index_loc,
  3095. ty: coerced_ty,
  3096. var_no: pos,
  3097. }
  3098. .cast(&slot_ty, ns);
  3099. if ty.array_length().is_some() {
  3100. // fixed length array
  3101. let elem_size = elem_ty.deref_any().solana_storage_size(ns);
  3102. Expression::Add {
  3103. loc: *loc,
  3104. ty: elem_ty,
  3105. overflowing: true,
  3106. left: Box::new(array),
  3107. right: Box::new(Expression::Multiply {
  3108. loc: *loc,
  3109. ty: slot_ty.clone(),
  3110. overflowing: true,
  3111. left: Box::new(index),
  3112. right: Box::new(Expression::NumberLiteral {
  3113. loc: *loc,
  3114. ty: slot_ty,
  3115. value: elem_size,
  3116. }),
  3117. }),
  3118. }
  3119. } else {
  3120. Expression::Subscript {
  3121. loc: *loc,
  3122. ty: elem_ty,
  3123. array_ty: array_ty.clone(),
  3124. expr: Box::new(array),
  3125. index: Box::new(index),
  3126. }
  3127. }
  3128. }
  3129. } else {
  3130. let elem_size = elem_ty.storage_slots(ns);
  3131. if let Expression::NumberLiteral {
  3132. value: arr_length, ..
  3133. } = &array_length
  3134. {
  3135. if arr_length.mul(elem_size.clone()).to_u64().is_some() {
  3136. // we need to calculate the storage offset. If this can be done with 64 bit
  3137. // arithmetic it will be much more efficient on wasm
  3138. return Expression::Add {
  3139. loc: *loc,
  3140. ty: elem_ty,
  3141. overflowing: true,
  3142. left: Box::new(array),
  3143. right: Box::new(Expression::ZeroExt {
  3144. loc: *loc,
  3145. ty: slot_ty,
  3146. expr: Box::new(Expression::Multiply {
  3147. loc: *loc,
  3148. ty: Type::Uint(64),
  3149. overflowing: true,
  3150. left: Box::new(
  3151. Expression::Variable {
  3152. loc: index_loc,
  3153. ty: coerced_ty,
  3154. var_no: pos,
  3155. }
  3156. .cast(&Type::Uint(64), ns),
  3157. ),
  3158. right: Box::new(Expression::NumberLiteral {
  3159. loc: *loc,
  3160. ty: Type::Uint(64),
  3161. value: elem_size,
  3162. }),
  3163. }),
  3164. }),
  3165. };
  3166. }
  3167. }
  3168. array_offset(
  3169. loc,
  3170. array,
  3171. Expression::Variable {
  3172. loc: index_loc,
  3173. ty: coerced_ty,
  3174. var_no: pos,
  3175. }
  3176. .cast(&ns.storage_type(), ns),
  3177. elem_ty,
  3178. ns,
  3179. )
  3180. }
  3181. } else {
  3182. match array_ty.deref_memory() {
  3183. Type::DynamicBytes | Type::Array(..) => Expression::Subscript {
  3184. loc: *loc,
  3185. ty: elem_ty.clone(),
  3186. array_ty: array_ty.clone(),
  3187. expr: Box::new(array),
  3188. index: Box::new(Expression::Variable {
  3189. loc: index_loc,
  3190. ty: coerced_ty,
  3191. var_no: pos,
  3192. }),
  3193. },
  3194. _ => {
  3195. // should not happen as type-checking already done
  3196. unreachable!();
  3197. }
  3198. }
  3199. }
  3200. }
  3201. fn string_location(
  3202. loc: &StringLocation<ast::Expression>,
  3203. cfg: &mut ControlFlowGraph,
  3204. contract_no: usize,
  3205. func: Option<&Function>,
  3206. ns: &Namespace,
  3207. vartab: &mut Vartable,
  3208. opt: &Options,
  3209. ) -> StringLocation<Expression> {
  3210. match loc {
  3211. StringLocation::RunTime(s) => StringLocation::RunTime(Box::new(expression(
  3212. s,
  3213. cfg,
  3214. contract_no,
  3215. func,
  3216. ns,
  3217. vartab,
  3218. opt,
  3219. ))),
  3220. StringLocation::CompileTime(vec) => StringLocation::CompileTime(vec.clone()),
  3221. }
  3222. }
  3223. // Generate a load from storage instruction
  3224. pub fn load_storage(
  3225. loc: &pt::Loc,
  3226. ty: &Type,
  3227. storage: Expression,
  3228. cfg: &mut ControlFlowGraph,
  3229. vartab: &mut Vartable,
  3230. ) -> Expression {
  3231. let res = vartab.temp_anonymous(ty);
  3232. cfg.add(
  3233. vartab,
  3234. Instr::LoadStorage {
  3235. res,
  3236. ty: ty.clone(),
  3237. storage,
  3238. },
  3239. );
  3240. Expression::Variable {
  3241. loc: *loc,
  3242. ty: ty.clone(),
  3243. var_no: res,
  3244. }
  3245. }
  3246. fn array_literal_to_memory_array(
  3247. loc: &pt::Loc,
  3248. expr: &Expression,
  3249. ty: &Type,
  3250. cfg: &mut ControlFlowGraph,
  3251. vartab: &mut Vartable,
  3252. ) -> Expression {
  3253. let memory_array = vartab.temp_anonymous(ty);
  3254. let elem_ty = ty.array_elem();
  3255. let dims = expr.ty().array_length().unwrap().clone();
  3256. let array_size = Expression::NumberLiteral {
  3257. loc: *loc,
  3258. ty: Type::Uint(32),
  3259. value: dims,
  3260. };
  3261. cfg.add(
  3262. vartab,
  3263. Instr::Set {
  3264. loc: *loc,
  3265. res: memory_array,
  3266. expr: Expression::AllocDynamicBytes {
  3267. loc: *loc,
  3268. ty: ty.clone(),
  3269. size: Box::new(array_size.clone()),
  3270. initializer: None,
  3271. },
  3272. },
  3273. );
  3274. let elements = if let Expression::ArrayLiteral { values: items, .. } = expr {
  3275. items
  3276. } else {
  3277. unreachable!()
  3278. };
  3279. for (item_no, item) in elements.iter().enumerate() {
  3280. cfg.add(
  3281. vartab,
  3282. Instr::Store {
  3283. dest: Expression::Subscript {
  3284. loc: *loc,
  3285. ty: Type::Ref(Box::new(elem_ty.clone())),
  3286. array_ty: ty.clone(),
  3287. expr: Box::new(Expression::Variable {
  3288. loc: *loc,
  3289. ty: ty.clone(),
  3290. var_no: memory_array,
  3291. }),
  3292. index: Box::new(Expression::NumberLiteral {
  3293. loc: *loc,
  3294. ty: Type::Uint(32),
  3295. value: BigInt::from(item_no),
  3296. }),
  3297. },
  3298. data: item.clone(),
  3299. },
  3300. );
  3301. }
  3302. let temp_res = vartab.temp_name("array_length", &Type::Uint(32));
  3303. cfg.add(
  3304. vartab,
  3305. Instr::Set {
  3306. loc: Loc::Codegen,
  3307. res: temp_res,
  3308. expr: array_size,
  3309. },
  3310. );
  3311. cfg.array_lengths_temps.insert(memory_array, temp_res);
  3312. Expression::Variable {
  3313. loc: *loc,
  3314. ty: ty.clone(),
  3315. var_no: memory_array,
  3316. }
  3317. }
  3318. /// This function encodes the arguments for the assert-failure instruction
  3319. /// and inserts it in the CFG.
  3320. pub(super) fn assert_failure(
  3321. loc: &Loc,
  3322. arg: Option<Expression>,
  3323. ns: &Namespace,
  3324. cfg: &mut ControlFlowGraph,
  3325. vartab: &mut Vartable,
  3326. ) {
  3327. if arg.is_none() {
  3328. cfg.add(vartab, Instr::AssertFailure { encoded_args: None });
  3329. return;
  3330. }
  3331. let selector = 0x08c3_79a0u32;
  3332. let selector = Expression::NumberLiteral {
  3333. loc: Loc::Codegen,
  3334. ty: Type::Uint(32),
  3335. value: BigInt::from(selector),
  3336. };
  3337. let args = vec![selector, arg.unwrap()];
  3338. let (encoded_buffer, _) = abi_encode(loc, args, ns, vartab, cfg, false);
  3339. cfg.add(
  3340. vartab,
  3341. Instr::AssertFailure {
  3342. encoded_args: Some(encoded_buffer),
  3343. },
  3344. )
  3345. }
  3346. /// Generate the binary code for a contract
  3347. fn code(loc: &Loc, contract_no: usize, ns: &Namespace, opt: &Options) -> Expression {
  3348. let contract = &ns.contracts[contract_no];
  3349. let code = contract.emit(ns, opt);
  3350. let size = Expression::NumberLiteral {
  3351. loc: *loc,
  3352. ty: Type::Uint(32),
  3353. value: code.len().into(),
  3354. };
  3355. Expression::AllocDynamicBytes {
  3356. loc: *loc,
  3357. ty: Type::DynamicBytes,
  3358. size: size.into(),
  3359. initializer: Some(code),
  3360. }
  3361. }
  3362. fn string_to_expr(string: String) -> Expression {
  3363. Expression::FormatString {
  3364. loc: Loc::Codegen,
  3365. args: vec![(
  3366. FormatArg::StringLiteral,
  3367. Expression::BytesLiteral {
  3368. loc: Loc::Codegen,
  3369. ty: Type::Bytes(string.as_bytes().len() as u8),
  3370. value: string.as_bytes().to_vec(),
  3371. },
  3372. )],
  3373. }
  3374. }
  3375. pub(crate) fn log_runtime_error(
  3376. report_error: bool,
  3377. reason: &str,
  3378. reason_loc: Loc,
  3379. cfg: &mut ControlFlowGraph,
  3380. vartab: &mut Vartable,
  3381. ns: &Namespace,
  3382. ) {
  3383. if report_error {
  3384. let error_with_loc = error_msg_with_loc(ns, reason, Some(reason_loc));
  3385. let expr = string_to_expr(error_with_loc + ",\n");
  3386. cfg.add(vartab, Instr::Print { expr });
  3387. }
  3388. }
  3389. fn add_prefix_and_delimiter_to_print(mut expr: Expression) -> Expression {
  3390. let prefix = b"print: ";
  3391. let delimiter = b",\n";
  3392. if let Expression::FormatString { loc, args } = &mut expr {
  3393. let mut new_vec = Vec::new();
  3394. new_vec.push((
  3395. FormatArg::StringLiteral,
  3396. Expression::BytesLiteral {
  3397. loc: Loc::Codegen,
  3398. ty: Type::Bytes(prefix.len() as u8),
  3399. value: prefix.to_vec(),
  3400. },
  3401. ));
  3402. new_vec.append(args);
  3403. new_vec.push((
  3404. FormatArg::StringLiteral,
  3405. Expression::BytesLiteral {
  3406. loc: Loc::Codegen,
  3407. ty: Type::Bytes(delimiter.len() as u8),
  3408. value: delimiter.to_vec(),
  3409. },
  3410. ));
  3411. Expression::FormatString {
  3412. loc: *loc,
  3413. args: new_vec,
  3414. }
  3415. } else {
  3416. Expression::FormatString {
  3417. loc: Loc::Codegen,
  3418. args: vec![
  3419. (
  3420. FormatArg::StringLiteral,
  3421. Expression::BytesLiteral {
  3422. loc: Loc::Codegen,
  3423. ty: Type::Bytes(prefix.len() as u8),
  3424. value: prefix.to_vec(),
  3425. },
  3426. ),
  3427. (FormatArg::Default, expr),
  3428. (
  3429. FormatArg::StringLiteral,
  3430. Expression::BytesLiteral {
  3431. loc: Loc::Codegen,
  3432. ty: Type::Bytes(delimiter.len() as u8),
  3433. value: delimiter.to_vec(),
  3434. },
  3435. ),
  3436. ],
  3437. }
  3438. }
  3439. }