aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CMakeLists.txt7
-rw-r--r--Changelog.md5
-rw-r--r--cmake/templates/license.h.in4
-rw-r--r--docs/abi-spec.rst345
-rw-r--r--docs/assembly.rst6
-rw-r--r--docs/contracts.rst2
-rw-r--r--docs/index.rst4
-rw-r--r--libevmasm/GasMeter.cpp1
-rw-r--r--libevmasm/Instruction.cpp4
-rw-r--r--libevmasm/Instruction.h1
-rw-r--r--libevmasm/SemanticInformation.cpp2
-rw-r--r--libjulia/backends/evm/EVMCodeTransform.cpp55
-rw-r--r--libjulia/backends/evm/EVMCodeTransform.h31
-rw-r--r--liblll/CompilerState.cpp5
-rw-r--r--libsolidity/ast/ASTJsonConverter.cpp1
-rw-r--r--libsolidity/inlineasm/AsmAnalysis.cpp26
-rw-r--r--libsolidity/inlineasm/AsmAnalysis.h8
-rw-r--r--libsolidity/inlineasm/AsmParser.cpp13
-rw-r--r--libsolidity/inlineasm/AsmScope.cpp2
-rw-r--r--libsolidity/inlineasm/AsmScope.h19
-rw-r--r--libsolidity/interface/AssemblyStack.cpp16
-rw-r--r--libsolidity/interface/AssemblyStack.h8
-rw-r--r--libsolidity/parsing/Parser.cpp13
-rw-r--r--solc/CommandLineInterface.cpp20
-rw-r--r--solc/jsonCompiler.cpp7
-rw-r--r--test/liblll/EndToEndTest.cpp57
-rw-r--r--test/libsolidity/ASTJSON.cpp30
-rw-r--r--test/libsolidity/InlineAssembly.cpp12
-rw-r--r--test/libsolidity/JSONCompiler.cpp10
-rw-r--r--test/libsolidity/SolidityNameAndTypeResolution.cpp8
-rw-r--r--test/libsolidity/SolidityParser.cpp11
-rw-r--r--test/libsolidity/StandardCompiler.cpp2
32 files changed, 646 insertions, 89 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 2dbc521d..d6ed6643 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -25,7 +25,12 @@ include(EthExecutableHelper)
include(EthUtils)
# Create license.h from LICENSE.txt and template
-file(READ ${CMAKE_SOURCE_DIR}/LICENSE.txt LICENSE_TEXT)
+# Converting to char array is required due to MSVC's string size limit.
+file(READ ${CMAKE_SOURCE_DIR}/LICENSE.txt LICENSE_TEXT HEX)
+string(REGEX MATCHALL ".." LICENSE_TEXT "${LICENSE_TEXT}")
+string(REGEX REPLACE ";" ",\n\t0x" LICENSE_TEXT "${LICENSE_TEXT}")
+set(LICENSE_TEXT "0x${LICENSE_TEXT}")
+
configure_file("${CMAKE_SOURCE_DIR}/cmake/templates/license.h.in" "license.h")
include(EthOptions)
diff --git a/Changelog.md b/Changelog.md
index 5954865c..5315dc59 100644
--- a/Changelog.md
+++ b/Changelog.md
@@ -1,8 +1,8 @@
### 0.4.12 (unreleased)
Features:
- * Assembly: renamed ``SHA3`` to `KECCAK256``.
- * Assembly: Add ``RETURNDATASIZE`` and ``RETURNDATACOPY`` (EIP211) instructions.
+ * Assembly: renamed ``SHA3`` to ``KECCAK256``.
+ * Assembly: Add ``CREATE2`` (EIP86), ``RETURNDATASIZE`` and ``RETURNDATACOPY`` (EIP211) instructions.
* AST: export all attributes to JSON format.
* Inline Assembly: Present proper error message when not supplying enough arguments to a functional
instruction.
@@ -11,6 +11,7 @@ Features:
Bugfixes:
* Fixed crash concerning non-callable types.
* Unused variable warnings no longer issued for variables used inside inline assembly.
+ * Inline Assembly: Enforce function arguments when parsing functional instructions.
### 0.4.11 (2017-05-03)
diff --git a/cmake/templates/license.h.in b/cmake/templates/license.h.in
index 48801347..6cdbc38d 100644
--- a/cmake/templates/license.h.in
+++ b/cmake/templates/license.h.in
@@ -1,3 +1,5 @@
#pragma once
-static char const* licenseText = R"(@LICENSE_TEXT@)";
+static char const licenseText[] = {
+ @LICENSE_TEXT@, 0
+};
diff --git a/docs/abi-spec.rst b/docs/abi-spec.rst
new file mode 100644
index 00000000..e39c8861
--- /dev/null
+++ b/docs/abi-spec.rst
@@ -0,0 +1,345 @@
+.. index:: abi, application binary interface
+
+.. _ABI:
+
+******************************************
+Application Binary Interface Specification
+******************************************
+
+Basic design
+============
+
+The Application Binary Interface is the standard way to interact with contracts in the Ethereum ecosystem, both
+from outside the blockchain and for contract-to-contract interaction. Data is encoded following its type,
+according to this specification.
+
+We assume the Application Binary Interface (ABI) is strongly typed, known at compilation time and static. No introspection mechanism will be provided. We assert that all contracts will have the interface definitions of any contracts they call available at compile-time.
+
+This specification does not address contracts whose interface is dynamic or otherwise known only at run-time. Should these cases become important they can be adequately handled as facilities built within the Ethereum ecosystem.
+
+Function Selector
+=================
+
+The first four bytes of the call data for a function call specifies the function to be called. It is the
+first (left, high-order in big-endian) four bytes of the Keccak (SHA-3) hash of the signature of the function. The signature is defined as the canonical expression of the basic prototype, i.e.
+the function name with the parenthesised list of parameter types. Parameter types are split by a single comma - no spaces are used.
+
+Argument Encoding
+=================
+
+Starting from the fifth byte, the encoded arguments follow. This encoding is also used in other places, e.g. the return values and also event arguments are encoded in the same way, without the four bytes specifying the function.
+
+Types
+=====
+
+The following elementary types exist:
+
+- `uint<M>`: unsigned integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`. e.g. `uint32`, `uint8`, `uint256`.
+
+- `int<M>`: two's complement signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`.
+
+- `address`: equivalent to `uint160`, except for the assumed interpretation and language typing.
+
+- `uint`, `int`: synonyms for `uint256`, `int256` respectively (not to be used for computing the function selector).
+
+- `bool`: equivalent to `uint8` restricted to the values 0 and 1
+
+- `fixed<M>x<N>`: signed fixed-point decimal number of `M` bits, `0 < M <= 256`, `M % 8 ==0`, and `0 < N <= 80`, which denotes the value `v` as `v / (10 ** N)`.
+
+- `ufixed<M>x<N>`: unsigned variant of `fixed<M>x<N>`.
+
+- `fixed`, `ufixed`: synonyms for `fixed128x19`, `ufixed128x19` respectively (not to be used for computing the function selector).
+
+- `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`.
+
+- `function`: equivalent to `bytes24`: an address, followed by a function selector
+
+The following (fixed-size) array type exists:
+
+- `<type>[M]`: a fixed-length array of the given fixed-length type.
+
+The following non-fixed-size types exist:
+
+- `bytes`: dynamic sized byte sequence.
+
+- `string`: dynamic sized unicode string assumed to be UTF-8 encoded.
+
+- `<type>[]`: a variable-length array of the given fixed-length type.
+
+Types can be combined to anonymous structs by enclosing a finite non-negative number
+of them inside parentheses, separated by commas:
+
+- `(T1,T2,...,Tn)`: anonymous struct (ordered tuple) consisting of the types `T1`, ..., `Tn`, `n >= 0`
+
+It is possible to form structs of structs, arrays of structs and so on.
+
+
+Formal Specification of the Encoding
+====================================
+
+We will now formally specify the encoding, such that it will have the following
+properties, which are especially useful if some arguments are nested arrays:
+
+Properties:
+
+ 1. The number of reads necessary to access a value is at most the depth of the value inside the argument array structure, i.e. four reads are needed to retrieve `a_i[k][l][r]`. In a previous version of the ABI, the number of reads scaled linearly with the total number of dynamic parameters in the worst case.
+
+ 2. The data of a variable or array element is not interleaved with other data and it is relocatable, i.e. it only uses relative "addresses"
+
+We distinguish static and dynamic types. Static types are encoded in-place and dynamic types are encoded at a separately allocated location after the current block.
+
+**Definition:** The following types are called "dynamic":
+* `bytes`
+* `string`
+* `T[]` for any `T`
+* `T[k]` for any dynamic `T` and any `k > 0`
+
+All other types are called "static".
+
+**Definition:** `len(a)` is the number of bytes in a binary string `a`.
+The type of `len(a)` is assumed to be `uint256`.
+
+We define `enc`, the actual encoding, as a mapping of values of the ABI types to binary strings such
+that `len(enc(X))` depends on the value of `X` if and only if the type of `X` is dynamic.
+
+**Definition:** For any ABI value `X`, we recursively define `enc(X)`, depending
+on the type of `X` being
+
+- `(T1,...,Tk)` for `k >= 0` and any types `T1`, ..., `Tk`
+
+ `enc(X) = head(X(1)) ... head(X(k-1)) tail(X(0)) ... tail(X(k-1))`
+
+ where `X(i)` is the `ith` component of the value, and
+ `head` and `tail` are defined for `Ti` being a static type as
+
+ `head(X(i)) = enc(X(i))` and `tail(X(i)) = ""` (the empty string)
+
+ and as
+
+ `head(X(i)) = enc(len(head(X(0)) ... head(X(k-1)) tail(X(0)) ... tail(X(i-1))))`
+ `tail(X(i)) = enc(X(i))`
+
+ otherwise, i.e. if `Ti` is a dynamic type.
+
+ Note that in the dynamic case, `head(X(i))` is well-defined since the lengths of
+ the head parts only depend on the types and not the values. Its value is the offset
+ of the beginning of `tail(X(i))` relative to the start of `enc(X)`.
+
+- `T[k]` for any `T` and `k`:
+
+ `enc(X) = enc((X[0], ..., X[k-1]))`
+
+ i.e. it is encoded as if it were an anonymous struct with `k` elements
+ of the same type.
+
+- `T[]` where `X` has `k` elements (`k` is assumed to be of type `uint256`):
+
+ `enc(X) = enc(k) enc([X[1], ..., X[k]])`
+
+ i.e. it is encoded as if it were an array of static size `k`, prefixed with
+ the number of elements.
+
+- `bytes`, of length `k` (which is assumed to be of type `uint256`):
+
+ `enc(X) = enc(k) pad_right(X)`, i.e. the number of bytes is encoded as a
+ `uint256` followed by the actual value of `X` as a byte sequence, followed by
+ the minimum number of zero-bytes such that `len(enc(X))` is a multiple of 32.
+
+- `string`:
+
+ `enc(X) = enc(enc_utf8(X))`, i.e. `X` is utf-8 encoded and this value is interpreted as of `bytes` type and encoded further. Note that the length used in this subsequent encoding is the number of bytes of the utf-8 encoded string, not its number of characters.
+
+- `uint<M>`: `enc(X)` is the big-endian encoding of `X`, padded on the higher-order (left) side with zero-bytes such that the length is a multiple of 32 bytes.
+- `address`: as in the `uint160` case
+- `int<M>`: `enc(X)` is the big-endian two's complement encoding of `X`, padded on the higher-oder (left) side with `0xff` for negative `X` and with zero bytes for positive `X` such that the length is a multiple of 32 bytes.
+- `bool`: as in the `uint8` case, where `1` is used for `true` and `0` for `false`
+- `fixed<M>x<N>`: `enc(X)` is `enc(X * 10**N)` where `X * 10**N` is interpreted as a `int256`.
+- `fixed`: as in the `fixed128x19` case
+- `ufixed<M>x<N>`: `enc(X)` is `enc(X * 10**N)` where `X * 10**N` is interpreted as a `uint256`.
+- `ufixed`: as in the `ufixed128x19` case
+- `bytes<M>`: `enc(X)` is the sequence of bytes in `X` padded with zero-bytes to a length of 32.
+
+Note that for any `X`, `len(enc(X))` is a multiple of 32.
+
+Function Selector and Argument Encoding
+=======================================
+
+All in all, a call to the function `f` with parameters `a_1, ..., a_n` is encoded as
+
+ `function_selector(f) enc((a_1, ..., a_n))`
+
+and the return values `v_1, ..., v_k` of `f` are encoded as
+
+ `enc((v_1, ..., v_k))`
+
+i.e. the values are combined into an anonymous struct and encoded.
+
+Examples
+========
+
+Given the contract:
+
+::
+
+ contract Foo {
+ function bar(bytes3[2] xy) {}
+ function baz(uint32 x, bool y) returns (bool r) { r = x > 32 || y; }
+ function sam(bytes name, bool z, uint[] data) {}
+ }
+
+
+Thus for our `Foo` example if we wanted to call `baz` with the parameters `69` and `true`, we would pass 68 bytes total, which can be broken down into:
+
+- `0xcdcd77c0`: the Method ID. This is derived as the first 4 bytes of the Keccak hash of the ASCII form of the signature `baz(uint32,bool)`.
+- `0x0000000000000000000000000000000000000000000000000000000000000045`: the first parameter, a uint32 value `69` padded to 32 bytes
+- `0x0000000000000000000000000000000000000000000000000000000000000001`: the second parameter - boolean `true`, padded to 32 bytes
+
+In total::
+
+ 0xcdcd77c000000000000000000000000000000000000000000000000000000000000000450000000000000000000000000000000000000000000000000000000000000001
+
+It returns a single `bool`. If, for example, it were to return `false`, its output would be the single byte array `0x0000000000000000000000000000000000000000000000000000000000000000`, a single bool.
+
+If we wanted to call `bar` with the argument `["abc", "def"]`, we would pass 68 bytes total, broken down into:
+
+- `0xfce353f6`: the Method ID. This is derived from the signature `bar(bytes3[2])`.
+- `0x6162630000000000000000000000000000000000000000000000000000000000`: the first part of the first parameter, a `bytes3` value `"abc"` (left-aligned).
+- `0x6465660000000000000000000000000000000000000000000000000000000000`: the second part of the first parameter, a `bytes3` value `"def"` (left-aligned).
+
+In total::
+
+ 0xfce353f661626300000000000000000000000000000000000000000000000000000000006465660000000000000000000000000000000000000000000000000000000000
+
+If we wanted to call `sam` with the arguments `"dave"`, `true` and `[1,2,3]`, we would pass 292 bytes total, broken down into:
+- `0xa5643bf2`: the Method ID. This is derived from the signature `sam(bytes,bool,uint256[])`. Note that `uint` is replaced with its canonical representation `uint256`.
+- `0x0000000000000000000000000000000000000000000000000000000000000060`: the location of the data part of the first parameter (dynamic type), measured in bytes from the start of the arguments block. In this case, `0x60`.
+- `0x0000000000000000000000000000000000000000000000000000000000000001`: the second parameter: boolean true.
+- `0x00000000000000000000000000000000000000000000000000000000000000a0`: the location of the data part of the third parameter (dynamic type), measured in bytes. In this case, `0xa0`.
+- `0x0000000000000000000000000000000000000000000000000000000000000004`: the data part of the first argument, it starts with the length of the byte array in elements, in this case, 4.
+- `0x6461766500000000000000000000000000000000000000000000000000000000`: the contents of the first argument: the UTF-8 (equal to ASCII in this case) encoding of `"dave"`, padded on the right to 32 bytes.
+- `0x0000000000000000000000000000000000000000000000000000000000000003`: the data part of the third argument, it starts with the length of the array in elements, in this case, 3.
+- `0x0000000000000000000000000000000000000000000000000000000000000001`: the first entry of the third parameter.
+- `0x0000000000000000000000000000000000000000000000000000000000000002`: the second entry of the third parameter.
+- `0x0000000000000000000000000000000000000000000000000000000000000003`: the third entry of the third parameter.
+
+In total::
+
+ 0xa5643bf20000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000464617665000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003
+
+Use of Dynamic Types
+====================
+
+A call to a function with the signature `f(uint,uint32[],bytes10,bytes)` with values `(0x123, [0x456, 0x789], "1234567890", "Hello, world!")` is encoded in the following way:
+
+We take the first four bytes of `sha3("f(uint256,uint32[],bytes10,bytes)")`, i.e. `0x8be65246`.
+Then we encode the head parts of all four arguments. For the static types `uint256` and `bytes10`, these are directly the values we want to pass, whereas for the dynamic types `uint32[]` and `bytes`, we use the offset in bytes to the start of their data area, measured from the start of the value encoding (i.e. not counting the first four bytes containing the hash of the function signature). These are:
+
+ - `0x0000000000000000000000000000000000000000000000000000000000000123` (`0x123` padded to 32 bytes)
+ - `0x0000000000000000000000000000000000000000000000000000000000000080` (offset to start of data part of second parameter, 4*32 bytes, exactly the size of the head part)
+ - `0x3132333435363738393000000000000000000000000000000000000000000000` (`"1234567890"` padded to 32 bytes on the right)
+ - `0x00000000000000000000000000000000000000000000000000000000000000e0` (offset to start of data part of fourth parameter = offset to start of data part of first dynamic parameter + size of data part of first dynamic parameter = 4\*32 + 3\*32 (see below))
+
+After this, the data part of the first dynamic argument, `[0x456, 0x789]` follows:
+
+ - `0x0000000000000000000000000000000000000000000000000000000000000002` (number of elements of the array, 2)
+ - `0x0000000000000000000000000000000000000000000000000000000000000456` (first element)
+ - `0x0000000000000000000000000000000000000000000000000000000000000789` (second element)
+
+Finally, we encode the data part of the second dynamic argument, `"Hello, world!"`:
+
+ - `0x000000000000000000000000000000000000000000000000000000000000000d` (number of elements (bytes in this case): 13)
+ - `0x48656c6c6f2c20776f726c642100000000000000000000000000000000000000` (`"Hello, world!"` padded to 32 bytes on the right)
+
+All together, the encoding is (newline after function selector and each 32-bytes for clarity):
+
+::
+
+ 0x8be65246
+ 0000000000000000000000000000000000000000000000000000000000000123
+ 0000000000000000000000000000000000000000000000000000000000000080
+ 3132333435363738393000000000000000000000000000000000000000000000
+ 00000000000000000000000000000000000000000000000000000000000000e0
+ 0000000000000000000000000000000000000000000000000000000000000002
+ 0000000000000000000000000000000000000000000000000000000000000456
+ 0000000000000000000000000000000000000000000000000000000000000789
+ 000000000000000000000000000000000000000000000000000000000000000d
+ 48656c6c6f2c20776f726c642100000000000000000000000000000000000000
+
+Events
+======
+
+Events are an abstraction of the Ethereum logging/event-watching protocol. Log entries provide the contract's address, a series of up to four topics and some arbitrary length binary data. Events leverage the existing function ABI in order to interpret this (together with an interface spec) as a properly typed structure.
+
+Given an event name and series of event parameters, we split them into two sub-series: those which are indexed and those which are not. Those which are indexed, which may number up to 3, are used alongside the Keccak hash of the event signature to form the topics of the log entry. Those which as not indexed form the byte array of the event.
+
+In effect, a log entry using this ABI is described as:
+
+- `address`: the address of the contract (intrinsically provided by Ethereum);
+- `topics[0]`: `keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")")` (`canonical_type_of` is a function that simply returns the canonical type of a given argument, e.g. for `uint indexed foo`, it would return `uint256`). If the event is declared as `anonymous` the `topics[0]` is not generated;
+- `topics[n]`: `EVENT_INDEXED_ARGS[n - 1]` (`EVENT_INDEXED_ARGS` is the series of `EVENT_ARGS` that are indexed);
+- `data`: `abi_serialise(EVENT_NON_INDEXED_ARGS)` (`EVENT_NON_INDEXED_ARGS` is the series of `EVENT_ARGS` that are not indexed, `abi_serialise` is the ABI serialisation function used for returning a series of typed values from a function, as described above).
+
+JSON
+====
+
+The JSON format for a contract's interface is given by an array of function and/or event descriptions. A function description is a JSON object with the fields:
+
+- `type`: `"function"`, `"constructor"`, or `"fallback"` (the :ref:`unnamed "default" function <fallback-function>`);
+- `name`: the name of the function;
+- `inputs`: an array of objects, each of which contains:
+ * `name`: the name of the parameter;
+ * `type`: the canonical type of the parameter.
+- `outputs`: an array of objects similar to `inputs`, can be omitted if function doesn't return anything;
+- `constant`: `true` if function is :ref:`specified to not modify blockchain state <constant-functions>`);
+- `payable`: `true` if function accepts ether, defaults to `false`.
+
+`type` can be omitted, defaulting to `"function"`.
+
+Constructor and fallback function never have `name` or `outputs`. Fallback function doesn't have `inputs` either.
+
+Sending non-zero ether to non-payable function will throw. Don't do it.
+
+An event description is a JSON object with fairly similar fields:
+
+- `type`: always `"event"`
+- `name`: the name of the event;
+- `inputs`: an array of objects, each of which contains:
+ * `name`: the name of the parameter;
+ * `type`: the canonical type of the parameter.
+ * `indexed`: `true` if the field is part of the log's topics, `false` if it one of the log's data segment.
+- `anonymous`: `true` if the event was declared as `anonymous`.
+
+For example,
+
+::
+
+ contract Test {
+ function Test(){ b = 0x12345678901234567890123456789012; }
+ event Event(uint indexed a, bytes32 b)
+ event Event2(uint indexed a, bytes32 b)
+ function foo(uint a) { Event(a, b); }
+ bytes32 b;
+ }
+
+would result in the JSON:
+
+.. code:: json
+
+ [{
+ "type":"event",
+ "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}],
+ "name":"Event"
+ }, {
+ "type":"event",
+ "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}],
+ "name":"Event2"
+ }, {
+ "type":"event",
+ "inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}],
+ "name":"Event2"
+ }, {
+ "type":"function",
+ "inputs": [{"name":"a","type":"uint256"}],
+ "name":"foo",
+ "outputs": []
+ }]
diff --git a/docs/assembly.rst b/docs/assembly.rst
index cd3ff4c0..9455dfb3 100644
--- a/docs/assembly.rst
+++ b/docs/assembly.rst
@@ -318,8 +318,10 @@ would be written as follows
mstore(0x80, add(mload(0x80), 3))
-Functional style and instructional style can be mixed, but any opcode inside a
-functional style expression has to return exactly one stack slot (most of the opcodes do).
+Functional style expressions cannot use instructional style internally, i.e.
+``1 2 mstore(0x80, add)`` is not valid assembly, it has to be written as
+``mstore(0x80, add(2, 1))``. For opcodes that do not take arguments, the
+parentheses can be omitted.
Note that the order of arguments is reversed in functional-style as opposed to the instruction-style
way. If you use functional-style, the first argument will end up on the stack top.
diff --git a/docs/contracts.rst b/docs/contracts.rst
index 01913654..356fa90d 100644
--- a/docs/contracts.rst
+++ b/docs/contracts.rst
@@ -458,6 +458,8 @@ value types and strings.
}
+.. _constant-functions:
+
******************
Constant Functions
******************
diff --git a/docs/index.rst b/docs/index.rst
index 4b48b91c..3cdda62d 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -59,6 +59,9 @@ Available Solidity Integrations
* `Atom Solidity Linter <https://atom.io/packages/linter-solidity>`_
Plugin for the Atom editor that provides Solidity linting.
+* `Atom Solium Linter <https://atom.io/packages/linter-solium>`_
+ Configurable Solidty linter for Atom using Solium as a base.
+
* `Solium <https://github.com/duaraghav8/Solium/>`_
A commandline linter for Solidity which strictly follows the rules prescribed by the `Solidity Style Guide <http://solidity.readthedocs.io/en/latest/style-guide.html>`_.
@@ -142,6 +145,7 @@ Contents
solidity-in-depth.rst
security-considerations.rst
using-the-compiler.rst
+ abi-spec.rst
style-guide.rst
common-patterns.rst
bugs.rst
diff --git a/libevmasm/GasMeter.cpp b/libevmasm/GasMeter.cpp
index 31a7d13e..c2e4f01d 100644
--- a/libevmasm/GasMeter.cpp
+++ b/libevmasm/GasMeter.cpp
@@ -155,6 +155,7 @@ GasMeter::GasConsumption GasMeter::estimateMax(AssemblyItem const& _item, bool _
gas += GasCosts::callNewAccountGas; // We very rarely know whether the address exists.
break;
case Instruction::CREATE:
+ case Instruction::CREATE2:
if (_includeExternalCosts)
// We assume that we do not know the target contract and thus, the consumption is infinite.
gas = GasConsumption::infinite();
diff --git a/libevmasm/Instruction.cpp b/libevmasm/Instruction.cpp
index af7e9ff9..d58a47a0 100644
--- a/libevmasm/Instruction.cpp
+++ b/libevmasm/Instruction.cpp
@@ -161,6 +161,7 @@ const std::map<std::string, Instruction> dev::solidity::c_instructions =
{ "CALLCODE", Instruction::CALLCODE },
{ "RETURN", Instruction::RETURN },
{ "DELEGATECALL", Instruction::DELEGATECALL },
+ { "CREATE2", Instruction::CREATE2 },
{ "REVERT", Instruction::REVERT },
{ "INVALID", Instruction::INVALID },
{ "SELFDESTRUCT", Instruction::SELFDESTRUCT }
@@ -299,7 +300,8 @@ static const std::map<Instruction, InstructionInfo> c_instructionInfo =
{ Instruction::CALLCODE, { "CALLCODE", 0, 7, 1, true, Tier::Special } },
{ Instruction::RETURN, { "RETURN", 0, 2, 0, true, Tier::Zero } },
{ Instruction::DELEGATECALL, { "DELEGATECALL", 0, 6, 1, true, Tier::Special } },
- { Instruction::REVERT, { "REVERT", 0, 2, 0, true, Tier::Zero } },
+ { Instruction::CREATE2, { "CREATE2", 0, 4, 1, true, Tier::Special } },
+ { Instruction::REVERT, { "REVERT", 0, 2, 0, true, Tier::Zero } },
{ Instruction::INVALID, { "INVALID", 0, 0, 0, true, Tier::Zero } },
{ Instruction::SELFDESTRUCT, { "SELFDESTRUCT", 0, 1, 0, true, Tier::Special } }
};
diff --git a/libevmasm/Instruction.h b/libevmasm/Instruction.h
index a8c3bf4a..37cdccdb 100644
--- a/libevmasm/Instruction.h
+++ b/libevmasm/Instruction.h
@@ -187,6 +187,7 @@ enum class Instruction: uint8_t
CALLCODE, ///< message-call with another account's code only
RETURN, ///< halt execution returning output data
DELEGATECALL, ///< like CALLCODE but keeps caller's value and sender
+ CREATE2 = 0xfb, ///< create new account with associated code
REVERT = 0xfd, ///< halt execution, revert state and return output data
INVALID = 0xfe, ///< invalid instruction for expressing runtime errors (e.g., division-by-zero)
diff --git a/libevmasm/SemanticInformation.cpp b/libevmasm/SemanticInformation.cpp
index 86feb1d2..db4ee867 100644
--- a/libevmasm/SemanticInformation.cpp
+++ b/libevmasm/SemanticInformation.cpp
@@ -138,6 +138,7 @@ bool SemanticInformation::isDeterministic(AssemblyItem const& _item)
case Instruction::CALLCODE:
case Instruction::DELEGATECALL:
case Instruction::CREATE:
+ case Instruction::CREATE2:
case Instruction::GAS:
case Instruction::PC:
case Instruction::MSIZE: // depends on previous writes and reads, not only on content
@@ -178,6 +179,7 @@ bool SemanticInformation::invalidatesStorage(Instruction _instruction)
case Instruction::CALLCODE:
case Instruction::DELEGATECALL:
case Instruction::CREATE:
+ case Instruction::CREATE2:
case Instruction::SSTORE:
return true;
default:
diff --git a/libjulia/backends/evm/EVMCodeTransform.cpp b/libjulia/backends/evm/EVMCodeTransform.cpp
index cd6fd276..7c14eb8b 100644
--- a/libjulia/backends/evm/EVMCodeTransform.cpp
+++ b/libjulia/backends/evm/EVMCodeTransform.cpp
@@ -64,8 +64,7 @@ void CodeTransform::operator()(VariableDeclaration const& _varDecl)
for (auto const& variable: _varDecl.variables)
{
auto& var = boost::get<Scope::Variable>(m_scope->identifiers.at(variable.name));
- var.stackHeight = height++;
- var.active = true;
+ m_context->variableStackHeights[&var] = height++;
}
checkStackHeight(&_varDecl);
}
@@ -91,8 +90,7 @@ void CodeTransform::operator()(Label const& _label)
solAssert(m_scope, "");
solAssert(m_scope->identifiers.count(_label.name), "");
Scope::Label& label = boost::get<Scope::Label>(m_scope->identifiers.at(_label.name));
- assignLabelIdIfUnset(label.id);
- m_assembly.appendLabel(*label.id);
+ m_assembly.appendLabel(labelID(label));
checkStackHeight(&_label);
}
@@ -120,12 +118,11 @@ void CodeTransform::operator()(FunctionCall const& _call)
for (auto const& arg: _call.arguments | boost::adaptors::reversed)
visitExpression(arg);
m_assembly.setSourceLocation(_call.location);
- assignLabelIdIfUnset(function->id);
if (m_evm15)
- m_assembly.appendJumpsub(*function->id, function->arguments.size(), function->returns.size());
+ m_assembly.appendJumpsub(functionEntryID(*function), function->arguments.size(), function->returns.size());
else
{
- m_assembly.appendJumpTo(*function->id, function->returns.size() - function->arguments.size() - 1);
+ m_assembly.appendJumpTo(functionEntryID(*function), function->returns.size() - function->arguments.size() - 1);
m_assembly.appendLabel(returnLabel);
m_stackAdjustment--;
}
@@ -181,8 +178,7 @@ void CodeTransform::operator()(assembly::Identifier const& _identifier)
},
[=](Scope::Label& _label)
{
- assignLabelIdIfUnset(_label.id);
- m_assembly.appendLabelReference(*_label.id);
+ m_assembly.appendLabelReference(labelID(_label));
},
[=](Scope::Function&)
{
@@ -282,7 +278,6 @@ void CodeTransform::operator()(FunctionDefinition const& _function)
solAssert(m_scope, "");
solAssert(m_scope->identifiers.count(_function.name), "");
Scope::Function& function = boost::get<Scope::Function>(m_scope->identifiers.at(_function.name));
- assignLabelIdIfUnset(function.id);
int const localStackAdjustment = m_evm15 ? 0 : 1;
int height = localStackAdjustment;
@@ -292,8 +287,7 @@ void CodeTransform::operator()(FunctionDefinition const& _function)
for (auto const& v: _function.arguments | boost::adaptors::reversed)
{
auto& var = boost::get<Scope::Variable>(varScope->identifiers.at(v.name));
- var.stackHeight = height++;
- var.active = true;
+ m_context->variableStackHeights[&var] = height++;
}
m_assembly.setSourceLocation(_function.location);
@@ -303,25 +297,24 @@ void CodeTransform::operator()(FunctionDefinition const& _function)
if (m_evm15)
{
m_assembly.appendJumpTo(afterFunction, -stackHeightBefore);
- m_assembly.appendBeginsub(*function.id, _function.arguments.size());
+ m_assembly.appendBeginsub(functionEntryID(function), _function.arguments.size());
}
else
{
m_assembly.appendJumpTo(afterFunction, -stackHeightBefore + height);
- m_assembly.appendLabel(*function.id);
+ m_assembly.appendLabel(functionEntryID(function));
}
m_stackAdjustment += localStackAdjustment;
for (auto const& v: _function.returns)
{
auto& var = boost::get<Scope::Variable>(varScope->identifiers.at(v.name));
- var.stackHeight = height++;
- var.active = true;
+ m_context->variableStackHeights[&var] = height++;
// Preset stack slots for return variables to zero.
m_assembly.appendConstant(u256(0));
}
- CodeTransform(m_assembly, m_info, m_evm15, m_identifierAccess, localStackAdjustment)
+ CodeTransform(m_assembly, m_info, m_evm15, m_identifierAccess, localStackAdjustment, m_context)
.run(_function.body);
{
@@ -367,7 +360,7 @@ void CodeTransform::operator()(FunctionDefinition const& _function)
void CodeTransform::operator()(Block const& _block)
{
- CodeTransform(m_assembly, m_info, m_evm15, m_identifierAccess, m_stackAdjustment).run(_block);
+ CodeTransform(m_assembly, m_info, m_evm15, m_identifierAccess, m_stackAdjustment, m_context).run(_block);
}
AbstractAssembly::LabelID CodeTransform::labelFromIdentifier(Identifier const& _identifier)
@@ -377,8 +370,7 @@ AbstractAssembly::LabelID CodeTransform::labelFromIdentifier(Identifier const& _
[=](Scope::Variable&) { solAssert(false, "Expected label"); },
[&](Scope::Label& _label)
{
- assignLabelIdIfUnset(_label.id);
- label = *_label.id;
+ label = labelID(_label);
},
[=](Scope::Function&) { solAssert(false, "Expected label"); }
)))
@@ -388,6 +380,20 @@ AbstractAssembly::LabelID CodeTransform::labelFromIdentifier(Identifier const& _
return label;
}
+AbstractAssembly::LabelID CodeTransform::labelID(Scope::Label const& _label)
+{
+ if (!m_context->labelIDs.count(&_label))
+ m_context->labelIDs[&_label] = m_assembly.newLabelId();
+ return m_context->labelIDs[&_label];
+}
+
+AbstractAssembly::LabelID CodeTransform::functionEntryID(Scope::Function const& _function)
+{
+ if (!m_context->functionEntryIDs.count(&_function))
+ m_context->functionEntryIDs[&_function] = m_assembly.newLabelId();
+ return m_context->functionEntryIDs[&_function];
+}
+
void CodeTransform::visitExpression(Statement const& _expression)
{
int height = m_assembly.stackHeight();
@@ -418,7 +424,8 @@ void CodeTransform::generateAssignment(Identifier const& _variableName)
int CodeTransform::variableHeightDiff(solidity::assembly::Scope::Variable const& _var, bool _forSwap)
{
- int heightDiff = m_assembly.stackHeight() - _var.stackHeight;
+ solAssert(m_context->variableStackHeights.count(&_var), "");
+ int heightDiff = m_assembly.stackHeight() - m_context->variableStackHeights[&_var];
if (heightDiff <= (_forSwap ? 1 : 0) || heightDiff > (_forSwap ? 17 : 16))
{
solUnimplemented(
@@ -446,9 +453,3 @@ void CodeTransform::checkStackHeight(void const* _astElement)
to_string(m_assembly.stackHeight() - m_stackAdjustment)
);
}
-
-void CodeTransform::assignLabelIdIfUnset(boost::optional<AbstractAssembly::LabelID>& _labelId)
-{
- if (!_labelId)
- _labelId.reset(m_assembly.newLabelId());
-}
diff --git a/libjulia/backends/evm/EVMCodeTransform.h b/libjulia/backends/evm/EVMCodeTransform.h
index f65948dc..202f5051 100644
--- a/libjulia/backends/evm/EVMCodeTransform.h
+++ b/libjulia/backends/evm/EVMCodeTransform.h
@@ -64,7 +64,14 @@ public:
solidity::assembly::AsmAnalysisInfo& _analysisInfo,
bool _evm15 = false,
ExternalIdentifierAccess const& _identifierAccess = ExternalIdentifierAccess()
- ): CodeTransform(_assembly, _analysisInfo, _evm15, _identifierAccess, _assembly.stackHeight())
+ ): CodeTransform(
+ _assembly,
+ _analysisInfo,
+ _evm15,
+ _identifierAccess,
+ _assembly.stackHeight(),
+ std::make_shared<Context>()
+ )
{
}
@@ -72,18 +79,28 @@ public:
void run(solidity::assembly::Block const& _block);
protected:
+ struct Context
+ {
+ using Scope = solidity::assembly::Scope;
+ std::map<Scope::Label const*, AbstractAssembly::LabelID> labelIDs;
+ std::map<Scope::Function const*, AbstractAssembly::LabelID> functionEntryIDs;
+ std::map<Scope::Variable const*, int> variableStackHeights;
+ };
+
CodeTransform(
julia::AbstractAssembly& _assembly,
solidity::assembly::AsmAnalysisInfo& _analysisInfo,
bool _evm15,
ExternalIdentifierAccess const& _identifierAccess,
- int _stackAdjustment
+ int _stackAdjustment,
+ std::shared_ptr<Context> _context
):
m_assembly(_assembly),
m_info(_analysisInfo),
m_evm15(_evm15),
m_identifierAccess(_identifierAccess),
- m_stackAdjustment(_stackAdjustment)
+ m_stackAdjustment(_stackAdjustment),
+ m_context(_context)
{}
public:
@@ -102,6 +119,10 @@ public:
private:
AbstractAssembly::LabelID labelFromIdentifier(solidity::assembly::Identifier const& _identifier);
+ /// @returns the label ID corresponding to the given label, allocating a new one if
+ /// necessary.
+ AbstractAssembly::LabelID labelID(solidity::assembly::Scope::Label const& _label);
+ AbstractAssembly::LabelID functionEntryID(solidity::assembly::Scope::Function const& _function);
/// Generates code for an expression that is supposed to return a single value.
void visitExpression(solidity::assembly::Statement const& _expression);
@@ -116,9 +137,6 @@ private:
void checkStackHeight(void const* _astElement);
- /// Assigns the label's or function's id to a value taken from eth::Assembly if it has not yet been set.
- void assignLabelIdIfUnset(boost::optional<AbstractAssembly::LabelID>& _labelId);
-
julia::AbstractAssembly& m_assembly;
solidity::assembly::AsmAnalysisInfo& m_info;
solidity::assembly::Scope* m_scope = nullptr;
@@ -129,6 +147,7 @@ private:
/// for inline assembly and different stack heights depending on the EVM backend used
/// (EVM 1.0 or 1.5).
int m_stackAdjustment = 0;
+ std::shared_ptr<Context> m_context;
};
}
diff --git a/liblll/CompilerState.cpp b/liblll/CompilerState.cpp
index 006929e4..c22242a3 100644
--- a/liblll/CompilerState.cpp
+++ b/liblll/CompilerState.cpp
@@ -56,10 +56,10 @@ void CompilerState::populateStandard()
"(def 'msg (to data) { [0]:data (msg allgas to 0 0 32) })"
"(def 'create (value code) { [0]:(msize) (create value @0 (lll code @0)) })"
"(def 'create (code) { [0]:(msize) (create 0 @0 (lll code @0)) })"
+ "(def 'sha3 (loc len) (keccak256 loc len))"
"(def 'sha3 (val) { [0]:val (sha3 0 32) })"
"(def 'sha3pair (a b) { [0]:a [32]:b (sha3 0 64) })"
"(def 'sha3trip (a b c) { [0]:a [32]:b [64]:c (sha3 0 96) })"
- "(def 'keccak256 (loc len) (sha3 loc len))"
"(def 'return (val) { [0]:val (return 0 32) })"
"(def 'returnlll (code) (return 0 (lll code 0)) )"
"(def 'makeperm (name pos) { (def name (sload pos)) (def name (v) (sstore pos v)) } )"
@@ -74,6 +74,9 @@ void CompilerState::populateStandard()
"(def 'szabo 1000000000000)"
"(def 'finney 1000000000000000)"
"(def 'ether 1000000000000000000)"
+ // these could be replaced by native instructions once supported by EVM
+ "(def 'shl (val shift) (mul val (exp 2 shift)))"
+ "(def 'shr (val shift) (div val (exp 2 shift)))"
"}";
CodeFragment::compile(s, *this);
}
diff --git a/libsolidity/ast/ASTJsonConverter.cpp b/libsolidity/ast/ASTJsonConverter.cpp
index 1de2e801..4ad1f962 100644
--- a/libsolidity/ast/ASTJsonConverter.cpp
+++ b/libsolidity/ast/ASTJsonConverter.cpp
@@ -252,6 +252,7 @@ bool ASTJsonConverter::visit(ContractDefinition const& _node)
{
setJsonNode(_node, "ContractDefinition", {
make_pair("name", _node.name()),
+ make_pair("documentation", _node.documentation() ? Json::Value(*_node.documentation()) : Json::nullValue),
make_pair("contractKind", contractKind(_node.contractKind())),
make_pair("fullyImplemented", _node.annotation().isFullyImplemented),
make_pair("linearizedBaseContracts", getContainerIds(_node.annotation().linearizedBaseContracts)),
diff --git a/libsolidity/inlineasm/AsmAnalysis.cpp b/libsolidity/inlineasm/AsmAnalysis.cpp
index 36ac0e75..630e0abf 100644
--- a/libsolidity/inlineasm/AsmAnalysis.cpp
+++ b/libsolidity/inlineasm/AsmAnalysis.cpp
@@ -92,7 +92,7 @@ bool AsmAnalyzer::operator()(assembly::Identifier const& _identifier)
if (m_currentScope->lookup(_identifier.name, Scope::Visitor(
[&](Scope::Variable const& _var)
{
- if (!_var.active)
+ if (!m_activeVariables.count(&_var))
{
m_errorReporter.declarationError(
_identifier.location,
@@ -187,7 +187,7 @@ bool AsmAnalyzer::operator()(assembly::VariableDeclaration const& _varDecl)
for (auto const& variable: _varDecl.variables)
{
expectValidType(variable.type, variable.location);
- boost::get<Scope::Variable>(m_currentScope->identifiers.at(variable.name)).active = true;
+ m_activeVariables.insert(&boost::get<Scope::Variable>(m_currentScope->identifiers.at(variable.name)));
}
m_info.stackHeightInfo[&_varDecl] = m_stackHeight;
return success;
@@ -201,7 +201,7 @@ bool AsmAnalyzer::operator()(assembly::FunctionDefinition const& _funDef)
for (auto const& var: _funDef.arguments + _funDef.returns)
{
expectValidType(var.type, var.location);
- boost::get<Scope::Variable>(varScope.identifiers.at(var.name)).active = true;
+ m_activeVariables.insert(&boost::get<Scope::Variable>(varScope.identifiers.at(var.name)));
}
int const stackHeight = m_stackHeight;
@@ -384,7 +384,7 @@ bool AsmAnalyzer::checkAssignment(assembly::Identifier const& _variable, size_t
m_errorReporter.typeError(_variable.location, "Assignment requires variable.");
success = false;
}
- else if (!boost::get<Scope::Variable>(*var).active)
+ else if (!m_activeVariables.count(&boost::get<Scope::Variable>(*var)))
{
m_errorReporter.declarationError(
_variable.location,
@@ -447,17 +447,25 @@ void AsmAnalyzer::expectValidType(string const& type, SourceLocation const& _loc
void AsmAnalyzer::warnOnFutureInstruction(solidity::Instruction _instr, SourceLocation const& _location)
{
+ string instr;
switch (_instr)
{
+ case solidity::Instruction::CREATE2:
+ instr = "create2";
+ break;
case solidity::Instruction::RETURNDATASIZE:
+ instr = "returndatasize";
+ break;
case solidity::Instruction::RETURNDATACOPY:
- m_errorReporter.warning(
- _location,
- "The RETURNDATASIZE/RETURNDATACOPY instructions are only available after "
- "the Metropolis hard fork. Before that they act as an invalid instruction."
- );
+ instr = "returndatacopy";
break;
default:
break;
}
+ if (!instr.empty())
+ m_errorReporter.warning(
+ _location,
+ "The \"" + instr + "\" instruction is only available after " +
+ "the Metropolis hard fork. Before that it acts as an invalid instruction."
+ );
}
diff --git a/libsolidity/inlineasm/AsmAnalysis.h b/libsolidity/inlineasm/AsmAnalysis.h
index 55b409ba..2516722a 100644
--- a/libsolidity/inlineasm/AsmAnalysis.h
+++ b/libsolidity/inlineasm/AsmAnalysis.h
@@ -22,6 +22,8 @@
#include <libsolidity/interface/Exceptions.h>
+#include <libsolidity/inlineasm/AsmScope.h>
+
#include <libjulia/backends/evm/AbstractAssembly.h>
#include <boost/variant.hpp>
@@ -51,9 +53,6 @@ struct FunctionCall;
struct Switch;
using Statement = boost::variant<Instruction, Literal, Label, StackAssignment, Identifier, Assignment, FunctionCall, FunctionalInstruction, VariableDeclaration, FunctionDefinition, Switch, Block>;
-
-struct Scope;
-
struct AsmAnalysisInfo;
/**
@@ -102,6 +101,9 @@ private:
int m_stackHeight = 0;
julia::ExternalIdentifierAccess::Resolver m_resolver;
Scope* m_currentScope = nullptr;
+ /// Variables that are active at the current point in assembly (as opposed to
+ /// "part of the scope but not yet declared")
+ std::set<Scope::Variable const*> m_activeVariables;
AsmAnalysisInfo& m_info;
ErrorReporter& m_errorReporter;
bool m_julia = false;
diff --git a/libsolidity/inlineasm/AsmParser.cpp b/libsolidity/inlineasm/AsmParser.cpp
index 68a9cb03..f9b073ba 100644
--- a/libsolidity/inlineasm/AsmParser.cpp
+++ b/libsolidity/inlineasm/AsmParser.cpp
@@ -174,6 +174,19 @@ assembly::Case Parser::parseCase()
assembly::Statement Parser::parseExpression()
{
Statement operation = parseElementaryOperation(true);
+ if (operation.type() == typeid(Instruction))
+ {
+ Instruction const& instr = boost::get<Instruction>(operation);
+ int args = instructionInfo(instr.instruction).args;
+ if (args > 0 && currentToken() != Token::LParen)
+ fatalParserError(string(
+ "Expected token \"(\" (\"" +
+ instructionNames().at(instr.instruction) +
+ "\" expects " +
+ boost::lexical_cast<string>(args) +
+ " arguments)"
+ ));
+ }
if (currentToken() == Token::LParen)
return parseCall(std::move(operation));
else
diff --git a/libsolidity/inlineasm/AsmScope.cpp b/libsolidity/inlineasm/AsmScope.cpp
index 7a086846..1db5ca41 100644
--- a/libsolidity/inlineasm/AsmScope.cpp
+++ b/libsolidity/inlineasm/AsmScope.cpp
@@ -46,7 +46,7 @@ bool Scope::registerFunction(string const& _name, std::vector<JuliaType> const&
{
if (exists(_name))
return false;
- identifiers[_name] = Function(_arguments, _returns);
+ identifiers[_name] = Function{_arguments, _returns};
return true;
}
diff --git a/libsolidity/inlineasm/AsmScope.h b/libsolidity/inlineasm/AsmScope.h
index ad321f77..de9119e0 100644
--- a/libsolidity/inlineasm/AsmScope.h
+++ b/libsolidity/inlineasm/AsmScope.h
@@ -65,27 +65,12 @@ struct Scope
using JuliaType = std::string;
using LabelID = size_t;
- struct Variable
- {
- /// Used during code generation to store the stack height. @todo move there.
- int stackHeight = 0;
- /// Used during analysis to check whether we already passed the declaration inside the block.
- /// @todo move there.
- bool active = false;
- JuliaType type;
- };
-
- struct Label
- {
- boost::optional<LabelID> id;
- };
-
+ struct Variable { JuliaType type; };
+ struct Label { };
struct Function
{
- Function(std::vector<JuliaType> const& _arguments, std::vector<JuliaType> const& _returns): arguments(_arguments), returns(_returns) {}
std::vector<JuliaType> arguments;
std::vector<JuliaType> returns;
- boost::optional<LabelID> id;
};
using Identifier = boost::variant<Variable, Label, Function>;
diff --git a/libsolidity/interface/AssemblyStack.cpp b/libsolidity/interface/AssemblyStack.cpp
index 75877881..7dc1edc7 100644
--- a/libsolidity/interface/AssemblyStack.cpp
+++ b/libsolidity/interface/AssemblyStack.cpp
@@ -77,7 +77,7 @@ bool AssemblyStack::analyzeParsed()
return m_analysisSuccessful;
}
-eth::LinkerObject AssemblyStack::assemble(Machine _machine) const
+MachineAssemblyObject AssemblyStack::assemble(Machine _machine) const
{
solAssert(m_analysisSuccessful, "");
solAssert(m_parserResult, "");
@@ -87,21 +87,29 @@ eth::LinkerObject AssemblyStack::assemble(Machine _machine) const
{
case Machine::EVM:
{
+ MachineAssemblyObject object;
eth::Assembly assembly;
assembly::CodeGenerator::assemble(*m_parserResult, *m_analysisInfo, assembly);
- return assembly.assemble();
+ object.bytecode = make_shared<eth::LinkerObject>(assembly.assemble());
+ ostringstream tmp;
+ assembly.stream(tmp);
+ object.assembly = tmp.str();
+ return object;
}
case Machine::EVM15:
{
+ MachineAssemblyObject object;
julia::EVMAssembly assembly(true);
julia::CodeTransform(assembly, *m_analysisInfo, true).run(*m_parserResult);
- return assembly.finalize();
+ object.bytecode = make_shared<eth::LinkerObject>(assembly.finalize());
+ /// TOOD: fill out text representation
+ return object;
}
case Machine::eWasm:
solUnimplemented("eWasm backend is not yet implemented.");
}
// unreachable
- return eth::LinkerObject();
+ return MachineAssemblyObject();
}
string AssemblyStack::print() const
diff --git a/libsolidity/interface/AssemblyStack.h b/libsolidity/interface/AssemblyStack.h
index ee2a334c..2ae596ed 100644
--- a/libsolidity/interface/AssemblyStack.h
+++ b/libsolidity/interface/AssemblyStack.h
@@ -38,6 +38,12 @@ struct AsmAnalysisInfo;
struct Block;
}
+struct MachineAssemblyObject
+{
+ std::shared_ptr<eth::LinkerObject> bytecode;
+ std::string assembly;
+};
+
/*
* Full assembly stack that can support EVM-assembly and JULIA as input and EVM, EVM1.5 and
* eWasm as output.
@@ -64,7 +70,7 @@ public:
bool analyze(assembly::Block const& _block, Scanner const* _scanner = nullptr);
/// Run the assembly step (should only be called after parseAndAnalyze).
- eth::LinkerObject assemble(Machine _machine) const;
+ MachineAssemblyObject assemble(Machine _machine) const;
/// @returns the errors generated during parsing, analysis (and potentially assembly).
ErrorList const& errors() const { return m_errors; }
diff --git a/libsolidity/parsing/Parser.cpp b/libsolidity/parsing/Parser.cpp
index ec27f89b..7c439211 100644
--- a/libsolidity/parsing/Parser.cpp
+++ b/libsolidity/parsing/Parser.cpp
@@ -1328,16 +1328,21 @@ pair<vector<ASTPointer<Expression>>, vector<ASTPointer<ASTString>>> Parser::pars
{
// call({arg1 : 1, arg2 : 2 })
expectToken(Token::LBrace);
+
+ bool first = true;
while (m_scanner->currentToken() != Token::RBrace)
{
+ if (!first)
+ expectToken(Token::Comma);
+
+ if (m_scanner->currentToken() == Token::RBrace)
+ fatalParserError("Unexpected trailing comma.");
+
ret.second.push_back(expectIdentifierToken());
expectToken(Token::Colon);
ret.first.push_back(parseExpression());
- if (m_scanner->currentToken() == Token::Comma)
- expectToken(Token::Comma);
- else
- break;
+ first = false;
}
expectToken(Token::RBrace);
}
diff --git a/solc/CommandLineInterface.cpp b/solc/CommandLineInterface.cpp
index cae05b18..58c8bf73 100644
--- a/solc/CommandLineInterface.cpp
+++ b/solc/CommandLineInterface.cpp
@@ -1103,9 +1103,14 @@ bool CommandLineInterface::assemble(
"eWasm";
cout << endl << "======= " << src.first << " (" << machine << ") =======" << endl;
AssemblyStack& stack = assemblyStacks[src.first];
+
+ cout << endl << "Pretty printed source:" << endl;
+ cout << stack.print() << endl;
+
+ MachineAssemblyObject object;
try
{
- cout << stack.assemble(_targetMachine).toHex() << endl;
+ object = stack.assemble(_targetMachine);
}
catch (Exception const& _exception)
{
@@ -1117,7 +1122,18 @@ bool CommandLineInterface::assemble(
cerr << "Unknown exception while assembling." << endl;
return false;
}
- cout << stack.print() << endl;
+
+ cout << endl << "Binary representation:" << endl;
+ if (object.bytecode)
+ cout << object.bytecode->toHex() << endl;
+ else
+ cerr << "No binary representation found." << endl;
+
+ cout << endl << "Text representation:" << endl;
+ if (!object.assembly.empty())
+ cout << object.assembly << endl;
+ else
+ cerr << "No text representation found." << endl;
}
return true;
diff --git a/solc/jsonCompiler.cpp b/solc/jsonCompiler.cpp
index 1505a43d..353258a6 100644
--- a/solc/jsonCompiler.cpp
+++ b/solc/jsonCompiler.cpp
@@ -41,6 +41,8 @@
#include <libsolidity/ast/ASTJsonConverter.h>
#include <libsolidity/interface/Version.h>
+#include "license.h"
+
using namespace std;
using namespace dev;
using namespace solidity;
@@ -305,6 +307,11 @@ static string s_outputBuffer;
extern "C"
{
+extern char const* license()
+{
+ /// TOOD: include the copyright information on the top.
+ return licenseText;
+}
extern char const* version()
{
return VersionString.c_str();
diff --git a/test/liblll/EndToEndTest.cpp b/test/liblll/EndToEndTest.cpp
index c8e7adf1..9021fa43 100644
--- a/test/liblll/EndToEndTest.cpp
+++ b/test/liblll/EndToEndTest.cpp
@@ -291,6 +291,63 @@ BOOST_AUTO_TEST_CASE(zeroarg_macro)
BOOST_CHECK(callFallback() == encodeArgs(u256(0x1234)));
}
+BOOST_AUTO_TEST_CASE(keccak256_32bytes)
+{
+ char const* sourceCode = R"(
+ (returnlll
+ (seq
+ (mstore 0x00 0x01)
+ (return (keccak256 0x00 0x20))))
+ )";
+ compileAndRun(sourceCode);
+ BOOST_CHECK(callFallback() == encodeArgs(
+ fromHex("b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6")));
+}
+
+BOOST_AUTO_TEST_CASE(sha3_two_args)
+{
+ char const* sourceCode = R"(
+ (returnlll
+ (seq
+ (mstore 0x00 0x01)
+ (return (sha3 0x00 0x20))))
+ )";
+ compileAndRun(sourceCode);
+ BOOST_CHECK(callFallback() == encodeArgs(
+ fromHex("b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6")));
+}
+
+BOOST_AUTO_TEST_CASE(sha3_one_arg)
+{
+ char const* sourceCode = R"(
+ (returnlll
+ (return (sha3 0x01)))
+ )";
+ compileAndRun(sourceCode);
+ BOOST_CHECK(callFallback() == encodeArgs(
+ fromHex("b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6")));
+}
+
+BOOST_AUTO_TEST_CASE(shift_left)
+{
+ char const* sourceCode = R"(
+ (returnlll
+ (return (shl 1 8)))
+ )";
+ compileAndRun(sourceCode);
+ BOOST_CHECK(callFallback() == encodeArgs(u256(256)));
+}
+
+BOOST_AUTO_TEST_CASE(shift_right)
+{
+ char const* sourceCode = R"(
+ (returnlll
+ (return (shr 65536 8)))
+ )";
+ compileAndRun(sourceCode);
+ BOOST_CHECK(callFallback() == encodeArgs(u256(256)));
+}
+
BOOST_AUTO_TEST_SUITE_END()
}
diff --git a/test/libsolidity/ASTJSON.cpp b/test/libsolidity/ASTJSON.cpp
index df7fac51..4fb4f20c 100644
--- a/test/libsolidity/ASTJSON.cpp
+++ b/test/libsolidity/ASTJSON.cpp
@@ -228,6 +228,36 @@ BOOST_AUTO_TEST_CASE(function_type)
BOOST_CHECK_EQUAL(funType["attributes"]["visibility"], "external");
}
+BOOST_AUTO_TEST_CASE(documentation)
+{
+ CompilerStack c;
+ c.addSource("a", "/**This contract is empty*/ contract C {}");
+ c.addSource("b",
+ "/**This contract is empty"
+ " and has a line-breaking comment.*/"
+ "contract C {}"
+ );
+ c.parseAndAnalyze();
+ map<string, unsigned> sourceIndices;
+ sourceIndices["a"] = 0;
+ sourceIndices["b"] = 1;
+ Json::Value astJsonA = ASTJsonConverter(true, sourceIndices).toJson(c.ast("a"));
+ Json::Value documentationA = astJsonA["children"][0]["attributes"]["documentation"];
+ BOOST_CHECK_EQUAL(documentationA, "This contract is empty");
+ Json::Value astJsonB = ASTJsonConverter(true, sourceIndices).toJson(c.ast("b"));
+ Json::Value documentationB = astJsonB["children"][0]["attributes"]["documentation"];
+ BOOST_CHECK_EQUAL(documentationB, "This contract is empty and has a line-breaking comment.");
+ //same tests for non-legacy mode
+ astJsonA = ASTJsonConverter(false, sourceIndices).toJson(c.ast("a"));
+ documentationA = astJsonA["nodes"][0]["documentation"];
+ BOOST_CHECK_EQUAL(documentationA, "This contract is empty");
+ astJsonB = ASTJsonConverter(false, sourceIndices).toJson(c.ast("b"));
+ documentationB = astJsonB["nodes"][0]["documentation"];
+ BOOST_CHECK_EQUAL(documentationB, "This contract is empty and has a line-breaking comment.");
+
+}
+
+
BOOST_AUTO_TEST_SUITE_END()
}
diff --git a/test/libsolidity/InlineAssembly.cpp b/test/libsolidity/InlineAssembly.cpp
index 435c3dad..7876b7ee 100644
--- a/test/libsolidity/InlineAssembly.cpp
+++ b/test/libsolidity/InlineAssembly.cpp
@@ -213,6 +213,16 @@ BOOST_AUTO_TEST_CASE(functional)
BOOST_CHECK(successParse("{ let x := 2 add(7, mul(6, x)) mul(7, 8) add =: x }"));
}
+BOOST_AUTO_TEST_CASE(functional_partial)
+{
+ CHECK_PARSE_ERROR("{ let x := byte }", ParserError, "Expected token \"(\"");
+}
+
+BOOST_AUTO_TEST_CASE(functional_partial_success)
+{
+ BOOST_CHECK(successParse("{ let x := byte(1, 2) }"));
+}
+
BOOST_AUTO_TEST_CASE(functional_assignment)
{
BOOST_CHECK(successParse("{ let x := 2 x := 7 }"));
@@ -258,7 +268,7 @@ BOOST_AUTO_TEST_CASE(switch_duplicate_case)
BOOST_AUTO_TEST_CASE(switch_invalid_expression)
{
CHECK_PARSE_ERROR("{ switch {} default {} }", ParserError, "Literal, identifier or instruction expected.");
- CHECK_PARSE_ERROR("{ 1 2 switch mul default {} }", ParserError, "Instructions are not supported as expressions for switch.");
+ CHECK_PARSE_ERROR("{ switch calldatasize default {} }", ParserError, "Instructions are not supported as expressions for switch.");
}
BOOST_AUTO_TEST_CASE(switch_default_before_case)
diff --git a/test/libsolidity/JSONCompiler.cpp b/test/libsolidity/JSONCompiler.cpp
index 6aec59ab..f5154395 100644
--- a/test/libsolidity/JSONCompiler.cpp
+++ b/test/libsolidity/JSONCompiler.cpp
@@ -90,11 +90,11 @@ BOOST_AUTO_TEST_CASE(basic_compilation)
BOOST_CHECK(result["sources"]["fileA"].isObject());
BOOST_CHECK(result["sources"]["fileA"]["AST"].isObject());
BOOST_CHECK(dev::jsonCompactPrint(result["sources"]["fileA"]["AST"]) ==
- "{\"attributes\":{\"absolutePath\":\"fileA\",\"exportedSymbols\":{\"A\":[1]}},"
- "\"children\":[{\"attributes\":{\"baseContracts\":[null],\"contractDependencies\":[null],"
- "\"contractKind\":\"contract\",\"fullyImplemented\":true,\"linearizedBaseContracts\":[1],"
- "\"name\":\"A\",\"nodes\":[null],\"scope\":2},\"id\":1,\"name\":\"ContractDefinition\","
- "\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}");
+ "{\"attributes\":{\"absolutePath\":\"fileA\",\"exportedSymbols\":{\"A\":[1]}},"
+ "\"children\":[{\"attributes\":{\"baseContracts\":[null],\"contractDependencies\":[null],"
+ "\"contractKind\":\"contract\",\"documentation\":null,\"fullyImplemented\":true,\"linearizedBaseContracts\":[1],"
+ "\"name\":\"A\",\"nodes\":[null],\"scope\":2},\"id\":1,\"name\":\"ContractDefinition\","
+ "\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}");
}
BOOST_AUTO_TEST_SUITE_END()
diff --git a/test/libsolidity/SolidityNameAndTypeResolution.cpp b/test/libsolidity/SolidityNameAndTypeResolution.cpp
index dddb5dde..70934543 100644
--- a/test/libsolidity/SolidityNameAndTypeResolution.cpp
+++ b/test/libsolidity/SolidityNameAndTypeResolution.cpp
@@ -5807,6 +5807,14 @@ BOOST_AUTO_TEST_CASE(returndatacopy_as_variable)
CHECK_WARNING_ALLOW_MULTI(text, "Variable is shadowed in inline assembly by an instruction of the same name");
}
+BOOST_AUTO_TEST_CASE(create2_as_variable)
+{
+ char const* text = R"(
+ contract c { function f() { uint create2; assembly { create2(0, 0, 0, 0) }}}
+ )";
+ CHECK_WARNING_ALLOW_MULTI(text, "Variable is shadowed in inline assembly by an instruction of the same name");
+}
+
BOOST_AUTO_TEST_CASE(shadowing_warning_can_be_removed)
{
char const* text = R"(
diff --git a/test/libsolidity/SolidityParser.cpp b/test/libsolidity/SolidityParser.cpp
index 31dfada9..27231b9b 100644
--- a/test/libsolidity/SolidityParser.cpp
+++ b/test/libsolidity/SolidityParser.cpp
@@ -199,6 +199,17 @@ BOOST_AUTO_TEST_CASE(missing_argument_in_named_args)
CHECK_PARSE_ERROR(text, "Expected primary expression");
}
+BOOST_AUTO_TEST_CASE(trailing_comma_in_named_args)
+{
+ char const* text = R"(
+ contract test {
+ function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; }
+ function b() returns (uint r) { r = a({a: 1, b: 2, c: 3, }); }
+ }
+ )";
+ CHECK_PARSE_ERROR(text, "Unexpected trailing comma");
+}
+
BOOST_AUTO_TEST_CASE(two_exact_functions)
{
char const* text = R"(
diff --git a/test/libsolidity/StandardCompiler.cpp b/test/libsolidity/StandardCompiler.cpp
index 050ca500..92bb471b 100644
--- a/test/libsolidity/StandardCompiler.cpp
+++ b/test/libsolidity/StandardCompiler.cpp
@@ -217,7 +217,7 @@ BOOST_AUTO_TEST_CASE(basic_compilation)
BOOST_CHECK(dev::jsonCompactPrint(result["sources"]["fileA"]["legacyAST"]) ==
"{\"attributes\":{\"absolutePath\":\"fileA\",\"exportedSymbols\":{\"A\":[1]}},\"children\":"
"[{\"attributes\":{\"baseContracts\":[null],\"contractDependencies\":[null],\"contractKind\":\"contract\","
- "\"fullyImplemented\":true,\"linearizedBaseContracts\":[1],\"name\":\"A\",\"nodes\":[null],\"scope\":2},"
+ "\"documentation\":null,\"fullyImplemented\":true,\"linearizedBaseContracts\":[1],\"name\":\"A\",\"nodes\":[null],\"scope\":2},"
"\"id\":1,\"name\":\"ContractDefinition\",\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}");
}