function_call.rs 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657
  1. // SPDX-License-Identifier: Apache-2.0
  2. use crate::sema::ast::{
  3. ArrayLength, Builtin, CallArgs, CallTy, Expression, Function, Mutability, Namespace,
  4. RetrieveType, StructType, Symbol, Type,
  5. };
  6. use crate::sema::contracts::is_base;
  7. use crate::sema::diagnostics::Diagnostics;
  8. use crate::sema::expression::constructor::{deprecated_constructor_arguments, new};
  9. use crate::sema::expression::literals::{named_struct_literal, struct_literal};
  10. use crate::sema::expression::resolve_expression::expression;
  11. use crate::sema::expression::{ExprContext, ResolveTo};
  12. use crate::sema::format::string_format;
  13. use crate::sema::symtable::Symtable;
  14. use crate::sema::unused_variable::check_function_call;
  15. use crate::sema::{builtin, using};
  16. use crate::Target;
  17. use solang_parser::diagnostics::Diagnostic;
  18. use solang_parser::pt;
  19. use solang_parser::pt::{CodeLocation, Loc, Visibility};
  20. use std::collections::HashMap;
  21. /// Resolve a function call via function type
  22. /// Function types do not have names so call cannot be using named parameters
  23. pub(super) fn call_function_type(
  24. loc: &pt::Loc,
  25. expr: &pt::Expression,
  26. args: &[pt::Expression],
  27. call_args: &[&pt::NamedArgument],
  28. call_args_loc: Option<pt::Loc>,
  29. context: &ExprContext,
  30. ns: &mut Namespace,
  31. symtable: &mut Symtable,
  32. diagnostics: &mut Diagnostics,
  33. resolve_to: ResolveTo,
  34. ) -> Result<Expression, ()> {
  35. let mut function = expression(expr, context, ns, symtable, diagnostics, ResolveTo::Unknown)?;
  36. let mut ty = function.ty();
  37. match ty {
  38. Type::StorageRef(_, real_ty) | Type::Ref(real_ty) => {
  39. ty = *real_ty;
  40. function = function.cast(&expr.loc(), &ty, true, ns, diagnostics)?;
  41. }
  42. _ => (),
  43. };
  44. if let Type::InternalFunction {
  45. params, returns, ..
  46. } = ty
  47. {
  48. if let Some(loc) = call_args_loc {
  49. diagnostics.push(Diagnostic::error(
  50. loc,
  51. "call arguments not permitted for internal calls".to_string(),
  52. ));
  53. }
  54. if params.len() != args.len() {
  55. diagnostics.push(Diagnostic::error(
  56. *loc,
  57. format!(
  58. "function expects {} arguments, {} provided",
  59. params.len(),
  60. args.len()
  61. ),
  62. ));
  63. return Err(());
  64. }
  65. let mut cast_args = Vec::new();
  66. // check if arguments can be implicitly casted
  67. for (i, arg) in args.iter().enumerate() {
  68. let arg = expression(
  69. arg,
  70. context,
  71. ns,
  72. symtable,
  73. diagnostics,
  74. ResolveTo::Type(&params[i]),
  75. )?;
  76. cast_args.push(arg.cast(&arg.loc(), &params[i], true, ns, diagnostics)?);
  77. }
  78. Ok(Expression::InternalFunctionCall {
  79. loc: *loc,
  80. returns: if returns.is_empty() || resolve_to == ResolveTo::Discard {
  81. vec![Type::Void]
  82. } else {
  83. returns
  84. },
  85. function: Box::new(function),
  86. args: cast_args,
  87. })
  88. } else if let Type::ExternalFunction {
  89. returns,
  90. params,
  91. mutability,
  92. } = ty
  93. {
  94. let call_args = parse_call_args(loc, call_args, true, context, ns, symtable, diagnostics)?;
  95. if let Some(value) = &call_args.value {
  96. if !value.const_zero(ns) && !matches!(mutability, Mutability::Payable(_)) {
  97. diagnostics.push(Diagnostic::error(
  98. *loc,
  99. format!(
  100. "sending value to function type '{}' which is not payable",
  101. function.ty().to_string(ns),
  102. ),
  103. ));
  104. return Err(());
  105. }
  106. }
  107. if params.len() != args.len() {
  108. diagnostics.push(Diagnostic::error(
  109. *loc,
  110. format!(
  111. "function expects {} arguments, {} provided",
  112. params.len(),
  113. args.len()
  114. ),
  115. ));
  116. return Err(());
  117. }
  118. let mut cast_args = Vec::new();
  119. // check if arguments can be implicitly casted
  120. for (i, arg) in args.iter().enumerate() {
  121. let arg = expression(
  122. arg,
  123. context,
  124. ns,
  125. symtable,
  126. diagnostics,
  127. ResolveTo::Type(&params[i]),
  128. )?;
  129. cast_args.push(arg.cast(&arg.loc(), &params[i], true, ns, diagnostics)?);
  130. }
  131. Ok(Expression::ExternalFunctionCall {
  132. loc: *loc,
  133. returns: if returns.is_empty() || resolve_to == ResolveTo::Discard {
  134. vec![Type::Void]
  135. } else {
  136. returns
  137. },
  138. function: Box::new(function),
  139. args: cast_args,
  140. call_args,
  141. })
  142. } else {
  143. diagnostics.push(Diagnostic::error(
  144. *loc,
  145. "expression is not a function".to_string(),
  146. ));
  147. Err(())
  148. }
  149. }
  150. /// Create a list of functions matching the given `name` that can be called in this context.
  151. /// A function is available if it has a body block or if its virtual and its contract is not concrete.
  152. ///
  153. /// If global is true, then include functions outside of contracts.
  154. pub fn available_functions(
  155. name: &str,
  156. global: bool,
  157. file_no: usize,
  158. contract_no: Option<usize>,
  159. ns: &Namespace,
  160. ) -> Vec<usize> {
  161. let mut list = Vec::new();
  162. if global {
  163. if let Some(Symbol::Function(v)) =
  164. ns.function_symbols.get(&(file_no, None, name.to_owned()))
  165. {
  166. list.extend(v.iter().map(|(_, func_no)| *func_no));
  167. }
  168. }
  169. if let Some(contract_no) = contract_no {
  170. list.extend(
  171. ns.contracts[contract_no]
  172. .all_functions
  173. .keys()
  174. .filter(|func_no| ns.functions[**func_no].name == name)
  175. .filter_map(|func_no| {
  176. let is_abstract = ns.functions[*func_no].is_virtual
  177. && !ns.contracts[contract_no].is_concrete();
  178. if ns.functions[*func_no].has_body || is_abstract {
  179. return Some(*func_no);
  180. }
  181. None
  182. }),
  183. );
  184. }
  185. list
  186. }
  187. /// Create a list of functions that can be called via super
  188. pub fn available_super_functions(name: &str, contract_no: usize, ns: &Namespace) -> Vec<usize> {
  189. let mut list = Vec::new();
  190. for base_contract_no in ns.contract_bases(contract_no).into_iter().rev() {
  191. if base_contract_no == contract_no {
  192. continue;
  193. }
  194. list.extend(
  195. ns.contracts[base_contract_no]
  196. .all_functions
  197. .keys()
  198. .filter_map(|func_no| {
  199. let func = &ns.functions[*func_no];
  200. if func.name == name && func.has_body {
  201. Some(*func_no)
  202. } else {
  203. None
  204. }
  205. }),
  206. );
  207. }
  208. list
  209. }
  210. /// Resolve a function call with positional arguments
  211. pub fn function_call_pos_args(
  212. loc: &pt::Loc,
  213. id: &pt::Identifier,
  214. func_ty: pt::FunctionTy,
  215. args: &[pt::Expression],
  216. function_nos: Vec<usize>,
  217. virtual_call: bool,
  218. context: &ExprContext,
  219. ns: &mut Namespace,
  220. resolve_to: ResolveTo,
  221. symtable: &mut Symtable,
  222. diagnostics: &mut Diagnostics,
  223. ) -> Result<Expression, ()> {
  224. let mut name_matches = 0;
  225. let mut errors = Diagnostics::default();
  226. if context.constant {
  227. diagnostics.push(Diagnostic::error(
  228. *loc,
  229. "cannot call function in constant expression".to_string(),
  230. ));
  231. return Err(());
  232. }
  233. // Try to resolve as a function call
  234. for function_no in &function_nos {
  235. let func = &ns.functions[*function_no];
  236. if func.ty != func_ty {
  237. continue;
  238. }
  239. name_matches += 1;
  240. let params_len = func.params.len();
  241. if params_len != args.len() {
  242. errors.push(Diagnostic::error(
  243. *loc,
  244. format!(
  245. "{} expects {} arguments, {} provided",
  246. func.ty,
  247. params_len,
  248. args.len()
  249. ),
  250. ));
  251. continue;
  252. }
  253. let mut matches = true;
  254. let mut cast_args = Vec::new();
  255. // check if arguments can be implicitly casted
  256. for (i, arg) in args.iter().enumerate() {
  257. let ty = ns.functions[*function_no].params[i].ty.clone();
  258. matches &=
  259. evaluate_argument(arg, context, ns, symtable, &ty, &mut errors, &mut cast_args);
  260. }
  261. if !matches {
  262. if function_nos.len() > 1 && diagnostics.extend_non_casting(&errors) {
  263. return Err(());
  264. }
  265. continue;
  266. }
  267. match resolve_internal_call(
  268. loc,
  269. *function_no,
  270. context,
  271. resolve_to,
  272. virtual_call,
  273. cast_args,
  274. ns,
  275. &mut errors,
  276. ) {
  277. Some(resolved_call) => return Ok(resolved_call),
  278. None => continue,
  279. }
  280. }
  281. match name_matches {
  282. 0 => {
  283. if func_ty == pt::FunctionTy::Modifier {
  284. diagnostics.push(Diagnostic::error(
  285. id.loc,
  286. format!("unknown modifier '{}'", id.name),
  287. ));
  288. } else {
  289. diagnostics.push(Diagnostic::error(
  290. id.loc,
  291. format!("unknown {} or type '{}'", func_ty, id.name),
  292. ));
  293. }
  294. }
  295. 1 => diagnostics.extend(errors),
  296. _ => {
  297. diagnostics.push(Diagnostic::error(
  298. *loc,
  299. format!("cannot find overloaded {func_ty} which matches signature"),
  300. ));
  301. }
  302. }
  303. Err(())
  304. }
  305. /// Resolve a function call with named arguments
  306. pub(super) fn function_call_named_args(
  307. loc: &pt::Loc,
  308. id: &pt::Identifier,
  309. args: &[pt::NamedArgument],
  310. function_nos: Vec<usize>,
  311. virtual_call: bool,
  312. context: &ExprContext,
  313. resolve_to: ResolveTo,
  314. ns: &mut Namespace,
  315. symtable: &mut Symtable,
  316. diagnostics: &mut Diagnostics,
  317. ) -> Result<Expression, ()> {
  318. let mut arguments = HashMap::new();
  319. for arg in args {
  320. if arguments.contains_key(arg.name.name.as_str()) {
  321. diagnostics.push(Diagnostic::error(
  322. arg.name.loc,
  323. format!("duplicate argument with name '{}'", arg.name.name),
  324. ));
  325. let _ = expression(
  326. &arg.expr,
  327. context,
  328. ns,
  329. symtable,
  330. diagnostics,
  331. ResolveTo::Unknown,
  332. );
  333. }
  334. arguments.insert(arg.name.name.as_str(), &arg.expr);
  335. }
  336. // Try to resolve as a function call
  337. let mut errors = Diagnostics::default();
  338. // Try to resolve as a function call
  339. for function_no in &function_nos {
  340. let func = &ns.functions[*function_no];
  341. if func.ty != pt::FunctionTy::Function {
  342. continue;
  343. }
  344. let unnamed_params = func.params.iter().filter(|p| p.id.is_none()).count();
  345. let params_len = func.params.len();
  346. let mut matches = true;
  347. if unnamed_params > 0 {
  348. errors.push(Diagnostic::cast_error_with_note(
  349. *loc,
  350. format!(
  351. "function cannot be called with named arguments as {unnamed_params} of its parameters do not have names"
  352. ),
  353. func.loc,
  354. format!("definition of {}", func.name),
  355. ));
  356. matches = false;
  357. } else if params_len != args.len() {
  358. errors.push(Diagnostic::cast_error(
  359. *loc,
  360. format!(
  361. "function expects {} arguments, {} provided",
  362. params_len,
  363. args.len()
  364. ),
  365. ));
  366. matches = false;
  367. }
  368. let mut cast_args = Vec::new();
  369. // check if arguments can be implicitly casted
  370. for i in 0..params_len {
  371. let param = &ns.functions[*function_no].params[i];
  372. if param.id.is_none() {
  373. continue;
  374. }
  375. let arg = match arguments.get(param.name_as_str()) {
  376. Some(a) => a,
  377. None => {
  378. matches = false;
  379. diagnostics.push(Diagnostic::cast_error(
  380. *loc,
  381. format!(
  382. "missing argument '{}' to function '{}'",
  383. param.name_as_str(),
  384. id.name,
  385. ),
  386. ));
  387. continue;
  388. }
  389. };
  390. let ty = param.ty.clone();
  391. matches &=
  392. evaluate_argument(arg, context, ns, symtable, &ty, &mut errors, &mut cast_args);
  393. }
  394. if !matches {
  395. if diagnostics.extend_non_casting(&errors) {
  396. return Err(());
  397. }
  398. continue;
  399. }
  400. match resolve_internal_call(
  401. loc,
  402. *function_no,
  403. context,
  404. resolve_to,
  405. virtual_call,
  406. cast_args,
  407. ns,
  408. &mut errors,
  409. ) {
  410. Some(resolved_call) => return Ok(resolved_call),
  411. None => continue,
  412. }
  413. }
  414. match function_nos.len() {
  415. 0 => {
  416. diagnostics.push(Diagnostic::error(
  417. id.loc,
  418. format!("unknown function or type '{}'", id.name),
  419. ));
  420. }
  421. 1 => diagnostics.extend(errors),
  422. _ => {
  423. diagnostics.push(Diagnostic::error(
  424. *loc,
  425. "cannot find overloaded function which matches signature".to_string(),
  426. ));
  427. }
  428. }
  429. Err(())
  430. }
  431. /// Check if the function is a method of a variable
  432. /// Returns:
  433. /// 1. Err, when there is an error
  434. /// 2. Ok(Some()), when we have indeed received a method of a variable
  435. /// 3. Ok(None), when we have not received a function that is a method of a variable
  436. fn try_namespace(
  437. loc: &pt::Loc,
  438. var: &pt::Expression,
  439. func: &pt::Identifier,
  440. args: &[pt::Expression],
  441. call_args_loc: Option<pt::Loc>,
  442. context: &ExprContext,
  443. ns: &mut Namespace,
  444. symtable: &mut Symtable,
  445. diagnostics: &mut Diagnostics,
  446. resolve_to: ResolveTo,
  447. ) -> Result<Option<Expression>, ()> {
  448. if let pt::Expression::Variable(namespace) = var {
  449. if builtin::is_builtin_call(Some(&namespace.name), &func.name, ns) {
  450. if let Some(loc) = call_args_loc {
  451. diagnostics.push(Diagnostic::error(
  452. loc,
  453. "call arguments not allowed on builtins".to_string(),
  454. ));
  455. return Err(());
  456. }
  457. return Ok(Some(builtin::resolve_namespace_call(
  458. loc,
  459. &namespace.name,
  460. &func.name,
  461. args,
  462. context,
  463. ns,
  464. symtable,
  465. diagnostics,
  466. )?));
  467. }
  468. // is it a call to super
  469. if namespace.name == "super" {
  470. if let Some(cur_contract_no) = context.contract_no {
  471. if let Some(loc) = call_args_loc {
  472. diagnostics.push(Diagnostic::error(
  473. loc,
  474. "call arguments not allowed on super calls".to_string(),
  475. ));
  476. return Err(());
  477. }
  478. return Ok(Some(function_call_pos_args(
  479. loc,
  480. func,
  481. pt::FunctionTy::Function,
  482. args,
  483. available_super_functions(&func.name, cur_contract_no, ns),
  484. false,
  485. context,
  486. ns,
  487. resolve_to,
  488. symtable,
  489. diagnostics,
  490. )?));
  491. } else {
  492. diagnostics.push(Diagnostic::error(
  493. *loc,
  494. "super not available outside contracts".to_string(),
  495. ));
  496. return Err(());
  497. }
  498. }
  499. // library or base contract call
  500. if let Some(call_contract_no) = ns.resolve_contract(context.file_no, namespace) {
  501. if ns.contracts[call_contract_no].is_library() {
  502. if let Some(loc) = call_args_loc {
  503. diagnostics.push(Diagnostic::error(
  504. loc,
  505. "call arguments not allowed on library calls".to_string(),
  506. ));
  507. return Err(());
  508. }
  509. return Ok(Some(function_call_pos_args(
  510. loc,
  511. func,
  512. pt::FunctionTy::Function,
  513. args,
  514. available_functions(
  515. &func.name,
  516. false,
  517. context.file_no,
  518. Some(call_contract_no),
  519. ns,
  520. ),
  521. true,
  522. context,
  523. ns,
  524. resolve_to,
  525. symtable,
  526. diagnostics,
  527. )?));
  528. }
  529. // is a base contract of us
  530. if let Some(contract_no) = context.contract_no {
  531. if is_base(call_contract_no, contract_no, ns) {
  532. if let Some(loc) = call_args_loc {
  533. diagnostics.push(Diagnostic::error(
  534. loc,
  535. "call arguments not allowed on internal calls".to_string(),
  536. ));
  537. return Err(());
  538. }
  539. return Ok(Some(function_call_pos_args(
  540. loc,
  541. func,
  542. pt::FunctionTy::Function,
  543. args,
  544. available_functions(
  545. &func.name,
  546. false,
  547. context.file_no,
  548. Some(call_contract_no),
  549. ns,
  550. ),
  551. false,
  552. context,
  553. ns,
  554. resolve_to,
  555. symtable,
  556. diagnostics,
  557. )?));
  558. } else {
  559. diagnostics.push(Diagnostic::error(
  560. *loc,
  561. "function calls via contract name are only valid for base contracts".into(),
  562. ));
  563. }
  564. }
  565. }
  566. }
  567. Ok(None)
  568. }
  569. /// Check if the function is a method of a storage reference
  570. /// Returns:
  571. /// 1. Err, when there is an error
  572. /// 2. Ok(Some()), when we have indeed received a method of a storage reference
  573. /// 3. Ok(None), when we have not received a function that is a method of a storage reference
  574. fn try_storage_reference(
  575. loc: &pt::Loc,
  576. var_expr: &Expression,
  577. func: &pt::Identifier,
  578. args: &[pt::Expression],
  579. context: &ExprContext,
  580. diagnostics: &mut Diagnostics,
  581. call_args_loc: Option<pt::Loc>,
  582. ns: &mut Namespace,
  583. symtable: &mut Symtable,
  584. resolve_to: &ResolveTo,
  585. ) -> Result<Option<Expression>, ()> {
  586. if let Type::StorageRef(immutable, ty) = &var_expr.ty() {
  587. match ty.as_ref() {
  588. Type::Array(_, dim) => {
  589. if *immutable {
  590. if let Some(function_no) = context.function_no {
  591. if !ns.functions[function_no].is_constructor() {
  592. diagnostics.push(Diagnostic::error(
  593. *loc,
  594. "cannot call method on immutable array outside of constructor"
  595. .to_string(),
  596. ));
  597. return Err(());
  598. }
  599. }
  600. }
  601. if let Some(loc) = call_args_loc {
  602. diagnostics.push(Diagnostic::error(
  603. loc,
  604. "call arguments not allowed on arrays".to_string(),
  605. ));
  606. return Err(());
  607. }
  608. if func.name == "push" {
  609. if matches!(dim.last(), Some(ArrayLength::Fixed(_))) {
  610. diagnostics.push(Diagnostic::error(
  611. func.loc,
  612. "method 'push()' not allowed on fixed length array".to_string(),
  613. ));
  614. return Err(());
  615. }
  616. let elem_ty = ty.array_elem();
  617. let mut builtin_args = vec![var_expr.clone()];
  618. let ret_ty = match args.len() {
  619. 1 => {
  620. let expr = expression(
  621. &args[0],
  622. context,
  623. ns,
  624. symtable,
  625. diagnostics,
  626. ResolveTo::Type(&elem_ty),
  627. )?;
  628. builtin_args.push(expr.cast(
  629. &args[0].loc(),
  630. &elem_ty,
  631. true,
  632. ns,
  633. diagnostics,
  634. )?);
  635. Type::Void
  636. }
  637. 0 => {
  638. if elem_ty.is_reference_type(ns) {
  639. Type::StorageRef(false, Box::new(elem_ty))
  640. } else {
  641. elem_ty
  642. }
  643. }
  644. _ => {
  645. diagnostics.push(Diagnostic::error(
  646. func.loc,
  647. "method 'push()' takes at most 1 argument".to_string(),
  648. ));
  649. return Err(());
  650. }
  651. };
  652. return Ok(Some(Expression::Builtin {
  653. loc: func.loc,
  654. tys: vec![ret_ty],
  655. kind: Builtin::ArrayPush,
  656. args: builtin_args,
  657. }));
  658. }
  659. if func.name == "pop" {
  660. if matches!(dim.last(), Some(ArrayLength::Fixed(_))) {
  661. diagnostics.push(Diagnostic::error(
  662. func.loc,
  663. "method 'pop()' not allowed on fixed length array".to_string(),
  664. ));
  665. return Err(());
  666. }
  667. if !args.is_empty() {
  668. diagnostics.push(Diagnostic::error(
  669. func.loc,
  670. "method 'pop()' does not take any arguments".to_string(),
  671. ));
  672. return Err(());
  673. }
  674. let storage_elem = ty.storage_array_elem();
  675. let elem_ty = storage_elem.deref_any();
  676. let return_ty = if *resolve_to == ResolveTo::Discard {
  677. Type::Void
  678. } else {
  679. elem_ty.clone()
  680. };
  681. return Ok(Some(Expression::Builtin {
  682. loc: func.loc,
  683. tys: vec![return_ty],
  684. kind: Builtin::ArrayPop,
  685. args: vec![var_expr.clone()],
  686. }));
  687. }
  688. }
  689. Type::DynamicBytes => {
  690. if *immutable {
  691. if let Some(function_no) = context.function_no {
  692. if !ns.functions[function_no].is_constructor() {
  693. diagnostics.push(Diagnostic::error(
  694. *loc,
  695. "cannot call method on immutable bytes outside of constructor"
  696. .to_string(),
  697. ));
  698. return Err(());
  699. }
  700. }
  701. }
  702. if let Some(loc) = call_args_loc {
  703. diagnostics.push(Diagnostic::error(
  704. loc,
  705. "call arguments not allowed on bytes".to_string(),
  706. ));
  707. return Err(());
  708. }
  709. if func.name == "push" {
  710. let mut builtin_args = vec![var_expr.clone()];
  711. let elem_ty = Type::Bytes(1);
  712. let ret_ty = match args.len() {
  713. 1 => {
  714. let expr = expression(
  715. &args[0],
  716. context,
  717. ns,
  718. symtable,
  719. diagnostics,
  720. ResolveTo::Type(&elem_ty),
  721. )?;
  722. builtin_args.push(expr.cast(
  723. &args[0].loc(),
  724. &elem_ty,
  725. true,
  726. ns,
  727. diagnostics,
  728. )?);
  729. Type::Void
  730. }
  731. 0 => elem_ty,
  732. _ => {
  733. diagnostics.push(Diagnostic::error(
  734. func.loc,
  735. "method 'push()' takes at most 1 argument".to_string(),
  736. ));
  737. return Err(());
  738. }
  739. };
  740. return Ok(Some(Expression::Builtin {
  741. loc: func.loc,
  742. tys: vec![ret_ty],
  743. kind: Builtin::ArrayPush,
  744. args: builtin_args,
  745. }));
  746. }
  747. if func.name == "pop" {
  748. if !args.is_empty() {
  749. diagnostics.push(Diagnostic::error(
  750. func.loc,
  751. "method 'pop()' does not take any arguments".to_string(),
  752. ));
  753. return Err(());
  754. }
  755. return Ok(Some(Expression::Builtin {
  756. loc: func.loc,
  757. tys: vec![Type::Bytes(1)],
  758. kind: Builtin::ArrayPop,
  759. args: vec![var_expr.clone()],
  760. }));
  761. }
  762. }
  763. _ => {}
  764. }
  765. }
  766. Ok(None)
  767. }
  768. /// Check if we can resolve the call with ns.resolve_type
  769. /// Returns:
  770. /// 1. Err, when there is an error
  771. /// 2. Ok(Some()), when we have indeed received a method that has correctly been resolved with
  772. /// ns.resolve_type
  773. /// 3. Ok(None), when the function we have received could not be resolved with ns.resolve_type
  774. fn try_user_type(
  775. loc: &pt::Loc,
  776. var: &pt::Expression,
  777. func: &pt::Identifier,
  778. args: &[pt::Expression],
  779. call_args_loc: Option<pt::Loc>,
  780. context: &ExprContext,
  781. ns: &mut Namespace,
  782. symtable: &mut Symtable,
  783. diagnostics: &mut Diagnostics,
  784. ) -> Result<Option<Expression>, ()> {
  785. if let Ok(Type::UserType(no)) = ns.resolve_type(
  786. context.file_no,
  787. context.contract_no,
  788. false,
  789. var,
  790. &mut Diagnostics::default(),
  791. ) {
  792. if let Some(loc) = call_args_loc {
  793. diagnostics.push(Diagnostic::error(
  794. loc,
  795. "call arguments not allowed on builtins".to_string(),
  796. ));
  797. return Err(());
  798. }
  799. let elem_ty = ns.user_types[no].ty.clone();
  800. let user_ty = Type::UserType(no);
  801. if func.name == "unwrap" {
  802. return if args.len() != 1 {
  803. diagnostics.push(Diagnostic::error(
  804. func.loc,
  805. "method 'unwrap()' takes one argument".to_string(),
  806. ));
  807. Err(())
  808. } else {
  809. let expr = expression(
  810. &args[0],
  811. context,
  812. ns,
  813. symtable,
  814. diagnostics,
  815. ResolveTo::Type(&user_ty),
  816. )?;
  817. Ok(Some(Expression::Builtin {
  818. loc: *loc,
  819. tys: vec![elem_ty],
  820. kind: Builtin::UserTypeUnwrap,
  821. args: vec![expr.cast(&expr.loc(), &user_ty, true, ns, diagnostics)?],
  822. }))
  823. };
  824. } else if func.name == "wrap" {
  825. return if args.len() != 1 {
  826. diagnostics.push(Diagnostic::error(
  827. func.loc,
  828. "method 'wrap()' takes one argument".to_string(),
  829. ));
  830. Err(())
  831. } else {
  832. let expr = expression(
  833. &args[0],
  834. context,
  835. ns,
  836. symtable,
  837. diagnostics,
  838. ResolveTo::Type(&elem_ty),
  839. )?;
  840. Ok(Some(Expression::Builtin {
  841. loc: *loc,
  842. tys: vec![user_ty],
  843. kind: Builtin::UserTypeWrap,
  844. args: vec![expr.cast(&expr.loc(), &elem_ty, true, ns, diagnostics)?],
  845. }))
  846. };
  847. }
  848. }
  849. Ok(None)
  850. }
  851. /// Check if the function call is to a type's method
  852. /// Returns:
  853. /// 1. Err, when there is an error
  854. /// 2. Ok(Some()), when we have indeed received a method of a type
  855. /// 3. Ok(None), when we have received a function that is not a method of a type
  856. fn try_type_method(
  857. loc: &pt::Loc,
  858. func: &pt::Identifier,
  859. var: &pt::Expression,
  860. args: &[pt::Expression],
  861. call_args: &[&pt::NamedArgument],
  862. call_args_loc: Option<pt::Loc>,
  863. context: &ExprContext,
  864. var_expr: &Expression,
  865. ns: &mut Namespace,
  866. symtable: &mut Symtable,
  867. diagnostics: &mut Diagnostics,
  868. resolve_to: ResolveTo,
  869. ) -> Result<Option<Expression>, ()> {
  870. let var_ty = var_expr.ty();
  871. match var_ty.deref_any() {
  872. Type::Bytes(..) | Type::String if func.name == "format" => {
  873. return if let pt::Expression::StringLiteral(bs) = var {
  874. if let Some(loc) = call_args_loc {
  875. diagnostics.push(Diagnostic::error(
  876. loc,
  877. "call arguments not allowed on builtins".to_string(),
  878. ));
  879. return Err(());
  880. }
  881. Ok(Some(string_format(
  882. loc,
  883. bs,
  884. args,
  885. context,
  886. ns,
  887. symtable,
  888. diagnostics,
  889. )?))
  890. } else {
  891. diagnostics.push(Diagnostic::error(
  892. *loc,
  893. "format only allowed on string literals".to_string(),
  894. ));
  895. Err(())
  896. };
  897. }
  898. Type::Array(..) | Type::DynamicBytes if var_ty.is_dynamic(ns) => {
  899. if func.name == "push" {
  900. let elem_ty = var_ty.array_elem();
  901. let val = match args.len() {
  902. 0 => {
  903. return Ok(Some(Expression::Builtin {
  904. loc: *loc,
  905. tys: vec![elem_ty.clone()],
  906. kind: Builtin::ArrayPush,
  907. args: vec![var_expr.clone()],
  908. }));
  909. }
  910. 1 => {
  911. let val_expr = expression(
  912. &args[0],
  913. context,
  914. ns,
  915. symtable,
  916. diagnostics,
  917. ResolveTo::Type(&elem_ty),
  918. )?;
  919. val_expr.cast(&args[0].loc(), &elem_ty, true, ns, diagnostics)?
  920. }
  921. _ => {
  922. diagnostics.push(Diagnostic::error(
  923. func.loc,
  924. "method 'push()' takes at most 1 argument".to_string(),
  925. ));
  926. return Err(());
  927. }
  928. };
  929. return Ok(Some(Expression::Builtin {
  930. loc: *loc,
  931. tys: vec![elem_ty.clone()],
  932. kind: Builtin::ArrayPush,
  933. args: vec![var_expr.clone(), val],
  934. }));
  935. }
  936. if func.name == "pop" {
  937. if !args.is_empty() {
  938. diagnostics.push(Diagnostic::error(
  939. func.loc,
  940. "method 'pop()' does not take any arguments".to_string(),
  941. ));
  942. return Err(());
  943. }
  944. let elem_ty = match &var_ty {
  945. Type::Array(ty, _) => ty,
  946. Type::DynamicBytes => &Type::Uint(8),
  947. _ => unreachable!(),
  948. };
  949. return Ok(Some(Expression::Builtin {
  950. loc: *loc,
  951. tys: vec![elem_ty.clone()],
  952. kind: Builtin::ArrayPop,
  953. args: vec![var_expr.clone()],
  954. }));
  955. }
  956. }
  957. Type::Array(..) if func.name == "push" || func.name == "pop" => {
  958. diagnostics.push(Diagnostic::error(
  959. func.loc,
  960. format!(
  961. "method {}() is not available for fixed length arrays",
  962. func.name
  963. ),
  964. ));
  965. return Err(());
  966. }
  967. Type::Contract(ext_contract_no) => {
  968. let call_args =
  969. parse_call_args(loc, call_args, true, context, ns, symtable, diagnostics)?;
  970. let mut errors = Diagnostics::default();
  971. let mut name_matches: Vec<usize> = Vec::new();
  972. for function_no in ns.contracts[*ext_contract_no].all_functions.keys() {
  973. if func.name != ns.functions[*function_no].name
  974. || ns.functions[*function_no].ty != pt::FunctionTy::Function
  975. {
  976. continue;
  977. }
  978. name_matches.push(*function_no);
  979. }
  980. for function_no in &name_matches {
  981. let params_len = ns.functions[*function_no].params.len();
  982. if params_len != args.len() {
  983. errors.push(Diagnostic::error(
  984. *loc,
  985. format!(
  986. "function expects {} arguments, {} provided",
  987. params_len,
  988. args.len()
  989. ),
  990. ));
  991. continue;
  992. }
  993. let mut matches = true;
  994. let mut cast_args = Vec::new();
  995. // check if arguments can be implicitly casted
  996. for (i, arg) in args.iter().enumerate() {
  997. let ty = ns.functions[*function_no].params[i].ty.clone();
  998. let arg = match expression(
  999. arg,
  1000. context,
  1001. ns,
  1002. symtable,
  1003. &mut errors,
  1004. ResolveTo::Type(&ty),
  1005. ) {
  1006. Ok(e) => e,
  1007. Err(_) => {
  1008. matches = false;
  1009. continue;
  1010. }
  1011. };
  1012. match arg.cast(&arg.loc(), &ty, true, ns, &mut errors) {
  1013. Ok(expr) => cast_args.push(expr),
  1014. Err(()) => {
  1015. matches = false;
  1016. continue;
  1017. }
  1018. }
  1019. }
  1020. if matches {
  1021. if !ns.functions[*function_no].is_public() {
  1022. diagnostics.push(Diagnostic::error(
  1023. *loc,
  1024. format!("function '{}' is not 'public' or 'external'", func.name),
  1025. ));
  1026. return Err(());
  1027. }
  1028. if let Some(value) = &call_args.value {
  1029. if !value.const_zero(ns) && !ns.functions[*function_no].is_payable() {
  1030. diagnostics.push(Diagnostic::error(
  1031. *loc,
  1032. format!(
  1033. "sending value to function '{}' which is not payable",
  1034. func.name
  1035. ),
  1036. ));
  1037. return Err(());
  1038. }
  1039. }
  1040. let func = &ns.functions[*function_no];
  1041. let returns = function_returns(func, resolve_to);
  1042. let ty = function_type(func, true, resolve_to);
  1043. return Ok(Some(Expression::ExternalFunctionCall {
  1044. loc: *loc,
  1045. returns,
  1046. function: Box::new(Expression::ExternalFunction {
  1047. loc: *loc,
  1048. ty,
  1049. function_no: *function_no,
  1050. address: Box::new(var_expr.cast(
  1051. &var.loc(),
  1052. &Type::Contract(func.contract_no.unwrap()),
  1053. true,
  1054. ns,
  1055. diagnostics,
  1056. )?),
  1057. }),
  1058. args: cast_args,
  1059. call_args,
  1060. }));
  1061. } else if name_matches.len() > 1 && diagnostics.extend_non_casting(&errors) {
  1062. return Err(());
  1063. }
  1064. }
  1065. // what about call args
  1066. match using::try_resolve_using_call(
  1067. loc,
  1068. func,
  1069. var_expr,
  1070. context,
  1071. args,
  1072. symtable,
  1073. diagnostics,
  1074. ns,
  1075. resolve_to,
  1076. ) {
  1077. Ok(Some(expr)) => {
  1078. return Ok(Some(expr));
  1079. }
  1080. Ok(None) => (),
  1081. Err(_) => {
  1082. return Err(());
  1083. }
  1084. }
  1085. if name_matches.len() == 1 {
  1086. diagnostics.extend(errors);
  1087. } else if name_matches.len() != 1 {
  1088. diagnostics.push(Diagnostic::error(
  1089. *loc,
  1090. "cannot find overloaded function which matches signature".to_string(),
  1091. ));
  1092. }
  1093. return Err(());
  1094. }
  1095. Type::Address(is_payable) => {
  1096. if func.name == "transfer" || func.name == "send" {
  1097. if !is_payable {
  1098. diagnostics.push(Diagnostic::error(
  1099. *loc,
  1100. format!(
  1101. "method '{}' available on type 'address payable' not 'address'",
  1102. func.name,
  1103. ),
  1104. ));
  1105. return Err(());
  1106. }
  1107. if args.len() != 1 {
  1108. diagnostics.push(Diagnostic::error(
  1109. *loc,
  1110. format!(
  1111. "'{}' expects 1 argument, {} provided",
  1112. func.name,
  1113. args.len()
  1114. ),
  1115. ));
  1116. return Err(());
  1117. }
  1118. if let Some(loc) = call_args_loc {
  1119. diagnostics.push(Diagnostic::error(
  1120. loc,
  1121. format!("call arguments not allowed on '{}'", func.name),
  1122. ));
  1123. return Err(());
  1124. }
  1125. let expr = expression(
  1126. &args[0],
  1127. context,
  1128. ns,
  1129. symtable,
  1130. diagnostics,
  1131. ResolveTo::Type(&Type::Value),
  1132. )?;
  1133. let address =
  1134. var_expr.cast(&var_expr.loc(), var_ty.deref_any(), true, ns, diagnostics)?;
  1135. let value = expr.cast(&args[0].loc(), &Type::Value, true, ns, diagnostics)?;
  1136. return if func.name == "transfer" {
  1137. Ok(Some(Expression::Builtin {
  1138. loc: *loc,
  1139. tys: vec![Type::Void],
  1140. kind: Builtin::PayableTransfer,
  1141. args: vec![address, value],
  1142. }))
  1143. } else {
  1144. Ok(Some(Expression::Builtin {
  1145. loc: *loc,
  1146. tys: vec![Type::Bool],
  1147. kind: Builtin::PayableSend,
  1148. args: vec![address, value],
  1149. }))
  1150. };
  1151. }
  1152. let ty = match func.name.as_str() {
  1153. "call" => Some(CallTy::Regular),
  1154. "delegatecall" if ns.target != Target::Solana => Some(CallTy::Delegate),
  1155. "staticcall" if ns.target == Target::EVM => Some(CallTy::Static),
  1156. _ => None,
  1157. };
  1158. if let Some(ty) = ty {
  1159. let call_args =
  1160. parse_call_args(loc, call_args, true, context, ns, symtable, diagnostics)?;
  1161. if ty != CallTy::Regular && call_args.value.is_some() {
  1162. diagnostics.push(Diagnostic::error(
  1163. *loc,
  1164. format!("'{}' cannot have value specified", func.name,),
  1165. ));
  1166. return Err(());
  1167. }
  1168. if ty == CallTy::Delegate && ns.target.is_polkadot() && call_args.gas.is_some() {
  1169. diagnostics.push(Diagnostic::warning(
  1170. *loc,
  1171. "'gas' specified on 'delegatecall' will be ignored".into(),
  1172. ));
  1173. }
  1174. if args.len() != 1 {
  1175. diagnostics.push(Diagnostic::error(
  1176. *loc,
  1177. format!(
  1178. "'{}' expects 1 argument, {} provided",
  1179. func.name,
  1180. args.len()
  1181. ),
  1182. ));
  1183. return Err(());
  1184. }
  1185. let args = expression(
  1186. &args[0],
  1187. context,
  1188. ns,
  1189. symtable,
  1190. diagnostics,
  1191. ResolveTo::Type(&Type::DynamicBytes),
  1192. )?;
  1193. let mut args_ty = args.ty();
  1194. match args_ty.deref_any() {
  1195. Type::DynamicBytes => (),
  1196. Type::Bytes(_) => {
  1197. args_ty = Type::DynamicBytes;
  1198. }
  1199. Type::Array(..) | Type::Struct(..) if !args_ty.is_dynamic(ns) => {}
  1200. _ => {
  1201. diagnostics.push(Diagnostic::error(
  1202. args.loc(),
  1203. format!("'{}' is not fixed length type", args_ty.to_string(ns),),
  1204. ));
  1205. return Err(());
  1206. }
  1207. }
  1208. let args = args.cast(&args.loc(), args_ty.deref_any(), true, ns, diagnostics)?;
  1209. return Ok(Some(Expression::ExternalFunctionCallRaw {
  1210. loc: *loc,
  1211. ty,
  1212. args: Box::new(args),
  1213. address: Box::new(var_expr.cast(
  1214. &var_expr.loc(),
  1215. &Type::Address(*is_payable),
  1216. true,
  1217. ns,
  1218. diagnostics,
  1219. )?),
  1220. call_args,
  1221. }));
  1222. }
  1223. }
  1224. _ => (),
  1225. }
  1226. Ok(None)
  1227. }
  1228. /// Resolve a method call with positional arguments
  1229. pub(super) fn method_call_pos_args(
  1230. loc: &pt::Loc,
  1231. var: &pt::Expression,
  1232. func: &pt::Identifier,
  1233. args: &[pt::Expression],
  1234. call_args: &[&pt::NamedArgument],
  1235. call_args_loc: Option<pt::Loc>,
  1236. context: &ExprContext,
  1237. ns: &mut Namespace,
  1238. symtable: &mut Symtable,
  1239. diagnostics: &mut Diagnostics,
  1240. resolve_to: ResolveTo,
  1241. ) -> Result<Expression, ()> {
  1242. if let Some(resolved_call) = try_namespace(
  1243. loc,
  1244. var,
  1245. func,
  1246. args,
  1247. call_args_loc,
  1248. context,
  1249. ns,
  1250. symtable,
  1251. diagnostics,
  1252. resolve_to,
  1253. )? {
  1254. return Ok(resolved_call);
  1255. }
  1256. if let Some(resolved_call) = try_user_type(
  1257. loc,
  1258. var,
  1259. func,
  1260. args,
  1261. call_args_loc,
  1262. context,
  1263. ns,
  1264. symtable,
  1265. diagnostics,
  1266. )? {
  1267. return Ok(resolved_call);
  1268. }
  1269. if context.constant {
  1270. diagnostics.push(Diagnostic::error(
  1271. *loc,
  1272. "cannot call function in constant expression".to_string(),
  1273. ));
  1274. return Err(());
  1275. }
  1276. if let Some(mut path) = ns.expr_to_identifier_path(var) {
  1277. path.identifiers.push(func.clone());
  1278. if let Ok(list) = ns.resolve_free_function_with_namespace(
  1279. context.file_no,
  1280. &path,
  1281. &mut Diagnostics::default(),
  1282. ) {
  1283. if let Some(loc) = call_args_loc {
  1284. diagnostics.push(Diagnostic::error(
  1285. loc,
  1286. "call arguments not allowed on internal calls".to_string(),
  1287. ));
  1288. }
  1289. return function_call_pos_args(
  1290. loc,
  1291. func,
  1292. pt::FunctionTy::Function,
  1293. args,
  1294. list.iter().map(|(_, no)| *no).collect(),
  1295. false,
  1296. context,
  1297. ns,
  1298. resolve_to,
  1299. symtable,
  1300. diagnostics,
  1301. );
  1302. }
  1303. }
  1304. let var_expr = expression(var, context, ns, symtable, diagnostics, ResolveTo::Unknown)?;
  1305. if let Some(resolved_call) =
  1306. builtin::resolve_method_call(&var_expr, func, args, context, ns, symtable, diagnostics)?
  1307. {
  1308. return Ok(resolved_call);
  1309. }
  1310. if let Some(resolved_call) = try_storage_reference(
  1311. loc,
  1312. &var_expr,
  1313. func,
  1314. args,
  1315. context,
  1316. diagnostics,
  1317. call_args_loc,
  1318. ns,
  1319. symtable,
  1320. &resolve_to,
  1321. )? {
  1322. return Ok(resolved_call);
  1323. }
  1324. let mut diagnostics_type: u8 = 0;
  1325. let mut type_method_diagnostics = Diagnostics::default();
  1326. match try_type_method(
  1327. loc,
  1328. func,
  1329. var,
  1330. args,
  1331. call_args,
  1332. call_args_loc,
  1333. context,
  1334. &var_expr,
  1335. ns,
  1336. symtable,
  1337. &mut type_method_diagnostics,
  1338. resolve_to,
  1339. ) {
  1340. Ok(Some(resolved_call)) => {
  1341. diagnostics.extend(type_method_diagnostics);
  1342. return Ok(resolved_call);
  1343. }
  1344. Ok(None) => (),
  1345. Err(()) => {
  1346. // Adding one means diagnostics from type method
  1347. diagnostics_type += 1;
  1348. }
  1349. }
  1350. let mut resolve_using_diagnostics = Diagnostics::default();
  1351. // resolve it using library extension
  1352. match using::try_resolve_using_call(
  1353. loc,
  1354. func,
  1355. &var_expr,
  1356. context,
  1357. args,
  1358. symtable,
  1359. &mut resolve_using_diagnostics,
  1360. ns,
  1361. resolve_to,
  1362. ) {
  1363. Ok(Some(resolved_call)) => {
  1364. diagnostics.extend(resolve_using_diagnostics);
  1365. return Ok(resolved_call);
  1366. }
  1367. Ok(None) => (),
  1368. Err(()) => {
  1369. // Adding two means diagnostics from resolve_using
  1370. diagnostics_type += 2;
  1371. }
  1372. }
  1373. match diagnostics_type {
  1374. 1 => diagnostics.extend(type_method_diagnostics),
  1375. 2 => diagnostics.extend(resolve_using_diagnostics),
  1376. // If 'diagnostics_type' is 3, we have errors from both type_method and resolve_using.
  1377. _ => diagnostics.push(Diagnostic::error(
  1378. func.loc,
  1379. format!("method '{}' does not exist", func.name),
  1380. )),
  1381. }
  1382. Err(())
  1383. }
  1384. pub(super) fn method_call_named_args(
  1385. loc: &pt::Loc,
  1386. var: &pt::Expression,
  1387. func_name: &pt::Identifier,
  1388. args: &[pt::NamedArgument],
  1389. call_args: &[&pt::NamedArgument],
  1390. call_args_loc: Option<pt::Loc>,
  1391. context: &ExprContext,
  1392. ns: &mut Namespace,
  1393. symtable: &mut Symtable,
  1394. diagnostics: &mut Diagnostics,
  1395. resolve_to: ResolveTo,
  1396. ) -> Result<Expression, ()> {
  1397. if let pt::Expression::Variable(namespace) = var {
  1398. // is it a call to super
  1399. if namespace.name == "super" {
  1400. if let Some(cur_contract_no) = context.contract_no {
  1401. if let Some(loc) = call_args_loc {
  1402. diagnostics.push(Diagnostic::error(
  1403. loc,
  1404. "call arguments not allowed on super calls".to_string(),
  1405. ));
  1406. return Err(());
  1407. }
  1408. return function_call_named_args(
  1409. loc,
  1410. func_name,
  1411. args,
  1412. available_super_functions(&func_name.name, cur_contract_no, ns),
  1413. false,
  1414. context,
  1415. resolve_to,
  1416. ns,
  1417. symtable,
  1418. diagnostics,
  1419. );
  1420. } else {
  1421. diagnostics.push(Diagnostic::error(
  1422. *loc,
  1423. "super not available outside contracts".to_string(),
  1424. ));
  1425. return Err(());
  1426. }
  1427. }
  1428. // library or base contract call
  1429. if let Some(call_contract_no) = ns.resolve_contract(context.file_no, namespace) {
  1430. if ns.contracts[call_contract_no].is_library() {
  1431. if let Some(loc) = call_args_loc {
  1432. diagnostics.push(Diagnostic::error(
  1433. loc,
  1434. "call arguments not allowed on library calls".to_string(),
  1435. ));
  1436. return Err(());
  1437. }
  1438. return function_call_named_args(
  1439. loc,
  1440. func_name,
  1441. args,
  1442. available_functions(
  1443. &func_name.name,
  1444. false,
  1445. context.file_no,
  1446. Some(call_contract_no),
  1447. ns,
  1448. ),
  1449. true,
  1450. context,
  1451. resolve_to,
  1452. ns,
  1453. symtable,
  1454. diagnostics,
  1455. );
  1456. }
  1457. // is a base contract of us
  1458. if let Some(contract_no) = context.contract_no {
  1459. if is_base(call_contract_no, contract_no, ns) {
  1460. if let Some(loc) = call_args_loc {
  1461. diagnostics.push(Diagnostic::error(
  1462. loc,
  1463. "call arguments not allowed on internal calls".to_string(),
  1464. ));
  1465. return Err(());
  1466. }
  1467. return function_call_named_args(
  1468. loc,
  1469. func_name,
  1470. args,
  1471. available_functions(
  1472. &func_name.name,
  1473. false,
  1474. context.file_no,
  1475. Some(call_contract_no),
  1476. ns,
  1477. ),
  1478. false,
  1479. context,
  1480. resolve_to,
  1481. ns,
  1482. symtable,
  1483. diagnostics,
  1484. );
  1485. } else {
  1486. diagnostics.push(Diagnostic::error(
  1487. *loc,
  1488. "function calls via contract name are only valid for base contracts".into(),
  1489. ));
  1490. }
  1491. }
  1492. }
  1493. }
  1494. if let Some(mut path) = ns.expr_to_identifier_path(var) {
  1495. path.identifiers.push(func_name.clone());
  1496. if let Ok(list) = ns.resolve_free_function_with_namespace(
  1497. context.file_no,
  1498. &path,
  1499. &mut Diagnostics::default(),
  1500. ) {
  1501. if let Some(loc) = call_args_loc {
  1502. diagnostics.push(Diagnostic::error(
  1503. loc,
  1504. "call arguments not allowed on internal calls".to_string(),
  1505. ));
  1506. }
  1507. return function_call_named_args(
  1508. loc,
  1509. func_name,
  1510. args,
  1511. list.iter().map(|(_, no)| *no).collect(),
  1512. false,
  1513. context,
  1514. resolve_to,
  1515. ns,
  1516. symtable,
  1517. diagnostics,
  1518. );
  1519. }
  1520. }
  1521. let var_expr = expression(var, context, ns, symtable, diagnostics, ResolveTo::Unknown)?;
  1522. let var_ty = var_expr.ty();
  1523. if let Type::Contract(external_contract_no) = &var_ty.deref_any() {
  1524. let call_args = parse_call_args(loc, call_args, true, context, ns, symtable, diagnostics)?;
  1525. let mut arguments = HashMap::new();
  1526. // check if the arguments are not garbage
  1527. for arg in args {
  1528. if arguments.contains_key(arg.name.name.as_str()) {
  1529. diagnostics.push(Diagnostic::error(
  1530. arg.name.loc,
  1531. format!("duplicate argument with name '{}'", arg.name.name),
  1532. ));
  1533. let _ = expression(
  1534. &arg.expr,
  1535. context,
  1536. ns,
  1537. symtable,
  1538. diagnostics,
  1539. ResolveTo::Unknown,
  1540. );
  1541. continue;
  1542. }
  1543. arguments.insert(arg.name.name.as_str(), &arg.expr);
  1544. }
  1545. let mut errors = Diagnostics::default();
  1546. let mut name_matches: Vec<usize> = Vec::new();
  1547. // function call
  1548. for function_no in ns.contracts[*external_contract_no].all_functions.keys() {
  1549. if ns.functions[*function_no].name != func_name.name
  1550. || ns.functions[*function_no].ty != pt::FunctionTy::Function
  1551. {
  1552. continue;
  1553. }
  1554. name_matches.push(*function_no);
  1555. }
  1556. for function_no in &name_matches {
  1557. let func = &ns.functions[*function_no];
  1558. let unnamed_params = func.params.iter().filter(|p| p.id.is_none()).count();
  1559. let params_len = func.params.len();
  1560. let mut matches = true;
  1561. if unnamed_params > 0 {
  1562. errors.push(Diagnostic::cast_error_with_note(
  1563. *loc,
  1564. format!(
  1565. "function cannot be called with named arguments as {unnamed_params} of its parameters do not have names"
  1566. ),
  1567. func.loc,
  1568. format!("definition of {}", func.name),
  1569. ));
  1570. matches = false;
  1571. } else if params_len != args.len() {
  1572. errors.push(Diagnostic::cast_error(
  1573. *loc,
  1574. format!(
  1575. "function expects {} arguments, {} provided",
  1576. params_len,
  1577. args.len()
  1578. ),
  1579. ));
  1580. matches = false;
  1581. }
  1582. let mut cast_args = Vec::new();
  1583. for i in 0..params_len {
  1584. let param = ns.functions[*function_no].params[i].clone();
  1585. if param.id.is_none() {
  1586. continue;
  1587. }
  1588. let arg = match arguments.get(param.name_as_str()) {
  1589. Some(a) => a,
  1590. None => {
  1591. matches = false;
  1592. diagnostics.push(Diagnostic::cast_error(
  1593. *loc,
  1594. format!(
  1595. "missing argument '{}' to function '{}'",
  1596. param.name_as_str(),
  1597. func_name.name,
  1598. ),
  1599. ));
  1600. continue;
  1601. }
  1602. };
  1603. let arg = match expression(
  1604. arg,
  1605. context,
  1606. ns,
  1607. symtable,
  1608. &mut errors,
  1609. ResolveTo::Type(&param.ty),
  1610. ) {
  1611. Ok(e) => e,
  1612. Err(()) => {
  1613. matches = false;
  1614. continue;
  1615. }
  1616. };
  1617. match arg.cast(&arg.loc(), &param.ty, true, ns, &mut errors) {
  1618. Ok(expr) => cast_args.push(expr),
  1619. Err(()) => {
  1620. matches = false;
  1621. break;
  1622. }
  1623. }
  1624. }
  1625. if matches {
  1626. if !ns.functions[*function_no].is_public() {
  1627. diagnostics.push(Diagnostic::error(
  1628. *loc,
  1629. format!(
  1630. "function '{}' is not 'public' or 'external'",
  1631. func_name.name
  1632. ),
  1633. ));
  1634. } else if let Some(value) = &call_args.value {
  1635. if !value.const_zero(ns) && !ns.functions[*function_no].is_payable() {
  1636. diagnostics.push(Diagnostic::error(
  1637. *loc,
  1638. format!(
  1639. "sending value to function '{}' which is not payable",
  1640. func_name.name
  1641. ),
  1642. ));
  1643. }
  1644. }
  1645. let func = &ns.functions[*function_no];
  1646. let returns = function_returns(func, resolve_to);
  1647. let ty = function_type(func, true, resolve_to);
  1648. return Ok(Expression::ExternalFunctionCall {
  1649. loc: *loc,
  1650. returns,
  1651. function: Box::new(Expression::ExternalFunction {
  1652. loc: *loc,
  1653. ty,
  1654. function_no: *function_no,
  1655. address: Box::new(var_expr.cast(
  1656. &var.loc(),
  1657. &Type::Contract(func.contract_no.unwrap()),
  1658. true,
  1659. ns,
  1660. diagnostics,
  1661. )?),
  1662. }),
  1663. args: cast_args,
  1664. call_args,
  1665. });
  1666. } else if name_matches.len() > 1 && diagnostics.extend_non_casting(&errors) {
  1667. return Err(());
  1668. }
  1669. }
  1670. match name_matches.len() {
  1671. 0 => {
  1672. diagnostics.push(Diagnostic::error(
  1673. *loc,
  1674. format!(
  1675. "contract '{}' does not have function '{}'",
  1676. var_ty.deref_any().to_string(ns),
  1677. func_name.name
  1678. ),
  1679. ));
  1680. }
  1681. 1 => diagnostics.extend(errors),
  1682. _ => {
  1683. diagnostics.push(Diagnostic::error(
  1684. *loc,
  1685. "cannot find overloaded function which matches signature".to_string(),
  1686. ));
  1687. }
  1688. }
  1689. return Err(());
  1690. }
  1691. diagnostics.push(Diagnostic::error(
  1692. func_name.loc,
  1693. format!("method '{}' does not exist", func_name.name),
  1694. ));
  1695. Err(())
  1696. }
  1697. /// Function call arguments
  1698. pub fn collect_call_args<'a>(
  1699. expr: &'a pt::Expression,
  1700. diagnostics: &mut Diagnostics,
  1701. ) -> Result<
  1702. (
  1703. &'a pt::Expression,
  1704. Vec<&'a pt::NamedArgument>,
  1705. Option<pt::Loc>,
  1706. ),
  1707. (),
  1708. > {
  1709. let mut named_arguments = Vec::new();
  1710. let mut expr = expr;
  1711. let mut loc: Option<pt::Loc> = None;
  1712. while let pt::Expression::FunctionCallBlock(_, e, block) = expr {
  1713. match block.as_ref() {
  1714. pt::Statement::Args(_, args) => {
  1715. if let Some(pt::Loc::File(file_no, start, _)) = loc {
  1716. loc = Some(pt::Loc::File(file_no, start, block.loc().end()));
  1717. } else {
  1718. loc = Some(block.loc());
  1719. }
  1720. named_arguments.extend(args);
  1721. }
  1722. pt::Statement::Block { statements, .. } if statements.is_empty() => {
  1723. // {}
  1724. diagnostics.push(Diagnostic::error(
  1725. block.loc(),
  1726. "missing call arguments".to_string(),
  1727. ));
  1728. return Err(());
  1729. }
  1730. _ => {
  1731. diagnostics.push(Diagnostic::error(
  1732. block.loc(),
  1733. "code block found where list of call arguments expected, like '{gas: 5000}'"
  1734. .to_string(),
  1735. ));
  1736. return Err(());
  1737. }
  1738. }
  1739. expr = e;
  1740. }
  1741. Ok((expr, named_arguments, loc))
  1742. }
  1743. /// Parse call arguments for external calls
  1744. pub(super) fn parse_call_args(
  1745. loc: &pt::Loc,
  1746. call_args: &[&pt::NamedArgument],
  1747. external_call: bool,
  1748. context: &ExprContext,
  1749. ns: &mut Namespace,
  1750. symtable: &mut Symtable,
  1751. diagnostics: &mut Diagnostics,
  1752. ) -> Result<CallArgs, ()> {
  1753. let mut args: HashMap<&String, &pt::NamedArgument> = HashMap::new();
  1754. for arg in call_args {
  1755. if let Some(prev) = args.get(&arg.name.name) {
  1756. diagnostics.push(Diagnostic::error_with_note(
  1757. arg.loc,
  1758. format!("'{}' specified multiple times", arg.name.name),
  1759. prev.loc,
  1760. format!("location of previous declaration of '{}'", arg.name.name),
  1761. ));
  1762. return Err(());
  1763. }
  1764. args.insert(&arg.name.name, arg);
  1765. }
  1766. let mut res = CallArgs::default();
  1767. for arg in args.values() {
  1768. match arg.name.name.as_str() {
  1769. "value" => {
  1770. if ns.target == Target::Solana {
  1771. diagnostics.push(Diagnostic::error(
  1772. arg.loc,
  1773. "Solana Cross Program Invocation (CPI) cannot transfer native value. See https://solang.readthedocs.io/en/latest/language/functions.html#value_transfer".to_string(),
  1774. ));
  1775. expression(
  1776. &arg.expr,
  1777. context,
  1778. ns,
  1779. symtable,
  1780. diagnostics,
  1781. ResolveTo::Unknown,
  1782. )?;
  1783. } else {
  1784. let ty = Type::Value;
  1785. let expr = expression(
  1786. &arg.expr,
  1787. context,
  1788. ns,
  1789. symtable,
  1790. diagnostics,
  1791. ResolveTo::Type(&ty),
  1792. )?;
  1793. res.value = Some(Box::new(expr.cast(
  1794. &arg.expr.loc(),
  1795. &ty,
  1796. true,
  1797. ns,
  1798. diagnostics,
  1799. )?));
  1800. }
  1801. }
  1802. "gas" => {
  1803. if ns.target == Target::Solana {
  1804. diagnostics.push(Diagnostic::error(
  1805. arg.loc,
  1806. format!(
  1807. "'gas' not permitted for external calls or constructors on {}",
  1808. ns.target
  1809. ),
  1810. ));
  1811. return Err(());
  1812. }
  1813. let ty = Type::Uint(64);
  1814. let expr = expression(
  1815. &arg.expr,
  1816. context,
  1817. ns,
  1818. symtable,
  1819. diagnostics,
  1820. ResolveTo::Type(&ty),
  1821. )?;
  1822. res.gas = Some(Box::new(expr.cast(
  1823. &arg.expr.loc(),
  1824. &ty,
  1825. true,
  1826. ns,
  1827. diagnostics,
  1828. )?));
  1829. }
  1830. "salt" => {
  1831. if ns.target == Target::Solana {
  1832. diagnostics.push(Diagnostic::error(
  1833. arg.loc,
  1834. format!(
  1835. "'salt' not permitted for external calls or constructors on {}",
  1836. ns.target
  1837. ),
  1838. ));
  1839. return Err(());
  1840. }
  1841. if external_call {
  1842. diagnostics.push(Diagnostic::error(
  1843. arg.loc,
  1844. "'salt' not valid for external calls".to_string(),
  1845. ));
  1846. return Err(());
  1847. }
  1848. let ty = Type::Bytes(32);
  1849. let expr = expression(
  1850. &arg.expr,
  1851. context,
  1852. ns,
  1853. symtable,
  1854. diagnostics,
  1855. ResolveTo::Type(&ty),
  1856. )?;
  1857. res.salt = Some(Box::new(expr.cast(
  1858. &arg.expr.loc(),
  1859. &ty,
  1860. true,
  1861. ns,
  1862. diagnostics,
  1863. )?));
  1864. }
  1865. "accounts" => {
  1866. if ns.target != Target::Solana {
  1867. diagnostics.push(Diagnostic::error(
  1868. arg.loc,
  1869. format!(
  1870. "'accounts' not permitted for external calls or constructors on {}",
  1871. ns.target
  1872. ),
  1873. ));
  1874. return Err(());
  1875. }
  1876. let expr = expression(
  1877. &arg.expr,
  1878. context,
  1879. ns,
  1880. symtable,
  1881. diagnostics,
  1882. ResolveTo::Unknown,
  1883. )?;
  1884. let mut correct_ty = false;
  1885. let expr_ty = expr.ty();
  1886. // if let chains would really help here
  1887. if let Type::Array(elem_ty, dims) = expr_ty.deref_memory() {
  1888. if elem_ty.is_builtin_struct() == Some(StructType::AccountMeta)
  1889. && dims.len() == 1
  1890. {
  1891. correct_ty = true;
  1892. }
  1893. }
  1894. if !correct_ty {
  1895. diagnostics.push(Diagnostic::error(
  1896. arg.loc,
  1897. format!(
  1898. "'accounts' takes array of AccountMeta, not '{}'",
  1899. expr_ty.to_string(ns)
  1900. ),
  1901. ));
  1902. return Err(());
  1903. } else if expr_ty.is_dynamic(ns) {
  1904. diagnostics.push(Diagnostic::error(
  1905. arg.loc,
  1906. "dynamic array is not supported for the 'accounts' argument".to_string(),
  1907. ));
  1908. }
  1909. res.accounts = Some(Box::new(expr));
  1910. }
  1911. "seeds" => {
  1912. if ns.target != Target::Solana {
  1913. diagnostics.push(Diagnostic::error(
  1914. arg.loc,
  1915. format!(
  1916. "'seeds' not permitted for external calls or constructors on {}",
  1917. ns.target
  1918. ),
  1919. ));
  1920. return Err(());
  1921. }
  1922. let ty = Type::Slice(Box::new(Type::Slice(Box::new(Type::Bytes(1)))));
  1923. let expr = expression(
  1924. &arg.expr,
  1925. context,
  1926. ns,
  1927. symtable,
  1928. diagnostics,
  1929. ResolveTo::Type(&ty),
  1930. )?;
  1931. res.seeds = Some(Box::new(expr));
  1932. }
  1933. "flags" => {
  1934. if !(ns.target.is_polkadot() && external_call) {
  1935. diagnostics.push(Diagnostic::error(
  1936. arg.loc,
  1937. "'flags' are only permitted for external calls on polkadot".into(),
  1938. ));
  1939. return Err(());
  1940. }
  1941. let ty = Type::Uint(32);
  1942. let expr = expression(
  1943. &arg.expr,
  1944. context,
  1945. ns,
  1946. symtable,
  1947. diagnostics,
  1948. ResolveTo::Type(&ty),
  1949. )?;
  1950. let flags = expr.cast(&arg.expr.loc(), &ty, true, ns, diagnostics)?;
  1951. res.flags = Some(flags.into());
  1952. }
  1953. _ => {
  1954. diagnostics.push(Diagnostic::error(
  1955. arg.loc,
  1956. format!("'{}' not a valid call parameter", arg.name.name),
  1957. ));
  1958. return Err(());
  1959. }
  1960. }
  1961. }
  1962. // address is required on solana constructors
  1963. if ns.target == Target::Solana
  1964. && !external_call
  1965. && res.accounts.is_none()
  1966. && !matches!(
  1967. ns.functions[context.function_no.unwrap()].visibility,
  1968. Visibility::External(_)
  1969. )
  1970. && !ns.functions[context.function_no.unwrap()].is_constructor()
  1971. {
  1972. diagnostics.push(Diagnostic::error(
  1973. *loc,
  1974. "accounts are required for calling a contract. You can either provide the \
  1975. accounts with the {accounts: ...} call argument or change this function's \
  1976. visibility to external"
  1977. .to_string(),
  1978. ));
  1979. return Err(());
  1980. }
  1981. Ok(res)
  1982. }
  1983. pub fn named_call_expr(
  1984. loc: &pt::Loc,
  1985. ty: &pt::Expression,
  1986. args: &[pt::NamedArgument],
  1987. is_destructible: bool,
  1988. context: &ExprContext,
  1989. ns: &mut Namespace,
  1990. symtable: &mut Symtable,
  1991. diagnostics: &mut Diagnostics,
  1992. resolve_to: ResolveTo,
  1993. ) -> Result<Expression, ()> {
  1994. let mut nullsink = Diagnostics::default();
  1995. // is it a struct literal
  1996. match ns.resolve_type(
  1997. context.file_no,
  1998. context.contract_no,
  1999. true,
  2000. ty,
  2001. &mut nullsink,
  2002. ) {
  2003. Ok(Type::Struct(str_ty)) => {
  2004. return named_struct_literal(loc, &str_ty, args, context, ns, symtable, diagnostics);
  2005. }
  2006. Ok(_) => {
  2007. diagnostics.push(Diagnostic::error(
  2008. *loc,
  2009. "struct or function expected".to_string(),
  2010. ));
  2011. return Err(());
  2012. }
  2013. _ => {}
  2014. }
  2015. // not a struct literal, remove those errors and try resolving as function call
  2016. if context.constant {
  2017. diagnostics.push(Diagnostic::error(
  2018. *loc,
  2019. "cannot call function in constant expression".to_string(),
  2020. ));
  2021. return Err(());
  2022. }
  2023. let expr = named_function_call_expr(
  2024. loc,
  2025. ty,
  2026. args,
  2027. context,
  2028. ns,
  2029. symtable,
  2030. diagnostics,
  2031. resolve_to,
  2032. )?;
  2033. check_function_call(ns, &expr, symtable);
  2034. if expr.tys().len() > 1 && !is_destructible {
  2035. diagnostics.push(Diagnostic::error(
  2036. *loc,
  2037. "destucturing statement needed for function that returns multiple values".to_string(),
  2038. ));
  2039. return Err(());
  2040. }
  2041. Ok(expr)
  2042. }
  2043. /// Resolve any callable expression
  2044. pub fn call_expr(
  2045. loc: &pt::Loc,
  2046. ty: &pt::Expression,
  2047. args: &[pt::Expression],
  2048. is_destructible: bool,
  2049. context: &ExprContext,
  2050. ns: &mut Namespace,
  2051. symtable: &mut Symtable,
  2052. diagnostics: &mut Diagnostics,
  2053. resolve_to: ResolveTo,
  2054. ) -> Result<Expression, ()> {
  2055. let mut nullsink = Diagnostics::default();
  2056. let ty = ty.remove_parenthesis();
  2057. match ns.resolve_type(
  2058. context.file_no,
  2059. context.contract_no,
  2060. true,
  2061. ty,
  2062. &mut nullsink,
  2063. ) {
  2064. Ok(Type::Struct(str_ty)) => {
  2065. return struct_literal(loc, &str_ty, args, context, ns, symtable, diagnostics);
  2066. }
  2067. Ok(to) => {
  2068. // Cast
  2069. return if args.is_empty() {
  2070. diagnostics.push(Diagnostic::error(
  2071. *loc,
  2072. "missing argument to cast".to_string(),
  2073. ));
  2074. Err(())
  2075. } else if args.len() > 1 {
  2076. diagnostics.push(Diagnostic::error(
  2077. *loc,
  2078. "too many arguments to cast".to_string(),
  2079. ));
  2080. Err(())
  2081. } else {
  2082. let expr = expression(
  2083. &args[0],
  2084. context,
  2085. ns,
  2086. symtable,
  2087. diagnostics,
  2088. ResolveTo::Unknown,
  2089. )?;
  2090. expr.cast(loc, &to, false, ns, diagnostics)
  2091. };
  2092. }
  2093. Err(_) => (),
  2094. }
  2095. let expr = match ty.remove_parenthesis() {
  2096. pt::Expression::New(_, ty) => new(loc, ty, args, context, ns, symtable, diagnostics)?,
  2097. pt::Expression::FunctionCallBlock(loc, expr, _)
  2098. if matches!(expr.remove_parenthesis(), pt::Expression::New(..)) =>
  2099. {
  2100. new(loc, ty, args, context, ns, symtable, diagnostics)?
  2101. }
  2102. _ => {
  2103. deprecated_constructor_arguments(ty, diagnostics)?;
  2104. function_call_expr(
  2105. loc,
  2106. ty,
  2107. args,
  2108. context,
  2109. ns,
  2110. symtable,
  2111. diagnostics,
  2112. resolve_to,
  2113. )?
  2114. }
  2115. };
  2116. check_function_call(ns, &expr, symtable);
  2117. if expr.tys().len() > 1 && !is_destructible {
  2118. diagnostics.push(Diagnostic::error(
  2119. *loc,
  2120. "destucturing statement needed for function that returns multiple values".to_string(),
  2121. ));
  2122. return Err(());
  2123. }
  2124. Ok(expr)
  2125. }
  2126. /// Resolve function call
  2127. pub fn function_call_expr(
  2128. loc: &pt::Loc,
  2129. ty: &pt::Expression,
  2130. args: &[pt::Expression],
  2131. context: &ExprContext,
  2132. ns: &mut Namespace,
  2133. symtable: &mut Symtable,
  2134. diagnostics: &mut Diagnostics,
  2135. resolve_to: ResolveTo,
  2136. ) -> Result<Expression, ()> {
  2137. let (ty, call_args, call_args_loc) = collect_call_args(ty, diagnostics)?;
  2138. match ty.remove_parenthesis() {
  2139. pt::Expression::MemberAccess(_, member, func) => method_call_pos_args(
  2140. loc,
  2141. member,
  2142. func,
  2143. args,
  2144. &call_args,
  2145. call_args_loc,
  2146. context,
  2147. ns,
  2148. symtable,
  2149. diagnostics,
  2150. resolve_to,
  2151. ),
  2152. pt::Expression::Variable(id) => {
  2153. // is it a builtin
  2154. if builtin::is_builtin_call(None, &id.name, ns) {
  2155. return {
  2156. let expr = builtin::resolve_call(
  2157. &id.loc,
  2158. None,
  2159. &id.name,
  2160. args,
  2161. context,
  2162. ns,
  2163. symtable,
  2164. diagnostics,
  2165. )?;
  2166. if expr.tys().len() > 1 {
  2167. diagnostics.push(Diagnostic::error(
  2168. *loc,
  2169. format!("builtin function '{}' returns more than one value", id.name),
  2170. ));
  2171. Err(())
  2172. } else {
  2173. Ok(expr)
  2174. }
  2175. };
  2176. }
  2177. if context.constant {
  2178. diagnostics.push(Diagnostic::error(
  2179. *loc,
  2180. "cannot call function in constant expression".to_string(),
  2181. ));
  2182. return Err(());
  2183. }
  2184. // is there a local variable or contract variable with this name
  2185. if symtable.find(&id.name).is_some()
  2186. || matches!(
  2187. ns.resolve_var(context.file_no, context.contract_no, id, true),
  2188. Some(Symbol::Variable(..))
  2189. )
  2190. {
  2191. call_function_type(
  2192. loc,
  2193. ty,
  2194. args,
  2195. &call_args,
  2196. call_args_loc,
  2197. context,
  2198. ns,
  2199. symtable,
  2200. diagnostics,
  2201. resolve_to,
  2202. )
  2203. } else {
  2204. if let Some(loc) = call_args_loc {
  2205. diagnostics.push(Diagnostic::error(
  2206. loc,
  2207. "call arguments not permitted for internal calls".to_string(),
  2208. ));
  2209. return Err(());
  2210. }
  2211. function_call_pos_args(
  2212. loc,
  2213. id,
  2214. pt::FunctionTy::Function,
  2215. args,
  2216. available_functions(&id.name, true, context.file_no, context.contract_no, ns),
  2217. true,
  2218. context,
  2219. ns,
  2220. resolve_to,
  2221. symtable,
  2222. diagnostics,
  2223. )
  2224. }
  2225. }
  2226. _ => call_function_type(
  2227. loc,
  2228. ty,
  2229. args,
  2230. &call_args,
  2231. call_args_loc,
  2232. context,
  2233. ns,
  2234. symtable,
  2235. diagnostics,
  2236. resolve_to,
  2237. ),
  2238. }
  2239. }
  2240. /// Resolve function call expression with named arguments
  2241. pub fn named_function_call_expr(
  2242. loc: &pt::Loc,
  2243. ty: &pt::Expression,
  2244. args: &[pt::NamedArgument],
  2245. context: &ExprContext,
  2246. ns: &mut Namespace,
  2247. symtable: &mut Symtable,
  2248. diagnostics: &mut Diagnostics,
  2249. resolve_to: ResolveTo,
  2250. ) -> Result<Expression, ()> {
  2251. let (ty, call_args, call_args_loc) = collect_call_args(ty, diagnostics)?;
  2252. match ty {
  2253. pt::Expression::MemberAccess(_, member, func) => method_call_named_args(
  2254. loc,
  2255. member,
  2256. func,
  2257. args,
  2258. &call_args,
  2259. call_args_loc,
  2260. context,
  2261. ns,
  2262. symtable,
  2263. diagnostics,
  2264. resolve_to,
  2265. ),
  2266. pt::Expression::Variable(id) => {
  2267. if let Some(loc) = call_args_loc {
  2268. diagnostics.push(Diagnostic::error(
  2269. loc,
  2270. "call arguments not permitted for internal calls".to_string(),
  2271. ));
  2272. return Err(());
  2273. }
  2274. function_call_named_args(
  2275. loc,
  2276. id,
  2277. args,
  2278. available_functions(&id.name, true, context.file_no, context.contract_no, ns),
  2279. true,
  2280. context,
  2281. resolve_to,
  2282. ns,
  2283. symtable,
  2284. diagnostics,
  2285. )
  2286. }
  2287. pt::Expression::ArraySubscript(..) => {
  2288. diagnostics.push(Diagnostic::error(
  2289. ty.loc(),
  2290. "unexpected array type".to_string(),
  2291. ));
  2292. Err(())
  2293. }
  2294. _ => {
  2295. diagnostics.push(Diagnostic::error(
  2296. ty.loc(),
  2297. "expression not expected here".to_string(),
  2298. ));
  2299. Err(())
  2300. }
  2301. }
  2302. }
  2303. /// Get the return values for a function call
  2304. pub(crate) fn function_returns(ftype: &Function, resolve_to: ResolveTo) -> Vec<Type> {
  2305. if !ftype.returns.is_empty() && !matches!(resolve_to, ResolveTo::Discard) {
  2306. ftype.returns.iter().map(|p| p.ty.clone()).collect()
  2307. } else {
  2308. vec![Type::Void]
  2309. }
  2310. }
  2311. /// Get the function type for an internal.external function call
  2312. pub(crate) fn function_type(func: &Function, external: bool, resolve_to: ResolveTo) -> Type {
  2313. let params = func.params.iter().map(|p| p.ty.clone()).collect();
  2314. let mutability = func.mutability.clone();
  2315. let returns = function_returns(func, resolve_to);
  2316. if external {
  2317. Type::ExternalFunction {
  2318. params,
  2319. mutability,
  2320. returns,
  2321. }
  2322. } else {
  2323. Type::InternalFunction {
  2324. params,
  2325. mutability,
  2326. returns,
  2327. }
  2328. }
  2329. }
  2330. /// This function evaluates the arguments of a function call with either positional arguments or
  2331. /// named arguments.
  2332. fn evaluate_argument(
  2333. arg: &pt::Expression,
  2334. context: &ExprContext,
  2335. ns: &mut Namespace,
  2336. symtable: &mut Symtable,
  2337. arg_ty: &Type,
  2338. errors: &mut Diagnostics,
  2339. cast_args: &mut Vec<Expression>,
  2340. ) -> bool {
  2341. expression(arg, context, ns, symtable, errors, ResolveTo::Type(arg_ty))
  2342. .and_then(|arg| arg.cast(&arg.loc(), arg_ty, true, ns, errors))
  2343. .map(|expr| cast_args.push(expr))
  2344. .is_ok()
  2345. }
  2346. /// This function finishes resolving internal function calls. It returns None if it is not
  2347. /// possible to resolve the function.
  2348. fn resolve_internal_call(
  2349. loc: &Loc,
  2350. function_no: usize,
  2351. context: &ExprContext,
  2352. resolve_to: ResolveTo,
  2353. virtual_call: bool,
  2354. cast_args: Vec<Expression>,
  2355. ns: &Namespace,
  2356. errors: &mut Diagnostics,
  2357. ) -> Option<Expression> {
  2358. let func = &ns.functions[function_no];
  2359. if func.contract_no != context.contract_no && func.is_private() {
  2360. errors.push(Diagnostic::error_with_note(
  2361. *loc,
  2362. format!("cannot call private {}", func.ty),
  2363. func.loc,
  2364. format!("declaration of {} '{}'", func.ty, func.name),
  2365. ));
  2366. return None;
  2367. } else if let (Some(base_no), Some(derived_no)) = (func.contract_no, context.contract_no) {
  2368. if is_base(base_no, derived_no, ns) && matches!(func.visibility, Visibility::External(_)) {
  2369. if func.is_accessor {
  2370. errors.push(Diagnostic::error_with_note(
  2371. *loc,
  2372. "accessor function cannot be called via an internal function call".to_string(),
  2373. func.loc,
  2374. format!("declaration of '{}'", func.name),
  2375. ));
  2376. } else {
  2377. errors.push(Diagnostic::error_with_note(
  2378. *loc,
  2379. "functions declared external cannot be called via an internal function call"
  2380. .to_string(),
  2381. func.loc,
  2382. format!("declaration of {} '{}'", func.ty, func.name),
  2383. ));
  2384. }
  2385. return None;
  2386. }
  2387. }
  2388. let returns = function_returns(func, resolve_to);
  2389. let ty = function_type(func, false, resolve_to);
  2390. Some(Expression::InternalFunctionCall {
  2391. loc: *loc,
  2392. returns,
  2393. function: Box::new(Expression::InternalFunction {
  2394. loc: *loc,
  2395. ty,
  2396. function_no,
  2397. signature: if virtual_call && (func.is_virtual || func.is_override.is_some()) {
  2398. Some(func.signature.clone())
  2399. } else {
  2400. None
  2401. },
  2402. }),
  2403. args: cast_args,
  2404. })
  2405. }