aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--docs/abi-spec.rst13
-rw-r--r--docs/control-structures.rst2
-rw-r--r--docs/types.rst76
-rw-r--r--docs/units-and-global-variables.rst98
-rw-r--r--libsolidity/analysis/SemVerHandler.cpp39
-rw-r--r--libsolidity/analysis/TypeChecker.cpp4
-rw-r--r--libsolidity/ast/Types.cpp9
-rw-r--r--libsolidity/ast/Types.h2
-rw-r--r--libsolidity/codegen/ExpressionCompiler.cpp6
-rw-r--r--libsolidity/inlineasm/AsmCodeGen.h2
-rw-r--r--libsolidity/interface/StandardCompiler.cpp12
-rw-r--r--test/libsolidity/StandardCompiler.cpp2
-rw-r--r--test/libsolidity/syntaxTests/functionTypes/external_function_type_to_address_payable.sol7
-rw-r--r--test/libsolidity/syntaxTests/types/address/address_to_payable_address_double.sol7
-rw-r--r--test/libsolidity/syntaxTests/types/address/bytes_long_to_payable_address.sol8
-rw-r--r--test/libsolidity/syntaxTests/types/address/bytes_short_to_payable_address.sol8
-rw-r--r--test/libsolidity/syntaxTests/types/address/bytes_to_payable_address.sol5
-rw-r--r--test/libsolidity/syntaxTests/types/address/uint_to_payable_address.sol5
18 files changed, 202 insertions, 103 deletions
diff --git a/docs/abi-spec.rst b/docs/abi-spec.rst
index 8a5e2f5c..4e7c88d0 100644
--- a/docs/abi-spec.rst
+++ b/docs/abi-spec.rst
@@ -78,13 +78,14 @@ Types can be combined to a tuple by enclosing them inside parentheses, separated
It is possible to form tuples of tuples, arrays of tuples and so on. It is also possible to form zero-tuples (where ``n == 0``).
-.. note::
- Solidity supports all the types presented above with the same names with the exception of tuples. The ABI tuple type is utilised for encoding Solidity ``structs``.
-
Mapping Solidity to ABI types
-----------------------------
-The following table shows on the left column Solidity types that are not part of the ABI,
-and on the right column the ABI type that they map to.
+
+Solidity supports all the types presented above with the same names with the
+exception of tuples. On the other hand, some Solidity types are not supported
+by the ABI. The following table shows on the left column Solidity types that
+are not part of the ABI, and on the right column the ABI types that represent
+them.
+-------------------------------+-----------------------------------------------------------------------------+
| Solidity | ABI |
@@ -98,6 +99,8 @@ and on the right column the ABI type that they map to.
| |For example, an ``enum`` of 255 values or less is mapped to ``uint8`` and |
| |an ``enum`` of 256 values is mapped to ``uint16``. |
+-------------------------------+-----------------------------------------------------------------------------+
+|:ref:`struct<structs>` |``tuple`` |
++-------------------------------+-----------------------------------------------------------------------------+
Formal Specification of the Encoding
====================================
diff --git a/docs/control-structures.rst b/docs/control-structures.rst
index 745a0599..7c91cab7 100644
--- a/docs/control-structures.rst
+++ b/docs/control-structures.rst
@@ -385,6 +385,8 @@ In any case, you will get a warning about the outer variable being shadowed.
.. index:: ! exception, ! throw, ! assert, ! require, ! revert
+.. _assert-and-require:
+
Error handling: Assert, Require, Revert and Exceptions
======================================================
diff --git a/docs/types.rst b/docs/types.rst
index 1cbbb1be..b5e1daa0 100644
--- a/docs/types.rst
+++ b/docs/types.rst
@@ -276,15 +276,19 @@ Contract Types
--------------
Every :ref:`contract<contracts>` defines its own type.
-You can implicitly convert contracts to contracts they inherit from,
-and explicitly convert them to and from the ``address`` type, if they have no
-payable fallback functions, or to and from the ``address payable`` type, if they do
-have payable fallback functions.
+You can implicitly convert contracts to contracts they inherit from.
+Contracts can be explicitly converted to and from all other contract types
+and the ``address`` type.
+
+Explicit conversion to and from the ``address payable`` type
+is only possible if the contract type has a payable fallback function.
+The conversion is still performed using ``address(x)`` and not
+using ``address payable(x)``. You can find more information in the section about
+the :ref:`address type<address>`.
.. note::
- Starting with version 0.5.0 contracts do not derive from the address type,
- but can still be explicitly converted to ``address``, resp. to ``address payable``,
- if they have a payable fallback function.
+ Before version 0.5.0, contracts directly derived from the address type
+ and there was no distinction between ``address`` and ``address payable``.
If you declare a local variable of contract type (`MyContract c`), you can call
functions on that contract. Take care to assign it from somewhere that is the
@@ -307,25 +311,29 @@ including public state variables.
Fixed-size byte arrays
----------------------
-``bytes1``, ``bytes2``, ``bytes3``, ..., ``bytes32``. ``byte`` is an alias for ``bytes1``.
+The value types ``bytes1``, ``bytes2``, ``bytes3``, ..., ``bytes32``
+hold a sequence of bytes from one to up to 32.
+``byte`` is an alias for ``bytes1``.
Operators:
* Comparisons: ``<=``, ``<``, ``==``, ``!=``, ``>=``, ``>`` (evaluate to ``bool``)
-* Bit operators: ``&``, ``|``, ``^`` (bitwise exclusive or), ``~`` (bitwise negation), ``<<`` (left shift), ``>>`` (right shift)
+* Bit operators: ``&``, ``|``, ``^`` (bitwise exclusive or), ``~`` (bitwise negation)
+* Shift operators: ``<<`` (left shift), ``>>`` (right shift)
* Index access: If ``x`` is of type ``bytesI``, then ``x[k]`` for ``0 <= k < I`` returns the ``k`` th byte (read-only).
-The shifting operator works with any integer type as right operand (but will
-return the type of the left operand), which denotes the number of bits to shift by.
-Shifting by a negative amount will cause a runtime exception.
+The shifting operator works with any integer type as right operand (but
+returns the type of the left operand), which denotes the number of bits to shift by.
+Shifting by a negative amount causes a runtime exception.
Members:
* ``.length`` yields the fixed length of the byte array (read-only).
.. note::
- It is possible to use an array of bytes as ``byte[]``, but it is wasting a lot of space, 31 bytes every element,
- to be exact, when passing in calls. It is better to use ``bytes``.
+ The type ``byte[]`` is an array of bytes, but due to padding rules, it wastes
+ 31 bytes of space for each element (except in storage). It is better to use the ``bytes``
+ type instead.
Dynamically-sized byte array
----------------------------
@@ -343,7 +351,7 @@ Address Literals
----------------
Hexadecimal literals that pass the address checksum test, for example
-``0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF`` are of ``address`` type.
+``0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF`` are of ``address payable`` type.
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.
@@ -371,10 +379,11 @@ Examples include ``2e10``, ``-2e10``, ``2e-10``, ``2.5e1``.
Underscores can be used to separate the digits of a numeric literal to aid readability.
For example, decimal ``123_000``, hexadecimal ``0x2eff_abde``, scientific decimal notation ``1_2e345_678`` are all valid.
Underscores are only allowed between two digits and only one consecutive underscore is allowed.
-There is no additional semantic meaning added to a number literal containing underscores.
+There is no additional semantic meaning added to a number literal containing underscores,
+the underscores are ignored.
Number literal expressions retain arbitrary precision until they are converted to a non-literal type (i.e. by
-using them together with a non-literal expression).
+using them together with a non-literal expression or by explicit conversion).
This means that computations do not overflow and divisions do not truncate
in number literal expressions.
@@ -396,14 +405,15 @@ a non-rational number).
belong to the same number literal type for the rational number three.
.. warning::
- Division on integer literals used to truncate in earlier versions, but it will now convert into a rational number, i.e. ``5 / 2`` is not equal to ``2``, but to ``2.5``.
+ Division on integer literals used to truncate in Solidity prior to version 0.4.0, but it now converts into a rational number, i.e. ``5 / 2`` is not equal to ``2``, but to ``2.5``.
.. note::
Number literal expressions are converted into a non-literal type as soon as they are used with non-literal
- expressions. Even though we know that the value of the
- expression assigned to ``b`` in the following example evaluates to
- an integer, but the partial expression ``2.5 + a`` does not type check so the code
- does not compile
+ expressions. Disregarding types, the value of the expression assigned to ``b``
+ below evaluates to an integer. Because ``a`` is of type ``uint128``, the
+ expression ``2.5 + a`` has to have a proper type, though. Since there is no common type
+ for the type of ``2.5`` and ``uint128``, the Solidity compiler does not accept
+ this code.
::
@@ -820,13 +830,12 @@ Members
^^^^^^^
**length**:
- Arrays have a ``length`` member to hold their number of elements.
- Dynamic arrays can be resized in storage (not in memory) by changing the
- ``.length`` member. This does not happen automatically when attempting to access elements outside the current length. The size of memory arrays is fixed (but dynamic, i.e. it can depend on runtime parameters) once they are created.
+ Arrays have a ``length`` member to read their number of elements.
+ Dynamically-sized arrays (only available for storage) have a read-write ``length`` member to resize the array. Increasing the length adds uninitialized elements to the array, this has *O(1)* complexity. Reducing the length performs :ref:``delete`` on each removed element and has *O(n)* complexity where *n* is the number of elements being deleted. Please note that calling ``length--`` on an empty array will set the length of the array to 2^256-1 due to ``uint256`` underflow wrapping.
**push**:
Dynamic storage arrays and ``bytes`` (not ``string``) have a member function called ``push`` that can be used to append an element at the end of the array. The function returns the new length.
**pop**:
- Dynamic storage arrays and ``bytes`` (not ``string``) have a member function called ``pop`` that can be used to remove an element from the end of the array.
+ Dynamic storage arrays and ``bytes`` (not ``string``) have a member function called ``pop`` that can be used to remove an element from the end of the array. This will also implicitly call :ref:``delete`` on the removed element.
.. warning::
It is not yet possible to use arrays of arrays in external functions.
@@ -1050,11 +1059,13 @@ If ``a`` is an LValue (i.e. a variable or something that can be assigned to), th
delete
------
-``delete a`` assigns the initial value for the type to ``a``. I.e. for integers it is equivalent to ``a = 0``, but it can also be used on arrays, where it assigns a dynamic array of length zero or a static array of the same length with all elements reset. For structs, it assigns a struct with all members reset.
+``delete a`` assigns the initial value for the type to ``a``. I.e. for integers it is equivalent to ``a = 0``, but it can also be used on arrays, where it assigns a dynamic array of length zero or a static array of the same length with all elements reset. For structs, it assigns a struct with all members reset. In other words, the value of ``a`` after ``delete a`` is the same as if ``a`` would be declared without assignment, with the following caveat:
-``delete`` has no effect on whole mappings (as the keys of mappings may be arbitrary and are generally unknown). So if you delete a struct, it will reset all members that are not mappings and also recurse into the members unless they are mappings. However, individual keys and what they map to can be deleted.
+``delete`` has no effect on mappings (as the keys of mappings may be arbitrary and are generally unknown). So if you delete a struct, it will reset all members that are not mappings and also recurse into the members unless they are mappings. However, individual keys and what they map to can be deleted: If ``a`` is a mapping, then ``delete a[x]`` will delete the value stored at ``x``.
It is important to note that ``delete a`` really behaves like an assignment to ``a``, i.e. it stores a new object in ``a``.
+This distinction is visible when ``a`` is reference variable: It will only reset ``a`` itself, not the
+value it referred to previously.
::
@@ -1067,7 +1078,7 @@ It is important to note that ``delete a`` really behaves like an assignment to `
function f() public {
uint x = data;
delete x; // sets x to 0, does not affect data
- delete data; // sets data to 0, does not affect x which still holds a copy
+ delete data; // sets data to 0, does not affect x
uint[] storage y = dataArray;
delete dataArray; // this sets dataArray.length to zero, but as uint[] is a complex object, also
// y is affected which is an alias to the storage object
@@ -1096,12 +1107,15 @@ makes sense semantically and no information is lost: ``uint8`` is convertible to
(because ``uint256`` cannot hold e.g. ``-1``).
Any integer type that can be converted to ``uint160`` can also be converted to ``address``.
+For more details, please consult the sections about the types themselves.
+
Explicit Conversions
--------------------
If the compiler does not allow implicit conversion but you know what you are
doing, an explicit type conversion is sometimes possible. Note that this may
-give you some unexpected behaviour so be sure to test to ensure that the
+give you some unexpected behaviour and allows you to bypass some security
+features of the compiler, so be sure to test that the
result is what you want! Take the following example where you are converting
a negative ``int8`` to a ``uint``:
@@ -1200,3 +1214,5 @@ Addresses
As described in :ref:`address_literals`, hex literals of the correct size that pass the checksum
test are of ``address`` type. No other literals can be implicitly converted to the ``address`` type.
+
+Explicit conversions from ``bytes20`` or any integer type to ``address`` results in ``address payable``. \ No newline at end of file
diff --git a/docs/units-and-global-variables.rst b/docs/units-and-global-variables.rst
index d6ef393e..7f62e71e 100644
--- a/docs/units-and-global-variables.rst
+++ b/docs/units-and-global-variables.rst
@@ -7,15 +7,25 @@ Units and Globally Available Variables
Ether Units
===========
-A literal number can take a suffix of ``wei``, ``finney``, ``szabo`` or ``ether`` to convert between the subdenominations of Ether, where Ether currency numbers without a postfix are assumed to be Wei, e.g. ``2 ether == 2000 finney`` evaluates to ``true``.
+A literal number can take a suffix of ``wei``, ``finney``, ``szabo`` or ``ether`` to specify a subdenomination of Ether, where Ether numbers without a postfix are assumed to be Wei.
+
+::
+
+ assert(1 wei == 1);
+ assert(1 szabo == 1e12);
+ assert(1 finney == 1e15);
+ assert(1 ether == 1e18);
+
+The only effect of the subdenomination suffix is a multiplication by a power of ten.
+
.. index:: time, seconds, minutes, hours, days, weeks, years
Time Units
==========
-Suffixes like ``seconds``, ``minutes``, ``hours``, ``days``, ``weeks`` and
-``years`` after literal numbers can be used to convert between units of time where seconds are the base
+Suffixes like ``seconds``, ``minutes``, ``hours``, ``days`` and ``weeks``
+after literal numbers can be used to specify units of time where seconds are the base
unit and units are considered naively in the following way:
* ``1 == 1 seconds``
@@ -23,7 +33,6 @@ unit and units are considered naively in the following way:
* ``1 hours == 60 minutes``
* ``1 days == 24 hours``
* ``1 weeks == 7 days``
- * ``1 years == 365 days``
Take care if you perform calendar calculations using these units, because
not every year equals 365 days and not even every day has 24 hours
@@ -32,7 +41,7 @@ Due to the fact that leap seconds cannot be predicted, an exact calendar
library has to be updated by an external oracle.
.. note::
- The suffix ``years`` has been deprecated due to the reasons above and cannot be used starting version 0.5.0.
+ The suffix ``years`` has been removed in version 0.5.0 due to the reasons above.
These suffixes cannot be applied to variables. If you want to
interpret some input variable in e.g. days, you can do it in the following way::
@@ -56,15 +65,14 @@ or are general-use utility functions.
Block and Transaction Properties
--------------------------------
-- ``block.blockhash(uint blockNumber) returns (bytes32)``: hash of the given block - only works for 256 most recent, excluding current, blocks - deprecated in version 0.4.22 and replaced by ``blockhash(uint blockNumber)``.
+- ``blockhash(uint blockNumber) returns (bytes32)``: hash of the given block - only works for 256 most recent, excluding current, blocks
- ``block.coinbase`` (``address payable``): current block miner's address
- ``block.difficulty`` (``uint``): current block difficulty
- ``block.gaslimit`` (``uint``): current block gaslimit
- ``block.number`` (``uint``): current block number
- ``block.timestamp`` (``uint``): current block timestamp as seconds since unix epoch
- ``gasleft() returns (uint256)``: remaining gas
-- ``msg.data`` (``bytes``): complete calldata
-- ``msg.gas`` (``uint``): remaining gas - deprecated in version 0.4.21 and to be replaced by ``gasleft()``
+- ``msg.data`` (``bytes calldata``): complete calldata
- ``msg.sender`` (``address payable``): sender of the message (current call)
- ``msg.sig`` (``bytes4``): first four bytes of the calldata (i.e. function identifier)
- ``msg.value`` (``uint``): number of wei sent with the message
@@ -94,20 +102,28 @@ Block and Transaction Properties
You can only access the hashes of the most recent 256 blocks, all other
values will be zero.
+.. note::
+ The function ``blockhash`` was previously known as ``block.blockhash``. It was deprecated in
+ version 0.4.22 and removed in version 0.5.0.
+
+.. note::
+ The function ``gasleft`` was previously known as ``msg.gas``. It was deprecated in
+ version 0.4.21 and removed in version 0.5.0.
+
.. index:: abi, encoding, packed
ABI Encoding and Decoding Functions
-----------------------------------
-- ``abi.decode(bytes encodedData, (...)) returns (...)``: ABI-decodes the given data, while the types are given in parentheses as second argument. Example: ``(uint a, uint[2] memory b, bytes memory c) = abi.decode(data, (uint, uint[2], bytes))``
-- ``abi.encode(...) returns (bytes)``: ABI-encodes the given arguments
-- ``abi.encodePacked(...) returns (bytes)``: Performs :ref:`packed encoding <abi_packed_mode>` of the given arguments
-- ``abi.encodeWithSelector(bytes4 selector, ...) returns (bytes)``: ABI-encodes the given arguments starting from the second and prepends the given four-byte selector
-- ``abi.encodeWithSignature(string signature, ...) returns (bytes)``: Equivalent to ``abi.encodeWithSelector(bytes4(keccak256(bytes(signature))), ...)```
+- ``abi.decode(bytes memory encodedData, (...)) returns (...)``: ABI-decodes the given data, while the types are given in parentheses as second argument. Example: ``(uint a, uint[2] memory b, bytes memory c) = abi.decode(data, (uint, uint[2], bytes))``
+- ``abi.encode(...) returns (bytes memory)``: ABI-encodes the given arguments
+- ``abi.encodePacked(...) returns (bytes memory)``: Performs :ref:`packed encoding <abi_packed_mode>` of the given arguments
+- ``abi.encodeWithSelector(bytes4 selector, ...) returns (bytes memory)``: ABI-encodes the given arguments starting from the second and prepends the given four-byte selector
+- ``abi.encodeWithSignature(string memory signature, ...) returns (bytes memory)``: Equivalent to ``abi.encodeWithSelector(bytes4(keccak256(bytes(signature))), ...)```
.. note::
- These encoding functions can be used to craft data for function calls without actually
- calling a function. Furthermore, ``keccak256(abi.encodePacked(a, b))`` is a way
+ These encoding functions can be used to craft data for external function calls without actually
+ calling an external function. Furthermore, ``keccak256(abi.encodePacked(a, b))`` is a way
to compute the hash of structured data (although be aware that it is possible to
craft a "hash collision" using different inputs types).
@@ -119,15 +135,18 @@ See the documentation about the :ref:`ABI <ABI>` and the
Error Handling
--------------
+See the dedicated section on :ref:`assert and require<assert-and-require>` for
+more details on error handling and when to use which function.
+
``assert(bool condition)``:
- invalidates the transaction if the condition is not met - to be used for internal errors.
+ causes an invalid opcode and thus state change reversion if the condition is not met - to be used for internal errors.
``require(bool condition)``:
reverts if the condition is not met - to be used for errors in inputs or external components.
-``require(bool condition, string message)``:
+``require(bool condition, string memory message)``:
reverts if the condition is not met - to be used for errors in inputs or external components. Also provides an error message.
``revert()``:
abort execution and revert state changes
-``revert(string reason)``:
+``revert(string memory reason)``:
abort execution and revert state changes, providing an explanatory string
.. index:: keccak256, ripemd160, sha256, ecrecover, addmod, mulmod, cryptography,
@@ -140,11 +159,9 @@ 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``. Assert that ``k != 0`` starting from version 0.5.0.
``keccak256(bytes memory) returns (bytes32)``:
- compute the Ethereum-SHA-3 (Keccak-256) hash of the input
+ compute the Keccak-256 hash of the input
``sha256(bytes memory) returns (bytes32)``:
compute the SHA-256 hash of the input
-``sha3(bytes memory) returns (bytes32)``:
- alias to ``keccak256``
``ripemd160(bytes memory) returns (bytes20)``:
compute RIPEMD-160 hash of the input
``ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)``:
@@ -158,26 +175,27 @@ Mathematical and Cryptographic Functions
It might be that you run into Out-of-Gas for ``sha256``, ``ripemd160`` or ``ecrecover`` on a *private blockchain*. The reason for this is that those are implemented as so-called precompiled contracts and these contracts only really exist after they received the first message (although their contract code is hardcoded). Messages to non-existing contracts are more expensive and thus the execution runs into an Out-of-Gas error. A workaround for this problem is to first send e.g. 1 Wei to each of the contracts before you use them in your actual contracts. This is not an issue on the official or test net.
+.. note::
+ There used to be an alias for ``keccak256`` called ``sha3``, which was removed in version 0.5.0.
+
.. index:: balance, send, transfer, call, callcode, delegatecall, staticcall
.. _address_related:
-Address Related
----------------
+Members of Address Types
+------------------------
``<address>.balance`` (``uint256``):
balance of the :ref:`address` in Wei
``<address payable>.transfer(uint256 amount)``:
- send given amount of Wei to :ref:`address`, throws on failure, forwards 2300 gas stipend, not adjustable
+ send given amount of Wei to :ref:`address`, reverts on failure, forwards 2300 gas stipend, not adjustable
``<address payable>.send(uint256 amount) returns (bool)``:
send given amount of Wei to :ref:`address`, returns ``false`` on failure, forwards 2300 gas stipend, not adjustable
-``<address>.call(bytes memory) returns (bool)``:
- issue low-level ``CALL`` with the given payload, returns ``false`` on failure, forwards all available gas, adjustable
-``<address>.callcode(bytes memory) returns (bool)``:
- issue low-level ``CALLCODE`` with the given payload, returns ``false`` on failure, forwards all available gas, adjustable
-``<address>.delegatecall(bytes memory) returns (bool)``:
- issue low-level ``DELEGATECALL`` with the given payload, returns ``false`` on failure, forwards all available gas, adjustable
-``<address>.staticcall(bytes memory) returns (bool)``:
- issue low-level ``STATICCALL`` with the given payload, returns ``false`` on failure, forwards all available gas, adjustable
+``<address>.call(bytes memory) returns (bool, bytes memory)``:
+ issue low-level ``CALL`` with the given payload, returns success condition and return data, forwards all available gas, adjustable
+``<address>.delegatecall(bytes memory) returns (bool, bytes memory)``:
+ issue low-level ``DELEGATECALL`` with the given payload, returns success condition and return data, forwards all available gas, adjustable
+``<address>.staticcall(bytes memory) returns (bool, bytes memory)``:
+ issue low-level ``STATICCALL`` with the given payload, returns success condition and return data, forwards all available gas, adjustable
For more information, see the section on :ref:`address`.
@@ -192,14 +210,19 @@ For more information, see the section on :ref:`address`.
This is now forbidden and an explicit conversion to address must be done: ``address(this).balance``.
.. note::
- If storage variables are accessed via a low-level delegatecall, the storage layout of the two contracts
+ If state variables are accessed via a low-level delegatecall, the storage layout of the two contracts
must align in order for the called contract to correctly access the storage variables of the calling contract by name.
This is of course not the case if storage pointers are passed as function arguments as in the case for
the high-level libraries.
+.. note::
+ Prior to version 0.5.0, ``.call``, ``.delegatecall`` and ``.staticcall`` only returned the
+ success condition and not the return data.
.. note::
- The use of ``callcode`` is discouraged and will be removed in the future.
+ Prior to version 0.5.0, there was a member called ``callcode`` with similar but slightly different
+ semantics than ``delegatecall``.
+
.. index:: this, selfdestruct
@@ -212,8 +235,9 @@ Contract Related
``selfdestruct(address payable recipient)``:
destroy the current contract, sending its funds to the given :ref:`address`
-``suicide(address payable recipient)``:
- deprecated alias to ``selfdestruct``
-
Furthermore, all functions of the current contract are callable directly including the current function.
+.. note::
+ Prior to version 0.5.0, there was a function called ``suicide`` with the same
+ semantics as ``selfdestruct``.
+
diff --git a/libsolidity/analysis/SemVerHandler.cpp b/libsolidity/analysis/SemVerHandler.cpp
index 42186396..29f6d5de 100644
--- a/libsolidity/analysis/SemVerHandler.cpp
+++ b/libsolidity/analysis/SemVerHandler.cpp
@@ -106,18 +106,22 @@ bool SemVerMatchExpression::MatchComponent::matches(SemVerVersion const& _versio
}
if (cmp == 0 && !_version.prerelease.empty() && didCompare)
cmp = -1;
- if (prefix == Token::Assign)
+
+ switch (prefix)
+ {
+ case Token::Assign:
return cmp == 0;
- else if (prefix == Token::LessThan)
+ case Token::LessThan:
return cmp < 0;
- else if (prefix == Token::LessThanOrEqual)
+ case Token::LessThanOrEqual:
return cmp <= 0;
- else if (prefix == Token::GreaterThan)
+ case Token::GreaterThan:
return cmp > 0;
- else if (prefix == Token::GreaterThanOrEqual)
+ case Token::GreaterThanOrEqual:
return cmp >= 0;
- else
+ default:
solAssert(false, "Invalid SemVer expression");
+ }
return false;
}
}
@@ -196,21 +200,22 @@ SemVerMatchExpression::MatchComponent SemVerMatchExpressionParser::parseMatchCom
{
SemVerMatchExpression::MatchComponent component;
Token::Value token = currentToken();
- if (
- token == Token::BitXor ||
- token == Token::BitNot ||
- token == Token::LessThan ||
- token == Token::LessThanOrEqual||
- token == Token::GreaterThan ||
- token == Token::GreaterThanOrEqual ||
- token == Token::Assign
- )
+
+ switch (token)
{
+ case Token::BitXor:
+ case Token::BitNot:
+ case Token::LessThan:
+ case Token::LessThanOrEqual:
+ case Token::GreaterThan:
+ case Token::GreaterThanOrEqual:
+ case Token::Assign:
component.prefix = token;
nextToken();
- }
- else
+ break;
+ default:
component.prefix = Token::Assign;
+ }
component.levelsPresent = 0;
while (component.levelsPresent < 3)
diff --git a/libsolidity/analysis/TypeChecker.cpp b/libsolidity/analysis/TypeChecker.cpp
index 3056561b..c42a0068 100644
--- a/libsolidity/analysis/TypeChecker.cpp
+++ b/libsolidity/analysis/TypeChecker.cpp
@@ -1778,9 +1778,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
}
if (resultType->category() == Type::Category::Address)
{
- bool payable = true;
- if (auto const* contractType = dynamic_cast<ContractType const*>(argType.get()))
- payable = contractType->isPayable();
+ bool payable = argType->isExplicitlyConvertibleTo(AddressType::addressPayable());
resultType = make_shared<AddressType>(payable ? StateMutability::Payable : StateMutability::NonPayable);
}
}
diff --git a/libsolidity/ast/Types.cpp b/libsolidity/ast/Types.cpp
index 25702f19..f49e1222 100644
--- a/libsolidity/ast/Types.cpp
+++ b/libsolidity/ast/Types.cpp
@@ -2126,8 +2126,11 @@ bool StructType::canBeUsedExternally(bool _inLibrary) const
// passed by value and thus the encoding does not differ, but it will disallow
// mappings.
for (auto const& var: m_struct.members())
+ {
+ solAssert(var->annotation().type, "");
if (!var->annotation().type->canBeUsedExternally(false))
return false;
+ }
}
return true;
}
@@ -2429,7 +2432,7 @@ FunctionType::FunctionType(VariableDeclaration const& _varDecl):
else if (auto arrayType = dynamic_cast<ArrayType const*>(returnType.get()))
{
if (arrayType->isByteArray())
- // Return byte arrays as as whole.
+ // Return byte arrays as whole.
break;
returnType = arrayType->baseType();
m_parameterNames.push_back("");
@@ -2641,8 +2644,8 @@ bool FunctionType::operator==(Type const& _other) const
bool FunctionType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
- if (m_kind == Kind::External && _convertTo.category() == Category::Address)
- return true;
+ if (m_kind == Kind::External && _convertTo == AddressType::address())
+ return true;
return _convertTo.category() == category();
}
diff --git a/libsolidity/ast/Types.h b/libsolidity/ast/Types.h
index 65a70019..0f3373a1 100644
--- a/libsolidity/ast/Types.h
+++ b/libsolidity/ast/Types.h
@@ -174,7 +174,7 @@ public:
/// Will not contain any character which would be invalid as an identifier.
std::string identifier() const;
- /// More complex identifier strings use "parentheses", where $_ is interpreted as as
+ /// More complex identifier strings use "parentheses", where $_ is interpreted as
/// "opening parenthesis", _$ as "closing parenthesis", _$_ as "comma" and any $ that
/// appears as part of a user-supplied identifier is escaped as _$$$_.
/// @returns an escaped identifier (will not contain any parenthesis or commas)
diff --git a/libsolidity/codegen/ExpressionCompiler.cpp b/libsolidity/codegen/ExpressionCompiler.cpp
index 8645f653..587cf34a 100644
--- a/libsolidity/codegen/ExpressionCompiler.cpp
+++ b/libsolidity/codegen/ExpressionCompiler.cpp
@@ -1230,7 +1230,7 @@ bool ExpressionCompiler::visit(MemberAccess const& _memberAccess)
else
solAssert(false, "Contract member is neither variable nor function.");
m_context << identifier;
- /// need to store store it as bytes4
+ /// need to store it as bytes4
utils().leftShiftNumberOnStack(224);
return false;
}
@@ -1305,7 +1305,7 @@ bool ExpressionCompiler::visit(MemberAccess const& _memberAccess)
if (member == "selector")
{
m_context << Instruction::SWAP1 << Instruction::POP;
- /// need to store store it as bytes4
+ /// need to store it as bytes4
utils().leftShiftNumberOnStack(224);
}
else
@@ -1975,7 +1975,7 @@ void ExpressionCompiler::appendExternalFunctionCall(
m_context << dupInstruction(m_context.baseToCurrentStackOffset(contractStackPos));
bool existenceChecked = false;
- // Check the the target contract exists (has code) for non-low-level calls.
+ // Check the target contract exists (has code) for non-low-level calls.
if (funKind == FunctionType::Kind::External || funKind == FunctionType::Kind::DelegateCall)
{
m_context << Instruction::DUP1 << Instruction::EXTCODESIZE << Instruction::ISZERO;
diff --git a/libsolidity/inlineasm/AsmCodeGen.h b/libsolidity/inlineasm/AsmCodeGen.h
index a7d7ead1..277e1879 100644
--- a/libsolidity/inlineasm/AsmCodeGen.h
+++ b/libsolidity/inlineasm/AsmCodeGen.h
@@ -41,7 +41,7 @@ struct Block;
class CodeGenerator
{
public:
- /// Performs code generation and appends generated to to _assembly.
+ /// Performs code generation and appends generated to _assembly.
static void assemble(
Block const& _parsedData,
AsmAnalysisInfo& _analysisInfo,
diff --git a/libsolidity/interface/StandardCompiler.cpp b/libsolidity/interface/StandardCompiler.cpp
index c1996777..b53c5a5e 100644
--- a/libsolidity/interface/StandardCompiler.cpp
+++ b/libsolidity/interface/StandardCompiler.cpp
@@ -280,6 +280,8 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input)
for (auto const& url: sources[sourceName]["urls"])
{
+ if (!url.isString())
+ return formatFatalError("JSONError", "URL must be a string.");
ReadCallback::Result result = m_readFile(url.asString());
if (result.success)
{
@@ -320,7 +322,9 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input)
if (settings.isMember("evmVersion"))
{
- boost::optional<EVMVersion> version = EVMVersion::fromString(settings.get("evmVersion", {}).asString());
+ if (!settings["evmVersion"].isString())
+ return formatFatalError("JSONError", "evmVersion must be a string.");
+ boost::optional<EVMVersion> version = EVMVersion::fromString(settings["evmVersion"].asString());
if (!version)
return formatFatalError("JSONError", "Invalid EVM version requested.");
m_compilerStack.setEVMVersion(*version);
@@ -329,6 +333,8 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input)
vector<CompilerStack::Remapping> remappings;
for (auto const& remapping: settings.get("remappings", Json::Value()))
{
+ if (!remapping.isString())
+ return formatFatalError("JSONError", "Remapping entry must be a string.");
if (auto r = CompilerStack::parseRemapping(remapping.asString()))
remappings.emplace_back(std::move(*r));
else
@@ -349,9 +355,11 @@ Json::Value StandardCompiler::compileInternal(Json::Value const& _input)
{
auto const& jsonSourceName = jsonLibraries[sourceName];
if (!jsonSourceName.isObject())
- return formatFatalError("JSONError", "library entry is not a JSON object.");
+ return formatFatalError("JSONError", "Library entry is not a JSON object.");
for (auto const& library: jsonSourceName.getMemberNames())
{
+ if (!jsonSourceName[library].isString())
+ return formatFatalError("JSONError", "Library address must be a string.");
string address = jsonSourceName[library].asString();
if (!boost::starts_with(address, "0x"))
diff --git a/test/libsolidity/StandardCompiler.cpp b/test/libsolidity/StandardCompiler.cpp
index 3aa1dc24..d34bacda 100644
--- a/test/libsolidity/StandardCompiler.cpp
+++ b/test/libsolidity/StandardCompiler.cpp
@@ -640,7 +640,7 @@ BOOST_AUTO_TEST_CASE(libraries_invalid_entry)
}
)";
Json::Value result = compile(input);
- BOOST_CHECK(containsError(result, "JSONError", "library entry is not a JSON object."));
+ BOOST_CHECK(containsError(result, "JSONError", "Library entry is not a JSON object."));
}
BOOST_AUTO_TEST_CASE(libraries_invalid_hex)
diff --git a/test/libsolidity/syntaxTests/functionTypes/external_function_type_to_address_payable.sol b/test/libsolidity/syntaxTests/functionTypes/external_function_type_to_address_payable.sol
new file mode 100644
index 00000000..adffb14b
--- /dev/null
+++ b/test/libsolidity/syntaxTests/functionTypes/external_function_type_to_address_payable.sol
@@ -0,0 +1,7 @@
+contract C {
+ function f() public view returns (address payable) {
+ return address(this.f);
+ }
+}
+// ----
+// TypeError: (85-100): Return argument type address is not implicitly convertible to expected type (type of first return variable) address payable.
diff --git a/test/libsolidity/syntaxTests/types/address/address_to_payable_address_double.sol b/test/libsolidity/syntaxTests/types/address/address_to_payable_address_double.sol
new file mode 100644
index 00000000..1e755033
--- /dev/null
+++ b/test/libsolidity/syntaxTests/types/address/address_to_payable_address_double.sol
@@ -0,0 +1,7 @@
+contract C {
+ function f(address a) public pure returns (address payable) {
+ return address(address(a));
+ }
+}
+// ----
+// TypeError: (94-113): Return argument type address is not implicitly convertible to expected type (type of first return variable) address payable.
diff --git a/test/libsolidity/syntaxTests/types/address/bytes_long_to_payable_address.sol b/test/libsolidity/syntaxTests/types/address/bytes_long_to_payable_address.sol
new file mode 100644
index 00000000..ef87ac55
--- /dev/null
+++ b/test/libsolidity/syntaxTests/types/address/bytes_long_to_payable_address.sol
@@ -0,0 +1,8 @@
+contract C {
+ function f(bytes32 x) public pure returns (address payable) {
+ return address(x);
+ }
+}
+// ----
+// TypeError: (94-104): Explicit type conversion not allowed from "bytes32" to "address".
+// TypeError: (94-104): Return argument type address is not implicitly convertible to expected type (type of first return variable) address payable.
diff --git a/test/libsolidity/syntaxTests/types/address/bytes_short_to_payable_address.sol b/test/libsolidity/syntaxTests/types/address/bytes_short_to_payable_address.sol
new file mode 100644
index 00000000..2aa60251
--- /dev/null
+++ b/test/libsolidity/syntaxTests/types/address/bytes_short_to_payable_address.sol
@@ -0,0 +1,8 @@
+contract C {
+ function f(bytes10 x) public pure returns (address payable) {
+ return address(x);
+ }
+}
+// ----
+// TypeError: (94-104): Explicit type conversion not allowed from "bytes10" to "address".
+// TypeError: (94-104): Return argument type address is not implicitly convertible to expected type (type of first return variable) address payable.
diff --git a/test/libsolidity/syntaxTests/types/address/bytes_to_payable_address.sol b/test/libsolidity/syntaxTests/types/address/bytes_to_payable_address.sol
new file mode 100644
index 00000000..5b6a6714
--- /dev/null
+++ b/test/libsolidity/syntaxTests/types/address/bytes_to_payable_address.sol
@@ -0,0 +1,5 @@
+contract C {
+ function f(bytes20 x) public pure returns (address payable) {
+ return address(x);
+ }
+}
diff --git a/test/libsolidity/syntaxTests/types/address/uint_to_payable_address.sol b/test/libsolidity/syntaxTests/types/address/uint_to_payable_address.sol
new file mode 100644
index 00000000..9a33985a
--- /dev/null
+++ b/test/libsolidity/syntaxTests/types/address/uint_to_payable_address.sol
@@ -0,0 +1,5 @@
+contract C {
+ function f(uint x) public pure returns (address payable) {
+ return address(x);
+ }
+}