可用于(内联)装配的语言: Joyfully Universal Language for (Inline) Assembly¶

JULIA is an intermediate language that can compile to various different backends(EVM 1.0, EVM 1.5 and eWASM are planned).Because of that, it is designed to be a usable common denominator of all threeplatforms.It can already be used for “inline assembly” inside Solidity andfuture versions of the Solidity compiler will even use JULIA as intermediatelanguage. It should also be easy to build high-level optimizer stages for JULIA.

Note

Note that the flavour used for “inline assembly” does not have types(everything is u256) and the built-in functions are identicalto the EVM opcodes. Please resort to the inline assembly documentationfor details.

The core components of JULIA are functions, blocks, variables, literals,for-loops, if-statements, switch-statements, expressions and assignments to variables.

JULIA is typed, both variables and literals must specify the type with postfixnotation. The supported types are bool, u8, s8, u32, s32,u64, s64, u128, s128, u256 and s256.

JULIA in itself does not even provide operators. If the EVM is targeted,opcodes will be available as built-in functions, but they can be reimplementedif the backend changes. For a list of mandatory built-in functions, see the section below.

The following example program assumes that the EVM opcodes mul, divand mod are available either natively or as functions and computes exponentiation.

  1. {
  2. function power(base:u256, exponent:u256) -> result:u256
  3. {
  4. switch exponent
  5. case 0:u256 { result := 1:u256 }
  6. case 1:u256 { result := base }
  7. default:
  8. {
  9. result := power(mul(base, base), div(exponent, 2:u256))
  10. switch mod(exponent, 2:u256)
  11. case 1:u256 { result := mul(base, result) }
  12. }
  13. }
  14. }

It is also possible to implement the same function using a for-loopinstead of with recursion. Here, we need the EVM opcodes lt (less-than)and add to be available.

  1. {
  2. function power(base:u256, exponent:u256) -> result:u256
  3. {
  4. result := 1:u256
  5. for { let i := 0:u256 } lt(i, exponent) { i := add(i, 1:u256) }
  6. {
  7. result := mul(result, base)
  8. }
  9. }
  10. }

Specification of JULIA¶

JULIA code is described in this chapter. JULIA code is usually placed into a JULIA object, which is described in the following chapter.

Grammar:

  1. Block = '{' Statement* '}'
  2. Statement =
  3. Block |
  4. FunctionDefinition |
  5. VariableDeclaration |
  6. Assignment |
  7. Expression |
  8. Switch |
  9. ForLoop |
  10. BreakContinue
  11. FunctionDefinition =
  12. 'function' Identifier '(' TypedIdentifierList? ')'
  13. ( '->' TypedIdentifierList )? Block
  14. VariableDeclaration =
  15. 'let' TypedIdentifierList ( ':=' Expression )?
  16. Assignment =
  17. IdentifierList ':=' Expression
  18. Expression =
  19. FunctionCall | Identifier | Literal
  20. If =
  21. 'if' Expression Block
  22. Switch =
  23. 'switch' Expression Case* ( 'default' Block )?
  24. Case =
  25. 'case' Literal Block
  26. ForLoop =
  27. 'for' Block Expression Block Block
  28. BreakContinue =
  29. 'break' | 'continue'
  30. FunctionCall =
  31. Identifier '(' ( Expression ( ',' Expression )* )? ')'
  32. Identifier = [a-zA-Z_$] [a-zA-Z_0-9]*
  33. IdentifierList = Identifier ( ',' Identifier)*
  34. TypeName = Identifier | BuiltinTypeName
  35. BuiltinTypeName = 'bool' | [us] ( '8' | '32' | '64' | '128' | '256' )
  36. TypedIdentifierList = Identifier ':' TypeName ( ',' Identifier ':' TypeName )*
  37. Literal =
  38. (NumberLiteral | StringLiteral | HexLiteral | TrueLiteral | FalseLiteral) ':' TypeName
  39. NumberLiteral = HexNumber | DecimalNumber
  40. HexLiteral = 'hex' ('"' ([0-9a-fA-F]{2})* '"' | '\'' ([0-9a-fA-F]{2})* '\'')
  41. StringLiteral = '"' ([^"\r\n\\] | '\\' .)* '"'
  42. TrueLiteral = 'true'
  43. FalseLiteral = 'false'
  44. HexNumber = '0x' [0-9a-fA-F]+
  45. DecimalNumber = [0-9]+

Restrictions on the Grammar¶

Switches must have at least one case (including the default case).If all possible values of the expression is covered, the default case shouldnot be allowed (i.e. a switch with a bool expression and having both atrue and false case should not allow a default case).

Every expression evaluates to zero or more values. Identifiers and Literalsevaluate to exactlyone value and function calls evaluate to a number of values equal to thenumber of return values of the function called.

In variable declarations and assignments, the right-hand-side expression(if present) has to evaluate to a number of values equal to the number ofvariables on the left-hand-side.This is the only situation where an expression evaluatingto more than one value is allowed.

Expressions that are also statements (i.e. at the block level) have toevaluate to zero values.

In all other situations, expressions have to evaluate to exactly one value.

The continue and break statements can only be used inside loop bodiesand have to be in the same function as the loop (or both have to be at thetop level).The condition part of the for-loop has to evaluate to exactly one value.

Literals cannot be larger than the their type. The largest type defined is 256-bit wide.

Scoping Rules¶

Scopes in JULIA are tied to Blocks (exceptions are functions and the for loopas explained below) and all declarations(FunctionDefinition, VariableDeclaration)introduce new identifiers into these scopes.

Identifiers are visible inthe block they are defined in (including all sub-nodes and sub-blocks).As an exception, identifiers defined in the “init” part of the for-loop(the first block) are visible in all other parts of the for-loop(but not outside of the loop).Identifiers declared in the other parts of the for loop respect the regularsyntatical scoping rules.The parameters and return parameters of functions are visible in thefunction body and their names cannot overlap.

Variables can only be referenced after their declaration. In particular,variables cannot be referenced in the right hand side of their own variabledeclaration.Functions can be referenced already before their declaration (if they are visible).

Shadowing is disallowed, i.e. you cannot declare an identifier at a pointwhere another identifier with the same name is also visible, even if it isnot accessible.

Inside functions, it is not possible to access a variable that was declaredoutside of that function.

Formal Specification¶

We formally specify JULIA by providing an evaluation function E overloadedon the various nodes of the AST. Any functions can have side effects, soE takes two state objects and the AST node and returns two newstate objects and a variable number of other values.The two state objects are the global state object(which in the context of the EVM is the memory, storage and state of theblockchain) and the local state object (the state of local variables, i.e. asegment of the stack in the EVM).If the AST node is a statement, E returns the two state objects and a “mode”,which is used for the break and continue statements.If the AST node is an expression, E returns the two state objects andas many values as the expression evaluates to.

The exact nature of the global state is unspecified for this high leveldescription. The local state L is a mapping of identifiers i to values v,denoted as L[i] = v.

For an identifier v, let $v be the name of the identifier.

We will use a destructuring notation for the AST nodes.

  1. E(G, L, <{St1, ..., Stn}>: Block) =
  2. let G1, L1, mode = E(G, L, St1, ..., Stn)
  3. let L2 be a restriction of L1 to the identifiers of L
  4. G1, L2, mode
  5. E(G, L, St1, ..., Stn: Statement) =
  6. if n is zero:
  7. G, L, regular
  8. else:
  9. let G1, L1, mode = E(G, L, St1)
  10. if mode is regular then
  11. E(G1, L1, St2, ..., Stn)
  12. otherwise
  13. G1, L1, mode
  14. E(G, L, FunctionDefinition) =
  15. G, L, regular
  16. E(G, L, <let var1, ..., varn := rhs>: VariableDeclaration) =
  17. E(G, L, <var1, ..., varn := rhs>: Assignment)
  18. E(G, L, <let var1, ..., varn>: VariableDeclaration) =
  19. let L1 be a copy of L where L1[$vari] = 0 for i = 1, ..., n
  20. G, L1, regular
  21. E(G, L, <var1, ..., varn := rhs>: Assignment) =
  22. let G1, L1, v1, ..., vn = E(G, L, rhs)
  23. let L2 be a copy of L1 where L2[$vari] = vi for i = 1, ..., n
  24. G, L2, regular
  25. E(G, L, <for { i1, ..., in } condition post body>: ForLoop) =
  26. if n >= 1:
  27. let G1, L1, mode = E(G, L, i1, ..., in)
  28. // mode has to be regular due to the syntactic restrictions
  29. let G2, L2, mode = E(G1, L1, for {} condition post body)
  30. // mode has to be regular due to the syntactic restrictions
  31. let L3 be the restriction of L2 to only variables of L
  32. G2, L3, regular
  33. else:
  34. let G1, L1, v = E(G, L, condition)
  35. if v is false:
  36. G1, L1, regular
  37. else:
  38. let G2, L2, mode = E(G1, L, body)
  39. if mode is break:
  40. G2, L2, regular
  41. else:
  42. G3, L3, mode = E(G2, L2, post)
  43. E(G3, L3, for {} condition post body)
  44. E(G, L, break: BreakContinue) =
  45. G, L, break
  46. E(G, L, continue: BreakContinue) =
  47. G, L, continue
  48. E(G, L, <if condition body>: If) =
  49. let G0, L0, v = E(G, L, condition)
  50. if v is true:
  51. E(G0, L0, body)
  52. else:
  53. G0, L0, regular
  54. E(G, L, <switch condition case l1:t1 st1 ... case ln:tn stn>: Switch) =
  55. E(G, L, switch condition case l1:t1 st1 ... case ln:tn stn default {})
  56. E(G, L, <switch condition case l1:t1 st1 ... case ln:tn stn default st'>: Switch) =
  57. let G0, L0, v = E(G, L, condition)
  58. // i = 1 .. n
  59. // Evaluate literals, context doesn't matter
  60. let _, _, v1 = E(G0, L0, l1)
  61. ...
  62. let _, _, vn = E(G0, L0, ln)
  63. if there exists smallest i such that vi = v:
  64. E(G0, L0, sti)
  65. else:
  66. E(G0, L0, st')
  67.  
  68. E(G, L, <name>: Identifier) =
  69. G, L, L[$name]
  70. E(G, L, <fname(arg1, ..., argn)>: FunctionCall) =
  71. G1, L1, vn = E(G, L, argn)
  72. ...
  73. G(n-1), L(n-1), v2 = E(G(n-2), L(n-2), arg2)
  74. Gn, Ln, v1 = E(G(n-1), L(n-1), arg1)
  75. Let <function fname (param1, ..., paramn) -> ret1, ..., retm block>
  76. be the function of name $fname visible at the point of the call.
  77. Let L' be a new local state such that
  78. L'[$parami] = vi and L'[$reti] = 0 for all i.
  79. Let G'', L'', mode = E(Gn, L', block)
  80. G'', Ln, L''[$ret1], ..., L''[$retm]
  81. E(G, L, l: HexLiteral) = G, L, hexString(l),
  82. where hexString decodes l from hex and left-aligns it into 32 bytes
  83. E(G, L, l: StringLiteral) = G, L, utf8EncodeLeftAligned(l),
  84. where utf8EncodeLeftAligned performs a utf8 encoding of l
  85. and aligns it left into 32 bytes
  86. E(G, L, n: HexNumber) = G, L, hex(n)
  87. where hex is the hexadecimal decoding function
  88. E(G, L, n: DecimalNumber) = G, L, dec(n),
  89. where dec is the decimal decoding function

Type Conversion Functions¶

JULIA has no support for implicit type conversion and therefore functions exists to provide explicit conversion.When converting a larger type to a shorter type a runtime exception can occur in case of an overflow.

The following type conversion functions must be available:- u32tobool(x:u32) -> y:bool- booltou32(x:bool) -> y:u32- u32tou64(x:u32) -> y:u64- u64tou32(x:u64) -> y:u32- etc. (TBD)

Low-level Functions¶

The following functions must be available:

|Arithmetics
|addu256(x:u256, y:u256) -> z:u256|x + y
|subu256(x:u256, y:u256) -> z:u256|x - y
|mulu256(x:u256, y:u256) -> z:u256|x y
|divu256(x:u256, y:u256) -> z:u256|x / y
|divs256(x:s256, y:s256) -> z:s256|x / y, for signed numbers in two’s complement
|modu256(x:u256, y:u256) -> z:u256|x % y
|mods256(x:s256, y:s256) -> z:s256|x % y, for signed numbers in two’s complement
|signextendu256(i:u256, x:u256) -> z:u256|sign extend from (i
8+7)th bit counting from least significant
|expu256(x:u256, y:u256) -> z:u256|x to the power of y
|addmodu256(x:u256, y:u256, m:u256) -> z:u256|(x + y) % m with arbitrary precision arithmetics
|mulmodu256(x:u256, y:u256, m:u256) -> z:u256|(x * y) % m with arbitrary precision arithmetics
|ltu256(x:u256, y:u256) -> z:bool|1 if x < y, 0 otherwise
|gtu256(x:u256, y:u256) -> z:bool|1 if x > y, 0 otherwise
|sltu256(x:s256, y:s256) -> z:bool|1 if x < y, 0 otherwise, for signed numbers in two’s complement
|sgtu256(x:s256, y:s256) -> z:bool|1 if x > y, 0 otherwise, for signed numbers in two’s complement
|equ256(x:u256, y:u256) -> z:bool|1 if x == y, 0 otherwise
|notu256(x:u256) -> z:u256|~x, every bit of x is negated
|andu256(x:u256, y:u256) -> z:u256|bitwise and of x and y
|oru256(x:u256, y:u256) -> z:u256|bitwise or of x and y
|xoru256(x:u256, y:u256) -> z:u256|bitwise xor of x and y
|shlu256(x:u256, y:u256) -> z:u256|logical left shift of x by y
|shru256(x:u256, y:u256) -> z:u256|logical right shift of x by y
|saru256(x:u256, y:u256) -> z:u256|arithmetic right shift of x by y
|byte(n:u256, x:u256) -> v:u256|nth byte of x, where the most significant byte is the 0th byteCannot this be just replaced by and256(shr256(n, x), 0xff) andlet it be optimised out by the EVM backend?
|Memory and storage
|mload(p:u256) -> v:u256|mem[p..(p+32))
|mstore(p:u256, v:u256)|mem[p..(p+32)) := v
|mstore8(p:u256, v:u256)|mem[p] := v & 0xff - only modifies a single byte
|sload(p:u256) -> v:u256|storage[p]
|sstore(p:u256, v:u256)|storage[p] := v
|msize() -> size:u256|size of memory, i.e. largest accessed memory index, albeit duedue to the memory extension function, which extends by words,this will always be a multiple of 32 bytes
|Execution control
|create(v:u256, p:u256, s:u256)|create new contract with code mem[p..(p+s)) and send v weiand return the new address
|call(g:u256, a:u256, v:u256, in:u256,insize:u256, out:u256,outsize:u256)-> r:u256|call contract at address a with input mem[in..(in+insize))providing g gas and v wei and output areamem[out..(out+outsize)) returning 0 on error (eg. out of gas)and 1 on success
|callcode(g:u256, a:u256, v:u256, in:u256,insize:u256, out:u256,outsize:u256) -> r:u256|identical to call but only use the code from aand stay in the context of thecurrent contract otherwise
|delegatecall(g:u256, a:u256, in:u256,insize:u256, out:u256,outsize:u256) -> r:u256|identical to callcode,but also keep callerand callvalue
|stop()|stop execution, identical to return(0,0)Perhaps it would make sense retiring this as it equals toreturn(0,0). It can be an optimisation by the EVM backend.
|abort()|abort (equals to invalid instruction on EVM)
|return(p:u256, s:u256)|end execution, return data mem[p..(p+s))
|revert(p:u256, s:u256)|end execution, revert state changes, return data mem[p..(p+s))
|selfdestruct(a:u256)|end execution, destroy current contract and send funds to a
|log0(p:u256, s:u256)|log without topics and data mem[p..(p+s))
|log1(p:u256, s:u256, t1:u256)|log with topic t1 and data mem[p..(p+s))
|log2(p:u256, s:u256, t1:u256, t2:u256)|log with topics t1, t2 and data mem[p..(p+s))
|log3(p:u256, s:u256, t1:u256, t2:u256,t3:u256)|log with topics t, t2, t3 and data mem[p..(p+s))
|log4(p:u256, s:u256, t1:u256, t2:u256,t3:u256, t4:u256)|log with topics t1, t2, t3, t4 and data mem[p..(p+s))
|State queries
|blockcoinbase() -> address:u256|current mining beneficiary
|blockdifficulty() -> difficulty:u256|difficulty of the current block
|blockgaslimit() -> limit:u256|block gas limit of the current block
|blockhash(b:u256) -> hash:u256|hash of block nr b - only for last 256 blocks excluding current
|blocknumber() -> block:u256|current block number
|blocktimestamp() -> timestamp:u256|timestamp of the current block in seconds since the epoch
|txorigin() -> address:u256|transaction sender
|txgasprice() -> price:u256|gas price of the transaction
|gasleft() -> gas:u256|gas still available to execution
|balance(a:u256) -> v:u256|wei balance at address a
|this() -> address:u256|address of the current contract / execution context
|caller() -> address:u256|call sender (excluding delegatecall)
|callvalue() -> v:u256|wei sent together with the current call
|calldataload(p:u256) -> v:u256|call data starting from position p (32 bytes)
|calldatasize() -> v:u256|size of call data in bytes
|calldatacopy(t:u256, f:u256, s:u256)|copy s bytes from calldata at position f to mem at position t
|codesize() -> size:u256|size of the code of the current contract / execution context
|codecopy(t:u256, f:u256, s:u256)|copy s bytes from code at position f to mem at position t
|extcodesize(a:u256) -> size:u256|size of the code at address a
|extcodecopy(a:u256, t:u256, f:u256, s:u256)|like codecopy(t, f, s) but take code at address a
|Others
|discardu256(unused:u256)|discard value
|

splitu256tou64(x:u256) -> (x1:u64, x2:u64,
x3:u64, x4:u64)
|split u256 to four u64’s
|
combineu64tou256(x1:u64, x2:u64, x3:u64,
x4:u64) -> (x:u256)
|combine four u64’s into a single u256
|sha3(p:u256, s:u256) -> v:u256|keccak(mem[p…(p+s)))

Backends¶

Backends or targets are the translators from JULIA to a specific bytecode. Each of the backends can expose functionsprefixed with the name of the backend. We reserve evm and ewasm prefixes for the two proposed backends.

Backend: EVM¶

The EVM target will have all the underlying EVM opcodes exposed with the evm_ prefix.

Backend: “EVM 1.5”¶

TBD

Backend: eWASM¶

TBD

Specification of JULIA Object¶

Grammar:

  1. TopLevelObject = 'object' '{' Code? ( Object | Data )* '}'
  2. Object = 'object' StringLiteral '{' Code? ( Object | Data )* '}'
  3. Code = 'code' Block
  4. Data = 'data' StringLiteral HexLiteral
  5. HexLiteral = 'hex' ('"' ([0-9a-fA-F]{2})* '"' | '\'' ([0-9a-fA-F]{2})* '\'')
  6. StringLiteral = '"' ([^"\r\n\\] | '\\' .)* '"'

Above, Block refers to Block in the JULIA code grammar explained in the previous chapter.

An example JULIA Object is shown below:

..code:

  1. // Code consists of a single object. A single "code" node is the code of the object.
  2. // Every (other) named object or data section is serialized and
  3. // made accessible to the special built-in functions datacopy / dataoffset / datasize
  4. object {
  5. code {
  6. let size = datasize("runtime")
  7. let offset = allocate(size)
  8. // This will turn into a memory->memory copy for eWASM and
  9. // a codecopy for EVM
  10. datacopy(dataoffset("runtime"), offset, size)
  11. // this is a constructor and the runtime code is returned
  12. return(offset, size)
  13. }
  14.  
  15. data "Table2" hex"4123"
  16.  
  17. object "runtime" {
  18. code {
  19. // runtime code
  20.  
  21. let size = datasize("Contract2")
  22. let offset = allocate(size)
  23. // This will turn into a memory->memory copy for eWASM and
  24. // a codecopy for EVM
  25. datacopy(dataoffset("Contract2"), offset, size)
  26. // constructor parameter is a single number 0x1234
  27. mstore(add(offset, size), 0x1234)
  28. create(offset, add(size, 32))
  29. }
  30.  
  31. // Embedded object. Use case is that the outside is a factory contract,
  32. // and Contract2 is the code to be created by the factory
  33. object "Contract2" {
  34. code {
  35. // code here ...
  36. }
  37.  
  38. object "runtime" {
  39. code {
  40. // code here ...
  41. }
  42. }
  43.  
  44. data "Table1" hex"4123"
  45. }
  46. }
  47. }

原文: http://solidity.apachecn.org/cn/doc/v0.4.21/julia.html