diff options
75 files changed, 1208 insertions, 520 deletions
diff --git a/Changelog.md b/Changelog.md index 1cb96833..7c4ac925 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,11 +2,13 @@ Features: * Build System: Update internal dependency of jsoncpp to 1.8.4, which introduces more strictness and reduces memory usage. + * Code Generator: Use native shift instructions on target Constantinople. * Optimizer: Remove unnecessary masking of the result of known short instructions (``ADDRESS``, ``CALLER``, ``ORIGIN`` and ``COINBASE``). * Type Checker: Deprecate the ``years`` unit denomination and raise a warning for it (or an error as experimental 0.5.0 feature). * Type Checker: Make literals (without explicit type casting) an error for tight packing as experimental 0.5.0 feature. Bugfixes: + * Type Checker: Show proper error when trying to ``emit`` a non-event. * Type Checker: Warn about empty tuple components (this will turn into an error with version 0.5.0). @@ -4,6 +4,32 @@ defaults: filters: tags: only: /.*/ + - setup_prerelease_commit_hash: &setup_prerelease_commit_hash + name: Store commit hash and prerelease + command: | + if [ "$CIRCLE_BRANCH" = release -o -n "$CIRCLE_TAG" ]; then echo -n > prerelease.txt; else date -u +"nightly.%Y.%-m.%-d" > prerelease.txt; fi + echo -n "$CIRCLE_SHA1" > commit_hash.txt + - run_build: &run_build + name: Build + command: | + mkdir -p build + cd build + cmake .. -DCMAKE_BUILD_TYPE=RelWithDebInfo + make -j4 + - run_tests: &run_tests + name: Tests + command: scripts/tests.sh --junit_report test_results + environment: + TERM: dumb + - solc_artifact: &solc_artifact + path: build/solc/solc + destination: solc + - all_artifacts: &all_artifacts + root: build + paths: + - solc/solc + - test/soltest + - test/tools/solfuzzer version: 2 jobs: @@ -87,7 +113,7 @@ jobs: command: | . /usr/local/nvm/nvm.sh test/externalTests.sh /tmp/workspace/soljson.js || test/externalTests.sh /tmp/workspace/soljson.js - build_x86: + build_x86_linux: docker: - image: buildpack-deps:artful steps: @@ -97,29 +123,31 @@ jobs: command: | apt-get -qq update apt-get -qy install cmake libboost-regex-dev libboost-filesystem-dev libboost-test-dev libboost-system-dev libboost-program-options-dev libz3-dev + - run: *setup_prerelease_commit_hash + - run: *run_build + - store_artifacts: *solc_artifact + - persist_to_workspace: *all_artifacts + + build_x86_mac: + macos: + xcode: "9.0" + steps: + - checkout - run: - name: Store commit hash and prerelease - command: | - if [ "$CIRCLE_BRANCH" = release -o -n "$CIRCLE_TAG" ]; then echo -n > prerelease.txt; else date -u +"nightly.%Y.%-m.%-d" > prerelease.txt; fi - echo -n "$CIRCLE_SHA1" > commit_hash.txt - - run: - name: Build + name: Install build dependencies command: | - mkdir -p build - cd build - cmake .. -DCMAKE_BUILD_TYPE=RelWithDebInfo - make -j4 - - store_artifacts: - path: build/solc/solc - destination: solc - - persist_to_workspace: - root: build - paths: - - solc/solc - - test/soltest - - test/tools/solfuzzer + brew update + brew upgrade + brew unlink python + brew install z3 + brew install boost + brew install cmake + - run: *setup_prerelease_commit_hash + - run: *run_build + - store_artifacts: *solc_artifact + - persist_to_workspace: *all_artifacts - test_x86: + test_x86_linux: docker: - image: buildpack-deps:artful steps: @@ -132,9 +160,26 @@ jobs: apt-get -qq update apt-get -qy install libz3-dev libleveldb1v5 - run: mkdir -p test_results + - run: *run_tests + - store_test_results: + path: test_results/ + + test_x86_mac: + macos: + xcode: "9.0" + steps: + - checkout + - attach_workspace: + at: build - run: - name: Tests - command: scripts/tests.sh --junit_report test_results + name: Install dependencies + command: | + brew update + brew upgrade + brew unlink python + brew install z3 + - run: mkdir -p test_results + - run: *run_tests - store_test_results: path: test_results/ @@ -148,11 +193,7 @@ jobs: command: | apt-get -qq update apt-get -qy install python-sphinx - - run: - name: Store commit hash and prerelease - command: | - if [ "$CIRCLE_BRANCH" = release -o -n "$CIRCLE_TAG" ]; then echo -n > prerelease.txt; else date -u +"nightly.%Y.%-m.%-d" > prerelease.txt; fi - echo -n "$CIRCLE_SHA1" > commit_hash.txt + - run: *setup_prerelease_commit_hash - run: name: Build documentation command: ./scripts/docs.sh @@ -173,9 +214,14 @@ workflows: <<: *build_on_tags requires: - build_emscripten - - build_x86: *build_on_tags - - test_x86: + - build_x86_linux: *build_on_tags + - build_x86_mac: *build_on_tags + - test_x86_linux: + <<: *build_on_tags + requires: + - build_x86_linux + - test_x86_mac: <<: *build_on_tags requires: - - build_x86 + - build_x86_mac - docs: *build_on_tags diff --git a/docs/abi-spec.rst b/docs/abi-spec.rst index 98301fdc..8591a07f 100644 --- a/docs/abi-spec.rst +++ b/docs/abi-spec.rst @@ -62,7 +62,7 @@ The following elementary types exist: The following (fixed-size) array type exists: -- ``<type>[M]``: a fixed-length array of ``M`` elements, ``M > 0``, of the given type. +- ``<type>[M]``: a fixed-length array of ``M`` elements, ``M >= 0``, of the given type. The following non-fixed-size types exist: @@ -77,7 +77,7 @@ of them inside parentheses, separated by commas: - ``(T1,T2,...,Tn)``: tuple consisting of the types ``T1``, ..., ``Tn``, ``n >= 0`` -It is possible to form tuples of tuples, arrays of tuples and so on. +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``. @@ -101,8 +101,8 @@ We distinguish static and dynamic types. Static types are encoded in-place and d * ``bytes`` * ``string`` * ``T[]`` for any ``T`` -* ``T[k]`` for any dynamic ``T`` and any ``k > 0`` -* ``(T1,...,Tk)`` if any ``Ti`` is dynamic for ``1 <= i <= k`` +* ``T[k]`` for any dynamic ``T`` and any ``k >= 0`` +* ``(T1,...,Tk)`` if ``Ti`` is dynamic for some ``1 <= i <= k`` All other types are called "static". @@ -117,16 +117,16 @@ on the type of ``X`` being - ``(T1,...,Tk)`` for ``k >= 0`` and any types ``T1``, ..., ``Tk`` - ``enc(X) = head(X(1)) ... head(X(k-1)) tail(X(0)) ... tail(X(k-1))`` + ``enc(X) = head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(k))`` - where ``X(i)`` is the ``ith`` component of the value, and + where ``X = (X(1), ..., X(k))`` and ``head`` and ``tail`` are defined for ``Ti`` being a static type as ``head(X(i)) = enc(X(i))`` and ``tail(X(i)) = ""`` (the empty string) and as - ``head(X(i)) = enc(len(head(X(0)) ... head(X(k-1)) tail(X(0)) ... tail(X(i-1))))`` + ``head(X(i)) = enc(len(head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(i-1)) ))`` ``tail(X(i)) = enc(X(i))`` otherwise, i.e. if ``Ti`` is a dynamic type. @@ -144,7 +144,7 @@ on the type of ``X`` being - ``T[]`` where ``X`` has ``k`` elements (``k`` is assumed to be of type ``uint256``): - ``enc(X) = enc(k) enc([X[1], ..., X[k]])`` + ``enc(X) = enc(k) enc([X[0], ..., X[k-1]])`` i.e. it is encoded as if it were an array of static size ``k``, prefixed with the number of elements. diff --git a/docs/installing-solidity.rst b/docs/installing-solidity.rst index 6726ded9..cba30ed3 100644 --- a/docs/installing-solidity.rst +++ b/docs/installing-solidity.rst @@ -203,19 +203,38 @@ Prerequisites - Windows You will need to install the following dependencies for Windows builds of Solidity: -+------------------------------+-------------------------------------------------------+ -| Software | Notes | -+==============================+=======================================================+ -| `Git for Windows`_ | Command-line tool for retrieving source from Github. | -+------------------------------+-------------------------------------------------------+ -| `CMake`_ | Cross-platform build file generator. | -+------------------------------+-------------------------------------------------------+ -| `Visual Studio 2015`_ | C++ compiler and dev environment. | -+------------------------------+-------------------------------------------------------+ ++-----------------------------------+-------------------------------------------------------+ +| Software | Notes | ++===================================+=======================================================+ +| `Git for Windows`_ | Command-line tool for retrieving source from Github. | ++-----------------------------------+-------------------------------------------------------+ +| `CMake`_ | Cross-platform build file generator. | ++-----------------------------------+-------------------------------------------------------+ +| `Visual Studio 2017 Build Tools`_ | C++ compiler | ++-----------------------------------+-------------------------------------------------------+ +| `Visual Studio 2017`_ (Optional) | C++ compiler and dev environment. | ++-----------------------------------+-------------------------------------------------------+ + +If you've already had one IDE and only need compiler and libraries, +you could install Visual Studio 2017 Build Tools. + +Visual Studio 2017 provides both IDE and necessary compiler and libraries. +So if you have not got an IDE and prefer to develop solidity, Visual Studio 2017 +may be an choice for you to get everything setup easily. + +Here is the list of components that should be installed +in Visual Studio 2017 Build Tools or Visual Studio 2017: + +* Visual Studio C++ core features +* VC++ 2017 v141 toolset (x86,x64) +* Windows Universal CRT SDK +* Windows 8.1 SDK +* C++/CLI support .. _Git for Windows: https://git-scm.com/download/win .. _CMake: https://cmake.org/download/ -.. _Visual Studio 2015: https://www.visualstudio.com/products/vs-2015-product-editions +.. _Visual Studio 2017: https://www.visualstudio.com/vs/ +.. _Visual Studio 2017 Build Tools: https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017 External Dependencies @@ -263,7 +282,7 @@ And even for Windows: mkdir build cd build - cmake -G "Visual Studio 14 2015 Win64" .. + cmake -G "Visual Studio 15 2017 Win64" .. This latter set of instructions should result in the creation of **solidity.sln** in that build directory. Double-clicking on that file diff --git a/docs/units-and-global-variables.rst b/docs/units-and-global-variables.rst index 51f7b9f3..4cb34fbd 100644 --- a/docs/units-and-global-variables.rst +++ b/docs/units-and-global-variables.rst @@ -31,6 +31,9 @@ because of `leap seconds <https://en.wikipedia.org/wiki/Leap_second>`_. 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. + 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:: diff --git a/docs/using-the-compiler.rst b/docs/using-the-compiler.rst index df30b6b4..1d7cb97b 100644 --- a/docs/using-the-compiler.rst +++ b/docs/using-the-compiler.rst @@ -14,7 +14,9 @@ Using the Commandline Compiler One of the build targets of the Solidity repository is ``solc``, the solidity commandline compiler. Using ``solc --help`` provides you with an explanation of all options. The compiler can produce various outputs, ranging from simple binaries and assembly over an abstract syntax tree (parse tree) to estimations of gas usage. -If you only want to compile a single file, you run it as ``solc --bin sourceFile.sol`` and it will print the binary. Before you deploy your contract, activate the optimizer while compiling using ``solc --optimize --bin sourceFile.sol``. If you want to get some of the more advanced output variants of ``solc``, it is probably better to tell it to output everything to separate files using ``solc -o outputDirectory --bin --ast --asm sourceFile.sol``. +If you only want to compile a single file, you run it as ``solc --bin sourceFile.sol`` and it will print the binary. If you want to get some of the more advanced output variants of ``solc``, it is probably better to tell it to output everything to separate files using ``solc -o outputDirectory --bin --ast --asm sourceFile.sol``. + +Before you deploy your contract, activate the optimizer while compiling using ``solc --optimize --bin sourceFile.sol``. By default, the optimizer will optimize the contract for 200 runs. If you want to optimize for initial contract deployment and get the smallest output, set it to ``--runs=1``. If you expect many transactions and don't care for higher deployment cost and output size, set ``--runs`` to a high number. The commandline compiler will automatically read imported files from the filesystem, but it is also possible to provide path redirects using ``prefix=path`` in the following way: @@ -96,10 +98,13 @@ Input Description { // Optional: Sorted list of remappings remappings: [ ":g/dir" ], - // Optional: Optimizer settings (enabled defaults to false) + // Optional: Optimizer settings optimizer: { + // disabled by default enabled: true, - runs: 500 + // Optimize for how many times you intend to run the code. + // Lower values will optimize more for initial deployment cost, higher values will optimize more for high-frequency usage. + runs: 200 }, evmVersion: "byzantium", // Version of the EVM to compile for. Affects type checking and code generation. Can be homestead, tangerineWhistle, spuriousDragon, byzantium or constantinople // Metadata settings (optional) diff --git a/libevmasm/Assembly.h b/libevmasm/Assembly.h index 367c6daa..1ed9b859 100644 --- a/libevmasm/Assembly.h +++ b/libevmasm/Assembly.h @@ -47,8 +47,8 @@ class Assembly public: Assembly() {} - AssemblyItem newTag() { return AssemblyItem(Tag, m_usedTags++); } - AssemblyItem newPushTag() { return AssemblyItem(PushTag, m_usedTags++); } + AssemblyItem newTag() { assertThrow(m_usedTags < 0xffffffff, AssemblyException, ""); return AssemblyItem(Tag, m_usedTags++); } + AssemblyItem newPushTag() { assertThrow(m_usedTags < 0xffffffff, AssemblyException, ""); return AssemblyItem(PushTag, m_usedTags++); } /// Returns a tag identified by the given name. Creates it if it does not yet exist. AssemblyItem namedTag(std::string const& _name); AssemblyItem newData(bytes const& _data) { h256 h(dev::keccak256(asString(_data))); m_data[h] = _data; return AssemblyItem(PushData, h); } diff --git a/libevmasm/ConstantOptimiser.h b/libevmasm/ConstantOptimiser.h index 9b60b26b..f0deb387 100644 --- a/libevmasm/ConstantOptimiser.h +++ b/libevmasm/ConstantOptimiser.h @@ -67,6 +67,7 @@ public: explicit ConstantOptimisationMethod(Params const& _params, u256 const& _value): m_params(_params), m_value(_value) {} + virtual ~ConstantOptimisationMethod() = default; virtual bigint gasNeeded() const = 0; /// Executes the method, potentially appending to the assembly and returns a vector of /// assembly items the constant should be relpaced with in one sweep. diff --git a/libevmasm/PeepholeOptimiser.h b/libevmasm/PeepholeOptimiser.h index a74cc8b3..a651143d 100644 --- a/libevmasm/PeepholeOptimiser.h +++ b/libevmasm/PeepholeOptimiser.h @@ -34,6 +34,7 @@ using AssemblyItems = std::vector<AssemblyItem>; class PeepholeOptimisationMethod { public: + virtual ~PeepholeOptimisationMethod() = default; virtual size_t windowSize() const; virtual bool apply(AssemblyItems::const_iterator _in, std::back_insert_iterator<AssemblyItems> _out); }; @@ -42,6 +43,7 @@ class PeepholeOptimiser { public: explicit PeepholeOptimiser(AssemblyItems& _items): m_items(_items) {} + virtual ~PeepholeOptimiser() = default; bool optimise(); diff --git a/libjulia/optimiser/ASTCopier.h b/libjulia/optimiser/ASTCopier.h index 36a1ced5..8681f2e0 100644 --- a/libjulia/optimiser/ASTCopier.h +++ b/libjulia/optimiser/ASTCopier.h @@ -37,6 +37,7 @@ namespace julia class ExpressionCopier: public boost::static_visitor<Expression> { public: + virtual ~ExpressionCopier() = default; virtual Expression operator()(Literal const& _literal) = 0; virtual Expression operator()(Identifier const& _identifier) = 0; virtual Expression operator()(FunctionalInstruction const& _instr) = 0; @@ -46,6 +47,7 @@ public: class StatementCopier: public boost::static_visitor<Statement> { public: + virtual ~StatementCopier() = default; virtual Statement operator()(ExpressionStatement const& _statement) = 0; virtual Statement operator()(Instruction const& _instruction) = 0; virtual Statement operator()(Label const& _label) = 0; @@ -66,6 +68,7 @@ public: class ASTCopier: public ExpressionCopier, public StatementCopier { public: + virtual ~ASTCopier() = default; virtual Expression operator()(Literal const& _literal) override; virtual Statement operator()(Instruction const& _instruction) override; virtual Expression operator()(Identifier const& _identifier) override; diff --git a/libjulia/optimiser/ASTWalker.h b/libjulia/optimiser/ASTWalker.h index 97891381..f09c2ff1 100644 --- a/libjulia/optimiser/ASTWalker.h +++ b/libjulia/optimiser/ASTWalker.h @@ -42,6 +42,7 @@ namespace julia class ASTWalker: public boost::static_visitor<> { public: + virtual ~ASTWalker() = default; virtual void operator()(Literal const&) {} virtual void operator()(Instruction const&) { solAssert(false, ""); } virtual void operator()(Identifier const&) {} @@ -82,6 +83,7 @@ protected: class ASTModifier: public boost::static_visitor<> { public: + virtual ~ASTModifier() = default; virtual void operator()(Literal&) {} virtual void operator()(Instruction&) { solAssert(false, ""); } virtual void operator()(Identifier&) {} diff --git a/libjulia/optimiser/FullInliner.cpp b/libjulia/optimiser/FullInliner.cpp new file mode 100644 index 00000000..05d70729 --- /dev/null +++ b/libjulia/optimiser/FullInliner.cpp @@ -0,0 +1,262 @@ +/* + 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/>. +*/ +/** + * Optimiser component that performs function inlining for arbitrary functions. + */ + +#include <libjulia/optimiser/FullInliner.h> + +#include <libjulia/optimiser/ASTCopier.h> +#include <libjulia/optimiser/ASTWalker.h> +#include <libjulia/optimiser/NameCollector.h> +#include <libjulia/optimiser/Semantics.h> + +#include <libsolidity/inlineasm/AsmData.h> + +#include <libsolidity/interface/Exceptions.h> + +#include <libdevcore/CommonData.h> + +#include <boost/range/adaptor/reversed.hpp> + +using namespace std; +using namespace dev; +using namespace dev::julia; +using namespace dev::solidity; + + + +FullInliner::FullInliner(Block& _ast): + m_ast(_ast) +{ + solAssert(m_ast.statements.size() >= 1, ""); + solAssert(m_ast.statements.front().type() == typeid(Block), ""); + m_nameDispenser.m_usedNames = NameCollector(m_ast).names(); + + for (size_t i = 1; i < m_ast.statements.size(); ++i) + { + solAssert(m_ast.statements.at(i).type() == typeid(FunctionDefinition), ""); + FunctionDefinition& fun = boost::get<FunctionDefinition>(m_ast.statements.at(i)); + m_functions[fun.name] = &fun; + m_functionsToVisit.insert(&fun); + } +} + +void FullInliner::run() +{ + solAssert(m_ast.statements[0].type() == typeid(Block), ""); + InlineModifier(*this, m_nameDispenser, "").visit(m_ast.statements[0]); + while (!m_functionsToVisit.empty()) + handleFunction(**m_functionsToVisit.begin()); +} + +void FullInliner::handleFunction(FunctionDefinition& _fun) +{ + if (!m_functionsToVisit.count(&_fun)) + return; + m_functionsToVisit.erase(&_fun); + (InlineModifier(*this, m_nameDispenser, _fun.name))(_fun.body); +} + +void InlineModifier::operator()(FunctionalInstruction& _instruction) +{ + visitArguments(_instruction.arguments); +} + +void InlineModifier::operator()(FunctionCall&) +{ + solAssert(false, "Should be handled in visit() instead."); +} + +void InlineModifier::operator()(ForLoop& _loop) +{ + (*this)(_loop.pre); + // Do not visit the condition because we cannot inline there. + (*this)(_loop.post); + (*this)(_loop.body); +} + +void InlineModifier::operator()(Block& _block) +{ + // This is only used if needed to minimize the number of move operations. + vector<Statement> modifiedStatements; + for (size_t i = 0; i < _block.statements.size(); ++i) + { + visit(_block.statements.at(i)); + if (!m_statementsToPrefix.empty()) + { + if (modifiedStatements.empty()) + std::move( + _block.statements.begin(), + _block.statements.begin() + i, + back_inserter(modifiedStatements) + ); + modifiedStatements += std::move(m_statementsToPrefix); + m_statementsToPrefix.clear(); + } + if (!modifiedStatements.empty()) + modifiedStatements.emplace_back(std::move(_block.statements[i])); + } + if (!modifiedStatements.empty()) + _block.statements = std::move(modifiedStatements); +} + +void InlineModifier::visit(Expression& _expression) +{ + if (_expression.type() != typeid(FunctionCall)) + return ASTModifier::visit(_expression); + + FunctionCall& funCall = boost::get<FunctionCall>(_expression); + FunctionDefinition& fun = m_driver.function(funCall.functionName.name); + + m_driver.handleFunction(fun); + + // TODO: Insert good heuristic here. Perhaps implement that inside the driver. + bool doInline = funCall.functionName.name != m_currentFunction; + + if (fun.returnVariables.size() > 1) + doInline = false; + + { + vector<string> argNames; + vector<string> argTypes; + for (auto const& arg: fun.parameters) + { + argNames.push_back(fun.name + "_" + arg.name); + argTypes.push_back(arg.type); + } + visitArguments(funCall.arguments, argNames, argTypes, doInline); + } + + if (!doInline) + return; + + map<string, string> variableReplacements; + for (size_t i = 0; i < funCall.arguments.size(); ++i) + variableReplacements[fun.parameters[i].name] = boost::get<Identifier>(funCall.arguments[i]).name; + if (fun.returnVariables.empty()) + _expression = noop(funCall.location); + else + { + string returnVariable = fun.returnVariables[0].name; + variableReplacements[returnVariable] = newName(fun.name + "_" + returnVariable); + + m_statementsToPrefix.emplace_back(VariableDeclaration{ + funCall.location, + {{funCall.location, variableReplacements[returnVariable], fun.returnVariables[0].type}}, + {} + }); + _expression = Identifier{funCall.location, variableReplacements[returnVariable]}; + } + m_statementsToPrefix.emplace_back(BodyCopier(m_nameDispenser, fun.name + "_", variableReplacements)(fun.body)); +} + +void InlineModifier::visit(Statement& _statement) +{ + ASTModifier::visit(_statement); + // Replace pop(0) expression statemets (and others) by empty blocks. + if (_statement.type() == typeid(ExpressionStatement)) + { + ExpressionStatement& expSt = boost::get<ExpressionStatement&>(_statement); + if (expSt.expression.type() == typeid(FunctionalInstruction)) + { + FunctionalInstruction& funInstr = boost::get<FunctionalInstruction&>(expSt.expression); + if (funInstr.instruction == solidity::Instruction::POP) + if (MovableChecker(funInstr.arguments.at(0)).movable()) + _statement = Block{expSt.location, {}}; + } + } +} + +void InlineModifier::visitArguments( + vector<Expression>& _arguments, + vector<string> const& _nameHints, + vector<string> const& _types, + bool _moveToFront +) +{ + // If one of the elements moves parts to the front, all other elements right of it + // also have to be moved to the front to keep the order of evaluation. + vector<Statement> prefix; + for (size_t i = 0; i < _arguments.size(); ++i) + { + auto& arg = _arguments[i]; + // TODO optimize vector operations, check that it actually moves + auto internalPrefix = visitRecursively(arg); + if (!internalPrefix.empty()) + { + _moveToFront = true; + // We go through the arguments left to right, so we have to invert + // the prefixes. + prefix = std::move(internalPrefix) + std::move(prefix); + } + else if (_moveToFront) + { + auto location = locationOf(arg); + string var = newName(i < _nameHints.size() ? _nameHints[i] : ""); + prefix.emplace(prefix.begin(), VariableDeclaration{ + location, + {{TypedName{location, var, i < _types.size() ? _types[i] : ""}}}, + make_shared<Expression>(std::move(arg)) + }); + arg = Identifier{location, var}; + } + } + m_statementsToPrefix += std::move(prefix); +} + +vector<Statement> InlineModifier::visitRecursively(Expression& _expression) +{ + vector<Statement> saved; + saved.swap(m_statementsToPrefix); + visit(_expression); + saved.swap(m_statementsToPrefix); + return saved; +} + +string InlineModifier::newName(string const& _prefix) +{ + return m_nameDispenser.newName(_prefix); +} + +Expression InlineModifier::noop(SourceLocation const& _location) +{ + return FunctionalInstruction{_location, solidity::Instruction::POP, { + Literal{_location, assembly::LiteralKind::Number, "0", ""} + }}; +} + +Statement BodyCopier::operator()(VariableDeclaration const& _varDecl) +{ + for (auto const& var: _varDecl.variables) + m_variableReplacements[var.name] = m_nameDispenser.newName(m_varNamePrefix + var.name); + return ASTCopier::operator()(_varDecl); +} + +Statement BodyCopier::operator()(FunctionDefinition const& _funDef) +{ + solAssert(false, "Function hoisting has to be done before function inlining."); + return _funDef; +} + +string BodyCopier::translateIdentifier(string const& _name) +{ + if (m_variableReplacements.count(_name)) + return m_variableReplacements.at(_name); + else + return _name; +} diff --git a/libjulia/optimiser/FullInliner.h b/libjulia/optimiser/FullInliner.h new file mode 100644 index 00000000..d3628e1a --- /dev/null +++ b/libjulia/optimiser/FullInliner.h @@ -0,0 +1,178 @@ +/* + 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/>. +*/ +/** + * Optimiser component that performs function inlining for arbitrary functions. + */ +#pragma once + +#include <libjulia/ASTDataForward.h> + +#include <libjulia/optimiser/ASTCopier.h> +#include <libjulia/optimiser/ASTWalker.h> +#include <libjulia/optimiser/NameDispenser.h> + +#include <libsolidity/interface/Exceptions.h> + +#include <boost/variant.hpp> +#include <boost/optional.hpp> + +#include <set> + +namespace dev +{ +namespace julia +{ + +class NameCollector; + + +/** + * Optimiser component that modifies an AST in place, inlining arbitrary functions. + * + * Code of the form + * + * function f(a, b) -> c { ... } + * h(g(x(...), f(arg1(...), arg2(...)), y(...)), z(...)) + * + * is transformed into + * + * function f(a, b) -> c { ... } + * + * let z1 := z(...) let y1 := y(...) let a2 := arg2(...) let a1 := arg1(...) + * let c1 := 0 + * { code of f, with replacements: a -> a1, b -> a2, c -> c1, d -> d1 } + * h(g(x(...), c1, y1), z1) + * + * No temporary variable is created for expressions that are "movable" + * (i.e. they are "pure", have no side-effects and also do not depend on other code + * that might have side-effects). + * + * This component can only be used on sources with unique names and with hoisted functions, + * i.e. the root node has to be a block that itself contains a single block followed by all + * function definitions. + */ +class FullInliner: public ASTModifier +{ +public: + explicit FullInliner(Block& _ast); + + void run(); + + /// Perform inlining operations inside the given function. + void handleFunction(FunctionDefinition& _function); + + FunctionDefinition& function(std::string _name) { return *m_functions.at(_name); } + +private: + /// The AST to be modified. The root block itself will not be modified, because + /// we store pointers to functions. + Block& m_ast; + std::map<std::string, FunctionDefinition*> m_functions; + std::set<FunctionDefinition*> m_functionsToVisit; + NameDispenser m_nameDispenser; +}; + +/** + * Class that walks the AST of a block that does not contain function definitions and perform + * the actual code modifications. + */ +class InlineModifier: public ASTModifier +{ +public: + InlineModifier(FullInliner& _driver, NameDispenser& _nameDispenser, std::string _functionName): + m_currentFunction(std::move(_functionName)), + m_driver(_driver), + m_nameDispenser(_nameDispenser) + { } + ~InlineModifier() + { + solAssert(m_statementsToPrefix.empty(), ""); + } + + virtual void operator()(FunctionalInstruction&) override; + virtual void operator()(FunctionCall&) override; + virtual void operator()(ForLoop&) override; + virtual void operator()(Block& _block) override; + + using ASTModifier::visit; + virtual void visit(Expression& _expression) override; + virtual void visit(Statement& _st) override; + +private: + + /// Visits a list of expressions (usually an argument list to a function call) and tries + /// to inline them. If one of them is inlined, all right of it have to be moved to the front + /// (to keep the order of evaluation). If @a _moveToFront is true, all elements are moved + /// to the front. @a _nameHints and @_types are used for the newly created variables, but + /// both can be empty. + void visitArguments( + std::vector<Expression>& _arguments, + std::vector<std::string> const& _nameHints = {}, + std::vector<std::string> const& _types = {}, + bool _moveToFront = false + ); + + /// Visits an expression, but saves and restores the current statements to prefix and returns + /// the statements that should be prefixed for @a _expression. + std::vector<Statement> visitRecursively(Expression& _expression); + + std::string newName(std::string const& _prefix); + + /// @returns an expression returning nothing. + Expression noop(SourceLocation const& _location); + + /// List of statements that should go in front of the currently visited AST element, + /// at the statement level. + std::vector<Statement> m_statementsToPrefix; + std::string m_currentFunction; + FullInliner& m_driver; + NameDispenser& m_nameDispenser; +}; + +/** + * Creates a copy of a block that is supposed to be the body of a function. + * Applies replacements to referenced variables and creates new names for + * variable declarations. + */ +class BodyCopier: public ASTCopier +{ +public: + BodyCopier( + NameDispenser& _nameDispenser, + std::string const& _varNamePrefix, + std::map<std::string, std::string> const& _variableReplacements + ): + m_nameDispenser(_nameDispenser), + m_varNamePrefix(_varNamePrefix), + m_variableReplacements(_variableReplacements) + {} + + using ASTCopier::operator (); + + virtual Statement operator()(VariableDeclaration const& _varDecl) override; + virtual Statement operator()(FunctionDefinition const& _funDef) override; + + virtual std::string translateIdentifier(std::string const& _name) override; + + NameDispenser& m_nameDispenser; + std::string const& m_varNamePrefix; + std::map<std::string, std::string> m_variableReplacements; +}; + + +} +} diff --git a/libjulia/optimiser/NameCollector.cpp b/libjulia/optimiser/NameCollector.cpp index 510ee289..c0d0b707 100644 --- a/libjulia/optimiser/NameCollector.cpp +++ b/libjulia/optimiser/NameCollector.cpp @@ -35,7 +35,6 @@ void NameCollector::operator()(VariableDeclaration const& _varDecl) void NameCollector::operator ()(FunctionDefinition const& _funDef) { m_names.insert(_funDef.name); - m_functions[_funDef.name] = &_funDef; for (auto const arg: _funDef.parameters) m_names.insert(arg.name); for (auto const ret: _funDef.returnVariables) diff --git a/libjulia/optimiser/NameCollector.h b/libjulia/optimiser/NameCollector.h index 2d4a1d4b..29856172 100644 --- a/libjulia/optimiser/NameCollector.h +++ b/libjulia/optimiser/NameCollector.h @@ -37,15 +37,18 @@ namespace julia class NameCollector: public ASTWalker { public: + explicit NameCollector(Block const& _block) + { + (*this)(_block); + } + using ASTWalker::operator (); virtual void operator()(VariableDeclaration const& _varDecl) override; virtual void operator()(FunctionDefinition const& _funDef) override; - std::set<std::string> const& names() const { return m_names; } - std::map<std::string, FunctionDefinition const*> const& functions() const { return m_functions; } + std::set<std::string> names() const { return m_names; } private: std::set<std::string> m_names; - std::map<std::string, FunctionDefinition const*> m_functions; }; /** diff --git a/libjulia/optimiser/NameDispenser.cpp b/libjulia/optimiser/NameDispenser.cpp new file mode 100644 index 00000000..e4f0e4f6 --- /dev/null +++ b/libjulia/optimiser/NameDispenser.cpp @@ -0,0 +1,38 @@ +/* + 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/>. +*/ +/** + * Optimiser component that can create new unique names. + */ + +#include <libjulia/optimiser/NameDispenser.h> + +using namespace std; +using namespace dev; +using namespace dev::julia; + +string NameDispenser::newName(string const& _prefix) +{ + string name = _prefix; + size_t suffix = 0; + while (name.empty() || m_usedNames.count(name)) + { + suffix++; + name = _prefix + "_" + std::to_string(suffix); + } + m_usedNames.insert(name); + return name; +} diff --git a/libjulia/optimiser/NameDispenser.h b/libjulia/optimiser/NameDispenser.h new file mode 100644 index 00000000..91c43d54 --- /dev/null +++ b/libjulia/optimiser/NameDispenser.h @@ -0,0 +1,37 @@ +/* + 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/>. +*/ +/** + * Optimiser component that can create new unique names. + */ +#pragma once + +#include <set> +#include <string> + +namespace dev +{ +namespace julia +{ + +struct NameDispenser +{ + std::string newName(std::string const& _prefix); + std::set<std::string> m_usedNames; +}; + +} +} diff --git a/libsolidity/analysis/TypeChecker.cpp b/libsolidity/analysis/TypeChecker.cpp index 7ea10c5b..32cf1b18 100644 --- a/libsolidity/analysis/TypeChecker.cpp +++ b/libsolidity/analysis/TypeChecker.cpp @@ -1067,6 +1067,7 @@ void TypeChecker::endVisit(EmitStatement const& _emit) { if ( _emit.eventCall().annotation().kind != FunctionCallKind::FunctionCall || + type(_emit.eventCall().expression())->category() != Type::Category::Function || dynamic_cast<FunctionType const&>(*type(_emit.eventCall().expression())).kind() != FunctionType::Kind::Event ) m_errorReporter.typeError(_emit.eventCall().expression().location(), "Expression has to be an event invocation."); @@ -1200,8 +1201,9 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement) string extension; if (auto type = dynamic_cast<IntegerType const*>(var.annotation().type.get())) { - int numBits = type->numBits(); + unsigned numBits = type->numBits(); bool isSigned = type->isSigned(); + solAssert(numBits > 0, ""); string minValue; string maxValue; if (isSigned) diff --git a/libsolidity/ast/AST.h b/libsolidity/ast/AST.h index a53987bf..fa0d6921 100644 --- a/libsolidity/ast/AST.h +++ b/libsolidity/ast/AST.h @@ -146,6 +146,7 @@ private: class Scopable { public: + virtual ~Scopable() = default; /// @returns the scope this declaration resides in. Can be nullptr if it is the global scope. /// Available only after name and type resolution step. ASTNode const* scope() const { return m_scope; } @@ -307,6 +308,7 @@ private: class VariableScope { public: + virtual ~VariableScope() = default; void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); } std::vector<VariableDeclaration const*> const& localVariables() const { return m_localVariables; } @@ -320,6 +322,7 @@ private: class Documented { public: + virtual ~Documented() = default; explicit Documented(ASTPointer<ASTString> const& _documentation): m_documentation(_documentation) {} /// @return A shared pointer of an ASTString. @@ -336,6 +339,7 @@ protected: class ImplementationOptional { public: + virtual ~ImplementationOptional() = default; explicit ImplementationOptional(bool _implemented): m_implemented(_implemented) {} /// @return whether this node is fully implemented or not diff --git a/libsolidity/ast/ASTVisitor.h b/libsolidity/ast/ASTVisitor.h index b1389f0f..6c0ce6f8 100644 --- a/libsolidity/ast/ASTVisitor.h +++ b/libsolidity/ast/ASTVisitor.h @@ -43,6 +43,7 @@ namespace solidity class ASTVisitor { public: + virtual ~ASTVisitor() = default; virtual bool visit(SourceUnit& _node) { return visitNode(_node); } virtual bool visit(PragmaDirective& _node) { return visitNode(_node); } virtual bool visit(ImportDirective& _node) { return visitNode(_node); } @@ -147,6 +148,7 @@ protected: class ASTConstVisitor { public: + virtual ~ASTConstVisitor() = default; virtual bool visit(SourceUnit const& _node) { return visitNode(_node); } virtual bool visit(PragmaDirective const& _node) { return visitNode(_node); } virtual bool visit(ImportDirective const& _node) { return visitNode(_node); } diff --git a/libsolidity/ast/Types.cpp b/libsolidity/ast/Types.cpp index 11d7160c..dc548538 100644 --- a/libsolidity/ast/Types.cpp +++ b/libsolidity/ast/Types.cpp @@ -425,14 +425,14 @@ bool isValidShiftAndAmountType(Token::Value _operator, Type const& _shiftAmountT } -IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier): +IntegerType::IntegerType(unsigned _bits, IntegerType::Modifier _modifier): m_bits(_bits), m_modifier(_modifier) { if (isAddress()) solAssert(m_bits == 160, ""); solAssert( m_bits > 0 && m_bits <= 256 && m_bits % 8 == 0, - "Invalid bit number for integer type: " + dev::toString(_bits) + "Invalid bit number for integer type: " + dev::toString(m_bits) ); } @@ -584,7 +584,7 @@ MemberList::MemberMap IntegerType::nativeMembers(ContractDefinition const*) cons { if (isAddress()) return { - {"balance", make_shared<IntegerType >(256)}, + {"balance", make_shared<IntegerType>(256)}, {"call", make_shared<FunctionType>(strings(), strings{"bool"}, FunctionType::Kind::BareCall, true, StateMutability::Payable)}, {"callcode", make_shared<FunctionType>(strings(), strings{"bool"}, FunctionType::Kind::BareCallCode, true, StateMutability::Payable)}, {"delegatecall", make_shared<FunctionType>(strings(), strings{"bool"}, FunctionType::Kind::BareDelegateCall, true)}, @@ -595,13 +595,12 @@ MemberList::MemberMap IntegerType::nativeMembers(ContractDefinition const*) cons return MemberList::MemberMap(); } -FixedPointType::FixedPointType(int _totalBits, int _fractionalDigits, FixedPointType::Modifier _modifier): +FixedPointType::FixedPointType(unsigned _totalBits, unsigned _fractionalDigits, FixedPointType::Modifier _modifier): m_totalBits(_totalBits), m_fractionalDigits(_fractionalDigits), m_modifier(_modifier) { solAssert( - 8 <= m_totalBits && m_totalBits <= 256 && m_totalBits % 8 == 0 && - 0 <= m_fractionalDigits && m_fractionalDigits <= 80, - "Invalid bit number(s) for fixed type: " + + 8 <= m_totalBits && m_totalBits <= 256 && m_totalBits % 8 == 0 && m_fractionalDigits <= 80, + "Invalid bit number(s) for fixed type: " + dev::toString(_totalBits) + "x" + dev::toString(_fractionalDigits) ); } @@ -696,7 +695,7 @@ TypePointer FixedPointType::binaryOperatorResult(Token::Value _operator, TypePoi std::shared_ptr<IntegerType> FixedPointType::asIntegerType() const { - return std::make_shared<IntegerType>(numBits(), isSigned() ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned); + return make_shared<IntegerType>(numBits(), isSigned() ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned); } tuple<bool, rational> RationalNumberType::parseRational(string const& _value) @@ -850,7 +849,7 @@ bool RationalNumberType::isImplicitlyConvertibleTo(Type const& _convertTo) const if (isFractional()) return false; IntegerType const& targetType = dynamic_cast<IntegerType const&>(_convertTo); - int forSignBit = (targetType.isSigned() ? 1 : 0); + unsigned forSignBit = (targetType.isSigned() ? 1 : 0); if (m_value > rational(0)) { if (m_value.numerator() <= (u256(-1) >> (256 - targetType.numBits() + forSignBit))) @@ -1264,7 +1263,7 @@ bool StringLiteralType::isValidUTF8() const return dev::validateUTF8(m_value); } -FixedBytesType::FixedBytesType(int _bytes): m_bytes(_bytes) +FixedBytesType::FixedBytesType(unsigned _bytes): m_bytes(_bytes) { solAssert( m_bytes > 0 && m_bytes <= 32, diff --git a/libsolidity/ast/Types.h b/libsolidity/ast/Types.h index a9536657..6defacfc 100644 --- a/libsolidity/ast/Types.h +++ b/libsolidity/ast/Types.h @@ -138,6 +138,7 @@ private: class Type: private boost::noncopyable, public std::enable_shared_from_this<Type> { public: + virtual ~Type() = default; enum class Category { Integer, RationalNumber, StringLiteral, Bool, FixedPoint, Array, @@ -318,7 +319,7 @@ public: }; virtual Category category() const override { return Category::Integer; } - explicit IntegerType(int _bits, Modifier _modifier = Modifier::Unsigned); + explicit IntegerType(unsigned _bits, Modifier _modifier = Modifier::Unsigned); virtual std::string richIdentifier() const override; virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; @@ -341,7 +342,7 @@ public: virtual TypePointer encodingType() const override { return shared_from_this(); } virtual TypePointer interfaceType(bool) const override { return shared_from_this(); } - int numBits() const { return m_bits; } + unsigned numBits() const { return m_bits; } bool isAddress() const { return m_modifier == Modifier::Address; } bool isSigned() const { return m_modifier == Modifier::Signed; } @@ -349,7 +350,7 @@ public: bigint maxValue() const; private: - int m_bits; + unsigned m_bits; Modifier m_modifier; }; @@ -365,7 +366,7 @@ public: }; virtual Category category() const override { return Category::FixedPoint; } - explicit FixedPointType(int _totalBits, int _fractionalDigits, Modifier _modifier = Modifier::Unsigned); + explicit FixedPointType(unsigned _totalBits, unsigned _fractionalDigits, Modifier _modifier = Modifier::Unsigned); virtual std::string richIdentifier() const override; virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; @@ -385,9 +386,9 @@ public: virtual TypePointer interfaceType(bool) const override { return shared_from_this(); } /// Number of bits used for this type in total. - int numBits() const { return m_totalBits; } + unsigned numBits() const { return m_totalBits; } /// Number of decimal digits after the radix point. - int fractionalDigits() const { return m_fractionalDigits; } + unsigned fractionalDigits() const { return m_fractionalDigits; } bool isSigned() const { return m_modifier == Modifier::Signed; } /// @returns the largest integer value this type con hold. Note that this is not the /// largest value in general. @@ -400,8 +401,8 @@ public: std::shared_ptr<IntegerType> asIntegerType() const; private: - int m_totalBits; - int m_fractionalDigits; + unsigned m_totalBits; + unsigned m_fractionalDigits; Modifier m_modifier; }; @@ -505,7 +506,7 @@ class FixedBytesType: public Type public: virtual Category category() const override { return Category::FixedBytes; } - explicit FixedBytesType(int _bytes); + explicit FixedBytesType(unsigned _bytes); virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; @@ -523,10 +524,10 @@ public: virtual TypePointer encodingType() const override { return shared_from_this(); } virtual TypePointer interfaceType(bool) const override { return shared_from_this(); } - int numBytes() const { return m_bytes; } + unsigned numBytes() const { return m_bytes; } private: - int m_bytes; + unsigned m_bytes; }; /** diff --git a/libsolidity/codegen/ABIFunctions.cpp b/libsolidity/codegen/ABIFunctions.cpp index 8e890854..3e3aa0ae 100644 --- a/libsolidity/codegen/ABIFunctions.cpp +++ b/libsolidity/codegen/ABIFunctions.cpp @@ -371,7 +371,7 @@ string ABIFunctions::conversionFunction(Type const& _from, Type const& _to) if (toCategory == Type::Category::Integer) body = Whiskers("converted := <convert>(<shift>(value))") - ("shift", shiftRightFunction(256 - from.numBytes() * 8, false)) + ("shift", shiftRightFunction(256 - from.numBytes() * 8)) ("convert", conversionFunction(IntegerType(from.numBytes() * 8), _to)) .render(); else @@ -458,8 +458,8 @@ string ABIFunctions::splitExternalFunctionIdFunction() } )") ("functionName", functionName) - ("shr32", shiftRightFunction(32, false)) - ("shr64", shiftRightFunction(64, false)) + ("shr32", shiftRightFunction(32)) + ("shr64", shiftRightFunction(64)) .render(); }); } @@ -831,7 +831,7 @@ string ABIFunctions::abiEncodingFunctionCompactStorageArray( templ("encodeToMemoryFun", encodeToMemoryFun); std::vector<std::map<std::string, std::string>> items(itemsPerSlot); for (size_t i = 0; i < itemsPerSlot; ++i) - items[i]["shiftRightFun"] = shiftRightFunction(i * storageBytes * 8, false); + items[i]["shiftRightFun"] = shiftRightFunction(i * storageBytes * 8); templ("items", items); return templ.render(); } @@ -927,7 +927,7 @@ string ABIFunctions::abiEncodingFunctionStruct( } else memberTempl("preprocess", ""); - memberTempl("retrieveValue", shiftRightFunction(intraSlotOffset * 8, false) + "(slotValue)"); + memberTempl("retrieveValue", shiftRightFunction(intraSlotOffset * 8) + "(slotValue)"); } else { @@ -1401,37 +1401,75 @@ string ABIFunctions::copyToMemoryFunction(bool _fromCalldata) string ABIFunctions::shiftLeftFunction(size_t _numBits) { + solAssert(_numBits < 256, ""); + string functionName = "shift_left_" + to_string(_numBits); - return createFunction(functionName, [&]() { - solAssert(_numBits < 256, ""); - return - Whiskers(R"( - function <functionName>(value) -> newValue { - newValue := mul(value, <multiplier>) - } - )") - ("functionName", functionName) - ("multiplier", toCompactHexWithPrefix(u256(1) << _numBits)) - .render(); - }); + if (m_evmVersion.hasBitwiseShifting()) + { + return createFunction(functionName, [&]() { + return + Whiskers(R"( + function <functionName>(value) -> newValue { + newValue := shl(<numBits>, value) + } + )") + ("functionName", functionName) + ("numBits", to_string(_numBits)) + .render(); + }); + } + else + { + return createFunction(functionName, [&]() { + return + Whiskers(R"( + function <functionName>(value) -> newValue { + newValue := mul(value, <multiplier>) + } + )") + ("functionName", functionName) + ("multiplier", toCompactHexWithPrefix(u256(1) << _numBits)) + .render(); + }); + } } -string ABIFunctions::shiftRightFunction(size_t _numBits, bool _signed) +string ABIFunctions::shiftRightFunction(size_t _numBits) { - string functionName = "shift_right_" + to_string(_numBits) + (_signed ? "_signed" : "_unsigned"); - return createFunction(functionName, [&]() { - solAssert(_numBits < 256, ""); - return - Whiskers(R"( - function <functionName>(value) -> newValue { - newValue := <div>(value, <multiplier>) - } - )") - ("functionName", functionName) - ("div", _signed ? "sdiv" : "div") - ("multiplier", toCompactHexWithPrefix(u256(1) << _numBits)) - .render(); - }); + solAssert(_numBits < 256, ""); + + // Note that if this is extended with signed shifts, + // the opcodes SAR and SDIV behave differently with regards to rounding! + + string functionName = "shift_right_" + to_string(_numBits) + "_unsigned"; + if (m_evmVersion.hasBitwiseShifting()) + { + return createFunction(functionName, [&]() { + return + Whiskers(R"( + function <functionName>(value) -> newValue { + newValue := shr(<numBits>, value) + } + )") + ("functionName", functionName) + ("numBits", to_string(_numBits)) + .render(); + }); + } + else + { + return createFunction(functionName, [&]() { + return + Whiskers(R"( + function <functionName>(value) -> newValue { + newValue := div(value, <multiplier>) + } + )") + ("functionName", functionName) + ("multiplier", toCompactHexWithPrefix(u256(1) << _numBits)) + .render(); + }); + } } string ABIFunctions::roundUpFunction() diff --git a/libsolidity/codegen/ABIFunctions.h b/libsolidity/codegen/ABIFunctions.h index 2b582e84..db4d40f5 100644 --- a/libsolidity/codegen/ABIFunctions.h +++ b/libsolidity/codegen/ABIFunctions.h @@ -22,6 +22,8 @@ #pragma once +#include <libsolidity/interface/EVMVersion.h> + #include <libsolidity/ast/ASTForward.h> #include <vector> @@ -48,6 +50,8 @@ using TypePointers = std::vector<TypePointer>; class ABIFunctions { public: + explicit ABIFunctions(EVMVersion _evmVersion = EVMVersion{}) : m_evmVersion(_evmVersion) {} + /// @returns name of an assembly function to ABI-encode values of @a _givenTypes /// into memory, converting the types to @a _targetTypes on the fly. /// Parameters are: <headStart> <value_n> ... <value_1>, i.e. @@ -191,7 +195,7 @@ private: std::string copyToMemoryFunction(bool _fromCalldata); std::string shiftLeftFunction(size_t _numBits); - std::string shiftRightFunction(size_t _numBits, bool _signed); + std::string shiftRightFunction(size_t _numBits); /// @returns the name of a function that rounds its input to the next multiple /// of 32 or the input if it is a multiple of 32. std::string roundUpFunction(); @@ -225,6 +229,8 @@ private: /// Map from function name to code for a multi-use function. std::map<std::string, std::string> m_requestedFunctions; + + EVMVersion m_evmVersion; }; } diff --git a/libsolidity/codegen/CompilerContext.h b/libsolidity/codegen/CompilerContext.h index 098472f7..5776b5d1 100644 --- a/libsolidity/codegen/CompilerContext.h +++ b/libsolidity/codegen/CompilerContext.h @@ -55,7 +55,8 @@ public: explicit CompilerContext(EVMVersion _evmVersion = EVMVersion{}, CompilerContext* _runtimeContext = nullptr): m_asm(std::make_shared<eth::Assembly>()), m_evmVersion(_evmVersion), - m_runtimeContext(_runtimeContext) + m_runtimeContext(_runtimeContext), + m_abiFunctions(m_evmVersion) { if (m_runtimeContext) m_runtimeSub = size_t(m_asm->newSub(m_runtimeContext->m_asm).data()); diff --git a/libsolidity/codegen/CompilerUtils.cpp b/libsolidity/codegen/CompilerUtils.cpp index 4af7d905..a39e799c 100644 --- a/libsolidity/codegen/CompilerUtils.cpp +++ b/libsolidity/codegen/CompilerUtils.cpp @@ -110,7 +110,7 @@ void CompilerUtils::loadFromMemoryDynamic( bool _padToWordBoundaries, bool _keepUpdatedMemoryOffset ) -{ +{ if (_keepUpdatedMemoryOffset) m_context << Instruction::DUP1; @@ -396,7 +396,7 @@ void CompilerUtils::encodeToMemory( // leave end_of_mem as dyn head pointer m_context << Instruction::DUP1 << u256(32) << Instruction::ADD; dynPointers++; - solAssert((argSize + dynPointers) < 16, "Stack too deep, try using less variables."); + solAssert((argSize + dynPointers) < 16, "Stack too deep, try using fewer variables."); } else { @@ -599,15 +599,15 @@ void CompilerUtils::splitExternalFunctionType(bool _leftAligned) if (_leftAligned) { m_context << Instruction::DUP1; - rightShiftNumberOnStack(64 + 32, false); + rightShiftNumberOnStack(64 + 32); // <input> <address> m_context << Instruction::SWAP1; - rightShiftNumberOnStack(64, false); + rightShiftNumberOnStack(64); } else { m_context << Instruction::DUP1; - rightShiftNumberOnStack(32, false); + rightShiftNumberOnStack(32); m_context << ((u256(1) << 160) - 1) << Instruction::AND << Instruction::SWAP1; } m_context << u256(0xffffffffUL) << Instruction::AND; @@ -675,7 +675,7 @@ void CompilerUtils::convertType( // conversion from bytes to integer. no need to clean the high bit // only to shift right because of opposite alignment IntegerType const& targetIntegerType = dynamic_cast<IntegerType const&>(_targetType); - rightShiftNumberOnStack(256 - typeOnStack.numBytes() * 8, false); + rightShiftNumberOnStack(256 - typeOnStack.numBytes() * 8); if (targetIntegerType.numBits() < typeOnStack.numBytes() * 8) convertType(IntegerType(typeOnStack.numBytes() * 8), _targetType, _cleanupNeeded); } @@ -688,7 +688,7 @@ void CompilerUtils::convertType( m_context << Instruction::POP << u256(0); else if (targetType.numBytes() > typeOnStack.numBytes() || _cleanupNeeded) { - int bytes = min(typeOnStack.numBytes(), targetType.numBytes()); + unsigned bytes = min(typeOnStack.numBytes(), targetType.numBytes()); m_context << ((u256(1) << (256 - bytes * 8)) - 1); m_context << Instruction::NOT << Instruction::AND; } @@ -741,7 +741,7 @@ void CompilerUtils::convertType( else if (targetTypeCategory == Type::Category::FixedPoint) { solAssert( - stackTypeCategory == Type::Category::Integer || + stackTypeCategory == Type::Category::Integer || stackTypeCategory == Type::Category::RationalNumber || stackTypeCategory == Type::Category::FixedPoint, "Invalid conversion to FixedMxNType requested." @@ -796,7 +796,7 @@ void CompilerUtils::convertType( bytesConstRef data(value); if (targetTypeCategory == Type::Category::FixedBytes) { - int const numBytes = dynamic_cast<FixedBytesType const&>(_targetType).numBytes(); + unsigned const numBytes = dynamic_cast<FixedBytesType const&>(_targetType).numBytes(); solAssert(data.size() <= 32, ""); m_context << (h256::Arith(h256(data, h256::AlignLeft)) & (~(u256(-1) >> (8 * numBytes)))); } @@ -1242,7 +1242,7 @@ unsigned CompilerUtils::loadFromMemoryHelper(Type const& _type, bool _fromCallda bool leftAligned = _type.category() == Type::Category::FixedBytes; // add leading or trailing zeros by dividing/multiplying depending on alignment int shiftFactor = (32 - numBytes) * 8; - rightShiftNumberOnStack(shiftFactor, false); + rightShiftNumberOnStack(shiftFactor); if (leftAligned) leftShiftNumberOnStack(shiftFactor); } @@ -1265,13 +1265,20 @@ void CompilerUtils::cleanHigherOrderBits(IntegerType const& _typeOnStack) void CompilerUtils::leftShiftNumberOnStack(unsigned _bits) { solAssert(_bits < 256, ""); - m_context << (u256(1) << _bits) << Instruction::MUL; + if (m_context.evmVersion().hasBitwiseShifting()) + m_context << _bits << Instruction::SHL; + else + m_context << (u256(1) << _bits) << Instruction::MUL; } -void CompilerUtils::rightShiftNumberOnStack(unsigned _bits, bool _isSigned) +void CompilerUtils::rightShiftNumberOnStack(unsigned _bits) { solAssert(_bits < 256, ""); - m_context << (u256(1) << _bits) << Instruction::SWAP1 << (_isSigned ? Instruction::SDIV : Instruction::DIV); + // NOTE: If we add signed right shift, SAR rounds differently than SDIV + if (m_context.evmVersion().hasBitwiseShifting()) + m_context << _bits << Instruction::SHR; + else + m_context << (u256(1) << _bits) << Instruction::SWAP1 << Instruction::DIV; } unsigned CompilerUtils::prepareMemoryStore(Type const& _type, bool _padToWords) diff --git a/libsolidity/codegen/CompilerUtils.h b/libsolidity/codegen/CompilerUtils.h index 476a7559..8e3a8a5d 100644 --- a/libsolidity/codegen/CompilerUtils.h +++ b/libsolidity/codegen/CompilerUtils.h @@ -254,7 +254,7 @@ public: /// Helper function to shift top value on the stack to the right. /// Stack pre: <value> <shift_by_bits> /// Stack post: <shifted_value> - void rightShiftNumberOnStack(unsigned _bits, bool _isSigned = false); + void rightShiftNumberOnStack(unsigned _bits); /// Appends code that computes tha Keccak-256 hash of the topmost stack element of 32 byte type. void computeHashStatic(); diff --git a/libsolidity/codegen/ExpressionCompiler.cpp b/libsolidity/codegen/ExpressionCompiler.cpp index 3cf46a9d..a8222e21 100644 --- a/libsolidity/codegen/ExpressionCompiler.cpp +++ b/libsolidity/codegen/ExpressionCompiler.cpp @@ -548,7 +548,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall) if (m_context.runtimeContext()) // We have a runtime context, so we need the creation part. - utils().rightShiftNumberOnStack(32, false); + utils().rightShiftNumberOnStack(32); else // Extract the runtime part. m_context << ((u256(1) << 32) - 1) << Instruction::AND; @@ -1706,13 +1706,23 @@ void ExpressionCompiler::appendShiftOperatorCode(Token::Value _operator, Type co m_context.appendConditionalInvalid(); } + m_context << Instruction::SWAP1; + // stack: value_to_shift shift_amount + switch (_operator) { case Token::SHL: - m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::MUL; + if (m_context.evmVersion().hasBitwiseShifting()) + m_context << Instruction::SHL; + else + m_context << u256(2) << Instruction::EXP << Instruction::MUL; break; case Token::SAR: - m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_valueSigned ? Instruction::SDIV : Instruction::DIV); + // NOTE: SAR rounds differently than SDIV + if (m_context.evmVersion().hasBitwiseShifting() && !c_valueSigned) + m_context << Instruction::SHR; + else + m_context << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_valueSigned ? Instruction::SDIV : Instruction::DIV); break; case Token::SHR: default: diff --git a/libsolidity/codegen/LValue.cpp b/libsolidity/codegen/LValue.cpp index e19cf41e..77684683 100644 --- a/libsolidity/codegen/LValue.cpp +++ b/libsolidity/codegen/LValue.cpp @@ -267,7 +267,7 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc else if (m_dataType->category() == Type::Category::FixedBytes) { solAssert(_sourceType.category() == Type::Category::FixedBytes, "source not fixed bytes"); - CompilerUtils(m_context).rightShiftNumberOnStack(256 - 8 * dynamic_cast<FixedBytesType const&>(*m_dataType).numBytes(), false); + CompilerUtils(m_context).rightShiftNumberOnStack(256 - 8 * dynamic_cast<FixedBytesType const&>(*m_dataType).numBytes()); } else { diff --git a/libsolidity/formal/SolverInterface.h b/libsolidity/formal/SolverInterface.h index e127bb55..16796684 100644 --- a/libsolidity/formal/SolverInterface.h +++ b/libsolidity/formal/SolverInterface.h @@ -193,6 +193,7 @@ DEV_SIMPLE_EXCEPTION(SolverError); class SolverInterface { public: + virtual ~SolverInterface() = default; virtual void reset() = 0; virtual void push() = 0; diff --git a/libsolidity/formal/SymbolicVariable.h b/libsolidity/formal/SymbolicVariable.h index e4e4ea8d..e29ded26 100644 --- a/libsolidity/formal/SymbolicVariable.h +++ b/libsolidity/formal/SymbolicVariable.h @@ -40,6 +40,7 @@ public: Declaration const& _decl, smt::SolverInterface& _interface ); + virtual ~SymbolicVariable() = default; smt::Expression operator()(int _seq) const { diff --git a/libsolidity/interface/GasEstimator.cpp b/libsolidity/interface/GasEstimator.cpp index a496cc21..a532f86e 100644 --- a/libsolidity/interface/GasEstimator.cpp +++ b/libsolidity/interface/GasEstimator.cpp @@ -136,13 +136,22 @@ GasEstimator::GasConsumption GasEstimator::functionalEstimation( ExpressionClasses& classes = state->expressionClasses(); using Id = ExpressionClasses::Id; using Ids = vector<Id>; - // div(calldataload(0), 1 << 224) equals to hashValue Id hashValue = classes.find(u256(FixedHash<4>::Arith(FixedHash<4>(dev::keccak256(_signature))))); Id calldata = classes.find(Instruction::CALLDATALOAD, Ids{classes.find(u256(0))}); - classes.forceEqual(hashValue, Instruction::DIV, Ids{ - calldata, - classes.find(u256(1) << 224) - }); + if (!m_evmVersion.hasBitwiseShifting()) + // div(calldataload(0), 1 << 224) equals to hashValue + classes.forceEqual( + hashValue, + Instruction::DIV, + Ids{calldata, classes.find(u256(1) << 224)} + ); + else + // shr(0xe0, calldataload(0)) equals to hashValue + classes.forceEqual( + hashValue, + Instruction::SHR, + Ids{classes.find(u256(0xe0)), calldata} + ); // lt(calldatasize(), 4) equals to 0 (ignore the shortcut for fallback functions) classes.forceEqual( classes.find(u256(0)), diff --git a/libsolidity/parsing/Parser.cpp b/libsolidity/parsing/Parser.cpp index a9ee9016..37732a37 100644 --- a/libsolidity/parsing/Parser.cpp +++ b/libsolidity/parsing/Parser.cpp @@ -1194,7 +1194,8 @@ ASTPointer<Expression> Parser::parseExpression( ASTPointer<Expression> expression = parseBinaryExpression(4, _lookAheadIndexAccessStructure); if (Token::isAssignmentOp(m_scanner->currentToken())) { - Token::Value assignmentOperator = expectAssignmentOperator(); + Token::Value assignmentOperator = m_scanner->currentToken(); + m_scanner->next(); ASTPointer<Expression> rightHandSide = parseExpression(); ASTNodeFactory nodeFactory(*this, expression); nodeFactory.setEndPositionFromNode(rightHandSide); @@ -1601,40 +1602,10 @@ ASTPointer<ParameterList> Parser::createEmptyParameterList() return nodeFactory.createNode<ParameterList>(vector<ASTPointer<VariableDeclaration>>()); } -string Parser::currentTokenName() -{ - Token::Value token = m_scanner->currentToken(); - if (Token::isElementaryTypeName(token)) //for the sake of accuracy in reporting - { - ElementaryTypeNameToken elemTypeName = m_scanner->currentElementaryTypeNameToken(); - return elemTypeName.toString(); - } - else - return Token::name(token); -} - -Token::Value Parser::expectAssignmentOperator() -{ - Token::Value op = m_scanner->currentToken(); - if (!Token::isAssignmentOp(op)) - fatalParserError( - string("Expected assignment operator, got '") + - currentTokenName() + - string("'") - ); - m_scanner->next(); - return op; -} - ASTPointer<ASTString> Parser::expectIdentifierToken() { - Token::Value id = m_scanner->currentToken(); - if (id != Token::Identifier) - fatalParserError( - string("Expected identifier, got '") + - currentTokenName() + - string("'") - ); + // do not advance on success + expectToken(Token::Identifier, false); return getLiteralAndAdvance(); } diff --git a/libsolidity/parsing/Parser.h b/libsolidity/parsing/Parser.h index c4254231..7f02d895 100644 --- a/libsolidity/parsing/Parser.h +++ b/libsolidity/parsing/Parser.h @@ -165,8 +165,6 @@ private: /// @returns an expression parsed in look-ahead fashion from something like "a.b[8][2**70]". ASTPointer<Expression> expressionFromIndexAccessStructure(IndexAccessedPath const& _pathAndIndices); - std::string currentTokenName(); - Token::Value expectAssignmentOperator(); ASTPointer<ASTString> expectIdentifierToken(); ASTPointer<ASTString> getLiteralAndAdvance(); ///@} diff --git a/libsolidity/parsing/ParserBase.cpp b/libsolidity/parsing/ParserBase.cpp index 5b83c5bd..617a1779 100644 --- a/libsolidity/parsing/ParserBase.cpp +++ b/libsolidity/parsing/ParserBase.cpp @@ -63,7 +63,7 @@ Token::Value ParserBase::advance() return m_scanner->next(); } -void ParserBase::expectToken(Token::Value _value) +void ParserBase::expectToken(Token::Value _value, bool _advance) { Token::Value tok = m_scanner->currentToken(); if (tok != _value) @@ -98,7 +98,8 @@ void ParserBase::expectToken(Token::Value _value) string("'") ); } - m_scanner->next(); + if (_advance) + m_scanner->next(); } void ParserBase::increaseRecursionDepth() diff --git a/libsolidity/parsing/ParserBase.h b/libsolidity/parsing/ParserBase.h index fd0de0d1..b28e1b1b 100644 --- a/libsolidity/parsing/ParserBase.h +++ b/libsolidity/parsing/ParserBase.h @@ -63,7 +63,7 @@ protected: ///@{ ///@name Helper functions /// If current token value is not _value, throw exception otherwise advance token. - void expectToken(Token::Value _value); + void expectToken(Token::Value _value, bool _advance = true); Token::Value currentToken() const; Token::Value peekNextToken() const; std::string currentLiteral() const; diff --git a/scripts/tests.sh b/scripts/tests.sh index 38073bf3..d63c1fe4 100755 --- a/scripts/tests.sh +++ b/scripts/tests.sh @@ -30,6 +30,17 @@ set -e REPO_ROOT="$(dirname "$0")"/.. +IPC_ENABLED=true +if [[ "$OSTYPE" == "darwin"* ]] +then + SMT_FLAGS="--no-smt" + if [ "$CIRCLECI" ] + then + IPC_ENABLED=false + IPC_FLAGS="--no-ipc" + fi +fi + if [ "$1" = --junit_report ] then if [ -z "$2" ] @@ -98,8 +109,11 @@ function run_eth() sleep 2 } -download_eth -ETH_PID=$(run_eth /tmp/test) +if [ "$IPC_ENABLED" = true ]; +then + download_eth + ETH_PID=$(run_eth /tmp/test) +fi progress="--show-progress" if [ "$CIRCLECI" ] @@ -131,7 +145,7 @@ do log=--logger=JUNIT,test_suite,$log_directory/noopt_$vm.xml $testargs_no_opt fi fi - "$REPO_ROOT"/build/test/soltest $progress $log -- --testpath "$REPO_ROOT"/test "$optimize" --evm-version "$vm" --ipcpath /tmp/test/geth.ipc + "$REPO_ROOT"/build/test/soltest $progress $log -- --testpath "$REPO_ROOT"/test "$optimize" --evm-version "$vm" $SMT_FLAGS $IPC_FLAGS --ipcpath /tmp/test/geth.ipc done done @@ -141,6 +155,9 @@ then exit 1 fi -pkill "$ETH_PID" || true -sleep 4 -pgrep "$ETH_PID" && pkill -9 "$ETH_PID" || true +if [ "$IPC_ENABLED" = true ] +then + pkill "$ETH_PID" || true + sleep 4 + pgrep "$ETH_PID" && pkill -9 "$ETH_PID" || true +fi diff --git a/solc/CommandLineInterface.cpp b/solc/CommandLineInterface.cpp index bd5e2eb1..1f04c68a 100644 --- a/solc/CommandLineInterface.cpp +++ b/solc/CommandLineInterface.cpp @@ -564,7 +564,8 @@ Allowed options)", ( g_argOptimizeRuns.c_str(), po::value<unsigned>()->value_name("n")->default_value(200), - "Estimated number of contract runs for optimizer tuning." + "Set for how many contract runs to optimize." + "Lower values will optimize more for initial deployment cost, higher values will optimize more for high-frequency usage." ) (g_argPrettyJson.c_str(), "Output JSON in pretty format. Currently it only works with the combined JSON output.") ( diff --git a/test/ExecutionFramework.h b/test/ExecutionFramework.h index ee8da322..4525cbf9 100644 --- a/test/ExecutionFramework.h +++ b/test/ExecutionFramework.h @@ -53,6 +53,7 @@ class ExecutionFramework public: ExecutionFramework(); + virtual ~ExecutionFramework() = default; virtual bytes const& compileAndRunWithoutCheck( std::string const& _sourceCode, diff --git a/test/libjulia/Inliner.cpp b/test/libjulia/Inliner.cpp index 88b51f28..464dcd93 100644 --- a/test/libjulia/Inliner.cpp +++ b/test/libjulia/Inliner.cpp @@ -1,18 +1,18 @@ /* - This file is part of solidity. + 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 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. + 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/>. + You should have received a copy of the GNU General Public License + along with solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @date 2017 @@ -23,6 +23,9 @@ #include <libjulia/optimiser/ExpressionInliner.h> #include <libjulia/optimiser/InlinableExpressionFunctionFinder.h> +#include <libjulia/optimiser/FullInliner.h> +#include <libjulia/optimiser/FunctionHoister.h> +#include <libjulia/optimiser/FunctionGrouper.h> #include <libsolidity/inlineasm/AsmPrinter.h> @@ -58,8 +61,17 @@ string inlineFunctions(string const& _source, bool _julia = true) ExpressionInliner(ast).run(); return assembly::AsmPrinter(_julia)(ast); } +string fullInline(string const& _source, bool _julia = true) +{ + Block ast = disambiguate(_source, _julia); + (FunctionHoister{})(ast); + (FunctionGrouper{})(ast);\ + FullInliner(ast).run(); + return assembly::AsmPrinter(_julia)(ast); +} } + BOOST_AUTO_TEST_SUITE(IuliaInlinableFunctionFilter) BOOST_AUTO_TEST_CASE(smoke_test) @@ -197,3 +209,135 @@ BOOST_AUTO_TEST_CASE(double_recursive_calls) } BOOST_AUTO_TEST_SUITE_END() + +BOOST_AUTO_TEST_SUITE(IuliaFullInliner) + +BOOST_AUTO_TEST_CASE(simple) +{ + BOOST_CHECK_EQUAL( + fullInline("{" + "function f(a) -> x { let r := mul(a, a) x := add(r, r) }" + "let y := add(f(sload(mload(2))), mload(7))" + "}", false), + format("{" + "{" + "let _1 := mload(7)" + "let f_a := sload(mload(2))" + "let f_x" + "{" + "let f_r := mul(f_a, f_a)" + "f_x := add(f_r, f_r)" + "}" + "let y := add(f_x, _1)" + "}" + "function f(a) -> x" + "{" + "let r := mul(a, a)" + "x := add(r, r)" + "}" + "}", false) + ); +} + +BOOST_AUTO_TEST_CASE(multi_fun) +{ + BOOST_CHECK_EQUAL( + fullInline("{" + "function f(a) -> x { x := add(a, a) }" + "function g(b, c) -> y { y := mul(mload(c), f(b)) }" + "let y := g(f(3), 7)" + "}", false), + format("{" + "{" + "let g_c := 7 " + "let f_a_1 := 3 " + "let f_x_1 " + "{ f_x_1 := add(f_a_1, f_a_1) } " + "let g_y " + "{" + "let g_f_a := f_x_1 " + "let g_f_x " + "{" + "g_f_x := add(g_f_a, g_f_a)" + "}" + "g_y := mul(mload(g_c), g_f_x)" + "}" + "let y_1 := g_y" + "}" + "function f(a) -> x" + "{" + "x := add(a, a)" + "}" + "function g(b, c) -> y" + "{" + "let f_a := b " + "let f_x " + "{" + "f_x := add(f_a, f_a)" + "}" + "y := mul(mload(c), f_x)" + "}" + "}", false) + ); +} + +BOOST_AUTO_TEST_CASE(move_up_rightwards_arguments) +{ + BOOST_CHECK_EQUAL( + fullInline("{" + "function f(a, b, c) -> x { x := add(a, b) x := mul(x, c) }" + "let y := add(mload(1), add(f(mload(2), mload(3), mload(4)), mload(5)))" + "}", false), + format("{" + "{" + "let _1 := mload(5)" + "let f_c := mload(4)" + "let f_b := mload(3)" + "let f_a := mload(2)" + "let f_x" + "{" + "f_x := add(f_a, f_b)" + "f_x := mul(f_x, f_c)" + "}" + "let y := add(mload(1), add(f_x, _1))" + "}" + "function f(a, b, c) -> x" + "{" + "x := add(a, b)" + "x := mul(x, c)" + "}" + "}", false) + ); +} + +BOOST_AUTO_TEST_CASE(pop_result) +{ + // This tests that `pop(r)` is removed. + BOOST_CHECK_EQUAL( + fullInline("{" + "function f(a) -> x { let r := mul(a, a) x := add(r, r) }" + "pop(add(f(7), 2))" + "}", false), + format("{" + "{" + "let _1 := 2 " + "let f_a := 7 " + "let f_x " + "{" + "let f_r := mul(f_a, f_a) " + "f_x := add(f_r, f_r)" + "}" + "{" + "}" + "}" + "function f(a) -> x" + "{" + "let r := mul(a, a) " + "x := add(r, r)" + "}" + "}", false) + ); +} + + +BOOST_AUTO_TEST_SUITE_END() diff --git a/test/libsolidity/AnalysisFramework.h b/test/libsolidity/AnalysisFramework.h index 05490a42..a904617d 100644 --- a/test/libsolidity/AnalysisFramework.h +++ b/test/libsolidity/AnalysisFramework.h @@ -52,6 +52,7 @@ protected: bool _insertVersionPragma = true, bool _allowMultipleErrors = false ); + virtual ~AnalysisFramework() = default; SourceUnit const* parseAndAnalyse(std::string const& _source); bool success(std::string const& _source); diff --git a/test/libsolidity/Assembly.cpp b/test/libsolidity/Assembly.cpp index 77ca363a..7b3df043 100644 --- a/test/libsolidity/Assembly.cpp +++ b/test/libsolidity/Assembly.cpp @@ -158,8 +158,9 @@ BOOST_AUTO_TEST_CASE(location_test) } )"; AssemblyItems items = compileContract(sourceCode); + bool hasShifts = dev::test::Options::get().evmVersion().hasBitwiseShifting(); vector<SourceLocation> locations = - vector<SourceLocation>(24, SourceLocation(2, 75, make_shared<string>(""))) + + vector<SourceLocation>(hasShifts ? 23 : 24, SourceLocation(2, 75, make_shared<string>(""))) + vector<SourceLocation>(2, SourceLocation(20, 72, make_shared<string>(""))) + vector<SourceLocation>(1, SourceLocation(8, 17, make_shared<string>("--CODEGEN--"))) + vector<SourceLocation>(3, SourceLocation(5, 7, make_shared<string>("--CODEGEN--"))) + @@ -172,8 +173,6 @@ BOOST_AUTO_TEST_CASE(location_test) vector<SourceLocation>(1, SourceLocation(65, 67, make_shared<string>(""))) + vector<SourceLocation>(2, SourceLocation(58, 67, make_shared<string>(""))) + vector<SourceLocation>(2, SourceLocation(20, 72, make_shared<string>(""))); - - checkAssemblyLocations(items, locations); } diff --git a/test/libsolidity/SolidityParser.cpp b/test/libsolidity/SolidityParser.cpp index 100b3662..f428f892 100644 --- a/test/libsolidity/SolidityParser.cpp +++ b/test/libsolidity/SolidityParser.cpp @@ -112,61 +112,6 @@ while(0) BOOST_AUTO_TEST_SUITE(SolidityParser) -BOOST_AUTO_TEST_CASE(empty_function) -{ - char const* text = R"( - contract test { - uint256 stateVar; - function functionName(bytes20 arg1, address addr) constant - returns (int id) - { } - } - )"; - BOOST_CHECK(successParse(text)); -} - -BOOST_AUTO_TEST_CASE(no_function_params) -{ - char const* text = R"( - contract test { - uint256 stateVar; - function functionName() {} - } - )"; - BOOST_CHECK(successParse(text)); -} - -BOOST_AUTO_TEST_CASE(single_function_param) -{ - char const* text = R"( - contract test { - uint256 stateVar; - function functionName(bytes32 input) returns (bytes32 out) {} - } - )"; - 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"( @@ -241,39 +186,6 @@ BOOST_AUTO_TEST_CASE(function_no_body) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(missing_parameter_name_in_named_args) -{ - char const* text = R"( - contract test { - function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; } - function b() returns (uint r) { r = a({: 1, : 2, : 3}); } - } - )"; - CHECK_PARSE_ERROR(text, "Expected identifier"); -} - -BOOST_AUTO_TEST_CASE(missing_argument_in_named_args) -{ - char const* text = R"( - contract test { - function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; } - function b() returns (uint r) { r = a({a: , b: , c: }); } - } - )"; - CHECK_PARSE_ERROR(text, "Expected primary expression"); -} - -BOOST_AUTO_TEST_CASE(trailing_comma_in_named_args) -{ - char const* text = R"( - contract test { - function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; } - function b() returns (uint r) { r = a({a: 1, b: 2, c: 3, }); } - } - )"; - CHECK_PARSE_ERROR(text, "Unexpected trailing comma"); -} - BOOST_AUTO_TEST_CASE(two_exact_functions) { char const* text = R"( @@ -557,18 +469,6 @@ BOOST_AUTO_TEST_CASE(variable_definition_with_initialization) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(variable_definition_in_mapping) -{ - char const* text = R"( - contract test { - function fun() { - mapping(var=>bytes32) d; - } - } - )"; - CHECK_PARSE_ERROR(text, "Expected elementary type name for mapping key type"); -} - BOOST_AUTO_TEST_CASE(operator_expression) { char const* text = R"( @@ -849,16 +749,6 @@ BOOST_AUTO_TEST_CASE(modifier) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(modifier_without_semicolon) -{ - char const* text = R"( - contract c { - modifier mod { if (msg.sender == 0) _ } - } - )"; - CHECK_PARSE_ERROR(text, "Expected token Semicolon got"); -} - BOOST_AUTO_TEST_CASE(modifier_arguments) { char const* text = R"( @@ -918,16 +808,6 @@ BOOST_AUTO_TEST_CASE(event_arguments_indexed) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(event_with_no_argument_list_fails) -{ - char const* text = R"( - contract c { - event e; - } - )"; - CHECK_PARSE_ERROR(text, "Expected token LParen got 'Semicolon'"); -} - BOOST_AUTO_TEST_CASE(visibility_specifiers) { char const* text = R"( @@ -1038,24 +918,6 @@ BOOST_AUTO_TEST_CASE(enum_valid_declaration) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(empty_enum_declaration) -{ - char const* text = R"( - contract c { - enum foo { } - })"; - CHECK_PARSE_ERROR(text, "enum with no members is not allowed"); -} - -BOOST_AUTO_TEST_CASE(malformed_enum_declaration) -{ - char const* text = R"( - contract c { - enum foo { WARNING,} - })"; - CHECK_PARSE_ERROR(text, "Expected Identifier after"); -} - BOOST_AUTO_TEST_CASE(external_function) { char const* text = R"( @@ -1065,15 +927,6 @@ BOOST_AUTO_TEST_CASE(external_function) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(external_variable) -{ - char const* text = R"( - contract c { - uint external x; - })"; - CHECK_PARSE_ERROR(text, "Expected identifier"); -} - BOOST_AUTO_TEST_CASE(arrays_in_storage) { char const* text = R"( @@ -1113,15 +966,6 @@ BOOST_AUTO_TEST_CASE(multi_arrays) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(constant_is_keyword) -{ - char const* text = R"( - contract Foo { - uint constant = 4; - })"; - CHECK_PARSE_ERROR(text, "Expected identifier"); -} - BOOST_AUTO_TEST_CASE(keyword_is_reserved) { auto keywords = { @@ -1148,19 +992,10 @@ BOOST_AUTO_TEST_CASE(keyword_is_reserved) for (const auto& keyword: keywords) { auto text = std::string("contract ") + keyword + " {}"; - CHECK_PARSE_ERROR(text.c_str(), "Expected identifier"); + CHECK_PARSE_ERROR(text.c_str(), "Expected token Identifier got reserved keyword"); } } -BOOST_AUTO_TEST_CASE(var_array) -{ - char const* text = R"( - contract Foo { - function f() { var[] a; } - })"; - CHECK_PARSE_ERROR(text, "Expected identifier"); -} - BOOST_AUTO_TEST_CASE(location_specifiers_for_params) { char const* text = R"( @@ -1184,24 +1019,6 @@ BOOST_AUTO_TEST_CASE(location_specifiers_for_locals) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(location_specifiers_for_state) -{ - char const* text = R"( - contract Foo { - uint[] memory x; - })"; - CHECK_PARSE_ERROR(text, "Expected identifier"); -} - -BOOST_AUTO_TEST_CASE(location_specifiers_with_var) -{ - char const* text = R"( - contract Foo { - function f() { var memory x; } - })"; - CHECK_PARSE_ERROR(text, "Location specifier needs explicit type name"); -} - BOOST_AUTO_TEST_CASE(empty_comment) { char const* text = R"( @@ -1224,7 +1041,6 @@ BOOST_AUTO_TEST_CASE(comment_end_with_double_star) BOOST_CHECK(successParse(text)); } - BOOST_AUTO_TEST_CASE(library_simple) { char const* text = R"( @@ -1235,20 +1051,6 @@ BOOST_AUTO_TEST_CASE(library_simple) BOOST_CHECK(successParse(text)); } - -BOOST_AUTO_TEST_CASE(local_const_variable) -{ - char const* text = R"( - contract Foo { - function localConst() returns (uint ret) - { - uint constant local = 4; - return local; - } - })"; - CHECK_PARSE_ERROR(text, "Expected token Semicolon"); -} - BOOST_AUTO_TEST_CASE(multi_variable_declaration) { char const* text = R"( @@ -1285,18 +1087,6 @@ BOOST_AUTO_TEST_CASE(tuples) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(tuples_without_commas) -{ - char const* text = R"( - contract C { - function f() { - var a = (2 2); - } - } - )"; - CHECK_PARSE_ERROR(text, "Expected token Comma"); -} - BOOST_AUTO_TEST_CASE(member_access_parser_ambiguity) { char const* text = R"( @@ -1365,34 +1155,6 @@ BOOST_AUTO_TEST_CASE(inline_array_declaration) BOOST_CHECK(successParse(text)); } - -BOOST_AUTO_TEST_CASE(inline_array_empty_cells_check_lvalue) -{ - char const* text = R"( - contract c { - uint[] a; - function f() returns (uint) { - a = [,2,3]; - return (a[0]); - } - } - )"; - CHECK_PARSE_ERROR(text, "Expected expression"); -} - -BOOST_AUTO_TEST_CASE(inline_array_empty_cells_check_without_lvalue) -{ - char const* text = R"( - contract c { - uint[] a; - function f() returns (uint, uint) { - return ([3, ,4][0]); - } - } - )"; - CHECK_PARSE_ERROR(text, "Expected expression"); -} - BOOST_AUTO_TEST_CASE(conditional_true_false_literal) { char const* text = R"( @@ -1520,38 +1282,6 @@ BOOST_AUTO_TEST_CASE(declaring_fixed_literal_variables) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(no_double_radix_in_fixed_literal) -{ - char const* text = R"( - contract A { - fixed40x40 pi = 3.14.15; - } - )"; - CHECK_PARSE_ERROR(text, "Expected token Semicolon"); -} - -BOOST_AUTO_TEST_CASE(invalid_fixed_conversion_leading_zeroes_check) -{ - char const* text = R"( - contract test { - function f() { - fixed a = 1.0x2; - } - } - )"; - CHECK_PARSE_ERROR(text, "Expected primary expression"); -} - -BOOST_AUTO_TEST_CASE(payable_accessor) -{ - char const* text = R"( - contract test { - uint payable x; - } - )"; - CHECK_PARSE_ERROR(text, "Expected identifier"); -} - BOOST_AUTO_TEST_CASE(function_type_in_expression) { char const* text = R"( @@ -1575,16 +1305,6 @@ BOOST_AUTO_TEST_CASE(function_type_as_storage_variable) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(function_type_as_storage_variable_with_modifiers) -{ - char const* text = R"( - contract test { - function (uint, uint) modifier1() returns (uint) f1; - } - )"; - CHECK_PARSE_ERROR(text, "Expected token LBrace"); -} - BOOST_AUTO_TEST_CASE(function_type_as_storage_variable_with_assignment) { char const* text = R"( @@ -1660,20 +1380,6 @@ BOOST_AUTO_TEST_CASE(function_type_state_variable) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(scientific_notation) -{ - char const* text = R"( - contract test { - uint256 a = 2e10; - uint256 b = 2E10; - uint256 c = 200e-2; - uint256 d = 2E10 wei; - uint256 e = 2.5e10; - } - )"; - BOOST_CHECK(successParse(text)); -} - BOOST_AUTO_TEST_CASE(interface) { char const* text = R"( @@ -1684,31 +1390,6 @@ BOOST_AUTO_TEST_CASE(interface) BOOST_CHECK(successParse(text)); } -BOOST_AUTO_TEST_CASE(newInvalidTypeName) -{ - char const* text = R"( - contract C { - function f() { - new var; - } - } - )"; - CHECK_PARSE_ERROR(text, "Expected explicit type name"); -} - -BOOST_AUTO_TEST_CASE(emitWithoutEvent) -{ - char const* text = R"( - contract C { - event A(); - function f() { - emit A; - } - } - )"; - CHECK_PARSE_ERROR(text, "Expected token LParen got 'Semicolon'"); -} - BOOST_AUTO_TEST_SUITE_END() } diff --git a/test/libsolidity/StandardCompiler.cpp b/test/libsolidity/StandardCompiler.cpp index 74bf01b2..f816905c 100644 --- a/test/libsolidity/StandardCompiler.cpp +++ b/test/libsolidity/StandardCompiler.cpp @@ -326,8 +326,8 @@ BOOST_AUTO_TEST_CASE(compilation_error) { BOOST_CHECK_EQUAL( dev::jsonCompactPrint(error), - "{\"component\":\"general\",\"formattedMessage\":\"fileA:1:23: ParserError: Expected identifier, got 'RBrace'\\n" - "contract A { function }\\n ^\\n\",\"message\":\"Expected identifier, got 'RBrace'\"," + "{\"component\":\"general\",\"formattedMessage\":\"fileA:1:23: ParserError: Expected token Identifier got 'RBrace'\\n" + "contract A { function }\\n ^\\n\",\"message\":\"Expected token Identifier got 'RBrace'\"," "\"severity\":\"error\",\"sourceLocation\":{\"end\":22,\"file\":\"fileA\",\"start\":22},\"type\":\"ParserError\"}" ); } diff --git a/test/libsolidity/syntaxTests/emit_non_event.sol b/test/libsolidity/syntaxTests/emit_non_event.sol new file mode 100644 index 00000000..1df6990d --- /dev/null +++ b/test/libsolidity/syntaxTests/emit_non_event.sol @@ -0,0 +1,10 @@ +contract C { + uint256 Test; + + function f() { + emit Test(); + } +} +// ---- +// TypeError: (56-62): Type is not callable +// TypeError: (56-60): Expression has to be an event invocation. diff --git a/test/libsolidity/syntaxTests/parsing/constant_is_keyword.sol b/test/libsolidity/syntaxTests/parsing/constant_is_keyword.sol new file mode 100644 index 00000000..59fe8518 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/constant_is_keyword.sol @@ -0,0 +1,5 @@ +contract Foo { + uint constant = 4; +} +// ---- +// ParserError: (30-30): Expected token Identifier got 'Assign' diff --git a/test/libsolidity/syntaxTests/parsing/emit_without_event.sol b/test/libsolidity/syntaxTests/parsing/emit_without_event.sol new file mode 100644 index 00000000..5916fc2b --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/emit_without_event.sol @@ -0,0 +1,8 @@ +contract C { + event A(); + function f() { + emit A; + } +} +// ---- +// ParserError: (49-49): Expected token LParen got 'Semicolon' diff --git a/test/libsolidity/syntaxTests/parsing/empty_enum.sol b/test/libsolidity/syntaxTests/parsing/empty_enum.sol new file mode 100644 index 00000000..dd786cdc --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/empty_enum.sol @@ -0,0 +1,5 @@ +contract c { + enum foo { } +} +// ---- +// ParserError: (25-25): enum with no members is not allowed. diff --git a/test/libsolidity/syntaxTests/parsing/empty_function.sol b/test/libsolidity/syntaxTests/parsing/empty_function.sol new file mode 100644 index 00000000..4f845189 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/empty_function.sol @@ -0,0 +1,10 @@ +contract test { + uint256 stateVar; + function functionName(bytes20 arg1, address addr) constant returns (int id) { } +} +// ---- +// Warning: (36-115): No visibility specified. Defaulting to "public". +// Warning: (58-70): Unused function parameter. Remove or comment out the variable name to silence this warning. +// Warning: (72-84): Unused function parameter. Remove or comment out the variable name to silence this warning. +// Warning: (104-110): Unused function parameter. Remove or comment out the variable name to silence this warning. +// Warning: (36-115): Function state mutability can be restricted to pure diff --git a/test/libsolidity/syntaxTests/parsing/event_with_no_argument_list.sol b/test/libsolidity/syntaxTests/parsing/event_with_no_argument_list.sol new file mode 100644 index 00000000..ae2591db --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/event_with_no_argument_list.sol @@ -0,0 +1,5 @@ +contract c { + event e; +} +// ---- +// ParserError: (21-21): Expected token LParen got 'Semicolon' diff --git a/test/libsolidity/syntaxTests/parsing/external_variable.sol b/test/libsolidity/syntaxTests/parsing/external_variable.sol new file mode 100644 index 00000000..1d2e65e6 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/external_variable.sol @@ -0,0 +1,5 @@ +contract c { + uint external x; +} +// ---- +// ParserError: (19-19): Expected token Identifier got 'External' diff --git a/test/libsolidity/syntaxTests/parsing/fixed_literal_with_double_radix.sol b/test/libsolidity/syntaxTests/parsing/fixed_literal_with_double_radix.sol new file mode 100644 index 00000000..43bb61fa --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/fixed_literal_with_double_radix.sol @@ -0,0 +1,5 @@ +contract A { + fixed40x40 pi = 3.14.15; +} +// ---- +// ParserError: (34-34): Expected token Semicolon got 'Number' diff --git a/test/libsolidity/syntaxTests/parsing/function_type_as_storage_variable_with_modifiers.sol b/test/libsolidity/syntaxTests/parsing/function_type_as_storage_variable_with_modifiers.sol new file mode 100644 index 00000000..12480459 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/function_type_as_storage_variable_with_modifiers.sol @@ -0,0 +1,5 @@ +contract test { + function (uint, uint) modifier1() returns (uint) f1; +} +// ---- +// ParserError: (66-66): Expected token LBrace got 'Identifier' diff --git a/test/libsolidity/syntaxTests/parsing/inline_array_empty_cells_check_lvalue.sol b/test/libsolidity/syntaxTests/parsing/inline_array_empty_cells_check_lvalue.sol new file mode 100644 index 00000000..23052980 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/inline_array_empty_cells_check_lvalue.sol @@ -0,0 +1,9 @@ +contract c { + uint[] a; + function f() returns (uint) { + a = [,2,3]; + return (a[0]); + } +} +// ---- +// ParserError: (62-62): Expected expression (inline array elements cannot be omitted). diff --git a/test/libsolidity/syntaxTests/parsing/inline_array_empty_cells_check_without_lvalue.sol b/test/libsolidity/syntaxTests/parsing/inline_array_empty_cells_check_without_lvalue.sol new file mode 100644 index 00000000..88c67619 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/inline_array_empty_cells_check_without_lvalue.sol @@ -0,0 +1,8 @@ +contract c { + uint[] a; + function f() returns (uint, uint) { + return ([3, ,4][0]); + } +} +// ---- +// ParserError: (75-75): Expected expression (inline array elements cannot be omitted). diff --git a/test/libsolidity/syntaxTests/parsing/invalid_fixed_conversion_leading_zeroes_check.sol b/test/libsolidity/syntaxTests/parsing/invalid_fixed_conversion_leading_zeroes_check.sol new file mode 100644 index 00000000..e0c8fa9a --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/invalid_fixed_conversion_leading_zeroes_check.sol @@ -0,0 +1,7 @@ +contract test { + function f() { + fixed a = 1.0x2; + } +} +// ---- +// ParserError: (44-44): Expected primary expression. diff --git a/test/libsolidity/syntaxTests/parsing/local_const_variable.sol b/test/libsolidity/syntaxTests/parsing/local_const_variable.sol new file mode 100644 index 00000000..55673160 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/local_const_variable.sol @@ -0,0 +1,9 @@ +contract Foo { + function localConst() returns (uint ret) + { + uint constant local = 4; + return local; + } +} +// ---- +// ParserError: (67-67): Expected token Semicolon got 'Constant' diff --git a/test/libsolidity/syntaxTests/parsing/location_specifiers_for_state_variables.sol b/test/libsolidity/syntaxTests/parsing/location_specifiers_for_state_variables.sol new file mode 100644 index 00000000..0fc85177 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/location_specifiers_for_state_variables.sol @@ -0,0 +1,5 @@ +contract Foo { + uint[] memory x; +} +// ---- +// ParserError: (23-23): Expected token Identifier got 'Memory' diff --git a/test/libsolidity/syntaxTests/parsing/location_specifiers_with_var.sol b/test/libsolidity/syntaxTests/parsing/location_specifiers_with_var.sol new file mode 100644 index 00000000..47fe37d5 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/location_specifiers_with_var.sol @@ -0,0 +1,5 @@ +contract Foo { + function f() { var memory x; } +} +// ---- +// ParserError: (35-35): Location specifier needs explicit type name. diff --git a/test/libsolidity/syntaxTests/parsing/malformed_enum_declaration.sol b/test/libsolidity/syntaxTests/parsing/malformed_enum_declaration.sol new file mode 100644 index 00000000..5a6eb270 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/malformed_enum_declaration.sol @@ -0,0 +1,5 @@ +contract c { + enum foo { WARNING,} +} +// ---- +// ParserError: (33-33): Expected Identifier after ',' diff --git a/test/libsolidity/syntaxTests/parsing/missing_argument_in_named_args.sol b/test/libsolidity/syntaxTests/parsing/missing_argument_in_named_args.sol new file mode 100644 index 00000000..8e0acfaa --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/missing_argument_in_named_args.sol @@ -0,0 +1,6 @@ +contract test { + function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; } + function b() returns (uint r) { r = a({a: , b: , c: }); } +} +// ---- +// ParserError: (146-146): Expected primary expression. diff --git a/test/libsolidity/syntaxTests/parsing/missing_parameter_name_in_named_args.sol b/test/libsolidity/syntaxTests/parsing/missing_parameter_name_in_named_args.sol new file mode 100644 index 00000000..3604f3b2 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/missing_parameter_name_in_named_args.sol @@ -0,0 +1,6 @@ +contract test { + function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; } + function b() returns (uint r) { r = a({: 1, : 2, : 3}); } +} +// ---- +// ParserError: (143-143): Expected token Identifier got 'Colon' diff --git a/test/libsolidity/syntaxTests/parsing/missing_variable_name_in_declaration.sol b/test/libsolidity/syntaxTests/parsing/missing_variable_name_in_declaration.sol index fd3067e3..bb1d015b 100644 --- a/test/libsolidity/syntaxTests/parsing/missing_variable_name_in_declaration.sol +++ b/test/libsolidity/syntaxTests/parsing/missing_variable_name_in_declaration.sol @@ -2,4 +2,4 @@ contract test { uint256 ; } // ---- -// ParserError: (28-28): Expected identifier, got 'Semicolon' +// ParserError: (28-28): Expected token Identifier got 'Semicolon' diff --git a/test/libsolidity/syntaxTests/parsing/modifier_without_semicolon.sol b/test/libsolidity/syntaxTests/parsing/modifier_without_semicolon.sol new file mode 100644 index 00000000..0d719db4 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/modifier_without_semicolon.sol @@ -0,0 +1,5 @@ +contract c { + modifier mod { if (msg.sender == 0) _ } +} +// ---- +// ParserError: (52-52): Expected token Semicolon got 'RBrace' diff --git a/test/libsolidity/syntaxTests/parsing/new_invalid_type_name.sol b/test/libsolidity/syntaxTests/parsing/new_invalid_type_name.sol new file mode 100644 index 00000000..31cd1f09 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/new_invalid_type_name.sol @@ -0,0 +1,7 @@ +contract C { + function f() { + new var; + } +} +// ---- +// ParserError: (35-35): Expected explicit type name. diff --git a/test/libsolidity/syntaxTests/parsing/no_function_params.sol b/test/libsolidity/syntaxTests/parsing/no_function_params.sol new file mode 100644 index 00000000..020f1233 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/no_function_params.sol @@ -0,0 +1,7 @@ +contract test { + uint256 stateVar; + function functionName() {} +} +// ---- +// Warning: (36-62): No visibility specified. Defaulting to "public". +// Warning: (36-62): Function state mutability can be restricted to pure diff --git a/test/libsolidity/syntaxTests/parsing/payable_accessor.sol b/test/libsolidity/syntaxTests/parsing/payable_accessor.sol new file mode 100644 index 00000000..44b04afd --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/payable_accessor.sol @@ -0,0 +1,5 @@ +contract test { + uint payable x; +} +// ---- +// ParserError: (22-22): Expected token Identifier got 'Payable' diff --git a/test/libsolidity/syntaxTests/parsing/scientific_notation.sol b/test/libsolidity/syntaxTests/parsing/scientific_notation.sol new file mode 100644 index 00000000..5d656508 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/scientific_notation.sol @@ -0,0 +1,7 @@ +contract test { + uint256 a = 2e10; + uint256 b = 2E10; + uint256 c = 200e-2; + uint256 d = 2E10 wei; + uint256 e = 2.5e10; +} diff --git a/test/libsolidity/syntaxTests/parsing/single_function_param.sol b/test/libsolidity/syntaxTests/parsing/single_function_param.sol new file mode 100644 index 00000000..08e531f1 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/single_function_param.sol @@ -0,0 +1,9 @@ +contract test { + uint256 stateVar; + function functionName(bytes32 input) returns (bytes32 out) {} +} +// ---- +// Warning: (36-97): No visibility specified. Defaulting to "public". +// Warning: (58-71): Unused function parameter. Remove or comment out the variable name to silence this warning. +// Warning: (82-93): Unused function parameter. Remove or comment out the variable name to silence this warning. +// Warning: (36-97): Function state mutability can be restricted to pure diff --git a/test/libsolidity/syntaxTests/parsing/single_function_param_trailing_comma.sol b/test/libsolidity/syntaxTests/parsing/single_function_param_trailing_comma.sol new file mode 100644 index 00000000..1febdab9 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/single_function_param_trailing_comma.sol @@ -0,0 +1,5 @@ +contract test { + function(uint a,) {} +} +// ---- +// ParserError: (32-32): Unexpected trailing comma in parameter list. diff --git a/test/libsolidity/syntaxTests/parsing/single_return_param_trailing_comma.sol b/test/libsolidity/syntaxTests/parsing/single_return_param_trailing_comma.sol new file mode 100644 index 00000000..d2e3bbb3 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/single_return_param_trailing_comma.sol @@ -0,0 +1,5 @@ +contract test { + function() returns (uint a,) {} +} +// ---- +// ParserError: (43-43): Unexpected trailing comma in parameter list. diff --git a/test/libsolidity/syntaxTests/parsing/trailing_comma_in_named_args.sol b/test/libsolidity/syntaxTests/parsing/trailing_comma_in_named_args.sol new file mode 100644 index 00000000..22efc58a --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/trailing_comma_in_named_args.sol @@ -0,0 +1,6 @@ +contract test { + function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; } + function b() returns (uint r) { r = a({a: 1, b: 2, c: 3, }); } +} +// ---- +// ParserError: (159-159): Unexpected trailing comma. diff --git a/test/libsolidity/syntaxTests/parsing/tuples_without_commas.sol b/test/libsolidity/syntaxTests/parsing/tuples_without_commas.sol new file mode 100644 index 00000000..d0e376b0 --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/tuples_without_commas.sol @@ -0,0 +1,7 @@ +contract C { + function f() { + var a = (2 2); + } +} +// ---- +// ParserError: (42-42): Expected token Comma got 'Number' diff --git a/test/libsolidity/syntaxTests/parsing/var_array.sol b/test/libsolidity/syntaxTests/parsing/var_array.sol new file mode 100644 index 00000000..86fc4fcb --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/var_array.sol @@ -0,0 +1,5 @@ +contract Foo { + function f() { var[] a; } +} +// ---- +// ParserError: (34-34): Expected token Identifier got 'LBrack' diff --git a/test/libsolidity/syntaxTests/parsing/variable_definition_in_mapping.sol b/test/libsolidity/syntaxTests/parsing/variable_definition_in_mapping.sol new file mode 100644 index 00000000..ec55a4db --- /dev/null +++ b/test/libsolidity/syntaxTests/parsing/variable_definition_in_mapping.sol @@ -0,0 +1,7 @@ +contract test { + function fun() { + mapping(var=>bytes32) d; + } +} +// ---- +// ParserError: (44-44): Expected elementary type name for mapping key type |