Merge pull request #3099 from ethereum/develop

Merge develop into release for 0.4.18.
This commit is contained in:
chriseth 2017-10-18 14:53:45 +02:00 committed by GitHub
commit 9cf6e910bd
99 changed files with 3267 additions and 1441 deletions

View File

@ -49,13 +49,6 @@ env:
matrix:
include:
# Ubuntu 14.04 LTS "Trusty Tahr"
# https://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_14.04_LTS_.28Trusty_Tahr.29
#
# TravisCI doesn't directly support any new Ubuntu releases. These is
# some Docker support, which we should probably investigate, at least for
# Ubuntu 16.04 LTS "Xenial Xerus"
# See https://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_16.04_LTS_.28Xenial_Xerus.29.
- os: linux
dist: trusty
sudo: required

View File

@ -8,7 +8,7 @@ include(EthPolicy)
eth_policy()
# project name and version should be set after cmake_policy CMP0048
set(PROJECT_VERSION "0.4.17")
set(PROJECT_VERSION "0.4.18")
project(solidity VERSION ${PROJECT_VERSION})
option(SOLC_LINK_STATIC "Link solc executable statically on supported platforms" OFF)
@ -35,7 +35,7 @@ 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")
configure_file("${CMAKE_SOURCE_DIR}/cmake/templates/license.h.in" include/license.h)
include(EthOptions)
configure_project(TESTS)

View File

@ -1,3 +1,31 @@
### 0.4.18 (2017-10-18)
Features:
* Code Generator: Always use all available gas for calls as experimental 0.5.0 feature
(previously, some amount was retained in order to work in pre-Tangerine-Whistle
EVM versions)
* Parser: Better error message for unexpected trailing comma in parameter lists.
* Standard JSON: Support the ``outputSelection`` field for selective compilation of supplied sources.
* Syntax Checker: Unary ``+`` is now a syntax error as experimental 0.5.0 feature.
* Type Checker: Disallow non-pure constant state variables as experimental 0.5.0 feature.
* Type Checker: Do not add members of ``address`` to contracts as experimental 0.5.0 feature.
* Type Checker: Force interface functions to be external as experimental 0.5.0 feature.
* Type Checker: Require ``storage`` or ``memory`` keyword for local variables as experimental 0.5.0 feature.
Bugfixes:
* Code Generator: Allocate one byte per memory byte array element instead of 32.
* Code Generator: Do not accept data with less than four bytes (truncated function
signature) for regular function calls - fallback function is invoked instead.
* Optimizer: Remove unused stack computation results.
* Parser: Fix source location of VariableDeclarationStatement.
* Type Checker: Allow ``gas`` in view functions.
* Type Checker: Do not mark event parameters as shadowing state variables.
* Type Checker: Prevent duplicate event declarations.
* Type Checker: Properly check array length and don't rely on an assertion in code generation.
* Type Checker: Properly support overwriting members inherited from ``address`` in a contract
(such as ``balance``, ``transfer``, etc.)
* Type Checker: Validate each number literal in tuple expressions even if they are not assigned from.
### 0.4.17 (2017-09-21)
Features:

View File

@ -47,10 +47,12 @@ environment:
#init:
# - ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
install:
- ps: $fileContent = "-----BEGIN RSA PRIVATE KEY-----`n"
- ps: $fileContent += $env:priv_key.Replace(' ', "`n")
- ps: $fileContent += "`n-----END RSA PRIVATE KEY-----`n"
- ps: Set-Content c:\users\appveyor\.ssh\id_rsa $fileContent
- ps: if ($env:priv_key) {
$fileContent = "-----BEGIN RSA PRIVATE KEY-----`n";
$fileContent += $env:priv_key.Replace(' ', "`n");
$fileContent += "`n-----END RSA PRIVATE KEY-----`n";
Set-Content c:\users\appveyor\.ssh\id_rsa $fileContent
}
- git submodule update --init --recursive
- ps: $prerelease = "nightly."
- ps: $prerelease += Get-Date -format "yyyy.M.d"
@ -66,12 +68,15 @@ build_script:
- cd %APPVEYOR_BUILD_FOLDER%
- scripts\release.bat %CONFIGURATION%
- ps: $bytecodedir = git show -s --format="%cd-%H" --date=short
- ps: scripts\bytecodecompare\storebytecode.bat $Env:CONFIGURATION $bytecodedir
# Skip bytecode compare if private key is not available
- ps: if ($env:priv_key) {
scripts\bytecodecompare\storebytecode.bat $Env:CONFIGURATION $bytecodedir
}
test_script:
- cd %APPVEYOR_BUILD_FOLDER%
- cd %APPVEYOR_BUILD_FOLDER%\build\test\%CONFIGURATION%
- soltest.exe --show-progress -- --no-ipc
- soltest.exe --show-progress -- --no-ipc --no-smt
artifacts:
- path: solidity-windows.zip

View File

@ -39,5 +39,5 @@ function(create_build_info NAME)
-DPROJECT_VERSION="${PROJECT_VERSION}"
-P "${ETH_SCRIPTS_DIR}/buildinfo.cmake"
)
include_directories(BEFORE ${PROJECT_BINARY_DIR})
include_directories("${PROJECT_BINARY_DIR}/include")
endfunction()

View File

@ -0,0 +1,23 @@
include(CheckCXXCompilerFlag)
# Adds CXX compiler flag if the flag is supported by the compiler.
#
# This is effectively a combination of CMake's check_cxx_compiler_flag()
# and add_compile_options():
#
# if(check_cxx_compiler_flag(flag))
# add_compile_options(flag)
#
function(eth_add_cxx_compiler_flag_if_supported FLAG)
# Remove leading - or / from the flag name.
string(REGEX REPLACE "^-|/" "" name ${FLAG})
check_cxx_compiler_flag(${FLAG} ${name})
if(${name})
add_compile_options(${FLAG})
endif()
# If the optional argument passed, store the result there.
if(ARGV1)
set(${ARGV1} ${name} PARENT_SCOPE)
endif()
endfunction()

View File

@ -4,7 +4,7 @@
# CMake file for cpp-ethereum project which specifies our compiler settings
# for each supported platform and build configuration.
#
# See http://www.ethdocs.org/en/latest/ethereum-clients/cpp-ethereum/.
# The documentation for cpp-ethereum is hosted at http://cpp-ethereum.org
#
# Copyright (c) 2014-2016 cpp-ethereum contributors.
#------------------------------------------------------------------------------
@ -14,18 +14,15 @@
#
# These settings then end up spanning all POSIX platforms (Linux, OS X, BSD, etc)
include(CheckCXXCompilerFlag)
include(EthCheckCXXCompilerFlag)
check_cxx_compiler_flag(-fstack-protector-strong have_stack_protector_strong)
if (have_stack_protector_strong)
add_compile_options(-fstack-protector-strong)
else()
check_cxx_compiler_flag(-fstack-protector have_stack_protector)
if(have_stack_protector)
add_compile_options(-fstack-protector)
endif()
eth_add_cxx_compiler_flag_if_supported(-fstack-protector-strong have_stack_protector_strong_support)
if(NOT have_stack_protector_strong_support)
eth_add_cxx_compiler_flag_if_supported(-fstack-protector)
endif()
eth_add_cxx_compiler_flag_if_supported(-Wimplicit-fallthrough)
if (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang"))
# Use ISO C++11 standard language.
@ -83,12 +80,6 @@ if (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MA
message(FATAL_ERROR "${PROJECT_NAME} requires g++ 4.7 or greater.")
endif ()
# Until https://github.com/ethereum/solidity/issues/2479 is handled
# disable all implicit fallthrough warnings in the codebase for GCC > 7.0
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0)
add_compile_options(-Wno-implicit-fallthrough)
endif()
# Additional Clang-specific compiler settings.
elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")

View File

@ -48,10 +48,3 @@ option(Boost_USE_STATIC_LIBS "Link Boost statically" ON)
find_package(Boost 1.54.0 QUIET REQUIRED COMPONENTS regex filesystem unit_test_framework program_options system)
eth_show_dependency(Boost boost)
if (APPLE)
link_directories(/usr/local/lib)
include_directories(/usr/local/include)
endif()
include_directories(BEFORE "${PROJECT_BINARY_DIR}/include")

View File

@ -279,7 +279,7 @@ 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.
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 are not indexed form the byte array of the event.
In effect, a log entry using this ABI is described as:
@ -442,3 +442,22 @@ would result in the JSON:
"outputs": []
}
]
.. _abi_packed_mode:
Non-standard Packed Mode
========================
Solidity supports a non-standard packed mode where:
- no :ref:`function selector <abi_function_selector>` is encoded,
- short types are not zero padded and
- dynamic types are encoded in-place and without the length.
As an example encoding ``uint1, bytes1, uint8, string`` with values ``1, 0x42, 0x2424, "Hello, world!"`` results in ::
0x0142242448656c6c6f2c20776f726c6421
^^ uint1(1)
^^ bytes1(0x42)
^^^^ uint8(0x2424)
^^^^^^^^^^^^^^^^^^^^^^^^^^ string("Hello, world!") without a length field

View File

@ -1,4 +1,11 @@
[
{
"name": "ZeroFunctionSelector",
"summary": "It is possible to craft the name of a function such that it is executed instead of the fallback function in very specific circumstances.",
"description": "If a function has a selector consisting only of zeros, is payable and part of a contract that does not have a fallback function and at most five external functions in total, this function is called instead of the fallback function if Ether is sent to the contract without data.",
"fixed": "0.4.18",
"severity": "very low"
},
{
"name": "DelegateCallReturnValue",
"summary": "The low-level .delegatecall() does not return the execution outcome, but converts the value returned by the functioned called to a boolean instead.",

View File

@ -48,7 +48,7 @@ fixed
publish
The date at which the bug became known publicly, optional
severity
Severity of the bug: low, medium, high. Takes into account
Severity of the bug: very low, low, medium, high. Takes into account
discoverability in contract tests, likelihood of occurrence and
potential damage by exploits.
conditions

View File

@ -1,6 +1,7 @@
{
"0.1.0": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -17,6 +18,7 @@
},
"0.1.1": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -33,6 +35,7 @@
},
"0.1.2": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -49,6 +52,7 @@
},
"0.1.3": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -65,6 +69,7 @@
},
"0.1.4": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -81,6 +86,7 @@
},
"0.1.5": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -97,6 +103,7 @@
},
"0.1.6": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -114,6 +121,7 @@
},
"0.1.7": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -131,6 +139,7 @@
},
"0.2.0": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -148,6 +157,7 @@
},
"0.2.1": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -165,6 +175,7 @@
},
"0.2.2": {
"bugs": [
"ZeroFunctionSelector",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
"ConstantOptimizerSubtraction",
@ -182,6 +193,7 @@
},
"0.3.0": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -199,6 +211,7 @@
},
"0.3.1": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -215,6 +228,7 @@
},
"0.3.2": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -231,6 +245,7 @@
},
"0.3.3": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -246,6 +261,7 @@
},
"0.3.4": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -261,6 +277,7 @@
},
"0.3.5": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -276,6 +293,7 @@
},
"0.3.6": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -289,6 +307,7 @@
},
"0.4.0": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -302,6 +321,7 @@
},
"0.4.1": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -315,6 +335,7 @@
},
"0.4.10": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -324,6 +345,7 @@
},
"0.4.11": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral"
@ -332,6 +354,7 @@
},
"0.4.12": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput"
],
@ -339,6 +362,7 @@
},
"0.4.13": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput"
],
@ -346,24 +370,36 @@
},
"0.4.14": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue"
],
"released": "2017-07-31"
},
"0.4.15": {
"bugs": [],
"bugs": [
"ZeroFunctionSelector"
],
"released": "2017-08-08"
},
"0.4.16": {
"bugs": [],
"bugs": [
"ZeroFunctionSelector"
],
"released": "2017-08-24"
},
"0.4.17": {
"bugs": [],
"bugs": [
"ZeroFunctionSelector"
],
"released": "2017-09-21"
},
"0.4.18": {
"bugs": [],
"released": "2017-10-18"
},
"0.4.2": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -376,6 +412,7 @@
},
"0.4.3": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -387,6 +424,7 @@
},
"0.4.4": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -397,6 +435,7 @@
},
"0.4.5": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -408,6 +447,7 @@
},
"0.4.6": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -418,6 +458,7 @@
},
"0.4.7": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -427,6 +468,7 @@
},
"0.4.8": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",
@ -436,6 +478,7 @@
},
"0.4.9": {
"bugs": [
"ZeroFunctionSelector",
"DelegateCallReturnValue",
"ECRecoverMalformedInput",
"SkipEmptyStringLiteral",

View File

@ -93,7 +93,7 @@ Notice that, in this example, an attacker could trap the
contract into an unusable state by causing ``richest`` to be
the address of a contract that has a fallback function
which fails (e.g. by using ``revert()`` or by just
conssuming more than the 2300 gas stipend). That way,
consuming more than the 2300 gas stipend). That way,
whenever ``transfer`` is called to deliver funds to the
"poisoned" contract, it will fail and thus also ``becomeRichest``
will fail, with the contract being stuck forever.
@ -121,7 +121,7 @@ unless you declare make your state variables ``public``.
Furthermore, you can restrict who can make modifications
to your contract's state or call your contract's
functions and this is what this page is about.
functions and this is what this section is about.
.. index:: function;modifier

View File

@ -20,7 +20,7 @@ Contracts can be created "from outside" via Ethereum transactions or from within
IDEs, such as `Remix <https://remix.ethereum.org/>`_, make the creation process seamless using UI elements.
Creating contracts programatically on Ethereum is best done via using the JavaScript API `web3.js <https://github.com/etherem/web3.js>`_.
Creating contracts programatically on Ethereum is best done via using the JavaScript API `web3.js <https://github.com/ethereum/web3.js>`_.
As of today it has a method called `web3.eth.Contract <https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#new-contract>`_
to facilitate contract creation.

View File

@ -64,9 +64,11 @@ Running the compiler tests
==========================
Solidity includes different types of tests. They are included in the application
called ``soltest``. Some of them require the ``cpp-ethereum`` client in testing mode.
called ``soltest``. Some of them require the ``cpp-ethereum`` client in testing mode,
some others require ``libz3`` to be installed.
To run a subset of the tests that do not require ``cpp-ethereum``, use ``./build/test/soltest -- --no-ipc``.
To disable the z3 tests, use ``./build/test/soltest -- --no-smt`` and
to run a subset of the tests that do not require ``cpp-ethereum``, use ``./build/test/soltest -- --no-ipc``.
For all other tests, you need to install `cpp-ethereum <https://github.com/ethereum/cpp-ethereum/releases/download/solidityTester/eth>`_ and run it in testing mode: ``eth --test -d /tmp/testeth``.

View File

@ -304,8 +304,9 @@ There are defaults for the storage location depending on which type
of variable it concerns:
* state variables are always in storage
* function arguments are always in memory
* local variables always reference storage
* function arguments are in memory by default
* local variables of struct, array or mapping type reference storage by default
* local variables of value type (i.e. neither array, nor struct nor mapping) are stored in the stack
Example::
@ -431,12 +432,12 @@ What happens to a ``struct``'s mapping when copying over a ``struct``?
This is a very interesting question. Suppose that we have a contract field set up like such::
struct user {
mapping(string => address) usedContracts;
mapping(string => string) comments;
}
function somefunction {
user user1;
user1.usedContracts["Hello"] = "World";
user1.comments["Hello"] = "World";
user user2 = user1;
}

View File

@ -145,7 +145,7 @@ Byte = 'byte' | 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' |
Fixed = 'fixed' | ( 'fixed' DecimalNumber 'x' DecimalNumber )
Uixed = 'ufixed' | ( 'ufixed' DecimalNumber 'x' DecimalNumber )
Ufixed = 'ufixed' | ( 'ufixed' DecimalNumber 'x' DecimalNumber )
InlineAssemblyBlock = '{' AssemblyItem* '}'

View File

@ -61,6 +61,9 @@ Available Solidity Integrations
* `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>`_.
* `Solhint <https://github.com/protofire/solhint>`_
Solidity linter that provides security, style guide and best practice rules for smart contract validation.
* `Visual Studio Code extension <http://juan.blanco.ws/solidity-contracts-in-visual-studio-code/>`_
Solidity plugin for Microsoft Visual Studio Code that includes syntax highlighting and the Solidity compiler.

View File

@ -322,17 +322,17 @@ Global Variables
- ``assert(bool condition)``: abort execution and revert state changes if condition is ``false`` (use for internal error)
- ``require(bool condition)``: abort execution and revert state changes if condition is ``false`` (use for malformed input or error in external component)
- ``revert()``: abort execution and revert state changes
- ``keccak256(...) returns (bytes32)``: compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments
- ``keccak256(...) returns (bytes32)``: compute the Ethereum-SHA-3 (Keccak-256) hash of the :ref:`(tightly packed) arguments <abi_packed_mode>`
- ``sha3(...) returns (bytes32)``: an alias to ``keccak256``
- ``sha256(...) returns (bytes32)``: compute the SHA-256 hash of the (tightly packed) arguments
- ``ripemd160(...) returns (bytes20)``: compute the RIPEMD-160 hash of the (tightly packed) arguments
- ``sha256(...) returns (bytes32)``: compute the SHA-256 hash of the :ref:`(tightly packed) arguments <abi_packed_mode>`
- ``ripemd160(...) returns (bytes20)``: compute the RIPEMD-160 hash of the :ref:`(tightly packed) arguments <abi_packed_mode>`
- ``ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)``: recover address associated with the public key from elliptic curve signature, return zero on error
- ``addmod(uint x, uint y, uint k) returns (uint)``: compute ``(x + y) % k`` where the addition is performed with arbitrary precision and does not wrap around at ``2**256``
- ``mulmod(uint x, uint y, uint k) returns (uint)``: compute ``(x * y) % k`` where the multiplication is performed with arbitrary precision and does not wrap around at ``2**256``
- ``this`` (current contract's type): the current contract, explicitly convertible to ``address``
- ``super``: the contract one level higher in the inheritance hierarchy
- ``selfdestruct(address recipient)``: destroy the current contract, sending its funds to the given address
- ``suicide(address recipieint)``: an alias to ``selfdestruct``
- ``suicide(address recipient)``: an alias to ``selfdestruct``
- ``<address>.balance`` (``uint256``): balance of the :ref:`address` in Wei
- ``<address>.send(uint256 amount) returns (bool)``: send given amount of Wei to :ref:`address`, returns ``false`` on failure
- ``<address>.transfer(uint256 amount)``: send given amount of Wei to :ref:`address`, throws on failure

View File

@ -107,6 +107,9 @@ Operators:
* ``<=``, ``<``, ``==``, ``!=``, ``>=`` and ``>``
.. note::
Starting with version 0.5.0 contracts do not derive from the address type, but can still be explicitly converted to address.
.. _members-of-addresses:
Members of Addresses
@ -240,6 +243,9 @@ Hexadecimal literals that are between 39 and 41 digits
long and do not pass the checksum test produce
a warning and are treated as regular rational number literals.
.. note::
The mixed-case address checksum format is defined in `EIP-55 <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md>`_.
.. index:: literal, literal;rational
.. _rational_literals:

View File

@ -116,13 +116,13 @@ Mathematical and Cryptographic Functions
``mulmod(uint x, uint y, uint k) returns (uint)``:
compute ``(x * y) % k`` where the multiplication is performed with arbitrary precision and does not wrap around at ``2**256``.
``keccak256(...) returns (bytes32)``:
compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments
compute the Ethereum-SHA-3 (Keccak-256) hash of the :ref:`(tightly packed) arguments <abi_packed_mode>`
``sha256(...) returns (bytes32)``:
compute the SHA-256 hash of the (tightly packed) arguments
compute the SHA-256 hash of the :ref:`(tightly packed) arguments <abi_packed_mode>`
``sha3(...) returns (bytes32)``:
alias to ``keccak256``
``ripemd160(...) returns (bytes20)``:
compute RIPEMD-160 hash of the (tightly packed) arguments
compute RIPEMD-160 hash of the :ref:`(tightly packed) arguments <abi_packed_mode>`
``ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)``:
recover the address associated with the public key from elliptic curve signature or return zero on error
(`example usage <https://ethereum.stackexchange.com/q/1777/222>`_)

View File

@ -24,10 +24,14 @@ using namespace dev;
char const* Exception::what() const noexcept
{
// Return the comment if available.
if (string const* cmt = comment())
return cmt->c_str();
else
return nullptr;
return cmt->data();
// Fallback to base what().
// Boost accepts nullptr, but the C++ standard doesn't
// and crashes on some platforms.
return std::exception::what();
}
string Exception::lineInfo() const

View File

@ -90,7 +90,13 @@ string Whiskers::replace(
string tagName(_match[1]);
if (!tagName.empty())
{
assertThrow(_parameters.count(tagName), WhiskersError, "Value for tag " + tagName + " not provided.");
assertThrow(
_parameters.count(tagName),
WhiskersError,
"Value for tag " + tagName + " not provided.\n" +
"Template:\n" +
_template
);
return _parameters.at(tagName);
}
else

View File

@ -408,7 +408,10 @@ map<u256, u256> Assembly::optimiseInternal(
{
PeepholeOptimiser peepOpt(m_items);
while (peepOpt.optimise())
{
count++;
assertThrow(count < 64000, OptimizerException, "Peephole optimizer seems to be stuck.");
}
}
// This only modifies PushTags, we have to run again to actually remove code.

View File

@ -17,8 +17,6 @@
#include <libevmasm/AssemblyItem.h>
#include <libevmasm/SemanticInformation.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/FixedHash.h>
@ -112,7 +110,7 @@ bool AssemblyItem::canBeFunctional() const
switch (m_type)
{
case Operation:
return !SemanticInformation::isDupInstruction(*this) && !SemanticInformation::isSwapInstruction(*this);
return !isDupInstruction(instruction()) && !isSwapInstruction(instruction());
case Push:
case PushString:
case PushTag:

View File

@ -2,4 +2,4 @@ file(GLOB sources "*.cpp")
file(GLOB headers "*.h")
add_library(evmasm ${sources} ${headers})
target_link_libraries(evmasm PUBLIC devcore jsoncpp)
target_link_libraries(evmasm PUBLIC jsoncpp devcore)

View File

@ -1,62 +0,0 @@
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EVMSchedule.h
* @author Gav <i@gavwood.com>
* @author Christian <c@ethdev.com>
* @date 2015
*/
#pragma once
namespace dev
{
namespace solidity
{
struct EVMSchedule
{
unsigned stackLimit = 1024;
unsigned expGas = 10;
unsigned expByteGas = 10;
unsigned keccak256Gas = 30;
unsigned keccak256WordGas = 6;
unsigned sloadGas = 200;
unsigned sstoreSetGas = 20000;
unsigned sstoreResetGas = 5000;
unsigned sstoreRefundGas = 15000;
unsigned jumpdestGas = 1;
unsigned logGas = 375;
unsigned logDataGas = 8;
unsigned logTopicGas = 375;
unsigned createGas = 32000;
unsigned callGas = 40;
unsigned callStipend = 2300;
unsigned callValueTransferGas = 9000;
unsigned callNewAccountGas = 25000;
unsigned selfdestructRefundGas = 24000;
unsigned memoryGas = 3;
unsigned quadCoeffDiv = 512;
unsigned createDataGas = 200;
unsigned txGas = 21000;
unsigned txCreateGas = 53000;
unsigned txDataZeroGas = 4;
unsigned txDataNonZeroGas = 68;
unsigned copyGas = 3;
};
}
}

View File

@ -197,6 +197,24 @@ enum class Instruction: uint8_t
SELFDESTRUCT = 0xff ///< halt execution and register account for later deletion
};
/// @returns true if the instruction is a PUSH
inline bool isPushInstruction(Instruction _inst)
{
return Instruction::PUSH1 <= _inst && _inst <= Instruction::PUSH32;
}
/// @returns true if the instruction is a DUP
inline bool isDupInstruction(Instruction _inst)
{
return Instruction::DUP1 <= _inst && _inst <= Instruction::DUP16;
}
/// @returns true if the instruction is a SWAP
inline bool isSwapInstruction(Instruction _inst)
{
return Instruction::SWAP1 <= _inst && _inst <= Instruction::SWAP16;
}
/// @returns the number of PUSH Instruction _inst
inline unsigned getPushNumber(Instruction _inst)
{

View File

@ -249,6 +249,11 @@ void applyMethods(OptimiserState& _state, Method, OtherMethods... _other)
applyMethods(_state, _other...);
}
size_t numberOfPops(AssemblyItems const& _items)
{
return std::count(_items.begin(), _items.end(), Instruction::POP);
}
}
bool PeepholeOptimiser::optimise()
@ -257,8 +262,10 @@ bool PeepholeOptimiser::optimise()
while (state.i < m_items.size())
applyMethods(state, PushPop(), OpPop(), DoublePush(), DoubleSwap(), JumpToNext(), UnreachableCode(), TagConjunctions(), Identity());
if (m_optimisedItems.size() < m_items.size() || (
m_optimisedItems.size() == m_items.size() &&
eth::bytesRequired(m_optimisedItems, 3) < eth::bytesRequired(m_items, 3)
m_optimisedItems.size() == m_items.size() && (
eth::bytesRequired(m_optimisedItems, 3) < eth::bytesRequired(m_items, 3) ||
numberOfPops(m_optimisedItems) > numberOfPops(m_items)
)
))
{
m_items = std::move(m_optimisedItems);

View File

@ -90,14 +90,14 @@ bool SemanticInformation::isDupInstruction(AssemblyItem const& _item)
{
if (_item.type() != Operation)
return false;
return Instruction::DUP1 <= _item.instruction() && _item.instruction() <= Instruction::DUP16;
return solidity::isDupInstruction(_item.instruction());
}
bool SemanticInformation::isSwapInstruction(AssemblyItem const& _item)
{
if (_item.type() != Operation)
return false;
return Instruction::SWAP1 <= _item.instruction() && _item.instruction() <= Instruction::SWAP16;
return solidity::isSwapInstruction(_item.instruction());
}
bool SemanticInformation::isJumpInstruction(AssemblyItem const& _item)
@ -198,6 +198,7 @@ bool SemanticInformation::invalidInPureFunctions(Instruction _instruction)
case Instruction::ORIGIN:
case Instruction::CALLER:
case Instruction::CALLVALUE:
case Instruction::GAS:
case Instruction::GASPRICE:
case Instruction::EXTCODESIZE:
case Instruction::EXTCODECOPY:
@ -223,7 +224,6 @@ bool SemanticInformation::invalidInViewFunctions(Instruction _instruction)
case Instruction::SSTORE:
case Instruction::JUMP:
case Instruction::JUMPI:
case Instruction::GAS:
case Instruction::LOG0:
case Instruction::LOG1:
case Instruction::LOG2:

View File

@ -47,7 +47,34 @@ void CodeFragment::finalise(CompilerState const& _cs)
}
}
CodeFragment::CodeFragment(sp::utree const& _t, CompilerState& _s, bool _allowASM)
namespace
{
/// Returns true iff the instruction is valid in "inline assembly".
bool validAssemblyInstruction(string us)
{
auto it = c_instructions.find(us);
return !(
it == c_instructions.end() ||
solidity::isPushInstruction(it->second)
);
}
/// Returns true iff the instruction is valid as a function.
bool validFunctionalInstruction(string us)
{
auto it = c_instructions.find(us);
return !(
it == c_instructions.end() ||
solidity::isPushInstruction(it->second) ||
solidity::isDupInstruction(it->second) ||
solidity::isSwapInstruction(it->second) ||
it->second == solidity::Instruction::JUMPDEST
);
}
}
CodeFragment::CodeFragment(sp::utree const& _t, CompilerState& _s, ReadCallback const& _readFile, bool _allowASM):
m_readFile(_readFile)
{
/*
std::cout << "CodeFragment. Locals:";
@ -79,7 +106,7 @@ CodeFragment::CodeFragment(sp::utree const& _t, CompilerState& _s, bool _allowAS
auto sr = _t.get<sp::basic_string<boost::iterator_range<char const*>, sp::utree_type::symbol_type>>();
string s(sr.begin(), sr.end());
string us = boost::algorithm::to_upper_copy(s);
if (_allowASM && c_instructions.count(us))
if (_allowASM && c_instructions.count(us) && validAssemblyInstruction(us))
m_asm.append(c_instructions.at(us));
else if (_s.defs.count(s))
m_asm.append(_s.defs.at(s).m_asm);
@ -103,7 +130,7 @@ CodeFragment::CodeFragment(sp::utree const& _t, CompilerState& _s, bool _allowAS
{
bigint i = *_t.get<bigint*>();
if (i < 0 || i > bigint(u256(0) - 1))
error<IntegerOutOfRange>();
error<IntegerOutOfRange>(toString(i));
m_asm.append((u256)i);
break;
}
@ -157,7 +184,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
{
auto i = *++_t.begin();
if (i.tag())
error<InvalidName>();
error<InvalidName>(toString(i));
if (i.which() == sp::utree_type::string_type)
{
auto sr = i.get<sp::basic_string<boost::iterator_range<char const*>, sp::utree_type::string_type>>();
@ -198,7 +225,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
int c = 0;
for (auto const& i: _t)
if (c++)
m_asm.append(CodeFragment(i, _s, true).m_asm);
m_asm.append(CodeFragment(i, _s, m_readFile, true).m_asm);
}
else if (us == "INCLUDE")
{
@ -207,10 +234,12 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
string fileName = firstAsString();
if (fileName.empty())
error<InvalidName>("Empty file name provided");
string contents = contentsString(fileName);
if (!m_readFile)
error<InvalidName>("Import callback not present");
string contents = m_readFile(fileName);
if (contents.empty())
error<InvalidName>(std::string("File not found (or empty): ") + fileName);
m_asm.append(CodeFragment::compile(contents, _s).m_asm);
m_asm.append(CodeFragment::compile(contents, _s, m_readFile).m_asm);
}
else if (us == "SET")
{
@ -219,7 +248,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
int c = 0;
for (auto const& i: _t)
if (c++ == 2)
m_asm.append(CodeFragment(i, _s, false).m_asm);
m_asm.append(CodeFragment(i, _s, m_readFile, false).m_asm);
m_asm.append((u256)varAddress(firstAsString(), true));
m_asm.append(Instruction::MSTORE);
}
@ -244,7 +273,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
if (ii == 1)
{
if (i.tag())
error<InvalidName>();
error<InvalidName>(toString(i));
if (i.which() == sp::utree_type::string_type)
{
auto sr = i.get<sp::basic_string<boost::iterator_range<char const*>, sp::utree_type::string_type>>();
@ -260,7 +289,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
if (_t.size() == 3)
{
/// NOTE: some compilers could do the assignment first if this is done in a single line
CodeFragment code = CodeFragment(i, _s);
CodeFragment code = CodeFragment(i, _s, m_readFile);
_s.defs[n] = code;
}
else
@ -301,13 +330,13 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
}
else if (ii == 1)
{
pos = CodeFragment(i, _s);
pos = CodeFragment(i, _s, m_readFile);
if (pos.m_asm.deposit() != 1)
error<InvalidDeposit>(us);
error<InvalidDeposit>(toString(i));
}
else if (i.tag() != 0)
{
error<InvalidLiteral>();
error<InvalidLiteral>(toString(i));
}
else if (i.which() == sp::utree_type::string_type)
{
@ -318,7 +347,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
{
bigint bi = *i.get<bigint*>();
if (bi < 0)
error<IntegerOutOfRange>();
error<IntegerOutOfRange>(toString(i));
else
{
bytes tmp = toCompactBigEndian(bi);
@ -327,7 +356,7 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
}
else
{
error<InvalidLiteral>();
error<InvalidLiteral>(toString(i));
}
ii++;
@ -380,9 +409,9 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
if (c++)
{
if (us == "LLL" && c == 1)
code.push_back(CodeFragment(i, ns));
code.push_back(CodeFragment(i, ns, m_readFile));
else
code.push_back(CodeFragment(i, _s));
code.push_back(CodeFragment(i, _s, m_readFile));
}
auto requireSize = [&](unsigned s) { if (code.size() != s) error<IncorrectParameterCount>(us); };
auto requireMinSize = [&](unsigned s) { if (code.size() < s) error<IncorrectParameterCount>(us); };
@ -403,13 +432,13 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
//requireDeposit(i, 1);
cs.args[m.args[i]] = code[i];
}
m_asm.append(CodeFragment(m.code, cs).m_asm);
m_asm.append(CodeFragment(m.code, cs, m_readFile).m_asm);
for (auto const& i: cs.defs)
_s.defs[i.first] = i.second;
for (auto const& i: cs.macros)
_s.macros.insert(i);
}
else if (c_instructions.count(us))
else if (c_instructions.count(us) && validFunctionalInstruction(us))
{
auto it = c_instructions.find(us);
requireSize(instructionInfo(it->second).args);
@ -514,6 +543,44 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
m_asm.appendJump(begin);
m_asm << end.tag();
}
else if (us == "SWITCH")
{
requireMinSize(1);
bool hasDefault = (code.size() % 2 == 1);
int startDeposit = m_asm.deposit();
int targetDeposit = hasDefault ? code[code.size() - 1].m_asm.deposit() : 0;
// The conditions
AssemblyItems jumpTags;
for (unsigned i = 0; i < code.size() - 1; i += 2)
{
requireDeposit(i, 1);
m_asm.append(code[i].m_asm);
jumpTags.push_back(m_asm.appendJumpI());
}
// The default, if present
if (hasDefault)
m_asm.append(code[code.size() - 1].m_asm);
// The targets - appending in reverse makes the top case the most efficient.
if (code.size() > 1)
{
auto end = m_asm.appendJump();
for (int i = 2 * (code.size() / 2 - 1); i >= 0; i -= 2)
{
m_asm << jumpTags[i / 2].tag();
requireDeposit(i + 1, targetDeposit);
m_asm.append(code[i + 1].m_asm);
if (i != 0)
m_asm.appendJump(end);
}
m_asm << end.tag();
}
m_asm.setDeposit(startDeposit + targetDeposit);
}
else if (us == "ALLOC")
{
requireSize(1);
@ -622,13 +689,13 @@ void CodeFragment::constructOperation(sp::utree const& _t, CompilerState& _s)
}
}
CodeFragment CodeFragment::compile(string const& _src, CompilerState& _s)
CodeFragment CodeFragment::compile(string const& _src, CompilerState& _s, ReadCallback const& _readFile)
{
CodeFragment ret;
sp::utree o;
parseTreeLLL(_src, o);
if (!o.empty())
ret = CodeFragment(o, _s);
ret = CodeFragment(o, _s, _readFile);
_s.treesToKill.push_back(o);
return ret;
}

View File

@ -39,10 +39,12 @@ struct CompilerState;
class CodeFragment
{
public:
CodeFragment() {}
CodeFragment(sp::utree const& _t, CompilerState& _s, bool _allowASM = false);
using ReadCallback = std::function<std::string(std::string const&)>;
static CodeFragment compile(std::string const& _src, CompilerState& _s);
CodeFragment() {}
CodeFragment(sp::utree const& _t, CompilerState& _s, ReadCallback const& _readFile, bool _allowASM = false);
static CodeFragment compile(std::string const& _src, CompilerState& _s, ReadCallback const& _readFile);
/// Consolidates data and compiles code.
Assembly& assembly(CompilerState const& _cs) { finalise(_cs); return m_asm; }
@ -60,6 +62,7 @@ private:
bool m_finalised = false;
Assembly m_asm;
ReadCallback m_readFile;
};
static const CodeFragment NullCodeFragment;

View File

@ -28,13 +28,14 @@ using namespace std;
using namespace dev;
using namespace dev::eth;
bytes dev::eth::compileLLL(string const& _src, bool _opt, vector<string>* _errors)
bytes dev::eth::compileLLL(string const& _src, bool _opt, vector<string>* _errors, ReadCallback const& _readFile)
{
try
{
CompilerState cs;
cs.populateStandard();
auto assembly = CodeFragment::compile(_src, cs).assembly(cs);
auto assembly = CodeFragment::compile(_src, cs, _readFile).assembly(cs);
if (_opt)
assembly = assembly.optimise(true);
bytes ret = assembly.assemble().bytecode;
@ -66,13 +67,13 @@ bytes dev::eth::compileLLL(string const& _src, bool _opt, vector<string>* _error
return bytes();
}
std::string dev::eth::compileLLLToAsm(std::string const& _src, bool _opt, std::vector<std::string>* _errors)
std::string dev::eth::compileLLLToAsm(std::string const& _src, bool _opt, std::vector<std::string>* _errors, ReadCallback const& _readFile)
{
try
{
CompilerState cs;
cs.populateStandard();
auto assembly = CodeFragment::compile(_src, cs).assembly(cs);
auto assembly = CodeFragment::compile(_src, cs, _readFile).assembly(cs);
if (_opt)
assembly = assembly.optimise(true);
string ret = assembly.assemblyString();

View File

@ -30,9 +30,11 @@ namespace dev
namespace eth
{
using ReadCallback = std::function<std::string(std::string const&)>;
std::string parseLLL(std::string const& _src);
std::string compileLLLToAsm(std::string const& _src, bool _opt = true, std::vector<std::string>* _errors = nullptr);
bytes compileLLL(std::string const& _src, bool _opt = true, std::vector<std::string>* _errors = nullptr);
std::string compileLLLToAsm(std::string const& _src, bool _opt = true, std::vector<std::string>* _errors = nullptr, ReadCallback const& _readFile = ReadCallback());
bytes compileLLL(std::string const& _src, bool _opt = true, std::vector<std::string>* _errors = nullptr, ReadCallback const& _readFile = ReadCallback());
}
}

View File

@ -82,5 +82,5 @@ void CompilerState::populateStandard()
"(def 'shl (val shift) (mul val (exp 2 shift)))"
"(def 'shr (val shift) (div val (exp 2 shift)))"
"}";
CodeFragment::compile(s, *this);
CodeFragment::compile(s, *this, CodeFragment::ReadCallback());
}

View File

@ -6,9 +6,9 @@ find_package(Z3 QUIET)
if (${Z3_FOUND})
include_directories(${Z3_INCLUDE_DIR})
add_definitions(-DHAVE_Z3)
message("Z3 SMT solver FOUND.")
message("Z3 SMT solver found. This enables optional SMT checking.")
else()
message("Z3 SMT solver NOT found.")
message("Z3 SMT solver NOT found. Optional SMT checking will not be available. Please install Z3 if it is desired.")
list(REMOVE_ITEM sources "${CMAKE_CURRENT_SOURCE_DIR}/formal/Z3Interface.cpp")
endif()

View File

@ -22,17 +22,17 @@
#include <libsolidity/analysis/ConstantEvaluator.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/interface/ErrorReporter.h>
using namespace std;
using namespace dev;
using namespace dev::solidity;
void ConstantEvaluator::endVisit(UnaryOperation const& _operation)
{
TypePointer const& subType = _operation.subExpression().annotation().type;
if (!dynamic_cast<RationalNumberType const*>(subType.get()))
BOOST_THROW_EXCEPTION(_operation.subExpression().createTypeError("Invalid constant expression."));
m_errorReporter.fatalTypeError(_operation.subExpression().location(), "Invalid constant expression.");
TypePointer t = subType->unaryOperatorResult(_operation.getOperator());
_operation.annotation().type = t;
}
@ -42,9 +42,9 @@ void ConstantEvaluator::endVisit(BinaryOperation const& _operation)
TypePointer const& leftType = _operation.leftExpression().annotation().type;
TypePointer const& rightType = _operation.rightExpression().annotation().type;
if (!dynamic_cast<RationalNumberType const*>(leftType.get()))
BOOST_THROW_EXCEPTION(_operation.leftExpression().createTypeError("Invalid constant expression."));
m_errorReporter.fatalTypeError(_operation.leftExpression().location(), "Invalid constant expression.");
if (!dynamic_cast<RationalNumberType const*>(rightType.get()))
BOOST_THROW_EXCEPTION(_operation.rightExpression().createTypeError("Invalid constant expression."));
m_errorReporter.fatalTypeError(_operation.rightExpression().location(), "Invalid constant expression.");
TypePointer commonType = leftType->binaryOperatorResult(_operation.getOperator(), rightType);
if (Token::isCompareOp(_operation.getOperator()))
commonType = make_shared<BoolType>();
@ -55,5 +55,5 @@ void ConstantEvaluator::endVisit(Literal const& _literal)
{
_literal.annotation().type = Type::forLiteral(_literal);
if (!_literal.annotation().type)
BOOST_THROW_EXCEPTION(_literal.createTypeError("Invalid literal value."));
m_errorReporter.fatalTypeError(_literal.location(), "Invalid literal value.");
}

View File

@ -29,6 +29,7 @@ namespace dev
namespace solidity
{
class ErrorReporter;
class TypeChecker;
/**
@ -37,13 +38,18 @@ class TypeChecker;
class ConstantEvaluator: private ASTConstVisitor
{
public:
ConstantEvaluator(Expression const& _expr) { _expr.accept(*this); }
ConstantEvaluator(Expression const& _expr, ErrorReporter& _errorReporter):
m_errorReporter(_errorReporter)
{
_expr.accept(*this);
}
private:
virtual void endVisit(BinaryOperation const& _operation);
virtual void endVisit(UnaryOperation const& _operation);
virtual void endVisit(Literal const& _literal);
ErrorReporter& m_errorReporter;
};
}

View File

@ -34,44 +34,29 @@ namespace solidity
{
GlobalContext::GlobalContext():
m_magicVariables(vector<shared_ptr<MagicVariableDeclaration const>>{make_shared<MagicVariableDeclaration>("block", make_shared<MagicType>(MagicType::Kind::Block)),
make_shared<MagicVariableDeclaration>("msg", make_shared<MagicType>(MagicType::Kind::Message)),
make_shared<MagicVariableDeclaration>("tx", make_shared<MagicType>(MagicType::Kind::Transaction)),
make_shared<MagicVariableDeclaration>("now", make_shared<IntegerType>(256)),
make_shared<MagicVariableDeclaration>("suicide",
make_shared<FunctionType>(strings{"address"}, strings{}, FunctionType::Kind::Selfdestruct)),
make_shared<MagicVariableDeclaration>("selfdestruct",
make_shared<FunctionType>(strings{"address"}, strings{}, FunctionType::Kind::Selfdestruct)),
make_shared<MagicVariableDeclaration>("addmod",
make_shared<FunctionType>(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Kind::AddMod, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("mulmod",
make_shared<FunctionType>(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Kind::MulMod, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("sha3",
make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Kind::SHA3, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("keccak256",
make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Kind::SHA3, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("log0",
make_shared<FunctionType>(strings{"bytes32"}, strings{}, FunctionType::Kind::Log0)),
make_shared<MagicVariableDeclaration>("log1",
make_shared<FunctionType>(strings{"bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log1)),
make_shared<MagicVariableDeclaration>("log2",
make_shared<FunctionType>(strings{"bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log2)),
make_shared<MagicVariableDeclaration>("log3",
make_shared<FunctionType>(strings{"bytes32", "bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log3)),
make_shared<MagicVariableDeclaration>("log4",
make_shared<FunctionType>(strings{"bytes32", "bytes32", "bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log4)),
make_shared<MagicVariableDeclaration>("sha256",
make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Kind::SHA256, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("ecrecover",
make_shared<FunctionType>(strings{"bytes32", "uint8", "bytes32", "bytes32"}, strings{"address"}, FunctionType::Kind::ECRecover, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("ripemd160",
make_shared<FunctionType>(strings(), strings{"bytes20"}, FunctionType::Kind::RIPEMD160, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("assert",
make_shared<FunctionType>(strings{"bool"}, strings{}, FunctionType::Kind::Assert, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("require",
make_shared<FunctionType>(strings{"bool"}, strings{}, FunctionType::Kind::Require, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("revert",
make_shared<FunctionType>(strings(), strings(), FunctionType::Kind::Revert, false, StateMutability::Pure))})
m_magicVariables(vector<shared_ptr<MagicVariableDeclaration const>>{
make_shared<MagicVariableDeclaration>("addmod", make_shared<FunctionType>(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Kind::AddMod, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("assert", make_shared<FunctionType>(strings{"bool"}, strings{}, FunctionType::Kind::Assert, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("block", make_shared<MagicType>(MagicType::Kind::Block)),
make_shared<MagicVariableDeclaration>("ecrecover", make_shared<FunctionType>(strings{"bytes32", "uint8", "bytes32", "bytes32"}, strings{"address"}, FunctionType::Kind::ECRecover, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("keccak256", make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Kind::SHA3, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("log0", make_shared<FunctionType>(strings{"bytes32"}, strings{}, FunctionType::Kind::Log0)),
make_shared<MagicVariableDeclaration>("log1", make_shared<FunctionType>(strings{"bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log1)),
make_shared<MagicVariableDeclaration>("log2", make_shared<FunctionType>(strings{"bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log2)),
make_shared<MagicVariableDeclaration>("log3", make_shared<FunctionType>(strings{"bytes32", "bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log3)),
make_shared<MagicVariableDeclaration>("log4", make_shared<FunctionType>(strings{"bytes32", "bytes32", "bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Kind::Log4)),
make_shared<MagicVariableDeclaration>("msg", make_shared<MagicType>(MagicType::Kind::Message)),
make_shared<MagicVariableDeclaration>("mulmod", make_shared<FunctionType>(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Kind::MulMod, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("now", make_shared<IntegerType>(256)),
make_shared<MagicVariableDeclaration>("require", make_shared<FunctionType>(strings{"bool"}, strings{}, FunctionType::Kind::Require, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("revert", make_shared<FunctionType>(strings(), strings(), FunctionType::Kind::Revert, false, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("ripemd160", make_shared<FunctionType>(strings(), strings{"bytes20"}, FunctionType::Kind::RIPEMD160, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("selfdestruct", make_shared<FunctionType>(strings{"address"}, strings{}, FunctionType::Kind::Selfdestruct)),
make_shared<MagicVariableDeclaration>("sha256", make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Kind::SHA256, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("sha3", make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Kind::SHA3, true, StateMutability::Pure)),
make_shared<MagicVariableDeclaration>("suicide", make_shared<FunctionType>(strings{"address"}, strings{}, FunctionType::Kind::Selfdestruct)),
make_shared<MagicVariableDeclaration>("tx", make_shared<MagicType>(MagicType::Kind::Transaction))
})
{
}
@ -92,8 +77,7 @@ vector<Declaration const*> GlobalContext::declarations() const
MagicVariableDeclaration const* GlobalContext::currentThis() const
{
if (!m_thisPointer[m_currentContract])
m_thisPointer[m_currentContract] = make_shared<MagicVariableDeclaration>(
"this", make_shared<ContractType>(*m_currentContract));
m_thisPointer[m_currentContract] = make_shared<MagicVariableDeclaration>("this", make_shared<ContractType>(*m_currentContract));
return m_thisPointer[m_currentContract].get();
}
@ -101,8 +85,7 @@ MagicVariableDeclaration const* GlobalContext::currentThis() const
MagicVariableDeclaration const* GlobalContext::currentSuper() const
{
if (!m_superPointer[m_currentContract])
m_superPointer[m_currentContract] = make_shared<MagicVariableDeclaration>(
"super", make_shared<ContractType>(*m_currentContract, true));
m_superPointer[m_currentContract] = make_shared<MagicVariableDeclaration>("super", make_shared<ContractType>(*m_currentContract, true));
return m_superPointer[m_currentContract].get();
}

View File

@ -647,10 +647,12 @@ void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaratio
bool warnAboutShadowing = true;
// Do not warn about shadowing for structs and enums because their members are
// not accessible without prefixes.
// not accessible without prefixes. Also do not warn about event parameters
// because they don't participate in any proper scope.
if (
dynamic_cast<StructDefinition const*>(m_currentScope) ||
dynamic_cast<EnumDefinition const*>(m_currentScope)
dynamic_cast<EnumDefinition const*>(m_currentScope) ||
dynamic_cast<EventDefinition const*>(m_currentScope)
)
warnAboutShadowing = false;
// Do not warn about the constructor shadowing the contract.

View File

@ -147,10 +147,12 @@ void ReferencesResolver::endVisit(ArrayTypeName const& _typeName)
if (Expression const* length = _typeName.length())
{
if (!length->annotation().type)
ConstantEvaluator e(*length);
ConstantEvaluator e(*length, m_errorReporter);
auto const* lengthType = dynamic_cast<RationalNumberType const*>(length->annotation().type.get());
if (!lengthType || lengthType->isFractional())
if (!lengthType || !lengthType->mobileType())
fatalTypeError(length->location(), "Invalid array length, expected integer literal.");
else if (lengthType->isFractional())
fatalTypeError(length->location(), "Array with fractional length specified.");
else if (lengthType->isNegative())
fatalTypeError(length->location(), "Array with negative length specified.");
else
@ -296,11 +298,19 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
{
typeLoc = DataLocation::Storage;
if (_variable.isLocalVariable())
m_errorReporter.warning(
_variable.location(),
"Variable is declared as a storage pointer. "
"Use an explicit \"storage\" keyword to silence this warning."
);
{
if (_variable.sourceUnit().annotation().experimentalFeatures.count(ExperimentalFeature::V050))
typeError(
_variable.location(),
"Storage location must be specified as either \"memory\" or \"storage\"."
);
else
m_errorReporter.warning(
_variable.location(),
"Variable is declared as a storage pointer. "
"Use an explicit \"storage\" keyword to silence this warning."
);
}
}
}
else
@ -347,4 +357,3 @@ void ReferencesResolver::fatalDeclarationError(SourceLocation const& _location,
m_errorOccurred = true;
m_errorReporter.fatalDeclarationError(_location, _description);
}

View File

@ -182,8 +182,15 @@ bool SyntaxChecker::visit(Throw const& _throwStatement)
bool SyntaxChecker::visit(UnaryOperation const& _operation)
{
bool const v050 = m_sourceUnit->annotation().experimentalFeatures.count(ExperimentalFeature::V050);
if (_operation.getOperator() == Token::Add)
m_errorReporter.warning(_operation.location(), "Use of unary + is deprecated.");
{
if (v050)
m_errorReporter.syntaxError(_operation.location(), "Use of unary + is deprecated.");
else
m_errorReporter.warning(_operation.location(), "Use of unary + is deprecated.");
}
return true;
}

View File

@ -75,6 +75,7 @@ bool TypeChecker::visit(ContractDefinition const& _contract)
ASTNode::listAccept(_contract.baseContracts(), *this);
checkContractDuplicateFunctions(_contract);
checkContractDuplicateEvents(_contract);
checkContractIllegalOverrides(_contract);
checkContractAbstractFunctions(_contract);
checkContractAbstractConstructors(_contract);
@ -183,9 +184,27 @@ void TypeChecker::checkContractDuplicateFunctions(ContractDefinition const& _con
msg
);
}
for (auto const& it: functions)
findDuplicateDefinitions(functions, "Function with same name and arguments defined twice.");
}
void TypeChecker::checkContractDuplicateEvents(ContractDefinition const& _contract)
{
/// Checks that two events with the same name defined in this contract have different
/// argument types
map<string, vector<EventDefinition const*>> events;
for (EventDefinition const* event: _contract.events())
events[event->name()].push_back(event);
findDuplicateDefinitions(events, "Event with same name and arguments defined twice.");
}
template <class T>
void TypeChecker::findDuplicateDefinitions(map<string, vector<T>> const& _definitions, string _message)
{
for (auto const& it: _definitions)
{
vector<FunctionDefinition const*> const& overloads = it.second;
vector<T> const& overloads = it.second;
set<size_t> reported;
for (size_t i = 0; i < overloads.size() && !reported.count(i); ++i)
{
@ -200,18 +219,17 @@ void TypeChecker::checkContractDuplicateFunctions(ContractDefinition const& _con
if (ssl.infos.size() > 0)
{
string msg = "Function with same name and arguments defined twice.";
size_t occurrences = ssl.infos.size();
if (occurrences > 32)
{
ssl.infos.resize(32);
msg += " Truncated from " + boost::lexical_cast<string>(occurrences) + " to the first 32 occurrences.";
_message += " Truncated from " + boost::lexical_cast<string>(occurrences) + " to the first 32 occurrences.";
}
m_errorReporter.declarationError(
overloads[i]->location(),
ssl,
msg
_message
);
}
}
@ -577,8 +595,16 @@ bool TypeChecker::visit(FunctionDefinition const& _function)
{
if (_function.isImplemented())
m_errorReporter.typeError(_function.location(), "Functions in interfaces cannot have an implementation.");
if (_function.visibility() < FunctionDefinition::Visibility::Public)
m_errorReporter.typeError(_function.location(), "Functions in interfaces cannot be internal or private.");
if (_function.sourceUnit().annotation().experimentalFeatures.count(ExperimentalFeature::V050))
{
if (_function.visibility() != FunctionDefinition::Visibility::External)
m_errorReporter.typeError(_function.location(), "Functions in interfaces must be declared external.");
}
else
{
if (_function.visibility() < FunctionDefinition::Visibility::Public)
m_errorReporter.typeError(_function.location(), "Functions in interfaces cannot be internal or private.");
}
if (_function.isConstructor())
m_errorReporter.typeError(_function.location(), "Constructor cannot be defined in interfaces.");
}
@ -627,14 +653,23 @@ bool TypeChecker::visit(VariableDeclaration const& _variable)
if (!allowed)
m_errorReporter.typeError(_variable.location(), "Constants of non-value type not yet implemented.");
}
if (!_variable.value())
m_errorReporter.typeError(_variable.location(), "Uninitialized \"constant\" variable.");
else if (!_variable.value()->annotation().isPure)
m_errorReporter.warning(
_variable.value()->location(),
"Initial value for constant variable has to be compile-time constant. "
"This will fail to compile with the next breaking version change."
);
{
if (_variable.sourceUnit().annotation().experimentalFeatures.count(ExperimentalFeature::V050))
m_errorReporter.typeError(
_variable.value()->location(),
"Initial value for constant variable has to be compile-time constant."
);
else
m_errorReporter.warning(
_variable.value()->location(),
"Initial value for constant variable has to be compile-time constant. "
"This will fail to compile with the next breaking version change."
);
}
}
if (!_variable.isStateVariable())
{
@ -1258,6 +1293,12 @@ bool TypeChecker::visit(TupleExpression const& _tuple)
{
components[i]->accept(*this);
types.push_back(type(*components[i]));
// Note: code generation will visit each of the expression even if they are not assigned from.
if (types[i]->category() == Type::Category::RationalNumber && components.size() > 1)
if (!dynamic_cast<RationalNumberType const&>(*types[i]).mobileType())
m_errorReporter.fatalTypeError(components[i]->location(), "Invalid rational number.");
if (_tuple.isInlineArray())
solAssert(!!types[i], "Inline array cannot have empty components");
if (_tuple.isInlineArray())
@ -1497,7 +1538,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
/* If no mobile type is available an error will be raised elsewhere. */
if (literal->mobileType())
m_errorReporter.warning(
_functionCall.location(),
arguments[i]->location(),
"The type of \"" +
argType->toString() +
"\" was inferred as " +
@ -1954,7 +1995,7 @@ void TypeChecker::endVisit(Literal const& _literal)
if (_literal.looksLikeAddress())
{
if (_literal.passesAddressChecksum())
_literal.annotation().type = make_shared<IntegerType>(0, IntegerType::Modifier::Address);
_literal.annotation().type = make_shared<IntegerType>(160, IntegerType::Modifier::Address);
else
m_errorReporter.warning(
_literal.location(),

View File

@ -61,6 +61,7 @@ private:
/// Checks that two functions defined in this contract with the same name have different
/// arguments and that there is at most one constructor.
void checkContractDuplicateFunctions(ContractDefinition const& _contract);
void checkContractDuplicateEvents(ContractDefinition const& _contract);
void checkContractIllegalOverrides(ContractDefinition const& _contract);
/// Reports a type error with an appropiate message if overriden function signature differs.
/// Also stores the direct super function in the AST annotations.
@ -108,6 +109,9 @@ private:
virtual void endVisit(ElementaryTypeNameExpression const& _expr) override;
virtual void endVisit(Literal const& _literal) override;
template <class T>
void findDuplicateDefinitions(std::map<std::string, std::vector<T>> const& _definitions, std::string _message);
bool contractDependenciesAreCyclic(
ContractDefinition const& _contract,
std::set<ContractDefinition const*> const& _seenContracts = std::set<ContractDefinition const*>()

View File

@ -22,7 +22,6 @@
#include <libsolidity/ast/AST.h>
#include <libsolidity/ast/ASTVisitor.h>
#include <libsolidity/interface/Exceptions.h>
#include <libsolidity/ast/AST_accept.h>
#include <libdevcore/SHA3.h>
@ -73,11 +72,6 @@ ASTAnnotation& ASTNode::annotation() const
return *m_annotation;
}
Error ASTNode::createTypeError(string const& _description) const
{
return Error(Error::Type::TypeError) << errinfo_sourceLocation(location()) << errinfo_comment(_description);
}
SourceUnitAnnotation& SourceUnit::annotation() const
{
if (!m_annotation)

View File

@ -26,7 +26,6 @@
#include <libsolidity/ast/ASTForward.h>
#include <libsolidity/parsing/Token.h>
#include <libsolidity/ast/Types.h>
#include <libsolidity/interface/Exceptions.h>
#include <libsolidity/ast/ASTAnnotations.h>
#include <libsolidity/ast/ASTEnums.h>
@ -89,10 +88,6 @@ public:
/// Returns the source code location of this node.
SourceLocation const& location() const { return m_location; }
/// Creates a @ref TypeError exception and decorates it with the location of the node and
/// the given description
Error createTypeError(std::string const& _description) const;
///@todo make this const-safe by providing a different way to access the annotation
virtual ASTAnnotation& annotation() const;

View File

@ -57,6 +57,7 @@ class UserDefinedTypeName;
class FunctionTypeName;
class Mapping;
class ArrayTypeName;
class InlineAssembly;
class Statement;
class Block;
class PlaceholderStatement;

View File

@ -89,7 +89,7 @@ pair<u256, unsigned> const* StorageOffsets::offset(size_t _index) const
MemberList& MemberList::operator=(MemberList&& _other)
{
assert(&_other != this);
solAssert(&_other != this, "");
m_memberTypes = move(_other.m_memberTypes);
m_storageOffsets = move(_other.m_storageOffsets);
@ -203,7 +203,7 @@ TypePointer Type::fromElementaryTypeName(ElementaryTypeNameToken const& _type)
case Token::Byte:
return make_shared<FixedBytesType>(1);
case Token::Address:
return make_shared<IntegerType>(0, IntegerType::Modifier::Address);
return make_shared<IntegerType>(160, IntegerType::Modifier::Address);
case Token::Bool:
return make_shared<BoolType>();
case Token::Bytes:
@ -327,11 +327,11 @@ IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier):
m_bits(_bits), m_modifier(_modifier)
{
if (isAddress())
m_bits = 160;
solAssert(m_bits == 160, "");
solAssert(
m_bits > 0 && m_bits <= 256 && m_bits % 8 == 0,
"Invalid bit number for integer type: " + dev::toString(_bits)
);
);
}
string IntegerType::identifier() const
@ -1616,10 +1616,10 @@ string ContractType::canonicalName() const
return m_contract.annotation().canonicalName;
}
MemberList::MemberMap ContractType::nativeMembers(ContractDefinition const*) const
MemberList::MemberMap ContractType::nativeMembers(ContractDefinition const* _contract) const
{
// All address members and all interface functions
MemberList::MemberMap members(IntegerType(120, IntegerType::Modifier::Address).nativeMembers(nullptr));
MemberList::MemberMap members;
solAssert(_contract, "");
if (m_super)
{
// add the most derived of all functions which are visible in derived contracts
@ -1661,9 +1661,47 @@ MemberList::MemberMap ContractType::nativeMembers(ContractDefinition const*) con
&it.second->declaration()
));
}
// In 0.5.0 address members are not populated into the contract.
if (!_contract->sourceUnit().annotation().experimentalFeatures.count(ExperimentalFeature::V050))
addNonConflictingAddressMembers(members);
return members;
}
void ContractType::addNonConflictingAddressMembers(MemberList::MemberMap& _members)
{
MemberList::MemberMap addressMembers = IntegerType(160, IntegerType::Modifier::Address).nativeMembers(nullptr);
for (auto const& addressMember: addressMembers)
{
bool clash = false;
for (auto const& member: _members)
{
if (
member.name == addressMember.name &&
(
// Members with different types are not allowed
member.type->category() != addressMember.type->category() ||
// Members must overload functions without clash
(
member.type->category() == Type::Category::Function &&
dynamic_cast<FunctionType const&>(*member.type).hasEqualArgumentTypes(dynamic_cast<FunctionType const&>(*addressMember.type))
)
)
)
{
clash = true;
break;
}
}
if (!clash)
_members.push_back(MemberList::Member(
addressMember.name,
addressMember.type,
addressMember.declaration
));
}
}
shared_ptr<FunctionType const> const& ContractType::newExpressionType() const
{
if (!m_constructorType)
@ -1987,7 +2025,7 @@ unsigned EnumType::memberValue(ASTString const& _member) const
return index;
++index;
}
BOOST_THROW_EXCEPTION(m_enum.createTypeError("Requested unknown enum value ." + _member));
solAssert(false, "Requested unknown enum value " + _member);
}
bool TupleType::isImplicitlyConvertibleTo(Type const& _other) const
@ -2968,7 +3006,7 @@ MemberList::MemberMap MagicType::nativeMembers(ContractDefinition const*) const
{
case Kind::Block:
return MemberList::MemberMap({
{"coinbase", make_shared<IntegerType>(0, IntegerType::Modifier::Address)},
{"coinbase", make_shared<IntegerType>(160, IntegerType::Modifier::Address)},
{"timestamp", make_shared<IntegerType>(256)},
{"blockhash", make_shared<FunctionType>(strings{"uint"}, strings{"bytes32"}, FunctionType::Kind::BlockHash, false, StateMutability::View)},
{"difficulty", make_shared<IntegerType>(256)},
@ -2977,7 +3015,7 @@ MemberList::MemberMap MagicType::nativeMembers(ContractDefinition const*) const
});
case Kind::Message:
return MemberList::MemberMap({
{"sender", make_shared<IntegerType>(0, IntegerType::Modifier::Address)},
{"sender", make_shared<IntegerType>(160, IntegerType::Modifier::Address)},
{"gas", make_shared<IntegerType>(256)},
{"value", make_shared<IntegerType>(256)},
{"data", make_shared<ArrayType>(DataLocation::CallData)},
@ -2985,7 +3023,7 @@ MemberList::MemberMap MagicType::nativeMembers(ContractDefinition const*) const
});
case Kind::Transaction:
return MemberList::MemberMap({
{"origin", make_shared<IntegerType>(0, IntegerType::Modifier::Address)},
{"origin", make_shared<IntegerType>(160, IntegerType::Modifier::Address)},
{"gasprice", make_shared<IntegerType>(256)}
});
default:

View File

@ -716,6 +716,8 @@ public:
std::vector<std::tuple<VariableDeclaration const*, u256, unsigned>> stateVariables() const;
private:
static void addNonConflictingAddressMembers(MemberList::MemberMap& _members);
ContractDefinition const& m_contract;
/// If true, it is the "super" type of the current contract, i.e. it contains only inherited
/// members.

View File

@ -87,7 +87,7 @@ string ABIFunctions::tupleEncoder(
);
elementTempl("values", valueNames);
elementTempl("pos", to_string(headPos));
elementTempl("abiEncode", abiEncodingFunction(*_givenTypes[i], *_targetTypes[i], _encodeAsLibraryTypes, false));
elementTempl("abiEncode", abiEncodingFunction(*_givenTypes[i], *_targetTypes[i], _encodeAsLibraryTypes, true));
encodeElements += elementTempl.render();
headPos += dynamic ? 0x20 : _targetTypes[i]->calldataEncodedSize();
}
@ -162,7 +162,7 @@ string ABIFunctions::cleanupFunction(Type const& _type, bool _revertOnFailure)
break;
}
case Type::Category::Contract:
templ("body", "cleaned := " + cleanupFunction(IntegerType(0, IntegerType::Modifier::Address)) + "(value)");
templ("body", "cleaned := " + cleanupFunction(IntegerType(160, IntegerType::Modifier::Address)) + "(value)");
break;
case Type::Category::Enum:
{
@ -243,7 +243,7 @@ string ABIFunctions::conversionFunction(Type const& _from, Type const& _to)
toCategory == Type::Category::Integer ||
toCategory == Type::Category::Contract,
"");
IntegerType const addressType(0, IntegerType::Modifier::Address);
IntegerType const addressType(160, IntegerType::Modifier::Address);
IntegerType const& to =
toCategory == Type::Category::Integer ?
dynamic_cast<IntegerType const&>(_to) :
@ -371,7 +371,7 @@ string ABIFunctions::abiEncodingFunction(
Type const& _from,
Type const& _to,
bool _encodeAsLibraryTypes,
bool _compacted
bool _fromStack
)
{
solUnimplementedAssert(
@ -415,7 +415,7 @@ string ABIFunctions::abiEncodingFunction(
dynamic_cast<FunctionType const&>(_from),
to,
_encodeAsLibraryTypes,
_compacted
_fromStack
);
solAssert(_from.sizeOnStack() == 1, "");
@ -487,6 +487,7 @@ string ABIFunctions::abiEncodingFunctionCalldataArray(
// TODO if this is not a byte array, we might just copy byte-by-byte anyway,
// because the encoding is position-independent, but we have to check that.
Whiskers templ(R"(
// <readableTypeNameFrom> -> <readableTypeNameTo>
function <functionName>(start, length, pos) -> end {
<storeLength> // might update pos
<copyFun>(start, pos, length)
@ -495,6 +496,8 @@ string ABIFunctions::abiEncodingFunctionCalldataArray(
)");
templ("storeLength", _to.isDynamicallySized() ? "mstore(pos, length) pos := add(pos, 0x20)" : "");
templ("functionName", functionName);
templ("readableTypeNameFrom", _from.toString(true));
templ("readableTypeNameTo", _to.toString(true));
templ("copyFun", copyToMemoryFunction(true));
templ("roundUpFun", roundUpFunction());
return templ.render();
@ -527,6 +530,7 @@ string ABIFunctions::abiEncodingFunctionSimpleArray(
Whiskers templ(
dynamicBase ?
R"(
// <readableTypeNameFrom> -> <readableTypeNameTo>
function <functionName>(value, pos) <return> {
let length := <lengthFun>(value)
<storeLength> // might update pos
@ -538,13 +542,14 @@ string ABIFunctions::abiEncodingFunctionSimpleArray(
mstore(pos, sub(tail, headStart))
tail := <encodeToMemoryFun>(<arrayElementAccess>, tail)
srcPtr := <nextArrayElement>(srcPtr)
pos := add(pos, <elementEncodedSize>)
pos := add(pos, 0x20)
}
pos := tail
<assignEnd>
}
)" :
R"(
// <readableTypeNameFrom> -> <readableTypeNameTo>
function <functionName>(value, pos) <return> {
let length := <lengthFun>(value)
<storeLength> // might update pos
@ -560,6 +565,8 @@ string ABIFunctions::abiEncodingFunctionSimpleArray(
)"
);
templ("functionName", functionName);
templ("readableTypeNameFrom", _from.toString(true));
templ("readableTypeNameTo", _to.toString(true));
templ("return", dynamic ? " -> end " : "");
templ("assignEnd", dynamic ? "end := pos" : "");
templ("lengthFun", arrayLengthFunction(_from));
@ -573,7 +580,7 @@ string ABIFunctions::abiEncodingFunctionSimpleArray(
*_from.baseType(),
*_to.baseType(),
_encodeAsLibraryTypes,
true
false
));
templ("arrayElementAccess", inMemory ? "mload(srcPtr)" : _from.baseType()->isValueType() ? "sload(srcPtr)" : "srcPtr" );
templ("nextArrayElement", nextArrayElementFunction(_from));
@ -639,6 +646,7 @@ string ABIFunctions::abiEncodingFunctionCompactStorageArray(
{
solAssert(_to.isByteArray(), "");
Whiskers templ(R"(
// <readableTypeNameFrom> -> <readableTypeNameTo>
function <functionName>(value, pos) -> ret {
let slotValue := sload(value)
switch and(slotValue, 1)
@ -665,6 +673,8 @@ string ABIFunctions::abiEncodingFunctionCompactStorageArray(
}
)");
templ("functionName", functionName);
templ("readableTypeNameFrom", _from.toString(true));
templ("readableTypeNameTo", _to.toString(true));
templ("arrayDataSlot", arrayDataAreaFunction(_from));
return templ.render();
}
@ -681,6 +691,7 @@ string ABIFunctions::abiEncodingFunctionCompactStorageArray(
// more than desired, i.e. it writes beyond the end of memory.
Whiskers templ(
R"(
// <readableTypeNameFrom> -> <readableTypeNameTo>
function <functionName>(value, pos) <return> {
let length := <lengthFun>(value)
<storeLength> // might update pos
@ -701,6 +712,8 @@ string ABIFunctions::abiEncodingFunctionCompactStorageArray(
)"
);
templ("functionName", functionName);
templ("readableTypeNameFrom", _from.toString(true));
templ("readableTypeNameTo", _to.toString(true));
templ("return", dynamic ? " -> end " : "");
templ("assignEnd", dynamic ? "end := pos" : "");
templ("lengthFun", arrayLengthFunction(_from));
@ -716,7 +729,7 @@ string ABIFunctions::abiEncodingFunctionCompactStorageArray(
*_from.baseType(),
*_to.baseType(),
_encodeAsLibraryTypes,
true
false
);
templ("encodeToMemoryFun", encodeToMemoryFun);
std::vector<std::map<std::string, std::string>> items(itemsPerSlot);
@ -748,6 +761,7 @@ string ABIFunctions::abiEncodingFunctionStruct(
bool fromStorage = _from.location() == DataLocation::Storage;
bool dynamic = _to.isDynamicallyEncoded();
Whiskers templ(R"(
// <readableTypeNameFrom> -> <readableTypeNameTo>
function <functionName>(value, pos) <return> {
let tail := add(pos, <headSize>)
<init>
@ -761,6 +775,8 @@ string ABIFunctions::abiEncodingFunctionStruct(
}
)");
templ("functionName", functionName);
templ("readableTypeNameFrom", _from.toString(true));
templ("readableTypeNameTo", _to.toString(true));
templ("return", dynamic ? " -> end " : "");
templ("assignEnd", dynamic ? "end := tail" : "");
// to avoid multiple loads from the same slot for subsequent members
@ -909,7 +925,7 @@ string ABIFunctions::abiEncodingFunctionFunctionType(
FunctionType const& _from,
Type const& _to,
bool _encodeAsLibraryTypes,
bool _compacted
bool _fromStack
)
{
solAssert(_from.kind() == FunctionType::Kind::External, "");
@ -920,24 +936,10 @@ string ABIFunctions::abiEncodingFunctionFunctionType(
_from.identifier() +
"_to_" +
_to.identifier() +
(_compacted ? "_compacted" : "") +
(_fromStack ? "_fromStack" : "") +
(_encodeAsLibraryTypes ? "_library" : "");
if (_compacted)
{
return createFunction(functionName, [&]() {
return Whiskers(R"(
function <functionName>(addr_and_function_id, pos) {
mstore(pos, <cleanExtFun>(addr_and_function_id))
}
)")
("functionName", functionName)
("cleanExtFun", cleanupCombinedExternalFunctionIdFunction())
.render();
});
}
else
{
if (_fromStack)
return createFunction(functionName, [&]() {
return Whiskers(R"(
function <functionName>(addr, function_id, pos) {
@ -948,7 +950,17 @@ string ABIFunctions::abiEncodingFunctionFunctionType(
("combineExtFun", combineExternalFunctionIdFunction())
.render();
});
}
else
return createFunction(functionName, [&]() {
return Whiskers(R"(
function <functionName>(addr_and_function_id, pos) {
mstore(pos, <cleanExtFun>(addr_and_function_id))
}
)")
("functionName", functionName)
("cleanExtFun", cleanupCombinedExternalFunctionIdFunction())
.render();
});
}
string ABIFunctions::copyToMemoryFunction(bool _fromCalldata)
@ -995,9 +1007,11 @@ string ABIFunctions::shiftLeftFunction(size_t _numBits)
return createFunction(functionName, [&]() {
solAssert(_numBits < 256, "");
return
Whiskers(R"(function <functionName>(value) -> newValue {
Whiskers(R"(
function <functionName>(value) -> newValue {
newValue := mul(value, <multiplier>)
})")
}
)")
("functionName", functionName)
("multiplier", toCompactHexWithPrefix(u256(1) << _numBits))
.render();
@ -1010,9 +1024,11 @@ string ABIFunctions::shiftRightFunction(size_t _numBits, bool _signed)
return createFunction(functionName, [&]() {
solAssert(_numBits < 256, "");
return
Whiskers(R"(function <functionName>(value) -> newValue {
Whiskers(R"(
function <functionName>(value) -> newValue {
newValue := <div>(value, <multiplier>)
})")
}
)")
("functionName", functionName)
("div", _signed ? "sdiv" : "div")
("multiplier", toCompactHexWithPrefix(u256(1) << _numBits))
@ -1025,9 +1041,11 @@ string ABIFunctions::roundUpFunction()
string functionName = "round_up_to_mul_of_32";
return createFunction(functionName, [&]() {
return
Whiskers(R"(function <functionName>(value) -> result {
Whiskers(R"(
function <functionName>(value) -> result {
result := and(add(value, 31), not(31))
})")
}
)")
("functionName", functionName)
.render();
});
@ -1190,10 +1208,7 @@ size_t ABIFunctions::headSize(TypePointers const& _targetTypes)
if (t->isDynamicallyEncoded())
headSize += 0x20;
else
{
solAssert(t->calldataEncodedSize() > 0, "");
headSize += t->calldataEncodedSize();
}
}
return headSize;

View File

@ -89,13 +89,13 @@ private:
/// @returns the name of the ABI encoding function with the given type
/// and queues the generation of the function to the requested functions.
/// @param _compacted if true, the input value was just loaded from storage
/// @param _fromStack if false, the input value was just loaded from storage
/// or memory and thus might be compacted into a single slot (depending on the type).
std::string abiEncodingFunction(
Type const& _givenType,
Type const& _targetType,
bool _encodeAsLibraryTypes,
bool _compacted
bool _fromStack
);
/// Part of @a abiEncodingFunction for array target type and given calldata array.
std::string abiEncodingFunctionCalldataArray(
@ -143,7 +143,7 @@ private:
FunctionType const& _from,
Type const& _to,
bool _encodeAsLibraryTypes,
bool _compacted
bool _fromStack
);
/// @returns a function that copies raw bytes of dynamic length from calldata

View File

@ -291,8 +291,11 @@ void ArrayUtils::copyArrayToMemory(ArrayType const& _sourceType, bool _padToWord
CompilerUtils utils(m_context);
unsigned baseSize = 1;
if (!_sourceType.isByteArray())
{
// We always pad the elements, regardless of _padToWordBoundaries.
baseSize = _sourceType.baseType()->calldataEncodedSize();
solAssert(baseSize >= 0x20, "");
}
if (_sourceType.location() == DataLocation::CallData)
{

View File

@ -26,6 +26,7 @@
#include <libsolidity/codegen/Compiler.h>
#include <libsolidity/interface/Version.h>
#include <libsolidity/interface/ErrorReporter.h>
#include <libsolidity/interface/SourceReferenceFormatter.h>
#include <libsolidity/parsing/Scanner.h>
#include <libsolidity/inlineasm/AsmParser.h>
#include <libsolidity/inlineasm/AsmCodeGen.h>
@ -37,6 +38,13 @@
#include <utility>
#include <numeric>
// Change to "define" to output all intermediate code
#undef SOL_OUTPUT_ASM
#ifdef SOL_OUTPUT_ASM
#include <libsolidity/inlineasm/AsmPrinter.h>
#endif
using namespace std;
namespace dev
@ -312,12 +320,31 @@ void CompilerContext::appendInlineAssembly(
ErrorReporter errorReporter(errors);
auto scanner = make_shared<Scanner>(CharStream(_assembly), "--CODEGEN--");
auto parserResult = assembly::Parser(errorReporter).parse(scanner);
solAssert(parserResult, "Failed to parse inline assembly block.");
solAssert(errorReporter.errors().empty(), "Failed to parse inline assembly block.");
#ifdef SOL_OUTPUT_ASM
cout << assembly::AsmPrinter()(*parserResult) << endl;
#endif
assembly::AsmAnalysisInfo analysisInfo;
assembly::AsmAnalyzer analyzer(analysisInfo, errorReporter, false, identifierAccess.resolve);
solAssert(analyzer.analyze(*parserResult), "Failed to analyze inline assembly block.");
bool analyzerResult = false;
if (parserResult)
analyzerResult = assembly::AsmAnalyzer(analysisInfo, errorReporter, false, identifierAccess.resolve).analyze(*parserResult);
if (!parserResult || !errorReporter.errors().empty() || !analyzerResult)
{
string message =
"Error parsing/analyzing inline assembly block:\n"
"------------------ Input: -----------------\n" +
_assembly + "\n"
"------------------ Errors: ----------------\n";
for (auto const& error: errorReporter.errors())
message += SourceReferenceFormatter::formatExceptionInformation(
*error,
(error->type() == Error::Type::Warning) ? "Warning" : "Error",
[&](string const&) -> Scanner const& { return *scanner; }
);
message += "-------------------------------------------\n";
solAssert(false, message);
}
solAssert(errorReporter.errors().empty(), "Failed to analyze inline assembly block.");
assembly::CodeGenerator::assemble(*parserResult, analysisInfo, *m_asm, identifierAccess, _system);
}

View File

@ -191,7 +191,7 @@ void CompilerUtils::encodeToMemory(
{
// Use the new JULIA-based encoding function
auto stackHeightBefore = m_context.stackHeight();
abiEncode(_givenTypes, targetTypes, _encodeAsLibraryTypes);
abiEncodeV2(_givenTypes, targetTypes, _encodeAsLibraryTypes);
solAssert(stackHeightBefore - m_context.stackHeight() == sizeOnStack(_givenTypes), "");
return;
}
@ -302,7 +302,7 @@ void CompilerUtils::encodeToMemory(
popStackSlots(argSize + dynPointers + 1);
}
void CompilerUtils::abiEncode(
void CompilerUtils::abiEncodeV2(
TypePointers const& _givenTypes,
TypePointers const& _targetTypes,
bool _encodeAsLibraryTypes
@ -541,7 +541,7 @@ void CompilerUtils::convertType(
else
{
solAssert(targetTypeCategory == Type::Category::Integer || targetTypeCategory == Type::Category::Contract, "");
IntegerType addressType(0, IntegerType::Modifier::Address);
IntegerType addressType(160, IntegerType::Modifier::Address);
IntegerType const& targetType = targetTypeCategory == Type::Category::Integer
? dynamic_cast<IntegerType const&>(_targetType) : addressType;
if (stackTypeCategory == Type::Category::RationalNumber)
@ -596,7 +596,6 @@ void CompilerUtils::convertType(
storeInMemoryDynamic(IntegerType(256));
// stack: mempos datapos
storeStringData(data);
break;
}
else
solAssert(
@ -810,9 +809,8 @@ void CompilerUtils::convertType(
if (_cleanupNeeded)
m_context << Instruction::ISZERO << Instruction::ISZERO;
break;
case Type::Category::Function:
{
if (targetTypeCategory == Type::Category::Integer)
default:
if (stackTypeCategory == Type::Category::Function && targetTypeCategory == Type::Category::Integer)
{
IntegerType const& targetType = dynamic_cast<IntegerType const&>(_targetType);
solAssert(targetType.isAddress(), "Function type can only be converted to address.");
@ -821,17 +819,16 @@ void CompilerUtils::convertType(
// stack: <address> <function_id>
m_context << Instruction::POP;
break;
}
}
// fall-through
default:
// All other types should not be convertible to non-equal types.
solAssert(_typeOnStack == _targetType, "Invalid type conversion requested.");
if (_cleanupNeeded && _targetType.canBeStored() && _targetType.storageBytes() < 32)
else
{
// All other types should not be convertible to non-equal types.
solAssert(_typeOnStack == _targetType, "Invalid type conversion requested.");
if (_cleanupNeeded && _targetType.canBeStored() && _targetType.storageBytes() < 32)
m_context
<< ((u256(1) << (8 * _targetType.storageBytes())) - 1)
<< Instruction::AND;
}
break;
}

View File

@ -102,13 +102,26 @@ public:
/// @note the locations of target reference types are ignored, because it will always be
/// memory.
void encodeToMemory(
TypePointers const& _givenTypes = {},
TypePointers const& _targetTypes = {},
bool _padToWords = true,
bool _copyDynamicDataInPlace = false,
TypePointers const& _givenTypes,
TypePointers const& _targetTypes,
bool _padToWords,
bool _copyDynamicDataInPlace,
bool _encodeAsLibraryTypes = false
);
/// Special case of @a encodeToMemory which assumes tight packing, e.g. no zero padding
/// and dynamic data is encoded in-place.
/// Stack pre: <value0> <value1> ... <valueN-1> <head_start>
/// Stack post: <mem_ptr>
void packedEncode(
TypePointers const& _givenTypes,
TypePointers const& _targetTypes,
bool _encodeAsLibraryTypes = false
)
{
encodeToMemory(_givenTypes, _targetTypes, false, true, _encodeAsLibraryTypes);
}
/// Special case of @a encodeToMemory which assumes that everything is padded to words
/// and dynamic data is not copied in place (i.e. a proper ABI encoding).
/// Stack pre: <value0> <value1> ... <valueN-1> <head_start>
@ -117,6 +130,20 @@ public:
TypePointers const& _givenTypes,
TypePointers const& _targetTypes,
bool _encodeAsLibraryTypes = false
)
{
encodeToMemory(_givenTypes, _targetTypes, true, false, _encodeAsLibraryTypes);
}
/// Special case of @a encodeToMemory which assumes that everything is padded to words
/// and dynamic data is not copied in place (i.e. a proper ABI encoding).
/// Uses a new, less tested encoder implementation.
/// Stack pre: <value0> <value1> ... <valueN-1> <head_start>
/// Stack post: <mem_ptr>
void abiEncodeV2(
TypePointers const& _givenTypes,
TypePointers const& _targetTypes,
bool _encodeAsLibraryTypes = false
);
/// Zero-initialises (the data part of) an already allocated memory array.

View File

@ -251,13 +251,10 @@ void ContractCompiler::appendFunctionSelector(ContractDefinition const& _contrac
FunctionDefinition const* fallback = _contract.fallbackFunction();
eth::AssemblyItem notFound = m_context.newTag();
// shortcut messages without data if we have many functions in order to be able to receive
// ether with constant gas
if (interfaceFunctions.size() > 5 || fallback)
{
m_context << Instruction::CALLDATASIZE << Instruction::ISZERO;
m_context.appendConditionalJumpTo(notFound);
}
// directly jump to fallback if the data is too short to contain a function selector
// also guards against short data
m_context << u256(4) << Instruction::CALLDATASIZE << Instruction::LT;
m_context.appendConditionalJumpTo(notFound);
// retrieve the function signature hash from the calldata
if (!interfaceFunctions.empty())
@ -421,7 +418,7 @@ void ContractCompiler::appendReturnValuePacker(TypePointers const& _typeParamete
utils.fetchFreeMemoryPointer();
//@todo optimization: if we return a single memory array, there should be enough space before
// its data to add the needed parts and we avoid a memory copy.
utils.encodeToMemory(_typeParameters, _typeParameters, true, false, _isLibrary);
utils.abiEncode(_typeParameters, _typeParameters, _isLibrary);
utils.toSizeAfterFreeMemoryPointer();
m_context << Instruction::RETURN;
}

View File

@ -581,7 +581,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
_context << Instruction::ADD;
}
);
utils().encodeToMemory(argumentTypes, function.parameterTypes());
utils().abiEncode(argumentTypes, function.parameterTypes());
// now on stack: memory_end_ptr
// need: size, offset, endowment
utils().toSizeAfterFreeMemoryPointer();
@ -675,7 +675,8 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
argumentTypes.push_back(arg->annotation().type);
}
utils().fetchFreeMemoryPointer();
utils().encodeToMemory(argumentTypes, TypePointers(), function.padArguments(), true);
solAssert(!function.padArguments(), "");
utils().packedEncode(argumentTypes, TypePointers());
utils().toSizeAfterFreeMemoryPointer();
m_context << Instruction::KECCAK256;
break;
@ -694,11 +695,10 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
}
arguments.front()->accept(*this);
utils().fetchFreeMemoryPointer();
utils().encodeToMemory(
utils().packedEncode(
{arguments.front()->annotation().type},
{function.parameterTypes().front()},
false,
true);
{function.parameterTypes().front()}
);
utils().toSizeAfterFreeMemoryPointer();
m_context << logInstruction(logNumber);
break;
@ -717,11 +717,9 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
if (auto const& arrayType = dynamic_pointer_cast<ArrayType const>(function.parameterTypes()[arg - 1]))
{
utils().fetchFreeMemoryPointer();
utils().encodeToMemory(
utils().packedEncode(
{arguments[arg - 1]->annotation().type},
{arrayType},
false,
true
{arrayType}
);
utils().toSizeAfterFreeMemoryPointer();
m_context << Instruction::KECCAK256;
@ -751,7 +749,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
nonIndexedParamTypes.push_back(function.parameterTypes()[arg]);
}
utils().fetchFreeMemoryPointer();
utils().encodeToMemory(nonIndexedArgTypes, nonIndexedParamTypes);
utils().abiEncode(nonIndexedArgTypes, nonIndexedParamTypes);
// need: topic1 ... topicn memsize memstart
utils().toSizeAfterFreeMemoryPointer();
m_context << logInstruction(numIndexed);
@ -860,8 +858,15 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
m_context << Instruction::DUP1 << Instruction::DUP3 << Instruction::MSTORE;
// Stack: memptr requested_length
// update free memory pointer
m_context << Instruction::DUP1 << arrayType.baseType()->memoryHeadSize();
m_context << Instruction::MUL << u256(32) << Instruction::ADD;
m_context << Instruction::DUP1;
// Stack: memptr requested_length requested_length
if (arrayType.isByteArray())
// Round up to multiple of 32
m_context << u256(31) << Instruction::ADD << u256(31) << Instruction::NOT << Instruction::AND;
else
m_context << arrayType.baseType()->memoryHeadSize() << Instruction::MUL;
// stacK: memptr requested_length data_size
m_context << u256(32) << Instruction::ADD;
m_context << Instruction::DUP3 << Instruction::ADD;
utils().storeFreeMemoryPointer();
// Stack: memptr requested_length
@ -1014,59 +1019,65 @@ bool ExpressionCompiler::visit(MemberAccess const& _memberAccess)
switch (_memberAccess.expression().annotation().type->category())
{
case Type::Category::Contract:
case Type::Category::Integer:
{
bool alsoSearchInteger = false;
ContractType const& type = dynamic_cast<ContractType const&>(*_memberAccess.expression().annotation().type);
if (type.isSuper())
if (_memberAccess.expression().annotation().type->category() == Type::Category::Contract)
{
solAssert(!!_memberAccess.annotation().referencedDeclaration, "Referenced declaration not resolved.");
utils().pushCombinedFunctionEntryLabel(m_context.superFunction(
dynamic_cast<FunctionDefinition const&>(*_memberAccess.annotation().referencedDeclaration),
type.contractDefinition()
));
}
else
{
// ordinary contract type
if (Declaration const* declaration = _memberAccess.annotation().referencedDeclaration)
ContractType const& type = dynamic_cast<ContractType const&>(*_memberAccess.expression().annotation().type);
if (type.isSuper())
{
u256 identifier;
if (auto const* variable = dynamic_cast<VariableDeclaration const*>(declaration))
identifier = FunctionType(*variable).externalIdentifier();
else if (auto const* function = dynamic_cast<FunctionDefinition const*>(declaration))
identifier = FunctionType(*function).externalIdentifier();
else
solAssert(false, "Contract member is neither variable nor function.");
utils().convertType(type, IntegerType(0, IntegerType::Modifier::Address), true);
m_context << identifier;
solAssert(!!_memberAccess.annotation().referencedDeclaration, "Referenced declaration not resolved.");
utils().pushCombinedFunctionEntryLabel(m_context.superFunction(
dynamic_cast<FunctionDefinition const&>(*_memberAccess.annotation().referencedDeclaration),
type.contractDefinition()
));
}
else
// not found in contract, search in members inherited from address
alsoSearchInteger = true;
{
// ordinary contract type
if (Declaration const* declaration = _memberAccess.annotation().referencedDeclaration)
{
u256 identifier;
if (auto const* variable = dynamic_cast<VariableDeclaration const*>(declaration))
identifier = FunctionType(*variable).externalIdentifier();
else if (auto const* function = dynamic_cast<FunctionDefinition const*>(declaration))
identifier = FunctionType(*function).externalIdentifier();
else
solAssert(false, "Contract member is neither variable nor function.");
utils().convertType(type, IntegerType(160, IntegerType::Modifier::Address), true);
m_context << identifier;
}
else
// not found in contract, search in members inherited from address
alsoSearchInteger = true;
}
}
if (!alsoSearchInteger)
break;
}
// fall-through
case Type::Category::Integer:
if (member == "balance")
{
utils().convertType(
*_memberAccess.expression().annotation().type,
IntegerType(0, IntegerType::Modifier::Address),
true
);
m_context << Instruction::BALANCE;
}
else if ((set<string>{"send", "transfer", "call", "callcode", "delegatecall"}).count(member))
utils().convertType(
*_memberAccess.expression().annotation().type,
IntegerType(0, IntegerType::Modifier::Address),
true
);
else
solAssert(false, "Invalid member access to integer");
alsoSearchInteger = true;
if (alsoSearchInteger)
{
if (member == "balance")
{
utils().convertType(
*_memberAccess.expression().annotation().type,
IntegerType(160, IntegerType::Modifier::Address),
true
);
m_context << Instruction::BALANCE;
}
else if ((set<string>{"send", "transfer", "call", "callcode", "delegatecall"}).count(member))
utils().convertType(
*_memberAccess.expression().annotation().type,
IntegerType(160, IntegerType::Modifier::Address),
true
);
else
solAssert(false, "Invalid member access to integer");
}
break;
}
case Type::Category::Function:
if (member == "selector")
{
@ -1206,11 +1217,9 @@ bool ExpressionCompiler::visit(IndexAccess const& _indexAccess)
utils().fetchFreeMemoryPointer();
// stack: base index mem
// note: the following operations must not allocate memory!
utils().encodeToMemory(
utils().packedEncode(
TypePointers{_indexAccess.indexExpression()->annotation().type},
TypePointers{keyType},
false,
true
TypePointers{keyType}
);
m_context << Instruction::SWAP1;
utils().storeInMemoryDynamic(IntegerType(256));
@ -1712,6 +1721,9 @@ void ExpressionCompiler::appendExternalFunctionCall(
if (_functionType.gasSet())
m_context << dupInstruction(m_context.baseToCurrentStackOffset(gasStackPos));
else if (m_context.experimentalFeatureActive(ExperimentalFeature::V050))
// Send all gas (requires tangerine whistle EVM)
m_context << Instruction::GAS;
else
{
// send all gas except the amount needed to execute "SUB" and "CALL"

View File

@ -234,6 +234,16 @@ void SMTChecker::endVisit(BinaryOperation const& _op)
void SMTChecker::endVisit(FunctionCall const& _funCall)
{
solAssert(_funCall.annotation().kind != FunctionCallKind::Unset, "");
if (_funCall.annotation().kind != FunctionCallKind::FunctionCall)
{
m_errorReporter.warning(
_funCall.location(),
"Assertion checker does not yet implement this expression."
);
return;
}
FunctionType const& funType = dynamic_cast<FunctionType const&>(*_funCall.expression().annotation().type);
std::vector<ASTPointer<Expression const>> const args = _funCall.arguments();
@ -484,10 +494,10 @@ void SMTChecker::createVariable(VariableDeclaration const& _varDecl, bool _setTo
{
solAssert(m_currentSequenceCounter.count(&_varDecl) == 0, "");
solAssert(m_nextFreeSequenceCounter.count(&_varDecl) == 0, "");
solAssert(m_Variables.count(&_varDecl) == 0, "");
solAssert(m_variables.count(&_varDecl) == 0, "");
m_currentSequenceCounter[&_varDecl] = 0;
m_nextFreeSequenceCounter[&_varDecl] = 1;
m_Variables.emplace(&_varDecl, m_interface->newFunction(uniqueSymbol(_varDecl), smt::Sort::Int, smt::Sort::Int));
m_variables.emplace(&_varDecl, m_interface->newFunction(uniqueSymbol(_varDecl), smt::Sort::Int, smt::Sort::Int));
setValue(_varDecl, _setToZero);
}
else
@ -556,7 +566,7 @@ smt::Expression SMTChecker::maxValue(IntegerType const& _t)
smt::Expression SMTChecker::expr(Expression const& _e)
{
if (!m_Expressions.count(&_e))
if (!m_expressions.count(&_e))
{
solAssert(_e.annotation().type, "");
switch (_e.annotation().type->category())
@ -565,24 +575,24 @@ smt::Expression SMTChecker::expr(Expression const& _e)
{
if (RationalNumberType const* rational = dynamic_cast<RationalNumberType const*>(_e.annotation().type.get()))
solAssert(!rational->isFractional(), "");
m_Expressions.emplace(&_e, m_interface->newInteger(uniqueSymbol(_e)));
m_expressions.emplace(&_e, m_interface->newInteger(uniqueSymbol(_e)));
break;
}
case Type::Category::Integer:
m_Expressions.emplace(&_e, m_interface->newInteger(uniqueSymbol(_e)));
m_expressions.emplace(&_e, m_interface->newInteger(uniqueSymbol(_e)));
break;
case Type::Category::Bool:
m_Expressions.emplace(&_e, m_interface->newBool(uniqueSymbol(_e)));
m_expressions.emplace(&_e, m_interface->newBool(uniqueSymbol(_e)));
break;
default:
solAssert(false, "Type not implemented.");
}
}
return m_Expressions.at(&_e);
return m_expressions.at(&_e);
}
smt::Expression SMTChecker::var(Declaration const& _decl)
{
solAssert(m_Variables.count(&_decl), "");
return m_Variables.at(&_decl);
solAssert(m_variables.count(&_decl), "");
return m_variables.at(&_decl);
}

View File

@ -103,8 +103,8 @@ private:
std::shared_ptr<smt::SolverInterface> m_interface;
std::map<Declaration const*, int> m_currentSequenceCounter;
std::map<Declaration const*, int> m_nextFreeSequenceCounter;
std::map<Expression const*, smt::Expression> m_Expressions;
std::map<Declaration const*, smt::Expression> m_Variables;
std::map<Expression const*, smt::Expression> m_expressions;
std::map<Declaration const*, smt::Expression> m_variables;
ErrorReporter& m_errorReporter;
FunctionDefinition const* m_currentFunction = nullptr;

View File

@ -72,36 +72,38 @@ void Z3Interface::addAssertion(Expression const& _expr)
pair<CheckResult, vector<string>> Z3Interface::check(vector<Expression> const& _expressionsToEvaluate)
{
// cout << "---------------------------------" << endl;
// cout << m_solver << endl;
CheckResult result;
switch (m_solver.check())
{
case z3::check_result::sat:
result = CheckResult::SATISFIABLE;
cout << "sat" << endl;
break;
case z3::check_result::unsat:
result = CheckResult::UNSATISFIABLE;
cout << "unsat" << endl;
break;
case z3::check_result::unknown:
result = CheckResult::UNKNOWN;
cout << "unknown" << endl;
break;
default:
solAssert(false, "");
}
// cout << "---------------------------------" << endl;
vector<string> values;
if (result != CheckResult::UNSATISFIABLE)
try
{
z3::model m = m_solver.get_model();
for (Expression const& e: _expressionsToEvaluate)
values.push_back(toString(m.eval(toZ3Expr(e))));
switch (m_solver.check())
{
case z3::check_result::sat:
result = CheckResult::SATISFIABLE;
break;
case z3::check_result::unsat:
result = CheckResult::UNSATISFIABLE;
break;
case z3::check_result::unknown:
result = CheckResult::UNKNOWN;
break;
default:
solAssert(false, "");
}
if (result != CheckResult::UNSATISFIABLE)
{
z3::model m = m_solver.get_model();
for (Expression const& e: _expressionsToEvaluate)
values.push_back(toString(m.eval(toZ3Expr(e))));
}
}
catch (z3::exception const& _e)
{
result = CheckResult::ERROR;
values.clear();
}
return make_pair(result, values);
}
@ -125,8 +127,7 @@ z3::expr Z3Interface::toZ3Expr(Expression const& _expr)
{">=", 2},
{"+", 2},
{"-", 2},
{"*", 2},
{">=", 2}
{"*", 2}
};
string const& n = _expr.name;
if (m_functions.count(n))
@ -142,7 +143,7 @@ z3::expr Z3Interface::toZ3Expr(Expression const& _expr)
return m_context.int_val(n.c_str());
}
assert(arity.count(n) && arity.at(n) == arguments.size());
solAssert(arity.count(n) && arity.at(n) == arguments.size(), "");
if (n == "ite")
return z3::ite(arguments[0], arguments[1], arguments[2]);
else if (n == "not")

View File

@ -256,7 +256,7 @@ std::map<string, dev::solidity::Instruction> const& Parser::instructions()
{
if (
instruction.second == solidity::Instruction::JUMPDEST ||
(solidity::Instruction::PUSH1 <= instruction.second && instruction.second <= solidity::Instruction::PUSH32)
solidity::isPushInstruction(instruction.second)
)
continue;
string name = instruction.first;
@ -443,9 +443,9 @@ assembly::Statement Parser::parseCall(assembly::Statement&& _instruction)
ret.location = ret.instruction.location;
solidity::Instruction instr = ret.instruction.instruction;
InstructionInfo instrInfo = instructionInfo(instr);
if (solidity::Instruction::DUP1 <= instr && instr <= solidity::Instruction::DUP16)
if (solidity::isDupInstruction(instr))
fatalParserError("DUPi instructions not allowed for functional notation");
if (solidity::Instruction::SWAP1 <= instr && instr <= solidity::Instruction::SWAP16)
if (solidity::isSwapInstruction(instr))
fatalParserError("SWAPi instructions not allowed for functional notation");
expectToken(Token::LParen);
unsigned args = unsigned(instrInfo.args);

View File

@ -252,6 +252,14 @@ bool CompilerStack::parseAndAnalyze()
return parse() && analyze();
}
bool CompilerStack::isRequestedContract(ContractDefinition const& _contract) const
{
return
m_requestedContractNames.empty() ||
m_requestedContractNames.count(_contract.fullyQualifiedName()) ||
m_requestedContractNames.count(_contract.name());
}
bool CompilerStack::compile()
{
if (m_stackState < AnalysisSuccessful)
@ -262,7 +270,8 @@ bool CompilerStack::compile()
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->nodes())
if (auto contract = dynamic_cast<ContractDefinition const*>(node.get()))
compileContract(*contract, compiledContracts);
if (isRequestedContract(*contract))
compileContract(*contract, compiledContracts);
this->link();
m_stackState = CompilationSuccessful;
return true;

View File

@ -116,6 +116,13 @@ public:
m_optimizeRuns = _runs;
}
/// Sets the list of requested contract names. If empty, no filtering is performed and every contract
/// found in the supplied sources is compiled. Names are cleared iff @a _contractNames is missing.
void setRequestedContractNames(std::set<std::string> const& _contractNames = std::set<std::string>{})
{
m_requestedContractNames = _contractNames;
}
/// @arg _metadataLiteralSources When true, store sources as literals in the contract metadata.
void useMetadataLiteralSources(bool _metadataLiteralSources) { m_metadataLiteralSources = _metadataLiteralSources; }
@ -259,6 +266,9 @@ private:
/// Helper function to return path converted strings.
std::string sanitizePath(std::string const& _path) const { return boost::filesystem::path(_path).generic_string(); }
/// @returns true if the contract is requested to be compiled.
bool isRequestedContract(ContractDefinition const& _contract) const;
/// Compile a single contract and put the result in @a _compiledContracts.
void compileContract(
ContractDefinition const& _contract,
@ -297,6 +307,7 @@ private:
ReadCallback::Callback m_smtQuery;
bool m_optimize = false;
unsigned m_optimizeRuns = 200;
std::set<std::string> m_requestedContractNames;
std::map<std::string, h160> m_libraries;
/// list of path prefix remappings, e.g. mylibrary: github.com/ethereum = /usr/local/ethereum
/// "context:prefix=target"

View File

@ -48,7 +48,7 @@ GasEstimator::ASTGasConsumptionSelfAccumulated GasEstimator::structuralEstimatio
ControlFlowGraph cfg(_items);
for (BasicBlock const& block: cfg.optimisedBlocks())
{
assertThrow(!!block.startState, OptimizerException, "");
solAssert(!!block.startState, "");
GasMeter meter(block.startState->copy());
auto const end = _items.begin() + block.end;
for (auto iter = _items.begin() + block.begin; iter != end; ++iter)

View File

@ -92,6 +92,22 @@ Json::Value formatErrorWithException(
return formatError(_warning, _type, _component, message, formattedMessage, location);
}
set<string> requestedContractNames(Json::Value const& _outputSelection)
{
set<string> names;
for (auto const& sourceName: _outputSelection.getMemberNames())
{
for (auto const& contractName: _outputSelection[sourceName].getMemberNames())
{
/// Consider the "all sources" shortcuts as requesting everything.
if (contractName == "*" || contractName == "")
return set<string>();
names.insert((sourceName == "*" ? "" : sourceName) + ":" + contractName);
}
}
return names;
}
/// Returns true iff @a _hash (hex with 0x prefix) is the Keccak256 hash of the binary data in @a _content.
bool hashMatchesContent(string const& _hash, string const& _content)
{
@ -265,6 +281,9 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input)
Json::Value metadataSettings = settings.get("metadata", Json::Value());
m_compilerStack.useMetadataLiteralSources(metadataSettings.get("useLiteralContent", Json::Value(false)).asBool());
Json::Value outputSelection = settings.get("outputSelection", Json::Value());
m_compilerStack.setRequestedContractNames(requestedContractNames(outputSelection));
auto scannerFromSourceName = [&](string const& _sourceName) -> solidity::Scanner const& { return m_compilerStack.scanner(_sourceName); };
try

View File

@ -828,6 +828,8 @@ ASTPointer<ParameterList> Parser::parseParameterList(
parameters.push_back(parseVariableDeclaration(options));
while (m_scanner->currentToken() != Token::RParen)
{
if (m_scanner->currentToken() == Token::Comma && m_scanner->peekNextToken() == Token::RParen)
fatalParserError("Unexpected trailing comma in parameter list.");
expectToken(Token::Comma);
parameters.push_back(parseVariableDeclaration(options));
}
@ -1131,6 +1133,7 @@ ASTPointer<VariableDeclarationStatement> Parser::parseVariableDeclarationStateme
options.allowVar = true;
options.allowLocationSpecifier = true;
variables.push_back(parseVariableDeclaration(options, _lookAheadArrayType));
nodeFactory.setEndPositionFromNode(variables.back());
}
if (m_scanner->currentToken() == Token::Assign)
{

View File

@ -138,7 +138,7 @@ int main(int argc, char** argv)
}
else if (mode == Binary || mode == Hex)
{
auto bs = compileLLL(src, optimise ? true : false, &errors);
auto bs = compileLLL(src, optimise ? true : false, &errors, contentsString);
if (mode == Hex)
cout << toHex(bs) << endl;
else if (mode == Binary)
@ -147,7 +147,7 @@ int main(int argc, char** argv)
else if (mode == ParseTree)
cout << parseLLL(src) << endl;
else if (mode == Assembly)
cout << compileLLLToAsm(src, optimise ? true : false, &errors) << endl;
cout << compileLLLToAsm(src, optimise ? true : false, &errors, contentsString) << endl;
for (auto const& i: errors)
cerr << i << endl;
if ( errors.size() )

View File

@ -231,6 +231,7 @@ case $(uname -s) in
autoconf \
automake \
boost-devel \
boost-static \
cmake \
gcc \
gcc-c++ \
@ -256,15 +257,6 @@ case $(uname -s) in
#------------------------------------------------------------------------------
# Ubuntu
#
# TODO - I wonder whether all of the Ubuntu-variants need some special
# treatment?
#
# TODO - We should also test this code on Ubuntu Server, Ubuntu Snappy Core
# and Ubuntu Phone.
#
# TODO - Our Ubuntu build is only working for amd64 and i386 processors.
# It would be good to add armel, armhf and arm64.
# See https://github.com/ethereum/webthree-umbrella/issues/228.
#------------------------------------------------------------------------------
Ubuntu)
@ -320,6 +312,14 @@ case $(uname -s) in
libboost-all-dev \
"$install_z3"
if [ "$CI" = true ]; then
# install Z3 from PPA if the distribution does not provide it
if ! dpkg -l libz3-dev > /dev/null 2>&1
then
sudo apt-add-repository -y ppa:hvr/z3
sudo apt-get -y update
sudo apt-get -y install libz3-dev
fi
# Install 'eth', for use in the Solidity Tests-over-IPC.
# We will not use this 'eth', but its dependencies
sudo add-apt-repository -y ppa:ethereum/ethereum

View File

@ -36,6 +36,10 @@ DIR=$(mktemp -d)
echo "Preparing solc-js..."
git clone --depth 1 https://github.com/ethereum/solc-js "$DIR"
cd "$DIR"
# disable "prepublish" script which downloads the latest version
# (we will replace it anyway and it is often incorrectly cached
# on travis)
npm config set script.prepublish ''
npm install
# Replace soljson with current build

View File

@ -42,8 +42,9 @@ elif [ -z $CI ]; then
ETH_PATH="eth"
else
mkdir -p /tmp/test
wget -O /tmp/test/eth https://github.com/ethereum/cpp-ethereum/releases/download/solidityTester/eth
test "$(shasum /tmp/test/eth)" = "c132e8989229e4840831a4fb1a1d058b732a11d5 /tmp/test/eth"
# Update hash below if binary is changed.
wget -q -O /tmp/test/eth https://github.com/ethereum/cpp-ethereum/releases/download/solidityTester/eth_byzantium2
test "$(shasum /tmp/test/eth)" = "4dc3f208475f622be7c8e53bee720e14cd254c6f /tmp/test/eth"
sync
chmod +x /tmp/test/eth
sync # Otherwise we might get a "text file busy" error

View File

@ -716,8 +716,17 @@ bool CommandLineInterface::processInput()
if (m_args.count(g_argAllowPaths))
{
vector<string> paths;
for (string const& path: boost::split(paths, m_args[g_argAllowPaths].as<string>(), boost::is_any_of(",")))
m_allowedDirectories.push_back(boost::filesystem::path(path));
for (string const& path: boost::split(paths, m_args[g_argAllowPaths].as<string>(), boost::is_any_of(","))) {
auto filesystem_path = boost::filesystem::path(path);
// If the given path had a trailing slash, the Boost filesystem
// path will have it's last component set to '.'. This breaks
// path comparison in later parts of the code, so we need to strip
// it.
if (filesystem_path.filename() == ".") {
filesystem_path.remove_filename();
}
m_allowedDirectories.push_back(filesystem_path);
}
}
if (m_args.count(g_argStandardJSON))

View File

@ -25,6 +25,8 @@
#include <libdevcore/CommonIO.h>
#include <test/ExecutionFramework.h>
#include <boost/algorithm/string/replace.hpp>
using namespace std;
using namespace dev;
using namespace dev::test;
@ -54,6 +56,32 @@ ExecutionFramework::ExecutionFramework() :
m_rpc.test_rewindToBlock(0);
}
std::pair<bool, string> ExecutionFramework::compareAndCreateMessage(
bytes const& _result,
bytes const& _expectation
)
{
if (_result == _expectation)
return std::make_pair(true, std::string{});
std::string message =
"Invalid encoded data\n"
" Result Expectation\n";
auto resultHex = boost::replace_all_copy(toHex(_result), "0", ".");
auto expectedHex = boost::replace_all_copy(toHex(_expectation), "0", ".");
for (size_t i = 0; i < std::max(resultHex.size(), expectedHex.size()); i += 0x40)
{
std::string result{i >= resultHex.size() ? string{} : resultHex.substr(i, 0x40)};
std::string expected{i > expectedHex.size() ? string{} : expectedHex.substr(i, 0x40)};
message +=
(result == expected ? " " : " X ") +
result +
std::string(0x41 - result.size(), ' ') +
expected +
"\n";
}
return make_pair(false, message);
}
void ExecutionFramework::sendMessage(bytes const& _data, bool _isCreation, u256 const& _value)
{
if (m_showMessages)

View File

@ -131,6 +131,8 @@ public:
}
}
static std::pair<bool, std::string> compareAndCreateMessage(bytes const& _result, bytes const& _expectation);
static bytes encode(bool _value) { return encode(byte(_value)); }
static bytes encode(int _value) { return encode(u256(_value)); }
static bytes encode(size_t _value) { return encode(u256(_value)); }
@ -293,6 +295,12 @@ protected:
u256 m_gasUsed;
};
#define ABI_CHECK(result, expectation) do { \
auto abiCheckResult = ExecutionFramework::compareAndCreateMessage((result), (expectation)); \
BOOST_CHECK_MESSAGE(abiCheckResult.first, abiCheckResult.second); \
} while (0)
}
} // end namespaces

View File

@ -217,11 +217,11 @@ void RPCSession::test_setChainParams(vector<string> const& _accounts)
{
"sealEngine": "NoProof",
"params": {
"accountStartNonce": "0x",
"accountStartNonce": "0x00",
"maximumExtraDataSize": "0x1000000",
"blockReward": "0x",
"allowFutureBlocks": "1",
"homsteadForkBlock": "0x00",
"allowFutureBlocks": true,
"homesteadForkBlock": "0x00",
"EIP150ForkBlock": "0x00",
"EIP158ForkBlock": "0x00"
},
@ -236,7 +236,10 @@ void RPCSession::test_setChainParams(vector<string> const& _accounts)
"0000000000000000000000000000000000000001": { "wei": "1", "precompiled": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "wei": "1", "precompiled": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "wei": "1", "precompiled": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "wei": "1", "precompiled": { "name": "identity", "linear": { "base": 15, "word": 3 } } }
"0000000000000000000000000000000000000004": { "wei": "1", "precompiled": { "name": "identity", "linear": { "base": 15, "word": 3 } } },
"0000000000000000000000000000000000000006": { "wei": "1", "precompiled": { "name": "alt_bn128_G1_add", "linear": { "base": 15, "word": 3 } } },
"0000000000000000000000000000000000000007": { "wei": "1", "precompiled": { "name": "alt_bn128_G1_mul", "linear": { "base": 15, "word": 3 } } },
"0000000000000000000000000000000000000008": { "wei": "1", "precompiled": { "name": "alt_bn128_pairing_product", "linear": { "base": 15, "word": 3 } } }
}
}
)";

View File

@ -45,6 +45,8 @@ Options::Options()
showMessages = true;
else if (string(suite.argv[i]) == "--no-ipc")
disableIPC = true;
else if (string(suite.argv[i]) == "--no-smt")
disableSMT = true;
if (!disableIPC && ipcPath.empty())
if (auto path = getenv("ETH_TEST_IPC"))

View File

@ -15,8 +15,6 @@
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TestHelper.h
* @author Marko Simovic <markobarko@gmail.com>
* @date 2014
*/
#pragma once
@ -31,84 +29,13 @@ namespace dev
namespace test
{
#if (BOOST_VERSION >= 105900)
#define ETH_BOOST_CHECK_IMPL(_message, _requireOrCheck) BOOST_TEST_TOOL_DIRECT_IMPL( \
false, \
_requireOrCheck, \
_message \
)
#else
#define ETH_BOOST_CHECK_IMPL(_message, _requireOrCheck) BOOST_CHECK_IMPL( \
false, \
_message, \
_requireOrCheck, \
CHECK_MSG \
)
#endif
/// Make sure that no Exception is thrown during testing. If one is thrown show its info and fail the test.
/// Our version of BOOST_REQUIRE_NO_THROW()
/// @param _statement The statement for which to make sure no exceptions are thrown
/// @param _message A message to act as a prefix to the expression's error information
#define ETH_TEST_REQUIRE_NO_THROW(_statement, _message) \
do \
{ \
try \
{ \
BOOST_TEST_PASSPOINT(); \
_statement; \
} \
catch (boost::exception const& _e) \
{ \
auto msg = std::string(_message " due to an exception thrown by " \
BOOST_STRINGIZE(_statement) "\n") + boost::diagnostic_information(_e); \
ETH_BOOST_CHECK_IMPL(msg, REQUIRE); \
} \
catch (...) \
{ \
ETH_BOOST_CHECK_IMPL( \
"Unknown exception thrown by " BOOST_STRINGIZE(_statement), \
REQUIRE \
); \
} \
} \
while (0)
/// Check if an Exception is thrown during testing. If one is thrown show its info and continue the test
/// Our version of BOOST_CHECK_NO_THROW()
/// @param _statement The statement for which to make sure no exceptions are thrown
/// @param _message A message to act as a prefix to the expression's error information
#define ETH_TEST_CHECK_NO_THROW(_statement, _message) \
do \
{ \
try \
{ \
BOOST_TEST_PASSPOINT(); \
_statement; \
} \
catch (boost::exception const& _e) \
{ \
auto msg = std::string(_message " due to an exception thrown by " \
BOOST_STRINGIZE(_statement) "\n") + boost::diagnostic_information(_e); \
ETH_BOOST_CHECK_IMPL(msg, CHECK); \
} \
catch (...) \
{ \
ETH_BOOST_CHECK_IMPL( \
"Unknown exception thrown by " BOOST_STRINGIZE(_statement), \
CHECK \
); \
} \
} \
while (0)
struct Options: boost::noncopyable
{
std::string ipcPath;
bool showMessages = false;
bool optimize = false;
bool disableIPC = false;
bool disableSMT = false;
static Options const& get();

View File

@ -39,6 +39,17 @@
using namespace boost::unit_test;
namespace
{
void removeTestSuite(std::string const& _name)
{
master_test_suite_t& master = framework::master_test_suite();
auto id = master.get(_name);
assert(id != INV_TEST_UNIT_ID);
master.remove(id);
}
}
test_suite* init_unit_test_suite( int /*argc*/, char* /*argv*/[] )
{
master_test_suite_t& master = framework::master_test_suite();
@ -57,12 +68,10 @@ test_suite* init_unit_test_suite( int /*argc*/, char* /*argv*/[] )
"SolidityEndToEndTest",
"SolidityOptimizer"
})
{
auto id = master.get(suite);
assert(id != INV_TEST_UNIT_ID);
master.remove(id);
}
removeTestSuite(suite);
}
if (dev::test::Options::get().disableSMT)
removeTestSuite("SMTChecker");
return 0;
}

View File

@ -223,7 +223,7 @@ protected:
m_compiler.reset(false);
m_compiler.addSource("", registrarCode);
m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(m_compiler.compile(), "Compiling contract failed");
s_compiledRegistrar.reset(new bytes(m_compiler.object("GlobalRegistrar").bytecode));
}
sendMessage(*s_compiledRegistrar, true);

View File

@ -136,7 +136,7 @@ protected:
m_compiler.reset(false);
m_compiler.addSource("", registrarCode);
m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(m_compiler.compile(), "Compiling contract failed");
s_compiledRegistrar.reset(new bytes(m_compiler.object("FixedFeeRegistrar").bytecode));
}
sendMessage(*s_compiledRegistrar, true);

View File

@ -451,7 +451,7 @@ protected:
m_compiler.reset(false);
m_compiler.addSource("", walletCode);
m_compiler.setOptimiserSettings(m_optimize, m_optimizeRuns);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(m_compiler.compile(), "Compiling contract failed");
s_compiledWallet.reset(new bytes(m_compiler.object("Wallet").bytecode));
}
bytes args = encodeArgs(u256(0x60), _required, _dailyLimit, u256(_owners.size()), _owners);

View File

@ -841,6 +841,20 @@ BOOST_AUTO_TEST_CASE(peephole_double_push)
);
}
BOOST_AUTO_TEST_CASE(peephole_pop_calldatasize)
{
AssemblyItems items{
u256(4),
Instruction::CALLDATASIZE,
Instruction::LT,
Instruction::POP
};
PeepholeOptimiser peepOpt(items);
for (size_t i = 0; i < 3; i++)
BOOST_CHECK(peepOpt.optimise());
BOOST_CHECK(items.empty());
}
BOOST_AUTO_TEST_CASE(jumpdest_removal)
{
AssemblyItems items{

145
test/liblll/Compiler.cpp Normal file
View File

@ -0,0 +1,145 @@
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Alex Beregszaszi
* @date 2017
* Unit tests for the LLL compiler.
*/
#include <string>
#include <memory>
#include <boost/test/unit_test.hpp>
#include <liblll/Compiler.h>
using namespace std;
namespace dev
{
namespace lll
{
namespace test
{
namespace
{
bool successCompile(std::string const& _sourceCode)
{
std::vector<std::string> errors;
bytes bytecode = eth::compileLLL(_sourceCode, false, &errors);
if (!errors.empty())
return false;
if (bytecode.empty())
return false;
return true;
}
}
BOOST_AUTO_TEST_SUITE(LLLCompiler)
BOOST_AUTO_TEST_CASE(smoke_test)
{
char const* sourceCode = "1";
BOOST_CHECK(successCompile(sourceCode));
}
BOOST_AUTO_TEST_CASE(switch_valid)
{
char const* sourceCode = R"(
(switch (origin))
)";
BOOST_CHECK(successCompile(sourceCode));
sourceCode = R"(
(switch
1 (panic)
2 (panic))
)";
BOOST_CHECK(successCompile(sourceCode));
sourceCode = R"(
(switch
1 (panic)
2 (panic)
(panic))
)";
BOOST_CHECK(successCompile(sourceCode));
sourceCode = R"(
(switch
1 (origin)
2 (origin)
(origin))
)";
BOOST_CHECK(successCompile(sourceCode));
}
BOOST_AUTO_TEST_CASE(switch_invalid_arg_count)
{
char const* sourceCode = R"(
(switch)
)";
BOOST_CHECK(!successCompile(sourceCode));
}
BOOST_AUTO_TEST_CASE(switch_inconsistent_return_count)
{
// cannot return stack items if the default case is not present
char const* sourceCode = R"(
(switch
1 (origin)
2 (origin)
)";
BOOST_CHECK(!successCompile(sourceCode));
// return count mismatch
sourceCode = R"(
(switch
1 (origin)
2 (origin)
(panic))
)";
BOOST_CHECK(!successCompile(sourceCode));
// return count mismatch
sourceCode = R"(
(switch
1 (panic)
2 (panic)
(origin))
)";
BOOST_CHECK(!successCompile(sourceCode));
}
BOOST_AUTO_TEST_CASE(disallowed_asm_instructions)
{
for (unsigned i = 1; i <= 32; i++)
BOOST_CHECK(!successCompile("(asm PUSH" + boost::lexical_cast<string>(i) + ")"));
}
BOOST_AUTO_TEST_CASE(disallowed_functional_asm_instructions)
{
for (unsigned i = 1; i <= 32; i++)
BOOST_CHECK(!successCompile("(PUSH" + boost::lexical_cast<string>(i) + ")"));
for (unsigned i = 1; i <= 16; i++)
BOOST_CHECK(!successCompile("(DUP" + boost::lexical_cast<string>(i) + ")"));
for (unsigned i = 1; i <= 16; i++)
BOOST_CHECK(!successCompile("(SWAP" + boost::lexical_cast<string>(i) + ")"));
BOOST_CHECK(!successCompile("(JUMPDEST)"));
}
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces

View File

@ -215,6 +215,92 @@ BOOST_AUTO_TEST_CASE(conditional_nested_then)
BOOST_CHECK(callContractFunction("test()", 0xfc) == encodeArgs(u256(6)));
}
BOOST_AUTO_TEST_CASE(conditional_switch)
{
char const* sourceCode = R"(
(returnlll
(seq
(def 'input (calldataload 0x04))
;; Calculates width in bytes of utf-8 characters.
(return
(switch
(< input 0x80) 1
(< input 0xE0) 2
(< input 0xF0) 3
(< input 0xF8) 4
(< input 0xFC) 5
6))))
)";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("test()", 0x00) == encodeArgs(u256(1)));
BOOST_CHECK(callContractFunction("test()", 0x80) == encodeArgs(u256(2)));
BOOST_CHECK(callContractFunction("test()", 0xe0) == encodeArgs(u256(3)));
BOOST_CHECK(callContractFunction("test()", 0xf0) == encodeArgs(u256(4)));
BOOST_CHECK(callContractFunction("test()", 0xf8) == encodeArgs(u256(5)));
BOOST_CHECK(callContractFunction("test()", 0xfc) == encodeArgs(u256(6)));
}
BOOST_AUTO_TEST_CASE(conditional_switch_one_arg_with_deposit)
{
char const* sourceCode = R"(
(returnlll
(return
(switch 42)))
)";
compileAndRun(sourceCode);
BOOST_CHECK(callFallback() == encodeArgs(u256(42)));
}
BOOST_AUTO_TEST_CASE(conditional_switch_one_arg_no_deposit)
{
char const* sourceCode = R"(
(returnlll
(seq
(switch [0]:42)
(return 0x00 0x20)))
)";
compileAndRun(sourceCode);
BOOST_CHECK(callFallback() == encodeArgs(u256(42)));
}
BOOST_AUTO_TEST_CASE(conditional_switch_two_args)
{
char const* sourceCode = R"(
(returnlll
(seq
(switch (= (calldataload 0x04) 1) [0]:42)
(return 0x00 0x20)))
)";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("test()", 0) == encodeArgs(u256(0)));
BOOST_CHECK(callContractFunction("test()", 1) == encodeArgs(u256(42)));
}
BOOST_AUTO_TEST_CASE(conditional_switch_three_args_with_deposit)
{
char const* sourceCode = R"(
(returnlll
(return
(switch (= (calldataload 0x04) 1) 41 42)))
)";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("test()", 0) == encodeArgs(u256(42)));
BOOST_CHECK(callContractFunction("test()", 1) == encodeArgs(u256(41)));
}
BOOST_AUTO_TEST_CASE(conditional_switch_three_args_no_deposit)
{
char const* sourceCode = R"(
(returnlll
(switch
(= (calldataload 0x04) 1) (return 41)
(return 42)))
)";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("test()", 0) == encodeArgs(u256(42)));
BOOST_CHECK(callContractFunction("test()", 1) == encodeArgs(u256(41)));
}
BOOST_AUTO_TEST_CASE(exp_operator_const)
{
char const* sourceCode = R"(

View File

@ -462,6 +462,87 @@ BOOST_AUTO_TEST_CASE(structs)
)
}
BOOST_AUTO_TEST_CASE(empty_struct)
{
string sourceCode = R"(
contract C {
struct S { }
S s;
event e(uint16, S, uint16);
function f() returns (uint, S, uint) {
e(7, s, 8);
return (7, s, 8);
}
}
)";
NEW_ENCODER(
compileAndRun(sourceCode, 0, "C");
bytes encoded = encodeArgs(7, 8);
BOOST_CHECK(callContractFunction("f()") == encoded);
REQUIRE_LOG_DATA(encoded);
)
}
BOOST_AUTO_TEST_CASE(structs2)
{
string sourceCode = R"(
contract C {
enum E {A, B, C}
struct T { uint x; E e; uint8 y; }
struct S { C c; T[] t;}
function f() public returns (uint a, S[2] s1, S[] s2, uint b) {
a = 7;
b = 8;
s1[0].c = this;
s1[0].t = new T[](1);
s1[0].t[0].x = 0x11;
s1[0].t[0].e = E.B;
s1[0].t[0].y = 0x12;
s2 = new S[](2);
s2[1].c = C(0x1234);
s2[1].t = new T[](3);
s2[1].t[1].x = 0x21;
s2[1].t[1].e = E.C;
s2[1].t[1].y = 0x22;
}
}
)";
NEW_ENCODER(
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f()"), encodeArgs(
7, 0x80, 0x1e0, 8,
// S[2] s1
0x40,
0x100,
// S s1[0]
u256(u160(m_contractAddress)),
0x40,
// T s1[0].t
1, // length
// s1[0].t[0]
0x11, 1, 0x12,
// S s1[1]
0, 0x40,
// T s1[1].t
0,
// S[] s2 (0x1e0)
2, // length
0x40, 0xa0,
// S s2[0]
0, 0x40, 0,
// S s2[1]
0x1234, 0x40,
// s2[1].t
3, // length
0, 0, 0,
0x21, 2, 0x22,
0, 0, 0
));
)
}
BOOST_AUTO_TEST_SUITE_END()
}

View File

@ -25,6 +25,8 @@
#include <libsolidity/ast/AST.h>
#include <libsolidity/parsing/Scanner.h>
#include <libdevcore/SHA3.h>
#include <boost/test/unit_test.hpp>
@ -46,8 +48,7 @@ AnalysisFramework::parseAnalyseAndReturnError(
m_compiler.addSource("", _insertVersionPragma ? "pragma solidity >=0.0;\n" + _source : _source);
if (!m_compiler.parse())
{
printErrors();
BOOST_ERROR("Parsing contract failed in analysis test suite.");
BOOST_ERROR("Parsing contract failed in analysis test suite:" + formatErrors());
}
m_compiler.analyze();
@ -56,15 +57,24 @@ AnalysisFramework::parseAnalyseAndReturnError(
for (auto const& currentError: m_compiler.errors())
{
solAssert(currentError->comment(), "");
if (currentError->comment()->find("This is a pre-release compiler version") == 0)
continue;
if (currentError->type() == Error::Type::Warning)
{
bool ignoreWarning = false;
for (auto const& filter: m_warningsToFilter)
if (currentError->comment()->find(filter) == 0)
{
ignoreWarning = true;
break;
}
if (ignoreWarning)
continue;
}
if (_reportWarnings || (currentError->type() != Error::Type::Warning))
{
if (firstError && !_allowMultipleErrors)
{
printErrors();
BOOST_FAIL("Multiple errors found.");
BOOST_FAIL("Multiple errors found: " + formatErrors());
}
if (!firstError)
firstError = currentError;
@ -78,7 +88,10 @@ SourceUnit const* AnalysisFramework::parseAndAnalyse(string const& _source)
{
auto sourceAndError = parseAnalyseAndReturnError(_source);
BOOST_REQUIRE(!!sourceAndError.first);
BOOST_REQUIRE(!sourceAndError.second);
string message;
if (sourceAndError.second)
message = "Unexpected error: " + formatError(*sourceAndError.second);
BOOST_REQUIRE_MESSAGE(!sourceAndError.second, message);
return sourceAndError.first;
}
@ -91,17 +104,23 @@ Error AnalysisFramework::expectError(std::string const& _source, bool _warning,
{
auto sourceAndError = parseAnalyseAndReturnError(_source, _warning, true, _allowMultiple);
BOOST_REQUIRE(!!sourceAndError.second);
BOOST_REQUIRE(!!sourceAndError.first);
BOOST_REQUIRE_MESSAGE(!!sourceAndError.first, "Expected error, but no error happened.");
return *sourceAndError.second;
}
void AnalysisFramework::printErrors()
string AnalysisFramework::formatErrors()
{
string message;
for (auto const& error: m_compiler.errors())
SourceReferenceFormatter::printExceptionInformation(
std::cerr,
*error,
(error->type() == Error::Type::Warning) ? "Warning" : "Error",
message += formatError(*error);
return message;
}
string AnalysisFramework::formatError(Error const& _error)
{
return SourceReferenceFormatter::formatExceptionInformation(
_error,
(_error.type() == Error::Type::Warning) ? "Warning" : "Error",
[&](std::string const& _sourceName) -> solidity::Scanner const& { return m_compiler.scanner(_sourceName); }
);
}

View File

@ -45,7 +45,7 @@ class AnalysisFramework
{
protected:
std::pair<SourceUnit const*, std::shared_ptr<Error const>>
virtual std::pair<SourceUnit const*, std::shared_ptr<Error const>>
parseAnalyseAndReturnError(
std::string const& _source,
bool _reportWarnings = false,
@ -57,7 +57,8 @@ protected:
bool success(std::string const& _source);
Error expectError(std::string const& _source, bool _warning = false, bool _allowMultiple = false);
void printErrors();
std::string formatErrors();
std::string formatError(Error const& _error);
static ContractDefinition const* retrieveContractByName(SourceUnit const& _source, std::string const& _name);
static FunctionTypePointer retrieveFunctionBySignature(
@ -65,6 +66,7 @@ protected:
std::string const& _signature
);
std::vector<std::string> m_warningsToFilter = {"This is a pre-release compiler version"};
dev::solidity::CompilerStack m_compiler;
};
@ -104,7 +106,10 @@ CHECK_ERROR_OR_WARNING(text, Warning, substring, true, true)
do \
{ \
auto sourceAndError = parseAnalyseAndReturnError((text), true); \
BOOST_CHECK(sourceAndError.second == nullptr); \
std::string message; \
if (sourceAndError.second) \
message = formatError(*sourceAndError.second); \
BOOST_CHECK_MESSAGE(!sourceAndError.second, message); \
} \
while(0)

View File

@ -119,7 +119,7 @@ BOOST_AUTO_TEST_CASE(location_test)
shared_ptr<string const> n = make_shared<string>("");
AssemblyItems items = compileContract(sourceCode);
vector<SourceLocation> locations =
vector<SourceLocation>(18, SourceLocation(2, 75, n)) +
vector<SourceLocation>(24, SourceLocation(2, 75, n)) +
vector<SourceLocation>(32, SourceLocation(20, 72, n)) +
vector<SourceLocation>{SourceLocation(42, 51, n), SourceLocation(65, 67, n)} +
vector<SourceLocation>(2, SourceLocation(58, 67, n)) +

View File

@ -21,7 +21,6 @@
*/
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <libevmasm/EVMSchedule.h>
#include <libevmasm/GasMeter.h>
#include <libevmasm/KnownState.h>
#include <libevmasm/PathGasMeter.h>
@ -50,7 +49,7 @@ public:
m_compiler.reset(false);
m_compiler.addSource("", "pragma solidity >=0.0;\n" + _sourceCode);
m_compiler.setOptimiserSettings(dev::test::Options::get().optimize);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(m_compiler.compile(), "Compiling contract failed");
AssemblyItems const* items = m_compiler.runtimeAssemblyItems("");
ASTNode const& sourceUnit = m_compiler.ast();
@ -63,15 +62,13 @@ public:
void testCreationTimeGas(string const& _sourceCode)
{
EVMSchedule schedule;
compileAndRun(_sourceCode);
auto state = make_shared<KnownState>();
PathGasMeter meter(*m_compiler.assemblyItems());
GasMeter::GasConsumption gas = meter.estimateMax(0, state);
u256 bytecodeSize(m_compiler.runtimeObject().bytecode.size());
// costs for deployment
gas += bytecodeSize * schedule.createDataGas;
gas += bytecodeSize * GasCosts::createDataGas;
// costs for transaction
gas += gasForTransaction(m_compiler.object().bytecode, true);
@ -103,10 +100,9 @@ public:
static GasMeter::GasConsumption gasForTransaction(bytes const& _data, bool _isCreation)
{
EVMSchedule schedule;
GasMeter::GasConsumption gas = _isCreation ? schedule.txCreateGas : schedule.txGas;
GasMeter::GasConsumption gas = _isCreation ? GasCosts::txCreateGas : GasCosts::txGas;
for (auto i: _data)
gas += i != 0 ? schedule.txDataNonZeroGas : schedule.txDataZeroGas;
gas += i != 0 ? GasCosts::txDataNonZeroGas : GasCosts::txDataZeroGas;
return gas;
}

View File

@ -46,7 +46,7 @@ BOOST_AUTO_TEST_CASE(metadata_stamp)
CompilerStack compilerStack;
compilerStack.addSource("", std::string(sourceCode));
compilerStack.setOptimiserSettings(dev::test::Options::get().optimize);
ETH_TEST_REQUIRE_NO_THROW(compilerStack.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
bytes const& bytecode = compilerStack.runtimeObject("test").bytecode;
std::string const& metadata = compilerStack.metadata("test");
BOOST_CHECK(dev::test::isValidMetadata(metadata));
@ -72,7 +72,7 @@ BOOST_AUTO_TEST_CASE(metadata_stamp_experimental)
CompilerStack compilerStack;
compilerStack.addSource("", std::string(sourceCode));
compilerStack.setOptimiserSettings(dev::test::Options::get().optimize);
ETH_TEST_REQUIRE_NO_THROW(compilerStack.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
bytes const& bytecode = compilerStack.runtimeObject("test").bytecode;
std::string const& metadata = compilerStack.metadata("test");
BOOST_CHECK(dev::test::isValidMetadata(metadata));
@ -106,7 +106,7 @@ BOOST_AUTO_TEST_CASE(metadata_relevant_sources)
)";
compilerStack.addSource("B", std::string(sourceCode));
compilerStack.setOptimiserSettings(dev::test::Options::get().optimize);
ETH_TEST_REQUIRE_NO_THROW(compilerStack.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string const& serialisedMetadata = compilerStack.metadata("A");
BOOST_CHECK(dev::test::isValidMetadata(serialisedMetadata));
@ -144,7 +144,7 @@ BOOST_AUTO_TEST_CASE(metadata_relevant_sources_imports)
)";
compilerStack.addSource("C", std::string(sourceCode));
compilerStack.setOptimiserSettings(dev::test::Options::get().optimize);
ETH_TEST_REQUIRE_NO_THROW(compilerStack.compile(), "Compiling contract failed");
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string const& serialisedMetadata = compilerStack.metadata("C");
BOOST_CHECK(dev::test::isValidMetadata(serialisedMetadata));

View File

@ -0,0 +1,112 @@
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Unit tests for the SMT checker.
*/
#include <test/libsolidity/AnalysisFramework.h>
#include <boost/test/unit_test.hpp>
#include <string>
using namespace std;
namespace dev
{
namespace solidity
{
namespace test
{
class SMTCheckerFramework: public AnalysisFramework
{
public:
SMTCheckerFramework()
{
m_warningsToFilter.push_back("Experimental features are turned on.");
}
protected:
virtual std::pair<SourceUnit const*, std::shared_ptr<Error const>>
parseAnalyseAndReturnError(
std::string const& _source,
bool _reportWarnings = false,
bool _insertVersionPragma = true,
bool _allowMultipleErrors = false
)
{
return AnalysisFramework::parseAnalyseAndReturnError(
"pragma experimental SMTChecker;\n" + _source,
_reportWarnings,
_insertVersionPragma,
_allowMultipleErrors
);
}
};
BOOST_FIXTURE_TEST_SUITE(SMTChecker, SMTCheckerFramework)
BOOST_AUTO_TEST_CASE(smoke_test)
{
string text = R"(
contract C { }
)";
CHECK_SUCCESS_NO_WARNINGS(text);
}
BOOST_AUTO_TEST_CASE(simple_overflow)
{
string text = R"(
contract C {
function f(uint a, uint b) public pure returns (uint) { return a + b; }
}
)";
CHECK_WARNING(text, "Overflow (resulting value larger than");
}
BOOST_AUTO_TEST_CASE(warn_on_typecast)
{
string text = R"(
contract C {
function f() public pure returns (uint) {
return uint8(1);
}
}
)";
CHECK_WARNING(text, "Assertion checker does not yet implement this expression.");
}
BOOST_AUTO_TEST_CASE(warn_on_struct)
{
string text = R"(
contract C {
struct A { uint a; uint b; }
function f() public pure returns (A) {
return A({ a: 1, b: 2 });
}
}
)";
/// Multiple warnings, should check for: Assertion checker does not yet implement this expression.
CHECK_WARNING_ALLOW_MULTI(text, "");
}
BOOST_AUTO_TEST_SUITE_END()
}
}
}

View File

@ -44,7 +44,7 @@ public:
{
m_compilerStack.reset(false);
m_compilerStack.addSource("", "pragma solidity >=0.0;\n" + _code);
ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parseAndAnalyze(), "Parsing contract failed");
BOOST_REQUIRE_MESSAGE(m_compilerStack.parseAndAnalyze(), "Parsing contract failed");
Json::Value generatedInterface = m_compilerStack.contractABI("");
Json::Value expectedInterface;

File diff suppressed because it is too large Load Diff

View File

@ -24,7 +24,7 @@
#include <functional>
#include "../ExecutionFramework.h"
#include <test/ExecutionFramework.h>
#include <libsolidity/interface/CompilerStack.h>
#include <libsolidity/interface/Exceptions.h>

View File

@ -125,7 +125,7 @@ bytes compileFirstExpression(
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
ETH_TEST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract), "Resolving names failed");
BOOST_REQUIRE_MESSAGE(resolver.resolveNamesAndTypes(*contract), "Resolving names failed");
inheritanceHierarchy = vector<ContractDefinition const*>(1, contract);
}
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())

View File

@ -1395,6 +1395,61 @@ BOOST_AUTO_TEST_CASE(events_with_same_name)
BOOST_CHECK(success(text));
}
BOOST_AUTO_TEST_CASE(events_with_same_name_unnamed_arguments)
{
char const* text = R"(
contract test {
event A(uint);
event A(uint, uint);
}
)";
CHECK_SUCCESS(text);
}
BOOST_AUTO_TEST_CASE(events_with_same_name_different_types)
{
char const* text = R"(
contract test {
event A(uint);
event A(bytes);
}
)";
CHECK_SUCCESS(text);
}
BOOST_AUTO_TEST_CASE(double_event_declaration)
{
char const* text = R"(
contract test {
event A(uint i);
event A(uint i);
}
)";
CHECK_ERROR(text, DeclarationError, "Event with same name and arguments defined twice.");
}
BOOST_AUTO_TEST_CASE(double_event_declaration_ignores_anonymous)
{
char const* text = R"(
contract test {
event A(uint i);
event A(uint i) anonymous;
}
)";
CHECK_ERROR(text, DeclarationError, "Event with same name and arguments defined twice.");
}
BOOST_AUTO_TEST_CASE(double_event_declaration_ignores_indexed)
{
char const* text = R"(
contract test {
event A(uint i);
event A(uint indexed i);
}
)";
CHECK_ERROR(text, DeclarationError, "Event with same name and arguments defined twice.");
}
BOOST_AUTO_TEST_CASE(event_call)
{
char const* text = R"(
@ -2306,17 +2361,28 @@ BOOST_AUTO_TEST_CASE(assigning_value_to_const_variable)
CHECK_ERROR(text, TypeError, "Cannot assign to a constant variable.");
}
BOOST_AUTO_TEST_CASE(assigning_state_to_const_variable)
BOOST_AUTO_TEST_CASE(assigning_state_to_const_variable_0_4_x)
{
char const* text = R"(
contract C {
address constant x = msg.sender;
}
)";
// Change to TypeError for 0.5.0.
CHECK_WARNING(text, "Initial value for constant variable has to be compile-time constant.");
}
BOOST_AUTO_TEST_CASE(assigning_state_to_const_variable)
{
char const* text = R"(
pragma experimental "v0.5.0";
contract C {
address constant x = msg.sender;
}
)";
CHECK_ERROR(text, TypeError, "Initial value for constant variable has to be compile-time constant.");
}
BOOST_AUTO_TEST_CASE(constant_string_literal_disallows_assignment)
{
char const* text = R"(
@ -2333,7 +2399,7 @@ BOOST_AUTO_TEST_CASE(constant_string_literal_disallows_assignment)
CHECK_ERROR(text, TypeError, "Index access for string is not possible.");
}
BOOST_AUTO_TEST_CASE(assign_constant_function_value_to_constant)
BOOST_AUTO_TEST_CASE(assign_constant_function_value_to_constant_0_4_x)
{
char const* text = R"(
contract C {
@ -2341,10 +2407,22 @@ BOOST_AUTO_TEST_CASE(assign_constant_function_value_to_constant)
uint constant y = x();
}
)";
// Change to TypeError for 0.5.0.
CHECK_WARNING(text, "Initial value for constant variable has to be compile-time constant.");
}
BOOST_AUTO_TEST_CASE(assign_constant_function_value_to_constant)
{
char const* text = R"(
pragma experimental "v0.5.0";
contract C {
function () constant returns (uint) x;
uint constant y = x();
}
)";
CHECK_ERROR(text, TypeError, "Initial value for constant variable has to be compile-time constant.");
}
BOOST_AUTO_TEST_CASE(assignment_to_const_var_involving_conversion)
{
char const* text = R"(
@ -4135,6 +4213,8 @@ BOOST_AUTO_TEST_CASE(rational_unary_operation)
}
)";
CHECK_SUCCESS_NO_WARNINGS(text);
// Test deprecation warning under < 0.5.0
text = R"(
contract test {
function f() pure public {
@ -4154,6 +4234,29 @@ BOOST_AUTO_TEST_CASE(rational_unary_operation)
}
)";
CHECK_WARNING(text,"Use of unary + is deprecated");
// Test syntax error under 0.5.0
text = R"(
pragma experimental "v0.5.0";
contract test {
function f() pure public {
ufixed16x2 a = +3.25;
fixed16x2 b = -3.25;
a; b;
}
}
)";
CHECK_ERROR(text, SyntaxError, "Use of unary + is deprecated");
text = R"(
pragma experimental "v0.5.0";
contract test {
function f(uint x) pure public {
uint y = +x;
y;
}
}
)";
CHECK_ERROR(text, SyntaxError, "Use of unary + is deprecated");
}
BOOST_AUTO_TEST_CASE(leading_zero_rationals_convert)
@ -4251,7 +4354,7 @@ BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_rational)
}
}
)";
CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal");
CHECK_ERROR(text, TypeError, "Array with fractional length specified.");
}
BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_signed_fixed_type)
@ -4263,7 +4366,7 @@ BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_signed_fixed_type)
}
}
)";
CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal");
CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal.");
}
BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_unsigned_fixed_type)
@ -4275,7 +4378,7 @@ BOOST_AUTO_TEST_CASE(invalid_array_declaration_with_unsigned_fixed_type)
}
}
)";
CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal");
CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal.");
}
BOOST_AUTO_TEST_CASE(rational_to_bytes_implicit_conversion)
@ -5434,7 +5537,7 @@ BOOST_AUTO_TEST_CASE(invalid_mobile_type)
}
}
)";
CHECK_ERROR(text, TypeError, "Invalid mobile type.");
CHECK_ERROR(text, TypeError, "Invalid rational number.");
}
BOOST_AUTO_TEST_CASE(warns_msg_value_in_non_payable_public_function)
@ -5776,6 +5879,28 @@ BOOST_AUTO_TEST_CASE(interface_function_bodies)
CHECK_ERROR(text, TypeError, "Functions in interfaces cannot have an implementation");
}
BOOST_AUTO_TEST_CASE(interface_function_external)
{
char const* text = R"(
pragma experimental "v0.5.0";
interface I {
function f() external;
}
)";
success(text);
}
BOOST_AUTO_TEST_CASE(interface_function_public)
{
char const* text = R"(
pragma experimental "v0.5.0";
interface I {
function f() public;
}
)";
CHECK_ERROR(text, TypeError, "Functions in interfaces must be declared external.");
}
BOOST_AUTO_TEST_CASE(interface_function_internal)
{
char const* text = R"(
@ -6107,6 +6232,26 @@ BOOST_AUTO_TEST_CASE(warn_unused_return_parameter)
CHECK_SUCCESS_NO_WARNINGS(text);
}
BOOST_AUTO_TEST_CASE(no_unused_warning_interface_arguments)
{
char const* text = R"(
interface I {
function f(uint a) pure public returns (uint b);
}
)";
CHECK_SUCCESS_NO_WARNINGS(text);
}
BOOST_AUTO_TEST_CASE(no_unused_warning_abstract_arguments)
{
char const* text = R"(
contract C {
function f(uint a) pure public returns (uint b);
}
)";
CHECK_SUCCESS_NO_WARNINGS(text);
}
BOOST_AUTO_TEST_CASE(no_unused_warnings)
{
char const* text = R"(
@ -6268,6 +6413,17 @@ BOOST_AUTO_TEST_CASE(function_override_is_not_shadowing)
CHECK_SUCCESS_NO_WARNINGS(text);
}
BOOST_AUTO_TEST_CASE(event_parameter_cannot_shadow_state_variable)
{
char const* text = R"(
contract C {
address a;
event E(address a);
}
)";
CHECK_SUCCESS_NO_WARNINGS(text);
}
BOOST_AUTO_TEST_CASE(callable_crash)
{
char const* text = R"(
@ -6409,7 +6565,19 @@ BOOST_AUTO_TEST_CASE(warn_unspecified_storage)
}
}
)";
CHECK_WARNING(text, "is declared as a storage pointer. Use an explicit \"storage\" keyword to silence this warning");
CHECK_WARNING(text, "Variable is declared as a storage pointer. Use an explicit \"storage\" keyword to silence this warning");
text = R"(
pragma experimental "v0.5.0";
contract C {
struct S { uint a; }
S x;
function f() view public {
S y = x;
y;
}
}
)";
CHECK_ERROR(text, TypeError, "Storage location must be specified as either \"memory\" or \"storage\".");
}
BOOST_AUTO_TEST_CASE(implicit_conversion_disallowed)
@ -6928,6 +7096,53 @@ BOOST_AUTO_TEST_CASE(non_external_fallback)
CHECK_ERROR(text, TypeError, "Fallback function must be defined as \"external\".");
}
BOOST_AUTO_TEST_CASE(invalid_literal_in_tuple)
{
char const* text = R"(
contract C {
function f() pure public {
uint x;
(x, ) = (1E111);
}
}
)";
CHECK_ERROR(text, TypeError, "is not implicitly convertible to expected type");
text = R"(
contract C {
function f() pure public {
uint x;
(x, ) = (1, 1E111);
}
}
)";
CHECK_ERROR(text, TypeError, "Invalid rational number.");
text = R"(
contract C {
function f() pure public {
uint x;
(x, ) = (1E111, 1);
}
}
)";
CHECK_ERROR(text, TypeError, "Invalid rational number.");
text = R"(
contract C {
function f() pure public {
(2**270, 1);
}
}
)";
CHECK_ERROR(text, TypeError, "Invalid rational number.");
text = R"(
contract C {
function f() pure public {
((2**270) / 2**100, 1);
}
}
)";
CHECK_SUCCESS(text);
}
BOOST_AUTO_TEST_CASE(warn_about_sha3)
{
char const* text = R"(
@ -6953,6 +7168,135 @@ BOOST_AUTO_TEST_CASE(warn_about_suicide)
CHECK_WARNING(text, "\"suicide\" has been deprecated in favour of \"selfdestruct\"");
}
BOOST_AUTO_TEST_CASE(address_overload_resolution)
{
char const* text = R"(
contract C {
function balance() returns (uint) {
this.balance; // to avoid pureness warning
return 1;
}
function transfer(uint amount) {
address(this).transfer(amount); // to avoid pureness warning
}
}
contract D {
function f() {
var x = (new C()).balance();
x;
(new C()).transfer(5);
}
}
)";
CHECK_SUCCESS(text);
}
BOOST_AUTO_TEST_CASE(array_length_too_large)
{
char const* text = R"(
contract C {
uint[8**90] ids;
}
)";
CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal.");
}
BOOST_AUTO_TEST_CASE(array_length_not_convertible_to_integer)
{
char const* text = R"(
contract C {
uint[true] ids;
}
)";
CHECK_ERROR(text, TypeError, "Invalid array length, expected integer literal.");
}
BOOST_AUTO_TEST_CASE(array_length_invalid_expression)
{
char const* text = R"(
contract C {
uint[-true] ids;
}
)";
CHECK_ERROR(text, TypeError, "Invalid constant expression.");
text = R"(
contract C {
uint[true/1] ids;
}
)";
CHECK_ERROR(text, TypeError, "Invalid constant expression.");
text = R"(
contract C {
uint[1/true] ids;
}
)";
CHECK_ERROR(text, TypeError, "Invalid constant expression.");
text = R"(
contract C {
uint[1.111111E1111111111111] ids;
}
)";
CHECK_ERROR(text, TypeError, "Invalid literal value.");
}
BOOST_AUTO_TEST_CASE(no_address_members_on_contract)
{
char const* text = R"(
pragma experimental "v0.5.0";
contract C {
function f() {
this.balance;
}
}
)";
CHECK_ERROR(text, TypeError, "Member \"balance\" not found or not visible after argument-dependent lookup in contract");
text = R"(
pragma experimental "v0.5.0";
contract C {
function f() {
this.transfer;
}
}
)";
CHECK_ERROR(text, TypeError, "Member \"transfer\" not found or not visible after argument-dependent lookup in contract");
text = R"(
pragma experimental "v0.5.0";
contract C {
function f() {
this.send;
}
}
)";
CHECK_ERROR(text, TypeError, "Member \"send\" not found or not visible after argument-dependent lookup in contract");
text = R"(
pragma experimental "v0.5.0";
contract C {
function f() {
this.call;
}
}
)";
CHECK_ERROR(text, TypeError, "Member \"call\" not found or not visible after argument-dependent lookup in contract");
text = R"(
pragma experimental "v0.5.0";
contract C {
function f() {
this.callcode;
}
}
)";
CHECK_ERROR(text, TypeError, "Member \"callcode\" not found or not visible after argument-dependent lookup in contract");
text = R"(
pragma experimental "v0.5.0";
contract C {
function f() {
this.delegatecall;
}
}
)";
CHECK_ERROR(text, TypeError, "Member \"delegatecall\" not found or not visible after argument-dependent lookup in contract");
}
BOOST_AUTO_TEST_SUITE_END()
}

View File

@ -47,7 +47,7 @@ public:
{
m_compilerStack.reset(false);
m_compilerStack.addSource("", "pragma solidity >=0.0;\n" + _code);
ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parseAndAnalyze(), "Parsing contract failed");
BOOST_REQUIRE_MESSAGE(m_compilerStack.parseAndAnalyze(), "Parsing contract failed");
Json::Value generatedDocumentation;
if (_userDocumentation)

View File

@ -167,6 +167,90 @@ BOOST_AUTO_TEST_CASE(single_function_param)
BOOST_CHECK(successParse(text));
}
BOOST_AUTO_TEST_CASE(single_function_param_trailing_comma)
{
char const* text = R"(
contract test {
function(uint a,) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(single_return_param_trailing_comma)
{
char const* text = R"(
contract test {
function() returns (uint a,) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(single_modifier_arg_trailing_comma)
{
char const* text = R"(
contract test {
modifier modTest(uint a,) { _; }
function(uint a) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(single_event_arg_trailing_comma)
{
char const* text = R"(
contract test {
event Test(uint a,);
function(uint a) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(multiple_function_param_trailing_comma)
{
char const* text = R"(
contract test {
function(uint a, uint b,) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(multiple_return_param_trailing_comma)
{
char const* text = R"(
contract test {
function() returns (uint a, uint b,) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(multiple_modifier_arg_trailing_comma)
{
char const* text = R"(
contract test {
modifier modTest(uint a, uint b,) { _; }
function(uint a) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(multiple_event_arg_trailing_comma)
{
char const* text = R"(
contract test {
event Test(uint a, uint b,);
function(uint a) {}
}
)";
CHECK_PARSE_ERROR(text, "Unexpected trailing comma in parameter list.");
}
BOOST_AUTO_TEST_CASE(function_no_body)
{
char const* text = R"(
@ -250,7 +334,7 @@ BOOST_AUTO_TEST_CASE(function_natspec_documentation)
FunctionDefinition const* function = nullptr;
auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "This is a test function");
}
@ -268,7 +352,7 @@ BOOST_AUTO_TEST_CASE(function_normal_comments)
ErrorList errors;
ASTPointer<ContractDefinition> contract = parseText(text, errors);
auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(0), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(function->documentation() == nullptr,
"Should not have gotten a Natspecc comment for this function");
}
@ -294,17 +378,17 @@ BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation)
ASTPointer<ContractDefinition> contract = parseText(text, errors);
auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "This is test function 1");
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(1), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(1), "Failed to retrieve function");
checkFunctionNatspec(function, "This is test function 2");
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(2), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(2), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(function->documentation() == nullptr,
"Should not have gotten natspec comment for functionName3()");
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(3), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(3), "Failed to retrieve function");
checkFunctionNatspec(function, "This is test function 4");
}
@ -323,7 +407,7 @@ BOOST_AUTO_TEST_CASE(multiline_function_documentation)
ErrorList errors;
ASTPointer<ContractDefinition> contract = parseText(text, errors);
auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "This is a test function\n"
" and it has 2 lines");
}
@ -351,10 +435,10 @@ BOOST_AUTO_TEST_CASE(natspec_comment_in_function_body)
ASTPointer<ContractDefinition> contract = parseText(text, errors);
auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "fun1 description");
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(1), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(1), "Failed to retrieve function");
checkFunctionNatspec(function, "This is a test function\n"
" and it has 2 lines");
}
@ -380,7 +464,7 @@ BOOST_AUTO_TEST_CASE(natspec_docstring_between_keyword_and_signature)
ASTPointer<ContractDefinition> contract = parseText(text, errors);
auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(0), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(!function->documentation(),
"Shouldn't get natspec docstring for this function");
}
@ -406,7 +490,7 @@ BOOST_AUTO_TEST_CASE(natspec_docstring_after_signature)
ASTPointer<ContractDefinition> contract = parseText(text, errors);
auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_REQUIRE_MESSAGE(function = functions.at(0), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(!function->documentation(),
"Shouldn't get natspec docstring for this function");
}

View File

@ -226,6 +226,183 @@ BOOST_AUTO_TEST_CASE(basic_compilation)
);
}
BOOST_AUTO_TEST_CASE(output_selection_explicit)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json::Value result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json::Value contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.isObject());
BOOST_CHECK(contract["abi"].isArray());
BOOST_CHECK_EQUAL(dev::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_all_contracts)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": {
"*": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json::Value result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json::Value contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.isObject());
BOOST_CHECK(contract["abi"].isArray());
BOOST_CHECK_EQUAL(dev::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_all_files_single_contract)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json::Value result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json::Value contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.isObject());
BOOST_CHECK(contract["abi"].isArray());
BOOST_CHECK_EQUAL(dev::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_all_files_all_contracts)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"*": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json::Value result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json::Value contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.isObject());
BOOST_CHECK(contract["abi"].isArray());
BOOST_CHECK_EQUAL(dev::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_dependent_contract)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract B { } contract A { function f() { new B(); } }"
}
}
}
)";
Json::Value result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json::Value contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.isObject());
BOOST_CHECK(contract["abi"].isArray());
BOOST_CHECK_EQUAL(dev::jsonCompactPrint(contract["abi"]), "[{\"constant\":false,\"inputs\":[],\"name\":\"f\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]");
}
BOOST_AUTO_TEST_CASE(output_selection_dependent_contract_with_import)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "import \"fileB\"; contract A { function f() { new B(); } }"
},
"fileB": {
"content": "contract B { }"
}
}
}
)";
Json::Value result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json::Value contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.isObject());
BOOST_CHECK(contract["abi"].isArray());
BOOST_CHECK_EQUAL(dev::jsonCompactPrint(contract["abi"]), "[{\"constant\":false,\"inputs\":[],\"name\":\"f\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]");
}
BOOST_AUTO_TEST_SUITE_END()
}

View File

@ -349,7 +349,7 @@ BOOST_AUTO_TEST_CASE(assembly)
assembly { x := 7 }
}
function g() view public {
assembly { for {} 1 { pop(sload(0)) } { } }
assembly { for {} 1 { pop(sload(0)) } { } pop(gas) }
}
function h() view public {
assembly { function g() { pop(blockhash(20)) } }
@ -357,6 +357,9 @@ BOOST_AUTO_TEST_CASE(assembly)
function j() public {
assembly { pop(call(0, 1, 2, 3, 4, 5, 6)) }
}
function k() public {
assembly { pop(call(gas, 1, 2, 3, 4, 5, 6)) }
}
}
)";
CHECK_SUCCESS_NO_WARNINGS(text);
@ -367,7 +370,7 @@ BOOST_AUTO_TEST_CASE(assembly_staticcall)
string text = R"(
contract C {
function i() view public {
assembly { pop(staticcall(0, 1, 2, 3, 4, 5)) }
assembly { pop(staticcall(gas, 1, 2, 3, 4, 5)) }
}
}
)";