functions.rst 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. Functions
  2. =========
  3. Functions in Yul cannot access any variable outside their scope, i.e. they can
  4. only operate with the variables they receive as arguments. You can define types for arguments and returns. If no
  5. type is specified, the compiler will default to ``u256``.
  6. .. warning::
  7. Yul functions are only available within the scope there are defined. They cannot be accessed from Solidity
  8. and from other inline assembly blocks, even if they are contained within the same Solidity function.
  9. Differently from solc, Solang allows name shadowing inside Yul
  10. functions. As they cannot access variables declared outside them, a redefinition of an outside name is allowed, if
  11. it has not been declared within the function yet. Builtin function names cannot be overdriven and verbatim functions
  12. supported by Solc are not implemented in Solang. ``verbatim``, nevertheless, is still a reserved keyword and
  13. cannot be the prefix of variable or function names.
  14. Function calls are identified by a name followed by parenthesis. If the types of the arguments passed to function
  15. calls do not match the respective parameter's type, Solang will implicitly convert them. Likewise, the returned
  16. values of function calls will be implicitly converted to match the type needed in an expression context.
  17. .. code-block:: yul
  18. {
  19. // return type defaulted to u256
  20. function noArgs() -> ret
  21. {
  22. ret := 2
  23. }
  24. // Parameters defaulted to u256 and ret has type u64
  25. function sum(a, b) -> ret : u64
  26. {
  27. ret := add(b, a)
  28. }
  29. function getMod(c : s32, d : u128, e) -> ret1, ret2 : u64
  30. {
  31. ret1 := mulmod(c, d, e)
  32. ret2 := addmod(c, d, e)
  33. }
  34. function noReturns(a, b)
  35. {
  36. // Syntax of function calls
  37. let x := noArgs()
  38. // Arguments will be implicitly converted form u256 to s32 and u128, respectively.
  39. // The returns will also be converted to u256
  40. let c, d := getMod(a, b)
  41. {
  42. // 'doThis' cannot be called from outside the block defined the by curly brackets.
  43. function doThis(f, g) -> ret {
  44. ret := sdiv(f, g)
  45. }
  46. }
  47. // 'doThat' cannot be called from outside 'noReturns'
  48. function doThat(f, g) -> ret {
  49. ret := smod(g, f)
  50. }
  51. }
  52. }