From 533d1a1081c95cd6276e478bf180e060b93b39fd Mon Sep 17 00:00:00 2001 From: chriseth Date: Thu, 20 Aug 2015 02:16:43 +0200 Subject: [PATCH] Removed Solidity after move to its own repository. --- CMakeLists.txt | 25 +- doc/Doxyfile | 1 - libsolidity/AST.cpp | 1164 ---- libsolidity/AST.h | 1355 ----- libsolidity/ASTForward.h | 94 - libsolidity/ASTJsonConverter.cpp | 437 -- libsolidity/ASTJsonConverter.h | 130 - libsolidity/ASTPrinter.cpp | 538 -- libsolidity/ASTPrinter.h | 141 - libsolidity/ASTUtils.cpp | 48 - libsolidity/ASTUtils.h | 54 - libsolidity/ASTVisitor.h | 286 - libsolidity/AST_accept.h | 685 --- libsolidity/ArrayUtils.cpp | 786 --- libsolidity/ArrayUtils.h | 98 - libsolidity/CMakeLists.txt | 25 - libsolidity/Compiler.cpp | 726 --- libsolidity/Compiler.h | 143 - libsolidity/CompilerContext.cpp | 214 - libsolidity/CompilerContext.h | 183 - libsolidity/CompilerStack.cpp | 391 -- libsolidity/CompilerStack.h | 198 - libsolidity/CompilerUtils.cpp | 734 --- libsolidity/CompilerUtils.h | 178 - libsolidity/DeclarationContainer.cpp | 85 - libsolidity/DeclarationContainer.h | 65 - libsolidity/Exceptions.h | 60 - libsolidity/ExpressionCompiler.cpp | 1271 ---- libsolidity/ExpressionCompiler.h | 134 - libsolidity/GasEstimator.cpp | 191 - libsolidity/GasEstimator.h | 83 - libsolidity/GlobalContext.cpp | 96 - libsolidity/GlobalContext.h | 64 - libsolidity/InterfaceHandler.cpp | 446 -- libsolidity/InterfaceHandler.h | 132 - libsolidity/LValue.cpp | 457 -- libsolidity/LValue.h | 196 - libsolidity/NameAndTypeResolver.cpp | 530 -- libsolidity/NameAndTypeResolver.h | 160 - libsolidity/Parser.cpp | 1082 ---- libsolidity/Parser.h | 148 - libsolidity/Scanner.cpp | 769 --- libsolidity/Scanner.h | 224 - libsolidity/SourceReferenceFormatter.cpp | 126 - libsolidity/SourceReferenceFormatter.h | 54 - libsolidity/Token.cpp | 100 - libsolidity/Token.h | 406 -- libsolidity/Types.cpp | 1758 ------ libsolidity/Types.h | 935 --- libsolidity/Utils.h | 30 - libsolidity/Version.cpp | 39 - libsolidity/Version.h | 36 - libsolidity/grammar.txt | 47 - solc/CMakeLists.txt | 29 - solc/CommandLineInterface.cpp | 657 --- solc/CommandLineInterface.h | 75 - solc/docker_emscripten/Dockerfile | 70 - solc/jsonCompiler.cpp | 196 - solc/main.cpp | 35 - test/CMakeLists.txt | 8 - test/contracts/AuctionRegistrar.cpp | 497 -- test/contracts/CMakeLists.txt | 5 - test/contracts/FixedFeeRegistrar.cpp | 242 - test/contracts/Wallet.cpp | 668 --- test/libsolidity/Assembly.cpp | 120 - test/libsolidity/CMakeLists.txt | 5 - test/libsolidity/GasMeter.cpp | 235 - test/libsolidity/SolidityABIJSON.cpp | 602 -- test/libsolidity/SolidityEndToEndTest.cpp | 5168 ----------------- .../SolidityExpressionCompiler.cpp | 491 -- test/libsolidity/SolidityInterface.cpp | 149 - .../SolidityNameAndTypeResolution.cpp | 2201 ------- test/libsolidity/SolidityNatspecJSON.cpp | 534 -- test/libsolidity/SolidityOptimizer.cpp | 1132 ---- test/libsolidity/SolidityParser.cpp | 921 --- test/libsolidity/SolidityScanner.cpp | 288 - test/libsolidity/SolidityTypes.cpp | 93 - test/libsolidity/solidityExecutionFramework.h | 310 - 78 files changed, 1 insertion(+), 33088 deletions(-) delete mode 100644 libsolidity/AST.cpp delete mode 100644 libsolidity/AST.h delete mode 100644 libsolidity/ASTForward.h delete mode 100644 libsolidity/ASTJsonConverter.cpp delete mode 100644 libsolidity/ASTJsonConverter.h delete mode 100644 libsolidity/ASTPrinter.cpp delete mode 100644 libsolidity/ASTPrinter.h delete mode 100644 libsolidity/ASTUtils.cpp delete mode 100644 libsolidity/ASTUtils.h delete mode 100644 libsolidity/ASTVisitor.h delete mode 100644 libsolidity/AST_accept.h delete mode 100644 libsolidity/ArrayUtils.cpp delete mode 100644 libsolidity/ArrayUtils.h delete mode 100644 libsolidity/CMakeLists.txt delete mode 100644 libsolidity/Compiler.cpp delete mode 100644 libsolidity/Compiler.h delete mode 100644 libsolidity/CompilerContext.cpp delete mode 100644 libsolidity/CompilerContext.h delete mode 100644 libsolidity/CompilerStack.cpp delete mode 100644 libsolidity/CompilerStack.h delete mode 100644 libsolidity/CompilerUtils.cpp delete mode 100644 libsolidity/CompilerUtils.h delete mode 100644 libsolidity/DeclarationContainer.cpp delete mode 100644 libsolidity/DeclarationContainer.h delete mode 100644 libsolidity/Exceptions.h delete mode 100644 libsolidity/ExpressionCompiler.cpp delete mode 100644 libsolidity/ExpressionCompiler.h delete mode 100644 libsolidity/GasEstimator.cpp delete mode 100644 libsolidity/GasEstimator.h delete mode 100644 libsolidity/GlobalContext.cpp delete mode 100644 libsolidity/GlobalContext.h delete mode 100644 libsolidity/InterfaceHandler.cpp delete mode 100644 libsolidity/InterfaceHandler.h delete mode 100644 libsolidity/LValue.cpp delete mode 100644 libsolidity/LValue.h delete mode 100644 libsolidity/NameAndTypeResolver.cpp delete mode 100644 libsolidity/NameAndTypeResolver.h delete mode 100644 libsolidity/Parser.cpp delete mode 100644 libsolidity/Parser.h delete mode 100644 libsolidity/Scanner.cpp delete mode 100644 libsolidity/Scanner.h delete mode 100644 libsolidity/SourceReferenceFormatter.cpp delete mode 100644 libsolidity/SourceReferenceFormatter.h delete mode 100644 libsolidity/Token.cpp delete mode 100644 libsolidity/Token.h delete mode 100644 libsolidity/Types.cpp delete mode 100644 libsolidity/Types.h delete mode 100644 libsolidity/Utils.h delete mode 100644 libsolidity/Version.cpp delete mode 100644 libsolidity/Version.h delete mode 100644 libsolidity/grammar.txt delete mode 100644 solc/CMakeLists.txt delete mode 100644 solc/CommandLineInterface.cpp delete mode 100644 solc/CommandLineInterface.h delete mode 100644 solc/docker_emscripten/Dockerfile delete mode 100644 solc/jsonCompiler.cpp delete mode 100644 solc/main.cpp delete mode 100644 test/contracts/AuctionRegistrar.cpp delete mode 100644 test/contracts/CMakeLists.txt delete mode 100644 test/contracts/FixedFeeRegistrar.cpp delete mode 100644 test/contracts/Wallet.cpp delete mode 100644 test/libsolidity/Assembly.cpp delete mode 100644 test/libsolidity/CMakeLists.txt delete mode 100644 test/libsolidity/GasMeter.cpp delete mode 100644 test/libsolidity/SolidityABIJSON.cpp delete mode 100644 test/libsolidity/SolidityEndToEndTest.cpp delete mode 100644 test/libsolidity/SolidityExpressionCompiler.cpp delete mode 100644 test/libsolidity/SolidityInterface.cpp delete mode 100644 test/libsolidity/SolidityNameAndTypeResolution.cpp delete mode 100644 test/libsolidity/SolidityNatspecJSON.cpp delete mode 100644 test/libsolidity/SolidityOptimizer.cpp delete mode 100644 test/libsolidity/SolidityParser.cpp delete mode 100644 test/libsolidity/SolidityScanner.cpp delete mode 100644 test/libsolidity/SolidityTypes.cpp delete mode 100644 test/libsolidity/solidityExecutionFramework.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 913349819..7e8a38313 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,7 +43,6 @@ endif () #defaults: set(D_CMAKE_BUILD_TYPE "RelWithDebInfo") set(D_SERPENT ${DECENT_PLATFORM}) -set(D_SOLIDITY ON) set(D_USENPM OFF) set(D_GUI ON) set(D_TOOLS ON) @@ -64,14 +63,12 @@ set(D_ETHKEY ON) if (BUNDLE STREQUAL "minimal") set(D_SERPENT OFF) - set(D_SOLIDITY OFF) set(D_USENPM OFF) set(D_GUI OFF) set(D_TOOLS ON) set(D_TESTS OFF) elseif (BUNDLE STREQUAL "full") set(D_SERPENT ${DECENT_PLATFORM}) - set(D_SOLIDITY ON) set(D_USENPM ON) set(D_GUI ON) set(D_TOOLS ON) @@ -79,7 +76,6 @@ elseif (BUNDLE STREQUAL "full") set(D_FATDB ON) elseif (BUNDLE STREQUAL "cli") set(D_SERPENT ${DECENT_PLATFORM}) - set(D_SOLIDITY ON) set(D_USENPM ON) set(D_GUI OFF) set(D_TOOLS ON) @@ -87,7 +83,6 @@ elseif (BUNDLE STREQUAL "cli") set(D_FATDB ON) elseif (BUNDLE STREQUAL "core") set(D_SERPENT OFF) - set(D_SOLIDITY ON) set(D_USENPM OFF) set(D_GUI ON) set(D_TOOLS ON) @@ -95,7 +90,6 @@ elseif (BUNDLE STREQUAL "core") set(D_FATDB ON) elseif (BUNDLE STREQUAL "tests") set(D_SERPENT ${DECENT_PLATFORM}) - set(D_SOLIDITY ON) set(D_USENPM OFF) set(D_GUI OFF) set(D_TOOLS OFF) @@ -103,14 +97,12 @@ elseif (BUNDLE STREQUAL "tests") set(D_FATDB ON) elseif (BUNDLE STREQUAL "user") set(D_SERPENT OFF) - set(D_SOLIDITY OFF) set(D_USENPM OFF) set(D_GUI ON) set(D_TOOLS ON) set(D_TESTS OFF) elseif (BUNDLE STREQUAL "wallet") set(D_SERPENT OFF) - set(D_SOLIDITY OFF) set(D_USENPM OFF) set(D_GUI OFF) set(D_TOOLS OFF) @@ -124,7 +116,6 @@ elseif (BUNDLE STREQUAL "wallet") set(D_EVMJIT OFF) elseif (BUNDLE STREQUAL "miner") set(D_SERPENT OFF) - set(D_SOLIDITY OFF) set(D_USENPM OFF) set(D_GUI OFF) set(D_TOOLS OFF) @@ -138,7 +129,6 @@ elseif (BUNDLE STREQUAL "miner") set(D_EVMJIT OFF) elseif (BUNDLE STREQUAL "release") # release builds set(D_SERPENT ${DECENT_PLATFORM}) - set(D_SOLIDITY ON) set(D_USENPM OFF) set(D_GUI ON) set(D_TOOLS ON) @@ -177,10 +167,6 @@ function(configureProject) add_definitions(-DETH_FATDB) endif() - if (SOLIDITY) - add_definitions(-DETH_SOLIDITY) - endif() - if (GUI) add_definitions(-DETH_GUI) endif() @@ -303,7 +289,6 @@ eth_format_option(JSONRPC) eth_format_option(MINER) eth_format_option(USENPM) eth_format_option(PROFILING) -eth_format_option(SOLIDITY) eth_format_option(ROCKSDB) eth_format_option(GUI) eth_format_option(TESTS) @@ -359,7 +344,6 @@ message("------------------------------------------------------------- component message("-- MINER Build miner ${MINER}") message("-- ETHKEY Build wallet tools ${ETHKEY}") message("-- TOOLS Build basic tools ${TOOLS}") -message("-- SOLIDITY Build Solidity language components ${SOLIDITY}") message("-- SERPENT Build Serpent language components ${SERPENT}") message("-- GUI Build GUI components ${GUI}") message("-- TESTS Build tests ${TESTS}") @@ -406,7 +390,7 @@ if (EVMJIT) endif() endif() -if (TOOLS OR GUI OR SOLIDITY OR TESTS) +if (TOOLS OR GUI OR TESTS) set(GENERAL 1) else () set(GENERAL 0) @@ -424,15 +408,8 @@ if (SERPENT) add_subdirectory(sc) endif () -if (SOLIDITY) - add_subdirectory(libsolidity) -endif () - if (TOOLS) add_subdirectory(lllc) - if (SOLIDITY) - add_subdirectory(solc) - endif () endif () if (JSONRPC AND GENERAL) diff --git a/doc/Doxyfile b/doc/Doxyfile index 71ca04136..83511ea7a 100644 --- a/doc/Doxyfile +++ b/doc/Doxyfile @@ -760,7 +760,6 @@ INPUT = ../libdevcore \ ../libevmface \ ../libevm \ ../liblll \ - ../libsolidity \ ../mix \ ../libwhisper \ ../libwebthree diff --git a/libsolidity/AST.cpp b/libsolidity/AST.cpp deleted file mode 100644 index 8bad6ccf8..000000000 --- a/libsolidity/AST.cpp +++ /dev/null @@ -1,1164 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity abstract syntax tree. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -TypeError ASTNode::createTypeError(string const& _description) const -{ - return TypeError() << errinfo_sourceLocation(getLocation()) << errinfo_comment(_description); -} - -TypePointer ContractDefinition::getType(ContractDefinition const* _currentContract) const -{ - return make_shared(make_shared(*this), _currentContract); -} - -void ContractDefinition::checkTypeRequirements() -{ - for (ASTPointer const& baseSpecifier: getBaseContracts()) - baseSpecifier->checkTypeRequirements(); - - checkDuplicateFunctions(); - checkIllegalOverrides(); - checkAbstractFunctions(); - checkAbstractConstructors(); - - FunctionDefinition const* constructor = getConstructor(); - if (constructor && !constructor->getReturnParameters().empty()) - BOOST_THROW_EXCEPTION(constructor->getReturnParameterList()->createTypeError( - "Non-empty \"returns\" directive for constructor.")); - - FunctionDefinition const* fallbackFunction = nullptr; - for (ASTPointer const& function: getDefinedFunctions()) - { - if (function->getName().empty()) - { - if (fallbackFunction) - BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_comment("Only one fallback function is allowed.")); - else - { - fallbackFunction = function.get(); - if (!fallbackFunction->getParameters().empty()) - BOOST_THROW_EXCEPTION(fallbackFunction->getParameterList().createTypeError("Fallback function cannot take parameters.")); - } - } - if (!function->isFullyImplemented()) - setFullyImplemented(false); - } - for (ASTPointer const& modifier: getFunctionModifiers()) - modifier->checkTypeRequirements(); - - for (ASTPointer const& function: getDefinedFunctions()) - function->checkTypeRequirements(); - - for (ASTPointer const& variable: m_stateVariables) - variable->checkTypeRequirements(); - - checkExternalTypeClashes(); - // check for hash collisions in function signatures - set> hashes; - for (auto const& it: getInterfaceFunctionList()) - { - FixedHash<4> const& hash = it.first; - if (hashes.count(hash)) - BOOST_THROW_EXCEPTION(createTypeError( - string("Function signature hash collision for ") + it.second->externalSignature() - )); - hashes.insert(hash); - } -} - -map, FunctionTypePointer> ContractDefinition::getInterfaceFunctions() const -{ - auto exportedFunctionList = getInterfaceFunctionList(); - - map, FunctionTypePointer> exportedFunctions; - for (auto const& it: exportedFunctionList) - exportedFunctions.insert(it); - - solAssert(exportedFunctionList.size() == exportedFunctions.size(), - "Hash collision at Function Definition Hash calculation"); - - return exportedFunctions; -} - -FunctionDefinition const* ContractDefinition::getConstructor() const -{ - for (ASTPointer const& f: m_definedFunctions) - if (f->isConstructor()) - return f.get(); - return nullptr; -} - -FunctionDefinition const* ContractDefinition::getFallbackFunction() const -{ - for (ContractDefinition const* contract: getLinearizedBaseContracts()) - for (ASTPointer const& f: contract->getDefinedFunctions()) - if (f->getName().empty()) - return f.get(); - return nullptr; -} - -void ContractDefinition::checkDuplicateFunctions() const -{ - /// Checks that two functions with the same name defined in this contract have different - /// argument types and that there is at most one constructor. - map> functions; - for (ASTPointer const& function: getDefinedFunctions()) - functions[function->getName()].push_back(function.get()); - - if (functions[getName()].size() > 1) - { - SecondarySourceLocation ssl; - auto it = functions[getName()].begin(); - ++it; - for (; it != functions[getName()].end(); ++it) - ssl.append("Another declaration is here:", (*it)->getLocation()); - - BOOST_THROW_EXCEPTION( - DeclarationError() << - errinfo_sourceLocation(functions[getName()].front()->getLocation()) << - errinfo_comment("More than one constructor defined.") << - errinfo_secondarySourceLocation(ssl) - ); - } - for (auto const& it: functions) - { - vector const& overloads = it.second; - for (size_t i = 0; i < overloads.size(); ++i) - for (size_t j = i + 1; j < overloads.size(); ++j) - if (FunctionType(*overloads[i]).hasEqualArgumentTypes(FunctionType(*overloads[j]))) - BOOST_THROW_EXCEPTION( - DeclarationError() << - errinfo_sourceLocation(overloads[j]->getLocation()) << - errinfo_comment("Function with same name and arguments defined twice.") << - errinfo_secondarySourceLocation(SecondarySourceLocation().append( - "Other declaration is here:", overloads[i]->getLocation())) - ); - } -} - -void ContractDefinition::checkAbstractFunctions() -{ - // Mapping from name to function definition (exactly one per argument type equality class) and - // flag to indicate whether it is fully implemented. - using FunTypeAndFlag = std::pair; - map> functions; - - // Search from base to derived - for (ContractDefinition const* contract: boost::adaptors::reverse(getLinearizedBaseContracts())) - for (ASTPointer const& function: contract->getDefinedFunctions()) - { - auto& overloads = functions[function->getName()]; - FunctionTypePointer funType = make_shared(*function); - auto it = find_if(overloads.begin(), overloads.end(), [&](FunTypeAndFlag const& _funAndFlag) - { - return funType->hasEqualArgumentTypes(*_funAndFlag.first); - }); - if (it == overloads.end()) - overloads.push_back(make_pair(funType, function->isFullyImplemented())); - else if (it->second) - { - if (!function->isFullyImplemented()) - BOOST_THROW_EXCEPTION(function->createTypeError("Redeclaring an already implemented function as abstract")); - } - else if (function->isFullyImplemented()) - it->second = true; - } - - // Set to not fully implemented if at least one flag is false. - for (auto const& it: functions) - for (auto const& funAndFlag: it.second) - if (!funAndFlag.second) - { - setFullyImplemented(false); - return; - } -} - -void ContractDefinition::checkAbstractConstructors() -{ - set argumentsNeeded; - // check that we get arguments for all base constructors that need it. - // If not mark the contract as abstract (not fully implemented) - - vector const& bases = getLinearizedBaseContracts(); - for (ContractDefinition const* contract: bases) - if (FunctionDefinition const* constructor = contract->getConstructor()) - if (contract != this && !constructor->getParameters().empty()) - argumentsNeeded.insert(contract); - - for (ContractDefinition const* contract: bases) - { - if (FunctionDefinition const* constructor = contract->getConstructor()) - for (auto const& modifier: constructor->getModifiers()) - { - auto baseContract = dynamic_cast( - &modifier->getName()->getReferencedDeclaration() - ); - if (baseContract) - argumentsNeeded.erase(baseContract); - } - - - for (ASTPointer const& base: contract->getBaseContracts()) - { - auto baseContract = dynamic_cast( - &base->getName()->getReferencedDeclaration() - ); - solAssert(baseContract, ""); - if (!base->getArguments().empty()) - argumentsNeeded.erase(baseContract); - } - } - if (!argumentsNeeded.empty()) - setFullyImplemented(false); -} - -void ContractDefinition::checkIllegalOverrides() const -{ - // TODO unify this at a later point. for this we need to put the constness and the access specifier - // into the types - map> functions; - map modifiers; - - // We search from derived to base, so the stored item causes the error. - for (ContractDefinition const* contract: getLinearizedBaseContracts()) - { - for (ASTPointer const& function: contract->getDefinedFunctions()) - { - if (function->isConstructor()) - continue; // constructors can neither be overridden nor override anything - string const& name = function->getName(); - if (modifiers.count(name)) - BOOST_THROW_EXCEPTION(modifiers[name]->createTypeError("Override changes function to modifier.")); - FunctionType functionType(*function); - // function should not change the return type - for (FunctionDefinition const* overriding: functions[name]) - { - FunctionType overridingType(*overriding); - if (!overridingType.hasEqualArgumentTypes(functionType)) - continue; - if ( - overriding->getVisibility() != function->getVisibility() || - overriding->isDeclaredConst() != function->isDeclaredConst() || - overridingType != functionType - ) - BOOST_THROW_EXCEPTION(overriding->createTypeError("Override changes extended function signature.")); - } - functions[name].push_back(function.get()); - } - for (ASTPointer const& modifier: contract->getFunctionModifiers()) - { - string const& name = modifier->getName(); - ModifierDefinition const*& override = modifiers[name]; - if (!override) - override = modifier.get(); - else if (ModifierType(*override) != ModifierType(*modifier)) - BOOST_THROW_EXCEPTION(override->createTypeError("Override changes modifier signature.")); - if (!functions[name].empty()) - BOOST_THROW_EXCEPTION(override->createTypeError("Override changes modifier to function.")); - } - } -} - -void ContractDefinition::checkExternalTypeClashes() const -{ - map>>> externalDeclarations; - for (ContractDefinition const* contract: getLinearizedBaseContracts()) - { - for (ASTPointer const& f: contract->getDefinedFunctions()) - if (f->isPartOfExternalInterface()) - { - auto functionType = make_shared(*f); - externalDeclarations[functionType->externalSignature(f->getName())].push_back( - make_pair(f.get(), functionType) - ); - } - for (ASTPointer const& v: contract->getStateVariables()) - if (v->isPartOfExternalInterface()) - { - auto functionType = make_shared(*v); - externalDeclarations[functionType->externalSignature(v->getName())].push_back( - make_pair(v.get(), functionType) - ); - } - } - for (auto const& it: externalDeclarations) - for (size_t i = 0; i < it.second.size(); ++i) - for (size_t j = i + 1; j < it.second.size(); ++j) - if (!it.second[i].second->hasEqualArgumentTypes(*it.second[j].second)) - BOOST_THROW_EXCEPTION(it.second[j].first->createTypeError( - "Function overload clash during conversion to external types for arguments." - )); -} - -vector> const& ContractDefinition::getInterfaceEvents() const -{ - if (!m_interfaceEvents) - { - set eventsSeen; - m_interfaceEvents.reset(new vector>()); - for (ContractDefinition const* contract: getLinearizedBaseContracts()) - for (ASTPointer const& e: contract->getEvents()) - if (eventsSeen.count(e->getName()) == 0) - { - eventsSeen.insert(e->getName()); - m_interfaceEvents->push_back(e); - } - } - return *m_interfaceEvents; -} - -vector, FunctionTypePointer>> const& ContractDefinition::getInterfaceFunctionList() const -{ - if (!m_interfaceFunctionList) - { - set functionsSeen; - set signaturesSeen; - m_interfaceFunctionList.reset(new vector, FunctionTypePointer>>()); - for (ContractDefinition const* contract: getLinearizedBaseContracts()) - { - for (ASTPointer const& f: contract->getDefinedFunctions()) - { - if (!f->isPartOfExternalInterface()) - continue; - string functionSignature = f->externalSignature(); - if (signaturesSeen.count(functionSignature) == 0) - { - functionsSeen.insert(f->getName()); - signaturesSeen.insert(functionSignature); - FixedHash<4> hash(dev::sha3(functionSignature)); - m_interfaceFunctionList->push_back(make_pair(hash, make_shared(*f, false))); - } - } - - for (ASTPointer const& v: contract->getStateVariables()) - if (functionsSeen.count(v->getName()) == 0 && v->isPartOfExternalInterface()) - { - FunctionType ftype(*v); - solAssert(v->getType().get(), ""); - functionsSeen.insert(v->getName()); - FixedHash<4> hash(dev::sha3(ftype.externalSignature(v->getName()))); - m_interfaceFunctionList->push_back(make_pair(hash, make_shared(*v))); - } - } - } - return *m_interfaceFunctionList; -} - -string const& ContractDefinition::devDocumentation() const -{ - return m_devDocumentation; -} - -string const& ContractDefinition::userDocumentation() const -{ - return m_userDocumentation; -} - -void ContractDefinition::setDevDocumentation(string const& _devDocumentation) -{ - m_devDocumentation = _devDocumentation; -} - -void ContractDefinition::setUserDocumentation(string const& _userDocumentation) -{ - m_userDocumentation = _userDocumentation; -} - - -vector const& ContractDefinition::getInheritableMembers() const -{ - if (!m_inheritableMembers) - { - set memberSeen; - m_inheritableMembers.reset(new vector()); - auto addInheritableMember = [&](Declaration const* _decl) - { - if (memberSeen.count(_decl->getName()) == 0 && _decl->isVisibleInDerivedContracts()) - { - memberSeen.insert(_decl->getName()); - m_inheritableMembers->push_back(_decl); - } - }; - - for (ASTPointer const& f: getDefinedFunctions()) - addInheritableMember(f.get()); - - for (ASTPointer const& v: getStateVariables()) - addInheritableMember(v.get()); - - for (ASTPointer const& s: getDefinedStructs()) - addInheritableMember(s.get()); - } - return *m_inheritableMembers; -} - -TypePointer EnumValue::getType(ContractDefinition const*) const -{ - EnumDefinition const* parentDef = dynamic_cast(getScope()); - solAssert(parentDef, "Enclosing Scope of EnumValue was not set"); - return make_shared(*parentDef); -} - -void InheritanceSpecifier::checkTypeRequirements() -{ - m_baseName->checkTypeRequirements(nullptr); - for (ASTPointer const& argument: m_arguments) - argument->checkTypeRequirements(nullptr); - - ContractDefinition const* base = dynamic_cast(&m_baseName->getReferencedDeclaration()); - solAssert(base, "Base contract not available."); - TypePointers parameterTypes = ContractType(*base).getConstructorType()->getParameterTypes(); - if (!m_arguments.empty() && parameterTypes.size() != m_arguments.size()) - BOOST_THROW_EXCEPTION(createTypeError( - "Wrong argument count for constructor call: " + - toString(m_arguments.size()) + - " arguments given but expected " + - toString(parameterTypes.size()) + - "." - )); - - for (size_t i = 0; i < m_arguments.size(); ++i) - if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i])) - BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( - "Invalid type for argument in constructor call. " - "Invalid implicit conversion from " + - m_arguments[i]->getType()->toString() + - " to " + - parameterTypes[i]->toString() + - " requested." - )); -} - -TypePointer StructDefinition::getType(ContractDefinition const*) const -{ - return make_shared(make_shared(*this)); -} - -void StructDefinition::checkMemberTypes() const -{ - for (ASTPointer const& member: getMembers()) - if (!member->getType()->canBeStored()) - BOOST_THROW_EXCEPTION(member->createTypeError("Type cannot be used in struct.")); -} - -void StructDefinition::checkRecursion() const -{ - using StructPointer = StructDefinition const*; - using StructPointersSet = set; - function check = [&](StructPointer _struct, StructPointersSet const& _parents) - { - if (_parents.count(_struct)) - BOOST_THROW_EXCEPTION( - ParserError() << - errinfo_sourceLocation(_struct->getLocation()) << - errinfo_comment("Recursive struct definition.") - ); - set parents = _parents; - parents.insert(_struct); - for (ASTPointer const& member: _struct->getMembers()) - if (member->getType()->getCategory() == Type::Category::Struct) - { - auto const& typeName = dynamic_cast(*member->getTypeName()); - check( - &dynamic_cast(*typeName.getReferencedDeclaration()), - parents - ); - } - }; - check(this, StructPointersSet{}); -} - -TypePointer EnumDefinition::getType(ContractDefinition const*) const -{ - return make_shared(make_shared(*this)); -} - -TypePointer FunctionDefinition::getType(ContractDefinition const*) const -{ - return make_shared(*this); -} - -void FunctionDefinition::checkTypeRequirements() -{ - for (ASTPointer const& var: getParameters() + getReturnParameters()) - { - if (!var->getType()->canLiveOutsideStorage()) - BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage.")); - if (getVisibility() >= Visibility::Public && !(var->getType()->externalType())) - BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed for public and external functions.")); - } - for (ASTPointer const& modifier: m_functionModifiers) - modifier->checkTypeRequirements(isConstructor() ? - dynamic_cast(*getScope()).getLinearizedBaseContracts() : - vector()); - if (m_body) - m_body->checkTypeRequirements(); -} - -string FunctionDefinition::externalSignature() const -{ - return FunctionType(*this).externalSignature(getName()); -} - -bool VariableDeclaration::isLValue() const -{ - // External function parameters and constant declared variables are Read-Only - return !isExternalCallableParameter() && !m_isConstant; -} - -void VariableDeclaration::checkTypeRequirements() -{ - // Variables can be declared without type (with "var"), in which case the first assignment - // sets the type. - // Note that assignments before the first declaration are legal because of the special scoping - // rules inherited from JavaScript. - if (m_isConstant) - { - if (!dynamic_cast(getScope())) - BOOST_THROW_EXCEPTION(createTypeError("Illegal use of \"constant\" specifier.")); - if ((m_type && !m_type->isValueType()) || !m_value) - BOOST_THROW_EXCEPTION(createTypeError("Unitialized \"constant\" variable.")); - } - if (m_type) - { - if (m_value) - m_value->expectType(*m_type); - } - else - { - if (!m_value) - // This feature might be extended in the future. - BOOST_THROW_EXCEPTION(createTypeError("Assignment necessary for type detection.")); - m_value->checkTypeRequirements(nullptr); - - TypePointer const& type = m_value->getType(); - if ( - type->getCategory() == Type::Category::IntegerConstant && - !dynamic_pointer_cast(type)->getIntegerType() - ) - BOOST_THROW_EXCEPTION(m_value->createTypeError("Invalid integer constant " + type->toString() + ".")); - else if (type->getCategory() == Type::Category::Void) - BOOST_THROW_EXCEPTION(createTypeError("Variable cannot have void type.")); - m_type = type->mobileType(); - } - solAssert(!!m_type, ""); - if (!m_isStateVariable) - { - if (m_type->dataStoredIn(DataLocation::Memory) || m_type->dataStoredIn(DataLocation::CallData)) - if (!m_type->canLiveOutsideStorage()) - BOOST_THROW_EXCEPTION(createTypeError( - "Type " + m_type->toString() + " is only valid in storage." - )); - } - else if (getVisibility() >= Visibility::Public && !FunctionType(*this).externalType()) - BOOST_THROW_EXCEPTION(createTypeError("Internal type is not allowed for public state variables.")); -} - -bool VariableDeclaration::isCallableParameter() const -{ - auto const* callable = dynamic_cast(getScope()); - if (!callable) - return false; - for (auto const& variable: callable->getParameters()) - if (variable.get() == this) - return true; - if (callable->getReturnParameterList()) - for (auto const& variable: callable->getReturnParameterList()->getParameters()) - if (variable.get() == this) - return true; - return false; -} - -bool VariableDeclaration::isExternalCallableParameter() const -{ - auto const* callable = dynamic_cast(getScope()); - if (!callable || callable->getVisibility() != Declaration::Visibility::External) - return false; - for (auto const& variable: callable->getParameters()) - if (variable.get() == this) - return true; - return false; -} - -TypePointer ModifierDefinition::getType(ContractDefinition const*) const -{ - return make_shared(*this); -} - -void ModifierDefinition::checkTypeRequirements() -{ - m_body->checkTypeRequirements(); -} - -void ModifierInvocation::checkTypeRequirements(vector const& _bases) -{ - TypePointers argumentTypes; - for (ASTPointer const& argument: m_arguments) - { - argument->checkTypeRequirements(nullptr); - argumentTypes.push_back(argument->getType()); - } - m_modifierName->checkTypeRequirements(&argumentTypes); - - auto const* declaration = &m_modifierName->getReferencedDeclaration(); - vector> emptyParameterList; - vector> const* parameters = nullptr; - if (auto modifier = dynamic_cast(declaration)) - parameters = &modifier->getParameters(); - else - // check parameters for Base constructors - for (ContractDefinition const* base: _bases) - if (declaration == base) - { - if (auto referencedConstructor = base->getConstructor()) - parameters = &referencedConstructor->getParameters(); - else - parameters = &emptyParameterList; - break; - } - if (!parameters) - BOOST_THROW_EXCEPTION(createTypeError("Referenced declaration is neither modifier nor base class.")); - if (parameters->size() != m_arguments.size()) - BOOST_THROW_EXCEPTION(createTypeError( - "Wrong argument count for modifier invocation: " + - toString(m_arguments.size()) + - " arguments given but expected " + - toString(parameters->size()) + - "." - )); - for (size_t i = 0; i < m_arguments.size(); ++i) - if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*(*parameters)[i]->getType())) - BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( - "Invalid type for argument in modifier invocation. " - "Invalid implicit conversion from " + - m_arguments[i]->getType()->toString() + - " to " + - (*parameters)[i]->getType()->toString() + - " requested." - )); -} - -void EventDefinition::checkTypeRequirements() -{ - int numIndexed = 0; - for (ASTPointer const& var: getParameters()) - { - if (var->isIndexed()) - numIndexed++; - if (!var->getType()->canLiveOutsideStorage()) - BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage.")); - if (!var->getType()->externalType()) - BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed as event parameter type.")); - } - if (numIndexed > 3) - BOOST_THROW_EXCEPTION(createTypeError("More than 3 indexed arguments for event.")); -} - -void Block::checkTypeRequirements() -{ - for (shared_ptr const& statement: m_statements) - statement->checkTypeRequirements(); -} - -void IfStatement::checkTypeRequirements() -{ - m_condition->expectType(BoolType()); - m_trueBody->checkTypeRequirements(); - if (m_falseBody) - m_falseBody->checkTypeRequirements(); -} - -void WhileStatement::checkTypeRequirements() -{ - m_condition->expectType(BoolType()); - m_body->checkTypeRequirements(); -} - -void ForStatement::checkTypeRequirements() -{ - if (m_initExpression) - m_initExpression->checkTypeRequirements(); - if (m_condExpression) - m_condExpression->expectType(BoolType()); - if (m_loopExpression) - m_loopExpression->checkTypeRequirements(); - m_body->checkTypeRequirements(); -} - -void Return::checkTypeRequirements() -{ - if (!m_expression) - return; - if (!m_returnParameters) - BOOST_THROW_EXCEPTION(createTypeError("Return arguments not allowed.")); - if (m_returnParameters->getParameters().size() != 1) - BOOST_THROW_EXCEPTION(createTypeError("Different number of arguments in return statement " - "than in returns declaration.")); - // this could later be changed such that the paramaters type is an anonymous struct type, - // but for now, we only allow one return parameter - m_expression->expectType(*m_returnParameters->getParameters().front()->getType()); -} - -void VariableDeclarationStatement::checkTypeRequirements() -{ - m_variable->checkTypeRequirements(); -} - -void Assignment::checkTypeRequirements(TypePointers const*) -{ - m_leftHandSide->checkTypeRequirements(nullptr); - m_leftHandSide->requireLValue(); - if (m_leftHandSide->getType()->getCategory() == Type::Category::Mapping) - BOOST_THROW_EXCEPTION(createTypeError("Mappings cannot be assigned to.")); - m_type = m_leftHandSide->getType(); - if (m_assigmentOperator == Token::Assign) - m_rightHandSide->expectType(*m_type); - else - { - // compound assignment - m_rightHandSide->checkTypeRequirements(nullptr); - TypePointer resultType = m_type->binaryOperatorResult(Token::AssignmentToBinaryOp(m_assigmentOperator), - m_rightHandSide->getType()); - if (!resultType || *resultType != *m_type) - BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_assigmentOperator)) + - " not compatible with types " + - m_type->toString() + " and " + - m_rightHandSide->getType()->toString())); - } -} - -void ExpressionStatement::checkTypeRequirements() -{ - m_expression->checkTypeRequirements(nullptr); - if (m_expression->getType()->getCategory() == Type::Category::IntegerConstant) - if (!dynamic_pointer_cast(m_expression->getType())->getIntegerType()) - BOOST_THROW_EXCEPTION(m_expression->createTypeError("Invalid integer constant.")); -} - -void Expression::expectType(Type const& _expectedType) -{ - checkTypeRequirements(nullptr); - Type const& type = *getType(); - if (!type.isImplicitlyConvertibleTo(_expectedType)) - BOOST_THROW_EXCEPTION(createTypeError( - "Type " + - type.toString() + - " is not implicitly convertible to expected type " + - _expectedType.toString() + - "." - )); -} - -void Expression::requireLValue() -{ - if (!isLValue()) - BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue.")); - m_lvalueRequested = true; -} - -void UnaryOperation::checkTypeRequirements(TypePointers const*) -{ - // Inc, Dec, Add, Sub, Not, BitNot, Delete - m_subExpression->checkTypeRequirements(nullptr); - if (m_operator == Token::Value::Inc || m_operator == Token::Value::Dec || m_operator == Token::Value::Delete) - m_subExpression->requireLValue(); - m_type = m_subExpression->getType()->unaryOperatorResult(m_operator); - if (!m_type) - BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type.")); -} - -void BinaryOperation::checkTypeRequirements(TypePointers const*) -{ - m_left->checkTypeRequirements(nullptr); - m_right->checkTypeRequirements(nullptr); - m_commonType = m_left->getType()->binaryOperatorResult(m_operator, m_right->getType()); - if (!m_commonType) - BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_operator)) + - " not compatible with types " + - m_left->getType()->toString() + " and " + - m_right->getType()->toString())); - m_type = Token::isCompareOp(m_operator) ? make_shared() : m_commonType; -} - -void FunctionCall::checkTypeRequirements(TypePointers const*) -{ - bool isPositionalCall = m_names.empty(); - - // we need to check arguments' type first as they will be forwarded to - // m_expression->checkTypeRequirements - TypePointers argumentTypes; - for (ASTPointer const& argument: m_arguments) - { - argument->checkTypeRequirements(nullptr); - // only store them for positional calls - if (isPositionalCall) - argumentTypes.push_back(argument->getType()); - } - - m_expression->checkTypeRequirements(isPositionalCall ? &argumentTypes : nullptr); - - TypePointer const& expressionType = m_expression->getType(); - FunctionTypePointer functionType; - if (isTypeConversion()) - { - TypeType const& type = dynamic_cast(*expressionType); - if (m_arguments.size() != 1) - BOOST_THROW_EXCEPTION(createTypeError("Exactly one argument expected for explicit type conversion.")); - if (!isPositionalCall) - BOOST_THROW_EXCEPTION(createTypeError("Type conversion cannot allow named arguments.")); - m_type = type.getActualType(); - auto argType = m_arguments.front()->getType(); - if (auto argRefType = dynamic_cast(argType.get())) - // do not change the data location when converting - // (data location cannot yet be specified for type conversions) - m_type = ReferenceType::copyForLocationIfReference(argRefType->location(), m_type); - if (!argType->isExplicitlyConvertibleTo(*m_type)) - BOOST_THROW_EXCEPTION(createTypeError("Explicit type conversion not allowed.")); - - return; - } - - /// For error message: Struct members that were removed during conversion to memory. - set membersRemovedForStructConstructor; - if (isStructConstructorCall()) - { - TypeType const& type = dynamic_cast(*expressionType); - auto const& structType = dynamic_cast(*type.getActualType()); - functionType = structType.constructorType(); - membersRemovedForStructConstructor = structType.membersMissingInMemory(); - } - else - functionType = dynamic_pointer_cast(expressionType); - - if (!functionType) - BOOST_THROW_EXCEPTION(createTypeError("Type is not callable.")); - - //@todo would be nice to create a struct type from the arguments - // and then ask if that is implicitly convertible to the struct represented by the - // function parameters - TypePointers const& parameterTypes = functionType->getParameterTypes(); - if (!functionType->takesArbitraryParameters() && parameterTypes.size() != m_arguments.size()) - { - string msg = - "Wrong argument count for function call: " + - toString(m_arguments.size()) + - " arguments given but expected " + - toString(parameterTypes.size()) + - "."; - // Extend error message in case we try to construct a struct with mapping member. - if (isStructConstructorCall() && !membersRemovedForStructConstructor.empty()) - { - msg += " Members that have to be skipped in memory:"; - for (auto const& member: membersRemovedForStructConstructor) - msg += " " + member; - } - BOOST_THROW_EXCEPTION(createTypeError(msg)); - } - - if (isPositionalCall) - { - // call by positional arguments - for (size_t i = 0; i < m_arguments.size(); ++i) - if ( - !functionType->takesArbitraryParameters() && - !m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i]) - ) - BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( - "Invalid type for argument in function call. " - "Invalid implicit conversion from " + - m_arguments[i]->getType()->toString() + - " to " + - parameterTypes[i]->toString() + - " requested." - )); - } - else - { - // call by named arguments - if (functionType->takesArbitraryParameters()) - BOOST_THROW_EXCEPTION(createTypeError( - "Named arguments cannnot be used for functions that take arbitrary parameters." - )); - auto const& parameterNames = functionType->getParameterNames(); - if (parameterNames.size() != m_names.size()) - BOOST_THROW_EXCEPTION(createTypeError("Some argument names are missing.")); - - // check duplicate names - for (size_t i = 0; i < m_names.size(); i++) - for (size_t j = i + 1; j < m_names.size(); j++) - if (*m_names[i] == *m_names[j]) - BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError("Duplicate named argument.")); - - for (size_t i = 0; i < m_names.size(); i++) { - bool found = false; - for (size_t j = 0; j < parameterNames.size(); j++) { - if (parameterNames[j] == *m_names[i]) { - // check type convertible - if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[j])) - BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( - "Invalid type for argument in function call. " - "Invalid implicit conversion from " + - m_arguments[i]->getType()->toString() + - " to " + - parameterTypes[i]->toString() + - " requested." - )); - - found = true; - break; - } - } - if (!found) - BOOST_THROW_EXCEPTION(createTypeError("Named argument does not match function declaration.")); - } - } - - // @todo actually the return type should be an anonymous struct, - // but we change it to the type of the first return value until we have anonymous - // structs and tuples - if (functionType->getReturnParameterTypes().empty()) - m_type = make_shared(); - else - m_type = functionType->getReturnParameterTypes().front(); -} - -bool FunctionCall::isTypeConversion() const -{ - return m_expression->getType()->getCategory() == Type::Category::TypeType && !isStructConstructorCall(); -} - -bool FunctionCall::isStructConstructorCall() const -{ - if (auto const* type = dynamic_cast(m_expression->getType().get())) - return type->getActualType()->getCategory() == Type::Category::Struct; - else - return false; -} - -void NewExpression::checkTypeRequirements(TypePointers const*) -{ - m_contractName->checkTypeRequirements(nullptr); - m_contract = dynamic_cast(&m_contractName->getReferencedDeclaration()); - if (!m_contract) - BOOST_THROW_EXCEPTION(createTypeError("Identifier is not a contract.")); - if (!m_contract->isFullyImplemented()) - BOOST_THROW_EXCEPTION(createTypeError("Trying to create an instance of an abstract contract.")); - shared_ptr contractType = make_shared(*m_contract); - TypePointers const& parameterTypes = contractType->getConstructorType()->getParameterTypes(); - m_type = make_shared( - parameterTypes, - TypePointers{contractType}, - strings(), - strings(), - FunctionType::Location::Creation); -} - -void MemberAccess::checkTypeRequirements(TypePointers const* _argumentTypes) -{ - m_expression->checkTypeRequirements(nullptr); - Type const& type = *m_expression->getType(); - - MemberList::MemberMap possibleMembers = type.getMembers().membersByName(*m_memberName); - if (possibleMembers.size() > 1 && _argumentTypes) - { - // do override resolution - for (auto it = possibleMembers.begin(); it != possibleMembers.end();) - if ( - it->type->getCategory() == Type::Category::Function && - !dynamic_cast(*it->type).canTakeArguments(*_argumentTypes) - ) - it = possibleMembers.erase(it); - else - ++it; - } - if (possibleMembers.size() == 0) - { - auto storageType = ReferenceType::copyForLocationIfReference( - DataLocation::Storage, - m_expression->getType() - ); - if (!storageType->getMembers().membersByName(*m_memberName).empty()) - BOOST_THROW_EXCEPTION(createTypeError( - "Member \"" + *m_memberName + "\" is not available in " + - type.toString() + - " outside of storage." - )); - BOOST_THROW_EXCEPTION(createTypeError( - "Member \"" + *m_memberName + "\" not found or not visible " - "after argument-dependent lookup in " + type.toString() - )); - } - else if (possibleMembers.size() > 1) - BOOST_THROW_EXCEPTION(createTypeError( - "Member \"" + *m_memberName + "\" not unique " - "after argument-dependent lookup in " + type.toString() - )); - - m_referencedDeclaration = possibleMembers.front().declaration; - m_type = possibleMembers.front().type; - if (type.getCategory() == Type::Category::Struct) - m_isLValue = true; - else if (type.getCategory() == Type::Category::Array) - { - auto const& arrayType(dynamic_cast(type)); - m_isLValue = ( - *m_memberName == "length" && - arrayType.location() == DataLocation::Storage && - arrayType.isDynamicallySized() - ); - } - else - m_isLValue = false; -} - -void IndexAccess::checkTypeRequirements(TypePointers const*) -{ - m_base->checkTypeRequirements(nullptr); - switch (m_base->getType()->getCategory()) - { - case Type::Category::Array: - { - ArrayType const& type = dynamic_cast(*m_base->getType()); - if (!m_index) - BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted.")); - if (type.isString()) - BOOST_THROW_EXCEPTION(createTypeError("Index access for string is not possible.")); - m_index->expectType(IntegerType(256)); - if (type.isByteArray()) - m_type = make_shared(1); - else - m_type = type.getBaseType(); - m_isLValue = type.location() != DataLocation::CallData; - break; - } - case Type::Category::Mapping: - { - MappingType const& type = dynamic_cast(*m_base->getType()); - if (!m_index) - BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted.")); - m_index->expectType(*type.getKeyType()); - m_type = type.getValueType(); - m_isLValue = true; - break; - } - case Type::Category::TypeType: - { - TypeType const& type = dynamic_cast(*m_base->getType()); - if (!m_index) - m_type = make_shared(make_shared(DataLocation::Memory, type.getActualType())); - else - { - m_index->checkTypeRequirements(nullptr); - auto length = dynamic_cast(m_index->getType().get()); - if (!length) - BOOST_THROW_EXCEPTION(m_index->createTypeError("Integer constant expected.")); - m_type = make_shared(make_shared( - DataLocation::Memory, type.getActualType(), - length->literalValue(nullptr) - )); - } - break; - } - default: - BOOST_THROW_EXCEPTION(m_base->createTypeError( - "Indexed expression has to be a type, mapping or array (is " + m_base->getType()->toString() + ")")); - } -} - -void Identifier::checkTypeRequirements(TypePointers const* _argumentTypes) -{ - if (!m_referencedDeclaration) - { - if (!_argumentTypes) - BOOST_THROW_EXCEPTION(createTypeError("Unable to determine overloaded type.")); - overloadResolution(*_argumentTypes); - } - solAssert(!!m_referencedDeclaration, "Referenced declaration is null after overload resolution."); - m_isLValue = m_referencedDeclaration->isLValue(); - m_type = m_referencedDeclaration->getType(m_currentContract); - if (!m_type) - BOOST_THROW_EXCEPTION(createTypeError("Declaration referenced before type could be determined.")); -} - -Declaration const& Identifier::getReferencedDeclaration() const -{ - solAssert(!!m_referencedDeclaration, "Identifier not resolved."); - return *m_referencedDeclaration; -} - -void Identifier::overloadResolution(TypePointers const& _argumentTypes) -{ - solAssert(!m_referencedDeclaration, "Referenced declaration should be null before overload resolution."); - solAssert(!m_overloadedDeclarations.empty(), "No candidates for overload resolution found."); - - vector possibles; - if (m_overloadedDeclarations.size() == 1) - m_referencedDeclaration = *m_overloadedDeclarations.begin(); - - for (Declaration const* declaration: m_overloadedDeclarations) - { - TypePointer const& function = declaration->getType(); - auto const* functionType = dynamic_cast(function.get()); - if (functionType && functionType->canTakeArguments(_argumentTypes)) - possibles.push_back(declaration); - } - if (possibles.size() == 1) - m_referencedDeclaration = possibles.front(); - else if (possibles.empty()) - BOOST_THROW_EXCEPTION(createTypeError("No matching declaration found after argument-dependent lookup.")); - else - BOOST_THROW_EXCEPTION(createTypeError("No unique declaration found after argument-dependent lookup.")); -} - -void ElementaryTypeNameExpression::checkTypeRequirements(TypePointers const*) -{ - m_type = make_shared(Type::fromElementaryTypeName(m_typeToken)); -} - -void Literal::checkTypeRequirements(TypePointers const*) -{ - m_type = Type::forLiteral(*this); - if (!m_type) - BOOST_THROW_EXCEPTION(createTypeError("Invalid literal value.")); -} - -} -} diff --git a/libsolidity/AST.h b/libsolidity/AST.h deleted file mode 100644 index fb83d4e11..000000000 --- a/libsolidity/AST.h +++ /dev/null @@ -1,1355 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity abstract syntax tree. - */ - -#pragma once - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -class ASTVisitor; -class ASTConstVisitor; - - -/** - * The root (abstract) class of the AST inheritance tree. - * It is possible to traverse all direct and indirect children of an AST node by calling - * accept, providing an ASTVisitor. - */ -class ASTNode: private boost::noncopyable -{ -public: - explicit ASTNode(SourceLocation const& _location): m_location(_location) {} - - virtual ~ASTNode() {} - - virtual void accept(ASTVisitor& _visitor) = 0; - virtual void accept(ASTConstVisitor& _visitor) const = 0; - template - static void listAccept(std::vector>& _list, ASTVisitor& _visitor) - { - for (ASTPointer& element: _list) - element->accept(_visitor); - } - template - static void listAccept(std::vector> const& _list, ASTConstVisitor& _visitor) - { - for (ASTPointer const& element: _list) - element->accept(_visitor); - } - - /// Returns the source code location of this node. - SourceLocation const& getLocation() const { return m_location; } - - /// Creates a @ref TypeError exception and decorates it with the location of the node and - /// the given description - TypeError createTypeError(std::string const& _description) const; - - ///@{ - ///@name equality operators - /// Equality relies on the fact that nodes cannot be copied. - bool operator==(ASTNode const& _other) const { return this == &_other; } - bool operator!=(ASTNode const& _other) const { return !operator==(_other); } - ///@} - -private: - SourceLocation m_location; -}; - -/** - * Source unit containing import directives and contract definitions. - */ -class SourceUnit: public ASTNode -{ -public: - SourceUnit(SourceLocation const& _location, std::vector> const& _nodes): - ASTNode(_location), m_nodes(_nodes) {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - std::vector> getNodes() const { return m_nodes; } - -private: - std::vector> m_nodes; -}; - -/** - * Import directive for referencing other files / source objects. - * Example: import "abc.sol" - * Source objects are identified by a string which can be a file name but does not have to be. - */ -class ImportDirective: public ASTNode -{ -public: - ImportDirective(SourceLocation const& _location, ASTPointer const& _identifier): - ASTNode(_location), m_identifier(_identifier) {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - ASTString const& getIdentifier() const { return *m_identifier; } - -private: - ASTPointer m_identifier; -}; - -/** - * Abstract AST class for a declaration (contract, function, struct, variable). - */ -class Declaration: public ASTNode -{ -public: - /// Visibility ordered from restricted to unrestricted. - enum class Visibility { Default, Private, Internal, Public, External }; - - Declaration(SourceLocation const& _location, ASTPointer const& _name, - Visibility _visibility = Visibility::Default): - ASTNode(_location), m_name(_name), m_visibility(_visibility), m_scope(nullptr) {} - - /// @returns the declared name. - ASTString const& getName() const { return *m_name; } - Visibility getVisibility() const { return m_visibility == Visibility::Default ? getDefaultVisibility() : m_visibility; } - bool isPublic() const { return getVisibility() >= Visibility::Public; } - virtual bool isVisibleInContract() const { return getVisibility() != Visibility::External; } - bool isVisibleInDerivedContracts() const { return isVisibleInContract() && getVisibility() >= Visibility::Internal; } - - /// @returns the scope this declaration resides in. Can be nullptr if it is the global scope. - /// Available only after name and type resolution step. - Declaration const* getScope() const { return m_scope; } - void setScope(Declaration const* _scope) { m_scope = _scope; } - - /// @returns the type of expressions referencing this declaration. - /// The current contract has to be given since this context can change the type, especially of - /// contract types. - virtual TypePointer getType(ContractDefinition const* m_currentContract = nullptr) const = 0; - virtual bool isLValue() const { return false; } - virtual bool isPartOfExternalInterface() const { return false; } - -protected: - virtual Visibility getDefaultVisibility() const { return Visibility::Public; } - -private: - ASTPointer m_name; - Visibility m_visibility; - Declaration const* m_scope; -}; - -/** - * Abstract class that is added to each AST node that can store local variables. - */ -class VariableScope -{ -public: - void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); } - std::vector const& getLocalVariables() const { return m_localVariables; } - -private: - std::vector m_localVariables; -}; - -/** - * Abstract class that is added to each AST node that can receive documentation. - */ -class Documented -{ -public: - explicit Documented(ASTPointer const& _documentation): m_documentation(_documentation) {} - - /// @return A shared pointer of an ASTString. - /// Can contain a nullptr in which case indicates absence of documentation - ASTPointer const& getDocumentation() const { return m_documentation; } - -protected: - ASTPointer m_documentation; -}; - -/** - * Abstract class that is added to AST nodes that can be marked as not being fully implemented - */ -class ImplementationOptional -{ -public: - explicit ImplementationOptional(bool _implemented): m_implemented(_implemented) {} - - /// @return whether this node is fully implemented or not - bool isFullyImplemented() const { return m_implemented; } - void setFullyImplemented(bool _implemented) { m_implemented = _implemented; } - -protected: - bool m_implemented; -}; - -/// @} - -/** - * Definition of a contract. This is the only AST nodes where child nodes are not visited in - * document order. It first visits all struct declarations, then all variable declarations and - * finally all function declarations. - */ -class ContractDefinition: public Declaration, public Documented, public ImplementationOptional -{ -public: - ContractDefinition( - SourceLocation const& _location, - ASTPointer const& _name, - ASTPointer const& _documentation, - std::vector> const& _baseContracts, - std::vector> const& _definedStructs, - std::vector> const& _definedEnums, - std::vector> const& _stateVariables, - std::vector> const& _definedFunctions, - std::vector> const& _functionModifiers, - std::vector> const& _events - ): - Declaration(_location, _name), - Documented(_documentation), - ImplementationOptional(true), - m_baseContracts(_baseContracts), - m_definedStructs(_definedStructs), - m_definedEnums(_definedEnums), - m_stateVariables(_stateVariables), - m_definedFunctions(_definedFunctions), - m_functionModifiers(_functionModifiers), - m_events(_events) - {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - std::vector> const& getBaseContracts() const { return m_baseContracts; } - std::vector> const& getDefinedStructs() const { return m_definedStructs; } - std::vector> const& getDefinedEnums() const { return m_definedEnums; } - std::vector> const& getStateVariables() const { return m_stateVariables; } - std::vector> const& getFunctionModifiers() const { return m_functionModifiers; } - std::vector> const& getDefinedFunctions() const { return m_definedFunctions; } - std::vector> const& getEvents() const { return m_events; } - std::vector> const& getInterfaceEvents() const; - - virtual TypePointer getType(ContractDefinition const* m_currentContract) const override; - - /// Checks that there are no illegal overrides, that the constructor does not have a "returns" - /// and calls checkTypeRequirements on all its functions. - void checkTypeRequirements(); - - /// @returns a map of canonical function signatures to FunctionDefinitions - /// as intended for use by the ABI. - std::map, FunctionTypePointer> getInterfaceFunctions() const; - - /// @returns a list of the inheritable members of this contract - std::vector const& getInheritableMembers() const; - - /// List of all (direct and indirect) base contracts in order from derived to base, including - /// the contract itself. Available after name resolution - std::vector const& getLinearizedBaseContracts() const { return m_linearizedBaseContracts; } - void setLinearizedBaseContracts(std::vector const& _bases) { m_linearizedBaseContracts = _bases; } - - /// Returns the constructor or nullptr if no constructor was specified. - FunctionDefinition const* getConstructor() const; - /// Returns the fallback function or nullptr if no fallback function was specified. - FunctionDefinition const* getFallbackFunction() const; - - std::string const& userDocumentation() const; - void setUserDocumentation(std::string const& _userDocumentation); - - std::string const& devDocumentation() const; - void setDevDocumentation(std::string const& _devDocumentation); - -private: - /// Checks that two functions defined in this contract with the same name have different - /// arguments and that there is at most one constructor. - void checkDuplicateFunctions() const; - void checkIllegalOverrides() const; - void checkAbstractFunctions(); - void checkAbstractConstructors(); - /// Checks that different functions with external visibility end up having different - /// external argument types (i.e. different signature). - void checkExternalTypeClashes() const; - - std::vector, FunctionTypePointer>> const& getInterfaceFunctionList() const; - - std::vector> m_baseContracts; - std::vector> m_definedStructs; - std::vector> m_definedEnums; - std::vector> m_stateVariables; - std::vector> m_definedFunctions; - std::vector> m_functionModifiers; - std::vector> m_events; - - // parsed Natspec documentation of the contract. - std::string m_userDocumentation; - std::string m_devDocumentation; - - std::vector m_linearizedBaseContracts; - mutable std::unique_ptr, FunctionTypePointer>>> m_interfaceFunctionList; - mutable std::unique_ptr>> m_interfaceEvents; - mutable std::unique_ptr> m_inheritableMembers; -}; - -class InheritanceSpecifier: public ASTNode -{ -public: - InheritanceSpecifier(SourceLocation const& _location, ASTPointer const& _baseName, - std::vector> _arguments): - ASTNode(_location), m_baseName(_baseName), m_arguments(_arguments) {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - ASTPointer const& getName() const { return m_baseName; } - std::vector> const& getArguments() const { return m_arguments; } - - void checkTypeRequirements(); - -private: - ASTPointer m_baseName; - std::vector> m_arguments; -}; - -class StructDefinition: public Declaration -{ -public: - StructDefinition(SourceLocation const& _location, - ASTPointer const& _name, - std::vector> const& _members): - Declaration(_location, _name), m_members(_members) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - std::vector> const& getMembers() const { return m_members; } - - virtual TypePointer getType(ContractDefinition const*) const override; - - /// Checks that the members do not include any recursive structs and have valid types - /// (e.g. no functions). - void checkValidityOfMembers() const; - -private: - void checkMemberTypes() const; - void checkRecursion() const; - - std::vector> m_members; -}; - -class EnumDefinition: public Declaration -{ -public: - EnumDefinition(SourceLocation const& _location, - ASTPointer const& _name, - std::vector> const& _members): - Declaration(_location, _name), m_members(_members) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - std::vector> const& getMembers() const { return m_members; } - - virtual TypePointer getType(ContractDefinition const*) const override; - -private: - std::vector> m_members; -}; - -/** - * Declaration of an Enum Value - */ -class EnumValue: public Declaration -{ - public: - EnumValue(SourceLocation const& _location, - ASTPointer const& _name): - Declaration(_location, _name) {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual TypePointer getType(ContractDefinition const* = nullptr) const override; -}; - -/** - * Parameter list, used as function parameter list and return list. - * None of the parameters is allowed to contain mappings (not even recursively - * inside structs). - */ -class ParameterList: public ASTNode -{ -public: - ParameterList(SourceLocation const& _location, - std::vector> const& _parameters): - ASTNode(_location), m_parameters(_parameters) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - std::vector> const& getParameters() const { return m_parameters; } - -private: - std::vector> m_parameters; -}; - -/** - * Base class for all nodes that define function-like objects, i.e. FunctionDefinition, - * EventDefinition and ModifierDefinition. - */ -class CallableDeclaration: public Declaration, public VariableScope -{ -public: - CallableDeclaration( - SourceLocation const& _location, - ASTPointer const& _name, - Declaration::Visibility _visibility, - ASTPointer const& _parameters, - ASTPointer const& _returnParameters = ASTPointer() - ): - Declaration(_location, _name, _visibility), - m_parameters(_parameters), - m_returnParameters(_returnParameters) - { - } - - std::vector> const& getParameters() const { return m_parameters->getParameters(); } - ParameterList const& getParameterList() const { return *m_parameters; } - ASTPointer const& getReturnParameterList() const { return m_returnParameters; } - -protected: - ASTPointer m_parameters; - ASTPointer m_returnParameters; -}; - -class FunctionDefinition: public CallableDeclaration, public Documented, public ImplementationOptional -{ -public: - FunctionDefinition( - SourceLocation const& _location, - ASTPointer const& _name, - Declaration::Visibility _visibility, - bool _isConstructor, - ASTPointer const& _documentation, - ASTPointer const& _parameters, - bool _isDeclaredConst, - std::vector> const& _modifiers, - ASTPointer const& _returnParameters, - ASTPointer const& _body - ): - CallableDeclaration(_location, _name, _visibility, _parameters, _returnParameters), - Documented(_documentation), - ImplementationOptional(_body != nullptr), - m_isConstructor(_isConstructor), - m_isDeclaredConst(_isDeclaredConst), - m_functionModifiers(_modifiers), - m_body(_body) - {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - bool isConstructor() const { return m_isConstructor; } - bool isDeclaredConst() const { return m_isDeclaredConst; } - std::vector> const& getModifiers() const { return m_functionModifiers; } - std::vector> const& getReturnParameters() const { return m_returnParameters->getParameters(); } - Block const& getBody() const { return *m_body; } - - virtual bool isVisibleInContract() const override - { - return Declaration::isVisibleInContract() && !isConstructor() && !getName().empty(); - } - virtual TypePointer getType(ContractDefinition const*) const override; - virtual bool isPartOfExternalInterface() const override { return isPublic() && !m_isConstructor && !getName().empty(); } - - /// Checks that all parameters have allowed types and calls checkTypeRequirements on the body. - void checkTypeRequirements(); - - /// @returns the external signature of the function - /// That consists of the name of the function followed by the types of the - /// arguments separated by commas all enclosed in parentheses without any spaces. - std::string externalSignature() const; - -private: - bool m_isConstructor; - bool m_isDeclaredConst; - std::vector> m_functionModifiers; - ASTPointer m_body; -}; - -/** - * Declaration of a variable. This can be used in various places, e.g. in function parameter - * lists, struct definitions and even function bodys. - */ -class VariableDeclaration: public Declaration -{ -public: - enum Location { Default, Storage, Memory }; - - VariableDeclaration( - SourceLocation const& _sourceLocation, - ASTPointer const& _type, - ASTPointer const& _name, - ASTPointer _value, - Visibility _visibility, - bool _isStateVar = false, - bool _isIndexed = false, - bool _isConstant = false, - Location _referenceLocation = Location::Default - ): - Declaration(_sourceLocation, _name, _visibility), - m_typeName(_type), - m_value(_value), - m_isStateVariable(_isStateVar), - m_isIndexed(_isIndexed), - m_isConstant(_isConstant), - m_location(_referenceLocation) {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - TypeName* getTypeName() { return m_typeName.get(); } - ASTPointer const& getValue() const { return m_value; } - - /// Returns the declared or inferred type. Can be an empty pointer if no type was explicitly - /// declared and there is no assignment to the variable that fixes the type. - TypePointer getType(ContractDefinition const* = nullptr) const override { return m_type; } - void setType(std::shared_ptr const& _type) { m_type = _type; } - - virtual bool isLValue() const override; - virtual bool isPartOfExternalInterface() const override { return isPublic() && !m_isConstant; } - - void checkTypeRequirements(); - bool isLocalVariable() const { return !!dynamic_cast(getScope()); } - /// @returns true if this variable is a parameter or return parameter of a function. - bool isCallableParameter() const; - /// @returns true if this variable is a parameter (not return parameter) of an external function. - bool isExternalCallableParameter() const; - bool isStateVariable() const { return m_isStateVariable; } - bool isIndexed() const { return m_isIndexed; } - bool isConstant() const { return m_isConstant; } - Location referenceLocation() const { return m_location; } - -protected: - Visibility getDefaultVisibility() const override { return Visibility::Internal; } - -private: - ASTPointer m_typeName; ///< can be empty ("var") - ASTPointer m_value; ///< the assigned value, can be missing - bool m_isStateVariable; ///< Whether or not this is a contract state variable - bool m_isIndexed; ///< Whether this is an indexed variable (used by events). - bool m_isConstant; ///< Whether the variable is a compile-time constant. - Location m_location; ///< Location of the variable if it is of reference type. - - std::shared_ptr m_type; ///< derived type, initially empty -}; - -/** - * Definition of a function modifier. - */ -class ModifierDefinition: public CallableDeclaration, public Documented -{ -public: - ModifierDefinition( - SourceLocation const& _location, - ASTPointer const& _name, - ASTPointer const& _documentation, - ASTPointer const& _parameters, - ASTPointer const& _body - ): - CallableDeclaration(_location, _name, Visibility::Default, _parameters), - Documented(_documentation), - m_body(_body) - { - } - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - Block const& getBody() const { return *m_body; } - - virtual TypePointer getType(ContractDefinition const* = nullptr) const override; - - void checkTypeRequirements(); - -private: - ASTPointer m_body; -}; - -/** - * Invocation/usage of a modifier in a function header or a base constructor call. - */ -class ModifierInvocation: public ASTNode -{ -public: - ModifierInvocation(SourceLocation const& _location, ASTPointer const& _name, - std::vector> _arguments): - ASTNode(_location), m_modifierName(_name), m_arguments(_arguments) {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - ASTPointer const& getName() const { return m_modifierName; } - std::vector> const& getArguments() const { return m_arguments; } - - /// @param _bases is the list of base contracts for base constructor calls. For modifiers an empty vector should be passed. - void checkTypeRequirements(std::vector const& _bases); - -private: - ASTPointer m_modifierName; - std::vector> m_arguments; -}; - -/** - * Definition of a (loggable) event. - */ -class EventDefinition: public CallableDeclaration, public Documented -{ -public: - EventDefinition( - SourceLocation const& _location, - ASTPointer const& _name, - ASTPointer const& _documentation, - ASTPointer const& _parameters, - bool _anonymous = false - ): - CallableDeclaration(_location, _name, Visibility::Default, _parameters), - Documented(_documentation), - m_anonymous(_anonymous) - { - } - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - bool isAnonymous() const { return m_anonymous; } - - virtual TypePointer getType(ContractDefinition const* = nullptr) const override - { - return std::make_shared(*this); - } - - void checkTypeRequirements(); - -private: - bool m_anonymous = false; -}; - -/** - * Pseudo AST node that is used as declaration for "this", "msg", "tx", "block" and the global - * functions when such an identifier is encountered. Will never have a valid location in the source code. - */ -class MagicVariableDeclaration: public Declaration -{ -public: - MagicVariableDeclaration(ASTString const& _name, std::shared_ptr const& _type): - Declaration(SourceLocation(), std::make_shared(_name)), m_type(_type) {} - virtual void accept(ASTVisitor&) override { BOOST_THROW_EXCEPTION(InternalCompilerError() - << errinfo_comment("MagicVariableDeclaration used inside real AST.")); } - virtual void accept(ASTConstVisitor&) const override { BOOST_THROW_EXCEPTION(InternalCompilerError() - << errinfo_comment("MagicVariableDeclaration used inside real AST.")); } - - virtual TypePointer getType(ContractDefinition const* = nullptr) const override { return m_type; } - -private: - std::shared_ptr m_type; -}; - -/// Types -/// @{ - -/** - * Abstract base class of a type name, can be any built-in or user-defined type. - */ -class TypeName: public ASTNode -{ -public: - explicit TypeName(SourceLocation const& _location): ASTNode(_location) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - /// Retrieve the element of the type hierarchy this node refers to. Can return an empty shared - /// pointer until the types have been resolved using the @ref NameAndTypeResolver. - /// If it returns an empty shared pointer after that, this indicates that the type was not found. - virtual std::shared_ptr toType() = 0; -}; - -/** - * Any pre-defined type name represented by a single keyword, i.e. it excludes mappings, - * contracts, functions, etc. - */ -class ElementaryTypeName: public TypeName -{ -public: - explicit ElementaryTypeName(SourceLocation const& _location, Token::Value _type): - TypeName(_location), m_type(_type) - { - solAssert(Token::isElementaryTypeName(_type), ""); - } - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual std::shared_ptr toType() override { return Type::fromElementaryTypeName(m_type); } - - Token::Value getTypeName() const { return m_type; } - -private: - Token::Value m_type; -}; - -/** - * Name referring to a user-defined type (i.e. a struct, contract, etc.). - */ -class UserDefinedTypeName: public TypeName -{ -public: - UserDefinedTypeName(SourceLocation const& _location, ASTPointer const& _name): - TypeName(_location), m_name(_name), m_referencedDeclaration(nullptr) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual std::shared_ptr toType() override { return Type::fromUserDefinedTypeName(*this); } - - ASTString const& getName() const { return *m_name; } - void setReferencedDeclaration(Declaration const& _referencedDeclaration) { m_referencedDeclaration = &_referencedDeclaration; } - Declaration const* getReferencedDeclaration() const { return m_referencedDeclaration; } - -private: - ASTPointer m_name; - - Declaration const* m_referencedDeclaration; -}; - -/** - * A mapping type. Its source form is "mapping('keyType' => 'valueType')" - */ -class Mapping: public TypeName -{ -public: - Mapping(SourceLocation const& _location, ASTPointer const& _keyType, - ASTPointer const& _valueType): - TypeName(_location), m_keyType(_keyType), m_valueType(_valueType) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual TypePointer toType() override { return Type::fromMapping(*m_keyType, *m_valueType); } - - ElementaryTypeName const& getKeyType() const { return *m_keyType; } - TypeName const& getValueType() const { return *m_valueType; } - -private: - ASTPointer m_keyType; - ASTPointer m_valueType; -}; - -/** - * An array type, can be "typename[]" or "typename[]". - */ -class ArrayTypeName: public TypeName -{ -public: - ArrayTypeName(SourceLocation const& _location, ASTPointer const& _baseType, - ASTPointer const& _length): - TypeName(_location), m_baseType(_baseType), m_length(_length) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual std::shared_ptr toType() override { return Type::fromArrayTypeName(*m_baseType, m_length.get()); } - - TypeName const& getBaseType() const { return *m_baseType; } - Expression const* getLength() const { return m_length.get(); } - -private: - ASTPointer m_baseType; - ASTPointer m_length; ///< Length of the array, might be empty. -}; - -/// @} - -/// Statements -/// @{ - - -/** - * Abstract base class for statements. - */ -class Statement: public ASTNode -{ -public: - explicit Statement(SourceLocation const& _location): ASTNode(_location) {} - - /// Check all type requirements, throws exception if some requirement is not met. - /// This includes checking that operators are applicable to their arguments but also that - /// the number of function call arguments matches the number of formal parameters and so forth. - virtual void checkTypeRequirements() = 0; -}; - -/** - * Brace-enclosed block containing zero or more statements. - */ -class Block: public Statement -{ -public: - Block(SourceLocation const& _location, std::vector> const& _statements): - Statement(_location), m_statements(_statements) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - virtual void checkTypeRequirements() override; - -private: - std::vector> m_statements; -}; - -/** - * Special placeholder statement denoted by "_" used in function modifiers. This is replaced by - * the original function when the modifier is applied. - */ -class PlaceholderStatement: public Statement -{ -public: - PlaceholderStatement(SourceLocation const& _location): Statement(_location) {} - - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - - virtual void checkTypeRequirements() override { } -}; - -/** - * If-statement with an optional "else" part. Note that "else if" is modeled by having a new - * if-statement as the false (else) body. - */ -class IfStatement: public Statement -{ -public: - IfStatement(SourceLocation const& _location, ASTPointer const& _condition, - ASTPointer const& _trueBody, ASTPointer const& _falseBody): - Statement(_location), - m_condition(_condition), m_trueBody(_trueBody), m_falseBody(_falseBody) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override; - - Expression const& getCondition() const { return *m_condition; } - Statement const& getTrueStatement() const { return *m_trueBody; } - /// @returns the "else" part of the if statement or nullptr if there is no "else" part. - Statement const* getFalseStatement() const { return m_falseBody.get(); } - -private: - ASTPointer m_condition; - ASTPointer m_trueBody; - ASTPointer m_falseBody; ///< "else" part, optional -}; - -/** - * Statement in which a break statement is legal (abstract class). - */ -class BreakableStatement: public Statement -{ -public: - BreakableStatement(SourceLocation const& _location): Statement(_location) {} -}; - -class WhileStatement: public BreakableStatement -{ -public: - WhileStatement(SourceLocation const& _location, ASTPointer const& _condition, - ASTPointer const& _body): - BreakableStatement(_location), m_condition(_condition), m_body(_body) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override; - - Expression const& getCondition() const { return *m_condition; } - Statement const& getBody() const { return *m_body; } - -private: - ASTPointer m_condition; - ASTPointer m_body; -}; - -/** - * For loop statement - */ -class ForStatement: public BreakableStatement -{ -public: - ForStatement(SourceLocation const& _location, - ASTPointer const& _initExpression, - ASTPointer const& _conditionExpression, - ASTPointer const& _loopExpression, - ASTPointer const& _body): - BreakableStatement(_location), - m_initExpression(_initExpression), - m_condExpression(_conditionExpression), - m_loopExpression(_loopExpression), - m_body(_body) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override; - - Statement const* getInitializationExpression() const { return m_initExpression.get(); } - Expression const* getCondition() const { return m_condExpression.get(); } - ExpressionStatement const* getLoopExpression() const { return m_loopExpression.get(); } - Statement const& getBody() const { return *m_body; } - -private: - /// For statement's initialization expresion. for(XXX; ; ). Can be empty - ASTPointer m_initExpression; - /// For statement's condition expresion. for(; XXX ; ). Can be empty - ASTPointer m_condExpression; - /// For statement's loop expresion. for(;;XXX). Can be empty - ASTPointer m_loopExpression; - /// The body of the loop - ASTPointer m_body; -}; - -class Continue: public Statement -{ -public: - Continue(SourceLocation const& _location): Statement(_location) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override {} -}; - -class Break: public Statement -{ -public: - Break(SourceLocation const& _location): Statement(_location) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override {} -}; - -class Return: public Statement -{ -public: - Return(SourceLocation const& _location, ASTPointer _expression): - Statement(_location), m_expression(_expression), m_returnParameters(nullptr) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override; - - void setFunctionReturnParameters(ParameterList const* _parameters) { m_returnParameters = _parameters; } - ParameterList const* getFunctionReturnParameters() const { return m_returnParameters; } - Expression const* getExpression() const { return m_expression.get(); } - -private: - ASTPointer m_expression; ///< value to return, optional - - /// Pointer to the parameter list of the function, filled by the @ref NameAndTypeResolver. - ParameterList const* m_returnParameters; -}; - -/** - * Definition of a variable as a statement inside a function. It requires a type name (which can - * also be "var") but the actual assignment can be missing. - * Examples: var a = 2; uint256 a; - */ -class VariableDeclarationStatement: public Statement -{ -public: - VariableDeclarationStatement(SourceLocation const& _location, ASTPointer _variable): - Statement(_location), m_variable(_variable) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override; - - VariableDeclaration const& getDeclaration() const { return *m_variable; } - Expression const* getExpression() const { return m_variable->getValue().get(); } - -private: - ASTPointer m_variable; -}; - -/** - * A statement that contains only an expression (i.e. an assignment, function call, ...). - */ -class ExpressionStatement: public Statement -{ -public: - ExpressionStatement(SourceLocation const& _location, ASTPointer _expression): - Statement(_location), m_expression(_expression) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements() override; - - Expression const& getExpression() const { return *m_expression; } - -private: - ASTPointer m_expression; -}; - -/// @} - -/// Expressions -/// @{ - -/** - * An expression, i.e. something that has a value (which can also be of type "void" in case - * of some function calls). - * @abstract - */ -class Expression: public ASTNode -{ -public: - Expression(SourceLocation const& _location): ASTNode(_location) {} - /// Performs type checking after which m_type should be set. - /// @arg _argumentTypes if set, provides the argument types for the case that this expression - /// is used in the context of a call, used for function overload resolution. - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) = 0; - - std::shared_ptr const& getType() const { return m_type; } - bool isLValue() const { return m_isLValue; } - - /// Helper function, infer the type via @ref checkTypeRequirements and then check that it - /// is implicitly convertible to @a _expectedType. If not, throw exception. - void expectType(Type const& _expectedType); - /// Checks that this expression is an lvalue and also registers that an address and - /// not a value is generated during compilation. Can be called after checkTypeRequirements() - /// by an enclosing expression. - void requireLValue(); - /// Returns true if @a requireLValue was previously called on this expression. - bool lvalueRequested() const { return m_lvalueRequested; } - -protected: - //! Inferred type of the expression, only filled after a call to checkTypeRequirements(). - std::shared_ptr m_type; - //! If this expression is an lvalue (i.e. something that can be assigned to). - //! This is set during calls to @a checkTypeRequirements() - bool m_isLValue = false; - //! Whether the outer expression requested the address (true) or the value (false) of this expression. - bool m_lvalueRequested = false; -}; - -/// Assignment, can also be a compound assignment. -/// Examples: (a = 7 + 8) or (a *= 2) -class Assignment: public Expression -{ -public: - Assignment(SourceLocation const& _location, ASTPointer const& _leftHandSide, - Token::Value _assignmentOperator, ASTPointer const& _rightHandSide): - Expression(_location), m_leftHandSide(_leftHandSide), - m_assigmentOperator(_assignmentOperator), m_rightHandSide(_rightHandSide) - { - solAssert(Token::isAssignmentOp(_assignmentOperator), ""); - } - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - Expression const& getLeftHandSide() const { return *m_leftHandSide; } - Token::Value getAssignmentOperator() const { return m_assigmentOperator; } - Expression const& getRightHandSide() const { return *m_rightHandSide; } - -private: - ASTPointer m_leftHandSide; - Token::Value m_assigmentOperator; - ASTPointer m_rightHandSide; -}; - -/** - * Operation involving a unary operator, pre- or postfix. - * Examples: ++i, delete x or !true - */ -class UnaryOperation: public Expression -{ -public: - UnaryOperation(SourceLocation const& _location, Token::Value _operator, - ASTPointer const& _subExpression, bool _isPrefix): - Expression(_location), m_operator(_operator), - m_subExpression(_subExpression), m_isPrefix(_isPrefix) - { - solAssert(Token::isUnaryOp(_operator), ""); - } - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - Token::Value getOperator() const { return m_operator; } - bool isPrefixOperation() const { return m_isPrefix; } - Expression const& getSubExpression() const { return *m_subExpression; } - -private: - Token::Value m_operator; - ASTPointer m_subExpression; - bool m_isPrefix; -}; - -/** - * Operation involving a binary operator. - * Examples: 1 + 2, true && false or 1 <= 4 - */ -class BinaryOperation: public Expression -{ -public: - BinaryOperation(SourceLocation const& _location, ASTPointer const& _left, - Token::Value _operator, ASTPointer const& _right): - Expression(_location), m_left(_left), m_operator(_operator), m_right(_right) - { - solAssert(Token::isBinaryOp(_operator) || Token::isCompareOp(_operator), ""); - } - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - Expression const& getLeftExpression() const { return *m_left; } - Expression const& getRightExpression() const { return *m_right; } - Token::Value getOperator() const { return m_operator; } - Type const& getCommonType() const { return *m_commonType; } - -private: - ASTPointer m_left; - Token::Value m_operator; - ASTPointer m_right; - - /// The common type that is used for the operation, not necessarily the result type (e.g. for - /// comparisons, this is always bool). - std::shared_ptr m_commonType; -}; - -/** - * Can be ordinary function call, type cast or struct construction. - */ -class FunctionCall: public Expression -{ -public: - FunctionCall(SourceLocation const& _location, ASTPointer const& _expression, - std::vector> const& _arguments, std::vector> const& _names): - Expression(_location), m_expression(_expression), m_arguments(_arguments), m_names(_names) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - Expression const& getExpression() const { return *m_expression; } - std::vector> getArguments() const { return {m_arguments.begin(), m_arguments.end()}; } - std::vector> const& getNames() const { return m_names; } - - /// @returns true if this is not an actual function call, but an explicit type conversion. - /// Returns false for struct constructor calls. - bool isTypeConversion() const; - /// @return true if this is a constructor call for a struct, i.e. StructName(...). - bool isStructConstructorCall() const; - -private: - ASTPointer m_expression; - std::vector> m_arguments; - std::vector> m_names; -}; - -/** - * Expression that creates a new contract, e.g. the "new SomeContract" part in "new SomeContract(1, 2)". - */ -class NewExpression: public Expression -{ -public: - NewExpression(SourceLocation const& _location, ASTPointer const& _contractName): - Expression(_location), m_contractName(_contractName) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - /// Returns the referenced contract. Can only be called after type checking. - ContractDefinition const* getContract() const { solAssert(m_contract, ""); return m_contract; } - -private: - ASTPointer m_contractName; - - ContractDefinition const* m_contract = nullptr; -}; - -/** - * Access to a member of an object. Example: x.name - */ -class MemberAccess: public Expression -{ -public: - MemberAccess(SourceLocation const& _location, ASTPointer _expression, - ASTPointer const& _memberName): - Expression(_location), m_expression(_expression), m_memberName(_memberName) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - Expression const& getExpression() const { return *m_expression; } - ASTString const& getMemberName() const { return *m_memberName; } - /// @returns the declaration referenced by this expression. Might return nullptr even if the - /// expression is valid, e.g. if the member does not correspond to an AST node. - Declaration const* referencedDeclaration() const { return m_referencedDeclaration; } - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - -private: - ASTPointer m_expression; - ASTPointer m_memberName; - - /// Pointer to the referenced declaration, this is sometimes needed to resolve function over - /// loads in the type-checking phase. - Declaration const* m_referencedDeclaration = nullptr; -}; - -/** - * Index access to an array. Example: a[2] - */ -class IndexAccess: public Expression -{ -public: - IndexAccess(SourceLocation const& _location, ASTPointer const& _base, - ASTPointer const& _index): - Expression(_location), m_base(_base), m_index(_index) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - Expression const& getBaseExpression() const { return *m_base; } - Expression const* getIndexExpression() const { return m_index.get(); } - -private: - ASTPointer m_base; - ASTPointer m_index; -}; - -/** - * Primary expression, i.e. an expression that cannot be divided any further. Examples are literals - * or variable references. - */ -class PrimaryExpression: public Expression -{ -public: - PrimaryExpression(SourceLocation const& _location): Expression(_location) {} -}; - -/** - * An identifier, i.e. a reference to a declaration by name like a variable or function. - */ -class Identifier: public PrimaryExpression -{ -public: - Identifier(SourceLocation const& _location, ASTPointer const& _name): - PrimaryExpression(_location), m_name(_name) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - ASTString const& getName() const { return *m_name; } - - void setReferencedDeclaration( - Declaration const& _referencedDeclaration, - ContractDefinition const* _currentContract = nullptr - ) - { - m_referencedDeclaration = &_referencedDeclaration; - m_currentContract = _currentContract; - } - Declaration const& getReferencedDeclaration() const; - - /// Stores a set of possible declarations referenced by this identifier. Has to be resolved - /// providing argument types using overloadResolution before the referenced declaration - /// is accessed. - void setOverloadedDeclarations(std::vector const& _declarations) - { - m_overloadedDeclarations = _declarations; - } - - /// Tries to find exactly one of the possible referenced declarations provided the given - /// argument types in a call context. - void overloadResolution(TypePointers const& _argumentTypes); - -private: - ASTPointer m_name; - - /// Declaration the name refers to. - Declaration const* m_referencedDeclaration = nullptr; - /// Stores a reference to the current contract. This is needed because types of base contracts - /// change depending on the context. - ContractDefinition const* m_currentContract = nullptr; - /// A vector of overloaded declarations, right now only FunctionDefinition has overloaded declarations. - std::vector m_overloadedDeclarations; -}; - -/** - * An elementary type name expression is used in expressions like "a = uint32(2)" to change the - * type of an expression explicitly. Here, "uint32" is the elementary type name expression and - * "uint32(2)" is a @ref FunctionCall. - */ -class ElementaryTypeNameExpression: public PrimaryExpression -{ -public: - ElementaryTypeNameExpression(SourceLocation const& _location, Token::Value _typeToken): - PrimaryExpression(_location), m_typeToken(_typeToken) - { - solAssert(Token::isElementaryTypeName(_typeToken), ""); - } - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - Token::Value getTypeToken() const { return m_typeToken; } - -private: - Token::Value m_typeToken; -}; - -/** - * A literal string or number. @see ExpressionCompiler::endVisit() is used to actually parse its value. - */ -class Literal: public PrimaryExpression -{ -public: - enum class SubDenomination - { - None = Token::Illegal, - Wei = Token::SubWei, - Szabo = Token::SubSzabo, - Finney = Token::SubFinney, - Ether = Token::SubEther, - Second = Token::SubSecond, - Minute = Token::SubMinute, - Hour = Token::SubHour, - Day = Token::SubDay, - Week = Token::SubWeek, - Year = Token::SubYear - }; - Literal(SourceLocation const& _location, Token::Value _token, - ASTPointer const& _value, - SubDenomination _sub = SubDenomination::None): - PrimaryExpression(_location), m_token(_token), m_value(_value), m_subDenomination(_sub) {} - virtual void accept(ASTVisitor& _visitor) override; - virtual void accept(ASTConstVisitor& _visitor) const override; - virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; - - Token::Value getToken() const { return m_token; } - /// @returns the non-parsed value of the literal - ASTString const& getValue() const { return *m_value; } - - SubDenomination getSubDenomination() const { return m_subDenomination; } - -private: - Token::Value m_token; - ASTPointer m_value; - SubDenomination m_subDenomination; -}; - -/// @} - - -} -} diff --git a/libsolidity/ASTForward.h b/libsolidity/ASTForward.h deleted file mode 100644 index 0ba485a2f..000000000 --- a/libsolidity/ASTForward.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Forward-declarations of AST classes. - */ - -#pragma once - -#include -#include -#include - -// Forward-declare all AST node types - -namespace dev -{ -namespace solidity -{ - -class ASTNode; -class SourceUnit; -class ImportDirective; -class Declaration; -class ContractDefinition; -class InheritanceSpecifier; -class StructDefinition; -class EnumDefinition; -class EnumValue; -class ParameterList; -class FunctionDefinition; -class VariableDeclaration; -class ModifierDefinition; -class ModifierInvocation; -class EventDefinition; -class MagicVariableDeclaration; -class TypeName; -class ElementaryTypeName; -class UserDefinedTypeName; -class Mapping; -class ArrayTypeName; -class Statement; -class Block; -class PlaceholderStatement; -class IfStatement; -class BreakableStatement; -class WhileStatement; -class ForStatement; -class Continue; -class Break; -class Return; -class VariableDeclarationStatement; -class ExpressionStatement; -class Expression; -class Assignment; -class UnaryOperation; -class BinaryOperation; -class FunctionCall; -class NewExpression; -class MemberAccess; -class IndexAccess; -class PrimaryExpression; -class Identifier; -class ElementaryTypeNameExpression; -class Literal; - -class VariableScope; - -// Used as pointers to AST nodes, to be replaced by more clever pointers, e.g. pointers which do -// not do reference counting but point to a special memory area that is completely released -// explicitly. -template -using ASTPointer = std::shared_ptr; - -using ASTString = std::string; - - -} -} diff --git a/libsolidity/ASTJsonConverter.cpp b/libsolidity/ASTJsonConverter.cpp deleted file mode 100644 index 122b1c0d1..000000000 --- a/libsolidity/ASTJsonConverter.cpp +++ /dev/null @@ -1,437 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Lefteris - * @date 2015 - * Converts the AST into json format - */ - -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -void ASTJsonConverter::addKeyValue(Json::Value& _obj, string const& _key, string const& _val) -{ - // special handling for booleans - if (_key == "const" || _key == "public" || _key == "local" || - _key == "lvalue" || _key == "local_lvalue" || _key == "prefix") - _obj[_key] = (_val == "1") ? true : false; - else - // else simply add it as a string - _obj[_key] = _val; -} - -void ASTJsonConverter::addJsonNode(string const& _nodeName, - initializer_list> _list, - bool _hasChildren = false) -{ - Json::Value node; - - node["name"] = _nodeName; - if (_list.size() != 0) - { - Json::Value attrs; - for (auto& e: _list) - addKeyValue(attrs, e.first, e.second); - node["attributes"] = attrs; - } - - m_jsonNodePtrs.top()->append(node); - - if (_hasChildren) - { - Json::Value& addedNode = (*m_jsonNodePtrs.top())[m_jsonNodePtrs.top()->size() - 1]; - Json::Value children(Json::arrayValue); - addedNode["children"] = children; - m_jsonNodePtrs.push(&addedNode["children"]); - } -} - -ASTJsonConverter::ASTJsonConverter(ASTNode const& _ast): m_ast(&_ast) -{ - Json::Value children(Json::arrayValue); - - m_astJson["name"] = "root"; - m_astJson["children"] = children; - m_jsonNodePtrs.push(&m_astJson["children"]); -} - -void ASTJsonConverter::print(ostream& _stream) -{ - process(); - _stream << m_astJson; -} - -Json::Value const& ASTJsonConverter::json() -{ - process(); - return m_astJson; -} - -bool ASTJsonConverter::visit(ImportDirective const& _node) -{ - addJsonNode("Import", { make_pair("file", _node.getIdentifier())}); - return true; -} - -bool ASTJsonConverter::visit(ContractDefinition const& _node) -{ - addJsonNode("Contract", { make_pair("name", _node.getName()) }, true); - return true; -} - -bool ASTJsonConverter::visit(StructDefinition const& _node) -{ - addJsonNode("Struct", { make_pair("name", _node.getName()) }, true); - return true; -} - -bool ASTJsonConverter::visit(ParameterList const&) -{ - addJsonNode("ParameterList", {}, true); - return true; -} - -bool ASTJsonConverter::visit(FunctionDefinition const& _node) -{ - addJsonNode("Function", - { make_pair("name", _node.getName()), - make_pair("public", boost::lexical_cast(_node.isPublic())), - make_pair("const", boost::lexical_cast(_node.isDeclaredConst())) }, - true); - return true; -} - -bool ASTJsonConverter::visit(VariableDeclaration const& _node) -{ - addJsonNode("VariableDeclaration", { make_pair("name", _node.getName()) }, true); - return true; -} - -bool ASTJsonConverter::visit(TypeName const&) -{ - return true; -} - -bool ASTJsonConverter::visit(ElementaryTypeName const& _node) -{ - addJsonNode("ElementaryTypeName", { make_pair("name", Token::toString(_node.getTypeName())) }); - return true; -} - -bool ASTJsonConverter::visit(UserDefinedTypeName const& _node) -{ - addJsonNode("UserDefinedTypeName", { make_pair("name", _node.getName()) }); - return true; -} - -bool ASTJsonConverter::visit(Mapping const&) -{ - addJsonNode("Mapping", {}, true); - return true; -} - -bool ASTJsonConverter::visit(Block const&) -{ - addJsonNode("Block", {}, true); - return true; -} - -bool ASTJsonConverter::visit(IfStatement const&) -{ - addJsonNode("IfStatement", {}, true); - return true; -} - -bool ASTJsonConverter::visit(WhileStatement const&) -{ - addJsonNode("WhileStatement", {}, true); - return true; -} - -bool ASTJsonConverter::visit(ForStatement const&) -{ - addJsonNode("ForStatement", {}, true); - return true; -} - -bool ASTJsonConverter::visit(Continue const&) -{ - addJsonNode("Continue", {}); - return true; -} - -bool ASTJsonConverter::visit(Break const&) -{ - addJsonNode("Break", {}); - return true; -} - -bool ASTJsonConverter::visit(Return const&) -{ - addJsonNode("Return", {}, true);; - return true; -} - -bool ASTJsonConverter::visit(VariableDeclarationStatement const&) -{ - addJsonNode("VariableDefinition", {}, true); - return true; -} - -bool ASTJsonConverter::visit(ExpressionStatement const&) -{ - addJsonNode("ExpressionStatement", {}, true); - return true; -} - -bool ASTJsonConverter::visit(Assignment const& _node) -{ - addJsonNode("Assignment", - { make_pair("operator", Token::toString(_node.getAssignmentOperator())), - make_pair("type", getType(_node)) }, - true); - return true; -} - -bool ASTJsonConverter::visit(UnaryOperation const& _node) -{ - addJsonNode("UnaryOperation", - { make_pair("prefix", boost::lexical_cast(_node.isPrefixOperation())), - make_pair("operator", Token::toString(_node.getOperator())), - make_pair("type", getType(_node)) }, - true); - return true; -} - -bool ASTJsonConverter::visit(BinaryOperation const& _node) -{ - addJsonNode("BinaryOperation", - { make_pair("operator", Token::toString(_node.getOperator())), - make_pair("type", getType(_node))}, - true); - return true; -} - -bool ASTJsonConverter::visit(FunctionCall const& _node) -{ - addJsonNode("FunctionCall", - { make_pair("type_conversion", boost::lexical_cast(_node.isTypeConversion())), - make_pair("type", getType(_node)) }, - true); - return true; -} - -bool ASTJsonConverter::visit(NewExpression const& _node) -{ - addJsonNode("NewExpression", { make_pair("type", getType(_node)) }, true); - return true; -} - -bool ASTJsonConverter::visit(MemberAccess const& _node) -{ - addJsonNode("MemberAccess", - { make_pair("member_name", _node.getMemberName()), - make_pair("type", getType(_node)) }, - true); - return true; -} - -bool ASTJsonConverter::visit(IndexAccess const& _node) -{ - addJsonNode("IndexAccess", { make_pair("type", getType(_node)) }, true); - return true; -} - -bool ASTJsonConverter::visit(Identifier const& _node) -{ - addJsonNode("Identifier", - { make_pair("value", _node.getName()), make_pair("type", getType(_node)) }); - return true; -} - -bool ASTJsonConverter::visit(ElementaryTypeNameExpression const& _node) -{ - addJsonNode("ElementaryTypenameExpression", - { make_pair("value", Token::toString(_node.getTypeToken())), make_pair("type", getType(_node)) }); - return true; -} - -bool ASTJsonConverter::visit(Literal const& _node) -{ - char const* tokenString = Token::toString(_node.getToken()); - addJsonNode("Literal", - { make_pair("string", (tokenString) ? tokenString : "null"), - make_pair("value", _node.getValue()), - make_pair("type", getType(_node)) }); - return true; -} - -void ASTJsonConverter::endVisit(ImportDirective const&) -{ -} - -void ASTJsonConverter::endVisit(ContractDefinition const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(StructDefinition const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(ParameterList const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(FunctionDefinition const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(VariableDeclaration const&) -{ -} - -void ASTJsonConverter::endVisit(TypeName const&) -{ -} - -void ASTJsonConverter::endVisit(ElementaryTypeName const&) -{ -} - -void ASTJsonConverter::endVisit(UserDefinedTypeName const&) -{ -} - -void ASTJsonConverter::endVisit(Mapping const&) -{ -} - -void ASTJsonConverter::endVisit(Block const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(IfStatement const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(WhileStatement const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(ForStatement const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(Continue const&) -{ -} - -void ASTJsonConverter::endVisit(Break const&) -{ -} - -void ASTJsonConverter::endVisit(Return const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(VariableDeclarationStatement const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(ExpressionStatement const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(Assignment const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(UnaryOperation const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(BinaryOperation const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(FunctionCall const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(NewExpression const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(MemberAccess const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(IndexAccess const&) -{ - goUp(); -} - -void ASTJsonConverter::endVisit(Identifier const&) -{ -} - -void ASTJsonConverter::endVisit(ElementaryTypeNameExpression const&) -{ -} - -void ASTJsonConverter::endVisit(Literal const&) -{ -} - -void ASTJsonConverter::process() -{ - if (!processed) - m_ast->accept(*this); - processed = true; -} - -string ASTJsonConverter::getType(Expression const& _expression) -{ - return (_expression.getType()) ? _expression.getType()->toString() : "Unknown"; -} - -} -} diff --git a/libsolidity/ASTJsonConverter.h b/libsolidity/ASTJsonConverter.h deleted file mode 100644 index aaa54f7fd..000000000 --- a/libsolidity/ASTJsonConverter.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Lefteris - * @date 2015 - * Converts the AST into json format - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -/** - * Converter of the AST into JSON format - */ -class ASTJsonConverter: public ASTConstVisitor -{ -public: - /// Create a converter to JSON for the given abstract syntax tree. - ASTJsonConverter(ASTNode const& _ast); - /// Output the json representation of the AST to _stream. - void print(std::ostream& _stream); - Json::Value const& json(); - - bool visit(ImportDirective const& _node) override; - bool visit(ContractDefinition const& _node) override; - bool visit(StructDefinition const& _node) override; - bool visit(ParameterList const& _node) override; - bool visit(FunctionDefinition const& _node) override; - bool visit(VariableDeclaration const& _node) override; - bool visit(TypeName const& _node) override; - bool visit(ElementaryTypeName const& _node) override; - bool visit(UserDefinedTypeName const& _node) override; - bool visit(Mapping const& _node) override; - bool visit(Block const& _node) override; - bool visit(IfStatement const& _node) override; - bool visit(WhileStatement const& _node) override; - bool visit(ForStatement const& _node) override; - bool visit(Continue const& _node) override; - bool visit(Break const& _node) override; - bool visit(Return const& _node) override; - bool visit(VariableDeclarationStatement const& _node) override; - bool visit(ExpressionStatement const& _node) override; - bool visit(Assignment const& _node) override; - bool visit(UnaryOperation const& _node) override; - bool visit(BinaryOperation const& _node) override; - bool visit(FunctionCall const& _node) override; - bool visit(NewExpression const& _node) override; - bool visit(MemberAccess const& _node) override; - bool visit(IndexAccess const& _node) override; - bool visit(Identifier const& _node) override; - bool visit(ElementaryTypeNameExpression const& _node) override; - bool visit(Literal const& _node) override; - - void endVisit(ImportDirective const&) override; - void endVisit(ContractDefinition const&) override; - void endVisit(StructDefinition const&) override; - void endVisit(ParameterList const&) override; - void endVisit(FunctionDefinition const&) override; - void endVisit(VariableDeclaration const&) override; - void endVisit(TypeName const&) override; - void endVisit(ElementaryTypeName const&) override; - void endVisit(UserDefinedTypeName const&) override; - void endVisit(Mapping const&) override; - void endVisit(Block const&) override; - void endVisit(IfStatement const&) override; - void endVisit(WhileStatement const&) override; - void endVisit(ForStatement const&) override; - void endVisit(Continue const&) override; - void endVisit(Break const&) override; - void endVisit(Return const&) override; - void endVisit(VariableDeclarationStatement const&) override; - void endVisit(ExpressionStatement const&) override; - void endVisit(Assignment const&) override; - void endVisit(UnaryOperation const&) override; - void endVisit(BinaryOperation const&) override; - void endVisit(FunctionCall const&) override; - void endVisit(NewExpression const&) override; - void endVisit(MemberAccess const&) override; - void endVisit(IndexAccess const&) override; - void endVisit(Identifier const&) override; - void endVisit(ElementaryTypeNameExpression const&) override; - void endVisit(Literal const&) override; - -private: - void process(); - void addKeyValue(Json::Value& _obj, std::string const& _key, std::string const& _val); - void addJsonNode(std::string const& _nodeName, - std::initializer_list> _list, - bool _hasChildren); - std::string getType(Expression const& _expression); - inline void goUp() - { - solAssert(!m_jsonNodePtrs.empty(), "Uneven json nodes stack. Internal error."); - m_jsonNodePtrs.pop(); - } - - bool processed = false; - Json::Value m_astJson; - std::stack m_jsonNodePtrs; - std::string m_source; - ASTNode const* m_ast; -}; - -} -} diff --git a/libsolidity/ASTPrinter.cpp b/libsolidity/ASTPrinter.cpp deleted file mode 100644 index d29ace178..000000000 --- a/libsolidity/ASTPrinter.cpp +++ /dev/null @@ -1,538 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Pretty-printer for the abstract syntax tree (the "pretty" is arguable), used for debugging. - */ - -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -ASTPrinter::ASTPrinter( - ASTNode const& _ast, - string const& _source, - GasEstimator::ASTGasConsumption const& _gasCosts -): m_indentation(0), m_source(_source), m_ast(&_ast), m_gasCosts(_gasCosts) -{ -} - -void ASTPrinter::print(ostream& _stream) -{ - m_ostream = &_stream; - m_ast->accept(*this); - m_ostream = nullptr; -} - - -bool ASTPrinter::visit(ImportDirective const& _node) -{ - writeLine("ImportDirective \"" + _node.getIdentifier() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ContractDefinition const& _node) -{ - writeLine("ContractDefinition \"" + _node.getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(InheritanceSpecifier const& _node) -{ - writeLine("InheritanceSpecifier \"" + _node.getName()->getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(StructDefinition const& _node) -{ - writeLine("StructDefinition \"" + _node.getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(EnumDefinition const& _node) -{ - writeLine("EnumDefinition \"" + _node.getName() + "\""); - return goDeeper(); -} - -bool ASTPrinter::visit(EnumValue const& _node) -{ - writeLine("EnumValue \"" + _node.getName() + "\""); - return goDeeper(); -} - -bool ASTPrinter::visit(ParameterList const& _node) -{ - writeLine("ParameterList"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(FunctionDefinition const& _node) -{ - writeLine("FunctionDefinition \"" + _node.getName() + "\"" + - (_node.isPublic() ? " - public" : "") + - (_node.isDeclaredConst() ? " - const" : "")); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(VariableDeclaration const& _node) -{ - writeLine("VariableDeclaration \"" + _node.getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ModifierDefinition const& _node) -{ - writeLine("ModifierDefinition \"" + _node.getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ModifierInvocation const& _node) -{ - writeLine("ModifierInvocation \"" + _node.getName()->getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(EventDefinition const& _node) -{ - writeLine("EventDefinition \"" + _node.getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(TypeName const& _node) -{ - writeLine("TypeName"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ElementaryTypeName const& _node) -{ - writeLine(string("ElementaryTypeName ") + Token::toString(_node.getTypeName())); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(UserDefinedTypeName const& _node) -{ - writeLine("UserDefinedTypeName \"" + _node.getName() + "\""); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Mapping const& _node) -{ - writeLine("Mapping"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ArrayTypeName const& _node) -{ - writeLine("ArrayTypeName"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Block const& _node) -{ - writeLine("Block"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(PlaceholderStatement const& _node) -{ - writeLine("PlaceholderStatement"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(IfStatement const& _node) -{ - writeLine("IfStatement"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(WhileStatement const& _node) -{ - writeLine("WhileStatement"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ForStatement const& _node) -{ - writeLine("ForStatement"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Continue const& _node) -{ - writeLine("Continue"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Break const& _node) -{ - writeLine("Break"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Return const& _node) -{ - writeLine("Return"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(VariableDeclarationStatement const& _node) -{ - writeLine("VariableDeclarationStatement"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ExpressionStatement const& _node) -{ - writeLine("ExpressionStatement"); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Assignment const& _node) -{ - writeLine(string("Assignment using operator ") + Token::toString(_node.getAssignmentOperator())); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(UnaryOperation const& _node) -{ - writeLine(string("UnaryOperation (") + (_node.isPrefixOperation() ? "prefix" : "postfix") + - ") " + Token::toString(_node.getOperator())); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(BinaryOperation const& _node) -{ - writeLine(string("BinaryOperation using operator ") + Token::toString(_node.getOperator())); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(FunctionCall const& _node) -{ - writeLine("FunctionCall"); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(NewExpression const& _node) -{ - writeLine("NewExpression"); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(MemberAccess const& _node) -{ - writeLine("MemberAccess to member " + _node.getMemberName()); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(IndexAccess const& _node) -{ - writeLine("IndexAccess"); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Identifier const& _node) -{ - writeLine(string("Identifier ") + _node.getName()); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(ElementaryTypeNameExpression const& _node) -{ - writeLine(string("ElementaryTypeNameExpression ") + Token::toString(_node.getTypeToken())); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -bool ASTPrinter::visit(Literal const& _node) -{ - char const* tokenString = Token::toString(_node.getToken()); - if (!tokenString) - tokenString = "[no token]"; - writeLine(string("Literal, token: ") + tokenString + " value: " + _node.getValue()); - printType(_node); - printSourcePart(_node); - return goDeeper(); -} - -void ASTPrinter::endVisit(ImportDirective const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ContractDefinition const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(InheritanceSpecifier const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(StructDefinition const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(EnumDefinition const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(EnumValue const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ParameterList const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(FunctionDefinition const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(VariableDeclaration const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ModifierDefinition const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ModifierInvocation const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(EventDefinition const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(TypeName const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ElementaryTypeName const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(UserDefinedTypeName const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Mapping const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ArrayTypeName const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Block const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(PlaceholderStatement const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(IfStatement const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(WhileStatement const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ForStatement const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Continue const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Break const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Return const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(VariableDeclarationStatement const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ExpressionStatement const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Assignment const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(UnaryOperation const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(BinaryOperation const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(FunctionCall const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(NewExpression const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(MemberAccess const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(IndexAccess const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Identifier const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(ElementaryTypeNameExpression const&) -{ - m_indentation--; -} - -void ASTPrinter::endVisit(Literal const&) -{ - m_indentation--; -} - -void ASTPrinter::printSourcePart(ASTNode const& _node) -{ - if (m_gasCosts.count(&_node)) - *m_ostream << getIndentation() << " Gas costs: " << m_gasCosts.at(&_node) << endl; - if (!m_source.empty()) - { - SourceLocation const& location(_node.getLocation()); - *m_ostream << getIndentation() << " Source: " - << escaped(m_source.substr(location.start, location.end - location.start), false) << endl; - } -} - -void ASTPrinter::printType(Expression const& _expression) -{ - if (_expression.getType()) - *m_ostream << getIndentation() << " Type: " << _expression.getType()->toString() << "\n"; - else - *m_ostream << getIndentation() << " Type unknown.\n"; -} - -string ASTPrinter::getIndentation() const -{ - return string(m_indentation * 2, ' '); -} - -void ASTPrinter::writeLine(string const& _line) -{ - *m_ostream << getIndentation() << _line << endl; -} - -} -} diff --git a/libsolidity/ASTPrinter.h b/libsolidity/ASTPrinter.h deleted file mode 100644 index cdf651f3d..000000000 --- a/libsolidity/ASTPrinter.h +++ /dev/null @@ -1,141 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Pretty-printer for the abstract syntax tree (the "pretty" is arguable), used for debugging. - */ - -#pragma once - -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -/** - * Pretty-printer for the abstract syntax tree (the "pretty" is arguable) for debugging purposes. - */ -class ASTPrinter: public ASTConstVisitor -{ -public: - /// Create a printer for the given abstract syntax tree. If the source is specified, - /// the corresponding parts of the source are printed with each node. - ASTPrinter( - ASTNode const& _ast, - std::string const& _source = std::string(), - GasEstimator::ASTGasConsumption const& _gasCosts = GasEstimator::ASTGasConsumption() - ); - /// Output the string representation of the AST to _stream. - void print(std::ostream& _stream); - - bool visit(ImportDirective const& _node) override; - bool visit(ContractDefinition const& _node) override; - bool visit(InheritanceSpecifier const& _node) override; - bool visit(StructDefinition const& _node) override; - bool visit(EnumDefinition const& _node) override; - bool visit(EnumValue const& _node) override; - bool visit(ParameterList const& _node) override; - bool visit(FunctionDefinition const& _node) override; - bool visit(VariableDeclaration const& _node) override; - bool visit(ModifierDefinition const& _node) override; - bool visit(ModifierInvocation const& _node) override; - bool visit(EventDefinition const& _node) override; - bool visit(TypeName const& _node) override; - bool visit(ElementaryTypeName const& _node) override; - bool visit(UserDefinedTypeName const& _node) override; - bool visit(Mapping const& _node) override; - bool visit(ArrayTypeName const& _node) override; - bool visit(Block const& _node) override; - bool visit(PlaceholderStatement const& _node) override; - bool visit(IfStatement const& _node) override; - bool visit(WhileStatement const& _node) override; - bool visit(ForStatement const& _node) override; - bool visit(Continue const& _node) override; - bool visit(Break const& _node) override; - bool visit(Return const& _node) override; - bool visit(VariableDeclarationStatement const& _node) override; - bool visit(ExpressionStatement const& _node) override; - bool visit(Assignment const& _node) override; - bool visit(UnaryOperation const& _node) override; - bool visit(BinaryOperation const& _node) override; - bool visit(FunctionCall const& _node) override; - bool visit(NewExpression const& _node) override; - bool visit(MemberAccess const& _node) override; - bool visit(IndexAccess const& _node) override; - bool visit(Identifier const& _node) override; - bool visit(ElementaryTypeNameExpression const& _node) override; - bool visit(Literal const& _node) override; - - void endVisit(ImportDirective const&) override; - void endVisit(ContractDefinition const&) override; - void endVisit(InheritanceSpecifier const&) override; - void endVisit(StructDefinition const&) override; - void endVisit(EnumDefinition const&) override; - void endVisit(EnumValue const&) override; - void endVisit(ParameterList const&) override; - void endVisit(FunctionDefinition const&) override; - void endVisit(VariableDeclaration const&) override; - void endVisit(ModifierDefinition const&) override; - void endVisit(ModifierInvocation const&) override; - void endVisit(EventDefinition const&) override; - void endVisit(TypeName const&) override; - void endVisit(ElementaryTypeName const&) override; - void endVisit(UserDefinedTypeName const&) override; - void endVisit(Mapping const&) override; - void endVisit(ArrayTypeName const&) override; - void endVisit(Block const&) override; - void endVisit(PlaceholderStatement const&) override; - void endVisit(IfStatement const&) override; - void endVisit(WhileStatement const&) override; - void endVisit(ForStatement const&) override; - void endVisit(Continue const&) override; - void endVisit(Break const&) override; - void endVisit(Return const&) override; - void endVisit(VariableDeclarationStatement const&) override; - void endVisit(ExpressionStatement const&) override; - void endVisit(Assignment const&) override; - void endVisit(UnaryOperation const&) override; - void endVisit(BinaryOperation const&) override; - void endVisit(FunctionCall const&) override; - void endVisit(NewExpression const&) override; - void endVisit(MemberAccess const&) override; - void endVisit(IndexAccess const&) override; - void endVisit(Identifier const&) override; - void endVisit(ElementaryTypeNameExpression const&) override; - void endVisit(Literal const&) override; - -private: - void printSourcePart(ASTNode const& _node); - void printType(Expression const& _expression); - std::string getIndentation() const; - void writeLine(std::string const& _line); - bool goDeeper() { m_indentation++; return true; } - - int m_indentation; - std::string m_source; - ASTNode const* m_ast; - GasEstimator::ASTGasConsumption m_gasCosts; - std::ostream* m_ostream; -}; - -} -} diff --git a/libsolidity/ASTUtils.cpp b/libsolidity/ASTUtils.cpp deleted file mode 100644 index 081d6b317..000000000 --- a/libsolidity/ASTUtils.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Utilities to work with the AST. - */ - -#include - -using namespace std; -using namespace dev; -using namespace dev::solidity; - - - -ASTNode const* LocationFinder::leastUpperBound() -{ - m_bestMatch = nullptr; - for (ASTNode const* rootNode: m_rootNodes) - rootNode->accept(*this); - - return m_bestMatch; -} - -bool LocationFinder::visitNode(const ASTNode& _node) -{ - if (_node.getLocation().contains(m_location)) - { - m_bestMatch = &_node; - return true; - } - return false; -} diff --git a/libsolidity/ASTUtils.h b/libsolidity/ASTUtils.h deleted file mode 100644 index b24a34048..000000000 --- a/libsolidity/ASTUtils.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Utilities to work with the AST. - */ - -#pragma once - -#include -#include - -namespace dev -{ -namespace solidity -{ - -class LocationFinder: private ASTConstVisitor -{ -public: - LocationFinder(SourceLocation const& _location, std::vector _rootNodes): - m_rootNodes(_rootNodes), m_location(_location) - { - } - - /// @returns the "closest" (in the sense of most-leafward) AST node which is a descendant of - /// _node and whose source location contains _location. - ASTNode const* leastUpperBound(); - -private: - bool visitNode(ASTNode const& _node); - - std::vector m_rootNodes; - SourceLocation m_location; - ASTNode const* m_bestMatch = nullptr; -}; - -} -} diff --git a/libsolidity/ASTVisitor.h b/libsolidity/ASTVisitor.h deleted file mode 100644 index f78472208..000000000 --- a/libsolidity/ASTVisitor.h +++ /dev/null @@ -1,286 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * AST visitor base class. - */ - -#pragma once - -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -/** - * Visitor interface for the abstract syntax tree. This class is tightly bound to the - * implementation of @ref ASTNode::accept and its overrides. After a call to - * @ref ASTNode::accept, the function visit for the appropriate parameter is called and then - * (if it returns true) this continues recursively for all child nodes in document order - * (there is an exception for contracts). After all child nodes have been visited, endVisit is - * called for the node. - */ -class ASTVisitor -{ -public: - virtual bool visit(SourceUnit& _node) { return visitNode(_node); } - virtual bool visit(ImportDirective& _node) { return visitNode(_node); } - virtual bool visit(ContractDefinition& _node) { return visitNode(_node); } - virtual bool visit(InheritanceSpecifier& _node) { return visitNode(_node); } - virtual bool visit(StructDefinition& _node) { return visitNode(_node); } - virtual bool visit(EnumDefinition& _node) { return visitNode(_node); } - virtual bool visit(EnumValue& _node) { return visitNode(_node); } - virtual bool visit(ParameterList& _node) { return visitNode(_node); } - virtual bool visit(FunctionDefinition& _node) { return visitNode(_node); } - virtual bool visit(VariableDeclaration& _node) { return visitNode(_node); } - virtual bool visit(ModifierDefinition& _node) { return visitNode(_node); } - virtual bool visit(ModifierInvocation& _node) { return visitNode(_node); } - virtual bool visit(EventDefinition& _node) { return visitNode(_node); } - virtual bool visit(TypeName& _node) { return visitNode(_node); } - virtual bool visit(ElementaryTypeName& _node) { return visitNode(_node); } - virtual bool visit(UserDefinedTypeName& _node) { return visitNode(_node); } - virtual bool visit(Mapping& _node) { return visitNode(_node); } - virtual bool visit(ArrayTypeName& _node) { return visitNode(_node); } - virtual bool visit(Block& _node) { return visitNode(_node); } - virtual bool visit(PlaceholderStatement& _node) { return visitNode(_node); } - virtual bool visit(IfStatement& _node) { return visitNode(_node); } - virtual bool visit(WhileStatement& _node) { return visitNode(_node); } - virtual bool visit(ForStatement& _node) { return visitNode(_node); } - virtual bool visit(Continue& _node) { return visitNode(_node); } - virtual bool visit(Break& _node) { return visitNode(_node); } - virtual bool visit(Return& _node) { return visitNode(_node); } - virtual bool visit(VariableDeclarationStatement& _node) { return visitNode(_node); } - virtual bool visit(ExpressionStatement& _node) { return visitNode(_node); } - virtual bool visit(Assignment& _node) { return visitNode(_node); } - virtual bool visit(UnaryOperation& _node) { return visitNode(_node); } - virtual bool visit(BinaryOperation& _node) { return visitNode(_node); } - virtual bool visit(FunctionCall& _node) { return visitNode(_node); } - virtual bool visit(NewExpression& _node) { return visitNode(_node); } - virtual bool visit(MemberAccess& _node) { return visitNode(_node); } - virtual bool visit(IndexAccess& _node) { return visitNode(_node); } - virtual bool visit(Identifier& _node) { return visitNode(_node); } - virtual bool visit(ElementaryTypeNameExpression& _node) { return visitNode(_node); } - virtual bool visit(Literal& _node) { return visitNode(_node); } - - virtual void endVisit(SourceUnit& _node) { endVisitNode(_node); } - virtual void endVisit(ImportDirective& _node) { endVisitNode(_node); } - virtual void endVisit(ContractDefinition& _node) { endVisitNode(_node); } - virtual void endVisit(InheritanceSpecifier& _node) { endVisitNode(_node); } - virtual void endVisit(StructDefinition& _node) { endVisitNode(_node); } - virtual void endVisit(EnumDefinition& _node) { endVisitNode(_node); } - virtual void endVisit(EnumValue& _node) { endVisitNode(_node); } - virtual void endVisit(ParameterList& _node) { endVisitNode(_node); } - virtual void endVisit(FunctionDefinition& _node) { endVisitNode(_node); } - virtual void endVisit(VariableDeclaration& _node) { endVisitNode(_node); } - virtual void endVisit(ModifierDefinition& _node) { endVisitNode(_node); } - virtual void endVisit(ModifierInvocation& _node) { endVisitNode(_node); } - virtual void endVisit(EventDefinition& _node) { endVisitNode(_node); } - virtual void endVisit(TypeName& _node) { endVisitNode(_node); } - virtual void endVisit(ElementaryTypeName& _node) { endVisitNode(_node); } - virtual void endVisit(UserDefinedTypeName& _node) { endVisitNode(_node); } - virtual void endVisit(Mapping& _node) { endVisitNode(_node); } - virtual void endVisit(ArrayTypeName& _node) { endVisitNode(_node); } - virtual void endVisit(Block& _node) { endVisitNode(_node); } - virtual void endVisit(PlaceholderStatement& _node) { endVisitNode(_node); } - virtual void endVisit(IfStatement& _node) { endVisitNode(_node); } - virtual void endVisit(WhileStatement& _node) { endVisitNode(_node); } - virtual void endVisit(ForStatement& _node) { endVisitNode(_node); } - virtual void endVisit(Continue& _node) { endVisitNode(_node); } - virtual void endVisit(Break& _node) { endVisitNode(_node); } - virtual void endVisit(Return& _node) { endVisitNode(_node); } - virtual void endVisit(VariableDeclarationStatement& _node) { endVisitNode(_node); } - virtual void endVisit(ExpressionStatement& _node) { endVisitNode(_node); } - virtual void endVisit(Assignment& _node) { endVisitNode(_node); } - virtual void endVisit(UnaryOperation& _node) { endVisitNode(_node); } - virtual void endVisit(BinaryOperation& _node) { endVisitNode(_node); } - virtual void endVisit(FunctionCall& _node) { endVisitNode(_node); } - virtual void endVisit(NewExpression& _node) { endVisitNode(_node); } - virtual void endVisit(MemberAccess& _node) { endVisitNode(_node); } - virtual void endVisit(IndexAccess& _node) { endVisitNode(_node); } - virtual void endVisit(Identifier& _node) { endVisitNode(_node); } - virtual void endVisit(ElementaryTypeNameExpression& _node) { endVisitNode(_node); } - virtual void endVisit(Literal& _node) { endVisitNode(_node); } - -protected: - /// Generic function called by default for each node, to be overridden by derived classes - /// if behaviour unspecific to a node type is desired. - virtual bool visitNode(ASTNode&) { return true; } - /// Generic function called by default for each node, to be overridden by derived classes - /// if behaviour unspecific to a node type is desired. - virtual void endVisitNode(ASTNode&) { } -}; - -class ASTConstVisitor -{ -public: - virtual bool visit(SourceUnit const& _node) { return visitNode(_node); } - virtual bool visit(ImportDirective const& _node) { return visitNode(_node); } - virtual bool visit(ContractDefinition const& _node) { return visitNode(_node); } - virtual bool visit(InheritanceSpecifier const& _node) { return visitNode(_node); } - virtual bool visit(StructDefinition const& _node) { return visitNode(_node); } - virtual bool visit(EnumDefinition const& _node) { return visitNode(_node); } - virtual bool visit(EnumValue const& _node) { return visitNode(_node); } - virtual bool visit(ParameterList const& _node) { return visitNode(_node); } - virtual bool visit(FunctionDefinition const& _node) { return visitNode(_node); } - virtual bool visit(VariableDeclaration const& _node) { return visitNode(_node); } - virtual bool visit(ModifierDefinition const& _node) { return visitNode(_node); } - virtual bool visit(ModifierInvocation const& _node) { return visitNode(_node); } - virtual bool visit(EventDefinition const& _node) { return visitNode(_node); } - virtual bool visit(TypeName const& _node) { return visitNode(_node); } - virtual bool visit(ElementaryTypeName const& _node) { return visitNode(_node); } - virtual bool visit(UserDefinedTypeName const& _node) { return visitNode(_node); } - virtual bool visit(Mapping const& _node) { return visitNode(_node); } - virtual bool visit(ArrayTypeName const& _node) { return visitNode(_node); } - virtual bool visit(Block const& _node) { return visitNode(_node); } - virtual bool visit(PlaceholderStatement const& _node) { return visitNode(_node); } - virtual bool visit(IfStatement const& _node) { return visitNode(_node); } - virtual bool visit(WhileStatement const& _node) { return visitNode(_node); } - virtual bool visit(ForStatement const& _node) { return visitNode(_node); } - virtual bool visit(Continue const& _node) { return visitNode(_node); } - virtual bool visit(Break const& _node) { return visitNode(_node); } - virtual bool visit(Return const& _node) { return visitNode(_node); } - virtual bool visit(VariableDeclarationStatement const& _node) { return visitNode(_node); } - virtual bool visit(ExpressionStatement const& _node) { return visitNode(_node); } - virtual bool visit(Assignment const& _node) { return visitNode(_node); } - virtual bool visit(UnaryOperation const& _node) { return visitNode(_node); } - virtual bool visit(BinaryOperation const& _node) { return visitNode(_node); } - virtual bool visit(FunctionCall const& _node) { return visitNode(_node); } - virtual bool visit(NewExpression const& _node) { return visitNode(_node); } - virtual bool visit(MemberAccess const& _node) { return visitNode(_node); } - virtual bool visit(IndexAccess const& _node) { return visitNode(_node); } - virtual bool visit(Identifier const& _node) { return visitNode(_node); } - virtual bool visit(ElementaryTypeNameExpression const& _node) { return visitNode(_node); } - virtual bool visit(Literal const& _node) { return visitNode(_node); } - - virtual void endVisit(SourceUnit const& _node) { endVisitNode(_node); } - virtual void endVisit(ImportDirective const& _node) { endVisitNode(_node); } - virtual void endVisit(ContractDefinition const& _node) { endVisitNode(_node); } - virtual void endVisit(InheritanceSpecifier const& _node) { endVisitNode(_node); } - virtual void endVisit(StructDefinition const& _node) { endVisitNode(_node); } - virtual void endVisit(EnumDefinition const& _node) { endVisitNode(_node); } - virtual void endVisit(EnumValue const& _node) { endVisitNode(_node); } - virtual void endVisit(ParameterList const& _node) { endVisitNode(_node); } - virtual void endVisit(FunctionDefinition const& _node) { endVisitNode(_node); } - virtual void endVisit(VariableDeclaration const& _node) { endVisitNode(_node); } - virtual void endVisit(ModifierDefinition const& _node) { endVisitNode(_node); } - virtual void endVisit(ModifierInvocation const& _node) { endVisitNode(_node); } - virtual void endVisit(EventDefinition const& _node) { endVisitNode(_node); } - virtual void endVisit(TypeName const& _node) { endVisitNode(_node); } - virtual void endVisit(ElementaryTypeName const& _node) { endVisitNode(_node); } - virtual void endVisit(UserDefinedTypeName const& _node) { endVisitNode(_node); } - virtual void endVisit(Mapping const& _node) { endVisitNode(_node); } - virtual void endVisit(ArrayTypeName const& _node) { endVisitNode(_node); } - virtual void endVisit(Block const& _node) { endVisitNode(_node); } - virtual void endVisit(PlaceholderStatement const& _node) { endVisitNode(_node); } - virtual void endVisit(IfStatement const& _node) { endVisitNode(_node); } - virtual void endVisit(WhileStatement const& _node) { endVisitNode(_node); } - virtual void endVisit(ForStatement const& _node) { endVisitNode(_node); } - virtual void endVisit(Continue const& _node) { endVisitNode(_node); } - virtual void endVisit(Break const& _node) { endVisitNode(_node); } - virtual void endVisit(Return const& _node) { endVisitNode(_node); } - virtual void endVisit(VariableDeclarationStatement const& _node) { endVisitNode(_node); } - virtual void endVisit(ExpressionStatement const& _node) { endVisitNode(_node); } - virtual void endVisit(Assignment const& _node) { endVisitNode(_node); } - virtual void endVisit(UnaryOperation const& _node) { endVisitNode(_node); } - virtual void endVisit(BinaryOperation const& _node) { endVisitNode(_node); } - virtual void endVisit(FunctionCall const& _node) { endVisitNode(_node); } - virtual void endVisit(NewExpression const& _node) { endVisitNode(_node); } - virtual void endVisit(MemberAccess const& _node) { endVisitNode(_node); } - virtual void endVisit(IndexAccess const& _node) { endVisitNode(_node); } - virtual void endVisit(Identifier const& _node) { endVisitNode(_node); } - virtual void endVisit(ElementaryTypeNameExpression const& _node) { endVisitNode(_node); } - virtual void endVisit(Literal const& _node) { endVisitNode(_node); } - -protected: - /// Generic function called by default for each node, to be overridden by derived classes - /// if behaviour unspecific to a node type is desired. - virtual bool visitNode(ASTNode const&) { return true; } - /// Generic function called by default for each node, to be overridden by derived classes - /// if behaviour unspecific to a node type is desired. - virtual void endVisitNode(ASTNode const&) { } -}; - -/** - * Utility class that accepts std::functions and calls them for visitNode and endVisitNode. - */ -class SimpleASTVisitor: public ASTConstVisitor -{ -public: - SimpleASTVisitor( - std::function _onVisit, - std::function _onEndVisit - ): m_onVisit(_onVisit), m_onEndVisit(_onEndVisit) {} - -protected: - virtual bool visitNode(ASTNode const& _n) override { return m_onVisit ? m_onVisit(_n) : true; } - virtual void endVisitNode(ASTNode const& _n) override { m_onEndVisit(_n); } - -private: - std::function m_onVisit; - std::function m_onEndVisit; -}; - -/** - * Utility class that visits the AST in depth-first order and calls a function on each node and each edge. - * Child nodes are only visited if the node callback of the parent returns true. - * The node callback of a parent is called before any edge or node callback involving the children. - * The edge callbacks of all children are called before the edge callback of the parent. - * This way, the node callback can be used as an initializing callback and the edge callbacks can be - * used to compute a "reduce" function. - */ -class ASTReduce: public ASTConstVisitor -{ -public: - /** - * Constructs a new ASTReduce object with the given callback functions. - * @param _onNode called for each node, before its child edges and nodes, should return true to descend deeper - * @param _onEdge called for each edge with (parent, child) - */ - ASTReduce( - std::function _onNode, - std::function _onEdge - ): m_onNode(_onNode), m_onEdge(_onEdge) - { - } - -protected: - bool visitNode(ASTNode const& _node) override - { - m_parents.push_back(&_node); - return m_onNode(_node); - } - void endVisitNode(ASTNode const& _node) override - { - m_parents.pop_back(); - if (!m_parents.empty()) - m_onEdge(*m_parents.back(), _node); - } - -private: - std::vector m_parents; - std::function m_onNode; - std::function m_onEdge; -}; - -} -} diff --git a/libsolidity/AST_accept.h b/libsolidity/AST_accept.h deleted file mode 100644 index 3557f8779..000000000 --- a/libsolidity/AST_accept.h +++ /dev/null @@ -1,685 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Implementation of the accept functions of AST nodes, included by AST.cpp to not clutter that - * file with these mechanical implementations. - */ - -#pragma once - -#include -#include - -namespace dev -{ -namespace solidity -{ - -void SourceUnit::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_nodes, _visitor); - _visitor.endVisit(*this); -} - -void SourceUnit::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - listAccept(m_nodes, _visitor); - _visitor.endVisit(*this); -} - -void ImportDirective::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void ImportDirective::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void ContractDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - listAccept(m_baseContracts, _visitor); - listAccept(m_definedStructs, _visitor); - listAccept(m_definedEnums, _visitor); - listAccept(m_stateVariables, _visitor); - listAccept(m_events, _visitor); - listAccept(m_functionModifiers, _visitor); - listAccept(m_definedFunctions, _visitor); - } - _visitor.endVisit(*this); -} - -void ContractDefinition::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - listAccept(m_baseContracts, _visitor); - listAccept(m_definedStructs, _visitor); - listAccept(m_definedEnums, _visitor); - listAccept(m_stateVariables, _visitor); - listAccept(m_events, _visitor); - listAccept(m_functionModifiers, _visitor); - listAccept(m_definedFunctions, _visitor); - } - _visitor.endVisit(*this); -} - -void InheritanceSpecifier::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_baseName->accept(_visitor); - listAccept(m_arguments, _visitor); - } - _visitor.endVisit(*this); -} - -void InheritanceSpecifier::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_baseName->accept(_visitor); - listAccept(m_arguments, _visitor); - } - _visitor.endVisit(*this); -} - -void EnumDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_members, _visitor); - _visitor.endVisit(*this); -} - -void EnumDefinition::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - listAccept(m_members, _visitor); - _visitor.endVisit(*this); -} - -void EnumValue::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void EnumValue::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void StructDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_members, _visitor); - _visitor.endVisit(*this); -} - -void StructDefinition::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - listAccept(m_members, _visitor); - _visitor.endVisit(*this); -} - -void StructDefinition::checkValidityOfMembers() const -{ - checkMemberTypes(); - checkRecursion(); -} - -void ParameterList::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_parameters, _visitor); - _visitor.endVisit(*this); -} - -void ParameterList::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - listAccept(m_parameters, _visitor); - _visitor.endVisit(*this); -} - -void FunctionDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_parameters->accept(_visitor); - if (m_returnParameters) - m_returnParameters->accept(_visitor); - listAccept(m_functionModifiers, _visitor); - if (m_body) - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void FunctionDefinition::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_parameters->accept(_visitor); - if (m_returnParameters) - m_returnParameters->accept(_visitor); - listAccept(m_functionModifiers, _visitor); - if (m_body) - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void VariableDeclaration::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - if (m_typeName) - m_typeName->accept(_visitor); - if (m_value) - m_value->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void VariableDeclaration::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - if (m_typeName) - m_typeName->accept(_visitor); - if (m_value) - m_value->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void ModifierDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_parameters->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void ModifierDefinition::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_parameters->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void ModifierInvocation::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_modifierName->accept(_visitor); - listAccept(m_arguments, _visitor); - } - _visitor.endVisit(*this); -} - -void ModifierInvocation::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_modifierName->accept(_visitor); - listAccept(m_arguments, _visitor); - } - _visitor.endVisit(*this); -} - -void EventDefinition::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - m_parameters->accept(_visitor); - _visitor.endVisit(*this); -} - -void EventDefinition::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - m_parameters->accept(_visitor); - _visitor.endVisit(*this); -} - -void TypeName::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void TypeName::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void ElementaryTypeName::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void ElementaryTypeName::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void UserDefinedTypeName::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void UserDefinedTypeName::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Mapping::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_keyType->accept(_visitor); - m_valueType->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Mapping::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_keyType->accept(_visitor); - m_valueType->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void ArrayTypeName::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_baseType->accept(_visitor); - if (m_length) - m_length->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void ArrayTypeName::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_baseType->accept(_visitor); - if (m_length) - m_length->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Block::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - listAccept(m_statements, _visitor); - _visitor.endVisit(*this); -} - -void Block::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - listAccept(m_statements, _visitor); - _visitor.endVisit(*this); -} - -void PlaceholderStatement::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void PlaceholderStatement::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void IfStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_condition->accept(_visitor); - m_trueBody->accept(_visitor); - if (m_falseBody) - m_falseBody->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void IfStatement::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_condition->accept(_visitor); - m_trueBody->accept(_visitor); - if (m_falseBody) - m_falseBody->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void WhileStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_condition->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void WhileStatement::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_condition->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void ForStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - if (m_initExpression) - m_initExpression->accept(_visitor); - if (m_condExpression) - m_condExpression->accept(_visitor); - if (m_loopExpression) - m_loopExpression->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void ForStatement::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - if (m_initExpression) - m_initExpression->accept(_visitor); - if (m_condExpression) - m_condExpression->accept(_visitor); - if (m_loopExpression) - m_loopExpression->accept(_visitor); - m_body->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Continue::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Continue::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Break::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Break::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Return::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - if (m_expression) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void Return::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - if (m_expression) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void ExpressionStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - if (m_expression) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void ExpressionStatement::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - if (m_expression) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void VariableDeclarationStatement::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - m_variable->accept(_visitor); - _visitor.endVisit(*this); -} - -void VariableDeclarationStatement::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - m_variable->accept(_visitor); - _visitor.endVisit(*this); -} - -void Assignment::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_leftHandSide->accept(_visitor); - m_rightHandSide->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Assignment::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_leftHandSide->accept(_visitor); - m_rightHandSide->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void UnaryOperation::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - m_subExpression->accept(_visitor); - _visitor.endVisit(*this); -} - -void UnaryOperation::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - m_subExpression->accept(_visitor); - _visitor.endVisit(*this); -} - -void BinaryOperation::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_left->accept(_visitor); - m_right->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void BinaryOperation::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_left->accept(_visitor); - m_right->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void FunctionCall::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_expression->accept(_visitor); - listAccept(m_arguments, _visitor); - } - _visitor.endVisit(*this); -} - -void FunctionCall::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_expression->accept(_visitor); - listAccept(m_arguments, _visitor); - } - _visitor.endVisit(*this); -} - -void NewExpression::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - m_contractName->accept(_visitor); - _visitor.endVisit(*this); -} - -void NewExpression::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - m_contractName->accept(_visitor); - _visitor.endVisit(*this); -} - -void MemberAccess::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void MemberAccess::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - m_expression->accept(_visitor); - _visitor.endVisit(*this); -} - -void IndexAccess::accept(ASTVisitor& _visitor) -{ - if (_visitor.visit(*this)) - { - m_base->accept(_visitor); - if (m_index) - m_index->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void IndexAccess::accept(ASTConstVisitor& _visitor) const -{ - if (_visitor.visit(*this)) - { - m_base->accept(_visitor); - if (m_index) - m_index->accept(_visitor); - } - _visitor.endVisit(*this); -} - -void Identifier::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Identifier::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void ElementaryTypeNameExpression::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void ElementaryTypeNameExpression::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Literal::accept(ASTVisitor& _visitor) -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -void Literal::accept(ASTConstVisitor& _visitor) const -{ - _visitor.visit(*this); - _visitor.endVisit(*this); -} - -} -} diff --git a/libsolidity/ArrayUtils.cpp b/libsolidity/ArrayUtils.cpp deleted file mode 100644 index 48ee5a052..000000000 --- a/libsolidity/ArrayUtils.cpp +++ /dev/null @@ -1,786 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Code generation utils that handle arrays. - */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace solidity; - -void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType const& _sourceType) const -{ - // this copies source to target and also clears target if it was larger - // need to leave "target_ref target_byte_off" on the stack at the end - - // stack layout: [source_ref] [source length] target_ref (top) - solAssert(_targetType.location() == DataLocation::Storage, ""); - - IntegerType uint256(256); - Type const* targetBaseType = _targetType.isByteArray() ? &uint256 : &(*_targetType.getBaseType()); - Type const* sourceBaseType = _sourceType.isByteArray() ? &uint256 : &(*_sourceType.getBaseType()); - - // TODO unroll loop for small sizes - - bool sourceIsStorage = _sourceType.location() == DataLocation::Storage; - bool fromCalldata = _sourceType.location() == DataLocation::CallData; - bool directCopy = sourceIsStorage && sourceBaseType->isValueType() && *sourceBaseType == *targetBaseType; - bool haveByteOffsetSource = !directCopy && sourceIsStorage && sourceBaseType->getStorageBytes() <= 16; - bool haveByteOffsetTarget = !directCopy && targetBaseType->getStorageBytes() <= 16; - unsigned byteOffsetSize = (haveByteOffsetSource ? 1 : 0) + (haveByteOffsetTarget ? 1 : 0); - - // stack: source_ref [source_length] target_ref - // store target_ref - for (unsigned i = _sourceType.getSizeOnStack(); i > 0; --i) - m_context << eth::swapInstruction(i); - // stack: target_ref source_ref [source_length] - // stack: target_ref source_ref [source_length] - // retrieve source length - if (_sourceType.location() != DataLocation::CallData || !_sourceType.isDynamicallySized()) - retrieveLength(_sourceType); // otherwise, length is already there - if (_sourceType.location() == DataLocation::Memory && _sourceType.isDynamicallySized()) - { - // increment source pointer to point to data - m_context << eth::Instruction::SWAP1 << u256(0x20); - m_context << eth::Instruction::ADD << eth::Instruction::SWAP1; - } - - // stack: target_ref source_ref source_length - m_context << eth::Instruction::DUP3; - // stack: target_ref source_ref source_length target_ref - retrieveLength(_targetType); - // stack: target_ref source_ref source_length target_ref target_length - if (_targetType.isDynamicallySized()) - // store new target length - m_context << eth::Instruction::DUP3 << eth::Instruction::DUP3 << eth::Instruction::SSTORE; - if (sourceBaseType->getCategory() == Type::Category::Mapping) - { - solAssert(targetBaseType->getCategory() == Type::Category::Mapping, ""); - solAssert(_sourceType.location() == DataLocation::Storage, ""); - // nothing to copy - m_context - << eth::Instruction::POP << eth::Instruction::POP - << eth::Instruction::POP << eth::Instruction::POP; - return; - } - // compute hashes (data positions) - m_context << eth::Instruction::SWAP1; - if (_targetType.isDynamicallySized()) - CompilerUtils(m_context).computeHashStatic(); - // stack: target_ref source_ref source_length target_length target_data_pos - m_context << eth::Instruction::SWAP1; - convertLengthToSize(_targetType); - m_context << eth::Instruction::DUP2 << eth::Instruction::ADD; - // stack: target_ref source_ref source_length target_data_pos target_data_end - m_context << eth::Instruction::SWAP3; - // stack: target_ref target_data_end source_length target_data_pos source_ref - // skip copying if source length is zero - m_context << eth::Instruction::DUP3 << eth::Instruction::ISZERO; - eth::AssemblyItem copyLoopEndWithoutByteOffset = m_context.newTag(); - m_context.appendConditionalJumpTo(copyLoopEndWithoutByteOffset); - - if (_sourceType.location() == DataLocation::Storage && _sourceType.isDynamicallySized()) - CompilerUtils(m_context).computeHashStatic(); - // stack: target_ref target_data_end source_length target_data_pos source_data_pos - m_context << eth::Instruction::SWAP2; - convertLengthToSize(_sourceType); - m_context << eth::Instruction::DUP3 << eth::Instruction::ADD; - // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end - if (haveByteOffsetTarget) - m_context << u256(0); - if (haveByteOffsetSource) - m_context << u256(0); - // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] - eth::AssemblyItem copyLoopStart = m_context.newTag(); - m_context << copyLoopStart; - // check for loop condition - m_context - << eth::dupInstruction(3 + byteOffsetSize) << eth::dupInstruction(2 + byteOffsetSize) - << eth::Instruction::GT << eth::Instruction::ISZERO; - eth::AssemblyItem copyLoopEnd = m_context.newTag(); - m_context.appendConditionalJumpTo(copyLoopEnd); - // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] - // copy - if (sourceBaseType->getCategory() == Type::Category::Array) - { - solAssert(byteOffsetSize == 0, "Byte offset for array as base type."); - auto const& sourceBaseArrayType = dynamic_cast(*sourceBaseType); - m_context << eth::Instruction::DUP3; - if (sourceBaseArrayType.location() == DataLocation::Memory) - m_context << eth::Instruction::MLOAD; - m_context << eth::Instruction::DUP3; - copyArrayToStorage(dynamic_cast(*targetBaseType), sourceBaseArrayType); - m_context << eth::Instruction::POP; - } - else if (directCopy) - { - solAssert(byteOffsetSize == 0, "Byte offset for direct copy."); - m_context - << eth::Instruction::DUP3 << eth::Instruction::SLOAD - << eth::Instruction::DUP3 << eth::Instruction::SSTORE; - } - else - { - // Note that we have to copy each element on its own in case conversion is involved. - // We might copy too much if there is padding at the last element, but this way end - // checking is easier. - // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] - m_context << eth::dupInstruction(3 + byteOffsetSize); - if (_sourceType.location() == DataLocation::Storage) - { - if (haveByteOffsetSource) - m_context << eth::Instruction::DUP2; - else - m_context << u256(0); - StorageItem(m_context, *sourceBaseType).retrieveValue(SourceLocation(), true); - } - else if (sourceBaseType->isValueType()) - CompilerUtils(m_context).loadFromMemoryDynamic(*sourceBaseType, fromCalldata, true, false); - else - solAssert(false, "Copying of type " + _sourceType.toString(false) + " to storage not yet supported."); - // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] ... - solAssert( - 2 + byteOffsetSize + sourceBaseType->getSizeOnStack() <= 16, - "Stack too deep, try removing local variables." - ); - // fetch target storage reference - m_context << eth::dupInstruction(2 + byteOffsetSize + sourceBaseType->getSizeOnStack()); - if (haveByteOffsetTarget) - m_context << eth::dupInstruction(1 + byteOffsetSize + sourceBaseType->getSizeOnStack()); - else - m_context << u256(0); - StorageItem(m_context, *targetBaseType).storeValue(*sourceBaseType, SourceLocation(), true); - } - // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] - // increment source - if (haveByteOffsetSource) - incrementByteOffset(sourceBaseType->getStorageBytes(), 1, haveByteOffsetTarget ? 5 : 4); - else - { - m_context << eth::swapInstruction(2 + byteOffsetSize); - if (sourceIsStorage) - m_context << sourceBaseType->getStorageSize(); - else if (_sourceType.location() == DataLocation::Memory) - m_context << sourceBaseType->memoryHeadSize(); - else - m_context << sourceBaseType->getCalldataEncodedSize(true); - m_context - << eth::Instruction::ADD - << eth::swapInstruction(2 + byteOffsetSize); - } - // increment target - if (haveByteOffsetTarget) - incrementByteOffset(targetBaseType->getStorageBytes(), byteOffsetSize, byteOffsetSize + 2); - else - m_context - << eth::swapInstruction(1 + byteOffsetSize) - << targetBaseType->getStorageSize() - << eth::Instruction::ADD - << eth::swapInstruction(1 + byteOffsetSize); - m_context.appendJumpTo(copyLoopStart); - m_context << copyLoopEnd; - if (haveByteOffsetTarget) - { - // clear elements that might be left over in the current slot in target - // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end target_byte_offset [source_byte_offset] - m_context << eth::dupInstruction(byteOffsetSize) << eth::Instruction::ISZERO; - eth::AssemblyItem copyCleanupLoopEnd = m_context.appendConditionalJump(); - m_context << eth::dupInstruction(2 + byteOffsetSize) << eth::dupInstruction(1 + byteOffsetSize); - StorageItem(m_context, *targetBaseType).setToZero(SourceLocation(), true); - incrementByteOffset(targetBaseType->getStorageBytes(), byteOffsetSize, byteOffsetSize + 2); - m_context.appendJumpTo(copyLoopEnd); - - m_context << copyCleanupLoopEnd; - m_context << eth::Instruction::POP; // might pop the source, but then target is popped next - } - if (haveByteOffsetSource) - m_context << eth::Instruction::POP; - m_context << copyLoopEndWithoutByteOffset; - - // zero-out leftovers in target - // stack: target_ref target_data_end source_data_pos target_data_pos_updated source_data_end - m_context << eth::Instruction::POP << eth::Instruction::SWAP1 << eth::Instruction::POP; - // stack: target_ref target_data_end target_data_pos_updated - clearStorageLoop(*targetBaseType); - m_context << eth::Instruction::POP; -} - -void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWordBoundaries) const -{ - solAssert( - _sourceType.getBaseType()->getCalldataEncodedSize() > 0, - "Nested dynamic arrays not implemented here." - ); - CompilerUtils utils(m_context); - unsigned baseSize = 1; - if (!_sourceType.isByteArray()) - // We always pad the elements, regardless of _padToWordBoundaries. - baseSize = _sourceType.getBaseType()->getCalldataEncodedSize(); - - if (_sourceType.location() == DataLocation::CallData) - { - if (!_sourceType.isDynamicallySized()) - m_context << _sourceType.getLength(); - if (baseSize > 1) - m_context << u256(baseSize) << eth::Instruction::MUL; - // stack: target source_offset source_len - m_context << eth::Instruction::DUP1 << eth::Instruction::DUP3 << eth::Instruction::DUP5; - // stack: target source_offset source_len source_len source_offset target - m_context << eth::Instruction::CALLDATACOPY; - m_context << eth::Instruction::DUP3 << eth::Instruction::ADD; - m_context << eth::Instruction::SWAP2 << eth::Instruction::POP << eth::Instruction::POP; - } - else if (_sourceType.location() == DataLocation::Memory) - { - retrieveLength(_sourceType); - // stack: target source length - if (!_sourceType.getBaseType()->isValueType()) - { - // copy using a loop - m_context << u256(0) << eth::Instruction::SWAP3; - // stack: counter source length target - auto repeat = m_context.newTag(); - m_context << repeat; - m_context << eth::Instruction::DUP2 << eth::Instruction::DUP5; - m_context << eth::Instruction::LT << eth::Instruction::ISZERO; - auto loopEnd = m_context.appendConditionalJump(); - m_context << eth::Instruction::DUP3 << eth::Instruction::DUP5; - accessIndex(_sourceType, false); - MemoryItem(m_context, *_sourceType.getBaseType(), true).retrieveValue(SourceLocation(), true); - if (auto baseArray = dynamic_cast(_sourceType.getBaseType().get())) - copyArrayToMemory(*baseArray, _padToWordBoundaries); - else - utils.storeInMemoryDynamic(*_sourceType.getBaseType()); - m_context << eth::Instruction::SWAP3 << u256(1) << eth::Instruction::ADD; - m_context << eth::Instruction::SWAP3; - m_context.appendJumpTo(repeat); - m_context << loopEnd; - m_context << eth::Instruction::SWAP3; - utils.popStackSlots(3); - // stack: updated_target_pos - return; - } - - // memcpy using the built-in contract - if (_sourceType.isDynamicallySized()) - { - // change pointer to data part - m_context << eth::Instruction::SWAP1 << u256(32) << eth::Instruction::ADD; - m_context << eth::Instruction::SWAP1; - } - // convert length to size - if (baseSize > 1) - m_context << u256(baseSize) << eth::Instruction::MUL; - // stack: - //@TODO do not use ::CALL if less than 32 bytes? - m_context << eth::Instruction::DUP1 << eth::Instruction::DUP4 << eth::Instruction::DUP4; - utils.memoryCopy(); - - m_context << eth::Instruction::SWAP1 << eth::Instruction::POP; - // stack: - - bool paddingNeeded = false; - if (_sourceType.isDynamicallySized()) - paddingNeeded = _padToWordBoundaries && ((baseSize % 32) != 0); - else - paddingNeeded = _padToWordBoundaries && (((_sourceType.getLength() * baseSize) % 32) != 0); - if (paddingNeeded) - { - // stack: - m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2 << eth::Instruction::ADD; - // stack: - m_context << eth::Instruction::SWAP1 << u256(31) << eth::Instruction::AND; - // stack: - eth::AssemblyItem skip = m_context.newTag(); - if (_sourceType.isDynamicallySized()) - { - m_context << eth::Instruction::DUP1 << eth::Instruction::ISZERO; - m_context.appendConditionalJumpTo(skip); - } - // round off, load from there. - // stack - m_context << eth::Instruction::DUP1 << eth::Instruction::DUP3; - m_context << eth::Instruction::SUB; - // stack: target+size remainder - m_context << eth::Instruction::DUP1 << eth::Instruction::MLOAD; - // Now we AND it with ~(2**(8 * (32 - remainder)) - 1) - m_context << u256(1); - m_context << eth::Instruction::DUP4 << u256(32) << eth::Instruction::SUB; - // stack: ... 1 <32 - remainder> - m_context << u256(0x100) << eth::Instruction::EXP << eth::Instruction::SUB; - m_context << eth::Instruction::NOT << eth::Instruction::AND; - // stack: target+size remainder target+size-remainder - m_context << eth::Instruction::DUP2 << eth::Instruction::MSTORE; - // stack: target+size remainder target+size-remainder - m_context << u256(32) << eth::Instruction::ADD; - // stack: target+size remainder - m_context << eth::Instruction::SWAP2 << eth::Instruction::POP; - - if (_sourceType.isDynamicallySized()) - m_context << skip.tag(); - // stack - m_context << eth::Instruction::POP; - } - else - // stack: - m_context << eth::Instruction::ADD; - } - else - { - solAssert(_sourceType.location() == DataLocation::Storage, ""); - unsigned storageBytes = _sourceType.getBaseType()->getStorageBytes(); - u256 storageSize = _sourceType.getBaseType()->getStorageSize(); - solAssert(storageSize > 1 || (storageSize == 1 && storageBytes > 0), ""); - - retrieveLength(_sourceType); - // stack here: memory_offset storage_offset length - // jump to end if length is zero - m_context << eth::Instruction::DUP1 << eth::Instruction::ISZERO; - eth::AssemblyItem loopEnd = m_context.newTag(); - m_context.appendConditionalJumpTo(loopEnd); - // compute memory end offset - if (baseSize > 1) - // convert length to memory size - m_context << u256(baseSize) << eth::Instruction::MUL; - m_context << eth::Instruction::DUP3 << eth::Instruction::ADD << eth::Instruction::SWAP2; - if (_sourceType.isDynamicallySized()) - { - // actual array data is stored at SHA3(storage_offset) - m_context << eth::Instruction::SWAP1; - utils.computeHashStatic(); - m_context << eth::Instruction::SWAP1; - } - - // stack here: memory_end_offset storage_data_offset memory_offset - bool haveByteOffset = !_sourceType.isByteArray() && storageBytes <= 16; - if (haveByteOffset) - m_context << u256(0) << eth::Instruction::SWAP1; - // stack here: memory_end_offset storage_data_offset [storage_byte_offset] memory_offset - eth::AssemblyItem loopStart = m_context.newTag(); - m_context << loopStart; - // load and store - if (_sourceType.isByteArray()) - { - // Packed both in storage and memory. - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; - m_context << eth::Instruction::DUP2 << eth::Instruction::MSTORE; - // increment storage_data_offset by 1 - m_context << eth::Instruction::SWAP1 << u256(1) << eth::Instruction::ADD; - // increment memory offset by 32 - m_context << eth::Instruction::SWAP1 << u256(32) << eth::Instruction::ADD; - } - else - { - // stack here: memory_end_offset storage_data_offset [storage_byte_offset] memory_offset - if (haveByteOffset) - m_context << eth::Instruction::DUP3 << eth::Instruction::DUP3; - else - m_context << eth::Instruction::DUP2 << u256(0); - StorageItem(m_context, *_sourceType.getBaseType()).retrieveValue(SourceLocation(), true); - if (auto baseArray = dynamic_cast(_sourceType.getBaseType().get())) - copyArrayToMemory(*baseArray, _padToWordBoundaries); - else - utils.storeInMemoryDynamic(*_sourceType.getBaseType()); - // increment storage_data_offset and byte offset - if (haveByteOffset) - incrementByteOffset(storageBytes, 2, 3); - else - { - m_context << eth::Instruction::SWAP1; - m_context << storageSize << eth::Instruction::ADD; - m_context << eth::Instruction::SWAP1; - } - } - // check for loop condition - m_context << eth::Instruction::DUP1 << eth::dupInstruction(haveByteOffset ? 5 : 4); - m_context << eth::Instruction::GT; - m_context.appendConditionalJumpTo(loopStart); - // stack here: memory_end_offset storage_data_offset [storage_byte_offset] memory_offset - if (haveByteOffset) - m_context << eth::Instruction::SWAP1 << eth::Instruction::POP; - if (_padToWordBoundaries && baseSize % 32 != 0) - { - // memory_end_offset - start is the actual length (we want to compute the ceil of). - // memory_offset - start is its next multiple of 32, but it might be off by 32. - // so we compute: memory_end_offset += (memory_offset - memory_end_offest) & 31 - m_context << eth::Instruction::DUP3 << eth::Instruction::SWAP1 << eth::Instruction::SUB; - m_context << u256(31) << eth::Instruction::AND; - m_context << eth::Instruction::DUP3 << eth::Instruction::ADD; - m_context << eth::Instruction::SWAP2; - } - m_context << loopEnd << eth::Instruction::POP << eth::Instruction::POP; - } -} - -void ArrayUtils::clearArray(ArrayType const& _type) const -{ - unsigned stackHeightStart = m_context.getStackHeight(); - solAssert(_type.location() == DataLocation::Storage, ""); - if (_type.getBaseType()->getStorageBytes() < 32) - { - solAssert(_type.getBaseType()->isValueType(), "Invalid storage size for non-value type."); - solAssert(_type.getBaseType()->getStorageSize() <= 1, "Invalid storage size for type."); - } - if (_type.getBaseType()->isValueType()) - solAssert(_type.getBaseType()->getStorageSize() <= 1, "Invalid size for value type."); - - m_context << eth::Instruction::POP; // remove byte offset - if (_type.isDynamicallySized()) - clearDynamicArray(_type); - else if (_type.getLength() == 0 || _type.getBaseType()->getCategory() == Type::Category::Mapping) - m_context << eth::Instruction::POP; - else if (_type.getBaseType()->isValueType() && _type.getStorageSize() <= 5) - { - // unroll loop for small arrays @todo choose a good value - // Note that we loop over storage slots here, not elements. - for (unsigned i = 1; i < _type.getStorageSize(); ++i) - m_context - << u256(0) << eth::Instruction::DUP2 << eth::Instruction::SSTORE - << u256(1) << eth::Instruction::ADD; - m_context << u256(0) << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; - } - else if (!_type.getBaseType()->isValueType() && _type.getLength() <= 4) - { - // unroll loop for small arrays @todo choose a good value - solAssert(_type.getBaseType()->getStorageBytes() >= 32, "Invalid storage size."); - for (unsigned i = 1; i < _type.getLength(); ++i) - { - m_context << u256(0); - StorageItem(m_context, *_type.getBaseType()).setToZero(SourceLocation(), false); - m_context - << eth::Instruction::POP - << u256(_type.getBaseType()->getStorageSize()) << eth::Instruction::ADD; - } - m_context << u256(0); - StorageItem(m_context, *_type.getBaseType()).setToZero(SourceLocation(), true); - } - else - { - m_context << eth::Instruction::DUP1 << _type.getLength(); - convertLengthToSize(_type); - m_context << eth::Instruction::ADD << eth::Instruction::SWAP1; - if (_type.getBaseType()->getStorageBytes() < 32) - clearStorageLoop(IntegerType(256)); - else - clearStorageLoop(*_type.getBaseType()); - m_context << eth::Instruction::POP; - } - solAssert(m_context.getStackHeight() == stackHeightStart - 2, ""); -} - -void ArrayUtils::clearDynamicArray(ArrayType const& _type) const -{ - solAssert(_type.location() == DataLocation::Storage, ""); - solAssert(_type.isDynamicallySized(), ""); - - unsigned stackHeightStart = m_context.getStackHeight(); - // fetch length - m_context << eth::Instruction::DUP1 << eth::Instruction::SLOAD; - // set length to zero - m_context << u256(0) << eth::Instruction::DUP3 << eth::Instruction::SSTORE; - // stack: ref old_length - convertLengthToSize(_type); - // compute data positions - m_context << eth::Instruction::SWAP1; - CompilerUtils(m_context).computeHashStatic(); - // stack: len data_pos - m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2 << eth::Instruction::ADD - << eth::Instruction::SWAP1; - // stack: data_pos_end data_pos - if (_type.isByteArray() || _type.getBaseType()->getStorageBytes() < 32) - clearStorageLoop(IntegerType(256)); - else - clearStorageLoop(*_type.getBaseType()); - // cleanup - m_context << eth::Instruction::POP; - solAssert(m_context.getStackHeight() == stackHeightStart - 1, ""); -} - -void ArrayUtils::resizeDynamicArray(const ArrayType& _type) const -{ - solAssert(_type.location() == DataLocation::Storage, ""); - solAssert(_type.isDynamicallySized(), ""); - if (!_type.isByteArray() && _type.getBaseType()->getStorageBytes() < 32) - solAssert(_type.getBaseType()->isValueType(), "Invalid storage size for non-value type."); - - unsigned stackHeightStart = m_context.getStackHeight(); - eth::AssemblyItem resizeEnd = m_context.newTag(); - - // stack: ref new_length - // fetch old length - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; - // stack: ref new_length old_length - // store new length - m_context << eth::Instruction::DUP2 << eth::Instruction::DUP4 << eth::Instruction::SSTORE; - // skip if size is not reduced - m_context << eth::Instruction::DUP2 << eth::Instruction::DUP2 - << eth::Instruction::ISZERO << eth::Instruction::GT; - m_context.appendConditionalJumpTo(resizeEnd); - - // size reduced, clear the end of the array - // stack: ref new_length old_length - convertLengthToSize(_type); - m_context << eth::Instruction::DUP2; - convertLengthToSize(_type); - // stack: ref new_length old_size new_size - // compute data positions - m_context << eth::Instruction::DUP4; - CompilerUtils(m_context).computeHashStatic(); - // stack: ref new_length old_size new_size data_pos - m_context << eth::Instruction::SWAP2 << eth::Instruction::DUP3 << eth::Instruction::ADD; - // stack: ref new_length data_pos new_size delete_end - m_context << eth::Instruction::SWAP2 << eth::Instruction::ADD; - // stack: ref new_length delete_end delete_start - if (_type.isByteArray() || _type.getBaseType()->getStorageBytes() < 32) - clearStorageLoop(IntegerType(256)); - else - clearStorageLoop(*_type.getBaseType()); - - m_context << resizeEnd; - // cleanup - m_context << eth::Instruction::POP << eth::Instruction::POP << eth::Instruction::POP; - solAssert(m_context.getStackHeight() == stackHeightStart - 2, ""); -} - -void ArrayUtils::clearStorageLoop(Type const& _type) const -{ - unsigned stackHeightStart = m_context.getStackHeight(); - if (_type.getCategory() == Type::Category::Mapping) - { - m_context << eth::Instruction::POP; - return; - } - // stack: end_pos pos - - // jump to and return from the loop to allow for duplicate code removal - eth::AssemblyItem returnTag = m_context.pushNewTag(); - m_context << eth::Instruction::SWAP2 << eth::Instruction::SWAP1; - - // stack: end_pos pos - eth::AssemblyItem loopStart = m_context.appendJumpToNew(); - m_context << loopStart; - // check for loop condition - m_context << eth::Instruction::DUP1 << eth::Instruction::DUP3 - << eth::Instruction::GT << eth::Instruction::ISZERO; - eth::AssemblyItem zeroLoopEnd = m_context.newTag(); - m_context.appendConditionalJumpTo(zeroLoopEnd); - // delete - m_context << u256(0); - StorageItem(m_context, _type).setToZero(SourceLocation(), false); - m_context << eth::Instruction::POP; - // increment - m_context << u256(1) << eth::Instruction::ADD; - m_context.appendJumpTo(loopStart); - // cleanup - m_context << zeroLoopEnd; - m_context << eth::Instruction::POP << eth::Instruction::SWAP1; - // "return" - m_context << eth::Instruction::JUMP; - - m_context << returnTag; - solAssert(m_context.getStackHeight() == stackHeightStart - 1, ""); -} - -void ArrayUtils::convertLengthToSize(ArrayType const& _arrayType, bool _pad) const -{ - if (_arrayType.location() == DataLocation::Storage) - { - if (_arrayType.getBaseType()->getStorageSize() <= 1) - { - unsigned baseBytes = _arrayType.getBaseType()->getStorageBytes(); - if (baseBytes == 0) - m_context << eth::Instruction::POP << u256(1); - else if (baseBytes <= 16) - { - unsigned itemsPerSlot = 32 / baseBytes; - m_context - << u256(itemsPerSlot - 1) << eth::Instruction::ADD - << u256(itemsPerSlot) << eth::Instruction::SWAP1 << eth::Instruction::DIV; - } - } - else - m_context << _arrayType.getBaseType()->getStorageSize() << eth::Instruction::MUL; - } - else - { - if (!_arrayType.isByteArray()) - { - if (_arrayType.location() == DataLocation::Memory) - m_context << _arrayType.getBaseType()->memoryHeadSize(); - else - m_context << _arrayType.getBaseType()->getCalldataEncodedSize(); - m_context << eth::Instruction::MUL; - } - else if (_pad) - m_context << u256(31) << eth::Instruction::ADD - << u256(32) << eth::Instruction::DUP1 - << eth::Instruction::SWAP2 << eth::Instruction::DIV << eth::Instruction::MUL; - } -} - -void ArrayUtils::retrieveLength(ArrayType const& _arrayType) const -{ - if (!_arrayType.isDynamicallySized()) - m_context << _arrayType.getLength(); - else - { - m_context << eth::Instruction::DUP1; - switch (_arrayType.location()) - { - case DataLocation::CallData: - // length is stored on the stack - break; - case DataLocation::Memory: - m_context << eth::Instruction::MLOAD; - break; - case DataLocation::Storage: - m_context << eth::Instruction::SLOAD; - break; - } - } -} - -void ArrayUtils::accessIndex(ArrayType const& _arrayType, bool _doBoundsCheck) const -{ - DataLocation location = _arrayType.location(); - eth::Instruction load = - location == DataLocation::Storage ? eth::Instruction::SLOAD : - location == DataLocation::Memory ? eth::Instruction::MLOAD : - eth::Instruction::CALLDATALOAD; - - if (_doBoundsCheck) - { - // retrieve length - if (!_arrayType.isDynamicallySized()) - m_context << _arrayType.getLength(); - else if (location == DataLocation::CallData) - // length is stored on the stack - m_context << eth::Instruction::SWAP1; - else - m_context << eth::Instruction::DUP2 << load; - // stack: - // check out-of-bounds access - m_context << eth::Instruction::DUP2 << eth::Instruction::LT << eth::Instruction::ISZERO; - // out-of-bounds access throws exception - m_context.appendConditionalJumpTo(m_context.errorTag()); - } - else if (location == DataLocation::CallData && _arrayType.isDynamicallySized()) - // remove length if present - m_context << eth::Instruction::SWAP1 << eth::Instruction::POP; - - // stack: - m_context << eth::Instruction::SWAP1; - if (_arrayType.isDynamicallySized()) - { - if (location == DataLocation::Storage) - CompilerUtils(m_context).computeHashStatic(); - else if (location == DataLocation::Memory) - m_context << u256(32) << eth::Instruction::ADD; - } - // stack: - switch (location) - { - case DataLocation::CallData: - case DataLocation::Memory: - if (!_arrayType.isByteArray()) - { - m_context << eth::Instruction::SWAP1; - if (location == DataLocation::CallData) - m_context << _arrayType.getBaseType()->getCalldataEncodedSize(); - else - m_context << u256(_arrayType.memoryHeadSize()); - m_context << eth::Instruction::MUL; - } - m_context << eth::Instruction::ADD; - break; - case DataLocation::Storage: - m_context << eth::Instruction::SWAP1; - if (_arrayType.getBaseType()->getStorageBytes() <= 16) - { - // stack: - // goal: - // = <(index % itemsPerSlot) * byteSize> - unsigned byteSize = _arrayType.getBaseType()->getStorageBytes(); - solAssert(byteSize != 0, ""); - unsigned itemsPerSlot = 32 / byteSize; - m_context << u256(itemsPerSlot) << eth::Instruction::SWAP2; - // stack: itemsPerSlot index data_ref - m_context - << eth::Instruction::DUP3 << eth::Instruction::DUP3 - << eth::Instruction::DIV << eth::Instruction::ADD - // stack: itemsPerSlot index (data_ref + index / itemsPerSlot) - << eth::Instruction::SWAP2 << eth::Instruction::SWAP1 - << eth::Instruction::MOD; - if (byteSize != 1) - m_context << u256(byteSize) << eth::Instruction::MUL; - } - else - { - if (_arrayType.getBaseType()->getStorageSize() != 1) - m_context << _arrayType.getBaseType()->getStorageSize() << eth::Instruction::MUL; - m_context << eth::Instruction::ADD << u256(0); - } - break; - } -} - -void ArrayUtils::incrementByteOffset(unsigned _byteSize, unsigned _byteOffsetPosition, unsigned _storageOffsetPosition) const -{ - solAssert(_byteSize < 32, ""); - solAssert(_byteSize != 0, ""); - // We do the following, but avoiding jumps: - // byteOffset += byteSize - // if (byteOffset + byteSize > 32) - // { - // storageOffset++; - // byteOffset = 0; - // } - if (_byteOffsetPosition > 1) - m_context << eth::swapInstruction(_byteOffsetPosition - 1); - m_context << u256(_byteSize) << eth::Instruction::ADD; - if (_byteOffsetPosition > 1) - m_context << eth::swapInstruction(_byteOffsetPosition - 1); - // compute, X := (byteOffset + byteSize - 1) / 32, should be 1 iff byteOffset + bytesize > 32 - m_context - << u256(32) << eth::dupInstruction(1 + _byteOffsetPosition) << u256(_byteSize - 1) - << eth::Instruction::ADD << eth::Instruction::DIV; - // increment storage offset if X == 1 (just add X to it) - // stack: X - m_context - << eth::swapInstruction(_storageOffsetPosition) << eth::dupInstruction(_storageOffsetPosition + 1) - << eth::Instruction::ADD << eth::swapInstruction(_storageOffsetPosition); - // stack: X - // set source_byte_offset to zero if X == 1 (using source_byte_offset *= 1 - X) - m_context << u256(1) << eth::Instruction::SUB; - // stack: 1 - X - if (_byteOffsetPosition == 1) - m_context << eth::Instruction::MUL; - else - m_context - << eth::dupInstruction(_byteOffsetPosition + 1) << eth::Instruction::MUL - << eth::swapInstruction(_byteOffsetPosition) << eth::Instruction::POP; -} diff --git a/libsolidity/ArrayUtils.h b/libsolidity/ArrayUtils.h deleted file mode 100644 index 80ffc008a..000000000 --- a/libsolidity/ArrayUtils.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Code generation utils that handle arrays. - */ - -#pragma once - -namespace dev -{ -namespace solidity -{ - -class CompilerContext; -class Type; -class ArrayType; - -/** - * Class that provides code generation for handling arrays. - */ -class ArrayUtils -{ -public: - ArrayUtils(CompilerContext& _context): m_context(_context) {} - - /// Copies an array to an array in storage. The arrays can be of different types only if - /// their storage representation is the same. - /// Stack pre: source_reference [source_length] target_reference - /// Stack post: target_reference - void copyArrayToStorage(ArrayType const& _targetType, ArrayType const& _sourceType) const; - /// Copies the data part of an array (which cannot be dynamically nested) from anywhere - /// to a given position in memory. - /// This always copies contained data as is (i.e. structs and fixed-size arrays are copied in - /// place as required by the ABI encoding). Use CompilerUtils::convertType if you want real - /// memory copies of nested arrays. - /// Stack pre: memory_offset source_item - /// Stack post: memory_offest + length(padded) - void copyArrayToMemory(ArrayType const& _sourceType, bool _padToWordBoundaries = true) const; - /// Clears the given dynamic or static array. - /// Stack pre: storage_ref storage_byte_offset - /// Stack post: - void clearArray(ArrayType const& _type) const; - /// Clears the length and data elements of the array referenced on the stack. - /// Stack pre: reference (excludes byte offset) - /// Stack post: - void clearDynamicArray(ArrayType const& _type) const; - /// Changes the size of a dynamic array and clears the tail if it is shortened. - /// Stack pre: reference (excludes byte offset) new_length - /// Stack post: - void resizeDynamicArray(ArrayType const& _type) const; - /// Appends a loop that clears a sequence of storage slots of the given type (excluding end). - /// Stack pre: end_ref start_ref - /// Stack post: end_ref - void clearStorageLoop(Type const& _type) const; - /// Converts length to size (number of storage slots or calldata/memory bytes). - /// if @a _pad then add padding to multiples of 32 bytes for calldata/memory. - /// Stack pre: length - /// Stack post: size - void convertLengthToSize(ArrayType const& _arrayType, bool _pad = false) const; - /// Retrieves the length (number of elements) of the array ref on the stack. This also - /// works for statically-sized arrays. - /// Stack pre: reference (excludes byte offset for dynamic storage arrays) - /// Stack post: reference length - void retrieveLength(ArrayType const& _arrayType) const; - /// Performs bounds checking and returns a reference on the stack. - /// Stack pre: reference [length] index - /// Stack post (storage): storage_slot byte_offset - /// Stack post: memory/calldata_offset - void accessIndex(ArrayType const& _arrayType, bool _doBoundsCheck = true) const; - -private: - /// Adds the given number of bytes to a storage byte offset counter and also increments - /// the storage offset if adding this number again would increase the counter over 32. - /// @param byteOffsetPosition the stack offset of the storage byte offset - /// @param storageOffsetPosition the stack offset of the storage slot offset - void incrementByteOffset(unsigned _byteSize, unsigned _byteOffsetPosition, unsigned _storageOffsetPosition) const; - - CompilerContext& m_context; -}; - -} -} diff --git a/libsolidity/CMakeLists.txt b/libsolidity/CMakeLists.txt deleted file mode 100644 index 787e55765..000000000 --- a/libsolidity/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -cmake_policy(SET CMP0015 NEW) -set(CMAKE_AUTOMOC OFF) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") - -aux_source_directory(. SRC_LIST) - -include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS}) -include_directories(BEFORE ..) -include_directories(${Boost_INCLUDE_DIRS}) - -set(EXECUTABLE solidity) - -file(GLOB HEADERS "*.h") - -add_library(${EXECUTABLE} ${SRC_LIST} ${HEADERS}) -add_dependencies(${EXECUTABLE} BuildInfo.h) - -target_link_libraries(${EXECUTABLE} ${JSONCPP_LIBRARIES}) -target_link_libraries(${EXECUTABLE} evmasm) -target_link_libraries(${EXECUTABLE} devcrypto) - -install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) -install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) - diff --git a/libsolidity/Compiler.cpp b/libsolidity/Compiler.cpp deleted file mode 100644 index f0d1b38ea..000000000 --- a/libsolidity/Compiler.cpp +++ /dev/null @@ -1,726 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity compiler. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace dev::solidity; - -/** - * Simple helper class to ensure that the stack height is the same at certain places in the code. - */ -class StackHeightChecker -{ -public: - StackHeightChecker(CompilerContext const& _context): - m_context(_context), stackHeight(m_context.getStackHeight()) {} - void check() { solAssert(m_context.getStackHeight() == stackHeight, "I sense a disturbance in the stack."); } -private: - CompilerContext const& m_context; - unsigned stackHeight; -}; - -void Compiler::compileContract(ContractDefinition const& _contract, - map const& _contracts) -{ - m_context = CompilerContext(); // clear it just in case - { - CompilerContext::LocationSetter locationSetterRunTime(m_context, _contract); - initializeContext(_contract, _contracts); - appendFunctionSelector(_contract); - appendFunctionsWithoutCode(); - } - - // Swap the runtime context with the creation-time context - swap(m_context, m_runtimeContext); - CompilerContext::LocationSetter locationSetterCreationTime(m_context, _contract); - initializeContext(_contract, _contracts); - packIntoContractCreator(_contract, m_runtimeContext); - if (m_optimize) - m_context.optimise(m_optimizeRuns); -} - -void Compiler::compileClone( - ContractDefinition const& _contract, - map const& _contracts -) -{ - m_context = CompilerContext(); // clear it just in case - initializeContext(_contract, _contracts); - - appendInitAndConstructorCode(_contract); - - //@todo determine largest return size of all runtime functions - eth::AssemblyItem runtimeSub = m_context.addSubroutine(getCloneRuntime()); - solAssert(runtimeSub.data() < numeric_limits::max(), ""); - m_runtimeSub = size_t(runtimeSub.data()); - - // stack contains sub size - m_context << eth::Instruction::DUP1 << runtimeSub << u256(0) << eth::Instruction::CODECOPY; - m_context << u256(0) << eth::Instruction::RETURN; - - appendFunctionsWithoutCode(); - - if (m_optimize) - m_context.optimise(m_optimizeRuns); -} - -eth::AssemblyItem Compiler::getFunctionEntryLabel(FunctionDefinition const& _function) const -{ - return m_runtimeContext.getFunctionEntryLabelIfExists(_function); -} - -void Compiler::initializeContext(ContractDefinition const& _contract, - map const& _contracts) -{ - CompilerUtils(m_context).initialiseFreeMemoryPointer(); - m_context.setCompiledContracts(_contracts); - m_context.setInheritanceHierarchy(_contract.getLinearizedBaseContracts()); - registerStateVariables(_contract); - m_context.resetVisitedNodes(&_contract); -} - -void Compiler::appendInitAndConstructorCode(ContractDefinition const& _contract) -{ - // Determine the arguments that are used for the base constructors. - std::vector const& bases = _contract.getLinearizedBaseContracts(); - for (ContractDefinition const* contract: bases) - { - if (FunctionDefinition const* constructor = contract->getConstructor()) - for (auto const& modifier: constructor->getModifiers()) - { - auto baseContract = dynamic_cast( - &modifier->getName()->getReferencedDeclaration()); - if (baseContract) - if (m_baseArguments.count(baseContract->getConstructor()) == 0) - m_baseArguments[baseContract->getConstructor()] = &modifier->getArguments(); - } - - for (ASTPointer const& base: contract->getBaseContracts()) - { - ContractDefinition const* baseContract = dynamic_cast( - &base->getName()->getReferencedDeclaration()); - solAssert(baseContract, ""); - - if (m_baseArguments.count(baseContract->getConstructor()) == 0) - m_baseArguments[baseContract->getConstructor()] = &base->getArguments(); - } - } - // Initialization of state variables in base-to-derived order. - for (ContractDefinition const* contract: boost::adaptors::reverse(bases)) - initializeStateVariables(*contract); - - if (FunctionDefinition const* constructor = _contract.getConstructor()) - appendConstructor(*constructor); - else if (auto c = m_context.getNextConstructor(_contract)) - appendBaseConstructor(*c); -} - -void Compiler::packIntoContractCreator(ContractDefinition const& _contract, CompilerContext const& _runtimeContext) -{ - appendInitAndConstructorCode(_contract); - - eth::AssemblyItem runtimeSub = m_context.addSubroutine(_runtimeContext.getAssembly()); - solAssert(runtimeSub.data() < numeric_limits::max(), ""); - m_runtimeSub = size_t(runtimeSub.data()); - - // stack contains sub size - m_context << eth::Instruction::DUP1 << runtimeSub << u256(0) << eth::Instruction::CODECOPY; - m_context << u256(0) << eth::Instruction::RETURN; - - // note that we have to include the functions again because of absolute jump labels - appendFunctionsWithoutCode(); -} - -void Compiler::appendBaseConstructor(FunctionDefinition const& _constructor) -{ - CompilerContext::LocationSetter locationSetter(m_context, _constructor); - FunctionType constructorType(_constructor); - if (!constructorType.getParameterTypes().empty()) - { - solAssert(m_baseArguments.count(&_constructor), ""); - std::vector> const* arguments = m_baseArguments[&_constructor]; - solAssert(arguments, ""); - for (unsigned i = 0; i < arguments->size(); ++i) - compileExpression(*(arguments->at(i)), constructorType.getParameterTypes()[i]); - } - _constructor.accept(*this); -} - -void Compiler::appendConstructor(FunctionDefinition const& _constructor) -{ - CompilerContext::LocationSetter locationSetter(m_context, _constructor); - // copy constructor arguments from code to memory and then to stack, they are supplied after the actual program - if (!_constructor.getParameters().empty()) - { - unsigned argumentSize = 0; - for (ASTPointer const& var: _constructor.getParameters()) - if (var->getType()->isDynamicallySized()) - { - argumentSize = 0; - break; - } - else - argumentSize += var->getType()->getCalldataEncodedSize(); - - CompilerUtils(m_context).fetchFreeMemoryPointer(); - if (argumentSize == 0) - { - // argument size is dynamic, use CODESIZE to determine it - m_context.appendProgramSize(); // program itself - // CODESIZE is program plus manually added arguments - m_context << eth::Instruction::CODESIZE << eth::Instruction::SUB; - } - else - m_context << u256(argumentSize); - // stack: - m_context << eth::Instruction::DUP1; - m_context.appendProgramSize(); - m_context << eth::Instruction::DUP4 << eth::Instruction::CODECOPY; - m_context << eth::Instruction::ADD; - CompilerUtils(m_context).storeFreeMemoryPointer(); - appendCalldataUnpacker( - FunctionType(_constructor).getParameterTypes(), - true, - CompilerUtils::freeMemoryPointer + 0x20 - ); - } - _constructor.accept(*this); -} - -void Compiler::appendFunctionSelector(ContractDefinition const& _contract) -{ - map, FunctionTypePointer> interfaceFunctions = _contract.getInterfaceFunctions(); - map, const eth::AssemblyItem> callDataUnpackerEntryPoints; - - FunctionDefinition const* fallback = _contract.getFallbackFunction(); - eth::AssemblyItem notFound = m_context.newTag(); - // shortcut messages without data if we have many functions in order to be able to receive - // ether with constant gas - if (interfaceFunctions.size() > 5 || fallback) - { - m_context << eth::Instruction::CALLDATASIZE << eth::Instruction::ISZERO; - m_context.appendConditionalJumpTo(notFound); - } - - // retrieve the function signature hash from the calldata - if (!interfaceFunctions.empty()) - CompilerUtils(m_context).loadFromMemory(0, IntegerType(CompilerUtils::dataStartOffset * 8), true); - - // stack now is: 1 0 - for (auto const& it: interfaceFunctions) - { - callDataUnpackerEntryPoints.insert(std::make_pair(it.first, m_context.newTag())); - m_context << eth::dupInstruction(1) << u256(FixedHash<4>::Arith(it.first)) << eth::Instruction::EQ; - m_context.appendConditionalJumpTo(callDataUnpackerEntryPoints.at(it.first)); - } - m_context.appendJumpTo(notFound); - - m_context << notFound; - if (fallback) - { - eth::AssemblyItem returnTag = m_context.pushNewTag(); - fallback->accept(*this); - m_context << returnTag; - appendReturnValuePacker(FunctionType(*fallback).getReturnParameterTypes()); - } - else - m_context << eth::Instruction::STOP; // function not found - - for (auto const& it: interfaceFunctions) - { - FunctionTypePointer const& functionType = it.second; - solAssert(functionType->hasDeclaration(), ""); - CompilerContext::LocationSetter locationSetter(m_context, functionType->getDeclaration()); - m_context << callDataUnpackerEntryPoints.at(it.first); - eth::AssemblyItem returnTag = m_context.pushNewTag(); - appendCalldataUnpacker(functionType->getParameterTypes()); - m_context.appendJumpTo(m_context.getFunctionEntryLabel(functionType->getDeclaration())); - m_context << returnTag; - appendReturnValuePacker(functionType->getReturnParameterTypes()); - } -} - -void Compiler::appendCalldataUnpacker( - TypePointers const& _typeParameters, - bool _fromMemory, - u256 _startOffset -) -{ - // We do not check the calldata size, everything is zero-paddedd - - //@todo this does not yet support nested dynamic arrays - - if (_startOffset == u256(-1)) - _startOffset = u256(CompilerUtils::dataStartOffset); - - m_context << _startOffset; - for (TypePointer const& type: _typeParameters) - { - // stack: v1 v2 ... v(k-1) mem_offset - switch (type->getCategory()) - { - case Type::Category::Array: - { - auto const& arrayType = dynamic_cast(*type); - solAssert(arrayType.location() != DataLocation::Storage, ""); - solAssert(!arrayType.getBaseType()->isDynamicallySized(), "Nested arrays not yet implemented."); - if (_fromMemory) - { - solAssert( - arrayType.getBaseType()->isValueType(), - "Nested memory arrays not yet implemented here." - ); - // @todo If base type is an array or struct, it is still calldata-style encoded, so - // we would have to convert it like below. - solAssert(arrayType.location() == DataLocation::Memory, ""); - // compute data pointer - m_context << eth::Instruction::DUP1 << eth::Instruction::MLOAD; - //@todo once we support nested arrays, this offset needs to be dynamic. - m_context << _startOffset << eth::Instruction::ADD; - m_context << eth::Instruction::SWAP1 << u256(0x20) << eth::Instruction::ADD; - } - else - { - // first load from calldata and potentially convert to memory if arrayType is memory - TypePointer calldataType = arrayType.copyForLocation(DataLocation::CallData, false); - if (calldataType->isDynamicallySized()) - { - // put on stack: data_pointer length - CompilerUtils(m_context).loadFromMemoryDynamic(IntegerType(256), !_fromMemory); - // stack: data_offset next_pointer - //@todo once we support nested arrays, this offset needs to be dynamic. - m_context << eth::Instruction::SWAP1 << _startOffset << eth::Instruction::ADD; - // stack: next_pointer data_pointer - // retrieve length - CompilerUtils(m_context).loadFromMemoryDynamic(IntegerType(256), !_fromMemory, true); - // stack: next_pointer length data_pointer - m_context << eth::Instruction::SWAP2; - } - else - { - // leave the pointer on the stack - m_context << eth::Instruction::DUP1; - m_context << u256(calldataType->getCalldataEncodedSize()) << eth::Instruction::ADD; - } - if (arrayType.location() == DataLocation::Memory) - { - // stack: calldata_ref [length] next_calldata - // copy to memory - // move calldata type up again - CompilerUtils(m_context).moveIntoStack(calldataType->getSizeOnStack()); - CompilerUtils(m_context).convertType(*calldataType, arrayType); - // fetch next pointer again - CompilerUtils(m_context).moveToStackTop(arrayType.getSizeOnStack()); - } - } - break; - } - default: - solAssert(!type->isDynamicallySized(), "Unknown dynamically sized type: " + type->toString()); - CompilerUtils(m_context).loadFromMemoryDynamic(*type, !_fromMemory, true); - } - } - m_context << eth::Instruction::POP; -} - -void Compiler::appendReturnValuePacker(TypePointers const& _typeParameters) -{ - CompilerUtils utils(m_context); - if (_typeParameters.empty()) - m_context << eth::Instruction::STOP; - else - { - utils.fetchFreeMemoryPointer(); - //@todo optimization: if we return a single memory array, there should be enough space before - // its data to add the needed parts and we avoid a memory copy. - utils.encodeToMemory(_typeParameters, _typeParameters); - utils.toSizeAfterFreeMemoryPointer(); - m_context << eth::Instruction::RETURN; - } -} - -void Compiler::registerStateVariables(ContractDefinition const& _contract) -{ - for (auto const& var: ContractType(_contract).getStateVariables()) - m_context.addStateVariable(*get<0>(var), get<1>(var), get<2>(var)); -} - -void Compiler::initializeStateVariables(ContractDefinition const& _contract) -{ - for (ASTPointer const& variable: _contract.getStateVariables()) - if (variable->getValue() && !variable->isConstant()) - ExpressionCompiler(m_context, m_optimize).appendStateVariableInitialization(*variable); -} - -bool Compiler::visit(VariableDeclaration const& _variableDeclaration) -{ - solAssert(_variableDeclaration.isStateVariable(), "Compiler visit to non-state variable declaration."); - CompilerContext::LocationSetter locationSetter(m_context, _variableDeclaration); - - m_context.startFunction(_variableDeclaration); - m_breakTags.clear(); - m_continueTags.clear(); - - ExpressionCompiler(m_context, m_optimize).appendStateVariableAccessor(_variableDeclaration); - - return false; -} - -bool Compiler::visit(FunctionDefinition const& _function) -{ - CompilerContext::LocationSetter locationSetter(m_context, _function); - - m_context.startFunction(_function); - - // stack upon entry: [return address] [arg0] [arg1] ... [argn] - // reserve additional slots: [retarg0] ... [retargm] [localvar0] ... [localvarp] - - unsigned parametersSize = CompilerUtils::getSizeOnStack(_function.getParameters()); - if (!_function.isConstructor()) - // adding 1 for return address. - m_context.adjustStackOffset(parametersSize + 1); - for (ASTPointer const& variable: _function.getParameters()) - { - m_context.addVariable(*variable, parametersSize); - parametersSize -= variable->getType()->getSizeOnStack(); - } - - for (ASTPointer const& variable: _function.getReturnParameters()) - appendStackVariableInitialisation(*variable); - for (VariableDeclaration const* localVariable: _function.getLocalVariables()) - appendStackVariableInitialisation(*localVariable); - - if (_function.isConstructor()) - if (auto c = m_context.getNextConstructor(dynamic_cast(*_function.getScope()))) - appendBaseConstructor(*c); - - m_returnTag = m_context.newTag(); - m_breakTags.clear(); - m_continueTags.clear(); - m_stackCleanupForReturn = 0; - m_currentFunction = &_function; - m_modifierDepth = 0; - - appendModifierOrFunctionCode(); - - m_context << m_returnTag; - - // Now we need to re-shuffle the stack. For this we keep a record of the stack layout - // that shows the target positions of the elements, where "-1" denotes that this element needs - // to be removed from the stack. - // Note that the fact that the return arguments are of increasing index is vital for this - // algorithm to work. - - unsigned const c_argumentsSize = CompilerUtils::getSizeOnStack(_function.getParameters()); - unsigned const c_returnValuesSize = CompilerUtils::getSizeOnStack(_function.getReturnParameters()); - unsigned const c_localVariablesSize = CompilerUtils::getSizeOnStack(_function.getLocalVariables()); - - vector stackLayout; - stackLayout.push_back(c_returnValuesSize); // target of return address - stackLayout += vector(c_argumentsSize, -1); // discard all arguments - for (unsigned i = 0; i < c_returnValuesSize; ++i) - stackLayout.push_back(i); - stackLayout += vector(c_localVariablesSize, -1); - - solAssert(stackLayout.size() <= 17, "Stack too deep, try removing local variables."); - while (stackLayout.back() != int(stackLayout.size() - 1)) - if (stackLayout.back() < 0) - { - m_context << eth::Instruction::POP; - stackLayout.pop_back(); - } - else - { - m_context << eth::swapInstruction(stackLayout.size() - stackLayout.back() - 1); - swap(stackLayout[stackLayout.back()], stackLayout.back()); - } - //@todo assert that everything is in place now - - for (ASTPointer const& variable: _function.getParameters() + _function.getReturnParameters()) - m_context.removeVariable(*variable); - for (VariableDeclaration const* localVariable: _function.getLocalVariables()) - m_context.removeVariable(*localVariable); - - m_context.adjustStackOffset(-(int)c_returnValuesSize); - - if (!_function.isConstructor()) - m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction); - return false; -} - -bool Compiler::visit(IfStatement const& _ifStatement) -{ - StackHeightChecker checker(m_context); - CompilerContext::LocationSetter locationSetter(m_context, _ifStatement); - compileExpression(_ifStatement.getCondition()); - m_context << eth::Instruction::ISZERO; - eth::AssemblyItem falseTag = m_context.appendConditionalJump(); - eth::AssemblyItem endTag = falseTag; - _ifStatement.getTrueStatement().accept(*this); - if (_ifStatement.getFalseStatement()) - { - endTag = m_context.appendJumpToNew(); - m_context << falseTag; - _ifStatement.getFalseStatement()->accept(*this); - } - m_context << endTag; - - checker.check(); - return false; -} - -bool Compiler::visit(WhileStatement const& _whileStatement) -{ - StackHeightChecker checker(m_context); - CompilerContext::LocationSetter locationSetter(m_context, _whileStatement); - eth::AssemblyItem loopStart = m_context.newTag(); - eth::AssemblyItem loopEnd = m_context.newTag(); - m_continueTags.push_back(loopStart); - m_breakTags.push_back(loopEnd); - - m_context << loopStart; - compileExpression(_whileStatement.getCondition()); - m_context << eth::Instruction::ISZERO; - m_context.appendConditionalJumpTo(loopEnd); - - _whileStatement.getBody().accept(*this); - - m_context.appendJumpTo(loopStart); - m_context << loopEnd; - - m_continueTags.pop_back(); - m_breakTags.pop_back(); - - checker.check(); - return false; -} - -bool Compiler::visit(ForStatement const& _forStatement) -{ - StackHeightChecker checker(m_context); - CompilerContext::LocationSetter locationSetter(m_context, _forStatement); - eth::AssemblyItem loopStart = m_context.newTag(); - eth::AssemblyItem loopEnd = m_context.newTag(); - eth::AssemblyItem loopNext = m_context.newTag(); - m_continueTags.push_back(loopNext); - m_breakTags.push_back(loopEnd); - - if (_forStatement.getInitializationExpression()) - _forStatement.getInitializationExpression()->accept(*this); - - m_context << loopStart; - - // if there is no terminating condition in for, default is to always be true - if (_forStatement.getCondition()) - { - compileExpression(*_forStatement.getCondition()); - m_context << eth::Instruction::ISZERO; - m_context.appendConditionalJumpTo(loopEnd); - } - - _forStatement.getBody().accept(*this); - - m_context << loopNext; - - // for's loop expression if existing - if (_forStatement.getLoopExpression()) - _forStatement.getLoopExpression()->accept(*this); - - m_context.appendJumpTo(loopStart); - m_context << loopEnd; - - m_continueTags.pop_back(); - m_breakTags.pop_back(); - - checker.check(); - return false; -} - -bool Compiler::visit(Continue const& _continueStatement) -{ - CompilerContext::LocationSetter locationSetter(m_context, _continueStatement); - if (!m_continueTags.empty()) - m_context.appendJumpTo(m_continueTags.back()); - return false; -} - -bool Compiler::visit(Break const& _breakStatement) -{ - CompilerContext::LocationSetter locationSetter(m_context, _breakStatement); - if (!m_breakTags.empty()) - m_context.appendJumpTo(m_breakTags.back()); - return false; -} - -bool Compiler::visit(Return const& _return) -{ - CompilerContext::LocationSetter locationSetter(m_context, _return); - //@todo modifications are needed to make this work with functions returning multiple values - if (Expression const* expression = _return.getExpression()) - { - solAssert(_return.getFunctionReturnParameters(), "Invalid return parameters pointer."); - VariableDeclaration const& firstVariable = *_return.getFunctionReturnParameters()->getParameters().front(); - compileExpression(*expression, firstVariable.getType()); - CompilerUtils(m_context).moveToStackVariable(firstVariable); - } - for (unsigned i = 0; i < m_stackCleanupForReturn; ++i) - m_context << eth::Instruction::POP; - m_context.appendJumpTo(m_returnTag); - m_context.adjustStackOffset(m_stackCleanupForReturn); - return false; -} - -bool Compiler::visit(VariableDeclarationStatement const& _variableDeclarationStatement) -{ - StackHeightChecker checker(m_context); - CompilerContext::LocationSetter locationSetter(m_context, _variableDeclarationStatement); - if (Expression const* expression = _variableDeclarationStatement.getExpression()) - { - compileExpression(*expression, _variableDeclarationStatement.getDeclaration().getType()); - CompilerUtils(m_context).moveToStackVariable(_variableDeclarationStatement.getDeclaration()); - } - checker.check(); - return false; -} - -bool Compiler::visit(ExpressionStatement const& _expressionStatement) -{ - StackHeightChecker checker(m_context); - CompilerContext::LocationSetter locationSetter(m_context, _expressionStatement); - Expression const& expression = _expressionStatement.getExpression(); - compileExpression(expression); - CompilerUtils(m_context).popStackElement(*expression.getType()); - checker.check(); - return false; -} - -bool Compiler::visit(PlaceholderStatement const& _placeholderStatement) -{ - StackHeightChecker checker(m_context); - CompilerContext::LocationSetter locationSetter(m_context, _placeholderStatement); - ++m_modifierDepth; - appendModifierOrFunctionCode(); - --m_modifierDepth; - checker.check(); - return true; -} - -void Compiler::appendFunctionsWithoutCode() -{ - set functions = m_context.getFunctionsWithoutCode(); - while (!functions.empty()) - { - for (Declaration const* function: functions) - { - m_context.setStackOffset(0); - function->accept(*this); - } - functions = m_context.getFunctionsWithoutCode(); - } -} - -void Compiler::appendModifierOrFunctionCode() -{ - solAssert(m_currentFunction, ""); - if (m_modifierDepth >= m_currentFunction->getModifiers().size()) - m_currentFunction->getBody().accept(*this); - else - { - ASTPointer const& modifierInvocation = m_currentFunction->getModifiers()[m_modifierDepth]; - - // constructor call should be excluded - if (dynamic_cast(&modifierInvocation->getName()->getReferencedDeclaration())) - { - ++m_modifierDepth; - appendModifierOrFunctionCode(); - --m_modifierDepth; - return; - } - - ModifierDefinition const& modifier = m_context.getFunctionModifier(modifierInvocation->getName()->getName()); - CompilerContext::LocationSetter locationSetter(m_context, modifier); - solAssert(modifier.getParameters().size() == modifierInvocation->getArguments().size(), ""); - for (unsigned i = 0; i < modifier.getParameters().size(); ++i) - { - m_context.addVariable(*modifier.getParameters()[i]); - compileExpression(*modifierInvocation->getArguments()[i], - modifier.getParameters()[i]->getType()); - } - for (VariableDeclaration const* localVariable: modifier.getLocalVariables()) - appendStackVariableInitialisation(*localVariable); - - unsigned const c_stackSurplus = CompilerUtils::getSizeOnStack(modifier.getParameters()) + - CompilerUtils::getSizeOnStack(modifier.getLocalVariables()); - m_stackCleanupForReturn += c_stackSurplus; - - modifier.getBody().accept(*this); - - for (unsigned i = 0; i < c_stackSurplus; ++i) - m_context << eth::Instruction::POP; - m_stackCleanupForReturn -= c_stackSurplus; - } -} - -void Compiler::appendStackVariableInitialisation(VariableDeclaration const& _variable) -{ - CompilerContext::LocationSetter location(m_context, _variable); - m_context.addVariable(_variable); - CompilerUtils(m_context).pushZeroValue(*_variable.getType()); -} - -void Compiler::compileExpression(Expression const& _expression, TypePointer const& _targetType) -{ - ExpressionCompiler expressionCompiler(m_context, m_optimize); - expressionCompiler.compile(_expression); - if (_targetType) - CompilerUtils(m_context).convertType(*_expression.getType(), *_targetType); -} - -eth::Assembly Compiler::getCloneRuntime() -{ - eth::Assembly a; - a << eth::Instruction::CALLDATASIZE; - a << u256(0) << eth::Instruction::DUP1 << eth::Instruction::CALLDATACOPY; - //@todo adjust for larger return values, make this dynamic. - a << u256(0x20) << u256(0) << eth::Instruction::CALLDATASIZE; - // unfortunately, we have to send the value again, so that CALLVALUE returns the correct value - // in the callcoded contract. - a << u256(0) << eth::Instruction::CALLVALUE; - // this is the address which has to be substituted by the linker. - //@todo implement as special "marker" AssemblyItem. - a << u256("0xcafecafecafecafecafecafecafecafecafecafe"); - a << u256(eth::c_callGas + eth::c_callValueTransferGas + 10) << eth::Instruction::GAS << eth::Instruction::SUB; - a << eth::Instruction::CALLCODE; - //@todo adjust for larger return values, make this dynamic. - a << u256(0x20) << u256(0) << eth::Instruction::RETURN; - return a; -} diff --git a/libsolidity/Compiler.h b/libsolidity/Compiler.h deleted file mode 100644 index bec2b0641..000000000 --- a/libsolidity/Compiler.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity AST to EVM bytecode compiler. - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace dev { -namespace solidity { - -class Compiler: private ASTConstVisitor -{ -public: - explicit Compiler(bool _optimize = false, unsigned _runs = 200): - m_optimize(_optimize), - m_optimizeRuns(_runs), - m_context(), - m_returnTag(m_context.newTag()) - { - } - - void compileContract(ContractDefinition const& _contract, - std::map const& _contracts); - /// Compiles a contract that uses CALLCODE to call into a pre-deployed version of the given - /// contract at runtime, but contains the full creation-time code. - void compileClone( - ContractDefinition const& _contract, - std::map const& _contracts - ); - bytes getAssembledBytecode() { return m_context.getAssembledBytecode(); } - bytes getRuntimeBytecode() { return m_context.getAssembledRuntimeBytecode(m_runtimeSub); } - /// @arg _sourceCodes is the map of input files to source code strings - /// @arg _inJsonFromat shows whether the out should be in Json format - Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const - { - return m_context.streamAssembly(_stream, _sourceCodes, _inJsonFormat); - } - /// @returns Assembly items of the normal compiler context - eth::AssemblyItems const& getAssemblyItems() const { return m_context.getAssembly().getItems(); } - /// @returns Assembly items of the runtime compiler context - eth::AssemblyItems const& getRuntimeAssemblyItems() const { return m_context.getAssembly().getSub(m_runtimeSub).getItems(); } - - /// @returns the entry label of the given function. Might return an AssemblyItem of type - /// UndefinedItem if it does not exist yet. - eth::AssemblyItem getFunctionEntryLabel(FunctionDefinition const& _function) const; - -private: - /// Registers the non-function objects inside the contract with the context. - void initializeContext(ContractDefinition const& _contract, - std::map const& _contracts); - /// Adds the code that is run at creation time. Should be run after exchanging the run-time context - /// with a new and initialized context. Adds the constructor code. - void packIntoContractCreator(ContractDefinition const& _contract, CompilerContext const& _runtimeContext); - /// Appends state variable initialisation and constructor code. - void appendInitAndConstructorCode(ContractDefinition const& _contract); - void appendBaseConstructor(FunctionDefinition const& _constructor); - void appendConstructor(FunctionDefinition const& _constructor); - void appendFunctionSelector(ContractDefinition const& _contract); - /// Creates code that unpacks the arguments for the given function represented by a vector of TypePointers. - /// From memory if @a _fromMemory is true, otherwise from call data. - /// Expects source offset on the stack. - void appendCalldataUnpacker( - TypePointers const& _typeParameters, - bool _fromMemory = false, - u256 _startOffset = u256(-1) - ); - void appendReturnValuePacker(TypePointers const& _typeParameters); - - void registerStateVariables(ContractDefinition const& _contract); - void initializeStateVariables(ContractDefinition const& _contract); - - /// Initialises all memory arrays in the local variables to point to an empty location. - void initialiseMemoryArrays(std::vector _variables); - /// Pushes the initialised value of the given type to the stack. If the type is a memory - /// reference type, allocates memory and pushes the memory pointer. - /// Not to be used for storage references. - void initialiseInMemory(Type const& _type); - - virtual bool visit(VariableDeclaration const& _variableDeclaration) override; - virtual bool visit(FunctionDefinition const& _function) override; - virtual bool visit(IfStatement const& _ifStatement) override; - virtual bool visit(WhileStatement const& _whileStatement) override; - virtual bool visit(ForStatement const& _forStatement) override; - virtual bool visit(Continue const& _continue) override; - virtual bool visit(Break const& _break) override; - virtual bool visit(Return const& _return) override; - virtual bool visit(VariableDeclarationStatement const& _variableDeclarationStatement) override; - virtual bool visit(ExpressionStatement const& _expressionStatement) override; - virtual bool visit(PlaceholderStatement const&) override; - - /// Repeatedly visits all function which are referenced but which are not compiled yet. - void appendFunctionsWithoutCode(); - - /// Appends one layer of function modifier code of the current function, or the function - /// body itself if the last modifier was reached. - void appendModifierOrFunctionCode(); - - void appendStackVariableInitialisation(VariableDeclaration const& _variable); - void compileExpression(Expression const& _expression, TypePointer const& _targetType = TypePointer()); - - /// @returns the runtime assembly for clone contracts. - static eth::Assembly getCloneRuntime(); - - bool const m_optimize; - unsigned const m_optimizeRuns; - CompilerContext m_context; - size_t m_runtimeSub = size_t(-1); ///< Identifier of the runtime sub-assembly - CompilerContext m_runtimeContext; - std::vector m_breakTags; ///< tag to jump to for a "break" statement - std::vector m_continueTags; ///< tag to jump to for a "continue" statement - eth::AssemblyItem m_returnTag; ///< tag to jump to for a "return" statement - unsigned m_modifierDepth = 0; - FunctionDefinition const* m_currentFunction = nullptr; - unsigned m_stackCleanupForReturn = 0; ///< this number of stack elements need to be removed before jump to m_returnTag - // arguments for base constructors, filled in derived-to-base order - std::map> const*> m_baseArguments; -}; - -} -} diff --git a/libsolidity/CompilerContext.cpp b/libsolidity/CompilerContext.cpp deleted file mode 100644 index 0f6f5fe76..000000000 --- a/libsolidity/CompilerContext.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Utilities for the solidity compiler. - */ - -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -void CompilerContext::addMagicGlobal(MagicVariableDeclaration const& _declaration) -{ - m_magicGlobals.insert(&_declaration); -} - -void CompilerContext::addStateVariable( - VariableDeclaration const& _declaration, - u256 const& _storageOffset, - unsigned _byteOffset -) -{ - m_stateVariables[&_declaration] = make_pair(_storageOffset, _byteOffset); -} - -void CompilerContext::startFunction(Declaration const& _function) -{ - m_functionsWithCode.insert(&_function); - *this << getFunctionEntryLabel(_function); -} - -void CompilerContext::addVariable(VariableDeclaration const& _declaration, - unsigned _offsetToCurrent) -{ - solAssert(m_asm.deposit() >= 0 && unsigned(m_asm.deposit()) >= _offsetToCurrent, ""); - m_localVariables[&_declaration] = unsigned(m_asm.deposit()) - _offsetToCurrent; -} - -void CompilerContext::removeVariable(VariableDeclaration const& _declaration) -{ - solAssert(!!m_localVariables.count(&_declaration), ""); - m_localVariables.erase(&_declaration); -} - -bytes const& CompilerContext::getCompiledContract(const ContractDefinition& _contract) const -{ - auto ret = m_compiledContracts.find(&_contract); - solAssert(ret != m_compiledContracts.end(), "Compiled contract not found."); - return *ret->second; -} - -bool CompilerContext::isLocalVariable(Declaration const* _declaration) const -{ - return !!m_localVariables.count(_declaration); -} - -eth::AssemblyItem CompilerContext::getFunctionEntryLabel(Declaration const& _declaration) -{ - auto res = m_functionEntryLabels.find(&_declaration); - if (res == m_functionEntryLabels.end()) - { - eth::AssemblyItem tag(m_asm.newTag()); - m_functionEntryLabels.insert(make_pair(&_declaration, tag)); - return tag.tag(); - } - else - return res->second.tag(); -} - -eth::AssemblyItem CompilerContext::getFunctionEntryLabelIfExists(Declaration const& _declaration) const -{ - auto res = m_functionEntryLabels.find(&_declaration); - return res == m_functionEntryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag(); -} - -eth::AssemblyItem CompilerContext::getVirtualFunctionEntryLabel(FunctionDefinition const& _function) -{ - solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); - return getVirtualFunctionEntryLabel(_function, m_inheritanceHierarchy.begin()); -} - -eth::AssemblyItem CompilerContext::getSuperFunctionEntryLabel(FunctionDefinition const& _function, ContractDefinition const& _base) -{ - solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); - return getVirtualFunctionEntryLabel(_function, getSuperContract(_base)); -} - -FunctionDefinition const* CompilerContext::getNextConstructor(ContractDefinition const& _contract) const -{ - vector::const_iterator it = getSuperContract(_contract); - for (; it != m_inheritanceHierarchy.end(); ++it) - if ((*it)->getConstructor()) - return (*it)->getConstructor(); - - return nullptr; -} - -set CompilerContext::getFunctionsWithoutCode() -{ - set functions; - for (auto const& it: m_functionEntryLabels) - if (m_functionsWithCode.count(it.first) == 0) - functions.insert(it.first); - return functions; -} - -ModifierDefinition const& CompilerContext::getFunctionModifier(string const& _name) const -{ - solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); - for (ContractDefinition const* contract: m_inheritanceHierarchy) - for (ASTPointer const& modifier: contract->getFunctionModifiers()) - if (modifier->getName() == _name) - return *modifier.get(); - BOOST_THROW_EXCEPTION(InternalCompilerError() - << errinfo_comment("Function modifier " + _name + " not found.")); -} - -unsigned CompilerContext::getBaseStackOffsetOfVariable(Declaration const& _declaration) const -{ - auto res = m_localVariables.find(&_declaration); - solAssert(res != m_localVariables.end(), "Variable not found on stack."); - return res->second; -} - -unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const -{ - return m_asm.deposit() - _baseOffset - 1; -} - -unsigned CompilerContext::currentToBaseStackOffset(unsigned _offset) const -{ - return m_asm.deposit() - _offset - 1; -} - -pair CompilerContext::getStorageLocationOfVariable(const Declaration& _declaration) const -{ - auto it = m_stateVariables.find(&_declaration); - solAssert(it != m_stateVariables.end(), "Variable not found in storage."); - return it->second; -} - -CompilerContext& CompilerContext::appendJump(eth::AssemblyItem::JumpType _jumpType) -{ - eth::AssemblyItem item(eth::Instruction::JUMP); - item.setJumpType(_jumpType); - return *this << item; -} - -void CompilerContext::resetVisitedNodes(ASTNode const* _node) -{ - stack newStack; - newStack.push(_node); - std::swap(m_visitedNodes, newStack); - updateSourceLocation(); -} - -eth::AssemblyItem CompilerContext::getVirtualFunctionEntryLabel( - FunctionDefinition const& _function, - vector::const_iterator _searchStart -) -{ - string name = _function.getName(); - FunctionType functionType(_function); - auto it = _searchStart; - for (; it != m_inheritanceHierarchy.end(); ++it) - for (ASTPointer const& function: (*it)->getDefinedFunctions()) - if ( - function->getName() == name && - !function->isConstructor() && - FunctionType(*function).hasEqualArgumentTypes(functionType) - ) - return getFunctionEntryLabel(*function); - solAssert(false, "Super function " + name + " not found."); - return m_asm.newTag(); // not reached -} - -vector::const_iterator CompilerContext::getSuperContract(ContractDefinition const& _contract) const -{ - solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); - auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract); - solAssert(it != m_inheritanceHierarchy.end(), "Base not found in inheritance hierarchy."); - return ++it; -} - -void CompilerContext::updateSourceLocation() -{ - m_asm.setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->getLocation()); -} - -} -} diff --git a/libsolidity/CompilerContext.h b/libsolidity/CompilerContext.h deleted file mode 100644 index 3f97d900b..000000000 --- a/libsolidity/CompilerContext.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Utilities for the solidity compiler. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dev { -namespace solidity { - - -/** - * Context to be shared by all units that compile the same contract. - * It stores the generated bytecode and the position of identifiers in memory and on the stack. - */ -class CompilerContext -{ -public: - void addMagicGlobal(MagicVariableDeclaration const& _declaration); - void addStateVariable(VariableDeclaration const& _declaration, u256 const& _storageOffset, unsigned _byteOffset); - void addVariable(VariableDeclaration const& _declaration, unsigned _offsetToCurrent = 0); - void removeVariable(VariableDeclaration const& _declaration); - - void setCompiledContracts(std::map const& _contracts) { m_compiledContracts = _contracts; } - bytes const& getCompiledContract(ContractDefinition const& _contract) const; - - void setStackOffset(int _offset) { m_asm.setDeposit(_offset); } - void adjustStackOffset(int _adjustment) { m_asm.adjustDeposit(_adjustment); } - unsigned getStackHeight() const { solAssert(m_asm.deposit() >= 0, ""); return unsigned(m_asm.deposit()); } - - bool isMagicGlobal(Declaration const* _declaration) const { return m_magicGlobals.count(_declaration) != 0; } - bool isLocalVariable(Declaration const* _declaration) const; - bool isStateVariable(Declaration const* _declaration) const { return m_stateVariables.count(_declaration) != 0; } - - /// @returns the entry label of the given function and creates it if it does not exist yet. - eth::AssemblyItem getFunctionEntryLabel(Declaration const& _declaration); - /// @returns the entry label of the given function. Might return an AssemblyItem of type - /// UndefinedItem if it does not exist yet. - eth::AssemblyItem getFunctionEntryLabelIfExists(Declaration const& _declaration) const; - void setInheritanceHierarchy(std::vector const& _hierarchy) { m_inheritanceHierarchy = _hierarchy; } - /// @returns the entry label of the given function and takes overrides into account. - eth::AssemblyItem getVirtualFunctionEntryLabel(FunctionDefinition const& _function); - /// @returns the entry label of a function that overrides the given declaration from the most derived class just - /// above _base in the current inheritance hierarchy. - eth::AssemblyItem getSuperFunctionEntryLabel(FunctionDefinition const& _function, ContractDefinition const& _base); - FunctionDefinition const* getNextConstructor(ContractDefinition const& _contract) const; - - /// @returns the set of functions for which we still need to generate code - std::set getFunctionsWithoutCode(); - /// Resets function specific members, inserts the function entry label and marks the function - /// as "having code". - void startFunction(Declaration const& _function); - - ModifierDefinition const& getFunctionModifier(std::string const& _name) const; - /// Returns the distance of the given local variable from the bottom of the stack (of the current function). - unsigned getBaseStackOffsetOfVariable(Declaration const& _declaration) const; - /// If supplied by a value returned by @ref getBaseStackOffsetOfVariable(variable), returns - /// the distance of that variable from the current top of the stack. - unsigned baseToCurrentStackOffset(unsigned _baseOffset) const; - /// Converts an offset relative to the current stack height to a value that can be used later - /// with baseToCurrentStackOffset to point to the same stack element. - unsigned currentToBaseStackOffset(unsigned _offset) const; - /// @returns pair of slot and byte offset of the value inside this slot. - std::pair getStorageLocationOfVariable(Declaration const& _declaration) const; - - /// Appends a JUMPI instruction to a new tag and @returns the tag - eth::AssemblyItem appendConditionalJump() { return m_asm.appendJumpI().tag(); } - /// Appends a JUMPI instruction to @a _tag - CompilerContext& appendConditionalJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJumpI(_tag); return *this; } - /// Appends a JUMP to a new tag and @returns the tag - eth::AssemblyItem appendJumpToNew() { return m_asm.appendJump().tag(); } - /// Appends a JUMP to a tag already on the stack - CompilerContext& appendJump(eth::AssemblyItem::JumpType _jumpType = eth::AssemblyItem::JumpType::Ordinary); - /// Returns an "ErrorTag" - eth::AssemblyItem errorTag() { return m_asm.errorTag(); } - /// Appends a JUMP to a specific tag - CompilerContext& appendJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJump(_tag); return *this; } - /// Appends pushing of a new tag and @returns the new tag. - eth::AssemblyItem pushNewTag() { return m_asm.append(m_asm.newPushTag()).tag(); } - /// @returns a new tag without pushing any opcodes or data - eth::AssemblyItem newTag() { return m_asm.newTag(); } - /// Adds a subroutine to the code (in the data section) and pushes its size (via a tag) - /// on the stack. @returns the assembly item corresponding to the pushed subroutine, i.e. its offset. - eth::AssemblyItem addSubroutine(eth::Assembly const& _assembly) { return m_asm.appendSubSize(_assembly); } - /// Pushes the size of the final program - void appendProgramSize() { return m_asm.appendProgramSize(); } - /// Adds data to the data section, pushes a reference to the stack - eth::AssemblyItem appendData(bytes const& _data) { return m_asm.append(_data); } - /// Resets the stack of visited nodes with a new stack having only @c _node - void resetVisitedNodes(ASTNode const* _node); - /// Pops the stack of visited nodes - void popVisitedNodes() { m_visitedNodes.pop(); updateSourceLocation(); } - /// Pushes an ASTNode to the stack of visited nodes - void pushVisitedNodes(ASTNode const* _node) { m_visitedNodes.push(_node); updateSourceLocation(); } - - /// Append elements to the current instruction list and adjust @a m_stackOffset. - CompilerContext& operator<<(eth::AssemblyItem const& _item) { m_asm.append(_item); return *this; } - CompilerContext& operator<<(eth::Instruction _instruction) { m_asm.append(_instruction); return *this; } - CompilerContext& operator<<(u256 const& _value) { m_asm.append(_value); return *this; } - CompilerContext& operator<<(bytes const& _data) { m_asm.append(_data); return *this; } - - void optimise(unsigned _runs = 200) { m_asm.optimise(true, true, _runs); } - - eth::Assembly const& getAssembly() const { return m_asm; } - /// @arg _sourceCodes is the map of input files to source code strings - /// @arg _inJsonFormat shows whether the out should be in Json format - Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const - { - return m_asm.stream(_stream, "", _sourceCodes, _inJsonFormat); - } - - bytes getAssembledBytecode() { return m_asm.assemble(); } - bytes getAssembledRuntimeBytecode(size_t _subIndex) { m_asm.assemble(); return m_asm.data(u256(_subIndex)); } - - /** - * Helper class to pop the visited nodes stack when a scope closes - */ - class LocationSetter: public ScopeGuard - { - public: - LocationSetter(CompilerContext& _compilerContext, ASTNode const& _node): - ScopeGuard([&]{ _compilerContext.popVisitedNodes(); }) { _compilerContext.pushVisitedNodes(&_node); } - }; - -private: - /// @returns the entry label of the given function - searches the inheritance hierarchy - /// startig from the given point towards the base. - eth::AssemblyItem getVirtualFunctionEntryLabel( - FunctionDefinition const& _function, - std::vector::const_iterator _searchStart - ); - /// @returns an iterator to the contract directly above the given contract. - std::vector::const_iterator getSuperContract(const ContractDefinition &_contract) const; - /// Updates source location set in the assembly. - void updateSourceLocation(); - - eth::Assembly m_asm; - /// Magic global variables like msg, tx or this, distinguished by type. - std::set m_magicGlobals; - /// Other already compiled contracts to be used in contract creation calls. - std::map m_compiledContracts; - /// Storage offsets of state variables - std::map> m_stateVariables; - /// Offsets of local variables on the stack (relative to stack base). - std::map m_localVariables; - /// Labels pointing to the entry points of functions. - std::map m_functionEntryLabels; - /// Set of functions for which we did not yet generate code. - std::set m_functionsWithCode; - /// List of current inheritance hierarchy from derived to base. - std::vector m_inheritanceHierarchy; - /// Stack of current visited AST nodes, used for location attachment - std::stack m_visitedNodes; -}; - -} -} diff --git a/libsolidity/CompilerStack.cpp b/libsolidity/CompilerStack.cpp deleted file mode 100644 index a85738ebd..000000000 --- a/libsolidity/CompilerStack.cpp +++ /dev/null @@ -1,391 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @author Gav Wood - * @date 2014 - * Full-stack compiler that converts a source code string to bytecode. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -const map StandardSources = map{ - {"coin", R"(import "CoinReg";import "Config";import "configUser";contract coin is configUser{function coin(bytes3 name, uint denom) {CoinReg(Config(configAddr()).lookup(3)).register(name, denom);}})"}, - {"Coin", R"(contract Coin{function isApprovedFor(address _target,address _proxy)constant returns(bool _r){}function isApproved(address _proxy)constant returns(bool _r){}function sendCoinFrom(address _from,uint256 _val,address _to){}function coinBalanceOf(address _a)constant returns(uint256 _r){}function sendCoin(uint256 _val,address _to){}function coinBalance()constant returns(uint256 _r){}function approve(address _a){}})"}, - {"CoinReg", R"(contract CoinReg{function count()constant returns(uint256 r){}function info(uint256 i)constant returns(address addr,bytes3 name,uint256 denom){}function register(bytes3 name,uint256 denom){}function unregister(){}})"}, - {"configUser", R"(contract configUser{function configAddr()constant returns(address a){ return 0xc6d9d2cd449a754c494264e1809c50e34d64562b;}})"}, - {"Config", R"(contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}})"}, - {"mortal", R"(import "owned";contract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }})"}, - {"named", R"(import "Config";import "NameReg";import "configUser";contract named is configUser {function named(bytes32 name) {NameReg(Config(configAddr()).lookup(1)).register(name);}})"}, - {"NameReg", R"(contract NameReg{function register(bytes32 name){}function addressOf(bytes32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(bytes32 name){}})"}, - {"owned", R"(contract owned{function owned(){owner = msg.sender;}modifier onlyowner(){if(msg.sender==owner)_}address owner;})"}, - {"service", R"(import "Config";import "configUser";contract service is configUser{function service(uint _n){Config(configAddr()).register(_n, this);}})"}, - {"std", R"(import "owned";import "mortal";import "Config";import "configUser";import "NameReg";import "named";)"} -}; - -CompilerStack::CompilerStack(bool _addStandardSources): - m_parseSuccessful(false) -{ - if (_addStandardSources) - addSources(StandardSources, true); // add them as libraries -} - -void CompilerStack::reset(bool _keepSources, bool _addStandardSources) -{ - m_parseSuccessful = false; - if (_keepSources) - for (auto sourcePair: m_sources) - sourcePair.second.reset(); - else - { - m_sources.clear(); - if (_addStandardSources) - addSources(StandardSources, true); - } - m_globalContext.reset(); - m_sourceOrder.clear(); - m_contracts.clear(); -} - -bool CompilerStack::addSource(string const& _name, string const& _content, bool _isLibrary) -{ - bool existed = m_sources.count(_name) != 0; - reset(true); - m_sources[_name].scanner = make_shared(CharStream(_content), _name); - m_sources[_name].isLibrary = _isLibrary; - return existed; -} - -void CompilerStack::setSource(string const& _sourceCode) -{ - reset(); - addSource("", _sourceCode); -} - -void CompilerStack::parse() -{ - for (auto& sourcePair: m_sources) - { - sourcePair.second.scanner->reset(); - sourcePair.second.ast = Parser().parse(sourcePair.second.scanner); - } - resolveImports(); - - m_globalContext = make_shared(); - NameAndTypeResolver resolver(m_globalContext->getDeclarations()); - for (Source const* source: m_sourceOrder) - resolver.registerDeclarations(*source->ast); - for (Source const* source: m_sourceOrder) - for (ASTPointer const& node: source->ast->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - m_globalContext->setCurrentContract(*contract); - resolver.updateDeclaration(*m_globalContext->getCurrentThis()); - resolver.updateDeclaration(*m_globalContext->getCurrentSuper()); - resolver.resolveNamesAndTypes(*contract); - m_contracts[contract->getName()].contract = contract; - } - InterfaceHandler interfaceHandler; - for (Source const* source: m_sourceOrder) - for (ASTPointer const& node: source->ast->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - m_globalContext->setCurrentContract(*contract); - resolver.updateDeclaration(*m_globalContext->getCurrentThis()); - resolver.checkTypeRequirements(*contract); - contract->setDevDocumentation(interfaceHandler.devDocumentation(*contract)); - contract->setUserDocumentation(interfaceHandler.userDocumentation(*contract)); - m_contracts[contract->getName()].contract = contract; - } - m_parseSuccessful = true; -} - -void CompilerStack::parse(string const& _sourceCode) -{ - setSource(_sourceCode); - parse(); -} - -vector CompilerStack::getContractNames() const -{ - if (!m_parseSuccessful) - BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); - vector contractNames; - for (auto const& contract: m_contracts) - contractNames.push_back(contract.first); - return contractNames; -} - - -void CompilerStack::compile(bool _optimize, unsigned _runs) -{ - if (!m_parseSuccessful) - parse(); - - map contractBytecode; - for (Source const* source: m_sourceOrder) - for (ASTPointer const& node: source->ast->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - if (!contract->isFullyImplemented()) - continue; - shared_ptr compiler = make_shared(_optimize, _runs); - compiler->compileContract(*contract, contractBytecode); - Contract& compiledContract = m_contracts.at(contract->getName()); - compiledContract.bytecode = compiler->getAssembledBytecode(); - compiledContract.runtimeBytecode = compiler->getRuntimeBytecode(); - compiledContract.compiler = move(compiler); - compiler = make_shared(_optimize, _runs); - compiler->compileContract(*contract, contractBytecode); - contractBytecode[compiledContract.contract] = &compiledContract.bytecode; - - Compiler cloneCompiler(_optimize, _runs); - cloneCompiler.compileClone(*contract, contractBytecode); - compiledContract.cloneBytecode = cloneCompiler.getAssembledBytecode(); - } -} - -bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize) -{ - parse(_sourceCode); - compile(_optimize); - return getBytecode(); -} - -eth::AssemblyItems const* CompilerStack::getAssemblyItems(string const& _contractName) const -{ - Contract const& contract = getContract(_contractName); - return contract.compiler ? &getContract(_contractName).compiler->getAssemblyItems() : nullptr; -} - -eth::AssemblyItems const* CompilerStack::getRuntimeAssemblyItems(string const& _contractName) const -{ - Contract const& contract = getContract(_contractName); - return contract.compiler ? &getContract(_contractName).compiler->getRuntimeAssemblyItems() : nullptr; -} - -bytes const& CompilerStack::getBytecode(string const& _contractName) const -{ - return getContract(_contractName).bytecode; -} - -bytes const& CompilerStack::getRuntimeBytecode(string const& _contractName) const -{ - return getContract(_contractName).runtimeBytecode; -} - -bytes const& CompilerStack::getCloneBytecode(string const& _contractName) const -{ - return getContract(_contractName).cloneBytecode; -} - -dev::h256 CompilerStack::getContractCodeHash(string const& _contractName) const -{ - return dev::sha3(getRuntimeBytecode(_contractName)); -} - -Json::Value CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName, StringMap _sourceCodes, bool _inJsonFormat) const -{ - Contract const& contract = getContract(_contractName); - if (contract.compiler) - return contract.compiler->streamAssembly(_outStream, _sourceCodes, _inJsonFormat); - else - { - _outStream << "Contract not fully implemented" << endl; - return Json::Value(); - } -} - -string const& CompilerStack::getInterface(string const& _contractName) const -{ - return getMetadata(_contractName, DocumentationType::ABIInterface); -} - -string const& CompilerStack::getSolidityInterface(string const& _contractName) const -{ - return getMetadata(_contractName, DocumentationType::ABISolidityInterface); -} - -string const& CompilerStack::getMetadata(string const& _contractName, DocumentationType _type) const -{ - if (!m_parseSuccessful) - BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); - - Contract const& contract = getContract(_contractName); - - std::unique_ptr* doc; - - // checks wheather we already have the documentation - switch (_type) - { - case DocumentationType::NatspecUser: - doc = &contract.userDocumentation; - break; - case DocumentationType::NatspecDev: - doc = &contract.devDocumentation; - break; - case DocumentationType::ABIInterface: - doc = &contract.interface; - break; - case DocumentationType::ABISolidityInterface: - doc = &contract.solidityInterface; - break; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type.")); - } - - // caches the result - if (!*doc) - doc->reset(new string(contract.interfaceHandler->getDocumentation(*contract.contract, _type))); - - return *(*doc); -} - -Scanner const& CompilerStack::getScanner(string const& _sourceName) const -{ - return *getSource(_sourceName).scanner; -} - -SourceUnit const& CompilerStack::getAST(string const& _sourceName) const -{ - return *getSource(_sourceName).ast; -} - -ContractDefinition const& CompilerStack::getContractDefinition(string const& _contractName) const -{ - return *getContract(_contractName).contract; -} - -size_t CompilerStack::getFunctionEntryPoint( - std::string const& _contractName, - FunctionDefinition const& _function -) const -{ - shared_ptr const& compiler = getContract(_contractName).compiler; - if (!compiler) - return 0; - eth::AssemblyItem tag = compiler->getFunctionEntryLabel(_function); - if (tag.type() == eth::UndefinedItem) - return 0; - eth::AssemblyItems const& items = compiler->getRuntimeAssemblyItems(); - for (size_t i = 0; i < items.size(); ++i) - if (items.at(i).type() == eth::Tag && items.at(i).data() == tag.data()) - return i; - return 0; -} - -bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize) -{ - CompilerStack stack; - return stack.compile(_sourceCode, _optimize); -} - -tuple CompilerStack::positionFromSourceLocation(SourceLocation const& _sourceLocation) const -{ - int startLine; - int startColumn; - int endLine; - int endColumn; - tie(startLine, startColumn) = getScanner(*_sourceLocation.sourceName).translatePositionToLineColumn(_sourceLocation.start); - tie(endLine, endColumn) = getScanner(*_sourceLocation.sourceName).translatePositionToLineColumn(_sourceLocation.end); - - return make_tuple(++startLine, ++startColumn, ++endLine, ++endColumn); -} - -void CompilerStack::resolveImports() -{ - // topological sorting (depth first search) of the import graph, cutting potential cycles - vector sourceOrder; - set sourcesSeen; - - function toposort = [&](Source const* _source) - { - if (sourcesSeen.count(_source)) - return; - sourcesSeen.insert(_source); - for (ASTPointer const& node: _source->ast->getNodes()) - if (ImportDirective const* import = dynamic_cast(node.get())) - { - string const& id = import->getIdentifier(); - if (!m_sources.count(id)) - BOOST_THROW_EXCEPTION(ParserError() - << errinfo_sourceLocation(import->getLocation()) - << errinfo_comment("Source not found.")); - toposort(&m_sources[id]); - } - sourceOrder.push_back(_source); - }; - - for (auto const& sourcePair: m_sources) - if (!sourcePair.second.isLibrary) - toposort(&sourcePair.second); - - swap(m_sourceOrder, sourceOrder); -} - -std::string CompilerStack::defaultContractName() const -{ - return getContract("").contract->getName(); -} - -CompilerStack::Contract const& CompilerStack::getContract(string const& _contractName) const -{ - if (m_contracts.empty()) - BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found.")); - string contractName = _contractName; - if (_contractName.empty()) - // try to find some user-supplied contract - for (auto const& it: m_sources) - if (!StandardSources.count(it.first)) - for (ASTPointer const& node: it.second.ast->getNodes()) - if (auto contract = dynamic_cast(node.get())) - contractName = contract->getName(); - auto it = m_contracts.find(contractName); - if (it == m_contracts.end()) - BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found.")); - return it->second; -} - -CompilerStack::Source const& CompilerStack::getSource(string const& _sourceName) const -{ - auto it = m_sources.find(_sourceName); - if (it == m_sources.end()) - BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Given source file not found.")); - return it->second; -} - -CompilerStack::Contract::Contract(): interfaceHandler(make_shared()) {} - -} -} diff --git a/libsolidity/CompilerStack.h b/libsolidity/CompilerStack.h deleted file mode 100644 index 735c4d156..000000000 --- a/libsolidity/CompilerStack.h +++ /dev/null @@ -1,198 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @author Gav Wood - * @date 2014 - * Full-stack compiler that converts a source code string to bytecode. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dev -{ - -namespace eth -{ -class AssemblyItem; -using AssemblyItems = std::vector; -} - -namespace solidity -{ - -// forward declarations -class Scanner; -class ContractDefinition; -class FunctionDefinition; -class SourceUnit; -class Compiler; -class GlobalContext; -class InterfaceHandler; - -enum class DocumentationType: uint8_t -{ - NatspecUser = 1, - NatspecDev, - ABIInterface, - ABISolidityInterface -}; - -/** - * Easy to use and self-contained Solidity compiler with as few header dependencies as possible. - * It holds state and can be used to either step through the compilation stages (and abort e.g. - * before compilation to bytecode) or run the whole compilation in one call. - */ -class CompilerStack: boost::noncopyable -{ -public: - /// Creates a new compiler stack. Adds standard sources if @a _addStandardSources. - explicit CompilerStack(bool _addStandardSources = true); - - /// Resets the compiler to a state where the sources are not parsed or even removed. - void reset(bool _keepSources = false, bool _addStandardSources = true); - - /// Adds a source object (e.g. file) to the parser. After this, parse has to be called again. - /// @returns true if a source object by the name already existed and was replaced. - void addSources(StringMap const& _nameContents, bool _isLibrary = false) { for (auto const& i: _nameContents) addSource(i.first, i.second, _isLibrary); } - bool addSource(std::string const& _name, std::string const& _content, bool _isLibrary = false); - void setSource(std::string const& _sourceCode); - /// Parses all source units that were added - void parse(); - /// Sets the given source code as the only source unit apart from standard sources and parses it. - void parse(std::string const& _sourceCode); - /// Returns a list of the contract names in the sources. - std::vector getContractNames() const; - std::string defaultContractName() const; - - /// Compiles the source units that were previously added and parsed. - void compile(bool _optimize = false, unsigned _runs = 200); - /// Parses and compiles the given source code. - /// @returns the compiled bytecode - bytes const& compile(std::string const& _sourceCode, bool _optimize = false); - - /// @returns the assembled bytecode for a contract. - bytes const& getBytecode(std::string const& _contractName = "") const; - /// @returns the runtime bytecode for the contract, i.e. the code that is returned by the constructor. - bytes const& getRuntimeBytecode(std::string const& _contractName = "") const; - /// @returns the bytecode of a contract that uses an already deployed contract via CALLCODE. - /// The returned bytes will contain a sequence of 20 bytes of the format "XXX...XXX" which have to - /// substituted by the actual address. Note that this sequence starts end ends in three X - /// characters but can contain anything in between. - bytes const& getCloneBytecode(std::string const& _contractName = "") const; - /// @returns normal contract assembly items - eth::AssemblyItems const* getAssemblyItems(std::string const& _contractName = "") const; - /// @returns runtime contract assembly items - eth::AssemblyItems const* getRuntimeAssemblyItems(std::string const& _contractName = "") const; - /// @returns hash of the runtime bytecode for the contract, i.e. the code that is returned by the constructor. - dev::h256 getContractCodeHash(std::string const& _contractName = "") const; - - /// Streams a verbose version of the assembly to @a _outStream. - /// @arg _sourceCodes is the map of input files to source code strings - /// @arg _inJsonFromat shows whether the out should be in Json format - /// Prerequisite: Successful compilation. - Json::Value streamAssembly(std::ostream& _outStream, std::string const& _contractName = "", StringMap _sourceCodes = StringMap(), bool _inJsonFormat = false) const; - - /// Returns a string representing the contract interface in JSON. - /// Prerequisite: Successful call to parse or compile. - std::string const& getInterface(std::string const& _contractName = "") const; - /// Returns a string representing the contract interface in Solidity. - /// Prerequisite: Successful call to parse or compile. - std::string const& getSolidityInterface(std::string const& _contractName = "") const; - /// Returns a string representing the contract's documentation in JSON. - /// Prerequisite: Successful call to parse or compile. - /// @param type The type of the documentation to get. - /// Can be one of 4 types defined at @c DocumentationType - std::string const& getMetadata(std::string const& _contractName, DocumentationType _type) const; - - /// @returns the previously used scanner, useful for counting lines during error reporting. - Scanner const& getScanner(std::string const& _sourceName = "") const; - /// @returns the parsed source unit with the supplied name. - SourceUnit const& getAST(std::string const& _sourceName = "") const; - /// @returns the parsed contract with the supplied name. Throws an exception if the contract - /// does not exist. - ContractDefinition const& getContractDefinition(std::string const& _contractName) const; - - /// @returns the offset of the entry point of the given function into the list of assembly items - /// or zero if it is not found or does not exist. - size_t getFunctionEntryPoint( - std::string const& _contractName, - FunctionDefinition const& _function - ) const; - - /// Compile the given @a _sourceCode to bytecode. If a scanner is provided, it is used for - /// scanning the source code - this is useful for printing exception information. - static bytes staticCompile(std::string const& _sourceCode, bool _optimize = false); - - /// Helper function for logs printing. Do only use in error cases, it's quite expensive. - /// line and columns are numbered starting from 1 with following order: - /// start line, start column, end line, end column - std::tuple positionFromSourceLocation(SourceLocation const& _sourceLocation) const; - -private: - /** - * Information pertaining to one source unit, filled gradually during parsing and compilation. - */ - struct Source - { - std::shared_ptr scanner; - std::shared_ptr ast; - std::string interface; - bool isLibrary = false; - void reset() { scanner.reset(); ast.reset(); interface.clear(); } - }; - - struct Contract - { - ContractDefinition const* contract = nullptr; - std::shared_ptr compiler; - bytes bytecode; - bytes runtimeBytecode; - bytes cloneBytecode; - std::shared_ptr interfaceHandler; - mutable std::unique_ptr interface; - mutable std::unique_ptr solidityInterface; - mutable std::unique_ptr userDocumentation; - mutable std::unique_ptr devDocumentation; - - Contract(); - }; - - void resolveImports(); - - Contract const& getContract(std::string const& _contractName = "") const; - Source const& getSource(std::string const& _sourceName = "") const; - - bool m_parseSuccessful; - std::map m_sources; - std::shared_ptr m_globalContext; - std::vector m_sourceOrder; - std::map m_contracts; -}; - -} -} diff --git a/libsolidity/CompilerUtils.cpp b/libsolidity/CompilerUtils.cpp deleted file mode 100644 index 492475817..000000000 --- a/libsolidity/CompilerUtils.cpp +++ /dev/null @@ -1,734 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Routines used by both the compiler and the expression compiler. - */ - -#include -#include -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -const unsigned CompilerUtils::dataStartOffset = 4; -const size_t CompilerUtils::freeMemoryPointer = 64; -const unsigned CompilerUtils::identityContractAddress = 4; - -void CompilerUtils::initialiseFreeMemoryPointer() -{ - m_context << u256(freeMemoryPointer + 32); - storeFreeMemoryPointer(); -} - -void CompilerUtils::fetchFreeMemoryPointer() -{ - m_context << u256(freeMemoryPointer) << eth::Instruction::MLOAD; -} - -void CompilerUtils::storeFreeMemoryPointer() -{ - m_context << u256(freeMemoryPointer) << eth::Instruction::MSTORE; -} - -void CompilerUtils::allocateMemory() -{ - fetchFreeMemoryPointer(); - m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2 << eth::Instruction::ADD; - storeFreeMemoryPointer(); -} - -void CompilerUtils::toSizeAfterFreeMemoryPointer() -{ - fetchFreeMemoryPointer(); - m_context << eth::Instruction::DUP1 << eth::Instruction::SWAP2 << eth::Instruction::SUB; - m_context << eth::Instruction::SWAP1; -} - -unsigned CompilerUtils::loadFromMemory( - unsigned _offset, - Type const& _type, - bool _fromCalldata, - bool _padToWordBoundaries -) -{ - solAssert(_type.getCategory() != Type::Category::Array, "Unable to statically load dynamic type."); - m_context << u256(_offset); - return loadFromMemoryHelper(_type, _fromCalldata, _padToWordBoundaries); -} - -void CompilerUtils::loadFromMemoryDynamic( - Type const& _type, - bool _fromCalldata, - bool _padToWordBoundaries, - bool _keepUpdatedMemoryOffset -) -{ - solAssert(_type.getCategory() != Type::Category::Array, "Arrays not yet implemented."); - if (_keepUpdatedMemoryOffset) - m_context << eth::Instruction::DUP1; - unsigned numBytes = loadFromMemoryHelper(_type, _fromCalldata, _padToWordBoundaries); - if (_keepUpdatedMemoryOffset) - { - // update memory counter - moveToStackTop(_type.getSizeOnStack()); - m_context << u256(numBytes) << eth::Instruction::ADD; - } -} - -void CompilerUtils::storeInMemory(unsigned _offset) -{ - unsigned numBytes = prepareMemoryStore(IntegerType(256), true); - if (numBytes > 0) - m_context << u256(_offset) << eth::Instruction::MSTORE; -} - -void CompilerUtils::storeInMemoryDynamic(Type const& _type, bool _padToWordBoundaries) -{ - if (auto ref = dynamic_cast(&_type)) - { - solAssert(ref->location() == DataLocation::Memory, ""); - storeInMemoryDynamic(IntegerType(256), _padToWordBoundaries); - } - else if (auto str = dynamic_cast(&_type)) - { - m_context << eth::Instruction::DUP1; - storeStringData(bytesConstRef(str->value())); - if (_padToWordBoundaries) - m_context << u256(((str->value().size() + 31) / 32) * 32); - else - m_context << u256(str->value().size()); - m_context << eth::Instruction::ADD; - } - else - { - unsigned numBytes = prepareMemoryStore(_type, _padToWordBoundaries); - if (numBytes > 0) - { - solAssert( - _type.getSizeOnStack() == 1, - "Memory store of types with stack size != 1 not implemented." - ); - m_context << eth::Instruction::DUP2 << eth::Instruction::MSTORE; - m_context << u256(numBytes) << eth::Instruction::ADD; - } - } -} - -void CompilerUtils::encodeToMemory( - TypePointers const& _givenTypes, - TypePointers const& _targetTypes, - bool _padToWordBoundaries, - bool _copyDynamicDataInPlace -) -{ - // stack: ... - TypePointers targetTypes = _targetTypes.empty() ? _givenTypes : _targetTypes; - solAssert(targetTypes.size() == _givenTypes.size(), ""); - for (TypePointer& t: targetTypes) - t = t->mobileType()->externalType(); - - // Stack during operation: - // ... ... - // The values dyn_head_i are added during the first loop and they point to the head part - // of the ith dynamic parameter, which is filled once the dynamic parts are processed. - - // store memory start pointer - m_context << eth::Instruction::DUP1; - - unsigned argSize = CompilerUtils::getSizeOnStack(_givenTypes); - unsigned stackPos = 0; // advances through the argument values - unsigned dynPointers = 0; // number of dynamic head pointers on the stack - for (size_t i = 0; i < _givenTypes.size(); ++i) - { - TypePointer targetType = targetTypes[i]; - solAssert(!!targetType, "Externalable type expected."); - if (targetType->isDynamicallySized() && !_copyDynamicDataInPlace) - { - // leave end_of_mem as dyn head pointer - m_context << eth::Instruction::DUP1 << u256(32) << eth::Instruction::ADD; - dynPointers++; - } - else - { - copyToStackTop(argSize - stackPos + dynPointers + 2, _givenTypes[i]->getSizeOnStack()); - solAssert(!!targetType, "Externalable type expected."); - TypePointer type = targetType; - if ( - _givenTypes[i]->dataStoredIn(DataLocation::Storage) || - _givenTypes[i]->dataStoredIn(DataLocation::CallData) || - _givenTypes[i]->getCategory() == Type::Category::StringLiteral - ) - type = _givenTypes[i]; // delay conversion - else - convertType(*_givenTypes[i], *targetType, true); - if (auto arrayType = dynamic_cast(type.get())) - ArrayUtils(m_context).copyArrayToMemory(*arrayType, _padToWordBoundaries); - else - storeInMemoryDynamic(*type, _padToWordBoundaries); - } - stackPos += _givenTypes[i]->getSizeOnStack(); - } - - // now copy the dynamic part - // Stack: ... ... - stackPos = 0; - unsigned thisDynPointer = 0; - for (size_t i = 0; i < _givenTypes.size(); ++i) - { - TypePointer targetType = targetTypes[i]; - solAssert(!!targetType, "Externalable type expected."); - if (targetType->isDynamicallySized() && !_copyDynamicDataInPlace) - { - // copy tail pointer (=mem_end - mem_start) to memory - m_context << eth::dupInstruction(2 + dynPointers) << eth::Instruction::DUP2; - m_context << eth::Instruction::SUB; - m_context << eth::dupInstruction(2 + dynPointers - thisDynPointer); - m_context << eth::Instruction::MSTORE; - // stack: ... - if (_givenTypes[i]->getCategory() == Type::Category::StringLiteral) - { - auto const& strType = dynamic_cast(*_givenTypes[i]); - m_context << u256(strType.value().size()); - storeInMemoryDynamic(IntegerType(256), true); - // stack: ... - storeInMemoryDynamic(strType, _padToWordBoundaries); - } - else - { - solAssert(_givenTypes[i]->getCategory() == Type::Category::Array, "Unknown dynamic type."); - auto const& arrayType = dynamic_cast(*_givenTypes[i]); - // now copy the array - copyToStackTop(argSize - stackPos + dynPointers + 2, arrayType.getSizeOnStack()); - // stack: ... - // copy length to memory - m_context << eth::dupInstruction(1 + arrayType.getSizeOnStack()); - if (arrayType.location() == DataLocation::CallData) - m_context << eth::Instruction::DUP2; // length is on stack - else if (arrayType.location() == DataLocation::Storage) - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; - else - { - solAssert(arrayType.location() == DataLocation::Memory, ""); - m_context << eth::Instruction::DUP2 << eth::Instruction::MLOAD; - } - // stack: ... - storeInMemoryDynamic(IntegerType(256), true); - // stack: ... - // copy the new memory pointer - m_context << eth::swapInstruction(arrayType.getSizeOnStack() + 1) << eth::Instruction::POP; - // stack: ... - // copy data part - ArrayUtils(m_context).copyArrayToMemory(arrayType, _padToWordBoundaries); - // stack: ... - } - - thisDynPointer++; - } - stackPos += _givenTypes[i]->getSizeOnStack(); - } - - // remove unneeded stack elements (and retain memory pointer) - m_context << eth::swapInstruction(argSize + dynPointers + 1); - popStackSlots(argSize + dynPointers + 1); -} - -void CompilerUtils::memoryCopy() -{ - // Stack here: size target source - // stack for call: outsize target size source value contract gas - //@TODO do not use ::CALL if less than 32 bytes? - m_context << eth::Instruction::DUP3 << eth::Instruction::SWAP1; - m_context << u256(0) << u256(identityContractAddress); - // compute gas costs - m_context << u256(32) << eth::Instruction::DUP5 << u256(31) << eth::Instruction::ADD; - m_context << eth::Instruction::DIV << u256(eth::c_identityWordGas) << eth::Instruction::MUL; - m_context << u256(eth::c_identityGas) << eth::Instruction::ADD; - m_context << eth::Instruction::CALL; - m_context << eth::Instruction::POP; // ignore return value -} - -void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetType, bool _cleanupNeeded) -{ - // For a type extension, we need to remove all higher-order bits that we might have ignored in - // previous operations. - // @todo: store in the AST whether the operand might have "dirty" higher order bits - - if (_typeOnStack == _targetType && !_cleanupNeeded) - return; - Type::Category stackTypeCategory = _typeOnStack.getCategory(); - Type::Category targetTypeCategory = _targetType.getCategory(); - - switch (stackTypeCategory) - { - case Type::Category::FixedBytes: - { - FixedBytesType const& typeOnStack = dynamic_cast(_typeOnStack); - if (targetTypeCategory == Type::Category::Integer) - { - // 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(_targetType); - m_context << (u256(1) << (256 - typeOnStack.numBytes() * 8)) << eth::Instruction::SWAP1 << eth::Instruction::DIV; - if (targetIntegerType.getNumBits() < typeOnStack.numBytes() * 8) - convertType(IntegerType(typeOnStack.numBytes() * 8), _targetType, _cleanupNeeded); - } - else - { - // clear lower-order bytes for conversion to shorter bytes - we always clean - solAssert(targetTypeCategory == Type::Category::FixedBytes, "Invalid type conversion requested."); - FixedBytesType const& targetType = dynamic_cast(_targetType); - if (targetType.numBytes() < typeOnStack.numBytes()) - { - if (targetType.numBytes() == 0) - m_context << eth::Instruction::DUP1 << eth::Instruction::XOR; - else - { - m_context << (u256(1) << (256 - targetType.numBytes() * 8)); - m_context << eth::Instruction::DUP1 << eth::Instruction::SWAP2; - m_context << eth::Instruction::DIV << eth::Instruction::MUL; - } - } - } - } - break; - case Type::Category::Enum: - solAssert(targetTypeCategory == Type::Category::Integer || targetTypeCategory == Type::Category::Enum, ""); - break; - case Type::Category::Integer: - case Type::Category::Contract: - case Type::Category::IntegerConstant: - if (targetTypeCategory == Type::Category::FixedBytes) - { - solAssert(stackTypeCategory == Type::Category::Integer || stackTypeCategory == Type::Category::IntegerConstant, - "Invalid conversion to FixedBytesType requested."); - // conversion from bytes to string. no need to clean the high bit - // only to shift left because of opposite alignment - FixedBytesType const& targetBytesType = dynamic_cast(_targetType); - if (auto typeOnStack = dynamic_cast(&_typeOnStack)) - if (targetBytesType.numBytes() * 8 > typeOnStack->getNumBits()) - cleanHigherOrderBits(*typeOnStack); - m_context << (u256(1) << (256 - targetBytesType.numBytes() * 8)) << eth::Instruction::MUL; - } - else if (targetTypeCategory == Type::Category::Enum) - // just clean - convertType(_typeOnStack, *_typeOnStack.mobileType(), true); - else - { - solAssert(targetTypeCategory == Type::Category::Integer || targetTypeCategory == Type::Category::Contract, ""); - IntegerType addressType(0, IntegerType::Modifier::Address); - IntegerType const& targetType = targetTypeCategory == Type::Category::Integer - ? dynamic_cast(_targetType) : addressType; - if (stackTypeCategory == Type::Category::IntegerConstant) - { - IntegerConstantType const& constType = dynamic_cast(_typeOnStack); - // We know that the stack is clean, we only have to clean for a narrowing conversion - // where cleanup is forced. - if (targetType.getNumBits() < constType.getIntegerType()->getNumBits() && _cleanupNeeded) - cleanHigherOrderBits(targetType); - } - else - { - IntegerType const& typeOnStack = stackTypeCategory == Type::Category::Integer - ? dynamic_cast(_typeOnStack) : addressType; - // Widening: clean up according to source type width - // Non-widening and force: clean up according to target type bits - if (targetType.getNumBits() > typeOnStack.getNumBits()) - cleanHigherOrderBits(typeOnStack); - else if (_cleanupNeeded) - cleanHigherOrderBits(targetType); - } - } - break; - case Type::Category::StringLiteral: - { - auto const& literalType = dynamic_cast(_typeOnStack); - string const& value = literalType.value(); - bytesConstRef data(value); - if (targetTypeCategory == Type::Category::FixedBytes) - { - solAssert(data.size() <= 32, ""); - m_context << h256::Arith(h256(data, h256::AlignLeft)); - } - else if (targetTypeCategory == Type::Category::Array) - { - auto const& arrayType = dynamic_cast(_targetType); - solAssert(arrayType.isByteArray(), ""); - u256 storageSize(32 + ((data.size() + 31) / 32) * 32); - m_context << storageSize; - allocateMemory(); - // stack: mempos - m_context << eth::Instruction::DUP1 << u256(data.size()); - storeInMemoryDynamic(IntegerType(256)); - // stack: mempos datapos - storeStringData(data); - break; - } - else - solAssert( - false, - "Invalid conversion from string literal to " + _targetType.toString(false) + " requested." - ); - break; - } - case Type::Category::Array: - { - solAssert(targetTypeCategory == stackTypeCategory, ""); - ArrayType const& typeOnStack = dynamic_cast(_typeOnStack); - ArrayType const& targetType = dynamic_cast(_targetType); - switch (targetType.location()) - { - case DataLocation::Storage: - // Other cases are done explicitly in LValue::storeValue, and only possible by assignment. - solAssert( - (targetType.isPointer() || (typeOnStack.isByteArray() && targetType.isByteArray())) && - typeOnStack.location() == DataLocation::Storage, - "Invalid conversion to storage type." - ); - break; - case DataLocation::Memory: - { - // Copy the array to a free position in memory, unless it is already in memory. - if (typeOnStack.location() != DataLocation::Memory) - { - // stack: (variably sized) - unsigned stackSize = typeOnStack.getSizeOnStack(); - ArrayUtils(m_context).retrieveLength(typeOnStack); - - // allocate memory - // stack: (variably sized) - m_context << eth::Instruction::DUP1; - ArrayUtils(m_context).convertLengthToSize(targetType, true); - // stack: (variably sized) - if (targetType.isDynamicallySized()) - m_context << u256(0x20) << eth::Instruction::ADD; - allocateMemory(); - // stack: (variably sized) - m_context << eth::Instruction::DUP1; - moveIntoStack(2 + stackSize); - if (targetType.isDynamicallySized()) - { - m_context << eth::Instruction::DUP2; - storeInMemoryDynamic(IntegerType(256)); - } - // stack: (variably sized) - if (targetType.getBaseType()->isValueType()) - { - solAssert(typeOnStack.getBaseType()->isValueType(), ""); - copyToStackTop(2 + stackSize, stackSize); - ArrayUtils(m_context).copyArrayToMemory(typeOnStack); - } - else - { - m_context << u256(0) << eth::Instruction::SWAP1; - // stack: (variably sized) - auto repeat = m_context.newTag(); - m_context << repeat; - m_context << eth::Instruction::DUP3 << eth::Instruction::DUP3; - m_context << eth::Instruction::LT << eth::Instruction::ISZERO; - auto loopEnd = m_context.appendConditionalJump(); - copyToStackTop(3 + stackSize, stackSize); - copyToStackTop(2 + stackSize, 1); - ArrayUtils(m_context).accessIndex(typeOnStack, false); - if (typeOnStack.location() == DataLocation::Storage) - StorageItem(m_context, *typeOnStack.getBaseType()).retrieveValue(SourceLocation(), true); - convertType(*typeOnStack.getBaseType(), *targetType.getBaseType(), _cleanupNeeded); - storeInMemoryDynamic(*targetType.getBaseType(), true); - m_context << eth::Instruction::SWAP1 << u256(1) << eth::Instruction::ADD; - m_context << eth::Instruction::SWAP1; - m_context.appendJumpTo(repeat); - m_context << loopEnd; - m_context << eth::Instruction::POP; - } - // stack: (variably sized) - popStackSlots(2 + stackSize); - // Stack: - } - break; - } - case DataLocation::CallData: - solAssert( - targetType.isByteArray() && - typeOnStack.isByteArray() && - typeOnStack.location() == DataLocation::CallData, - "Invalid conversion to calldata type."); - break; - default: - solAssert( - false, - "Invalid type conversion " + - _typeOnStack.toString(false) + - " to " + - _targetType.toString(false) + - " requested." - ); - } - break; - } - case Type::Category::Struct: - { - solAssert(targetTypeCategory == stackTypeCategory, ""); - auto& targetType = dynamic_cast(_targetType); - auto& typeOnStack = dynamic_cast(_typeOnStack); - solAssert( - targetType.location() != DataLocation::CallData && - typeOnStack.location() != DataLocation::CallData - , ""); - switch (targetType.location()) - { - case DataLocation::Storage: - // Other cases are done explicitly in LValue::storeValue, and only possible by assignment. - solAssert( - targetType.isPointer() && - typeOnStack.location() == DataLocation::Storage, - "Invalid conversion to storage type." - ); - break; - case DataLocation::Memory: - // Copy the array to a free position in memory, unless it is already in memory. - if (typeOnStack.location() != DataLocation::Memory) - { - solAssert(typeOnStack.location() == DataLocation::Storage, ""); - // stack: - m_context << typeOnStack.memorySize(); - allocateMemory(); - m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2; - // stack: - for (auto const& member: typeOnStack.getMembers()) - { - if (!member.type->canLiveOutsideStorage()) - continue; - pair const& offsets = typeOnStack.getStorageOffsetsOfMember(member.name); - m_context << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD; - m_context << u256(offsets.second); - StorageItem(m_context, *member.type).retrieveValue(SourceLocation(), true); - TypePointer targetMemberType = targetType.getMemberType(member.name); - solAssert(!!targetMemberType, "Member not found in target type."); - convertType(*member.type, *targetMemberType, true); - storeInMemoryDynamic(*targetMemberType, true); - } - m_context << eth::Instruction::POP << eth::Instruction::POP; - } - break; - case DataLocation::CallData: - solAssert(false, "Invalid type conversion target location CallData."); - break; - } - break; - } - default: - // All other types should not be convertible to non-equal types. - solAssert(_typeOnStack == _targetType, "Invalid type conversion requested."); - break; - } -} - -void CompilerUtils::pushZeroValue(const Type& _type) -{ - auto const* referenceType = dynamic_cast(&_type); - if (!referenceType || referenceType->location() == DataLocation::Storage) - { - for (size_t i = 0; i < _type.getSizeOnStack(); ++i) - m_context << u256(0); - return; - } - solAssert(referenceType->location() == DataLocation::Memory, ""); - - m_context << u256(max(32u, _type.getCalldataEncodedSize())); - allocateMemory(); - m_context << eth::Instruction::DUP1; - - if (auto structType = dynamic_cast(&_type)) - for (auto const& member: structType->getMembers()) - { - pushZeroValue(*member.type); - storeInMemoryDynamic(*member.type); - } - else if (auto arrayType = dynamic_cast(&_type)) - { - if (arrayType->isDynamicallySized()) - { - // zero length - m_context << u256(0); - storeInMemoryDynamic(IntegerType(256)); - } - else if (arrayType->getLength() > 0) - { - m_context << arrayType->getLength() << eth::Instruction::SWAP1; - // stack: items_to_do memory_pos - auto repeat = m_context.newTag(); - m_context << repeat; - pushZeroValue(*arrayType->getBaseType()); - storeInMemoryDynamic(*arrayType->getBaseType()); - m_context << eth::Instruction::SWAP1 << u256(1) << eth::Instruction::SWAP1; - m_context << eth::Instruction::SUB << eth::Instruction::SWAP1; - m_context << eth::Instruction::DUP2; - m_context.appendConditionalJumpTo(repeat); - m_context << eth::Instruction::SWAP1 << eth::Instruction::POP; - } - } - else - solAssert(false, "Requested initialisation for unknown type: " + _type.toString()); - - // remove the updated memory pointer - m_context << eth::Instruction::POP; -} - -void CompilerUtils::moveToStackVariable(VariableDeclaration const& _variable) -{ - unsigned const stackPosition = m_context.baseToCurrentStackOffset(m_context.getBaseStackOffsetOfVariable(_variable)); - unsigned const size = _variable.getType()->getSizeOnStack(); - solAssert(stackPosition >= size, "Variable size and position mismatch."); - // move variable starting from its top end in the stack - if (stackPosition - size + 1 > 16) - BOOST_THROW_EXCEPTION( - CompilerError() << - errinfo_sourceLocation(_variable.getLocation()) << - errinfo_comment("Stack too deep, try removing local variables.") - ); - for (unsigned i = 0; i < size; ++i) - m_context << eth::swapInstruction(stackPosition - size + 1) << eth::Instruction::POP; -} - -void CompilerUtils::copyToStackTop(unsigned _stackDepth, unsigned _itemSize) -{ - solAssert(_stackDepth <= 16, "Stack too deep, try removing local variables."); - for (unsigned i = 0; i < _itemSize; ++i) - m_context << eth::dupInstruction(_stackDepth); -} - -void CompilerUtils::moveToStackTop(unsigned _stackDepth) -{ - solAssert(_stackDepth <= 15, "Stack too deep, try removing local variables."); - for (unsigned i = 0; i < _stackDepth; ++i) - m_context << eth::swapInstruction(1 + i); -} - -void CompilerUtils::moveIntoStack(unsigned _stackDepth) -{ - solAssert(_stackDepth <= 16, "Stack too deep, try removing local variables."); - for (unsigned i = _stackDepth; i > 0; --i) - m_context << eth::swapInstruction(i); -} - -void CompilerUtils::popStackElement(Type const& _type) -{ - popStackSlots(_type.getSizeOnStack()); -} - -void CompilerUtils::popStackSlots(size_t _amount) -{ - for (size_t i = 0; i < _amount; ++i) - m_context << eth::Instruction::POP; -} - -unsigned CompilerUtils::getSizeOnStack(vector> const& _variableTypes) -{ - unsigned size = 0; - for (shared_ptr const& type: _variableTypes) - size += type->getSizeOnStack(); - return size; -} - -void CompilerUtils::computeHashStatic() -{ - storeInMemory(0); - m_context << u256(32) << u256(0) << eth::Instruction::SHA3; -} - -void CompilerUtils::storeStringData(bytesConstRef _data) -{ - //@todo provide both alternatives to the optimiser - // stack: mempos - if (_data.size() <= 128) - { - for (unsigned i = 0; i < _data.size(); i += 32) - { - m_context << h256::Arith(h256(_data.cropped(i), h256::AlignLeft)); - storeInMemoryDynamic(IntegerType(256)); - } - m_context << eth::Instruction::POP; - } - else - { - // stack: mempos mempos_data - m_context.appendData(_data.toBytes()); - m_context << u256(_data.size()) << eth::Instruction::SWAP2; - m_context << eth::Instruction::CODECOPY; - } -} - -unsigned CompilerUtils::loadFromMemoryHelper(Type const& _type, bool _fromCalldata, bool _padToWordBoundaries) -{ - unsigned numBytes = _type.getCalldataEncodedSize(_padToWordBoundaries); - bool leftAligned = _type.getCategory() == Type::Category::FixedBytes; - if (numBytes == 0) - m_context << eth::Instruction::POP << u256(0); - else - { - solAssert(numBytes <= 32, "Static memory load of more than 32 bytes requested."); - m_context << (_fromCalldata ? eth::Instruction::CALLDATALOAD : eth::Instruction::MLOAD); - if (numBytes != 32) - { - // add leading or trailing zeros by dividing/multiplying depending on alignment - u256 shiftFactor = u256(1) << ((32 - numBytes) * 8); - m_context << shiftFactor << eth::Instruction::SWAP1 << eth::Instruction::DIV; - if (leftAligned) - m_context << shiftFactor << eth::Instruction::MUL; - } - } - - return numBytes; -} - -void CompilerUtils::cleanHigherOrderBits(IntegerType const& _typeOnStack) -{ - if (_typeOnStack.getNumBits() == 256) - return; - else if (_typeOnStack.isSigned()) - m_context << u256(_typeOnStack.getNumBits() / 8 - 1) << eth::Instruction::SIGNEXTEND; - else - m_context << ((u256(1) << _typeOnStack.getNumBits()) - 1) << eth::Instruction::AND; -} - -unsigned CompilerUtils::prepareMemoryStore(Type const& _type, bool _padToWordBoundaries) const -{ - unsigned numBytes = _type.getCalldataEncodedSize(_padToWordBoundaries); - bool leftAligned = _type.getCategory() == Type::Category::FixedBytes; - if (numBytes == 0) - m_context << eth::Instruction::POP; - else - { - solAssert(numBytes <= 32, "Memory store of more than 32 bytes requested."); - if (numBytes != 32 && !leftAligned && !_padToWordBoundaries) - // shift the value accordingly before storing - m_context << (u256(1) << ((32 - numBytes) * 8)) << eth::Instruction::MUL; - } - return numBytes; -} - -} -} diff --git a/libsolidity/CompilerUtils.h b/libsolidity/CompilerUtils.h deleted file mode 100644 index dbb00a1de..000000000 --- a/libsolidity/CompilerUtils.h +++ /dev/null @@ -1,178 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Routines used by both the compiler and the expression compiler. - */ - -#pragma once - -#include -#include - -namespace dev { -namespace solidity { - -class Type; // forward - -class CompilerUtils -{ -public: - CompilerUtils(CompilerContext& _context): m_context(_context) {} - - /// Stores the initial value of the free-memory-pointer at its position; - void initialiseFreeMemoryPointer(); - /// Copies the free memory pointer to the stack. - void fetchFreeMemoryPointer(); - /// Stores the free memory pointer from the stack. - void storeFreeMemoryPointer(); - /// Allocates a number of bytes in memory as given on the stack. - /// Stack pre: - /// Stack post: - void allocateMemory(); - /// Appends code that transforms memptr to (memptr - free_memptr) memptr - void toSizeAfterFreeMemoryPointer(); - - /// Loads data from memory to the stack. - /// @param _offset offset in memory (or calldata) - /// @param _type data type to load - /// @param _fromCalldata if true, load from calldata, not from memory - /// @param _padToWordBoundaries if true, assume the data is padded to word (32 byte) boundaries - /// @returns the number of bytes consumed in memory. - unsigned loadFromMemory( - unsigned _offset, - Type const& _type = IntegerType(256), - bool _fromCalldata = false, - bool _padToWordBoundaries = false - ); - /// Dynamic version of @see loadFromMemory, expects the memory offset on the stack. - /// Stack pre: memory_offset - /// Stack post: value... (memory_offset+length) - void loadFromMemoryDynamic( - Type const& _type, - bool _fromCalldata = false, - bool _padToWordBoundaries = true, - bool _keepUpdatedMemoryOffset = true - ); - /// Stores a 256 bit integer from stack in memory. - /// @param _offset offset in memory - /// @param _type type of the data on the stack - void storeInMemory(unsigned _offset); - /// Dynamic version of @see storeInMemory, expects the memory offset below the value on the stack - /// and also updates that. For reference types, only copies the data pointer. Fails for - /// non-memory-references. - /// @param _padToWordBoundaries if true, adds zeros to pad to multiple of 32 bytes. Array elements - /// are always padded (except for byte arrays), regardless of this parameter. - /// Stack pre: memory_offset value... - /// Stack post: (memory_offset+length) - void storeInMemoryDynamic(Type const& _type, bool _padToWordBoundaries = true); - - /// Copies values (of types @a _givenTypes) given on the stack to a location in memory given - /// at the stack top, encoding them according to the ABI as the given types @a _targetTypes. - /// Removes the values from the stack and leaves the updated memory pointer. - /// Stack pre: ... - /// Stack post: - /// Does not touch the memory-free pointer. - /// @param _padToWordBoundaries if false, all values are concatenated without padding. - /// @param _copyDynamicDataInPlace if true, dynamic types is stored (without length) - /// together with fixed-length data. - /// @note the locations of target reference types are ignored, because it will always be - /// memory. - void encodeToMemory( - TypePointers const& _givenTypes = {}, - TypePointers const& _targetTypes = {}, - bool _padToWordBoundaries = true, - bool _copyDynamicDataInPlace = false - ); - - /// Uses a CALL to the identity contract to perform a memory-to-memory copy. - /// Stack pre: - /// Stack post: - void memoryCopy(); - - /// Appends code for an implicit or explicit type conversion. This includes erasing higher - /// order bits (@see appendHighBitCleanup) when widening integer but also copy to memory - /// if a reference type is converted from calldata or storage to memory. - /// If @a _cleanupNeeded, high order bits cleanup is also done if no type conversion would be - /// necessary. - void convertType(Type const& _typeOnStack, Type const& _targetType, bool _cleanupNeeded = false); - - /// Creates a zero-value for the given type and puts it onto the stack. This might allocate - /// memory for memory references. - void pushZeroValue(Type const& _type); - - /// Moves the value that is at the top of the stack to a stack variable. - void moveToStackVariable(VariableDeclaration const& _variable); - /// Copies an item that occupies @a _itemSize stack slots from a stack depth of @a _stackDepth - /// to the top of the stack. - void copyToStackTop(unsigned _stackDepth, unsigned _itemSize); - /// Moves a single stack element (with _stackDepth items on top of it) to the top of the stack. - void moveToStackTop(unsigned _stackDepth); - /// Moves a single stack element past @a _stackDepth other stack elements - void moveIntoStack(unsigned _stackDepth); - /// Removes the current value from the top of the stack. - void popStackElement(Type const& _type); - /// Removes element from the top of the stack _amount times. - void popStackSlots(size_t _amount); - - template - static unsigned getSizeOnStack(std::vector const& _variables); - static unsigned getSizeOnStack(std::vector> const& _variableTypes); - - /// Appends code that computes tha SHA3 hash of the topmost stack element of 32 byte type. - void computeHashStatic(); - - /// Bytes we need to the start of call data. - /// - The size in bytes of the function (hash) identifier. - static const unsigned dataStartOffset; - - /// Position of the free-memory-pointer in memory; - static const size_t freeMemoryPointer; - -private: - /// Address of the precompiled identity contract. - static const unsigned identityContractAddress; - - /// Stores the given string in memory. - /// Stack pre: mempos - /// Stack post: - void storeStringData(bytesConstRef _data); - - /// Appends code that cleans higher-order bits for integer types. - void cleanHigherOrderBits(IntegerType const& _typeOnStack); - - /// Prepares the given type for storing in memory by shifting it if necessary. - unsigned prepareMemoryStore(Type const& _type, bool _padToWordBoundaries) const; - /// Loads type from memory assuming memory offset is on stack top. - unsigned loadFromMemoryHelper(Type const& _type, bool _fromCalldata, bool _padToWordBoundaries); - - CompilerContext& m_context; -}; - - -template -unsigned CompilerUtils::getSizeOnStack(std::vector const& _variables) -{ - unsigned size = 0; - for (T const& variable: _variables) - size += variable->getType()->getSizeOnStack(); - return size; -} - -} -} diff --git a/libsolidity/DeclarationContainer.cpp b/libsolidity/DeclarationContainer.cpp deleted file mode 100644 index 3e23d93b8..000000000 --- a/libsolidity/DeclarationContainer.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Scope - object that holds declaration of names. - */ - -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace dev::solidity; - -Declaration const* DeclarationContainer::conflictingDeclaration(Declaration const& _declaration) const -{ - ASTString const& name(_declaration.getName()); - solAssert(!name.empty(), ""); - vector declarations; - if (m_declarations.count(name)) - declarations += m_declarations.at(name); - if (m_invisibleDeclarations.count(name)) - declarations += m_invisibleDeclarations.at(name); - - if (dynamic_cast(&_declaration)) - { - // check that all other declarations with the same name are functions - for (Declaration const* declaration: declarations) - if (!dynamic_cast(declaration)) - return declaration; - } - else if (!declarations.empty()) - return declarations.front(); - - return nullptr; -} - -bool DeclarationContainer::registerDeclaration(Declaration const& _declaration, bool _invisible, bool _update) -{ - ASTString const& name(_declaration.getName()); - if (name.empty()) - return true; - - if (_update) - { - solAssert(!dynamic_cast(&_declaration), "Attempt to update function definition."); - m_declarations.erase(name); - m_invisibleDeclarations.erase(name); - } - else if (conflictingDeclaration(_declaration)) - return false; - - if (_invisible) - m_invisibleDeclarations[name].push_back(&_declaration); - else - m_declarations[name].push_back(&_declaration); - return true; -} - -std::vector DeclarationContainer::resolveName(ASTString const& _name, bool _recursive) const -{ - solAssert(!_name.empty(), "Attempt to resolve empty name."); - auto result = m_declarations.find(_name); - if (result != m_declarations.end()) - return result->second; - if (_recursive && m_enclosingContainer) - return m_enclosingContainer->resolveName(_name, true); - return vector({}); -} diff --git a/libsolidity/DeclarationContainer.h b/libsolidity/DeclarationContainer.h deleted file mode 100644 index 0f0b57179..000000000 --- a/libsolidity/DeclarationContainer.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Scope - object that holds declaration of names. - */ - -#pragma once - -#include -#include -#include - -#include - -namespace dev -{ -namespace solidity -{ - -/** - * Container that stores mappings between names and declarations. It also contains a link to the - * enclosing scope. - */ -class DeclarationContainer -{ -public: - explicit DeclarationContainer(Declaration const* _enclosingDeclaration = nullptr, - DeclarationContainer const* _enclosingContainer = nullptr): - m_enclosingDeclaration(_enclosingDeclaration), m_enclosingContainer(_enclosingContainer) {} - /// Registers the declaration in the scope unless its name is already declared or the name is empty. - /// @param _invisible if true, registers the declaration, reports name clashes but does not return it in @a resolveName - /// @param _update if true, replaces a potential declaration that is already present - /// @returns false if the name was already declared. - bool registerDeclaration(Declaration const& _declaration, bool _invisible = false, bool _update = false); - std::vector resolveName(ASTString const& _name, bool _recursive = false) const; - Declaration const* getEnclosingDeclaration() const { return m_enclosingDeclaration; } - std::map> const& getDeclarations() const { return m_declarations; } - /// @returns whether declaration is valid, and if not also returns previous declaration. - Declaration const* conflictingDeclaration(Declaration const& _declaration) const; - -private: - Declaration const* m_enclosingDeclaration; - DeclarationContainer const* m_enclosingContainer; - std::map> m_declarations; - std::map> m_invisibleDeclarations; -}; - -} -} diff --git a/libsolidity/Exceptions.h b/libsolidity/Exceptions.h deleted file mode 100644 index 4bb6644b1..000000000 --- a/libsolidity/Exceptions.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity exception hierarchy. - */ - -#pragma once - -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -struct ParserError: virtual Exception {}; -struct TypeError: virtual Exception {}; -struct DeclarationError: virtual Exception {}; -struct CompilerError: virtual Exception {}; -struct InternalCompilerError: virtual Exception {}; -struct DocstringParsingError: virtual Exception {}; - -using errorSourceLocationInfo = std::pair; - -class SecondarySourceLocation -{ -public: - SecondarySourceLocation& append(std::string const& _errMsg, SourceLocation const& _sourceLocation) - { - infos.push_back(std::make_pair(_errMsg, _sourceLocation)); - return *this; - } - - std::vector infos; -}; - -using errinfo_sourceLocation = boost::error_info; -using errinfo_secondarySourceLocation = boost::error_info; - -} -} diff --git a/libsolidity/ExpressionCompiler.cpp b/libsolidity/ExpressionCompiler.cpp deleted file mode 100644 index 0841089bc..000000000 --- a/libsolidity/ExpressionCompiler.cpp +++ /dev/null @@ -1,1271 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity AST to EVM bytecode compiler for expressions. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -void ExpressionCompiler::compile(Expression const& _expression) -{ - _expression.accept(*this); -} - -void ExpressionCompiler::appendStateVariableInitialization(VariableDeclaration const& _varDecl) -{ - if (!_varDecl.getValue()) - return; - TypePointer type = _varDecl.getValue()->getType(); - solAssert(!!type, "Type information not available."); - CompilerContext::LocationSetter locationSetter(m_context, _varDecl); - _varDecl.getValue()->accept(*this); - - if (_varDecl.getType()->dataStoredIn(DataLocation::Storage)) - { - // reference type, only convert value to mobile type and do final conversion in storeValue. - utils().convertType(*type, *type->mobileType()); - type = type->mobileType(); - } - else - { - utils().convertType(*type, *_varDecl.getType()); - type = _varDecl.getType(); - } - StorageItem(m_context, _varDecl).storeValue(*type, _varDecl.getLocation(), true); -} - -void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const& _varDecl) -{ - CompilerContext::LocationSetter locationSetter(m_context, _varDecl); - FunctionType accessorType(_varDecl); - - TypePointers const& paramTypes = accessorType.getParameterTypes(); - - // retrieve the position of the variable - auto const& location = m_context.getStorageLocationOfVariable(_varDecl); - m_context << location.first << u256(location.second); - - TypePointer returnType = _varDecl.getType(); - - for (size_t i = 0; i < paramTypes.size(); ++i) - { - if (auto mappingType = dynamic_cast(returnType.get())) - { - solAssert(CompilerUtils::freeMemoryPointer >= 0x40, ""); - solAssert( - !paramTypes[i]->isDynamicallySized(), - "Accessors for mapping with dynamically-sized keys not yet implemented." - ); - // pop offset - m_context << eth::Instruction::POP; - // move storage offset to memory. - utils().storeInMemory(32); - // move key to memory. - utils().copyToStackTop(paramTypes.size() - i, 1); - utils().storeInMemory(0); - m_context << u256(64) << u256(0) << eth::Instruction::SHA3; - // push offset - m_context << u256(0); - returnType = mappingType->getValueType(); - } - else if (auto arrayType = dynamic_cast(returnType.get())) - { - // pop offset - m_context << eth::Instruction::POP; - utils().copyToStackTop(paramTypes.size() - i + 1, 1); - ArrayUtils(m_context).accessIndex(*arrayType); - returnType = arrayType->getBaseType(); - } - else - solAssert(false, "Index access is allowed only for \"mapping\" and \"array\" types."); - } - // remove index arguments. - if (paramTypes.size() == 1) - m_context << eth::Instruction::SWAP2 << eth::Instruction::POP << eth::Instruction::SWAP1; - else if (paramTypes.size() >= 2) - { - m_context << eth::swapInstruction(paramTypes.size()); - m_context << eth::Instruction::POP; - m_context << eth::swapInstruction(paramTypes.size()); - utils().popStackSlots(paramTypes.size() - 1); - } - unsigned retSizeOnStack = 0; - solAssert(accessorType.getReturnParameterTypes().size() >= 1, ""); - auto const& returnTypes = accessorType.getReturnParameterTypes(); - if (StructType const* structType = dynamic_cast(returnType.get())) - { - // remove offset - m_context << eth::Instruction::POP; - auto const& names = accessorType.getReturnParameterNames(); - // struct - for (size_t i = 0; i < names.size(); ++i) - { - if (returnTypes[i]->getCategory() == Type::Category::Mapping) - continue; - if (auto arrayType = dynamic_cast(returnTypes[i].get())) - if (!arrayType->isByteArray()) - continue; - pair const& offsets = structType->getStorageOffsetsOfMember(names[i]); - m_context << eth::Instruction::DUP1 << u256(offsets.first) << eth::Instruction::ADD << u256(offsets.second); - TypePointer memberType = structType->getMemberType(names[i]); - StorageItem(m_context, *memberType).retrieveValue(SourceLocation(), true); - utils().convertType(*memberType, *returnTypes[i]); - utils().moveToStackTop(returnTypes[i]->getSizeOnStack()); - retSizeOnStack += returnTypes[i]->getSizeOnStack(); - } - // remove slot - m_context << eth::Instruction::POP; - } - else - { - // simple value or array - solAssert(returnTypes.size() == 1, ""); - StorageItem(m_context, *returnType).retrieveValue(SourceLocation(), true); - utils().convertType(*returnType, *returnTypes.front()); - retSizeOnStack = returnTypes.front()->getSizeOnStack(); - } - solAssert(retSizeOnStack == utils().getSizeOnStack(returnTypes), ""); - solAssert(retSizeOnStack <= 15, "Stack is too deep."); - m_context << eth::dupInstruction(retSizeOnStack + 1); - m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction); -} - -bool ExpressionCompiler::visit(Assignment const& _assignment) -{ - CompilerContext::LocationSetter locationSetter(m_context, _assignment); - _assignment.getRightHandSide().accept(*this); - TypePointer type = _assignment.getRightHandSide().getType(); - if (!_assignment.getType()->dataStoredIn(DataLocation::Storage)) - { - utils().convertType(*type, *_assignment.getType()); - type = _assignment.getType(); - } - else - { - utils().convertType(*type, *type->mobileType()); - type = type->mobileType(); - } - - _assignment.getLeftHandSide().accept(*this); - solAssert(!!m_currentLValue, "LValue not retrieved."); - - Token::Value op = _assignment.getAssignmentOperator(); - if (op != Token::Assign) // compound assignment - { - solAssert(_assignment.getType()->isValueType(), "Compound operators not implemented for non-value types."); - unsigned lvalueSize = m_currentLValue->sizeOnStack(); - unsigned itemSize = _assignment.getType()->getSizeOnStack(); - if (lvalueSize > 0) - { - utils().copyToStackTop(lvalueSize + itemSize, itemSize); - utils().copyToStackTop(itemSize + lvalueSize, lvalueSize); - // value lvalue_ref value lvalue_ref - } - m_currentLValue->retrieveValue(_assignment.getLocation(), true); - appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), *_assignment.getType()); - if (lvalueSize > 0) - { - solAssert(itemSize + lvalueSize <= 16, "Stack too deep, try removing local variables."); - // value [lvalue_ref] updated_value - for (unsigned i = 0; i < itemSize; ++i) - m_context << eth::swapInstruction(itemSize + lvalueSize) << eth::Instruction::POP; - } - } - m_currentLValue->storeValue(*type, _assignment.getLocation()); - m_currentLValue.reset(); - return false; -} - -bool ExpressionCompiler::visit(UnaryOperation const& _unaryOperation) -{ - CompilerContext::LocationSetter locationSetter(m_context, _unaryOperation); - //@todo type checking and creating code for an operator should be in the same place: - // the operator should know how to convert itself and to which types it applies, so - // put this code together with "Type::acceptsBinary/UnaryOperator" into a class that - // represents the operator - if (_unaryOperation.getType()->getCategory() == Type::Category::IntegerConstant) - { - m_context << _unaryOperation.getType()->literalValue(nullptr); - return false; - } - - _unaryOperation.getSubExpression().accept(*this); - - switch (_unaryOperation.getOperator()) - { - case Token::Not: // ! - m_context << eth::Instruction::ISZERO; - break; - case Token::BitNot: // ~ - m_context << eth::Instruction::NOT; - break; - case Token::After: // after - m_context << eth::Instruction::TIMESTAMP << eth::Instruction::ADD; - break; - case Token::Delete: // delete - solAssert(!!m_currentLValue, "LValue not retrieved."); - m_currentLValue->setToZero(_unaryOperation.getLocation()); - m_currentLValue.reset(); - break; - case Token::Inc: // ++ (pre- or postfix) - case Token::Dec: // -- (pre- or postfix) - solAssert(!!m_currentLValue, "LValue not retrieved."); - m_currentLValue->retrieveValue(_unaryOperation.getLocation()); - if (!_unaryOperation.isPrefixOperation()) - { - // store value for later - solAssert(_unaryOperation.getType()->getSizeOnStack() == 1, "Stack size != 1 not implemented."); - m_context << eth::Instruction::DUP1; - if (m_currentLValue->sizeOnStack() > 0) - for (unsigned i = 1 + m_currentLValue->sizeOnStack(); i > 0; --i) - m_context << eth::swapInstruction(i); - } - m_context << u256(1); - if (_unaryOperation.getOperator() == Token::Inc) - m_context << eth::Instruction::ADD; - else - m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB; - // Stack for prefix: [ref...] (*ref)+-1 - // Stack for postfix: *ref [ref...] (*ref)+-1 - for (unsigned i = m_currentLValue->sizeOnStack(); i > 0; --i) - m_context << eth::swapInstruction(i); - m_currentLValue->storeValue( - *_unaryOperation.getType(), _unaryOperation.getLocation(), - !_unaryOperation.isPrefixOperation()); - m_currentLValue.reset(); - break; - case Token::Add: // + - // unary add, so basically no-op - break; - case Token::Sub: // - - m_context << u256(0) << eth::Instruction::SUB; - break; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid unary operator: " + - string(Token::toString(_unaryOperation.getOperator())))); - } - return false; -} - -bool ExpressionCompiler::visit(BinaryOperation const& _binaryOperation) -{ - CompilerContext::LocationSetter locationSetter(m_context, _binaryOperation); - Expression const& leftExpression = _binaryOperation.getLeftExpression(); - Expression const& rightExpression = _binaryOperation.getRightExpression(); - Type const& commonType = _binaryOperation.getCommonType(); - Token::Value const c_op = _binaryOperation.getOperator(); - - if (c_op == Token::And || c_op == Token::Or) // special case: short-circuiting - appendAndOrOperatorCode(_binaryOperation); - else if (commonType.getCategory() == Type::Category::IntegerConstant) - m_context << commonType.literalValue(nullptr); - else - { - bool cleanupNeeded = commonType.getCategory() == Type::Category::Integer && - (Token::isCompareOp(c_op) || c_op == Token::Div || c_op == Token::Mod); - - // for commutative operators, push the literal as late as possible to allow improved optimization - auto isLiteral = [](Expression const& _e) - { - return dynamic_cast(&_e) || _e.getType()->getCategory() == Type::Category::IntegerConstant; - }; - bool swap = m_optimize && Token::isCommutativeOp(c_op) && isLiteral(rightExpression) && !isLiteral(leftExpression); - if (swap) - { - leftExpression.accept(*this); - utils().convertType(*leftExpression.getType(), commonType, cleanupNeeded); - rightExpression.accept(*this); - utils().convertType(*rightExpression.getType(), commonType, cleanupNeeded); - } - else - { - rightExpression.accept(*this); - utils().convertType(*rightExpression.getType(), commonType, cleanupNeeded); - leftExpression.accept(*this); - utils().convertType(*leftExpression.getType(), commonType, cleanupNeeded); - } - if (Token::isCompareOp(c_op)) - appendCompareOperatorCode(c_op, commonType); - else - appendOrdinaryBinaryOperatorCode(c_op, commonType); - } - - // do not visit the child nodes, we already did that explicitly - return false; -} - -bool ExpressionCompiler::visit(FunctionCall const& _functionCall) -{ - CompilerContext::LocationSetter locationSetter(m_context, _functionCall); - using Location = FunctionType::Location; - if (_functionCall.isTypeConversion()) - { - solAssert(_functionCall.getArguments().size() == 1, ""); - solAssert(_functionCall.getNames().empty(), ""); - Expression const& firstArgument = *_functionCall.getArguments().front(); - firstArgument.accept(*this); - utils().convertType(*firstArgument.getType(), *_functionCall.getType()); - return false; - } - - FunctionTypePointer functionType; - if (_functionCall.isStructConstructorCall()) - { - auto const& type = dynamic_cast(*_functionCall.getExpression().getType()); - auto const& structType = dynamic_cast(*type.getActualType()); - functionType = structType.constructorType(); - } - else - functionType = dynamic_pointer_cast(_functionCall.getExpression().getType()); - - TypePointers const& parameterTypes = functionType->getParameterTypes(); - vector> const& callArguments = _functionCall.getArguments(); - vector> const& callArgumentNames = _functionCall.getNames(); - if (!functionType->takesArbitraryParameters()) - solAssert(callArguments.size() == parameterTypes.size(), ""); - - vector> arguments; - if (callArgumentNames.empty()) - // normal arguments - arguments = callArguments; - else - // named arguments - for (auto const& parameterName: functionType->getParameterNames()) - { - bool found = false; - for (size_t j = 0; j < callArgumentNames.size() && !found; j++) - if ((found = (parameterName == *callArgumentNames[j]))) - // we found the actual parameter position - arguments.push_back(callArguments[j]); - solAssert(found, ""); - } - - if (_functionCall.isStructConstructorCall()) - { - TypeType const& type = dynamic_cast(*_functionCall.getExpression().getType()); - auto const& structType = dynamic_cast(*type.getActualType()); - - m_context << u256(max(32u, structType.getCalldataEncodedSize(true))); - utils().allocateMemory(); - m_context << eth::Instruction::DUP1; - - for (unsigned i = 0; i < arguments.size(); ++i) - { - arguments[i]->accept(*this); - utils().convertType(*arguments[i]->getType(), *functionType->getParameterTypes()[i]); - utils().storeInMemoryDynamic(*functionType->getParameterTypes()[i]); - } - m_context << eth::Instruction::POP; - } - else - { - FunctionType const& function = *functionType; - switch (function.getLocation()) - { - case Location::Internal: - { - // Calling convention: Caller pushes return address and arguments - // Callee removes them and pushes return values - - eth::AssemblyItem returnLabel = m_context.pushNewTag(); - for (unsigned i = 0; i < arguments.size(); ++i) - { - arguments[i]->accept(*this); - utils().convertType(*arguments[i]->getType(), *function.getParameterTypes()[i]); - } - _functionCall.getExpression().accept(*this); - - m_context.appendJump(eth::AssemblyItem::JumpType::IntoFunction); - m_context << returnLabel; - - unsigned returnParametersSize = CompilerUtils::getSizeOnStack(function.getReturnParameterTypes()); - // callee adds return parameters, but removes arguments and return label - m_context.adjustStackOffset(returnParametersSize - CompilerUtils::getSizeOnStack(function.getParameterTypes()) - 1); - - // @todo for now, the return value of a function is its first return value, so remove - // all others - for (unsigned i = 1; i < function.getReturnParameterTypes().size(); ++i) - utils().popStackElement(*function.getReturnParameterTypes()[i]); - break; - } - case Location::External: - case Location::CallCode: - case Location::Bare: - case Location::BareCallCode: - _functionCall.getExpression().accept(*this); - appendExternalFunctionCall(function, arguments); - break; - case Location::Creation: - { - _functionCall.getExpression().accept(*this); - solAssert(!function.gasSet(), "Gas limit set for contract creation."); - solAssert(function.getReturnParameterTypes().size() == 1, ""); - TypePointers argumentTypes; - for (auto const& arg: arguments) - { - arg->accept(*this); - argumentTypes.push_back(arg->getType()); - } - ContractDefinition const& contract = dynamic_cast( - *function.getReturnParameterTypes().front()).getContractDefinition(); - // copy the contract's code into memory - bytes const& bytecode = m_context.getCompiledContract(contract); - utils().fetchFreeMemoryPointer(); - m_context << u256(bytecode.size()) << eth::Instruction::DUP1; - //@todo could be done by actually appending the Assembly, but then we probably need to compile - // multiple times. Will revisit once external fuctions are inlined. - m_context.appendData(bytecode); - m_context << eth::Instruction::DUP4 << eth::Instruction::CODECOPY; - - m_context << eth::Instruction::ADD; - utils().encodeToMemory(argumentTypes, function.getParameterTypes()); - // now on stack: memory_end_ptr - // need: size, offset, endowment - utils().toSizeAfterFreeMemoryPointer(); - if (function.valueSet()) - m_context << eth::dupInstruction(3); - else - m_context << u256(0); - m_context << eth::Instruction::CREATE; - if (function.valueSet()) - m_context << eth::swapInstruction(1) << eth::Instruction::POP; - break; - } - case Location::SetGas: - { - // stack layout: contract_address function_id [gas] [value] - _functionCall.getExpression().accept(*this); - - arguments.front()->accept(*this); - utils().convertType(*arguments.front()->getType(), IntegerType(256), true); - // Note that function is not the original function, but the ".gas" function. - // Its values of gasSet and valueSet is equal to the original function's though. - unsigned stackDepth = (function.gasSet() ? 1 : 0) + (function.valueSet() ? 1 : 0); - if (stackDepth > 0) - m_context << eth::swapInstruction(stackDepth); - if (function.gasSet()) - m_context << eth::Instruction::POP; - break; - } - case Location::SetValue: - // stack layout: contract_address function_id [gas] [value] - _functionCall.getExpression().accept(*this); - // Note that function is not the original function, but the ".value" function. - // Its values of gasSet and valueSet is equal to the original function's though. - if (function.valueSet()) - m_context << eth::Instruction::POP; - arguments.front()->accept(*this); - break; - case Location::Send: - _functionCall.getExpression().accept(*this); - m_context << u256(0); // do not send gas (there still is the stipend) - arguments.front()->accept(*this); - utils().convertType( - *arguments.front()->getType(), - *function.getParameterTypes().front(), true - ); - appendExternalFunctionCall( - FunctionType( - TypePointers{}, - TypePointers{}, - strings(), - strings(), - Location::Bare, - false, - nullptr, - true, - true - ), - {} - ); - break; - case Location::Suicide: - arguments.front()->accept(*this); - utils().convertType(*arguments.front()->getType(), *function.getParameterTypes().front(), true); - m_context << eth::Instruction::SUICIDE; - break; - case Location::SHA3: - { - TypePointers argumentTypes; - for (auto const& arg: arguments) - { - arg->accept(*this); - argumentTypes.push_back(arg->getType()); - } - utils().fetchFreeMemoryPointer(); - utils().encodeToMemory(argumentTypes, TypePointers(), function.padArguments(), true); - utils().toSizeAfterFreeMemoryPointer(); - m_context << eth::Instruction::SHA3; - break; - } - case Location::Log0: - case Location::Log1: - case Location::Log2: - case Location::Log3: - case Location::Log4: - { - unsigned logNumber = int(function.getLocation()) - int(Location::Log0); - for (unsigned arg = logNumber; arg > 0; --arg) - { - arguments[arg]->accept(*this); - utils().convertType(*arguments[arg]->getType(), *function.getParameterTypes()[arg], true); - } - arguments.front()->accept(*this); - utils().fetchFreeMemoryPointer(); - utils().encodeToMemory( - {arguments.front()->getType()}, - {function.getParameterTypes().front()}, - false, - true); - utils().toSizeAfterFreeMemoryPointer(); - m_context << eth::logInstruction(logNumber); - break; - } - case Location::Event: - { - _functionCall.getExpression().accept(*this); - auto const& event = dynamic_cast(function.getDeclaration()); - unsigned numIndexed = 0; - // All indexed arguments go to the stack - for (unsigned arg = arguments.size(); arg > 0; --arg) - if (event.getParameters()[arg - 1]->isIndexed()) - { - ++numIndexed; - arguments[arg - 1]->accept(*this); - utils().convertType( - *arguments[arg - 1]->getType(), - *function.getParameterTypes()[arg - 1], - true - ); - } - if (!event.isAnonymous()) - { - m_context << u256(h256::Arith(dev::sha3(function.externalSignature(event.getName())))); - ++numIndexed; - } - solAssert(numIndexed <= 4, "Too many indexed arguments."); - // Copy all non-indexed arguments to memory (data) - // Memory position is only a hack and should be removed once we have free memory pointer. - TypePointers nonIndexedArgTypes; - TypePointers nonIndexedParamTypes; - for (unsigned arg = 0; arg < arguments.size(); ++arg) - if (!event.getParameters()[arg]->isIndexed()) - { - arguments[arg]->accept(*this); - nonIndexedArgTypes.push_back(arguments[arg]->getType()); - nonIndexedParamTypes.push_back(function.getParameterTypes()[arg]); - } - utils().fetchFreeMemoryPointer(); - utils().encodeToMemory(nonIndexedArgTypes, nonIndexedParamTypes); - // need: topic1 ... topicn memsize memstart - utils().toSizeAfterFreeMemoryPointer(); - m_context << eth::logInstruction(numIndexed); - break; - } - case Location::BlockHash: - { - arguments[0]->accept(*this); - utils().convertType(*arguments[0]->getType(), *function.getParameterTypes()[0], true); - m_context << eth::Instruction::BLOCKHASH; - break; - } - case Location::ECRecover: - case Location::SHA256: - case Location::RIPEMD160: - { - _functionCall.getExpression().accept(*this); - static const map contractAddresses{{Location::ECRecover, 1}, - {Location::SHA256, 2}, - {Location::RIPEMD160, 3}}; - m_context << contractAddresses.find(function.getLocation())->second; - for (unsigned i = function.getSizeOnStack(); i > 0; --i) - m_context << eth::swapInstruction(i); - appendExternalFunctionCall(function, arguments); - break; - } - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid function type.")); - } - } - return false; -} - -bool ExpressionCompiler::visit(NewExpression const&) -{ - // code is created for the function call (CREATION) only - return false; -} - -void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess) -{ - CompilerContext::LocationSetter locationSetter(m_context, _memberAccess); - ASTString const& member = _memberAccess.getMemberName(); - switch (_memberAccess.getExpression().getType()->getCategory()) - { - case Type::Category::Contract: - { - bool alsoSearchInteger = false; - ContractType const& type = dynamic_cast(*_memberAccess.getExpression().getType()); - if (type.isSuper()) - { - solAssert(!!_memberAccess.referencedDeclaration(), "Referenced declaration not resolved."); - m_context << m_context.getSuperFunctionEntryLabel( - dynamic_cast(*_memberAccess.referencedDeclaration()), - type.getContractDefinition() - ).pushTag(); - } - else - { - // ordinary contract type - if (Declaration const* declaration = _memberAccess.referencedDeclaration()) - { - u256 identifier; - if (auto const* variable = dynamic_cast(declaration)) - identifier = FunctionType(*variable).externalIdentifier(); - else if (auto const* function = dynamic_cast(declaration)) - identifier = FunctionType(*function).externalIdentifier(); - else - solAssert(false, "Contract member is neither variable nor function."); - utils().convertType(type, IntegerType(0, IntegerType::Modifier::Address), true); - m_context << identifier; - } - else - // not found in contract, search in members inherited from address - alsoSearchInteger = true; - } - if (!alsoSearchInteger) - break; - } - case Type::Category::Integer: - if (member == "balance") - { - utils().convertType( - *_memberAccess.getExpression().getType(), - IntegerType(0, IntegerType::Modifier::Address), - true - ); - m_context << eth::Instruction::BALANCE; - } - else if ((set{"send", "call", "callcode"}).count(member)) - utils().convertType( - *_memberAccess.getExpression().getType(), - IntegerType(0, IntegerType::Modifier::Address), - true - ); - else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid member access to integer.")); - break; - case Type::Category::Function: - solAssert(!!_memberAccess.getExpression().getType()->getMemberType(member), - "Invalid member access to function."); - break; - case Type::Category::Magic: - // we can ignore the kind of magic and only look at the name of the member - if (member == "coinbase") - m_context << eth::Instruction::COINBASE; - else if (member == "timestamp") - m_context << eth::Instruction::TIMESTAMP; - else if (member == "difficulty") - m_context << eth::Instruction::DIFFICULTY; - else if (member == "number") - m_context << eth::Instruction::NUMBER; - else if (member == "gaslimit") - m_context << eth::Instruction::GASLIMIT; - else if (member == "sender") - m_context << eth::Instruction::CALLER; - else if (member == "value") - m_context << eth::Instruction::CALLVALUE; - else if (member == "origin") - m_context << eth::Instruction::ORIGIN; - else if (member == "gas") - m_context << eth::Instruction::GAS; - else if (member == "gasprice") - m_context << eth::Instruction::GASPRICE; - else if (member == "data") - m_context << u256(0) << eth::Instruction::CALLDATASIZE; - else if (member == "sig") - m_context << u256(0) << eth::Instruction::CALLDATALOAD - << (u256(0xffffffff) << (256 - 32)) << eth::Instruction::AND; - else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown magic member.")); - break; - case Type::Category::Struct: - { - StructType const& type = dynamic_cast(*_memberAccess.getExpression().getType()); - switch (type.location()) - { - case DataLocation::Storage: - { - pair const& offsets = type.getStorageOffsetsOfMember(member); - m_context << offsets.first << eth::Instruction::ADD << u256(offsets.second); - setLValueToStorageItem(_memberAccess); - break; - } - case DataLocation::Memory: - { - m_context << type.memoryOffsetOfMember(member) << eth::Instruction::ADD; - setLValue(_memberAccess, *_memberAccess.getType()); - break; - } - default: - solAssert(false, "Illegal data location for struct."); - } - break; - } - case Type::Category::Enum: - { - EnumType const& type = dynamic_cast(*_memberAccess.getExpression().getType()); - m_context << type.getMemberValue(_memberAccess.getMemberName()); - break; - } - case Type::Category::TypeType: - { - TypeType const& type = dynamic_cast(*_memberAccess.getExpression().getType()); - solAssert( - !type.getMembers().membersByName(_memberAccess.getMemberName()).empty(), - "Invalid member access to " + type.toString(false) - ); - - if (dynamic_cast(type.getActualType().get())) - { - auto const* function = dynamic_cast(_memberAccess.referencedDeclaration()); - solAssert(!!function, "Function not found in member access"); - m_context << m_context.getFunctionEntryLabel(*function).pushTag(); - } - else if (auto enumType = dynamic_cast(type.getActualType().get())) - m_context << enumType->getMemberValue(_memberAccess.getMemberName()); - break; - } - case Type::Category::Array: - { - solAssert(member == "length", "Illegal array member."); - auto const& type = dynamic_cast(*_memberAccess.getExpression().getType()); - if (!type.isDynamicallySized()) - { - utils().popStackElement(type); - m_context << type.getLength(); - } - else - switch (type.location()) - { - case DataLocation::CallData: - m_context << eth::Instruction::SWAP1 << eth::Instruction::POP; - break; - case DataLocation::Storage: - setLValue(_memberAccess, type); - break; - case DataLocation::Memory: - m_context << eth::Instruction::MLOAD; - break; - } - break; - } - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member access to unknown type.")); - } -} - -bool ExpressionCompiler::visit(IndexAccess const& _indexAccess) -{ - CompilerContext::LocationSetter locationSetter(m_context, _indexAccess); - _indexAccess.getBaseExpression().accept(*this); - - Type const& baseType = *_indexAccess.getBaseExpression().getType(); - if (baseType.getCategory() == Type::Category::Mapping) - { - // stack: storage_base_ref - TypePointer keyType = dynamic_cast(baseType).getKeyType(); - solAssert(_indexAccess.getIndexExpression(), "Index expression expected."); - if (keyType->isDynamicallySized()) - { - _indexAccess.getIndexExpression()->accept(*this); - utils().fetchFreeMemoryPointer(); - // stack: base index mem - // note: the following operations must not allocate memory! - utils().encodeToMemory( - TypePointers{_indexAccess.getIndexExpression()->getType()}, - TypePointers{keyType}, - false, - true - ); - m_context << eth::Instruction::SWAP1; - utils().storeInMemoryDynamic(IntegerType(256)); - utils().toSizeAfterFreeMemoryPointer(); - } - else - { - m_context << u256(0); // memory position - appendExpressionCopyToMemory(*keyType, *_indexAccess.getIndexExpression()); - m_context << eth::Instruction::SWAP1; - solAssert(CompilerUtils::freeMemoryPointer >= 0x40, ""); - utils().storeInMemoryDynamic(IntegerType(256)); - m_context << u256(0); - } - m_context << eth::Instruction::SHA3; - m_context << u256(0); - setLValueToStorageItem(_indexAccess); - } - else if (baseType.getCategory() == Type::Category::Array) - { - ArrayType const& arrayType = dynamic_cast(baseType); - solAssert(_indexAccess.getIndexExpression(), "Index expression expected."); - - _indexAccess.getIndexExpression()->accept(*this); - // stack layout: [] - ArrayUtils(m_context).accessIndex(arrayType); - switch (arrayType.location()) - { - case DataLocation::Storage: - if (arrayType.isByteArray()) - { - solAssert(!arrayType.isString(), "Index access to string is not allowed."); - setLValue(_indexAccess); - } - else - setLValueToStorageItem(_indexAccess); - break; - case DataLocation::Memory: - setLValue(_indexAccess, *_indexAccess.getType(), !arrayType.isByteArray()); - break; - case DataLocation::CallData: - //@todo if we implement this, the value in calldata has to be added to the base offset - solAssert(!arrayType.getBaseType()->isDynamicallySized(), "Nested arrays not yet implemented."); - if (arrayType.getBaseType()->isValueType()) - CompilerUtils(m_context).loadFromMemoryDynamic( - *arrayType.getBaseType(), - true, - !arrayType.isByteArray(), - false - ); - break; - } - } - else - solAssert(false, "Index access only allowed for mappings or arrays."); - - return false; -} - -void ExpressionCompiler::endVisit(Identifier const& _identifier) -{ - CompilerContext::LocationSetter locationSetter(m_context, _identifier); - Declaration const* declaration = &_identifier.getReferencedDeclaration(); - if (MagicVariableDeclaration const* magicVar = dynamic_cast(declaration)) - { - switch (magicVar->getType()->getCategory()) - { - case Type::Category::Contract: - // "this" or "super" - if (!dynamic_cast(*magicVar->getType()).isSuper()) - m_context << eth::Instruction::ADDRESS; - break; - case Type::Category::Integer: - // "now" - m_context << eth::Instruction::TIMESTAMP; - break; - default: - break; - } - } - else if (FunctionDefinition const* functionDef = dynamic_cast(declaration)) - m_context << m_context.getVirtualFunctionEntryLabel(*functionDef).pushTag(); - else if (auto variable = dynamic_cast(declaration)) - { - if (!variable->isConstant()) - setLValueFromDeclaration(*declaration, _identifier); - else - variable->getValue()->accept(*this); - } - else if (dynamic_cast(declaration)) - { - // no-op - } - else if (dynamic_cast(declaration)) - { - // no-op - } - else if (dynamic_cast(declaration)) - { - // no-op - } - else - { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Identifier type not expected in expression context.")); - } -} - -void ExpressionCompiler::endVisit(Literal const& _literal) -{ - CompilerContext::LocationSetter locationSetter(m_context, _literal); - TypePointer type = _literal.getType(); - switch (type->getCategory()) - { - case Type::Category::IntegerConstant: - case Type::Category::Bool: - m_context << type->literalValue(&_literal); - break; - case Type::Category::StringLiteral: - break; // will be done during conversion - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Only integer, boolean and string literals implemented for now.")); - } -} - -void ExpressionCompiler::appendAndOrOperatorCode(BinaryOperation const& _binaryOperation) -{ - Token::Value const c_op = _binaryOperation.getOperator(); - solAssert(c_op == Token::Or || c_op == Token::And, ""); - - _binaryOperation.getLeftExpression().accept(*this); - m_context << eth::Instruction::DUP1; - if (c_op == Token::And) - m_context << eth::Instruction::ISZERO; - eth::AssemblyItem endLabel = m_context.appendConditionalJump(); - m_context << eth::Instruction::POP; - _binaryOperation.getRightExpression().accept(*this); - m_context << endLabel; -} - -void ExpressionCompiler::appendCompareOperatorCode(Token::Value _operator, Type const& _type) -{ - if (_operator == Token::Equal || _operator == Token::NotEqual) - { - m_context << eth::Instruction::EQ; - if (_operator == Token::NotEqual) - m_context << eth::Instruction::ISZERO; - } - else - { - bool isSigned = false; - if (auto type = dynamic_cast(&_type)) - isSigned = type->isSigned(); - - switch (_operator) - { - case Token::GreaterThanOrEqual: - m_context << - (isSigned ? eth::Instruction::SLT : eth::Instruction::LT) << - eth::Instruction::ISZERO; - break; - case Token::LessThanOrEqual: - m_context << - (isSigned ? eth::Instruction::SGT : eth::Instruction::GT) << - eth::Instruction::ISZERO; - break; - case Token::GreaterThan: - m_context << (isSigned ? eth::Instruction::SGT : eth::Instruction::GT); - break; - case Token::LessThan: - m_context << (isSigned ? eth::Instruction::SLT : eth::Instruction::LT); - break; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown comparison operator.")); - } - } -} - -void ExpressionCompiler::appendOrdinaryBinaryOperatorCode(Token::Value _operator, Type const& _type) -{ - if (Token::isArithmeticOp(_operator)) - appendArithmeticOperatorCode(_operator, _type); - else if (Token::isBitOp(_operator)) - appendBitOperatorCode(_operator); - else if (Token::isShiftOp(_operator)) - appendShiftOperatorCode(_operator); - else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown binary operator.")); -} - -void ExpressionCompiler::appendArithmeticOperatorCode(Token::Value _operator, Type const& _type) -{ - IntegerType const& type = dynamic_cast(_type); - bool const c_isSigned = type.isSigned(); - - switch (_operator) - { - case Token::Add: - m_context << eth::Instruction::ADD; - break; - case Token::Sub: - m_context << eth::Instruction::SUB; - break; - case Token::Mul: - m_context << eth::Instruction::MUL; - break; - case Token::Div: - m_context << (c_isSigned ? eth::Instruction::SDIV : eth::Instruction::DIV); - break; - case Token::Mod: - m_context << (c_isSigned ? eth::Instruction::SMOD : eth::Instruction::MOD); - break; - case Token::Exp: - m_context << eth::Instruction::EXP; - break; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown arithmetic operator.")); - } -} - -void ExpressionCompiler::appendBitOperatorCode(Token::Value _operator) -{ - switch (_operator) - { - case Token::BitOr: - m_context << eth::Instruction::OR; - break; - case Token::BitAnd: - m_context << eth::Instruction::AND; - break; - case Token::BitXor: - m_context << eth::Instruction::XOR; - break; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown bit operator.")); - } -} - -void ExpressionCompiler::appendShiftOperatorCode(Token::Value _operator) -{ - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Shift operators not yet implemented.")); - switch (_operator) - { - case Token::SHL: - break; - case Token::SAR: - break; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown shift operator.")); - } -} - -void ExpressionCompiler::appendExternalFunctionCall( - FunctionType const& _functionType, - vector> const& _arguments -) -{ - solAssert(_functionType.takesArbitraryParameters() || - _arguments.size() == _functionType.getParameterTypes().size(), ""); - - // Assumed stack content here: - // - // value [if _functionType.valueSet()] - // gas [if _functionType.gasSet()] - // function identifier [unless bare] - // contract address - - unsigned gasValueSize = (_functionType.gasSet() ? 1 : 0) + (_functionType.valueSet() ? 1 : 0); - - unsigned contractStackPos = m_context.currentToBaseStackOffset(1 + gasValueSize + (_functionType.isBareCall() ? 0 : 1)); - unsigned gasStackPos = m_context.currentToBaseStackOffset(gasValueSize); - unsigned valueStackPos = m_context.currentToBaseStackOffset(1); - - using FunctionKind = FunctionType::Location; - FunctionKind funKind = _functionType.getLocation(); - bool returnSuccessCondition = funKind == FunctionKind::Bare || funKind == FunctionKind::BareCallCode; - bool isCallCode = funKind == FunctionKind::BareCallCode || funKind == FunctionKind::CallCode; - - //@todo only return the first return value for now - Type const* firstReturnType = - _functionType.getReturnParameterTypes().empty() ? - nullptr : - _functionType.getReturnParameterTypes().front().get(); - unsigned retSize = 0; - if (returnSuccessCondition) - retSize = 0; // return value actually is success condition - else if (firstReturnType) - { - retSize = firstReturnType->getCalldataEncodedSize(); - solAssert(retSize > 0, "Unable to return dynamic type from external call."); - } - - // Evaluate arguments. - TypePointers argumentTypes; - bool manualFunctionId = - (funKind == FunctionKind::Bare || funKind == FunctionKind::BareCallCode) && - !_arguments.empty() && - _arguments.front()->getType()->mobileType()->getCalldataEncodedSize(false) == - CompilerUtils::dataStartOffset; - if (manualFunctionId) - { - // If we have a BareCall or BareCallCode and the first type has exactly 4 bytes, use it as - // function identifier. - _arguments.front()->accept(*this); - utils().convertType( - *_arguments.front()->getType(), - IntegerType(8 * CompilerUtils::dataStartOffset), - true - ); - for (unsigned i = 0; i < gasValueSize; ++i) - m_context << eth::swapInstruction(gasValueSize - i); - gasStackPos++; - valueStackPos++; - } - for (size_t i = manualFunctionId ? 1 : 0; i < _arguments.size(); ++i) - { - _arguments[i]->accept(*this); - argumentTypes.push_back(_arguments[i]->getType()); - } - - // Copy function identifier to memory. - utils().fetchFreeMemoryPointer(); - if (!_functionType.isBareCall() || manualFunctionId) - { - m_context << eth::dupInstruction(2 + gasValueSize + CompilerUtils::getSizeOnStack(argumentTypes)); - utils().storeInMemoryDynamic(IntegerType(8 * CompilerUtils::dataStartOffset), false); - } - // If the function takes arbitrary parameters, copy dynamic length data in place. - // Move argumenst to memory, will not update the free memory pointer (but will update the memory - // pointer on the stack). - utils().encodeToMemory( - argumentTypes, - _functionType.getParameterTypes(), - _functionType.padArguments(), - _functionType.takesArbitraryParameters() - ); - - // Stack now: - // - // input_memory_end - // value [if _functionType.valueSet()] - // gas [if _functionType.gasSet()] - // function identifier [unless bare] - // contract address - - // Output data will replace input data. - // put on stack: - m_context << u256(retSize); - utils().fetchFreeMemoryPointer(); - m_context << eth::Instruction::DUP1 << eth::Instruction::DUP4 << eth::Instruction::SUB; - m_context << eth::Instruction::DUP2; - - // CALL arguments: outSize, outOff, inSize, inOff (already present up to here) - // value, addr, gas (stack top) - if (_functionType.valueSet()) - m_context << eth::dupInstruction(m_context.baseToCurrentStackOffset(valueStackPos)); - else - m_context << u256(0); - m_context << eth::dupInstruction(m_context.baseToCurrentStackOffset(contractStackPos)); - - if (_functionType.gasSet()) - m_context << eth::dupInstruction(m_context.baseToCurrentStackOffset(gasStackPos)); - else - { - // send all gas except the amount needed to execute "SUB" and "CALL" - // @todo this retains too much gas for now, needs to be fine-tuned. - u256 gasNeededByCaller = eth::c_callGas + 10; - if (_functionType.valueSet()) - gasNeededByCaller += eth::c_callValueTransferGas; - if (!isCallCode) - gasNeededByCaller += eth::c_callNewAccountGas; // we never know - m_context << - gasNeededByCaller << - eth::Instruction::GAS << - eth::Instruction::SUB; - } - if (isCallCode) - m_context << eth::Instruction::CALLCODE; - else - m_context << eth::Instruction::CALL; - - unsigned remainsSize = - 2 + // contract address, input_memory_end - _functionType.valueSet() + - _functionType.gasSet() + - (!_functionType.isBareCall() || manualFunctionId); - - if (returnSuccessCondition) - m_context << eth::swapInstruction(remainsSize); - else - { - //Propagate error condition (if CALL pushes 0 on stack). - m_context << eth::Instruction::ISZERO; - m_context.appendConditionalJumpTo(m_context.errorTag()); - } - - utils().popStackSlots(remainsSize); - - if (returnSuccessCondition) - { - // already there - } - else if (funKind == FunctionKind::RIPEMD160) - { - // fix: built-in contract returns right-aligned data - utils().fetchFreeMemoryPointer(); - utils().loadFromMemoryDynamic(IntegerType(160), false, true, false); - utils().convertType(IntegerType(160), FixedBytesType(20)); - } - else if (firstReturnType) - { - //@todo manually update free memory pointer if we accept returning memory-stored objects - utils().fetchFreeMemoryPointer(); - utils().loadFromMemoryDynamic(*firstReturnType, false, true, false); - - } -} - -void ExpressionCompiler::appendExpressionCopyToMemory(Type const& _expectedType, Expression const& _expression) -{ - solAssert(_expectedType.isValueType(), "Not implemented for non-value types."); - _expression.accept(*this); - utils().convertType(*_expression.getType(), _expectedType, true); - utils().storeInMemoryDynamic(_expectedType); -} - -void ExpressionCompiler::setLValueFromDeclaration(Declaration const& _declaration, Expression const& _expression) -{ - if (m_context.isLocalVariable(&_declaration)) - setLValue(_expression, _declaration); - else if (m_context.isStateVariable(&_declaration)) - setLValue(_expression, _declaration); - else - BOOST_THROW_EXCEPTION(InternalCompilerError() - << errinfo_sourceLocation(_expression.getLocation()) - << errinfo_comment("Identifier type not supported or identifier not found.")); -} - -void ExpressionCompiler::setLValueToStorageItem(Expression const& _expression) -{ - setLValue(_expression, *_expression.getType()); -} - -CompilerUtils ExpressionCompiler::utils() -{ - return CompilerUtils(m_context); -} - -} -} diff --git a/libsolidity/ExpressionCompiler.h b/libsolidity/ExpressionCompiler.h deleted file mode 100644 index 642560c64..000000000 --- a/libsolidity/ExpressionCompiler.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @author Gav Wood - * @date 2014 - * Solidity AST to EVM bytecode compiler for expressions. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dev { -namespace eth -{ -class AssemblyItem; // forward -} -namespace solidity { - -// forward declarations -class CompilerContext; -class CompilerUtils; -class Type; -class IntegerType; -class ArrayType; - -/** - * Compiler for expressions, i.e. converts an AST tree whose root is an Expression into a stream - * of EVM instructions. It needs a compiler context that is the same for the whole compilation - * unit. - */ -class ExpressionCompiler: private ASTConstVisitor -{ -public: - /// Appends code for a State Variable accessor function - static void appendStateVariableAccessor(CompilerContext& _context, VariableDeclaration const& _varDecl, bool _optimize = false); - - explicit ExpressionCompiler(CompilerContext& _compilerContext, bool _optimize = false): - m_optimize(_optimize), m_context(_compilerContext) {} - - /// Compile the given @a _expression and leave its value on the stack. - void compile(Expression const& _expression); - - /// Appends code to set a state variable to its initial value/expression. - void appendStateVariableInitialization(VariableDeclaration const& _varDecl); - - /// Appends code for a State Variable accessor function - void appendStateVariableAccessor(VariableDeclaration const& _varDecl); - -private: - virtual bool visit(Assignment const& _assignment) override; - virtual bool visit(UnaryOperation const& _unaryOperation) override; - virtual bool visit(BinaryOperation const& _binaryOperation) override; - virtual bool visit(FunctionCall const& _functionCall) override; - virtual bool visit(NewExpression const& _newExpression) override; - virtual void endVisit(MemberAccess const& _memberAccess) override; - virtual bool visit(IndexAccess const& _indexAccess) override; - virtual void endVisit(Identifier const& _identifier) override; - virtual void endVisit(Literal const& _literal) override; - - ///@{ - ///@name Append code for various operator types - void appendAndOrOperatorCode(BinaryOperation const& _binaryOperation); - void appendCompareOperatorCode(Token::Value _operator, Type const& _type); - void appendOrdinaryBinaryOperatorCode(Token::Value _operator, Type const& _type); - - void appendArithmeticOperatorCode(Token::Value _operator, Type const& _type); - void appendBitOperatorCode(Token::Value _operator); - void appendShiftOperatorCode(Token::Value _operator); - /// @} - - /// Appends code to call a function of the given type with the given arguments. - void appendExternalFunctionCall( - FunctionType const& _functionType, - std::vector> const& _arguments - ); - /// Appends code that evaluates a single expression and moves the result to memory. The memory offset is - /// expected to be on the stack and is updated by this call. - void appendExpressionCopyToMemory(Type const& _expectedType, Expression const& _expression); - - /// Sets the current LValue to a new one (of the appropriate type) from the given declaration. - /// Also retrieves the value if it was not requested by @a _expression. - void setLValueFromDeclaration(Declaration const& _declaration, Expression const& _expression); - /// Sets the current LValue to a StorageItem holding the type of @a _expression. The reference is assumed - /// to be on the stack. - /// Also retrieves the value if it was not requested by @a _expression. - void setLValueToStorageItem(Expression const& _expression); - /// Sets the current LValue to a new LValue constructed from the arguments. - /// Also retrieves the value if it was not requested by @a _expression. - template - void setLValue(Expression const& _expression, _Arguments const&... _arguments); - - /// @returns the CompilerUtils object containing the current context. - CompilerUtils utils(); - - bool m_optimize; - CompilerContext& m_context; - std::unique_ptr m_currentLValue; - -}; - -template -void ExpressionCompiler::setLValue(Expression const& _expression, _Arguments const&... _arguments) -{ - solAssert(!m_currentLValue, "Current LValue not reset before trying to set new one."); - std::unique_ptr<_LValueType> lvalue(new _LValueType(m_context, _arguments...)); - if (_expression.lvalueRequested()) - m_currentLValue = move(lvalue); - else - lvalue->retrieveValue(_expression.getLocation(), true); -} - -} -} diff --git a/libsolidity/GasEstimator.cpp b/libsolidity/GasEstimator.cpp deleted file mode 100644 index 01219a65b..000000000 --- a/libsolidity/GasEstimator.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Gas consumption estimator working alongside the AST. - */ - -#include "GasEstimator.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace dev::eth; -using namespace dev::solidity; - -GasEstimator::ASTGasConsumptionSelfAccumulated GasEstimator::structuralEstimation( - AssemblyItems const& _items, - vector const& _ast -) -{ - solAssert(std::count(_ast.begin(), _ast.end(), nullptr) == 0, ""); - map particularCosts; - - ControlFlowGraph cfg(_items); - for (BasicBlock const& block: cfg.optimisedBlocks()) - { - assertThrow(!!block.startState, OptimizerException, ""); - GasMeter meter(block.startState->copy()); - auto const end = _items.begin() + block.end; - for (auto iter = _items.begin() + block.begin; iter != end; ++iter) - particularCosts[iter->getLocation()] += meter.estimateMax(*iter); - } - - set finestNodes = finestNodesAtLocation(_ast); - ASTGasConsumptionSelfAccumulated gasCosts; - auto onNode = [&](ASTNode const& _node) - { - if (!finestNodes.count(&_node)) - return true; - gasCosts[&_node][0] = gasCosts[&_node][1] = particularCosts[_node.getLocation()]; - return true; - }; - auto onEdge = [&](ASTNode const& _parent, ASTNode const& _child) - { - gasCosts[&_parent][1] += gasCosts[&_child][1]; - }; - ASTReduce folder(onNode, onEdge); - for (ASTNode const* ast: _ast) - ast->accept(folder); - - return gasCosts; -} - -map GasEstimator::breakToStatementLevel( - ASTGasConsumptionSelfAccumulated const& _gasCosts, - vector const& _roots -) -{ - solAssert(std::count(_roots.begin(), _roots.end(), nullptr) == 0, ""); - // first pass: statementDepth[node] is the distance from the deepend statement to node - // in direction of the tree root (or undefined if not possible) - map statementDepth; - auto onNodeFirstPass = [&](ASTNode const& _node) - { - if (dynamic_cast(&_node)) - statementDepth[&_node] = 0; - return true; - }; - auto onEdgeFirstPass = [&](ASTNode const& _parent, ASTNode const& _child) - { - if (statementDepth.count(&_child)) - statementDepth[&_parent] = max(statementDepth[&_parent], statementDepth[&_child] + 1); - }; - ASTReduce firstPass(onNodeFirstPass, onEdgeFirstPass); - for (ASTNode const* node: _roots) - node->accept(firstPass); - - // we use the location of a node if - // - its statement depth is 0 or - // - its statement depth is undefined but the parent's statement depth is at least 1 - map gasCosts; - auto onNodeSecondPass = [&](ASTNode const& _node) - { - return statementDepth.count(&_node); - }; - auto onEdgeSecondPass = [&](ASTNode const& _parent, ASTNode const& _child) - { - bool useNode = false; - if (statementDepth.count(&_child)) - useNode = statementDepth[&_child] == 0; - else - useNode = statementDepth.count(&_parent) && statementDepth.at(&_parent) > 0; - if (useNode) - gasCosts[&_child] = _gasCosts.at(&_child)[1]; - }; - ASTReduce secondPass(onNodeSecondPass, onEdgeSecondPass); - for (ASTNode const* node: _roots) - node->accept(secondPass); - // gasCosts should only contain non-overlapping locations - return gasCosts; -} - -GasEstimator::GasConsumption GasEstimator::functionalEstimation( - AssemblyItems const& _items, - string const& _signature -) -{ - auto state = make_shared(); - - if (!_signature.empty()) - { - ExpressionClasses& classes = state->expressionClasses(); - using Id = ExpressionClasses::Id; - using Ids = vector; - Id hashValue = classes.find(u256(FixedHash<4>::Arith(FixedHash<4>(dev::sha3(_signature))))); - Id calldata = classes.find(eth::Instruction::CALLDATALOAD, Ids{classes.find(u256(0))}); - classes.forceEqual(hashValue, eth::Instruction::DIV, Ids{ - calldata, - classes.find(u256(1) << (8 * 28)) - }); - } - - PathGasMeter meter(_items); - return meter.estimateMax(0, state); -} - -GasEstimator::GasConsumption GasEstimator::functionalEstimation( - AssemblyItems const& _items, - size_t const& _offset, - FunctionDefinition const& _function -) -{ - auto state = make_shared(); - - unsigned parametersSize = CompilerUtils::getSizeOnStack(_function.getParameters()); - if (parametersSize > 16) - return GasConsumption::infinite(); - - // Store an invalid return value on the stack, so that the path estimator breaks upon reaching - // the return jump. - AssemblyItem invalidTag(PushTag, u256(-0x10)); - state->feedItem(invalidTag, true); - if (parametersSize > 0) - state->feedItem(eth::swapInstruction(parametersSize)); - - return PathGasMeter(_items).estimateMax(_offset, state); -} - -set GasEstimator::finestNodesAtLocation( - vector const& _roots -) -{ - map locations; - set nodes; - SimpleASTVisitor visitor(function(), [&](ASTNode const& _n) - { - if (!locations.count(_n.getLocation())) - { - locations[_n.getLocation()] = &_n; - nodes.insert(&_n); - } - }); - - for (ASTNode const* root: _roots) - root->accept(visitor); - return nodes; -} diff --git a/libsolidity/GasEstimator.h b/libsolidity/GasEstimator.h deleted file mode 100644 index 4020d60b3..000000000 --- a/libsolidity/GasEstimator.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Gas consumption estimator working alongside the AST. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -struct GasEstimator -{ -public: - using GasConsumption = eth::GasMeter::GasConsumption; - using ASTGasConsumption = std::map; - using ASTGasConsumptionSelfAccumulated = - std::map>; - - /// Estimates the gas consumption for every assembly item in the given assembly and stores - /// it by source location. - /// @returns a mapping from each AST node to a pair of its particular and syntactically accumulated gas costs. - static ASTGasConsumptionSelfAccumulated structuralEstimation( - eth::AssemblyItems const& _items, - std::vector const& _ast - ); - /// @returns a mapping from nodes with non-overlapping source locations to gas consumptions such that - /// the following source locations are part of the mapping: - /// 1. source locations of statements that do not contain other statements - /// 2. maximal source locations that do not overlap locations coming from the first rule - static ASTGasConsumption breakToStatementLevel( - ASTGasConsumptionSelfAccumulated const& _gasCosts, - std::vector const& _roots - ); - - /// @returns the estimated gas consumption by the (public or external) function with the - /// given signature. If no signature is given, estimates the maximum gas usage. - static GasConsumption functionalEstimation( - eth::AssemblyItems const& _items, - std::string const& _signature = "" - ); - - /// @returns the estimated gas consumption by the given function which starts at the given - /// offset into the list of assembly items. - /// @note this does not work correctly for recursive functions. - static GasConsumption functionalEstimation( - eth::AssemblyItems const& _items, - size_t const& _offset, - FunctionDefinition const& _function - ); - -private: - /// @returns the set of AST nodes which are the finest nodes at their location. - static std::set finestNodesAtLocation(std::vector const& _roots); -}; - -} -} diff --git a/libsolidity/GlobalContext.cpp b/libsolidity/GlobalContext.cpp deleted file mode 100644 index 80cebd760..000000000 --- a/libsolidity/GlobalContext.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @author Gav Wood - * @date 2014 - * Container of the (implicit and explicit) global objects. - */ - -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -GlobalContext::GlobalContext(): -m_magicVariables(vector>{make_shared("block", make_shared(MagicType::Kind::Block)), - make_shared("msg", make_shared(MagicType::Kind::Message)), - make_shared("tx", make_shared(MagicType::Kind::Transaction)), - make_shared("now", make_shared(256)), - make_shared("suicide", - make_shared(strings{"address"}, strings{}, FunctionType::Location::Suicide)), - make_shared("sha3", - make_shared(strings(), strings{"bytes32"}, FunctionType::Location::SHA3, true)), - make_shared("log0", - make_shared(strings{"bytes32"}, strings{}, FunctionType::Location::Log0)), - make_shared("log1", - make_shared(strings{"bytes32", "bytes32"}, strings{}, FunctionType::Location::Log1)), - make_shared("log2", - make_shared(strings{"bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Location::Log2)), - make_shared("log3", - make_shared(strings{"bytes32", "bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Location::Log3)), - make_shared("log4", - make_shared(strings{"bytes32", "bytes32", "bytes32", "bytes32", "bytes32"}, strings{}, FunctionType::Location::Log4)), - make_shared("sha256", - make_shared(strings(), strings{"bytes32"}, FunctionType::Location::SHA256, true)), - make_shared("ecrecover", - make_shared(strings{"bytes32", "uint8", "bytes32", "bytes32"}, strings{"address"}, FunctionType::Location::ECRecover)), - make_shared("ripemd160", - make_shared(strings(), strings{"bytes20"}, FunctionType::Location::RIPEMD160, true))}) -{ -} - -void GlobalContext::setCurrentContract(ContractDefinition const& _contract) -{ - m_currentContract = &_contract; -} - -vector GlobalContext::getDeclarations() const -{ - vector declarations; - declarations.reserve(m_magicVariables.size()); - for (ASTPointer const& variable: m_magicVariables) - declarations.push_back(variable.get()); - return declarations; -} - -MagicVariableDeclaration const* GlobalContext::getCurrentThis() const -{ - if (!m_thisPointer[m_currentContract]) - m_thisPointer[m_currentContract] = make_shared( - "this", make_shared(*m_currentContract)); - return m_thisPointer[m_currentContract].get(); - -} - -MagicVariableDeclaration const* GlobalContext::getCurrentSuper() const -{ - if (!m_superPointer[m_currentContract]) - m_superPointer[m_currentContract] = make_shared( - "super", make_shared(*m_currentContract, true)); - return m_superPointer[m_currentContract].get(); -} - -} -} diff --git a/libsolidity/GlobalContext.h b/libsolidity/GlobalContext.h deleted file mode 100644 index f861c67d7..000000000 --- a/libsolidity/GlobalContext.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Container of the (implicit and explicit) global objects. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -class Type; // forward - -/** - * Container for all global objects which look like AST nodes, but are not part of the AST - * that is currently being compiled. - * @note must not be destroyed or moved during compilation as its objects can be referenced from - * other objects. - */ -class GlobalContext: private boost::noncopyable -{ -public: - GlobalContext(); - void setCurrentContract(ContractDefinition const& _contract); - MagicVariableDeclaration const* getCurrentThis() const; - MagicVariableDeclaration const* getCurrentSuper() const; - - /// @returns a vector of all implicit global declarations excluding "this". - std::vector getDeclarations() const; - -private: - std::vector> m_magicVariables; - ContractDefinition const* m_currentContract = nullptr; - std::map> mutable m_thisPointer; - std::map> mutable m_superPointer; -}; - -} -} diff --git a/libsolidity/InterfaceHandler.cpp b/libsolidity/InterfaceHandler.cpp deleted file mode 100644 index c6f8553d8..000000000 --- a/libsolidity/InterfaceHandler.cpp +++ /dev/null @@ -1,446 +0,0 @@ - -#include -#include -#include -using namespace std; - -namespace dev -{ -namespace solidity -{ - -/* -- public -- */ - -InterfaceHandler::InterfaceHandler() -{ - m_lastTag = DocTagType::None; -} - -string InterfaceHandler::getDocumentation( - ContractDefinition const& _contractDef, - DocumentationType _type -) -{ - switch(_type) - { - case DocumentationType::NatspecUser: - return userDocumentation(_contractDef); - case DocumentationType::NatspecDev: - return devDocumentation(_contractDef); - case DocumentationType::ABIInterface: - return getABIInterface(_contractDef); - case DocumentationType::ABISolidityInterface: - return getABISolidityInterface(_contractDef); - } - - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation type")); - return ""; -} - -string InterfaceHandler::getABIInterface(ContractDefinition const& _contractDef) -{ - Json::Value abi(Json::arrayValue); - - auto populateParameters = [](vector const& _paramNames, vector const& _paramTypes) - { - Json::Value params(Json::arrayValue); - solAssert(_paramNames.size() == _paramTypes.size(), "Names and types vector size does not match"); - for (unsigned i = 0; i < _paramNames.size(); ++i) - { - Json::Value param; - param["name"] = _paramNames[i]; - param["type"] = _paramTypes[i]; - params.append(param); - } - return params; - }; - - for (auto it: _contractDef.getInterfaceFunctions()) - { - auto externalFunctionType = it.second->externalFunctionType(); - Json::Value method; - method["type"] = "function"; - method["name"] = it.second->getDeclaration().getName(); - method["constant"] = it.second->isConstant(); - method["inputs"] = populateParameters( - externalFunctionType->getParameterNames(), - externalFunctionType->getParameterTypeNames() - ); - method["outputs"] = populateParameters( - externalFunctionType->getReturnParameterNames(), - externalFunctionType->getReturnParameterTypeNames() - ); - abi.append(method); - } - if (_contractDef.getConstructor()) - { - Json::Value method; - method["type"] = "constructor"; - auto externalFunction = FunctionType(*_contractDef.getConstructor()).externalFunctionType(); - solAssert(!!externalFunction, ""); - method["inputs"] = populateParameters( - externalFunction->getParameterNames(), - externalFunction->getParameterTypeNames() - ); - abi.append(method); - } - - for (auto const& it: _contractDef.getInterfaceEvents()) - { - Json::Value event; - event["type"] = "event"; - event["name"] = it->getName(); - event["anonymous"] = it->isAnonymous(); - Json::Value params(Json::arrayValue); - for (auto const& p: it->getParameters()) - { - Json::Value input; - input["name"] = p->getName(); - input["type"] = p->getType()->toString(true); - input["indexed"] = p->isIndexed(); - params.append(input); - } - event["inputs"] = params; - abi.append(event); - } - return Json::FastWriter().write(abi); -} - -string InterfaceHandler::getABISolidityInterface(ContractDefinition const& _contractDef) -{ - string ret = "contract " + _contractDef.getName() + "{"; - - auto populateParameters = [](vector const& _paramNames, vector const& _paramTypes) - { - string r = ""; - solAssert(_paramNames.size() == _paramTypes.size(), "Names and types vector size does not match"); - for (unsigned i = 0; i < _paramNames.size(); ++i) - r += (r.size() ? "," : "(") + _paramTypes[i] + " " + _paramNames[i]; - return r.size() ? r + ")" : "()"; - }; - if (_contractDef.getConstructor()) - { - auto externalFunction = FunctionType(*_contractDef.getConstructor()).externalFunctionType(); - solAssert(!!externalFunction, ""); - ret += - "function " + - _contractDef.getName() + - populateParameters(externalFunction->getParameterNames(), externalFunction->getParameterTypeNames()) + - ";"; - } - for (auto const& it: _contractDef.getInterfaceFunctions()) - { - ret += "function " + it.second->getDeclaration().getName() + - populateParameters(it.second->getParameterNames(), it.second->getParameterTypeNames()) + - (it.second->isConstant() ? "constant " : ""); - if (it.second->getReturnParameterTypes().size()) - ret += "returns" + populateParameters(it.second->getReturnParameterNames(), it.second->getReturnParameterTypeNames()); - else if (ret.back() == ' ') - ret.pop_back(); - ret += ";"; - } - - return ret + "}"; -} - -string InterfaceHandler::userDocumentation(ContractDefinition const& _contractDef) -{ - Json::Value doc; - Json::Value methods(Json::objectValue); - - for (auto const& it: _contractDef.getInterfaceFunctions()) - { - Json::Value user; - auto strPtr = it.second->getDocumentation(); - if (strPtr) - { - resetUser(); - parseDocString(*strPtr, CommentOwner::Function); - if (!m_notice.empty()) - {// since @notice is the only user tag if missing function should not appear - user["notice"] = Json::Value(m_notice); - methods[it.second->externalSignature()] = user; - } - } - } - doc["methods"] = methods; - - return Json::StyledWriter().write(doc); -} - -string InterfaceHandler::devDocumentation(ContractDefinition const& _contractDef) -{ - // LTODO: Somewhere in this function warnings for mismatch of param names - // should be thrown - Json::Value doc; - Json::Value methods(Json::objectValue); - - auto contractDoc = _contractDef.getDocumentation(); - if (contractDoc) - { - m_contractAuthor.clear(); - m_title.clear(); - parseDocString(*contractDoc, CommentOwner::Contract); - - if (!m_contractAuthor.empty()) - doc["author"] = m_contractAuthor; - - if (!m_title.empty()) - doc["title"] = m_title; - } - - for (auto const& it: _contractDef.getInterfaceFunctions()) - { - Json::Value method; - auto strPtr = it.second->getDocumentation(); - if (strPtr) - { - resetDev(); - parseDocString(*strPtr, CommentOwner::Function); - - if (!m_dev.empty()) - method["details"] = Json::Value(m_dev); - - if (!m_author.empty()) - method["author"] = m_author; - - Json::Value params(Json::objectValue); - vector paramNames = it.second->getParameterNames(); - for (auto const& pair: m_params) - { - if (find(paramNames.begin(), paramNames.end(), pair.first) == paramNames.end()) - // LTODO: mismatching parameter name, throw some form of warning and not just an exception - BOOST_THROW_EXCEPTION( - DocstringParsingError() << - errinfo_comment("documented parameter \"" + pair.first + "\" not found in the parameter list of the function.") - ); - params[pair.first] = pair.second; - } - - if (!m_params.empty()) - method["params"] = params; - - if (!m_return.empty()) - method["return"] = m_return; - - if (!method.empty()) // add the function, only if we have any documentation to add - methods[it.second->externalSignature()] = method; - } - } - doc["methods"] = methods; - - return Json::StyledWriter().write(doc); -} - -/* -- private -- */ -void InterfaceHandler::resetUser() -{ - m_notice.clear(); -} - -void InterfaceHandler::resetDev() -{ - m_dev.clear(); - m_author.clear(); - m_return.clear(); - m_params.clear(); -} - -static inline string::const_iterator skipLineOrEOS( - string::const_iterator _nlPos, - string::const_iterator _end -) -{ - return (_nlPos == _end) ? _end : ++_nlPos; -} - -string::const_iterator InterfaceHandler::parseDocTagLine( - string::const_iterator _pos, - string::const_iterator _end, - string& _tagString, - DocTagType _tagType, - bool _appending -) -{ - auto nlPos = find(_pos, _end, '\n'); - if (_appending && _pos < _end && *_pos != ' ') - _tagString += " "; - copy(_pos, nlPos, back_inserter(_tagString)); - m_lastTag = _tagType; - return skipLineOrEOS(nlPos, _end); -} - -string::const_iterator InterfaceHandler::parseDocTagParam( - string::const_iterator _pos, - string::const_iterator _end -) -{ - // find param name - auto currPos = find(_pos, _end, ' '); - if (currPos == _end) - BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("End of param name not found" + string(_pos, _end))); - - - auto paramName = string(_pos, currPos); - - currPos += 1; - auto nlPos = find(currPos, _end, '\n'); - auto paramDesc = string(currPos, nlPos); - m_params.push_back(make_pair(paramName, paramDesc)); - - m_lastTag = DocTagType::Param; - return skipLineOrEOS(nlPos, _end); -} - -string::const_iterator InterfaceHandler::appendDocTagParam( - string::const_iterator _pos, - string::const_iterator _end -) -{ - // Should never be called with an empty vector - solAssert(!m_params.empty(), "Internal: Tried to append to empty parameter"); - - auto pair = m_params.back(); - if (_pos < _end && *_pos != ' ') - pair.second += " "; - auto nlPos = find(_pos, _end, '\n'); - copy(_pos, nlPos, back_inserter(pair.second)); - - m_params.at(m_params.size() - 1) = pair; - - return skipLineOrEOS(nlPos, _end); -} - -string::const_iterator InterfaceHandler::parseDocTag( - string::const_iterator _pos, - string::const_iterator _end, - string const& _tag, - CommentOwner _owner -) -{ - // LTODO: need to check for @(start of a tag) between here and the end of line - // for all cases. Also somehow automate list of acceptable tags for each - // language construct since current way does not scale well. - if (m_lastTag == DocTagType::None || _tag != "") - { - if (_tag == "dev") - return parseDocTagLine(_pos, _end, m_dev, DocTagType::Dev, false); - else if (_tag == "notice") - return parseDocTagLine(_pos, _end, m_notice, DocTagType::Notice, false); - else if (_tag == "return") - return parseDocTagLine(_pos, _end, m_return, DocTagType::Return, false); - else if (_tag == "author") - { - if (_owner == CommentOwner::Contract) - return parseDocTagLine(_pos, _end, m_contractAuthor, DocTagType::Author, false); - else if (_owner == CommentOwner::Function) - return parseDocTagLine(_pos, _end, m_author, DocTagType::Author, false); - else - // LTODO: for now this else makes no sense but later comments will go to more language constructs - BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@author tag is legal only for contracts")); - } - else if (_tag == "title") - { - if (_owner == CommentOwner::Contract) - return parseDocTagLine(_pos, _end, m_title, DocTagType::Title, false); - else - // LTODO: Unknown tag, throw some form of warning and not just an exception - BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@title tag is legal only for contracts")); - } - else if (_tag == "param") - return parseDocTagParam(_pos, _end); - else - // LTODO: Unknown tag, throw some form of warning and not just an exception - BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("Unknown tag " + _tag + " encountered")); - } - else - return appendDocTag(_pos, _end, _owner); -} - -string::const_iterator InterfaceHandler::appendDocTag( - string::const_iterator _pos, - string::const_iterator _end, - CommentOwner _owner -) -{ - switch (m_lastTag) - { - case DocTagType::Dev: - return parseDocTagLine(_pos, _end, m_dev, DocTagType::Dev, true); - case DocTagType::Notice: - return parseDocTagLine(_pos, _end, m_notice, DocTagType::Notice, true); - case DocTagType::Return: - return parseDocTagLine(_pos, _end, m_return, DocTagType::Return, true); - case DocTagType::Author: - if (_owner == CommentOwner::Contract) - return parseDocTagLine(_pos, _end, m_contractAuthor, DocTagType::Author, true); - else if (_owner == CommentOwner::Function) - return parseDocTagLine(_pos, _end, m_author, DocTagType::Author, true); - else - // LTODO: Unknown tag, throw some form of warning and not just an exception - BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@author tag in illegal comment")); - case DocTagType::Title: - if (_owner == CommentOwner::Contract) - return parseDocTagLine(_pos, _end, m_title, DocTagType::Title, true); - else - // LTODO: Unknown tag, throw some form of warning and not just an exception - BOOST_THROW_EXCEPTION(DocstringParsingError() << errinfo_comment("@title tag in illegal comment")); - case DocTagType::Param: - return appendDocTagParam(_pos, _end); - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Internal: Illegal documentation tag type")); - break; - } -} - -static inline string::const_iterator getFirstSpaceOrNl( - string::const_iterator _pos, - string::const_iterator _end -) -{ - auto spacePos = find(_pos, _end, ' '); - auto nlPos = find(_pos, _end, '\n'); - return (spacePos < nlPos) ? spacePos : nlPos; -} - -void InterfaceHandler::parseDocString(string const& _string, CommentOwner _owner) -{ - auto currPos = _string.begin(); - auto end = _string.end(); - - while (currPos != end) - { - auto tagPos = find(currPos, end, '@'); - auto nlPos = find(currPos, end, '\n'); - - if (tagPos != end && tagPos < nlPos) - { - // we found a tag - auto tagNameEndPos = getFirstSpaceOrNl(tagPos, end); - if (tagNameEndPos == end) - BOOST_THROW_EXCEPTION( - DocstringParsingError() << - errinfo_comment("End of tag " + string(tagPos, tagNameEndPos) + "not found")); - - currPos = parseDocTag(tagNameEndPos + 1, end, string(tagPos + 1, tagNameEndPos), _owner); - } - else if (m_lastTag != DocTagType::None) // continuation of the previous tag - currPos = appendDocTag(currPos, end, _owner); - else if (currPos != end) - { - // if it begins without a tag then consider it as @notice - if (currPos == _string.begin()) - { - currPos = parseDocTag(currPos, end, "notice", CommentOwner::Function); - continue; - } - else if (nlPos == end) //end of text - return; - // else skip the line if a newline was found and we get here - currPos = nlPos + 1; - } - } -} - -} //solidity NS -} // dev NS diff --git a/libsolidity/InterfaceHandler.h b/libsolidity/InterfaceHandler.h deleted file mode 100644 index 7784dbd7f..000000000 --- a/libsolidity/InterfaceHandler.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Lefteris - * @date 2014 - * Takes the parsed AST and produces the Natspec - * documentation and the ABI interface - * https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format - * - * Can generally deal with JSON files - */ - -#pragma once - -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -// Forward declarations -class ContractDefinition; -enum class DocumentationType: uint8_t; - -enum class DocTagType: uint8_t -{ - None = 0, - Dev, - Notice, - Param, - Return, - Author, - Title -}; - -enum class CommentOwner -{ - Contract, - Function -}; - -class InterfaceHandler -{ -public: - InterfaceHandler(); - - /// Get the given type of documentation - /// @param _contractDef The contract definition - /// @param _type The type of the documentation. Can be one of the - /// types provided by @c DocumentationType - /// @return A string with the json representation of provided type - std::string getDocumentation( - ContractDefinition const& _contractDef, - DocumentationType _type - ); - /// Get the ABI Interface of the contract - /// @param _contractDef The contract definition - /// @return A string with the json representation of the contract's ABI Interface - std::string getABIInterface(ContractDefinition const& _contractDef); - std::string getABISolidityInterface(ContractDefinition const& _contractDef); - /// Get the User documentation of the contract - /// @param _contractDef The contract definition - /// @return A string with the json representation of the contract's user documentation - std::string userDocumentation(ContractDefinition const& _contractDef); - /// Genereates the Developer's documentation of the contract - /// @param _contractDef The contract definition - /// @return A string with the json representation - /// of the contract's developer documentation - std::string devDocumentation(ContractDefinition const& _contractDef); - -private: - void resetUser(); - void resetDev(); - - std::string::const_iterator parseDocTagLine( - std::string::const_iterator _pos, - std::string::const_iterator _end, - std::string& _tagString, - DocTagType _tagType, - bool _appending - ); - std::string::const_iterator parseDocTagParam( - std::string::const_iterator _pos, - std::string::const_iterator _end - ); - std::string::const_iterator appendDocTagParam( - std::string::const_iterator _pos, - std::string::const_iterator _end - ); - void parseDocString(std::string const& _string, CommentOwner _owner); - std::string::const_iterator appendDocTag( - std::string::const_iterator _pos, - std::string::const_iterator _end, - CommentOwner _owner - ); - std::string::const_iterator parseDocTag( - std::string::const_iterator _pos, - std::string::const_iterator _end, - std::string const& _tag, - CommentOwner _owner - ); - - // internal state - DocTagType m_lastTag; - std::string m_notice; - std::string m_dev; - std::string m_return; - std::string m_contractAuthor; - std::string m_author; - std::string m_title; - std::vector> m_params; -}; - -} //solidity NS -} // dev NS diff --git a/libsolidity/LValue.cpp b/libsolidity/LValue.cpp deleted file mode 100644 index 5c43fb82a..000000000 --- a/libsolidity/LValue.cpp +++ /dev/null @@ -1,457 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * LValues for use in the expresison compiler. - */ - -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace solidity; - - -StackVariable::StackVariable(CompilerContext& _compilerContext, Declaration const& _declaration): - LValue(_compilerContext, *_declaration.getType()), - m_baseStackOffset(m_context.getBaseStackOffsetOfVariable(_declaration)), - m_size(m_dataType.getSizeOnStack()) -{ -} - -void StackVariable::retrieveValue(SourceLocation const& _location, bool) const -{ - unsigned stackPos = m_context.baseToCurrentStackOffset(m_baseStackOffset); - if (stackPos + 1 > 16) //@todo correct this by fetching earlier or moving to memory - BOOST_THROW_EXCEPTION( - CompilerError() << - errinfo_sourceLocation(_location) << - errinfo_comment("Stack too deep, try removing local variables.") - ); - solAssert(stackPos + 1 >= m_size, "Size and stack pos mismatch."); - for (unsigned i = 0; i < m_size; ++i) - m_context << eth::dupInstruction(stackPos + 1); -} - -void StackVariable::storeValue(Type const&, SourceLocation const& _location, bool _move) const -{ - unsigned stackDiff = m_context.baseToCurrentStackOffset(m_baseStackOffset) - m_size + 1; - if (stackDiff > 16) - BOOST_THROW_EXCEPTION( - CompilerError() << - errinfo_sourceLocation(_location) << - errinfo_comment("Stack too deep, try removing local variables.") - ); - else if (stackDiff > 0) - for (unsigned i = 0; i < m_size; ++i) - m_context << eth::swapInstruction(stackDiff) << eth::Instruction::POP; - if (!_move) - retrieveValue(_location); -} - -void StackVariable::setToZero(SourceLocation const& _location, bool) const -{ - CompilerUtils(m_context).pushZeroValue(m_dataType); - storeValue(m_dataType, _location, true); -} - -MemoryItem::MemoryItem(CompilerContext& _compilerContext, Type const& _type, bool _padded): - LValue(_compilerContext, _type), - m_padded(_padded) -{ -} - -void MemoryItem::retrieveValue(SourceLocation const&, bool _remove) const -{ - if (m_dataType.isValueType()) - { - if (!_remove) - m_context << eth::Instruction::DUP1; - CompilerUtils(m_context).loadFromMemoryDynamic(m_dataType, false, m_padded, false); - } - else - m_context << eth::Instruction::MLOAD; -} - -void MemoryItem::storeValue(Type const& _sourceType, SourceLocation const&, bool _move) const -{ - CompilerUtils utils(m_context); - if (m_dataType.isValueType()) - { - solAssert(_sourceType.isValueType(), ""); - utils.moveIntoStack(_sourceType.getSizeOnStack()); - utils.convertType(_sourceType, m_dataType, true); - if (!_move) - { - utils.moveToStackTop(m_dataType.getSizeOnStack()); - utils.copyToStackTop(2, m_dataType.getSizeOnStack()); - } - utils.storeInMemoryDynamic(m_dataType, m_padded); - m_context << eth::Instruction::POP; - } - else - { - solAssert(_sourceType == m_dataType, "Conversion not implemented for assignment to memory."); - - solAssert(m_dataType.getSizeOnStack() == 1, ""); - if (!_move) - m_context << eth::Instruction::DUP2 << eth::Instruction::SWAP1; - // stack: [value] value lvalue - // only store the reference - m_context << eth::Instruction::MSTORE; - } -} - -void MemoryItem::setToZero(SourceLocation const&, bool _removeReference) const -{ - CompilerUtils utils(m_context); - if (!_removeReference) - m_context << eth::Instruction::DUP1; - utils.pushZeroValue(m_dataType); - utils.storeInMemoryDynamic(m_dataType, m_padded); - m_context << eth::Instruction::POP; -} - -StorageItem::StorageItem(CompilerContext& _compilerContext, Declaration const& _declaration): - StorageItem(_compilerContext, *_declaration.getType()) -{ - auto const& location = m_context.getStorageLocationOfVariable(_declaration); - m_context << location.first << u256(location.second); -} - -StorageItem::StorageItem(CompilerContext& _compilerContext, Type const& _type): - LValue(_compilerContext, _type) -{ - if (m_dataType.isValueType()) - { - solAssert(m_dataType.getStorageSize() == m_dataType.getSizeOnStack(), ""); - solAssert(m_dataType.getStorageSize() == 1, "Invalid storage size."); - } -} - -void StorageItem::retrieveValue(SourceLocation const&, bool _remove) const -{ - // stack: storage_key storage_offset - if (!m_dataType.isValueType()) - { - solAssert(m_dataType.getSizeOnStack() == 1, "Invalid storage ref size."); - if (_remove) - m_context << eth::Instruction::POP; // remove byte offset - else - m_context << eth::Instruction::DUP2; - return; - } - if (!_remove) - CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack()); - if (m_dataType.getStorageBytes() == 32) - m_context << eth::Instruction::POP << eth::Instruction::SLOAD; - else - { - m_context - << eth::Instruction::SWAP1 << eth::Instruction::SLOAD << eth::Instruction::SWAP1 - << u256(0x100) << eth::Instruction::EXP << eth::Instruction::SWAP1 << eth::Instruction::DIV; - if (m_dataType.getCategory() == Type::Category::FixedBytes) - m_context << (u256(0x1) << (256 - 8 * m_dataType.getStorageBytes())) << eth::Instruction::MUL; - else if ( - m_dataType.getCategory() == Type::Category::Integer && - dynamic_cast(m_dataType).isSigned() - ) - m_context << u256(m_dataType.getStorageBytes() - 1) << eth::Instruction::SIGNEXTEND; - else - m_context << ((u256(0x1) << (8 * m_dataType.getStorageBytes())) - 1) << eth::Instruction::AND; - } -} - -void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _location, bool _move) const -{ - CompilerUtils utils(m_context); - // stack: value storage_key storage_offset - if (m_dataType.isValueType()) - { - solAssert(m_dataType.getStorageBytes() <= 32, "Invalid storage bytes size."); - solAssert(m_dataType.getStorageBytes() > 0, "Invalid storage bytes size."); - if (m_dataType.getStorageBytes() == 32) - { - // offset should be zero - m_context << eth::Instruction::POP; - if (!_move) - m_context << eth::Instruction::DUP2 << eth::Instruction::SWAP1; - m_context << eth::Instruction::SSTORE; - } - else - { - // OR the value into the other values in the storage slot - m_context << u256(0x100) << eth::Instruction::EXP; - // stack: value storage_ref multiplier - // fetch old value - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; - // stack: value storege_ref multiplier old_full_value - // clear bytes in old value - m_context - << eth::Instruction::DUP2 << ((u256(1) << (8 * m_dataType.getStorageBytes())) - 1) - << eth::Instruction::MUL; - m_context << eth::Instruction::NOT << eth::Instruction::AND; - // stack: value storage_ref multiplier cleared_value - m_context - << eth::Instruction::SWAP1 << eth::Instruction::DUP4; - // stack: value storage_ref cleared_value multiplier value - if (m_dataType.getCategory() == Type::Category::FixedBytes) - m_context - << (u256(0x1) << (256 - 8 * dynamic_cast(m_dataType).numBytes())) - << eth::Instruction::SWAP1 << eth::Instruction::DIV; - else if ( - m_dataType.getCategory() == Type::Category::Integer && - dynamic_cast(m_dataType).isSigned() - ) - // remove the higher order bits - m_context - << (u256(1) << (8 * (32 - m_dataType.getStorageBytes()))) - << eth::Instruction::SWAP1 - << eth::Instruction::DUP2 - << eth::Instruction::MUL - << eth::Instruction::DIV; - m_context << eth::Instruction::MUL << eth::Instruction::OR; - // stack: value storage_ref updated_value - m_context << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; - if (_move) - m_context << eth::Instruction::POP; - } - } - else - { - solAssert( - _sourceType.getCategory() == m_dataType.getCategory(), - "Wrong type conversation for assignment."); - if (m_dataType.getCategory() == Type::Category::Array) - { - m_context << eth::Instruction::POP; // remove byte offset - ArrayUtils(m_context).copyArrayToStorage( - dynamic_cast(m_dataType), - dynamic_cast(_sourceType)); - if (_move) - m_context << eth::Instruction::POP; - } - else if (m_dataType.getCategory() == Type::Category::Struct) - { - // stack layout: source_ref target_ref target_offset - // note that we have structs, so offset should be zero and are ignored - m_context << eth::Instruction::POP; - auto const& structType = dynamic_cast(m_dataType); - auto const& sourceType = dynamic_cast(_sourceType); - solAssert( - structType.structDefinition() == sourceType.structDefinition(), - "Struct assignment with conversion." - ); - solAssert(sourceType.location() != DataLocation::CallData, "Structs in calldata not supported."); - for (auto const& member: structType.getMembers()) - { - // assign each member that is not a mapping - TypePointer const& memberType = member.type; - if (memberType->getCategory() == Type::Category::Mapping) - continue; - TypePointer sourceMemberType = sourceType.getMemberType(member.name); - if (sourceType.location() == DataLocation::Storage) - { - // stack layout: source_ref target_ref - pair const& offsets = sourceType.getStorageOffsetsOfMember(member.name); - m_context << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD; - m_context << u256(offsets.second); - // stack: source_ref target_ref source_member_ref source_member_off - StorageItem(m_context, *sourceMemberType).retrieveValue(_location, true); - // stack: source_ref target_ref source_value... - } - else - { - solAssert(sourceType.location() == DataLocation::Memory, ""); - // stack layout: source_ref target_ref - TypePointer sourceMemberType = sourceType.getMemberType(member.name); - m_context << sourceType.memoryOffsetOfMember(member.name); - m_context << eth::Instruction::DUP3 << eth::Instruction::ADD; - MemoryItem(m_context, *sourceMemberType).retrieveValue(_location, true); - // stack layout: source_ref target_ref source_value... - } - unsigned stackSize = sourceMemberType->getSizeOnStack(); - pair const& offsets = structType.getStorageOffsetsOfMember(member.name); - m_context << eth::dupInstruction(1 + stackSize) << offsets.first << eth::Instruction::ADD; - m_context << u256(offsets.second); - // stack: source_ref target_ref target_off source_value... target_member_ref target_member_byte_off - StorageItem(m_context, *memberType).storeValue(*sourceMemberType, _location, true); - } - // stack layout: source_ref target_ref - solAssert(sourceType.getSizeOnStack() == 1, "Unexpected source size."); - if (_move) - utils.popStackSlots(2); - else - m_context << eth::Instruction::SWAP1 << eth::Instruction::POP; - } - else - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_sourceLocation(_location) - << errinfo_comment("Invalid non-value type for assignment.")); - } -} - -void StorageItem::setToZero(SourceLocation const&, bool _removeReference) const -{ - if (m_dataType.getCategory() == Type::Category::Array) - { - if (!_removeReference) - CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack()); - ArrayUtils(m_context).clearArray(dynamic_cast(m_dataType)); - } - else if (m_dataType.getCategory() == Type::Category::Struct) - { - // stack layout: storage_key storage_offset - // @todo this can be improved: use StorageItem for non-value types, and just store 0 in - // all slots that contain value types later. - auto const& structType = dynamic_cast(m_dataType); - for (auto const& member: structType.getMembers()) - { - // zero each member that is not a mapping - TypePointer const& memberType = member.type; - if (memberType->getCategory() == Type::Category::Mapping) - continue; - pair const& offsets = structType.getStorageOffsetsOfMember(member.name); - m_context - << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD - << u256(offsets.second); - StorageItem(m_context, *memberType).setToZero(); - } - if (_removeReference) - m_context << eth::Instruction::POP << eth::Instruction::POP; - } - else - { - solAssert(m_dataType.isValueType(), "Clearing of unsupported type requested: " + m_dataType.toString()); - if (!_removeReference) - CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack()); - if (m_dataType.getStorageBytes() == 32) - { - // offset should be zero - m_context - << eth::Instruction::POP << u256(0) - << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; - } - else - { - m_context << u256(0x100) << eth::Instruction::EXP; - // stack: storage_ref multiplier - // fetch old value - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; - // stack: storege_ref multiplier old_full_value - // clear bytes in old value - m_context - << eth::Instruction::SWAP1 << ((u256(1) << (8 * m_dataType.getStorageBytes())) - 1) - << eth::Instruction::MUL; - m_context << eth::Instruction::NOT << eth::Instruction::AND; - // stack: storage_ref cleared_value - m_context << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; - } - } -} - -/// Used in StorageByteArrayElement -static FixedBytesType byteType(1); - -StorageByteArrayElement::StorageByteArrayElement(CompilerContext& _compilerContext): - LValue(_compilerContext, byteType) -{ -} - -void StorageByteArrayElement::retrieveValue(SourceLocation const&, bool _remove) const -{ - // stack: ref byte_number - if (_remove) - m_context << eth::Instruction::SWAP1 << eth::Instruction::SLOAD - << eth::Instruction::SWAP1 << eth::Instruction::BYTE; - else - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD - << eth::Instruction::DUP2 << eth::Instruction::BYTE; - m_context << (u256(1) << (256 - 8)) << eth::Instruction::MUL; -} - -void StorageByteArrayElement::storeValue(Type const&, SourceLocation const&, bool _move) const -{ - // stack: value ref byte_number - m_context << u256(31) << eth::Instruction::SUB << u256(0x100) << eth::Instruction::EXP; - // stack: value ref (1<<(8*(31-byte_number))) - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; - // stack: value ref (1<<(8*(31-byte_number))) old_full_value - // clear byte in old value - m_context << eth::Instruction::DUP2 << u256(0xff) << eth::Instruction::MUL - << eth::Instruction::NOT << eth::Instruction::AND; - // stack: value ref (1<<(32-byte_number)) old_full_value_with_cleared_byte - m_context << eth::Instruction::SWAP1; - m_context << (u256(1) << (256 - 8)) << eth::Instruction::DUP5 << eth::Instruction::DIV - << eth::Instruction::MUL << eth::Instruction::OR; - // stack: value ref new_full_value - m_context << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; - if (_move) - m_context << eth::Instruction::POP; -} - -void StorageByteArrayElement::setToZero(SourceLocation const&, bool _removeReference) const -{ - // stack: ref byte_number - if (!_removeReference) - m_context << eth::Instruction::DUP2 << eth::Instruction::DUP2; - m_context << u256(31) << eth::Instruction::SUB << u256(0x100) << eth::Instruction::EXP; - // stack: ref (1<<(8*(31-byte_number))) - m_context << eth::Instruction::DUP2 << eth::Instruction::SLOAD; - // stack: ref (1<<(8*(31-byte_number))) old_full_value - // clear byte in old value - m_context << eth::Instruction::SWAP1 << u256(0xff) << eth::Instruction::MUL; - m_context << eth::Instruction::NOT << eth::Instruction::AND; - // stack: ref old_full_value_with_cleared_byte - m_context << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; -} - -StorageArrayLength::StorageArrayLength(CompilerContext& _compilerContext, const ArrayType& _arrayType): - LValue(_compilerContext, *_arrayType.getMemberType("length")), - m_arrayType(_arrayType) -{ - solAssert(m_arrayType.isDynamicallySized(), ""); -} - -void StorageArrayLength::retrieveValue(SourceLocation const&, bool _remove) const -{ - if (!_remove) - m_context << eth::Instruction::DUP1; - m_context << eth::Instruction::SLOAD; -} - -void StorageArrayLength::storeValue(Type const&, SourceLocation const&, bool _move) const -{ - if (_move) - m_context << eth::Instruction::SWAP1; - else - m_context << eth::Instruction::DUP2; - ArrayUtils(m_context).resizeDynamicArray(m_arrayType); -} - -void StorageArrayLength::setToZero(SourceLocation const&, bool _removeReference) const -{ - if (!_removeReference) - m_context << eth::Instruction::DUP1; - ArrayUtils(m_context).clearDynamicArray(m_arrayType); -} diff --git a/libsolidity/LValue.h b/libsolidity/LValue.h deleted file mode 100644 index a93df9f9d..000000000 --- a/libsolidity/LValue.h +++ /dev/null @@ -1,196 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * LValues for use in the expresison compiler. - */ - -#pragma once - -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -class Declaration; -class Type; -class ArrayType; -class CompilerContext; - -/** - * Abstract class used to retrieve, delete and store data in lvalues/variables. - */ -class LValue -{ -protected: - LValue(CompilerContext& _compilerContext, Type const& _dataType): - m_context(_compilerContext), m_dataType(_dataType) {} - -public: - /// @returns the number of stack slots occupied by the lvalue reference - virtual unsigned sizeOnStack() const { return 1; } - /// Copies the value of the current lvalue to the top of the stack and, if @a _remove is true, - /// also removes the reference from the stack. - /// @a _location source location of the current expression, used for error reporting. - virtual void retrieveValue(SourceLocation const& _location, bool _remove = false) const = 0; - /// Moves a value from the stack to the lvalue. Removes the value if @a _move is true. - /// @a _location is the source location of the expression that caused this operation. - /// Stack pre: value [lvalue_ref] - /// Stack post: if !_move: value_of(lvalue_ref) - virtual void storeValue(Type const& _sourceType, - SourceLocation const& _location = SourceLocation(), bool _move = false) const = 0; - /// Stores zero in the lvalue. Removes the reference from the stack if @a _removeReference is true. - /// @a _location is the source location of the requested operation - virtual void setToZero( - SourceLocation const& _location = SourceLocation(), - bool _removeReference = true - ) const = 0; - -protected: - CompilerContext& m_context; - Type const& m_dataType; -}; - -/** - * Local variable that is completely stored on the stack. - */ -class StackVariable: public LValue -{ -public: - StackVariable(CompilerContext& _compilerContext, Declaration const& _declaration); - - virtual unsigned sizeOnStack() const override { return 0; } - virtual void retrieveValue(SourceLocation const& _location, bool _remove = false) const override; - virtual void storeValue( - Type const& _sourceType, - SourceLocation const& _location = SourceLocation(), - bool _move = false - ) const override; - virtual void setToZero( - SourceLocation const& _location = SourceLocation(), - bool _removeReference = true - ) const override; - -private: - /// Base stack offset (@see CompilerContext::getBaseStackOffsetOfVariable) of the local variable. - unsigned m_baseStackOffset; - /// Number of stack elements occupied by the value (not the reference). - unsigned m_size; -}; - -/** - * Reference to some item in memory. - */ -class MemoryItem: public LValue -{ -public: - MemoryItem(CompilerContext& _compilerContext, Type const& _type, bool _padded = true); - virtual unsigned sizeOnStack() const override { return 1; } - virtual void retrieveValue(SourceLocation const& _location, bool _remove = false) const override; - virtual void storeValue( - Type const& _sourceType, - SourceLocation const& _location = SourceLocation(), - bool _move = false - ) const override; - virtual void setToZero( - SourceLocation const& _location = SourceLocation(), - bool _removeReference = true - ) const override; -private: - /// Special flag to deal with byte array elements. - bool m_padded = false; -}; - -/** - * Reference to some item in storage. On the stack this is , - * where 0 <= offset_inside_value < 32 and an offset of i means that the value is multiplied - * by 2**i before storing it. - */ -class StorageItem: public LValue -{ -public: - /// Constructs the LValue and pushes the location of @a _declaration onto the stack. - StorageItem(CompilerContext& _compilerContext, Declaration const& _declaration); - /// Constructs the LValue and assumes that the storage reference is already on the stack. - StorageItem(CompilerContext& _compilerContext, Type const& _type); - virtual unsigned sizeOnStack() const override { return 2; } - virtual void retrieveValue(SourceLocation const& _location, bool _remove = false) const override; - virtual void storeValue( - Type const& _sourceType, - SourceLocation const& _location = SourceLocation(), - bool _move = false - ) const override; - virtual void setToZero( - SourceLocation const& _location = SourceLocation(), - bool _removeReference = true - ) const override; -}; - -/** - * Reference to a single byte inside a storage byte array. - * Stack: - */ -class StorageByteArrayElement: public LValue -{ -public: - /// Constructs the LValue and assumes that the storage reference is already on the stack. - StorageByteArrayElement(CompilerContext& _compilerContext); - virtual unsigned sizeOnStack() const override { return 2; } - virtual void retrieveValue(SourceLocation const& _location, bool _remove = false) const override; - virtual void storeValue( - Type const& _sourceType, - SourceLocation const& _location = SourceLocation(), - bool _move = false - ) const override; - virtual void setToZero( - SourceLocation const& _location = SourceLocation(), - bool _removeReference = true - ) const override; -}; - -/** - * Reference to the "length" member of a dynamically-sized array. This is an LValue with special - * semantics since assignments to it might reduce its length and thus arrays members have to be - * deleted. - */ -class StorageArrayLength: public LValue -{ -public: - /// Constructs the LValue, assumes that the reference to the array head is already on the stack. - StorageArrayLength(CompilerContext& _compilerContext, ArrayType const& _arrayType); - virtual void retrieveValue(SourceLocation const& _location, bool _remove = false) const override; - virtual void storeValue( - Type const& _sourceType, - SourceLocation const& _location = SourceLocation(), - bool _move = false - ) const override; - virtual void setToZero( - SourceLocation const& _location = SourceLocation(), - bool _removeReference = true - ) const override; - -private: - ArrayType const& m_arrayType; -}; - -} -} diff --git a/libsolidity/NameAndTypeResolver.cpp b/libsolidity/NameAndTypeResolver.cpp deleted file mode 100644 index 87f9da7ee..000000000 --- a/libsolidity/NameAndTypeResolver.cpp +++ /dev/null @@ -1,530 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Parser part that determines the declarations corresponding to names and the types of expressions. - */ - -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -NameAndTypeResolver::NameAndTypeResolver(vector const& _globals) -{ - for (Declaration const* declaration: _globals) - m_scopes[nullptr].registerDeclaration(*declaration); -} - -void NameAndTypeResolver::registerDeclarations(SourceUnit& _sourceUnit) -{ - // The helper registers all declarations in m_scopes as a side-effect of its construction. - DeclarationRegistrationHelper registrar(m_scopes, _sourceUnit); -} - -void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract) -{ - m_currentScope = &m_scopes[nullptr]; - - for (ASTPointer const& baseContract: _contract.getBaseContracts()) - ReferencesResolver resolver(*baseContract, *this, &_contract, nullptr); - - m_currentScope = &m_scopes[&_contract]; - - linearizeBaseContracts(_contract); - std::vector properBases( - ++_contract.getLinearizedBaseContracts().begin(), - _contract.getLinearizedBaseContracts().end() - ); - - for (ContractDefinition const* base: properBases) - importInheritedScope(*base); - - for (ASTPointer const& structDef: _contract.getDefinedStructs()) - ReferencesResolver resolver(*structDef, *this, &_contract, nullptr); - for (ASTPointer const& enumDef: _contract.getDefinedEnums()) - ReferencesResolver resolver(*enumDef, *this, &_contract, nullptr); - for (ASTPointer const& variable: _contract.getStateVariables()) - ReferencesResolver resolver(*variable, *this, &_contract, nullptr); - for (ASTPointer const& event: _contract.getEvents()) - ReferencesResolver resolver(*event, *this, &_contract, nullptr); - - // these can contain code, only resolve parameters for now - for (ASTPointer const& modifier: _contract.getFunctionModifiers()) - { - m_currentScope = &m_scopes[modifier.get()]; - ReferencesResolver resolver(*modifier, *this, &_contract, nullptr); - } - for (ASTPointer const& function: _contract.getDefinedFunctions()) - { - m_currentScope = &m_scopes[function.get()]; - ReferencesResolver referencesResolver(*function, *this, &_contract, - function->getReturnParameterList().get()); - } - - m_currentScope = &m_scopes[&_contract]; - - // now resolve references inside the code - for (ASTPointer const& modifier: _contract.getFunctionModifiers()) - { - m_currentScope = &m_scopes[modifier.get()]; - ReferencesResolver resolver(*modifier, *this, &_contract, nullptr, true); - } - for (ASTPointer const& function: _contract.getDefinedFunctions()) - { - m_currentScope = &m_scopes[function.get()]; - ReferencesResolver referencesResolver( - *function, - *this, - &_contract, - function->getReturnParameterList().get(), - true - ); - } -} - -void NameAndTypeResolver::checkTypeRequirements(ContractDefinition& _contract) -{ - for (ASTPointer const& structDef: _contract.getDefinedStructs()) - structDef->checkValidityOfMembers(); - _contract.checkTypeRequirements(); -} - -void NameAndTypeResolver::updateDeclaration(Declaration const& _declaration) -{ - m_scopes[nullptr].registerDeclaration(_declaration, false, true); - solAssert(_declaration.getScope() == nullptr, "Updated declaration outside global scope."); -} - -vector NameAndTypeResolver::resolveName(ASTString const& _name, Declaration const* _scope) const -{ - auto iterator = m_scopes.find(_scope); - if (iterator == end(m_scopes)) - return vector({}); - return iterator->second.resolveName(_name, false); -} - -vector NameAndTypeResolver::getNameFromCurrentScope(ASTString const& _name, bool _recursive) -{ - return m_currentScope->resolveName(_name, _recursive); -} - -vector NameAndTypeResolver::cleanedDeclarations( - Identifier const& _identifier, - vector const& _declarations -) -{ - solAssert(_declarations.size() > 1, ""); - vector uniqueFunctions; - - for (auto it = _declarations.begin(); it != _declarations.end(); ++it) - { - solAssert(*it, ""); - // the declaration is functionDefinition while declarations > 1 - FunctionDefinition const& functionDefinition = dynamic_cast(**it); - FunctionType functionType(functionDefinition); - for (auto parameter: functionType.getParameterTypes() + functionType.getReturnParameterTypes()) - if (!parameter) - BOOST_THROW_EXCEPTION( - DeclarationError() << - errinfo_sourceLocation(_identifier.getLocation()) << - errinfo_comment("Function type can not be used in this context") - ); - if (uniqueFunctions.end() == find_if( - uniqueFunctions.begin(), - uniqueFunctions.end(), - [&](Declaration const* d) - { - FunctionType newFunctionType(dynamic_cast(*d)); - return functionType.hasEqualArgumentTypes(newFunctionType); - } - )) - uniqueFunctions.push_back(*it); - } - return uniqueFunctions; -} - -void NameAndTypeResolver::importInheritedScope(ContractDefinition const& _base) -{ - auto iterator = m_scopes.find(&_base); - solAssert(iterator != end(m_scopes), ""); - for (auto const& nameAndDeclaration: iterator->second.getDeclarations()) - for (auto const& declaration: nameAndDeclaration.second) - // Import if it was declared in the base, is not the constructor and is visible in derived classes - if (declaration->getScope() == &_base && declaration->isVisibleInDerivedContracts()) - m_currentScope->registerDeclaration(*declaration); -} - -void NameAndTypeResolver::linearizeBaseContracts(ContractDefinition& _contract) const -{ - // order in the lists is from derived to base - // list of lists to linearize, the last element is the list of direct bases - list> input(1, {}); - for (ASTPointer const& baseSpecifier: _contract.getBaseContracts()) - { - ASTPointer baseName = baseSpecifier->getName(); - auto base = dynamic_cast(&baseName->getReferencedDeclaration()); - if (!base) - BOOST_THROW_EXCEPTION(baseName->createTypeError("Contract expected.")); - // "push_front" has the effect that bases mentioned later can overwrite members of bases - // mentioned earlier - input.back().push_front(base); - vector const& basesBases = base->getLinearizedBaseContracts(); - if (basesBases.empty()) - BOOST_THROW_EXCEPTION(baseName->createTypeError("Definition of base has to precede definition of derived contract")); - input.push_front(list(basesBases.begin(), basesBases.end())); - } - input.back().push_front(&_contract); - vector result = cThreeMerge(input); - if (result.empty()) - BOOST_THROW_EXCEPTION(_contract.createTypeError("Linearization of inheritance graph impossible")); - _contract.setLinearizedBaseContracts(result); -} - -template -vector<_T const*> NameAndTypeResolver::cThreeMerge(list>& _toMerge) -{ - // returns true iff _candidate appears only as last element of the lists - auto appearsOnlyAtHead = [&](_T const* _candidate) -> bool - { - for (list<_T const*> const& bases: _toMerge) - { - solAssert(!bases.empty(), ""); - if (find(++bases.begin(), bases.end(), _candidate) != bases.end()) - return false; - } - return true; - }; - // returns the next candidate to append to the linearized list or nullptr on failure - auto nextCandidate = [&]() -> _T const* - { - for (list<_T const*> const& bases: _toMerge) - { - solAssert(!bases.empty(), ""); - if (appearsOnlyAtHead(bases.front())) - return bases.front(); - } - return nullptr; - }; - // removes the given contract from all lists - auto removeCandidate = [&](_T const* _candidate) - { - for (auto it = _toMerge.begin(); it != _toMerge.end();) - { - it->remove(_candidate); - if (it->empty()) - it = _toMerge.erase(it); - else - ++it; - } - }; - - _toMerge.remove_if([](list<_T const*> const& _bases) { return _bases.empty(); }); - vector<_T const*> result; - while (!_toMerge.empty()) - { - _T const* candidate = nextCandidate(); - if (!candidate) - return vector<_T const*>(); - result.push_back(candidate); - removeCandidate(candidate); - } - return result; -} - -DeclarationRegistrationHelper::DeclarationRegistrationHelper(map& _scopes, - ASTNode& _astRoot): - m_scopes(_scopes), m_currentScope(nullptr) -{ - _astRoot.accept(*this); -} - -bool DeclarationRegistrationHelper::visit(ContractDefinition& _contract) -{ - registerDeclaration(_contract, true); - return true; -} - -void DeclarationRegistrationHelper::endVisit(ContractDefinition&) -{ - closeCurrentScope(); -} - -bool DeclarationRegistrationHelper::visit(StructDefinition& _struct) -{ - registerDeclaration(_struct, true); - return true; -} - -void DeclarationRegistrationHelper::endVisit(StructDefinition&) -{ - closeCurrentScope(); -} - -bool DeclarationRegistrationHelper::visit(EnumDefinition& _enum) -{ - registerDeclaration(_enum, true); - return true; -} - -void DeclarationRegistrationHelper::endVisit(EnumDefinition&) -{ - closeCurrentScope(); -} - -bool DeclarationRegistrationHelper::visit(EnumValue& _value) -{ - registerDeclaration(_value, false); - return true; -} - -bool DeclarationRegistrationHelper::visit(FunctionDefinition& _function) -{ - registerDeclaration(_function, true); - m_currentFunction = &_function; - return true; -} - -void DeclarationRegistrationHelper::endVisit(FunctionDefinition&) -{ - m_currentFunction = nullptr; - closeCurrentScope(); -} - -bool DeclarationRegistrationHelper::visit(ModifierDefinition& _modifier) -{ - registerDeclaration(_modifier, true); - m_currentFunction = &_modifier; - return true; -} - -void DeclarationRegistrationHelper::endVisit(ModifierDefinition&) -{ - m_currentFunction = nullptr; - closeCurrentScope(); -} - -void DeclarationRegistrationHelper::endVisit(VariableDeclarationStatement& _variableDeclarationStatement) -{ - // Register the local variables with the function - // This does not fit here perfectly, but it saves us another AST visit. - solAssert(m_currentFunction, "Variable declaration without function."); - m_currentFunction->addLocalVariable(_variableDeclarationStatement.getDeclaration()); -} - -bool DeclarationRegistrationHelper::visit(VariableDeclaration& _declaration) -{ - registerDeclaration(_declaration, false); - return true; -} - -bool DeclarationRegistrationHelper::visit(EventDefinition& _event) -{ - registerDeclaration(_event, true); - return true; -} - -void DeclarationRegistrationHelper::endVisit(EventDefinition&) -{ - closeCurrentScope(); -} - -void DeclarationRegistrationHelper::enterNewSubScope(Declaration const& _declaration) -{ - map::iterator iter; - bool newlyAdded; - tie(iter, newlyAdded) = m_scopes.emplace(&_declaration, DeclarationContainer(m_currentScope, &m_scopes[m_currentScope])); - solAssert(newlyAdded, "Unable to add new scope."); - m_currentScope = &_declaration; -} - -void DeclarationRegistrationHelper::closeCurrentScope() -{ - solAssert(m_currentScope, "Closed non-existing scope."); - m_currentScope = m_scopes[m_currentScope].getEnclosingDeclaration(); -} - -void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaration, bool _opensScope) -{ - if (!m_scopes[m_currentScope].registerDeclaration(_declaration, !_declaration.isVisibleInContract())) - { - SourceLocation firstDeclarationLocation; - SourceLocation secondDeclarationLocation; - Declaration const* conflictingDeclaration = m_scopes[m_currentScope].conflictingDeclaration(_declaration); - solAssert(conflictingDeclaration, ""); - - if (_declaration.getLocation().start < conflictingDeclaration->getLocation().start) - { - firstDeclarationLocation = _declaration.getLocation(); - secondDeclarationLocation = conflictingDeclaration->getLocation(); - } - else - { - firstDeclarationLocation = conflictingDeclaration->getLocation(); - secondDeclarationLocation = _declaration.getLocation(); - } - - BOOST_THROW_EXCEPTION( - DeclarationError() << - errinfo_sourceLocation(secondDeclarationLocation) << - errinfo_comment("Identifier already declared.") << - errinfo_secondarySourceLocation( - SecondarySourceLocation().append("The previous declaration is here:", firstDeclarationLocation) - ) - ); - } - - _declaration.setScope(m_currentScope); - if (_opensScope) - enterNewSubScope(_declaration); -} - -ReferencesResolver::ReferencesResolver( - ASTNode& _root, - NameAndTypeResolver& _resolver, - ContractDefinition const* _currentContract, - ParameterList const* _returnParameters, - bool _resolveInsideCode, - bool _allowLazyTypes -): - m_resolver(_resolver), - m_currentContract(_currentContract), - m_returnParameters(_returnParameters), - m_resolveInsideCode(_resolveInsideCode), - m_allowLazyTypes(_allowLazyTypes) -{ - _root.accept(*this); -} - -void ReferencesResolver::endVisit(VariableDeclaration& _variable) -{ - // endVisit because the internal type needs resolving if it is a user defined type - // or mapping - if (_variable.getTypeName()) - { - TypePointer type = _variable.getTypeName()->toType(); - using Location = VariableDeclaration::Location; - Location loc = _variable.referenceLocation(); - // References are forced to calldata for external function parameters (not return) - // and memory for parameters (also return) of publicly visible functions. - // They default to memory for function parameters and storage for local variables. - if (auto ref = dynamic_cast(type.get())) - { - if (_variable.isExternalCallableParameter()) - { - // force location of external function parameters (not return) to calldata - if (loc != Location::Default) - BOOST_THROW_EXCEPTION(_variable.createTypeError( - "Location has to be calldata for external functions " - "(remove the \"memory\" or \"storage\" keyword)." - )); - type = ref->copyForLocation(DataLocation::CallData, true); - } - else if (_variable.isCallableParameter() && _variable.getScope()->isPublic()) - { - // force locations of public or external function (return) parameters to memory - if (loc == VariableDeclaration::Location::Storage) - BOOST_THROW_EXCEPTION(_variable.createTypeError( - "Location has to be memory for publicly visible functions " - "(remove the \"storage\" keyword)." - )); - type = ref->copyForLocation(DataLocation::Memory, true); - } - else - { - if (loc == Location::Default) - loc = _variable.isCallableParameter() ? Location::Memory : Location::Storage; - bool isPointer = !_variable.isStateVariable(); - type = ref->copyForLocation( - loc == Location::Memory ? - DataLocation::Memory : - DataLocation::Storage, - isPointer - ); - } - } - else if (loc != Location::Default && !ref) - BOOST_THROW_EXCEPTION(_variable.createTypeError( - "Storage location can only be given for array or struct types." - )); - - _variable.setType(type); - - if (!_variable.getType()) - BOOST_THROW_EXCEPTION(_variable.getTypeName()->createTypeError("Invalid type name")); - } - else if (!m_allowLazyTypes) - BOOST_THROW_EXCEPTION(_variable.createTypeError("Explicit type needed.")); - // otherwise we have a "var"-declaration whose type is resolved by the first assignment -} - -bool ReferencesResolver::visit(Return& _return) -{ - _return.setFunctionReturnParameters(m_returnParameters); - return true; -} - -bool ReferencesResolver::visit(Mapping&) -{ - return true; -} - -bool ReferencesResolver::visit(UserDefinedTypeName& _typeName) -{ - auto declarations = m_resolver.getNameFromCurrentScope(_typeName.getName()); - if (declarations.empty()) - BOOST_THROW_EXCEPTION( - DeclarationError() << - errinfo_sourceLocation(_typeName.getLocation()) << - errinfo_comment("Undeclared identifier.") - ); - else if (declarations.size() > 1) - BOOST_THROW_EXCEPTION( - DeclarationError() << - errinfo_sourceLocation(_typeName.getLocation()) << - errinfo_comment("Duplicate identifier.") - ); - else - _typeName.setReferencedDeclaration(**declarations.begin()); - return false; -} - -bool ReferencesResolver::visit(Identifier& _identifier) -{ - auto declarations = m_resolver.getNameFromCurrentScope(_identifier.getName()); - if (declarations.empty()) - BOOST_THROW_EXCEPTION( - DeclarationError() << - errinfo_sourceLocation(_identifier.getLocation()) << - errinfo_comment("Undeclared identifier.") - ); - else if (declarations.size() == 1) - _identifier.setReferencedDeclaration(*declarations.front(), m_currentContract); - else - _identifier.setOverloadedDeclarations(m_resolver.cleanedDeclarations(_identifier, declarations)); - return false; -} - -} -} diff --git a/libsolidity/NameAndTypeResolver.h b/libsolidity/NameAndTypeResolver.h deleted file mode 100644 index d7a0a3b2f..000000000 --- a/libsolidity/NameAndTypeResolver.h +++ /dev/null @@ -1,160 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Parser part that determines the declarations corresponding to names and the types of expressions. - */ - -#pragma once - -#include -#include -#include - -#include -#include - -namespace dev -{ -namespace solidity -{ - -/** - * Resolves name references, types and checks types of all expressions. - * Specifically, it checks that all operations are valid for the inferred types. - * An exception is throw on the first error. - */ -class NameAndTypeResolver: private boost::noncopyable -{ -public: - explicit NameAndTypeResolver(std::vector const& _globals); - /// Registers all declarations found in the source unit. - void registerDeclarations(SourceUnit& _sourceUnit); - /// Resolves all names and types referenced from the given contract. - void resolveNamesAndTypes(ContractDefinition& _contract); - /// Check all type requirements in the given contract. - void checkTypeRequirements(ContractDefinition& _contract); - /// Updates the given global declaration (used for "this"). Not to be used with declarations - /// that create their own scope. - void updateDeclaration(Declaration const& _declaration); - - /// Resolves the given @a _name inside the scope @a _scope. If @a _scope is omitted, - /// the global scope is used (i.e. the one containing only the contract). - /// @returns a pointer to the declaration on success or nullptr on failure. - std::vector resolveName(ASTString const& _name, Declaration const* _scope = nullptr) const; - - /// Resolves a name in the "current" scope. Should only be called during the initial - /// resolving phase. - std::vector getNameFromCurrentScope(ASTString const& _name, bool _recursive = true); - - /// returns the vector of declarations without repetitions - static std::vector cleanedDeclarations( - Identifier const& _identifier, - std::vector const& _declarations - ); - -private: - void reset(); - - /// Imports all members declared directly in the given contract (i.e. does not import inherited members) - /// into the current scope if they are not present already. - void importInheritedScope(ContractDefinition const& _base); - - /// Computes "C3-Linearization" of base contracts and stores it inside the contract. - void linearizeBaseContracts(ContractDefinition& _contract) const; - /// Computes the C3-merge of the given list of lists of bases. - /// @returns the linearized vector or an empty vector if linearization is not possible. - template - static std::vector<_T const*> cThreeMerge(std::list>& _toMerge); - - /// Maps nodes declaring a scope to scopes, i.e. ContractDefinition and FunctionDeclaration, - /// where nullptr denotes the global scope. Note that structs are not scope since they do - /// not contain code. - std::map m_scopes; - - DeclarationContainer* m_currentScope = nullptr; -}; - -/** - * Traverses the given AST upon construction and fills _scopes with all declarations inside the - * AST. - */ -class DeclarationRegistrationHelper: private ASTVisitor -{ -public: - DeclarationRegistrationHelper(std::map& _scopes, ASTNode& _astRoot); - -private: - bool visit(ContractDefinition& _contract) override; - void endVisit(ContractDefinition& _contract) override; - bool visit(StructDefinition& _struct) override; - void endVisit(StructDefinition& _struct) override; - bool visit(EnumDefinition& _enum) override; - void endVisit(EnumDefinition& _enum) override; - bool visit(EnumValue& _value) override; - bool visit(FunctionDefinition& _function) override; - void endVisit(FunctionDefinition& _function) override; - bool visit(ModifierDefinition& _modifier) override; - void endVisit(ModifierDefinition& _modifier) override; - void endVisit(VariableDeclarationStatement& _variableDeclarationStatement) override; - bool visit(VariableDeclaration& _declaration) override; - bool visit(EventDefinition& _event) override; - void endVisit(EventDefinition& _event) override; - - void enterNewSubScope(Declaration const& _declaration); - void closeCurrentScope(); - void registerDeclaration(Declaration& _declaration, bool _opensScope); - - std::map& m_scopes; - Declaration const* m_currentScope; - VariableScope* m_currentFunction; -}; - -/** - * Resolves references to declarations (of variables and types) and also establishes the link - * between a return statement and the return parameter list. - */ -class ReferencesResolver: private ASTVisitor -{ -public: - ReferencesResolver( - ASTNode& _root, - NameAndTypeResolver& _resolver, - ContractDefinition const* _currentContract, - ParameterList const* _returnParameters, - bool _resolveInsideCode = false, - bool _allowLazyTypes = true - ); - -private: - virtual void endVisit(VariableDeclaration& _variable) override; - virtual bool visit(Block&) override { return m_resolveInsideCode; } - virtual bool visit(Identifier& _identifier) override; - virtual bool visit(UserDefinedTypeName& _typeName) override; - virtual bool visit(Mapping&) override; - virtual bool visit(Return& _return) override; - - NameAndTypeResolver& m_resolver; - ContractDefinition const* m_currentContract; - ParameterList const* m_returnParameters; - bool m_resolveInsideCode; - bool m_allowLazyTypes; -}; - -} -} diff --git a/libsolidity/Parser.cpp b/libsolidity/Parser.cpp deleted file mode 100644 index fbf8478df..000000000 --- a/libsolidity/Parser.cpp +++ /dev/null @@ -1,1082 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity parser. - */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -/// AST node factory that also tracks the begin and end position of an AST node -/// while it is being parsed -class Parser::ASTNodeFactory -{ -public: - ASTNodeFactory(Parser const& _parser): - m_parser(_parser), m_location(_parser.getPosition(), -1, _parser.getSourceName()) {} - ASTNodeFactory(Parser const& _parser, ASTPointer const& _childNode): - m_parser(_parser), m_location(_childNode->getLocation()) {} - - void markEndPosition() { m_location.end = m_parser.getEndPosition(); } - void setLocation(SourceLocation const& _location) { m_location = _location; } - void setLocationEmpty() { m_location.end = m_location.start; } - /// Set the end position to the one of the given node. - void setEndPositionFromNode(ASTPointer const& _node) { m_location.end = _node->getLocation().end; } - - template - ASTPointer createNode(Args&& ... _args) - { - if (m_location.end < 0) - markEndPosition(); - return make_shared(m_location, forward(_args)...); - } - -private: - Parser const& m_parser; - SourceLocation m_location; -}; - -ASTPointer Parser::parse(shared_ptr const& _scanner) -{ - m_scanner = _scanner; - ASTNodeFactory nodeFactory(*this); - vector> nodes; - while (_scanner->getCurrentToken() != Token::EOS) - { - switch (m_scanner->getCurrentToken()) - { - case Token::Import: - nodes.push_back(parseImportDirective()); - break; - case Token::Contract: - nodes.push_back(parseContractDefinition()); - break; - default: - BOOST_THROW_EXCEPTION(createParserError(std::string("Expected import directive or contract definition."))); - } - } - return nodeFactory.createNode(nodes); -} - -std::shared_ptr const& Parser::getSourceName() const -{ - return m_scanner->getSourceName(); -} - -int Parser::getPosition() const -{ - return m_scanner->getCurrentLocation().start; -} - -int Parser::getEndPosition() const -{ - return m_scanner->getCurrentLocation().end; -} - -ASTPointer Parser::parseImportDirective() -{ - ASTNodeFactory nodeFactory(*this); - expectToken(Token::Import); - if (m_scanner->getCurrentToken() != Token::StringLiteral) - BOOST_THROW_EXCEPTION(createParserError("Expected string literal (URL).")); - ASTPointer url = getLiteralAndAdvance(); - nodeFactory.markEndPosition(); - expectToken(Token::Semicolon); - return nodeFactory.createNode(url); -} - -ASTPointer Parser::parseContractDefinition() -{ - ASTNodeFactory nodeFactory(*this); - ASTPointer docString; - if (m_scanner->getCurrentCommentLiteral() != "") - docString = make_shared(m_scanner->getCurrentCommentLiteral()); - expectToken(Token::Contract); - ASTPointer name = expectIdentifierToken(); - vector> baseContracts; - vector> structs; - vector> enums; - vector> stateVariables; - vector> functions; - vector> modifiers; - vector> events; - if (m_scanner->getCurrentToken() == Token::Is) - do - { - m_scanner->next(); - baseContracts.push_back(parseInheritanceSpecifier()); - } - while (m_scanner->getCurrentToken() == Token::Comma); - expectToken(Token::LBrace); - while (true) - { - Token::Value currentToken = m_scanner->getCurrentToken(); - if (currentToken == Token::RBrace) - break; - else if (currentToken == Token::Function) - functions.push_back(parseFunctionDefinition(name.get())); - else if (currentToken == Token::Struct) - structs.push_back(parseStructDefinition()); - else if (currentToken == Token::Enum) - enums.push_back(parseEnumDefinition()); - else if (currentToken == Token::Identifier || currentToken == Token::Mapping || - Token::isElementaryTypeName(currentToken)) - { - VarDeclParserOptions options; - options.isStateVariable = true; - options.allowInitialValue = true; - stateVariables.push_back(parseVariableDeclaration(options)); - expectToken(Token::Semicolon); - } - else if (currentToken == Token::Modifier) - modifiers.push_back(parseModifierDefinition()); - else if (currentToken == Token::Event) - events.push_back(parseEventDefinition()); - else - BOOST_THROW_EXCEPTION(createParserError("Function, variable, struct or modifier declaration expected.")); - } - nodeFactory.markEndPosition(); - expectToken(Token::RBrace); - return nodeFactory.createNode( - name, - docString, - baseContracts, - structs, - enums, - stateVariables, - functions, - modifiers, - events - ); -} - -ASTPointer Parser::parseInheritanceSpecifier() -{ - ASTNodeFactory nodeFactory(*this); - ASTPointer name(parseIdentifier()); - vector> arguments; - if (m_scanner->getCurrentToken() == Token::LParen) - { - m_scanner->next(); - arguments = parseFunctionCallListArguments(); - nodeFactory.markEndPosition(); - expectToken(Token::RParen); - } - else - nodeFactory.setEndPositionFromNode(name); - return nodeFactory.createNode(name, arguments); -} - -Declaration::Visibility Parser::parseVisibilitySpecifier(Token::Value _token) -{ - Declaration::Visibility visibility(Declaration::Visibility::Default); - if (_token == Token::Public) - visibility = Declaration::Visibility::Public; - else if (_token == Token::Internal) - visibility = Declaration::Visibility::Internal; - else if (_token == Token::Private) - visibility = Declaration::Visibility::Private; - else if (_token == Token::External) - visibility = Declaration::Visibility::External; - else - solAssert(false, "Invalid visibility specifier."); - m_scanner->next(); - return visibility; -} - -ASTPointer Parser::parseFunctionDefinition(ASTString const* _contractName) -{ - ASTNodeFactory nodeFactory(*this); - ASTPointer docstring; - if (m_scanner->getCurrentCommentLiteral() != "") - docstring = make_shared(m_scanner->getCurrentCommentLiteral()); - - expectToken(Token::Function); - ASTPointer name; - if (m_scanner->getCurrentToken() == Token::LParen) - name = make_shared(); // anonymous function - else - name = expectIdentifierToken(); - VarDeclParserOptions options; - options.allowLocationSpecifier = true; - ASTPointer parameters(parseParameterList(options)); - bool isDeclaredConst = false; - Declaration::Visibility visibility(Declaration::Visibility::Default); - vector> modifiers; - while (true) - { - Token::Value token = m_scanner->getCurrentToken(); - if (token == Token::Const) - { - isDeclaredConst = true; - m_scanner->next(); - } - else if (token == Token::Identifier) - modifiers.push_back(parseModifierInvocation()); - else if (Token::isVisibilitySpecifier(token)) - { - if (visibility != Declaration::Visibility::Default) - BOOST_THROW_EXCEPTION(createParserError("Multiple visibility specifiers.")); - visibility = parseVisibilitySpecifier(token); - } - else - break; - } - ASTPointer returnParameters; - if (m_scanner->getCurrentToken() == Token::Returns) - { - bool const permitEmptyParameterList = false; - m_scanner->next(); - returnParameters = parseParameterList(options, permitEmptyParameterList); - } - else - returnParameters = createEmptyParameterList(); - ASTPointer block = ASTPointer(); - nodeFactory.markEndPosition(); - if (m_scanner->getCurrentToken() != Token::Semicolon) - { - block = parseBlock(); - nodeFactory.setEndPositionFromNode(block); - } - else - m_scanner->next(); // just consume the ';' - bool const c_isConstructor = (_contractName && *name == *_contractName); - return nodeFactory.createNode(name, visibility, c_isConstructor, docstring, - parameters, isDeclaredConst, modifiers, - returnParameters, block); -} - -ASTPointer Parser::parseStructDefinition() -{ - ASTNodeFactory nodeFactory(*this); - expectToken(Token::Struct); - ASTPointer name = expectIdentifierToken(); - vector> members; - expectToken(Token::LBrace); - while (m_scanner->getCurrentToken() != Token::RBrace) - { - members.push_back(parseVariableDeclaration()); - expectToken(Token::Semicolon); - } - nodeFactory.markEndPosition(); - expectToken(Token::RBrace); - return nodeFactory.createNode(name, members); -} - -ASTPointer Parser::parseEnumValue() -{ - ASTNodeFactory nodeFactory(*this); - nodeFactory.markEndPosition(); - return nodeFactory.createNode(expectIdentifierToken()); -} - -ASTPointer Parser::parseEnumDefinition() -{ - ASTNodeFactory nodeFactory(*this); - expectToken(Token::Enum); - ASTPointer name = expectIdentifierToken(); - vector> members; - expectToken(Token::LBrace); - - while (m_scanner->getCurrentToken() != Token::RBrace) - { - members.push_back(parseEnumValue()); - if (m_scanner->getCurrentToken() == Token::RBrace) - break; - expectToken(Token::Comma); - if (m_scanner->getCurrentToken() != Token::Identifier) - BOOST_THROW_EXCEPTION(createParserError("Expected Identifier after ','")); - } - - nodeFactory.markEndPosition(); - expectToken(Token::RBrace); - return nodeFactory.createNode(name, members); -} - -ASTPointer Parser::parseVariableDeclaration( - VarDeclParserOptions const& _options, - ASTPointer const& _lookAheadArrayType -) -{ - ASTNodeFactory nodeFactory = _lookAheadArrayType ? - ASTNodeFactory(*this, _lookAheadArrayType) : ASTNodeFactory(*this); - ASTPointer type; - if (_lookAheadArrayType) - type = _lookAheadArrayType; - else - { - type = parseTypeName(_options.allowVar); - if (type != nullptr) - nodeFactory.setEndPositionFromNode(type); - } - bool isIndexed = false; - bool isDeclaredConst = false; - Declaration::Visibility visibility(Declaration::Visibility::Default); - VariableDeclaration::Location location = VariableDeclaration::Location::Default; - ASTPointer identifier; - - while (true) - { - Token::Value token = m_scanner->getCurrentToken(); - if (_options.isStateVariable && Token::isVariableVisibilitySpecifier(token)) - { - if (visibility != Declaration::Visibility::Default) - BOOST_THROW_EXCEPTION(createParserError("Visibility already specified.")); - visibility = parseVisibilitySpecifier(token); - } - else - { - if (_options.allowIndexed && token == Token::Indexed) - isIndexed = true; - else if (token == Token::Const) - isDeclaredConst = true; - else if (_options.allowLocationSpecifier && Token::isLocationSpecifier(token)) - { - if (location != VariableDeclaration::Location::Default) - BOOST_THROW_EXCEPTION(createParserError("Location already specified.")); - if (!type) - BOOST_THROW_EXCEPTION(createParserError("Location specifier needs explicit type name.")); - location = ( - token == Token::Memory ? - VariableDeclaration::Location::Memory : - VariableDeclaration::Location::Storage - ); - } - else - break; - m_scanner->next(); - } - } - nodeFactory.markEndPosition(); - - if (_options.allowEmptyName && m_scanner->getCurrentToken() != Token::Identifier) - { - identifier = make_shared(""); - solAssert(type != nullptr, ""); - nodeFactory.setEndPositionFromNode(type); - } - else - identifier = expectIdentifierToken(); - ASTPointer value; - if (_options.allowInitialValue) - { - if (m_scanner->getCurrentToken() == Token::Assign) - { - m_scanner->next(); - value = parseExpression(); - nodeFactory.setEndPositionFromNode(value); - } - } - return nodeFactory.createNode( - type, - identifier, - value, - visibility, - _options.isStateVariable, - isIndexed, - isDeclaredConst, - location - ); -} - -ASTPointer Parser::parseModifierDefinition() -{ - ScopeGuard resetModifierFlag([this]() { m_insideModifier = false; }); - m_insideModifier = true; - - ASTNodeFactory nodeFactory(*this); - ASTPointer docstring; - if (m_scanner->getCurrentCommentLiteral() != "") - docstring = make_shared(m_scanner->getCurrentCommentLiteral()); - - expectToken(Token::Modifier); - ASTPointer name(expectIdentifierToken()); - ASTPointer parameters; - if (m_scanner->getCurrentToken() == Token::LParen) - { - VarDeclParserOptions options; - options.allowIndexed = true; - options.allowLocationSpecifier = true; - parameters = parseParameterList(options); - } - else - parameters = createEmptyParameterList(); - ASTPointer block = parseBlock(); - nodeFactory.setEndPositionFromNode(block); - return nodeFactory.createNode(name, docstring, parameters, block); -} - -ASTPointer Parser::parseEventDefinition() -{ - ASTNodeFactory nodeFactory(*this); - ASTPointer docstring; - if (m_scanner->getCurrentCommentLiteral() != "") - docstring = make_shared(m_scanner->getCurrentCommentLiteral()); - - expectToken(Token::Event); - ASTPointer name(expectIdentifierToken()); - ASTPointer parameters; - if (m_scanner->getCurrentToken() == Token::LParen) - { - VarDeclParserOptions options; - options.allowIndexed = true; - parameters = parseParameterList(options); - } - else - parameters = createEmptyParameterList(); - bool anonymous = false; - if (m_scanner->getCurrentToken() == Token::Anonymous) - { - anonymous = true; - m_scanner->next(); - } - nodeFactory.markEndPosition(); - expectToken(Token::Semicolon); - return nodeFactory.createNode(name, docstring, parameters, anonymous); -} - -ASTPointer Parser::parseModifierInvocation() -{ - ASTNodeFactory nodeFactory(*this); - ASTPointer name(parseIdentifier()); - vector> arguments; - if (m_scanner->getCurrentToken() == Token::LParen) - { - m_scanner->next(); - arguments = parseFunctionCallListArguments(); - nodeFactory.markEndPosition(); - expectToken(Token::RParen); - } - else - nodeFactory.setEndPositionFromNode(name); - return nodeFactory.createNode(name, arguments); -} - -ASTPointer Parser::parseIdentifier() -{ - ASTNodeFactory nodeFactory(*this); - nodeFactory.markEndPosition(); - return nodeFactory.createNode(expectIdentifierToken()); -} - -ASTPointer Parser::parseTypeName(bool _allowVar) -{ - ASTNodeFactory nodeFactory(*this); - ASTPointer type; - Token::Value token = m_scanner->getCurrentToken(); - if (Token::isElementaryTypeName(token)) - { - type = ASTNodeFactory(*this).createNode(token); - m_scanner->next(); - } - else if (token == Token::Var) - { - if (!_allowVar) - BOOST_THROW_EXCEPTION(createParserError("Expected explicit type name.")); - m_scanner->next(); - } - else if (token == Token::Mapping) - type = parseMapping(); - else if (token == Token::Identifier) - { - ASTNodeFactory nodeFactory(*this); - nodeFactory.markEndPosition(); - type = nodeFactory.createNode(expectIdentifierToken()); - } - else - BOOST_THROW_EXCEPTION(createParserError("Expected type name")); - - if (type) - // Parse "[...]" postfixes for arrays. - while (m_scanner->getCurrentToken() == Token::LBrack) - { - m_scanner->next(); - ASTPointer length; - if (m_scanner->getCurrentToken() != Token::RBrack) - length = parseExpression(); - nodeFactory.markEndPosition(); - expectToken(Token::RBrack); - type = nodeFactory.createNode(type, length); - } - return type; -} - -ASTPointer Parser::parseMapping() -{ - ASTNodeFactory nodeFactory(*this); - expectToken(Token::Mapping); - expectToken(Token::LParen); - if (!Token::isElementaryTypeName(m_scanner->getCurrentToken())) - BOOST_THROW_EXCEPTION(createParserError("Expected elementary type name for mapping key type")); - ASTPointer keyType; - keyType = ASTNodeFactory(*this).createNode(m_scanner->getCurrentToken()); - m_scanner->next(); - expectToken(Token::Arrow); - bool const allowVar = false; - ASTPointer valueType = parseTypeName(allowVar); - nodeFactory.markEndPosition(); - expectToken(Token::RParen); - return nodeFactory.createNode(keyType, valueType); -} - -ASTPointer Parser::parseParameterList( - VarDeclParserOptions const& _options, - bool _allowEmpty -) -{ - ASTNodeFactory nodeFactory(*this); - vector> parameters; - VarDeclParserOptions options(_options); - options.allowEmptyName = true; - expectToken(Token::LParen); - if (!_allowEmpty || m_scanner->getCurrentToken() != Token::RParen) - { - parameters.push_back(parseVariableDeclaration(options)); - while (m_scanner->getCurrentToken() != Token::RParen) - { - expectToken(Token::Comma); - parameters.push_back(parseVariableDeclaration(options)); - } - } - nodeFactory.markEndPosition(); - m_scanner->next(); - return nodeFactory.createNode(parameters); -} - -ASTPointer Parser::parseBlock() -{ - ASTNodeFactory nodeFactory(*this); - expectToken(Token::LBrace); - vector> statements; - while (m_scanner->getCurrentToken() != Token::RBrace) - statements.push_back(parseStatement()); - nodeFactory.markEndPosition(); - expectToken(Token::RBrace); - return nodeFactory.createNode(statements); -} - -ASTPointer Parser::parseStatement() -{ - ASTPointer statement; - switch (m_scanner->getCurrentToken()) - { - case Token::If: - return parseIfStatement(); - case Token::While: - return parseWhileStatement(); - case Token::For: - return parseForStatement(); - case Token::LBrace: - return parseBlock(); - // starting from here, all statements must be terminated by a semicolon - case Token::Continue: - statement = ASTNodeFactory(*this).createNode(); - m_scanner->next(); - break; - case Token::Break: - statement = ASTNodeFactory(*this).createNode(); - m_scanner->next(); - break; - case Token::Return: - { - ASTNodeFactory nodeFactory(*this); - ASTPointer expression; - if (m_scanner->next() != Token::Semicolon) - { - expression = parseExpression(); - nodeFactory.setEndPositionFromNode(expression); - } - statement = nodeFactory.createNode(expression); - break; - } - case Token::Identifier: - if (m_insideModifier && m_scanner->getCurrentLiteral() == "_") - { - statement = ASTNodeFactory(*this).createNode(); - m_scanner->next(); - return statement; - } - // fall-through - default: - statement = parseSimpleStatement(); - } - expectToken(Token::Semicolon); - return statement; -} - -ASTPointer Parser::parseIfStatement() -{ - ASTNodeFactory nodeFactory(*this); - expectToken(Token::If); - expectToken(Token::LParen); - ASTPointer condition = parseExpression(); - expectToken(Token::RParen); - ASTPointer trueBody = parseStatement(); - ASTPointer falseBody; - if (m_scanner->getCurrentToken() == Token::Else) - { - m_scanner->next(); - falseBody = parseStatement(); - nodeFactory.setEndPositionFromNode(falseBody); - } - else - nodeFactory.setEndPositionFromNode(trueBody); - return nodeFactory.createNode(condition, trueBody, falseBody); -} - -ASTPointer Parser::parseWhileStatement() -{ - ASTNodeFactory nodeFactory(*this); - expectToken(Token::While); - expectToken(Token::LParen); - ASTPointer condition = parseExpression(); - expectToken(Token::RParen); - ASTPointer body = parseStatement(); - nodeFactory.setEndPositionFromNode(body); - return nodeFactory.createNode(condition, body); -} - -ASTPointer Parser::parseForStatement() -{ - ASTNodeFactory nodeFactory(*this); - ASTPointer initExpression; - ASTPointer conditionExpression; - ASTPointer loopExpression; - expectToken(Token::For); - expectToken(Token::LParen); - - // LTODO: Maybe here have some predicate like peekExpression() instead of checking for semicolon and RParen? - if (m_scanner->getCurrentToken() != Token::Semicolon) - initExpression = parseSimpleStatement(); - expectToken(Token::Semicolon); - - if (m_scanner->getCurrentToken() != Token::Semicolon) - conditionExpression = parseExpression(); - expectToken(Token::Semicolon); - - if (m_scanner->getCurrentToken() != Token::RParen) - loopExpression = parseExpressionStatement(); - expectToken(Token::RParen); - - ASTPointer body = parseStatement(); - nodeFactory.setEndPositionFromNode(body); - return nodeFactory.createNode(initExpression, - conditionExpression, - loopExpression, - body); -} - -ASTPointer Parser::parseSimpleStatement() -{ - // These two cases are very hard to distinguish: - // x[7 * 20 + 3] a; - x[7 * 20 + 3] = 9; - // In the first case, x is a type name, in the second it is the name of a variable. - switch (peekStatementType()) - { - case LookAheadInfo::VariableDeclarationStatement: - return parseVariableDeclarationStatement(); - case LookAheadInfo::ExpressionStatement: - return parseExpressionStatement(); - default: - break; - } - - // At this point, we have '(Identifier|ElementaryTypeName) "["'. - // We parse '(Identifier|ElementaryTypeName) ( "[" Expression "]" )+' and then decide whether to hand this over - // to ExpressionStatement or create a VariableDeclarationStatement out of it. - ASTPointer primary; - if (m_scanner->getCurrentToken() == Token::Identifier) - primary = parseIdentifier(); - else - { - primary = ASTNodeFactory(*this).createNode(m_scanner->getCurrentToken()); - m_scanner->next(); - } - vector, SourceLocation>> indices; - solAssert(m_scanner->getCurrentToken() == Token::LBrack, ""); - SourceLocation indexLocation = primary->getLocation(); - do - { - expectToken(Token::LBrack); - ASTPointer index; - if (m_scanner->getCurrentToken() != Token::RBrack) - index = parseExpression(); - indexLocation.end = getEndPosition(); - indices.push_back(make_pair(index, indexLocation)); - expectToken(Token::RBrack); - } - while (m_scanner->getCurrentToken() == Token::LBrack); - - if (m_scanner->getCurrentToken() == Token::Identifier || Token::isLocationSpecifier(m_scanner->getCurrentToken())) - return parseVariableDeclarationStatement(typeNameIndexAccessStructure(primary, indices)); - else - return parseExpressionStatement(expressionFromIndexAccessStructure(primary, indices)); -} - -ASTPointer Parser::parseVariableDeclarationStatement( - ASTPointer const& _lookAheadArrayType) -{ - VarDeclParserOptions options; - options.allowVar = true; - options.allowInitialValue = true; - options.allowLocationSpecifier = true; - ASTPointer variable = parseVariableDeclaration(options, _lookAheadArrayType); - ASTNodeFactory nodeFactory(*this, variable); - return nodeFactory.createNode(variable); -} - -ASTPointer Parser::parseExpressionStatement( - ASTPointer const& _lookAheadIndexAccessStructure) -{ - ASTPointer expression = parseExpression(_lookAheadIndexAccessStructure); - return ASTNodeFactory(*this, expression).createNode(expression); -} - -ASTPointer Parser::parseExpression( - ASTPointer const& _lookAheadIndexAccessStructure) -{ - ASTPointer expression = parseBinaryExpression(4, _lookAheadIndexAccessStructure); - if (!Token::isAssignmentOp(m_scanner->getCurrentToken())) - return expression; - Token::Value assignmentOperator = expectAssignmentOperator(); - ASTPointer rightHandSide = parseExpression(); - ASTNodeFactory nodeFactory(*this, expression); - nodeFactory.setEndPositionFromNode(rightHandSide); - return nodeFactory.createNode(expression, assignmentOperator, rightHandSide); -} - -ASTPointer Parser::parseBinaryExpression(int _minPrecedence, - ASTPointer const& _lookAheadIndexAccessStructure) -{ - ASTPointer expression = parseUnaryExpression(_lookAheadIndexAccessStructure); - ASTNodeFactory nodeFactory(*this, expression); - int precedence = Token::precedence(m_scanner->getCurrentToken()); - for (; precedence >= _minPrecedence; --precedence) - while (Token::precedence(m_scanner->getCurrentToken()) == precedence) - { - Token::Value op = m_scanner->getCurrentToken(); - m_scanner->next(); - ASTPointer right = parseBinaryExpression(precedence + 1); - nodeFactory.setEndPositionFromNode(right); - expression = nodeFactory.createNode(expression, op, right); - } - return expression; -} - -ASTPointer Parser::parseUnaryExpression( - ASTPointer const& _lookAheadIndexAccessStructure) -{ - ASTNodeFactory nodeFactory = _lookAheadIndexAccessStructure ? - ASTNodeFactory(*this, _lookAheadIndexAccessStructure) : ASTNodeFactory(*this); - Token::Value token = m_scanner->getCurrentToken(); - if (!_lookAheadIndexAccessStructure && (Token::isUnaryOp(token) || Token::isCountOp(token))) - { - // prefix expression - m_scanner->next(); - ASTPointer subExpression = parseUnaryExpression(); - nodeFactory.setEndPositionFromNode(subExpression); - return nodeFactory.createNode(token, subExpression, true); - } - else - { - // potential postfix expression - ASTPointer subExpression = parseLeftHandSideExpression(_lookAheadIndexAccessStructure); - token = m_scanner->getCurrentToken(); - if (!Token::isCountOp(token)) - return subExpression; - nodeFactory.markEndPosition(); - m_scanner->next(); - return nodeFactory.createNode(token, subExpression, false); - } -} - -ASTPointer Parser::parseLeftHandSideExpression( - ASTPointer const& _lookAheadIndexAccessStructure) -{ - ASTNodeFactory nodeFactory = _lookAheadIndexAccessStructure ? - ASTNodeFactory(*this, _lookAheadIndexAccessStructure) : ASTNodeFactory(*this); - - ASTPointer expression; - if (_lookAheadIndexAccessStructure) - expression = _lookAheadIndexAccessStructure; - else if (m_scanner->getCurrentToken() == Token::New) - { - expectToken(Token::New); - ASTPointer contractName(parseIdentifier()); - nodeFactory.setEndPositionFromNode(contractName); - expression = nodeFactory.createNode(contractName); - } - else - expression = parsePrimaryExpression(); - - while (true) - { - switch (m_scanner->getCurrentToken()) - { - case Token::LBrack: - { - m_scanner->next(); - ASTPointer index; - if (m_scanner->getCurrentToken() != Token::RBrack) - index = parseExpression(); - nodeFactory.markEndPosition(); - expectToken(Token::RBrack); - expression = nodeFactory.createNode(expression, index); - } - break; - case Token::Period: - { - m_scanner->next(); - nodeFactory.markEndPosition(); - expression = nodeFactory.createNode(expression, expectIdentifierToken()); - } - break; - case Token::LParen: - { - m_scanner->next(); - vector> arguments; - vector> names; - std::tie(arguments, names) = parseFunctionCallArguments(); - nodeFactory.markEndPosition(); - expectToken(Token::RParen); - expression = nodeFactory.createNode(expression, arguments, names); - } - break; - default: - return expression; - } - } -} - -ASTPointer Parser::parsePrimaryExpression() -{ - ASTNodeFactory nodeFactory(*this); - Token::Value token = m_scanner->getCurrentToken(); - ASTPointer expression; - switch (token) - { - case Token::TrueLiteral: - case Token::FalseLiteral: - expression = nodeFactory.createNode(token, getLiteralAndAdvance()); - break; - case Token::Number: - if (Token::isEtherSubdenomination(m_scanner->peekNextToken())) - { - ASTPointer literal = getLiteralAndAdvance(); - nodeFactory.markEndPosition(); - Literal::SubDenomination subdenomination = static_cast(m_scanner->getCurrentToken()); - m_scanner->next(); - expression = nodeFactory.createNode(token, literal, subdenomination); - break; - } - if (Token::isTimeSubdenomination(m_scanner->peekNextToken())) - { - ASTPointer literal = getLiteralAndAdvance(); - nodeFactory.markEndPosition(); - Literal::SubDenomination subdenomination = static_cast(m_scanner->getCurrentToken()); - m_scanner->next(); - expression = nodeFactory.createNode(token, literal, subdenomination); - break; - } - // fall-through - case Token::StringLiteral: - nodeFactory.markEndPosition(); - expression = nodeFactory.createNode(token, getLiteralAndAdvance()); - break; - case Token::Identifier: - nodeFactory.markEndPosition(); - expression = nodeFactory.createNode(getLiteralAndAdvance()); - break; - case Token::LParen: - { - m_scanner->next(); - ASTPointer expression = parseExpression(); - expectToken(Token::RParen); - return expression; - } - default: - if (Token::isElementaryTypeName(token)) - { - // used for casts - expression = nodeFactory.createNode(token); - m_scanner->next(); - } - else - BOOST_THROW_EXCEPTION(createParserError("Expected primary expression.")); - break; - } - return expression; -} - -vector> Parser::parseFunctionCallListArguments() -{ - vector> arguments; - if (m_scanner->getCurrentToken() != Token::RParen) - { - arguments.push_back(parseExpression()); - while (m_scanner->getCurrentToken() != Token::RParen) - { - expectToken(Token::Comma); - arguments.push_back(parseExpression()); - } - } - return arguments; -} - -pair>, vector>> Parser::parseFunctionCallArguments() -{ - pair>, vector>> ret; - Token::Value token = m_scanner->getCurrentToken(); - if (token == Token::LBrace) - { - // call({arg1 : 1, arg2 : 2 }) - expectToken(Token::LBrace); - while (m_scanner->getCurrentToken() != Token::RBrace) - { - ret.second.push_back(expectIdentifierToken()); - expectToken(Token::Colon); - ret.first.push_back(parseExpression()); - - if (m_scanner->getCurrentToken() == Token::Comma) - expectToken(Token::Comma); - else - break; - } - expectToken(Token::RBrace); - } - else - ret.first = parseFunctionCallListArguments(); - return ret; -} - -Parser::LookAheadInfo Parser::peekStatementType() const -{ - // Distinguish between variable declaration (and potentially assignment) and expression statement - // (which include assignments to other expressions and pre-declared variables). - // We have a variable declaration if we get a keyword that specifies a type name. - // If it is an identifier or an elementary type name followed by an identifier, we also have - // a variable declaration. - // If we get an identifier followed by a "[", it can be both ("type[9] a;" or "arr[9] = 7;"). - // In all other cases, we have an expression statement. - Token::Value token(m_scanner->getCurrentToken()); - bool mightBeTypeName = (Token::isElementaryTypeName(token) || token == Token::Identifier); - - if (token == Token::Mapping || token == Token::Var) - return LookAheadInfo::VariableDeclarationStatement; - if (mightBeTypeName) - { - Token::Value next = m_scanner->peekNextToken(); - if (next == Token::Identifier || Token::isLocationSpecifier(next)) - return LookAheadInfo::VariableDeclarationStatement; - if (m_scanner->peekNextToken() == Token::LBrack) - return LookAheadInfo::IndexAccessStructure; - } - return LookAheadInfo::ExpressionStatement; -} - -ASTPointer Parser::typeNameIndexAccessStructure( - ASTPointer const& _primary, vector, SourceLocation>> const& _indices) -{ - ASTNodeFactory nodeFactory(*this, _primary); - ASTPointer type; - if (auto identifier = dynamic_cast(_primary.get())) - type = nodeFactory.createNode(make_shared(identifier->getName())); - else if (auto typeName = dynamic_cast(_primary.get())) - type = nodeFactory.createNode(typeName->getTypeToken()); - else - solAssert(false, "Invalid type name for array look-ahead."); - for (auto const& lengthExpression: _indices) - { - nodeFactory.setLocation(lengthExpression.second); - type = nodeFactory.createNode(type, lengthExpression.first); - } - return type; -} - -ASTPointer Parser::expressionFromIndexAccessStructure( - ASTPointer const& _primary, vector, SourceLocation>> const& _indices) -{ - ASTNodeFactory nodeFactory(*this, _primary); - ASTPointer expression(_primary); - for (auto const& index: _indices) - { - nodeFactory.setLocation(index.second); - expression = nodeFactory.createNode(expression, index.first); - } - return expression; -} - -void Parser::expectToken(Token::Value _value) -{ - if (m_scanner->getCurrentToken() != _value) - BOOST_THROW_EXCEPTION(createParserError(string("Expected token ") + string(Token::getName(_value)))); - m_scanner->next(); -} - -Token::Value Parser::expectAssignmentOperator() -{ - Token::Value op = m_scanner->getCurrentToken(); - if (!Token::isAssignmentOp(op)) - BOOST_THROW_EXCEPTION(createParserError("Expected assignment operator")); - m_scanner->next(); - return op; -} - -ASTPointer Parser::expectIdentifierToken() -{ - if (m_scanner->getCurrentToken() != Token::Identifier) - BOOST_THROW_EXCEPTION(createParserError("Expected identifier")); - return getLiteralAndAdvance(); -} - -ASTPointer Parser::getLiteralAndAdvance() -{ - ASTPointer identifier = make_shared(m_scanner->getCurrentLiteral()); - m_scanner->next(); - return identifier; -} - -ASTPointer Parser::createEmptyParameterList() -{ - ASTNodeFactory nodeFactory(*this); - nodeFactory.setLocationEmpty(); - return nodeFactory.createNode(vector>()); -} - -ParserError Parser::createParserError(string const& _description) const -{ - return ParserError() << errinfo_sourceLocation(SourceLocation(getPosition(), getPosition(), getSourceName())) - << errinfo_comment(_description); -} - - -} -} diff --git a/libsolidity/Parser.h b/libsolidity/Parser.h deleted file mode 100644 index d667aa3e1..000000000 --- a/libsolidity/Parser.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity parser. - */ - -#pragma once - -#include "libsolidity/AST.h" - -namespace dev -{ -namespace solidity -{ - -class Scanner; - -class Parser -{ -public: - Parser() {} - - ASTPointer parse(std::shared_ptr const& _scanner); - std::shared_ptr const& getSourceName() const; - -private: - class ASTNodeFactory; - - /// Start position of the current token - int getPosition() const; - /// End position of the current token - int getEndPosition() const; - - struct VarDeclParserOptions - { - VarDeclParserOptions() {} - bool allowVar = false; - bool isStateVariable = false; - bool allowIndexed = false; - bool allowEmptyName = false; - bool allowInitialValue = false; - bool allowLocationSpecifier = false; - }; - - ///@{ - ///@name Parsing functions for the AST nodes - ASTPointer parseImportDirective(); - ASTPointer parseContractDefinition(); - ASTPointer parseInheritanceSpecifier(); - Declaration::Visibility parseVisibilitySpecifier(Token::Value _token); - ASTPointer parseFunctionDefinition(ASTString const* _contractName); - ASTPointer parseStructDefinition(); - ASTPointer parseEnumDefinition(); - ASTPointer parseEnumValue(); - ASTPointer parseVariableDeclaration(VarDeclParserOptions const& _options = VarDeclParserOptions(), - ASTPointer const& _lookAheadArrayType = ASTPointer()); - ASTPointer parseModifierDefinition(); - ASTPointer parseEventDefinition(); - ASTPointer parseModifierInvocation(); - ASTPointer parseIdentifier(); - ASTPointer parseTypeName(bool _allowVar); - ASTPointer parseMapping(); - ASTPointer parseParameterList( - VarDeclParserOptions const& _options, - bool _allowEmpty = true - ); - ASTPointer parseBlock(); - ASTPointer parseStatement(); - ASTPointer parseIfStatement(); - ASTPointer parseWhileStatement(); - ASTPointer parseForStatement(); - /// A "simple statement" can be a variable declaration statement or an expression statement. - ASTPointer parseSimpleStatement(); - ASTPointer parseVariableDeclarationStatement( - ASTPointer const& _lookAheadArrayType = ASTPointer()); - ASTPointer parseExpressionStatement( - ASTPointer const& _lookAheadIndexAccessStructure = ASTPointer()); - ASTPointer parseExpression( - ASTPointer const& _lookAheadIndexAccessStructure = ASTPointer()); - ASTPointer parseBinaryExpression(int _minPrecedence = 4, - ASTPointer const& _lookAheadIndexAccessStructure = ASTPointer()); - ASTPointer parseUnaryExpression( - ASTPointer const& _lookAheadIndexAccessStructure = ASTPointer()); - ASTPointer parseLeftHandSideExpression( - ASTPointer const& _lookAheadIndexAccessStructure = ASTPointer()); - ASTPointer parsePrimaryExpression(); - std::vector> parseFunctionCallListArguments(); - std::pair>, std::vector>> parseFunctionCallArguments(); - ///@} - - ///@{ - ///@name Helper functions - - /// Used as return value of @see peekStatementType. - enum class LookAheadInfo - { - IndexAccessStructure, VariableDeclarationStatement, ExpressionStatement - }; - - /// Performs limited look-ahead to distinguish between variable declaration and expression statement. - /// For source code of the form "a[][8]" ("IndexAccessStructure"), this is not possible to - /// decide with constant look-ahead. - LookAheadInfo peekStatementType() const; - /// Returns a typename parsed in look-ahead fashion from something like "a[8][2**70]". - ASTPointer typeNameIndexAccessStructure( - ASTPointer const& _primary, - std::vector, SourceLocation>> const& _indices); - /// Returns an expression parsed in look-ahead fashion from something like "a[8][2**70]". - ASTPointer expressionFromIndexAccessStructure( - ASTPointer const& _primary, - std::vector, SourceLocation>> const& _indices); - /// If current token value is not _value, throw exception otherwise advance token. - void expectToken(Token::Value _value); - Token::Value expectAssignmentOperator(); - ASTPointer expectIdentifierToken(); - ASTPointer getLiteralAndAdvance(); - ///@} - - /// Creates an empty ParameterList at the current location (used if parameters can be omitted). - ASTPointer createEmptyParameterList(); - - /// Creates a @ref ParserError exception and annotates it with the current position and the - /// given @a _description. - ParserError createParserError(std::string const& _description) const; - - std::shared_ptr m_scanner; - /// Flag that signifies whether '_' is parsed as a PlaceholderStatement or a regular identifier. - bool m_insideModifier = false; -}; - -} -} diff --git a/libsolidity/Scanner.cpp b/libsolidity/Scanner.cpp deleted file mode 100644 index fbe3ea974..000000000 --- a/libsolidity/Scanner.cpp +++ /dev/null @@ -1,769 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . - - This file is derived from the file "scanner.cc", which was part of the - V8 project. The original copyright header follows: - - Copyright 2006-2012, the V8 project authors. All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of Google Inc. nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/** - * @author Christian - * @date 2014 - * Solidity scanner. - */ - -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -namespace -{ -bool isDecimalDigit(char c) -{ - return '0' <= c && c <= '9'; -} -bool isHexDigit(char c) -{ - return isDecimalDigit(c) - || ('a' <= c && c <= 'f') - || ('A' <= c && c <= 'F'); -} -bool isLineTerminator(char c) -{ - return c == '\n'; -} -bool isWhiteSpace(char c) -{ - return c == ' ' || c == '\n' || c == '\t' || c == '\r'; -} -bool isIdentifierStart(char c) -{ - return c == '_' || c == '$' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); -} -bool isIdentifierPart(char c) -{ - return isIdentifierStart(c) || isDecimalDigit(c); -} - -int hexValue(char c) -{ - if (c >= '0' && c <= '9') - return c - '0'; - else if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - return c - 'A' + 10; - else return -1; -} -} // end anonymous namespace - - - -/// Scoped helper for literal recording. Automatically drops the literal -/// if aborting the scanning before it's complete. -enum LiteralType { - LITERAL_TYPE_STRING, - LITERAL_TYPE_NUMBER, // not really different from string type in behaviour - LITERAL_TYPE_COMMENT -}; - -class LiteralScope -{ -public: - explicit LiteralScope(Scanner* _self, enum LiteralType _type): m_type(_type) - , m_scanner(_self) - , m_complete(false) - { - if (_type == LITERAL_TYPE_COMMENT) - m_scanner->m_nextSkippedComment.literal.clear(); - else - m_scanner->m_nextToken.literal.clear(); - } - ~LiteralScope() - { - if (!m_complete) - { - if (m_type == LITERAL_TYPE_COMMENT) - m_scanner->m_nextSkippedComment.literal.clear(); - else - m_scanner->m_nextToken.literal.clear(); - } - } - void complete() { m_complete = true; } - -private: - enum LiteralType m_type; - Scanner* m_scanner; - bool m_complete; -}; // end of LiteralScope class - - -void Scanner::reset(CharStream const& _source, string const& _sourceName) -{ - m_source = _source; - m_sourceName = make_shared(_sourceName); - reset(); -} - -void Scanner::reset() -{ - m_source.reset(); - m_char = m_source.get(); - skipWhitespace(); - scanToken(); - next(); -} - -bool Scanner::scanHexByte(char& o_scannedByte) -{ - char x = 0; - for (int i = 0; i < 2; i++) - { - int d = hexValue(m_char); - if (d < 0) - { - rollback(i); - return false; - } - x = x * 16 + d; - advance(); - } - o_scannedByte = x; - return true; -} - - -// Ensure that tokens can be stored in a byte. -BOOST_STATIC_ASSERT(Token::NUM_TOKENS <= 0x100); - -Token::Value Scanner::next() -{ - m_currentToken = m_nextToken; - m_skippedComment = m_nextSkippedComment; - scanToken(); - - return m_currentToken.token; -} - -Token::Value Scanner::selectToken(char _next, Token::Value _then, Token::Value _else) -{ - advance(); - if (m_char == _next) - return selectToken(_then); - else - return _else; -} - -bool Scanner::skipWhitespace() -{ - int const startPosition = getSourcePos(); - while (isWhiteSpace(m_char)) - advance(); - // Return whether or not we skipped any characters. - return getSourcePos() != startPosition; -} - -bool Scanner::skipWhitespaceExceptLF() -{ - int const startPosition = getSourcePos(); - while (isWhiteSpace(m_char) && !isLineTerminator(m_char)) - advance(); - // Return whether or not we skipped any characters. - return getSourcePos() != startPosition; -} - -Token::Value Scanner::skipSingleLineComment() -{ - // The line terminator at the end of the line is not considered - // to be part of the single-line comment; it is recognized - // separately by the lexical grammar and becomes part of the - // stream of input elements for the syntactic grammar - while (advance() && !isLineTerminator(m_char)) { }; - return Token::Whitespace; -} - -Token::Value Scanner::scanSingleLineDocComment() -{ - LiteralScope literal(this, LITERAL_TYPE_COMMENT); - advance(); //consume the last '/' at /// - skipWhitespaceExceptLF(); - while (!isSourcePastEndOfInput()) - { - if (isLineTerminator(m_char)) - { - // check if next line is also a documentation comment - skipWhitespace(); - if (!m_source.isPastEndOfInput(3) && - m_source.get(0) == '/' && - m_source.get(1) == '/' && - m_source.get(2) == '/') - { - addCommentLiteralChar('\n'); - m_char = m_source.advanceAndGet(3); - } - else - break; // next line is not a documentation comment, we are done - - } - addCommentLiteralChar(m_char); - advance(); - } - literal.complete(); - return Token::CommentLiteral; -} - -Token::Value Scanner::skipMultiLineComment() -{ - advance(); - while (!isSourcePastEndOfInput()) - { - char ch = m_char; - advance(); - - // If we have reached the end of the multi-line comment, we - // consume the '/' and insert a whitespace. This way all - // multi-line comments are treated as whitespace. - if (ch == '*' && m_char == '/') - { - m_char = ' '; - return Token::Whitespace; - } - } - // Unterminated multi-line comment. - return Token::Illegal; -} - -Token::Value Scanner::scanMultiLineDocComment() -{ - LiteralScope literal(this, LITERAL_TYPE_COMMENT); - bool endFound = false; - bool charsAdded = false; - - while (!isSourcePastEndOfInput()) - { - //handle newlines in multline comments - if (isLineTerminator(m_char)) - { - skipWhitespace(); - if (!m_source.isPastEndOfInput(1) && m_source.get(0) == '*' && m_source.get(1) != '/') - { // skip first '*' in subsequent lines - if (charsAdded) - addCommentLiteralChar('\n'); - m_char = m_source.advanceAndGet(2); - } - else if (!m_source.isPastEndOfInput(1) && m_source.get(0) == '*' && m_source.get(1) == '/') - { // if after newline the comment ends, don't insert the newline - m_char = m_source.advanceAndGet(2); - endFound = true; - break; - } - else if (charsAdded) - addCommentLiteralChar('\n'); - } - - if (!m_source.isPastEndOfInput(1) && m_source.get(0) == '*' && m_source.get(1) == '/') - { - m_char = m_source.advanceAndGet(2); - endFound = true; - break; - } - addCommentLiteralChar(m_char); - charsAdded = true; - advance(); - } - literal.complete(); - if (!endFound) - return Token::Illegal; - else - return Token::CommentLiteral; -} - -Token::Value Scanner::scanSlash() -{ - int firstSlashPosition = getSourcePos(); - advance(); - if (m_char == '/') - { - if (!advance()) /* double slash comment directly before EOS */ - return Token::Whitespace; - else if (m_char == '/') - { - // doxygen style /// comment - Token::Value comment; - m_nextSkippedComment.location.start = firstSlashPosition; - comment = scanSingleLineDocComment(); - m_nextSkippedComment.location.end = getSourcePos(); - m_nextSkippedComment.token = comment; - return Token::Whitespace; - } - else - return skipSingleLineComment(); - } - else if (m_char == '*') - { - // doxygen style /** natspec comment - if (!advance()) /* slash star comment before EOS */ - return Token::Whitespace; - else if (m_char == '*') - { - advance(); //consume the last '*' at /** - skipWhitespaceExceptLF(); - - // special case of a closed normal multiline comment - if (!m_source.isPastEndOfInput() && m_source.get(0) == '/') - advance(); //skip the closing slash - else // we actually have a multiline documentation comment - { - Token::Value comment; - m_nextSkippedComment.location.start = firstSlashPosition; - comment = scanMultiLineDocComment(); - m_nextSkippedComment.location.end = getSourcePos(); - m_nextSkippedComment.token = comment; - } - return Token::Whitespace; - } - else - return skipMultiLineComment(); - } - else if (m_char == '=') - return selectToken(Token::AssignDiv); - else - return Token::Div; -} - -void Scanner::scanToken() -{ - m_nextToken.literal.clear(); - m_nextSkippedComment.literal.clear(); - Token::Value token; - do - { - // Remember the position of the next token - m_nextToken.location.start = getSourcePos(); - switch (m_char) - { - case '\n': // fall-through - case ' ': - case '\t': - token = selectToken(Token::Whitespace); - break; - case '"': - case '\'': - token = scanString(); - break; - case '<': - // < <= << <<= - advance(); - if (m_char == '=') - token = selectToken(Token::LessThanOrEqual); - else if (m_char == '<') - token = selectToken('=', Token::AssignShl, Token::SHL); - else - token = Token::LessThan; - break; - case '>': - // > >= >> >>= >>> >>>= - advance(); - if (m_char == '=') - token = selectToken(Token::GreaterThanOrEqual); - else if (m_char == '>') - { - // >> >>= >>> >>>= - advance(); - if (m_char == '=') - token = selectToken(Token::AssignSar); - else if (m_char == '>') - token = selectToken('=', Token::AssignShr, Token::SHR); - else - token = Token::SAR; - } - else - token = Token::GreaterThan; - break; - case '=': - // = == => - advance(); - if (m_char == '=') - token = selectToken(Token::Equal); - else if (m_char == '>') - token = selectToken(Token::Arrow); - else - token = Token::Assign; - break; - case '!': - // ! != - advance(); - if (m_char == '=') - token = selectToken(Token::NotEqual); - else - token = Token::Not; - break; - case '+': - // + ++ += - advance(); - if (m_char == '+') - token = selectToken(Token::Inc); - else if (m_char == '=') - token = selectToken(Token::AssignAdd); - else - token = Token::Add; - break; - case '-': - // - -- -= - advance(); - if (m_char == '-') - token = selectToken(Token::Dec); - else if (m_char == '=') - token = selectToken(Token::AssignSub); - else - token = Token::Sub; - break; - case '*': - // * ** *= - advance(); - if (m_char == '*') - token = selectToken(Token::Exp); - else if (m_char == '=') - token = selectToken(Token::AssignMul); - else - token = Token::Mul; - break; - case '%': - // % %= - token = selectToken('=', Token::AssignMod, Token::Mod); - break; - case '/': - // / // /* /= - token = scanSlash(); - break; - case '&': - // & && &= - advance(); - if (m_char == '&') - token = selectToken(Token::And); - else if (m_char == '=') - token = selectToken(Token::AssignBitAnd); - else - token = Token::BitAnd; - break; - case '|': - // | || |= - advance(); - if (m_char == '|') - token = selectToken(Token::Or); - else if (m_char == '=') - token = selectToken(Token::AssignBitOr); - else - token = Token::BitOr; - break; - case '^': - // ^ ^= - token = selectToken('=', Token::AssignBitXor, Token::BitXor); - break; - case '.': - // . Number - advance(); - if (isDecimalDigit(m_char)) - token = scanNumber('.'); - else - token = Token::Period; - break; - case ':': - token = selectToken(Token::Colon); - break; - case ';': - token = selectToken(Token::Semicolon); - break; - case ',': - token = selectToken(Token::Comma); - break; - case '(': - token = selectToken(Token::LParen); - break; - case ')': - token = selectToken(Token::RParen); - break; - case '[': - token = selectToken(Token::LBrack); - break; - case ']': - token = selectToken(Token::RBrack); - break; - case '{': - token = selectToken(Token::LBrace); - break; - case '}': - token = selectToken(Token::RBrace); - break; - case '?': - token = selectToken(Token::Conditional); - break; - case '~': - token = selectToken(Token::BitNot); - break; - default: - if (isIdentifierStart(m_char)) - token = scanIdentifierOrKeyword(); - else if (isDecimalDigit(m_char)) - token = scanNumber(); - else if (skipWhitespace()) - token = Token::Whitespace; - else if (isSourcePastEndOfInput()) - token = Token::EOS; - else - token = selectToken(Token::Illegal); - break; - } - // Continue scanning for tokens as long as we're just skipping - // whitespace. - } - while (token == Token::Whitespace); - m_nextToken.location.end = getSourcePos(); - m_nextToken.token = token; -} - -bool Scanner::scanEscape() -{ - char c = m_char; - advance(); - // Skip escaped newlines. - if (isLineTerminator(c)) - return true; - switch (c) - { - case '\'': // fall through - case '"': // fall through - case '\\': - break; - case 'b': - c = '\b'; - break; - case 'f': - c = '\f'; - break; - case 'n': - c = '\n'; - break; - case 'r': - c = '\r'; - break; - case 't': - c = '\t'; - break; - case 'v': - c = '\v'; - break; - case 'x': - if (!scanHexByte(c)) - return false; - break; - } - - addLiteralChar(c); - return true; -} - -Token::Value Scanner::scanString() -{ - char const quote = m_char; - advance(); // consume quote - LiteralScope literal(this, LITERAL_TYPE_STRING); - while (m_char != quote && !isSourcePastEndOfInput() && !isLineTerminator(m_char)) - { - char c = m_char; - advance(); - if (c == '\\') - { - if (isSourcePastEndOfInput() || !scanEscape()) - return Token::Illegal; - } - else - addLiteralChar(c); - } - if (m_char != quote) - return Token::Illegal; - literal.complete(); - advance(); // consume quote - return Token::StringLiteral; -} - -void Scanner::scanDecimalDigits() -{ - while (isDecimalDigit(m_char)) - addLiteralCharAndAdvance(); -} - -Token::Value Scanner::scanNumber(char _charSeen) -{ - enum { DECIMAL, HEX, BINARY } kind = DECIMAL; - LiteralScope literal(this, LITERAL_TYPE_NUMBER); - if (_charSeen == '.') - { - // we have already seen a decimal point of the float - addLiteralChar('.'); - scanDecimalDigits(); // we know we have at least one digit - } - else - { - solAssert(_charSeen == 0, ""); - // if the first character is '0' we must check for octals and hex - if (m_char == '0') - { - addLiteralCharAndAdvance(); - // either 0, 0exxx, 0Exxx, 0.xxx or a hex number - if (m_char == 'x' || m_char == 'X') - { - // hex number - kind = HEX; - addLiteralCharAndAdvance(); - if (!isHexDigit(m_char)) - return Token::Illegal; // we must have at least one hex digit after 'x'/'X' - while (isHexDigit(m_char)) - addLiteralCharAndAdvance(); - } - } - // Parse decimal digits and allow trailing fractional part. - if (kind == DECIMAL) - { - scanDecimalDigits(); // optional - if (m_char == '.') - { - addLiteralCharAndAdvance(); - scanDecimalDigits(); // optional - } - } - } - // scan exponent, if any - if (m_char == 'e' || m_char == 'E') - { - solAssert(kind != HEX, "'e'/'E' must be scanned as part of the hex number"); - if (kind != DECIMAL) - return Token::Illegal; - // scan exponent - addLiteralCharAndAdvance(); - if (m_char == '+' || m_char == '-') - addLiteralCharAndAdvance(); - if (!isDecimalDigit(m_char)) - return Token::Illegal; // we must have at least one decimal digit after 'e'/'E' - scanDecimalDigits(); - } - // The source character immediately following a numeric literal must - // not be an identifier start or a decimal digit; see ECMA-262 - // section 7.8.3, page 17 (note that we read only one decimal digit - // if the value is 0). - if (isDecimalDigit(m_char) || isIdentifierStart(m_char)) - return Token::Illegal; - literal.complete(); - return Token::Number; -} - -Token::Value Scanner::scanIdentifierOrKeyword() -{ - solAssert(isIdentifierStart(m_char), ""); - LiteralScope literal(this, LITERAL_TYPE_STRING); - addLiteralCharAndAdvance(); - // Scan the rest of the identifier characters. - while (isIdentifierPart(m_char)) - addLiteralCharAndAdvance(); - literal.complete(); - return Token::fromIdentifierOrKeyword(m_nextToken.literal); -} - -char CharStream::advanceAndGet(size_t _chars) -{ - if (isPastEndOfInput()) - return 0; - m_pos += _chars; - if (isPastEndOfInput()) - return 0; - return m_source[m_pos]; -} - -char CharStream::rollback(size_t _amount) -{ - solAssert(m_pos >= _amount, ""); - m_pos -= _amount; - return get(); -} - -string CharStream::getLineAtPosition(int _position) const -{ - // if _position points to \n, it returns the line before the \n - using size_type = string::size_type; - size_type searchStart = min(m_source.size(), _position); - if (searchStart > 0) - searchStart--; - size_type lineStart = m_source.rfind('\n', searchStart); - if (lineStart == string::npos) - lineStart = 0; - else - lineStart++; - return m_source.substr(lineStart, min(m_source.find('\n', lineStart), - m_source.size()) - lineStart); -} - -tuple CharStream::translatePositionToLineColumn(int _position) const -{ - using size_type = string::size_type; - size_type searchPosition = min(m_source.size(), _position); - int lineNumber = count(m_source.begin(), m_source.begin() + searchPosition, '\n'); - size_type lineStart; - if (searchPosition == 0) - lineStart = 0; - else - { - lineStart = m_source.rfind('\n', searchPosition - 1); - lineStart = lineStart == string::npos ? 0 : lineStart + 1; - } - return tuple(lineNumber, searchPosition - lineStart); -} - - -} -} diff --git a/libsolidity/Scanner.h b/libsolidity/Scanner.h deleted file mode 100644 index 43fcd133c..000000000 --- a/libsolidity/Scanner.h +++ /dev/null @@ -1,224 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . - - This file is derived from the file "scanner.h", which was part of the - V8 project. The original copyright header follows: - - Copyright 2006-2012, the V8 project authors. All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of Google Inc. nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/** - * @author Christian - * @date 2014 - * Solidity scanner. - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - - -class AstRawString; -class AstValueFactory; -class ParserRecorder; - -class CharStream -{ -public: - CharStream(): m_pos(0) {} - explicit CharStream(std::string const& _source): m_source(_source), m_pos(0) {} - int getPos() const { return m_pos; } - bool isPastEndOfInput(size_t _charsForward = 0) const { return (m_pos + _charsForward) >= m_source.size(); } - char get(size_t _charsForward = 0) const { return m_source[m_pos + _charsForward]; } - char advanceAndGet(size_t _chars=1); - char rollback(size_t _amount); - - void reset() { m_pos = 0; } - - ///@{ - ///@name Error printing helper functions - /// Functions that help pretty-printing parse errors - /// Do only use in error cases, they are quite expensive. - std::string getLineAtPosition(int _position) const; - std::tuple translatePositionToLineColumn(int _position) const; - ///@} - -private: - std::string m_source; - size_t m_pos; -}; - - - -class Scanner -{ - friend class LiteralScope; -public: - - explicit Scanner(CharStream const& _source = CharStream(), std::string const& _sourceName = "") { reset(_source, _sourceName); } - - /// Resets the scanner as if newly constructed with _source and _sourceName as input. - void reset(CharStream const& _source, std::string const& _sourceName); - /// Resets scanner to the start of input. - void reset(); - - /// Returns the next token and advances input - Token::Value next(); - - ///@{ - ///@name Information about the current token - - /// Returns the current token - Token::Value getCurrentToken() - { - return m_currentToken.token; - } - - SourceLocation getCurrentLocation() const { return m_currentToken.location; } - std::string const& getCurrentLiteral() const { return m_currentToken.literal; } - ///@} - - ///@{ - ///@name Information about the current comment token - - SourceLocation getCurrentCommentLocation() const { return m_skippedComment.location; } - std::string const& getCurrentCommentLiteral() const { return m_skippedComment.literal; } - /// Called by the parser during FunctionDefinition parsing to clear the current comment - void clearCurrentCommentLiteral() { m_skippedComment.literal.clear(); } - - ///@} - - ///@{ - ///@name Information about the next token - - /// Returns the next token without advancing input. - Token::Value peekNextToken() const { return m_nextToken.token; } - SourceLocation peekLocation() const { return m_nextToken.location; } - std::string const& peekLiteral() const { return m_nextToken.literal; } - ///@} - - std::shared_ptr const& getSourceName() const { return m_sourceName; } - - ///@{ - ///@name Error printing helper functions - /// Functions that help pretty-printing parse errors - /// Do only use in error cases, they are quite expensive. - std::string getLineAtPosition(int _position) const { return m_source.getLineAtPosition(_position); } - std::tuple translatePositionToLineColumn(int _position) const { return m_source.translatePositionToLineColumn(_position); } - ///@} - -private: - /// Used for the current and look-ahead token and comments - struct TokenDesc - { - Token::Value token; - SourceLocation location; - std::string literal; - }; - - ///@{ - ///@name Literal buffer support - inline void addLiteralChar(char c) { m_nextToken.literal.push_back(c); } - inline void addCommentLiteralChar(char c) { m_nextSkippedComment.literal.push_back(c); } - inline void addLiteralCharAndAdvance() { addLiteralChar(m_char); advance(); } - ///@} - - bool advance() { m_char = m_source.advanceAndGet(); return !m_source.isPastEndOfInput(); } - void rollback(int _amount) { m_char = m_source.rollback(_amount); } - - inline Token::Value selectToken(Token::Value _tok) { advance(); return _tok; } - /// If the next character is _next, advance and return _then, otherwise return _else. - inline Token::Value selectToken(char _next, Token::Value _then, Token::Value _else); - - bool scanHexByte(char& o_scannedByte); - - /// Scans a single Solidity token. - void scanToken(); - - /// Skips all whitespace and @returns true if something was skipped. - bool skipWhitespace(); - /// Skips all whitespace except Line feeds and returns true if something was skipped - bool skipWhitespaceExceptLF(); - Token::Value skipSingleLineComment(); - Token::Value skipMultiLineComment(); - - void scanDecimalDigits(); - Token::Value scanNumber(char _charSeen = 0); - Token::Value scanIdentifierOrKeyword(); - - Token::Value scanString(); - Token::Value scanSingleLineDocComment(); - Token::Value scanMultiLineDocComment(); - /// Scans a slash '/' and depending on the characters returns the appropriate token - Token::Value scanSlash(); - - /// Scans an escape-sequence which is part of a string and adds the - /// decoded character to the current literal. Returns true if a pattern - /// is scanned. - bool scanEscape(); - - /// Return the current source position. - int getSourcePos() { return m_source.getPos(); } - bool isSourcePastEndOfInput() { return m_source.isPastEndOfInput(); } - - TokenDesc m_skippedComment; // desc for current skipped comment - TokenDesc m_nextSkippedComment; // desc for next skiped comment - - TokenDesc m_currentToken; // desc for current token (as returned by Next()) - TokenDesc m_nextToken; // desc for next token (one token look-ahead) - - CharStream m_source; - std::shared_ptr m_sourceName; - - /// one character look-ahead, equals 0 at end of input - char m_char; -}; - -} -} diff --git a/libsolidity/SourceReferenceFormatter.cpp b/libsolidity/SourceReferenceFormatter.cpp deleted file mode 100644 index 77805efc8..000000000 --- a/libsolidity/SourceReferenceFormatter.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Formatting functions for errors referencing positions and locations in the source. - */ - -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -void SourceReferenceFormatter::printSourceLocation( - ostream& _stream, - SourceLocation const& _location, - Scanner const& _scanner -) -{ - int startLine; - int startColumn; - tie(startLine, startColumn) = _scanner.translatePositionToLineColumn(_location.start); - int endLine; - int endColumn; - tie(endLine, endColumn) = _scanner.translatePositionToLineColumn(_location.end); - if (startLine == endLine) - { - string line = _scanner.getLineAtPosition(_location.start); - _stream << line << endl; - for_each( - line.cbegin(), - line.cbegin() + startColumn, - [&_stream](char const& ch) { _stream << (ch == '\t' ? '\t' : ' '); } - ); - _stream << "^"; - if (endColumn > startColumn + 2) - _stream << string(endColumn - startColumn - 2, '-'); - if (endColumn > startColumn + 1) - _stream << "^"; - _stream << endl; - } - else - _stream << - _scanner.getLineAtPosition(_location.start) << - endl << - string(startColumn, ' ') << - "^\n" << - "Spanning multiple lines.\n"; -} - -void SourceReferenceFormatter::printSourceName( - ostream& _stream, - SourceLocation const& _location, - Scanner const& _scanner -) -{ - int startLine; - int startColumn; - tie(startLine, startColumn) = _scanner.translatePositionToLineColumn(_location.start); - _stream << *_location.sourceName << ":" << (startLine + 1) << ":" << (startColumn + 1) << ": "; -} - -void SourceReferenceFormatter::printExceptionInformation( - ostream& _stream, - Exception const& _exception, - string const& _name, - CompilerStack const& _compiler -) -{ - SourceLocation const* location = boost::get_error_info(_exception); - auto secondarylocation = boost::get_error_info(_exception); - Scanner const* scanner = nullptr; - - if (location) - { - scanner = &_compiler.getScanner(*location->sourceName); - printSourceName(_stream, *location, *scanner); - } - - _stream << _name; - if (string const* description = boost::get_error_info(_exception)) - _stream << ": " << *description << endl; - - if (location) - { - scanner = &_compiler.getScanner(*location->sourceName); - printSourceLocation(_stream, *location, *scanner); - } - - if (secondarylocation && !secondarylocation->infos.empty()) - { - for (auto info: secondarylocation->infos) - { - scanner = &_compiler.getScanner(*info.second.sourceName); - _stream << info.first << " "; - printSourceName(_stream, info.second, *scanner); - _stream << endl; - printSourceLocation(_stream, info.second, *scanner); - } - _stream << endl; - } -} - -} -} diff --git a/libsolidity/SourceReferenceFormatter.h b/libsolidity/SourceReferenceFormatter.h deleted file mode 100644 index dd258c276..000000000 --- a/libsolidity/SourceReferenceFormatter.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Formatting functions for errors referencing positions and locations in the source. - */ - -#pragma once - -#include -#include - -namespace dev -{ - -struct Exception; // forward - -namespace solidity -{ - -class Scanner; // forward -class CompilerStack; // forward - -struct SourceReferenceFormatter -{ -public: - static void printSourceLocation(std::ostream& _stream, SourceLocation const& _location, Scanner const& _scanner); - static void printExceptionInformation( - std::ostream& _stream, - Exception const& _exception, - std::string const& _name, - CompilerStack const& _compiler - ); -private: - static void printSourceName(std::ostream& _stream, SourceLocation const& _location, Scanner const& _scanner); -}; - -} -} diff --git a/libsolidity/Token.cpp b/libsolidity/Token.cpp deleted file mode 100644 index d07d75021..000000000 --- a/libsolidity/Token.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2006-2012, the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Modifications as part of cpp-ethereum under the following license: -// -// cpp-ethereum 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. -// -// cpp-ethereum 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 cpp-ethereum. If not, see . - -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ - -#define T(name, string, precedence) #name, -char const* const Token::m_name[NUM_TOKENS] = -{ - TOKEN_LIST(T, T) -}; -#undef T - - -#define T(name, string, precedence) string, -char const* const Token::m_string[NUM_TOKENS] = -{ - TOKEN_LIST(T, T) -}; -#undef T - - -#define T(name, string, precedence) precedence, -int8_t const Token::m_precedence[NUM_TOKENS] = -{ - TOKEN_LIST(T, T) -}; -#undef T - - -#define KT(a, b, c) 'T', -#define KK(a, b, c) 'K', -char const Token::m_tokenType[] = -{ - TOKEN_LIST(KT, KK) -}; -Token::Value Token::fromIdentifierOrKeyword(const std::string& _name) -{ - // The following macros are used inside TOKEN_LIST and cause non-keyword tokens to be ignored - // and keywords to be put inside the keywords variable. -#define KEYWORD(name, string, precedence) {string, Token::name}, -#define TOKEN(name, string, precedence) - static const map keywords({TOKEN_LIST(TOKEN, KEYWORD)}); -#undef KEYWORD -#undef TOKEN - auto it = keywords.find(_name); - return it == keywords.end() ? Token::Identifier : it->second; -} - -#undef KT -#undef KK - -} -} diff --git a/libsolidity/Token.h b/libsolidity/Token.h deleted file mode 100644 index 7c7b1c7ff..000000000 --- a/libsolidity/Token.h +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright 2006-2012, the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Modifications as part of cpp-ethereum under the following license: -// -// cpp-ethereum 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. -// -// cpp-ethereum 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 cpp-ethereum. If not, see . - -#pragma once - -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -// TOKEN_LIST takes a list of 3 macros M, all of which satisfy the -// same signature M(name, string, precedence), where name is the -// symbolic token name, string is the corresponding syntactic symbol -// (or NULL, for literals), and precedence is the precedence (or 0). -// The parameters are invoked for token categories as follows: -// -// T: Non-keyword tokens -// K: Keyword tokens - -// IGNORE_TOKEN is a convenience macro that can be supplied as -// an argument (at any position) for a TOKEN_LIST call. It does -// nothing with tokens belonging to the respective category. - -#define IGNORE_TOKEN(name, string, precedence) - -#define TOKEN_LIST(T, K) \ - /* End of source indicator. */ \ - T(EOS, "EOS", 0) \ - \ - /* Punctuators (ECMA-262, section 7.7, page 15). */ \ - T(LParen, "(", 0) \ - T(RParen, ")", 0) \ - T(LBrack, "[", 0) \ - T(RBrack, "]", 0) \ - T(LBrace, "{", 0) \ - T(RBrace, "}", 0) \ - T(Colon, ":", 0) \ - T(Semicolon, ";", 0) \ - T(Period, ".", 0) \ - T(Conditional, "?", 3) \ - T(Arrow, "=>", 0) \ - \ - /* Assignment operators. */ \ - /* IsAssignmentOp() relies on this block of enum values being */ \ - /* contiguous and sorted in the same order!*/ \ - T(Assign, "=", 2) \ - /* The following have to be in exactly the same order as the simple binary operators*/ \ - T(AssignBitOr, "|=", 2) \ - T(AssignBitXor, "^=", 2) \ - T(AssignBitAnd, "&=", 2) \ - T(AssignShl, "<<=", 2) \ - T(AssignSar, ">>=", 2) \ - T(AssignShr, ">>>=", 2) \ - T(AssignAdd, "+=", 2) \ - T(AssignSub, "-=", 2) \ - T(AssignMul, "*=", 2) \ - T(AssignDiv, "/=", 2) \ - T(AssignMod, "%=", 2) \ - \ - /* Binary operators sorted by precedence. */ \ - /* IsBinaryOp() relies on this block of enum values */ \ - /* being contiguous and sorted in the same order! */ \ - T(Comma, ",", 1) \ - T(Or, "||", 4) \ - T(And, "&&", 5) \ - T(BitOr, "|", 8) \ - T(BitXor, "^", 9) \ - T(BitAnd, "&", 10) \ - T(SHL, "<<", 11) \ - T(SAR, ">>", 11) \ - T(SHR, ">>>", 11) \ - T(Add, "+", 12) \ - T(Sub, "-", 12) \ - T(Mul, "*", 13) \ - T(Div, "/", 13) \ - T(Mod, "%", 13) \ - T(Exp, "**", 14) \ - \ - /* Compare operators sorted by precedence. */ \ - /* IsCompareOp() relies on this block of enum values */ \ - /* being contiguous and sorted in the same order! */ \ - T(Equal, "==", 6) \ - T(NotEqual, "!=", 6) \ - T(LessThan, "<", 7) \ - T(GreaterThan, ">", 7) \ - T(LessThanOrEqual, "<=", 7) \ - T(GreaterThanOrEqual, ">=", 7) \ - K(In, "in", 7) \ - \ - /* Unary operators. */ \ - /* IsUnaryOp() relies on this block of enum values */ \ - /* being contiguous and sorted in the same order! */ \ - T(Not, "!", 0) \ - T(BitNot, "~", 0) \ - T(Inc, "++", 0) \ - T(Dec, "--", 0) \ - K(Delete, "delete", 0) \ - \ - /* Keywords */ \ - K(Anonymous, "anonymous", 0) \ - K(Break, "break", 0) \ - K(Const, "constant", 0) \ - K(Continue, "continue", 0) \ - K(Contract, "contract", 0) \ - K(Default, "default", 0) \ - K(Do, "do", 0) \ - K(Else, "else", 0) \ - K(Enum, "enum", 0) \ - K(Event, "event", 0) \ - K(External, "external", 0) \ - K(For, "for", 0) \ - K(Function, "function", 0) \ - K(If, "if", 0) \ - K(Indexed, "indexed", 0) \ - K(Internal, "internal", 0) \ - K(Import, "import", 0) \ - K(Is, "is", 0) \ - K(Mapping, "mapping", 0) \ - K(Memory, "memory", 0) \ - K(Modifier, "modifier", 0) \ - K(New, "new", 0) \ - K(Public, "public", 0) \ - K(Private, "private", 0) \ - K(Return, "return", 0) \ - K(Returns, "returns", 0) \ - K(Storage, "storage", 0) \ - K(Struct, "struct", 0) \ - K(Var, "var", 0) \ - K(While, "while", 0) \ - \ - /* Ether subdenominations */ \ - K(SubWei, "wei", 0) \ - K(SubSzabo, "szabo", 0) \ - K(SubFinney, "finney", 0) \ - K(SubEther, "ether", 0) \ - K(SubSecond, "seconds", 0) \ - K(SubMinute, "minutes", 0) \ - K(SubHour, "hours", 0) \ - K(SubDay, "days", 0) \ - K(SubWeek, "weeks", 0) \ - K(SubYear, "years", 0) \ - K(After, "after", 0) \ - /* type keywords, keep them in this order, keep int as first keyword - * the implementation in Types.cpp has to be synced to this here */\ - K(Int, "int", 0) \ - K(Int8, "int8", 0) \ - K(Int16, "int16", 0) \ - K(Int24, "int24", 0) \ - K(Int32, "int32", 0) \ - K(Int40, "int40", 0) \ - K(Int48, "int48", 0) \ - K(Int56, "int56", 0) \ - K(Int64, "int64", 0) \ - K(Int72, "int72", 0) \ - K(Int80, "int80", 0) \ - K(Int88, "int88", 0) \ - K(Int96, "int96", 0) \ - K(Int104, "int104", 0) \ - K(Int112, "int112", 0) \ - K(Int120, "int120", 0) \ - K(Int128, "int128", 0) \ - K(Int136, "int136", 0) \ - K(Int144, "int144", 0) \ - K(Int152, "int152", 0) \ - K(Int160, "int160", 0) \ - K(Int168, "int168", 0) \ - K(Int176, "int178", 0) \ - K(Int184, "int184", 0) \ - K(Int192, "int192", 0) \ - K(Int200, "int200", 0) \ - K(Int208, "int208", 0) \ - K(Int216, "int216", 0) \ - K(Int224, "int224", 0) \ - K(Int232, "int232", 0) \ - K(Int240, "int240", 0) \ - K(Int248, "int248", 0) \ - K(Int256, "int256", 0) \ - K(UInt, "uint", 0) \ - K(UInt8, "uint8", 0) \ - K(UInt16, "uint16", 0) \ - K(UInt24, "uint24", 0) \ - K(UInt32, "uint32", 0) \ - K(UInt40, "uint40", 0) \ - K(UInt48, "uint48", 0) \ - K(UInt56, "uint56", 0) \ - K(UInt64, "uint64", 0) \ - K(UInt72, "uint72", 0) \ - K(UInt80, "uint80", 0) \ - K(UInt88, "uint88", 0) \ - K(UInt96, "uint96", 0) \ - K(UInt104, "uint104", 0) \ - K(UInt112, "uint112", 0) \ - K(UInt120, "uint120", 0) \ - K(UInt128, "uint128", 0) \ - K(UInt136, "uint136", 0) \ - K(UInt144, "uint144", 0) \ - K(UInt152, "uint152", 0) \ - K(UInt160, "uint160", 0) \ - K(UInt168, "uint168", 0) \ - K(UInt176, "uint178", 0) \ - K(UInt184, "uint184", 0) \ - K(UInt192, "uint192", 0) \ - K(UInt200, "uint200", 0) \ - K(UInt208, "uint208", 0) \ - K(UInt216, "uint216", 0) \ - K(UInt224, "uint224", 0) \ - K(UInt232, "uint232", 0) \ - K(UInt240, "uint240", 0) \ - K(UInt248, "uint248", 0) \ - K(UInt256, "uint256", 0) \ - K(Bytes1, "bytes1", 0) \ - K(Bytes2, "bytes2", 0) \ - K(Bytes3, "bytes3", 0) \ - K(Bytes4, "bytes4", 0) \ - K(Bytes5, "bytes5", 0) \ - K(Bytes6, "bytes6", 0) \ - K(Bytes7, "bytes7", 0) \ - K(Bytes8, "bytes8", 0) \ - K(Bytes9, "bytes9", 0) \ - K(Bytes10, "bytes10", 0) \ - K(Bytes11, "bytes11", 0) \ - K(Bytes12, "bytes12", 0) \ - K(Bytes13, "bytes13", 0) \ - K(Bytes14, "bytes14", 0) \ - K(Bytes15, "bytes15", 0) \ - K(Bytes16, "bytes16", 0) \ - K(Bytes17, "bytes17", 0) \ - K(Bytes18, "bytes18", 0) \ - K(Bytes19, "bytes19", 0) \ - K(Bytes20, "bytes20", 0) \ - K(Bytes21, "bytes21", 0) \ - K(Bytes22, "bytes22", 0) \ - K(Bytes23, "bytes23", 0) \ - K(Bytes24, "bytes24", 0) \ - K(Bytes25, "bytes25", 0) \ - K(Bytes26, "bytes26", 0) \ - K(Bytes27, "bytes27", 0) \ - K(Bytes28, "bytes28", 0) \ - K(Bytes29, "bytes29", 0) \ - K(Bytes30, "bytes30", 0) \ - K(Bytes31, "bytes31", 0) \ - K(Bytes32, "bytes32", 0) \ - K(Bytes, "bytes", 0) \ - K(Byte, "byte", 0) \ - K(String, "string", 0) \ - K(Address, "address", 0) \ - K(Bool, "bool", 0) \ - K(Real, "real", 0) \ - K(UReal, "ureal", 0) \ - T(TypesEnd, NULL, 0) /* used as type enum end marker */ \ - \ - /* Literals */ \ - K(NullLiteral, "null", 0) \ - K(TrueLiteral, "true", 0) \ - K(FalseLiteral, "false", 0) \ - T(Number, NULL, 0) \ - T(StringLiteral, NULL, 0) \ - T(CommentLiteral, NULL, 0) \ - \ - /* Identifiers (not keywords or future reserved words). */ \ - T(Identifier, NULL, 0) \ - \ - /* Keywords reserved for future. use. */ \ - K(As, "as", 0) \ - K(Case, "case", 0) \ - K(Catch, "catch", 0) \ - K(Final, "final", 0) \ - K(Let, "let", 0) \ - K(Match, "match", 0) \ - K(Of, "of", 0) \ - K(Relocatable, "relocatable", 0) \ - K(Switch, "switch", 0) \ - K(Throw, "throw", 0) \ - K(Try, "try", 0) \ - K(Type, "type", 0) \ - K(TypeOf, "typeof", 0) \ - K(Using, "using", 0) \ - /* Illegal token - not able to scan. */ \ - T(Illegal, "ILLEGAL", 0) \ - \ - /* Scanner-internal use only. */ \ - T(Whitespace, NULL, 0) - - -class Token -{ -public: - // All token values. - // attention! msvc issue: - // http://stackoverflow.com/questions/9567868/compile-errors-after-adding-v8-to-my-project-c2143-c2059 - // @todo: avoid TOKEN_LIST macro -#define T(name, string, precedence) name, - enum Value - { - TOKEN_LIST(T, T) - NUM_TOKENS - }; -#undef T - - // Returns a string corresponding to the C++ token name - // (e.g. "LT" for the token LT). - static char const* getName(Value tok) - { - solAssert(tok < NUM_TOKENS, ""); - return m_name[tok]; - } - - // Predicates - static bool isElementaryTypeName(Value tok) { return Int <= tok && tok < TypesEnd; } - static bool isAssignmentOp(Value tok) { return Assign <= tok && tok <= AssignMod; } - static bool isBinaryOp(Value op) { return Comma <= op && op <= Exp; } - static bool isCommutativeOp(Value op) { return op == BitOr || op == BitXor || op == BitAnd || - op == Add || op == Mul || op == Equal || op == NotEqual; } - static bool isArithmeticOp(Value op) { return Add <= op && op <= Exp; } - static bool isCompareOp(Value op) { return Equal <= op && op <= In; } - - static Value AssignmentToBinaryOp(Value op) - { - solAssert(isAssignmentOp(op) && op != Assign, ""); - return Value(op + (BitOr - AssignBitOr)); - } - - static bool isBitOp(Value op) { return (BitOr <= op && op <= SHR) || op == BitNot; } - static bool isBooleanOp(Value op) { return (Or <= op && op <= And) || op == Not; } - static bool isUnaryOp(Value op) { return (Not <= op && op <= Delete) || op == Add || op == Sub || op == After; } - static bool isCountOp(Value op) { return op == Inc || op == Dec; } - static bool isShiftOp(Value op) { return (SHL <= op) && (op <= SHR); } - static bool isVisibilitySpecifier(Value op) { return isVariableVisibilitySpecifier(op) || op == External; } - static bool isVariableVisibilitySpecifier(Value op) { return op == Public || op == Private || op == Internal; } - static bool isLocationSpecifier(Value op) { return op == Memory || op == Storage; } - static bool isEtherSubdenomination(Value op) { return op == SubWei || op == SubSzabo || op == SubFinney || op == SubEther; } - static bool isTimeSubdenomination(Value op) { return op == SubSecond || op == SubMinute || op == SubHour || op == SubDay || op == SubWeek || op == SubYear; } - - // Returns a string corresponding to the JS token string - // (.e., "<" for the token LT) or NULL if the token doesn't - // have a (unique) string (e.g. an IDENTIFIER). - static char const* toString(Value tok) - { - solAssert(tok < NUM_TOKENS, ""); - return m_string[tok]; - } - - // Returns the precedence > 0 for binary and compare - // operators; returns 0 otherwise. - static int precedence(Value tok) - { - solAssert(tok < NUM_TOKENS, ""); - return m_precedence[tok]; - } - - static Token::Value fromIdentifierOrKeyword(std::string const& _name); - -private: - static char const* const m_name[NUM_TOKENS]; - static char const* const m_string[NUM_TOKENS]; - static int8_t const m_precedence[NUM_TOKENS]; - static char const m_tokenType[NUM_TOKENS]; -}; - -} -} diff --git a/libsolidity/Types.cpp b/libsolidity/Types.cpp deleted file mode 100644 index bda683569..000000000 --- a/libsolidity/Types.cpp +++ /dev/null @@ -1,1758 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity data types - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace dev::solidity; - -void StorageOffsets::computeOffsets(TypePointers const& _types) -{ - bigint slotOffset = 0; - unsigned byteOffset = 0; - map> offsets; - for (size_t i = 0; i < _types.size(); ++i) - { - TypePointer const& type = _types[i]; - if (!type->canBeStored()) - continue; - if (byteOffset + type->getStorageBytes() > 32) - { - // would overflow, go to next slot - ++slotOffset; - byteOffset = 0; - } - if (slotOffset >= bigint(1) << 256) - BOOST_THROW_EXCEPTION(TypeError() << errinfo_comment("Object too large for storage.")); - offsets[i] = make_pair(u256(slotOffset), byteOffset); - solAssert(type->getStorageSize() >= 1, "Invalid storage size."); - if (type->getStorageSize() == 1 && byteOffset + type->getStorageBytes() <= 32) - byteOffset += type->getStorageBytes(); - else - { - slotOffset += type->getStorageSize(); - byteOffset = 0; - } - } - if (byteOffset > 0) - ++slotOffset; - if (slotOffset >= bigint(1) << 256) - BOOST_THROW_EXCEPTION(TypeError() << errinfo_comment("Object too large for storage.")); - m_storageSize = u256(slotOffset); - swap(m_offsets, offsets); -} - -pair const* StorageOffsets::getOffset(size_t _index) const -{ - if (m_offsets.count(_index)) - return &m_offsets.at(_index); - else - return nullptr; -} - -MemberList& MemberList::operator=(MemberList&& _other) -{ - assert(&_other != this); - - m_memberTypes = std::move(_other.m_memberTypes); - m_storageOffsets = std::move(_other.m_storageOffsets); - return *this; -} - -std::pair const* MemberList::getMemberStorageOffset(string const& _name) const -{ - if (!m_storageOffsets) - { - TypePointers memberTypes; - memberTypes.reserve(m_memberTypes.size()); - for (auto const& member: m_memberTypes) - memberTypes.push_back(member.type); - m_storageOffsets.reset(new StorageOffsets()); - m_storageOffsets->computeOffsets(memberTypes); - } - for (size_t index = 0; index < m_memberTypes.size(); ++index) - if (m_memberTypes[index].name == _name) - return m_storageOffsets->getOffset(index); - return nullptr; -} - -u256 const& MemberList::getStorageSize() const -{ - // trigger lazy computation - getMemberStorageOffset(""); - return m_storageOffsets->getStorageSize(); -} - -TypePointer Type::fromElementaryTypeName(Token::Value _typeToken) -{ - char const* tokenCstr = Token::toString(_typeToken); - solAssert(Token::isElementaryTypeName(_typeToken), - "Expected an elementary type name but got " + ((tokenCstr) ? std::string(Token::toString(_typeToken)) : "")); - - if (Token::Int <= _typeToken && _typeToken <= Token::Bytes32) - { - int offset = _typeToken - Token::Int; - int bytes = offset % 33; - if (bytes == 0 && _typeToken != Token::Bytes1) - bytes = 32; - int modifier = offset / 33; - switch(modifier) - { - case 0: - return make_shared(bytes * 8, IntegerType::Modifier::Signed); - case 1: - return make_shared(bytes * 8, IntegerType::Modifier::Unsigned); - case 2: - return make_shared(bytes + 1); - default: - solAssert(false, "Unexpected modifier value. Should never happen"); - return TypePointer(); - } - } - else if (_typeToken == Token::Byte) - return make_shared(1); - else if (_typeToken == Token::Address) - return make_shared(0, IntegerType::Modifier::Address); - else if (_typeToken == Token::Bool) - return make_shared(); - else if (_typeToken == Token::Bytes) - return make_shared(DataLocation::Storage); - else if (_typeToken == Token::String) - return make_shared(DataLocation::Storage, true); - else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment( - "Unable to convert elementary typename " + std::string(Token::toString(_typeToken)) + " to type." - )); -} - -TypePointer Type::fromElementaryTypeName(string const& _name) -{ - return fromElementaryTypeName(Token::fromIdentifierOrKeyword(_name)); -} - -TypePointer Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeName) -{ - Declaration const* declaration = _typeName.getReferencedDeclaration(); - if (StructDefinition const* structDef = dynamic_cast(declaration)) - return make_shared(*structDef); - else if (EnumDefinition const* enumDef = dynamic_cast(declaration)) - return make_shared(*enumDef); - else if (FunctionDefinition const* function = dynamic_cast(declaration)) - return make_shared(*function); - else if (ContractDefinition const* contract = dynamic_cast(declaration)) - return make_shared(*contract); - return TypePointer(); -} - -TypePointer Type::fromMapping(ElementaryTypeName& _keyType, TypeName& _valueType) -{ - TypePointer keyType = _keyType.toType(); - if (!keyType) - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Error resolving type name.")); - TypePointer valueType = _valueType.toType(); - if (!valueType) - BOOST_THROW_EXCEPTION(_valueType.createTypeError("Invalid type name.")); - // Convert value type to storage reference. - valueType = ReferenceType::copyForLocationIfReference(DataLocation::Storage, valueType); - // Convert key type to memory. - keyType = ReferenceType::copyForLocationIfReference(DataLocation::Memory, keyType); - return make_shared(keyType, valueType); -} - -TypePointer Type::fromArrayTypeName(TypeName& _baseTypeName, Expression* _length) -{ - TypePointer baseType = _baseTypeName.toType(); - if (!baseType) - BOOST_THROW_EXCEPTION(_baseTypeName.createTypeError("Invalid type name.")); - if (baseType->getStorageBytes() == 0) - BOOST_THROW_EXCEPTION(_baseTypeName.createTypeError("Illegal base type of storage size zero for array.")); - if (_length) - { - if (!_length->getType()) - _length->checkTypeRequirements(nullptr); - auto const* length = dynamic_cast(_length->getType().get()); - if (!length) - BOOST_THROW_EXCEPTION(_length->createTypeError("Invalid array length.")); - return make_shared(DataLocation::Storage, baseType, length->literalValue(nullptr)); - } - else - return make_shared(DataLocation::Storage, baseType); -} - -TypePointer Type::forLiteral(Literal const& _literal) -{ - switch (_literal.getToken()) - { - case Token::TrueLiteral: - case Token::FalseLiteral: - return make_shared(); - case Token::Number: - if (!IntegerConstantType::isValidLiteral(_literal)) - return TypePointer(); - return make_shared(_literal); - case Token::StringLiteral: - return make_shared(_literal); - default: - return shared_ptr(); - } -} - -TypePointer Type::commonType(TypePointer const& _a, TypePointer const& _b) -{ - if (_b->isImplicitlyConvertibleTo(*_a)) - return _a; - else if (_a->isImplicitlyConvertibleTo(*_b)) - return _b; - else - return TypePointer(); -} - -const MemberList Type::EmptyMemberList; - -IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier): - m_bits(_bits), m_modifier(_modifier) -{ - if (isAddress()) - m_bits = 160; - solAssert(m_bits > 0 && m_bits <= 256 && m_bits % 8 == 0, - "Invalid bit number for integer type: " + dev::toString(_bits)); -} - -bool IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const -{ - if (_convertTo.getCategory() != getCategory()) - return false; - IntegerType const& convertTo = dynamic_cast(_convertTo); - if (convertTo.m_bits < m_bits) - return false; - if (isAddress()) - return convertTo.isAddress(); - else if (isSigned()) - return convertTo.isSigned(); - else - return !convertTo.isSigned() || convertTo.m_bits > m_bits; -} - -bool IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const -{ - return _convertTo.getCategory() == getCategory() || - _convertTo.getCategory() == Category::Contract || - _convertTo.getCategory() == Category::Enum || - _convertTo.getCategory() == Category::FixedBytes; -} - -TypePointer IntegerType::unaryOperatorResult(Token::Value _operator) const -{ - // "delete" is ok for all integer types - if (_operator == Token::Delete) - return make_shared(); - // no further unary operators for addresses - else if (isAddress()) - return TypePointer(); - // for non-address integers, we allow +, -, ++ and -- - else if (_operator == Token::Add || _operator == Token::Sub || - _operator == Token::Inc || _operator == Token::Dec || - _operator == Token::After || _operator == Token::BitNot) - return shared_from_this(); - else - return TypePointer(); -} - -bool IntegerType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - IntegerType const& other = dynamic_cast(_other); - return other.m_bits == m_bits && other.m_modifier == m_modifier; -} - -string IntegerType::toString(bool) const -{ - if (isAddress()) - return "address"; - string prefix = isSigned() ? "int" : "uint"; - return prefix + dev::toString(m_bits); -} - -TypePointer IntegerType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const -{ - if (_other->getCategory() != Category::IntegerConstant && _other->getCategory() != getCategory()) - return TypePointer(); - auto commonType = dynamic_pointer_cast(Type::commonType(shared_from_this(), _other)); - - if (!commonType) - return TypePointer(); - - // All integer types can be compared - if (Token::isCompareOp(_operator)) - return commonType; - if (Token::isBooleanOp(_operator)) - return TypePointer(); - // Nothing else can be done with addresses - if (commonType->isAddress()) - return TypePointer(); - - return commonType; -} - -const MemberList IntegerType::AddressMemberList({ - {"balance", make_shared(256)}, - {"call", make_shared(strings(), strings{"bool"}, FunctionType::Location::Bare, true)}, - {"callcode", make_shared(strings(), strings{"bool"}, FunctionType::Location::BareCallCode, true)}, - {"send", make_shared(strings{"uint"}, strings{"bool"}, FunctionType::Location::Send)} -}); - -bool IntegerConstantType::isValidLiteral(const Literal& _literal) -{ - try - { - bigint x(_literal.getValue()); - } - catch (...) - { - return false; - } - return true; -} - -IntegerConstantType::IntegerConstantType(Literal const& _literal) -{ - m_value = bigint(_literal.getValue()); - - switch (_literal.getSubDenomination()) - { - case Literal::SubDenomination::Wei: - case Literal::SubDenomination::Second: - case Literal::SubDenomination::None: - break; - case Literal::SubDenomination::Szabo: - m_value *= bigint("1000000000000"); - break; - case Literal::SubDenomination::Finney: - m_value *= bigint("1000000000000000"); - break; - case Literal::SubDenomination::Ether: - m_value *= bigint("1000000000000000000"); - break; - case Literal::SubDenomination::Minute: - m_value *= bigint("60"); - break; - case Literal::SubDenomination::Hour: - m_value *= bigint("3600"); - break; - case Literal::SubDenomination::Day: - m_value *= bigint("86400"); - break; - case Literal::SubDenomination::Week: - m_value *= bigint("604800"); - break; - case Literal::SubDenomination::Year: - m_value *= bigint("31536000"); - break; - } -} - -bool IntegerConstantType::isImplicitlyConvertibleTo(Type const& _convertTo) const -{ - if (auto targetType = dynamic_cast(&_convertTo)) - { - if (m_value == 0) - return true; - int forSignBit = (targetType->isSigned() ? 1 : 0); - if (m_value > 0) - { - if (m_value <= (u256(-1) >> (256 - targetType->getNumBits() + forSignBit))) - return true; - } - else if (targetType->isSigned() && -m_value <= (u256(1) << (targetType->getNumBits() - forSignBit))) - return true; - return false; - } - else if (_convertTo.getCategory() == Category::FixedBytes) - { - FixedBytesType const& fixedBytes = dynamic_cast(_convertTo); - return fixedBytes.numBytes() * 8 >= getIntegerType()->getNumBits(); - } - else - return false; -} - -bool IntegerConstantType::isExplicitlyConvertibleTo(Type const& _convertTo) const -{ - TypePointer integerType = getIntegerType(); - return integerType && integerType->isExplicitlyConvertibleTo(_convertTo); -} - -TypePointer IntegerConstantType::unaryOperatorResult(Token::Value _operator) const -{ - bigint value; - switch (_operator) - { - case Token::BitNot: - value = ~m_value; - break; - case Token::Add: - value = m_value; - break; - case Token::Sub: - value = -m_value; - break; - case Token::After: - return shared_from_this(); - default: - return TypePointer(); - } - return make_shared(value); -} - -TypePointer IntegerConstantType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const -{ - if (_other->getCategory() == Category::Integer) - { - shared_ptr integerType = getIntegerType(); - if (!integerType) - return TypePointer(); - return integerType->binaryOperatorResult(_operator, _other); - } - else if (_other->getCategory() != getCategory()) - return TypePointer(); - - IntegerConstantType const& other = dynamic_cast(*_other); - if (Token::isCompareOp(_operator)) - { - shared_ptr thisIntegerType = getIntegerType(); - shared_ptr otherIntegerType = other.getIntegerType(); - if (!thisIntegerType || !otherIntegerType) - return TypePointer(); - return thisIntegerType->binaryOperatorResult(_operator, otherIntegerType); - } - else - { - bigint value; - switch (_operator) - { - case Token::BitOr: - value = m_value | other.m_value; - break; - case Token::BitXor: - value = m_value ^ other.m_value; - break; - case Token::BitAnd: - value = m_value & other.m_value; - break; - case Token::Add: - value = m_value + other.m_value; - break; - case Token::Sub: - value = m_value - other.m_value; - break; - case Token::Mul: - value = m_value * other.m_value; - break; - case Token::Div: - if (other.m_value == 0) - return TypePointer(); - value = m_value / other.m_value; - break; - case Token::Mod: - if (other.m_value == 0) - return TypePointer(); - value = m_value % other.m_value; - break; - case Token::Exp: - if (other.m_value < 0) - return TypePointer(); - else if (other.m_value > std::numeric_limits::max()) - return TypePointer(); - else - value = boost::multiprecision::pow(m_value, other.m_value.convert_to()); - break; - default: - return TypePointer(); - } - return make_shared(value); - } -} - -bool IntegerConstantType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - return m_value == dynamic_cast(_other).m_value; -} - -string IntegerConstantType::toString(bool) const -{ - return "int_const " + m_value.str(); -} - -u256 IntegerConstantType::literalValue(Literal const*) const -{ - u256 value; - // we ignore the literal and hope that the type was correctly determined - solAssert(m_value <= u256(-1), "Integer constant too large."); - solAssert(m_value >= -(bigint(1) << 255), "Integer constant too small."); - - if (m_value >= 0) - value = u256(m_value); - else - value = s2u(s256(m_value)); - - return value; -} - -TypePointer IntegerConstantType::mobileType() const -{ - auto intType = getIntegerType(); - solAssert(!!intType, "mobileType called with invalid integer constant " + toString(false)); - return intType; -} - -shared_ptr IntegerConstantType::getIntegerType() const -{ - bigint value = m_value; - bool negative = (value < 0); - if (negative) // convert to positive number of same bit requirements - value = ((-value) - 1) << 1; - if (value > u256(-1)) - return shared_ptr(); - else - return make_shared( - max(bytesRequired(value), 1u) * 8, - negative ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned - ); -} - -StringLiteralType::StringLiteralType(Literal const& _literal): - m_value(_literal.getValue()) -{ -} - -bool StringLiteralType::isImplicitlyConvertibleTo(Type const& _convertTo) const -{ - if (auto fixedBytes = dynamic_cast(&_convertTo)) - return size_t(fixedBytes->numBytes()) >= m_value.size(); - else if (auto arrayType = dynamic_cast(&_convertTo)) - return arrayType->isByteArray(); - else - return false; -} - -bool StringLiteralType::operator==(const Type& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - return m_value == dynamic_cast(_other).m_value; -} - -TypePointer StringLiteralType::mobileType() const -{ - return make_shared(DataLocation::Memory, true); -} - -shared_ptr FixedBytesType::smallestTypeForLiteral(string const& _literal) -{ - if (_literal.length() <= 32) - return make_shared(_literal.length()); - return shared_ptr(); -} - -FixedBytesType::FixedBytesType(int _bytes): m_bytes(_bytes) -{ - solAssert(m_bytes >= 0 && m_bytes <= 32, - "Invalid byte number for fixed bytes type: " + dev::toString(m_bytes)); -} - -bool FixedBytesType::isImplicitlyConvertibleTo(Type const& _convertTo) const -{ - if (_convertTo.getCategory() != getCategory()) - return false; - FixedBytesType const& convertTo = dynamic_cast(_convertTo); - return convertTo.m_bytes >= m_bytes; -} - -bool FixedBytesType::isExplicitlyConvertibleTo(Type const& _convertTo) const -{ - return _convertTo.getCategory() == Category::Integer || - _convertTo.getCategory() == Category::Contract || - _convertTo.getCategory() == getCategory(); -} - -TypePointer FixedBytesType::unaryOperatorResult(Token::Value _operator) const -{ - // "delete" and "~" is okay for FixedBytesType - if (_operator == Token::Delete) - return make_shared(); - else if (_operator == Token::BitNot) - return shared_from_this(); - - return TypePointer(); -} - -TypePointer FixedBytesType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const -{ - auto commonType = dynamic_pointer_cast(Type::commonType(shared_from_this(), _other)); - if (!commonType) - return TypePointer(); - - // FixedBytes can be compared and have bitwise operators applied to them - if (Token::isCompareOp(_operator) || Token::isBitOp(_operator)) - return commonType; - - return TypePointer(); -} - -bool FixedBytesType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - FixedBytesType const& other = dynamic_cast(_other); - return other.m_bytes == m_bytes; -} - -bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const -{ - // conversion to integer is fine, but not to address - // this is an example of explicit conversions being not transitive (though implicit should be) - if (_convertTo.getCategory() == getCategory()) - { - IntegerType const& convertTo = dynamic_cast(_convertTo); - if (!convertTo.isAddress()) - return true; - } - return isImplicitlyConvertibleTo(_convertTo); -} - -u256 BoolType::literalValue(Literal const* _literal) const -{ - solAssert(_literal, ""); - if (_literal->getToken() == Token::TrueLiteral) - return u256(1); - else if (_literal->getToken() == Token::FalseLiteral) - return u256(0); - else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal.")); -} - -TypePointer BoolType::unaryOperatorResult(Token::Value _operator) const -{ - if (_operator == Token::Delete) - return make_shared(); - return (_operator == Token::Not) ? shared_from_this() : TypePointer(); -} - -TypePointer BoolType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const -{ - if (getCategory() != _other->getCategory()) - return TypePointer(); - if (Token::isCompareOp(_operator) || _operator == Token::And || _operator == Token::Or) - return _other; - else - return TypePointer(); -} - -bool ContractType::isImplicitlyConvertibleTo(Type const& _convertTo) const -{ - if (*this == _convertTo) - return true; - if (_convertTo.getCategory() == Category::Integer) - return dynamic_cast(_convertTo).isAddress(); - if (_convertTo.getCategory() == Category::Contract) - { - auto const& bases = getContractDefinition().getLinearizedBaseContracts(); - if (m_super && bases.size() <= 1) - return false; - return find(m_super ? ++bases.begin() : bases.begin(), bases.end(), - &dynamic_cast(_convertTo).getContractDefinition()) != bases.end(); - } - return false; -} - -bool ContractType::isExplicitlyConvertibleTo(Type const& _convertTo) const -{ - return isImplicitlyConvertibleTo(_convertTo) || _convertTo.getCategory() == Category::Integer || - _convertTo.getCategory() == Category::Contract; -} - -TypePointer ContractType::unaryOperatorResult(Token::Value _operator) const -{ - return _operator == Token::Delete ? make_shared() : TypePointer(); -} - -TypePointer ReferenceType::unaryOperatorResult(Token::Value _operator) const -{ - if (_operator != Token::Delete) - return TypePointer(); - // delete can be used on everything except calldata references or storage pointers - // (storage references are ok) - switch (location()) - { - case DataLocation::CallData: - return TypePointer(); - case DataLocation::Memory: - return make_shared(); - case DataLocation::Storage: - return m_isPointer ? TypePointer() : make_shared(); - default: - solAssert(false, ""); - } - return TypePointer(); -} - -TypePointer ReferenceType::copyForLocationIfReference(DataLocation _location, TypePointer const& _type) -{ - if (auto type = dynamic_cast(_type.get())) - return type->copyForLocation(_location, false); - return _type; -} - -TypePointer ReferenceType::copyForLocationIfReference(TypePointer const& _type) const -{ - return copyForLocationIfReference(m_location, _type); -} - -string ReferenceType::stringForReferencePart() const -{ - switch (m_location) - { - case DataLocation::Storage: - return string("storage ") + (m_isPointer ? "pointer" : "ref"); - case DataLocation::CallData: - return "calldata"; - case DataLocation::Memory: - return "memory"; - } - solAssert(false, ""); - return ""; -} - -bool ArrayType::isImplicitlyConvertibleTo(const Type& _convertTo) const -{ - if (_convertTo.getCategory() != getCategory()) - return false; - auto& convertTo = dynamic_cast(_convertTo); - if (convertTo.isByteArray() != isByteArray() || convertTo.isString() != isString()) - return false; - // memory/calldata to storage can be converted, but only to a direct storage reference - if (convertTo.location() == DataLocation::Storage && location() != DataLocation::Storage && convertTo.isPointer()) - return false; - if (convertTo.location() == DataLocation::CallData && location() != convertTo.location()) - return false; - if (convertTo.location() == DataLocation::Storage && !convertTo.isPointer()) - { - // Less restrictive conversion, since we need to copy anyway. - if (!getBaseType()->isImplicitlyConvertibleTo(*convertTo.getBaseType())) - return false; - if (convertTo.isDynamicallySized()) - return true; - return !isDynamicallySized() && convertTo.getLength() >= getLength(); - } - else - { - // Conversion to storage pointer or to memory, we de not copy element-for-element here, so - // require that the base type is the same, not only convertible. - // This disallows assignment of nested dynamic arrays from storage to memory for now. - if ( - *copyForLocationIfReference(location(), getBaseType()) != - *copyForLocationIfReference(location(), convertTo.getBaseType()) - ) - return false; - if (isDynamicallySized() != convertTo.isDynamicallySized()) - return false; - // We also require that the size is the same. - if (!isDynamicallySized() && getLength() != convertTo.getLength()) - return false; - return true; - } -} - -bool ArrayType::isExplicitlyConvertibleTo(const Type& _convertTo) const -{ - if (isImplicitlyConvertibleTo(_convertTo)) - return true; - // allow conversion bytes <-> string - if (_convertTo.getCategory() != getCategory()) - return false; - auto& convertTo = dynamic_cast(_convertTo); - if (convertTo.location() != location()) - return false; - if (!isByteArray() || !convertTo.isByteArray()) - return false; - return true; -} - -bool ArrayType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - ArrayType const& other = dynamic_cast(_other); - if ( - !ReferenceType::operator==(other) || - other.isByteArray() != isByteArray() || - other.isString() != isString() || - other.isDynamicallySized() != isDynamicallySized() - ) - return false; - return isDynamicallySized() || getLength() == other.getLength(); -} - -unsigned ArrayType::getCalldataEncodedSize(bool _padded) const -{ - if (isDynamicallySized()) - return 0; - bigint size = bigint(getLength()) * (isByteArray() ? 1 : getBaseType()->getCalldataEncodedSize(_padded)); - size = ((size + 31) / 32) * 32; - solAssert(size <= numeric_limits::max(), "Array size does not fit unsigned."); - return unsigned(size); -} - -u256 ArrayType::getStorageSize() const -{ - if (isDynamicallySized()) - return 1; - - bigint size; - unsigned baseBytes = getBaseType()->getStorageBytes(); - if (baseBytes == 0) - size = 1; - else if (baseBytes < 32) - { - unsigned itemsPerSlot = 32 / baseBytes; - size = (bigint(getLength()) + (itemsPerSlot - 1)) / itemsPerSlot; - } - else - size = bigint(getLength()) * getBaseType()->getStorageSize(); - if (size >= bigint(1) << 256) - BOOST_THROW_EXCEPTION(TypeError() << errinfo_comment("Array too large for storage.")); - return max(1, u256(size)); -} - -unsigned ArrayType::getSizeOnStack() const -{ - if (m_location == DataLocation::CallData) - // offset [length] (stack top) - return 1 + (isDynamicallySized() ? 1 : 0); - else - // storage slot or memory offset - // byte offset inside storage value is omitted - return 1; -} - -string ArrayType::toString(bool _short) const -{ - string ret; - if (isString()) - ret = "string"; - else if (isByteArray()) - ret = "bytes"; - else - { - ret = getBaseType()->toString(_short) + "["; - if (!isDynamicallySized()) - ret += getLength().str(); - ret += "]"; - } - if (!_short) - ret += " " + stringForReferencePart(); - return ret; -} - -TypePointer ArrayType::externalType() const -{ - if (m_arrayKind != ArrayKind::Ordinary) - return this->copyForLocation(DataLocation::Memory, true); - TypePointer baseExt = m_baseType->externalType(); - if (!baseExt) - return TypePointer(); - if (m_baseType->getCategory() == Category::Array && m_baseType->isDynamicallySized()) - return TypePointer(); - - if (isDynamicallySized()) - return std::make_shared(DataLocation::Memory, baseExt); - else - return std::make_shared(DataLocation::Memory, baseExt, m_length); -} - -TypePointer ArrayType::copyForLocation(DataLocation _location, bool _isPointer) const -{ - auto copy = make_shared(_location); - copy->m_isPointer = _isPointer; - copy->m_arrayKind = m_arrayKind; - copy->m_baseType = copy->copyForLocationIfReference(m_baseType); - copy->m_hasDynamicLength = m_hasDynamicLength; - copy->m_length = m_length; - return copy; -} - -const MemberList ArrayType::s_arrayTypeMemberList({{"length", make_shared(256)}}); - -bool ContractType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - ContractType const& other = dynamic_cast(_other); - return other.m_contract == m_contract && other.m_super == m_super; -} - -string ContractType::toString(bool) const -{ - return "contract " + string(m_super ? "super " : "") + m_contract.getName(); -} - -MemberList const& ContractType::getMembers() const -{ - // We need to lazy-initialize it because of recursive references. - if (!m_members) - { - // All address members and all interface functions - MemberList::MemberMap members( - IntegerType::AddressMemberList.begin(), - IntegerType::AddressMemberList.end() - ); - if (m_super) - { - // add the most derived of all functions which are visible in derived contracts - for (ContractDefinition const* base: m_contract.getLinearizedBaseContracts()) - for (ASTPointer const& function: base->getDefinedFunctions()) - { - if (!function->isVisibleInDerivedContracts()) - continue; - auto functionType = make_shared(*function, true); - bool functionWithEqualArgumentsFound = false; - for (auto const& member: members) - { - if (member.name != function->getName()) - continue; - auto memberType = dynamic_cast(member.type.get()); - solAssert(!!memberType, "Override changes type."); - if (!memberType->hasEqualArgumentTypes(*functionType)) - continue; - functionWithEqualArgumentsFound = true; - break; - } - if (!functionWithEqualArgumentsFound) - members.push_back(MemberList::Member( - function->getName(), - functionType, - function.get() - )); - } - } - else - for (auto const& it: m_contract.getInterfaceFunctions()) - members.push_back(MemberList::Member( - it.second->getDeclaration().getName(), - it.second->asMemberFunction(), - &it.second->getDeclaration() - )); - m_members.reset(new MemberList(members)); - } - return *m_members; -} - -shared_ptr const& ContractType::getConstructorType() const -{ - if (!m_constructorType) - { - FunctionDefinition const* constructor = m_contract.getConstructor(); - if (constructor) - m_constructorType = make_shared(*constructor); - else - m_constructorType = make_shared(TypePointers(), TypePointers()); - } - return m_constructorType; -} - -vector> ContractType::getStateVariables() const -{ - vector variables; - for (ContractDefinition const* contract: boost::adaptors::reverse(m_contract.getLinearizedBaseContracts())) - for (ASTPointer const& variable: contract->getStateVariables()) - if (!variable->isConstant()) - variables.push_back(variable.get()); - TypePointers types; - for (auto variable: variables) - types.push_back(variable->getType()); - StorageOffsets offsets; - offsets.computeOffsets(types); - - vector> variablesAndOffsets; - for (size_t index = 0; index < variables.size(); ++index) - if (auto const* offset = offsets.getOffset(index)) - variablesAndOffsets.push_back(make_tuple(variables[index], offset->first, offset->second)); - return variablesAndOffsets; -} - -bool StructType::isImplicitlyConvertibleTo(const Type& _convertTo) const -{ - if (_convertTo.getCategory() != getCategory()) - return false; - auto& convertTo = dynamic_cast(_convertTo); - // memory/calldata to storage can be converted, but only to a direct storage reference - if (convertTo.location() == DataLocation::Storage && location() != DataLocation::Storage && convertTo.isPointer()) - return false; - if (convertTo.location() == DataLocation::CallData && location() != convertTo.location()) - return false; - return this->m_struct == convertTo.m_struct; -} - -bool StructType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - StructType const& other = dynamic_cast(_other); - return ReferenceType::operator==(other) && other.m_struct == m_struct; -} - -unsigned StructType::getCalldataEncodedSize(bool _padded) const -{ - unsigned size = 0; - for (auto const& member: getMembers()) - if (!member.type->canLiveOutsideStorage()) - return 0; - else - { - unsigned memberSize = member.type->getCalldataEncodedSize(_padded); - if (memberSize == 0) - return 0; - size += memberSize; - } - return size; -} - -u256 StructType::memorySize() const -{ - u256 size; - for (auto const& member: getMembers()) - if (member.type->canLiveOutsideStorage()) - size += member.type->memoryHeadSize(); - return size; -} - -u256 StructType::getStorageSize() const -{ - return max(1, getMembers().getStorageSize()); -} - -string StructType::toString(bool _short) const -{ - string ret = "struct " + m_struct.getName(); - if (!_short) - ret += " " + stringForReferencePart(); - return ret; -} - -MemberList const& StructType::getMembers() const -{ - // We need to lazy-initialize it because of recursive references. - if (!m_members) - { - MemberList::MemberMap members; - for (ASTPointer const& variable: m_struct.getMembers()) - { - TypePointer type = variable->getType(); - // Skip all mapping members if we are not in storage. - if (location() != DataLocation::Storage && !type->canLiveOutsideStorage()) - continue; - members.push_back(MemberList::Member( - variable->getName(), - copyForLocationIfReference(type), - variable.get()) - ); - } - m_members.reset(new MemberList(members)); - } - return *m_members; -} - -TypePointer StructType::copyForLocation(DataLocation _location, bool _isPointer) const -{ - auto copy = make_shared(m_struct, _location); - copy->m_isPointer = _isPointer; - return copy; -} - -FunctionTypePointer StructType::constructorType() const -{ - TypePointers paramTypes; - strings paramNames; - for (auto const& member: getMembers()) - { - if (!member.type->canLiveOutsideStorage()) - continue; - paramNames.push_back(member.name); - paramTypes.push_back(copyForLocationIfReference(DataLocation::Memory, member.type)); - } - return make_shared( - paramTypes, - TypePointers{copyForLocation(DataLocation::Memory, false)}, - paramNames, - strings(), - FunctionType::Location::Internal - ); -} - -pair const& StructType::getStorageOffsetsOfMember(string const& _name) const -{ - auto const* offsets = getMembers().getMemberStorageOffset(_name); - solAssert(offsets, "Storage offset of non-existing member requested."); - return *offsets; -} - -u256 StructType::memoryOffsetOfMember(string const& _name) const -{ - u256 offset; - for (auto const& member: getMembers()) - if (member.name == _name) - return offset; - else - offset += member.type->memoryHeadSize(); - solAssert(false, "Member not found in struct."); - return 0; -} - -set StructType::membersMissingInMemory() const -{ - set missing; - for (ASTPointer const& variable: m_struct.getMembers()) - if (!variable->getType()->canLiveOutsideStorage()) - missing.insert(variable->getName()); - return missing; -} - -TypePointer EnumType::unaryOperatorResult(Token::Value _operator) const -{ - return _operator == Token::Delete ? make_shared() : TypePointer(); -} - -bool EnumType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - EnumType const& other = dynamic_cast(_other); - return other.m_enum == m_enum; -} - -unsigned EnumType::getStorageBytes() const -{ - size_t elements = m_enum.getMembers().size(); - if (elements <= 1) - return 1; - else - return dev::bytesRequired(elements - 1); -} - -string EnumType::toString(bool) const -{ - return string("enum ") + m_enum.getName(); -} - -bool EnumType::isExplicitlyConvertibleTo(Type const& _convertTo) const -{ - return _convertTo.getCategory() == getCategory() || _convertTo.getCategory() == Category::Integer; -} - -unsigned int EnumType::getMemberValue(ASTString const& _member) const -{ - unsigned int index = 0; - for (ASTPointer const& decl: m_enum.getMembers()) - { - if (decl->getName() == _member) - return index; - ++index; - } - BOOST_THROW_EXCEPTION(m_enum.createTypeError("Requested unknown enum value ." + _member)); -} - -FunctionType::FunctionType(FunctionDefinition const& _function, bool _isInternal): - m_location(_isInternal ? Location::Internal : Location::External), - m_isConstant(_function.isDeclaredConst()), - m_declaration(&_function) -{ - TypePointers params; - vector paramNames; - TypePointers retParams; - vector retParamNames; - - params.reserve(_function.getParameters().size()); - paramNames.reserve(_function.getParameters().size()); - for (ASTPointer const& var: _function.getParameters()) - { - paramNames.push_back(var->getName()); - params.push_back(var->getType()); - } - retParams.reserve(_function.getReturnParameters().size()); - retParamNames.reserve(_function.getReturnParameters().size()); - for (ASTPointer const& var: _function.getReturnParameters()) - { - retParamNames.push_back(var->getName()); - retParams.push_back(var->getType()); - } - swap(params, m_parameterTypes); - swap(paramNames, m_parameterNames); - swap(retParams, m_returnParameterTypes); - swap(retParamNames, m_returnParameterNames); -} - -FunctionType::FunctionType(VariableDeclaration const& _varDecl): - m_location(Location::External), m_isConstant(true), m_declaration(&_varDecl) -{ - TypePointers paramTypes; - vector paramNames; - auto returnType = _varDecl.getType(); - - while (true) - { - if (auto mappingType = dynamic_cast(returnType.get())) - { - paramTypes.push_back(mappingType->getKeyType()); - paramNames.push_back(""); - returnType = mappingType->getValueType(); - } - else if (auto arrayType = dynamic_cast(returnType.get())) - { - if (arrayType->isByteArray()) - // Return byte arrays as as whole. - break; - returnType = arrayType->getBaseType(); - paramNames.push_back(""); - paramTypes.push_back(make_shared(256)); - } - else - break; - } - - TypePointers retParams; - vector retParamNames; - if (auto structType = dynamic_cast(returnType.get())) - { - for (auto const& member: structType->getMembers()) - if (member.type->getCategory() != Category::Mapping) - { - if (auto arrayType = dynamic_cast(member.type.get())) - if (!arrayType->isByteArray()) - continue; - retParams.push_back(member.type); - retParamNames.push_back(member.name); - } - } - else - { - retParams.push_back(ReferenceType::copyForLocationIfReference( - DataLocation::Memory, - returnType - )); - retParamNames.push_back(""); - } - - swap(paramTypes, m_parameterTypes); - swap(paramNames, m_parameterNames); - swap(retParams, m_returnParameterTypes); - swap(retParamNames, m_returnParameterNames); -} - -FunctionType::FunctionType(const EventDefinition& _event): - m_location(Location::Event), m_isConstant(true), m_declaration(&_event) -{ - TypePointers params; - vector paramNames; - params.reserve(_event.getParameters().size()); - paramNames.reserve(_event.getParameters().size()); - for (ASTPointer const& var: _event.getParameters()) - { - paramNames.push_back(var->getName()); - params.push_back(var->getType()); - } - swap(params, m_parameterTypes); - swap(paramNames, m_parameterNames); -} - -bool FunctionType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - FunctionType const& other = dynamic_cast(_other); - - if (m_location != other.m_location) - return false; - if (m_isConstant != other.isConstant()) - return false; - - if (m_parameterTypes.size() != other.m_parameterTypes.size() || - m_returnParameterTypes.size() != other.m_returnParameterTypes.size()) - return false; - auto typeCompare = [](TypePointer const& _a, TypePointer const& _b) -> bool { return *_a == *_b; }; - - if (!equal(m_parameterTypes.cbegin(), m_parameterTypes.cend(), - other.m_parameterTypes.cbegin(), typeCompare)) - return false; - if (!equal(m_returnParameterTypes.cbegin(), m_returnParameterTypes.cend(), - other.m_returnParameterTypes.cbegin(), typeCompare)) - return false; - //@todo this is ugly, but cannot be prevented right now - if (m_gasSet != other.m_gasSet || m_valueSet != other.m_valueSet) - return false; - return true; -} - -string FunctionType::toString(bool _short) const -{ - string name = "function ("; - for (auto it = m_parameterTypes.begin(); it != m_parameterTypes.end(); ++it) - name += (*it)->toString(_short) + (it + 1 == m_parameterTypes.end() ? "" : ","); - name += ") returns ("; - for (auto it = m_returnParameterTypes.begin(); it != m_returnParameterTypes.end(); ++it) - name += (*it)->toString(_short) + (it + 1 == m_returnParameterTypes.end() ? "" : ","); - return name + ")"; -} - -u256 FunctionType::getStorageSize() const -{ - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable function type requested.")); -} - -unsigned FunctionType::getSizeOnStack() const -{ - Location location = m_location; - if (m_location == Location::SetGas || m_location == Location::SetValue) - { - solAssert(m_returnParameterTypes.size() == 1, ""); - location = dynamic_cast(*m_returnParameterTypes.front()).m_location; - } - - unsigned size = 0; - if (location == Location::External || location == Location::CallCode) - size = 2; - else if (location == Location::Bare || location == Location::BareCallCode) - size = 1; - else if (location == Location::Internal) - size = 1; - if (m_gasSet) - size++; - if (m_valueSet) - size++; - return size; -} - -FunctionTypePointer FunctionType::externalFunctionType() const -{ - TypePointers paramTypes; - TypePointers retParamTypes; - - for (auto type: m_parameterTypes) - { - if (auto ext = type->externalType()) - paramTypes.push_back(ext); - else - return FunctionTypePointer(); - } - for (auto type: m_returnParameterTypes) - { - if (auto ext = type->externalType()) - retParamTypes.push_back(ext); - else - return FunctionTypePointer(); - } - return make_shared(paramTypes, retParamTypes, m_parameterNames, m_returnParameterNames, m_location, m_arbitraryParameters); -} - -MemberList const& FunctionType::getMembers() const -{ - switch (m_location) - { - case Location::External: - case Location::Creation: - case Location::ECRecover: - case Location::SHA256: - case Location::RIPEMD160: - case Location::Bare: - case Location::BareCallCode: - if (!m_members) - { - MemberList::MemberMap members{ - { - "value", - make_shared( - parseElementaryTypeVector({"uint"}), - TypePointers{copyAndSetGasOrValue(false, true)}, - strings(), - strings(), - Location::SetValue, - false, - nullptr, - m_gasSet, - m_valueSet - ) - } - }; - if (m_location != Location::Creation) - members.push_back( - MemberList::Member( - "gas", - make_shared( - parseElementaryTypeVector({"uint"}), - TypePointers{copyAndSetGasOrValue(true, false)}, - strings(), - strings(), - Location::SetGas, - false, - nullptr, - m_gasSet, - m_valueSet - ) - ) - ); - m_members.reset(new MemberList(members)); - } - return *m_members; - default: - return EmptyMemberList; - } -} - -bool FunctionType::canTakeArguments(TypePointers const& _argumentTypes) const -{ - TypePointers const& parameterTypes = getParameterTypes(); - if (takesArbitraryParameters()) - return true; - else if (_argumentTypes.size() != parameterTypes.size()) - return false; - else - return std::equal( - _argumentTypes.cbegin(), - _argumentTypes.cend(), - parameterTypes.cbegin(), - [](TypePointer const& argumentType, TypePointer const& parameterType) - { - return argumentType->isImplicitlyConvertibleTo(*parameterType); - } - ); -} - -bool FunctionType::hasEqualArgumentTypes(FunctionType const& _other) const -{ - if (m_parameterTypes.size() != _other.m_parameterTypes.size()) - return false; - return equal( - m_parameterTypes.cbegin(), - m_parameterTypes.cend(), - _other.m_parameterTypes.cbegin(), - [](TypePointer const& _a, TypePointer const& _b) -> bool { return *_a == *_b; } - ); -} - -bool FunctionType::isBareCall() const -{ - switch (m_location) - { - case Location::Bare: - case Location::BareCallCode: - case Location::ECRecover: - case Location::SHA256: - case Location::RIPEMD160: - return true; - default: - return false; - } -} - -string FunctionType::externalSignature(std::string const& _name) const -{ - std::string funcName = _name; - if (_name == "") - { - solAssert(m_declaration != nullptr, "Function type without name needs a declaration"); - funcName = m_declaration->getName(); - } - string ret = funcName + "("; - - FunctionTypePointer external = externalFunctionType(); - solAssert(!!external, "External function type requested."); - TypePointers externalParameterTypes = external->getParameterTypes(); - for (auto it = externalParameterTypes.cbegin(); it != externalParameterTypes.cend(); ++it) - { - solAssert(!!(*it), "Parameter should have external type"); - ret += (*it)->toString(true) + (it + 1 == externalParameterTypes.cend() ? "" : ","); - } - - return ret + ")"; -} - -u256 FunctionType::externalIdentifier() const -{ - return FixedHash<4>::Arith(FixedHash<4>(dev::sha3(externalSignature()))); -} - -TypePointers FunctionType::parseElementaryTypeVector(strings const& _types) -{ - TypePointers pointers; - pointers.reserve(_types.size()); - for (string const& type: _types) - pointers.push_back(Type::fromElementaryTypeName(type)); - return pointers; -} - -TypePointer FunctionType::copyAndSetGasOrValue(bool _setGas, bool _setValue) const -{ - return make_shared( - m_parameterTypes, - m_returnParameterTypes, - m_parameterNames, - m_returnParameterNames, - m_location, - m_arbitraryParameters, - m_declaration, - m_gasSet || _setGas, - m_valueSet || _setValue - ); -} - -FunctionTypePointer FunctionType::asMemberFunction() const -{ - TypePointers parameterTypes; - for (auto const& t: m_parameterTypes) - { - auto refType = dynamic_cast(t.get()); - if (refType && refType->location() == DataLocation::CallData) - parameterTypes.push_back(refType->copyForLocation(DataLocation::Memory, false)); - else - parameterTypes.push_back(t); - } - - //@todo make this more intelligent once we support destructuring assignments - TypePointers returnParameterTypes; - vector returnParameterNames; - if (!m_returnParameterTypes.empty() && m_returnParameterTypes.front()->getCalldataEncodedSize() > 0) - { - returnParameterTypes.push_back(m_returnParameterTypes.front()); - returnParameterNames.push_back(m_returnParameterNames.front()); - } - return make_shared( - parameterTypes, - returnParameterTypes, - m_parameterNames, - returnParameterNames, - m_location, - m_arbitraryParameters, - m_declaration, - m_gasSet, - m_valueSet - ); -} - -vector const FunctionType::getParameterTypeNames() const -{ - vector names; - for (TypePointer const& t: m_parameterTypes) - names.push_back(t->toString(true)); - - return names; -} - -vector const FunctionType::getReturnParameterTypeNames() const -{ - vector names; - for (TypePointer const& t: m_returnParameterTypes) - names.push_back(t->toString(true)); - - return names; -} - -ASTPointer FunctionType::getDocumentation() const -{ - auto function = dynamic_cast(m_declaration); - if (function) - return function->getDocumentation(); - - return ASTPointer(); -} - -bool MappingType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - MappingType const& other = dynamic_cast(_other); - return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType; -} - -string MappingType::toString(bool _short) const -{ - return "mapping(" + getKeyType()->toString(_short) + " => " + getValueType()->toString(_short) + ")"; -} - -u256 VoidType::getStorageSize() const -{ - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable void type requested.")); -} - -bool TypeType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - TypeType const& other = dynamic_cast(_other); - return *getActualType() == *other.getActualType(); -} - -u256 TypeType::getStorageSize() const -{ - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable type type requested.")); -} - -MemberList const& TypeType::getMembers() const -{ - // We need to lazy-initialize it because of recursive references. - if (!m_members) - { - MemberList::MemberMap members; - if (m_actualType->getCategory() == Category::Contract && m_currentContract != nullptr) - { - ContractDefinition const& contract = dynamic_cast(*m_actualType).getContractDefinition(); - vector currentBases = m_currentContract->getLinearizedBaseContracts(); - if (find(currentBases.begin(), currentBases.end(), &contract) != currentBases.end()) - // We are accessing the type of a base contract, so add all public and protected - // members. Note that this does not add inherited functions on purpose. - for (Declaration const* decl: contract.getInheritableMembers()) - members.push_back(MemberList::Member(decl->getName(), decl->getType(), decl)); - } - else if (m_actualType->getCategory() == Category::Enum) - { - EnumDefinition const& enumDef = dynamic_cast(*m_actualType).getEnumDefinition(); - auto enumType = make_shared(enumDef); - for (ASTPointer const& enumValue: enumDef.getMembers()) - members.push_back(MemberList::Member(enumValue->getName(), enumType)); - } - m_members.reset(new MemberList(members)); - } - return *m_members; -} - -ModifierType::ModifierType(const ModifierDefinition& _modifier) -{ - TypePointers params; - params.reserve(_modifier.getParameters().size()); - for (ASTPointer const& var: _modifier.getParameters()) - params.push_back(var->getType()); - swap(params, m_parameterTypes); -} - -u256 ModifierType::getStorageSize() const -{ - BOOST_THROW_EXCEPTION( - InternalCompilerError() - << errinfo_comment("Storage size of non-storable type type requested.")); -} - -bool ModifierType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - ModifierType const& other = dynamic_cast(_other); - - if (m_parameterTypes.size() != other.m_parameterTypes.size()) - return false; - auto typeCompare = [](TypePointer const& _a, TypePointer const& _b) -> bool { return *_a == *_b; }; - - if (!equal(m_parameterTypes.cbegin(), m_parameterTypes.cend(), - other.m_parameterTypes.cbegin(), typeCompare)) - return false; - return true; -} - -string ModifierType::toString(bool _short) const -{ - string name = "modifier ("; - for (auto it = m_parameterTypes.begin(); it != m_parameterTypes.end(); ++it) - name += (*it)->toString(_short) + (it + 1 == m_parameterTypes.end() ? "" : ","); - return name + ")"; -} - -MagicType::MagicType(MagicType::Kind _kind): - m_kind(_kind) -{ - switch (m_kind) - { - case Kind::Block: - m_members = MemberList({ - {"coinbase", make_shared(0, IntegerType::Modifier::Address)}, - {"timestamp", make_shared(256)}, - {"blockhash", make_shared(strings{"uint"}, strings{"bytes32"}, FunctionType::Location::BlockHash)}, - {"difficulty", make_shared(256)}, - {"number", make_shared(256)}, - {"gaslimit", make_shared(256)} - }); - break; - case Kind::Message: - m_members = MemberList({ - {"sender", make_shared(0, IntegerType::Modifier::Address)}, - {"gas", make_shared(256)}, - {"value", make_shared(256)}, - {"data", make_shared(DataLocation::CallData)}, - {"sig", make_shared(4)} - }); - break; - case Kind::Transaction: - m_members = MemberList({ - {"origin", make_shared(0, IntegerType::Modifier::Address)}, - {"gasprice", make_shared(256)} - }); - break; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); - } -} - -bool MagicType::operator==(Type const& _other) const -{ - if (_other.getCategory() != getCategory()) - return false; - MagicType const& other = dynamic_cast(_other); - return other.m_kind == m_kind; -} - -string MagicType::toString(bool) const -{ - switch (m_kind) - { - case Kind::Block: - return "block"; - case Kind::Message: - return "msg"; - case Kind::Transaction: - return "tx"; - default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); - } -} diff --git a/libsolidity/Types.h b/libsolidity/Types.h deleted file mode 100644 index c4992cfdf..000000000 --- a/libsolidity/Types.h +++ /dev/null @@ -1,935 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity data types - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -class Type; // forward -class FunctionType; // forward -using TypePointer = std::shared_ptr; -using FunctionTypePointer = std::shared_ptr; -using TypePointers = std::vector; - - -enum class DataLocation { Storage, CallData, Memory }; - -/** - * Helper class to compute storage offsets of members of structs and contracts. - */ -class StorageOffsets -{ -public: - /// Resets the StorageOffsets objects and determines the position in storage for each - /// of the elements of @a _types. - void computeOffsets(TypePointers const& _types); - /// @returns the offset of the given member, might be null if the member is not part of storage. - std::pair const* getOffset(size_t _index) const; - /// @returns the total number of slots occupied by all members. - u256 const& getStorageSize() const { return m_storageSize; } - -private: - u256 m_storageSize; - std::map> m_offsets; -}; - -/** - * List of members of a type. - */ -class MemberList -{ -public: - struct Member - { - Member(std::string const& _name, TypePointer const& _type, Declaration const* _declaration = nullptr): - name(_name), - type(_type), - declaration(_declaration) - { - } - - std::string name; - TypePointer type; - Declaration const* declaration = nullptr; - }; - - using MemberMap = std::vector; - - MemberList() {} - explicit MemberList(MemberMap const& _members): m_memberTypes(_members) {} - MemberList& operator=(MemberList&& _other); - TypePointer getMemberType(std::string const& _name) const - { - TypePointer type; - for (auto const& it: m_memberTypes) - if (it.name == _name) - { - solAssert(!type, "Requested member type by non-unique name."); - type = it.type; - } - return type; - } - MemberMap membersByName(std::string const& _name) const - { - MemberMap members; - for (auto const& it: m_memberTypes) - if (it.name == _name) - members.push_back(it); - return members; - } - /// @returns the offset of the given member in storage slots and bytes inside a slot or - /// a nullptr if the member is not part of storage. - std::pair const* getMemberStorageOffset(std::string const& _name) const; - /// @returns the number of storage slots occupied by the members. - u256 const& getStorageSize() const; - - MemberMap::const_iterator begin() const { return m_memberTypes.begin(); } - MemberMap::const_iterator end() const { return m_memberTypes.end(); } - -private: - MemberMap m_memberTypes; - mutable std::unique_ptr m_storageOffsets; -}; - -/** - * Abstract base class that forms the root of the type hierarchy. - */ -class Type: private boost::noncopyable, public std::enable_shared_from_this -{ -public: - enum class Category - { - Integer, IntegerConstant, StringLiteral, Bool, Real, Array, - FixedBytes, Contract, Struct, Function, Enum, - Mapping, Void, TypeType, Modifier, Magic - }; - - /// @{ - /// @name Factory functions - /// Factory functions that convert an AST @ref TypeName to a Type. - static TypePointer fromElementaryTypeName(Token::Value _typeToken); - static TypePointer fromElementaryTypeName(std::string const& _name); - static TypePointer fromUserDefinedTypeName(UserDefinedTypeName const& _typeName); - static TypePointer fromMapping(ElementaryTypeName& _keyType, TypeName& _valueType); - static TypePointer fromArrayTypeName(TypeName& _baseTypeName, Expression* _length); - /// @} - - /// Auto-detect the proper type for a literal. @returns an empty pointer if the literal does - /// not fit any type. - static TypePointer forLiteral(Literal const& _literal); - /// @returns a pointer to _a or _b if the other is implicitly convertible to it or nullptr otherwise - static TypePointer commonType(TypePointer const& _a, TypePointer const& _b); - - /// Calculates the - - virtual Category getCategory() const = 0; - virtual bool isImplicitlyConvertibleTo(Type const& _other) const { return *this == _other; } - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const - { - return isImplicitlyConvertibleTo(_convertTo); - } - /// @returns the resulting type of applying the given unary operator or an empty pointer if - /// this is not possible. - /// The default implementation does not allow any unary operator. - virtual TypePointer unaryOperatorResult(Token::Value) const { return TypePointer(); } - /// @returns the resulting type of applying the given binary operator or an empty pointer if - /// this is not possible. - /// The default implementation allows comparison operators if a common type exists - virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const - { - return Token::isCompareOp(_operator) ? commonType(shared_from_this(), _other) : TypePointer(); - } - - virtual bool operator==(Type const& _other) const { return getCategory() == _other.getCategory(); } - virtual bool operator!=(Type const& _other) const { return !this->operator ==(_other); } - - /// @returns number of bytes used by this type when encoded for CALL, or 0 if the encoding - /// is not a simple big-endian encoding or the type cannot be stored in calldata. - /// If @a _padded then it is assumed that each element is padded to a multiple of 32 bytes. - virtual unsigned getCalldataEncodedSize(bool _padded) const { (void)_padded; return 0; } - /// @returns the size of this data type in bytes when stored in memory. For memory-reference - /// types, this is the size of the memory pointer. - virtual unsigned memoryHeadSize() const { return getCalldataEncodedSize(); } - /// Convenience version of @see getCalldataEncodedSize(bool) - unsigned getCalldataEncodedSize() const { return getCalldataEncodedSize(true); } - /// @returns true if the type is dynamically encoded in calldata - virtual bool isDynamicallySized() const { return false; } - /// @returns the number of storage slots required to hold this value in storage. - /// For dynamically "allocated" types, it returns the size of the statically allocated head, - virtual u256 getStorageSize() const { return 1; } - /// Multiple small types can be packed into a single storage slot. If such a packing is possible - /// this function @returns the size in bytes smaller than 32. Data is moved to the next slot if - /// it does not fit. - /// In order to avoid computation at runtime of whether such moving is necessary, structs and - /// array data (not each element) always start a new slot. - virtual unsigned getStorageBytes() const { return 32; } - /// Returns true if the type can be stored in storage. - virtual bool canBeStored() const { return true; } - /// Returns false if the type cannot live outside the storage, i.e. if it includes some mapping. - virtual bool canLiveOutsideStorage() const { return true; } - /// Returns true if the type can be stored as a value (as opposed to a reference) on the stack, - /// i.e. it behaves differently in lvalue context and in value context. - virtual bool isValueType() const { return false; } - virtual unsigned getSizeOnStack() const { return 1; } - /// @returns the mobile (in contrast to static) type corresponding to the given type. - /// This returns the corresponding integer type for IntegerConstantTypes and the pointer type - /// for storage reference types. - virtual TypePointer mobileType() const { return shared_from_this(); } - /// @returns true if this is a non-value type and the data of this type is stored at the - /// given location. - virtual bool dataStoredIn(DataLocation) const { return false; } - - /// Returns the list of all members of this type. Default implementation: no members. - virtual MemberList const& getMembers() const { return EmptyMemberList; } - /// Convenience method, returns the type of the given named member or an empty pointer if no such member exists. - TypePointer getMemberType(std::string const& _name) const { return getMembers().getMemberType(_name); } - - virtual std::string toString(bool _short) const = 0; - std::string toString() const { return toString(false); } - virtual u256 literalValue(Literal const*) const - { - BOOST_THROW_EXCEPTION( - InternalCompilerError() << - errinfo_comment("Literal value requested for type without literals.") - ); - } - - /// @returns a type suitable for outside of Solidity, i.e. for contract types it returns address. - /// If there is no such type, returns an empty shared pointer. - virtual TypePointer externalType() const { return TypePointer(); } - -protected: - /// Convenience object used when returning an empty member list. - static const MemberList EmptyMemberList; -}; - -/** - * Any kind of integer type (signed, unsigned, address). - */ -class IntegerType: public Type -{ -public: - enum class Modifier - { - Unsigned, Signed, Address - }; - virtual Category getCategory() const override { return Category::Integer; } - - explicit IntegerType(int _bits, Modifier _modifier = Modifier::Unsigned); - - virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; - virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override; - - virtual bool operator==(Type const& _other) const override; - - virtual unsigned getCalldataEncodedSize(bool _padded = true) const override { return _padded ? 32 : m_bits / 8; } - virtual unsigned getStorageBytes() const override { return m_bits / 8; } - virtual bool isValueType() const override { return true; } - - virtual MemberList const& getMembers() const override { return isAddress() ? AddressMemberList : EmptyMemberList; } - - virtual std::string toString(bool _short) const override; - - virtual TypePointer externalType() const override { return shared_from_this(); } - - int getNumBits() const { return m_bits; } - bool isAddress() const { return m_modifier == Modifier::Address; } - bool isSigned() const { return m_modifier == Modifier::Signed; } - - static const MemberList AddressMemberList; - -private: - int m_bits; - Modifier m_modifier; -}; - -/** - * Integer constants either literals or computed. Example expressions: 2, 2+10, ~10. - * There is one distinct type per value. - */ -class IntegerConstantType: public Type -{ -public: - virtual Category getCategory() const override { return Category::IntegerConstant; } - - /// @returns true if the literal is a valid integer. - static bool isValidLiteral(Literal const& _literal); - - explicit IntegerConstantType(Literal const& _literal); - explicit IntegerConstantType(bigint _value): m_value(_value) {} - - virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; - virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override; - - virtual bool operator==(Type const& _other) const override; - - virtual bool canBeStored() const override { return false; } - virtual bool canLiveOutsideStorage() const override { return false; } - - virtual std::string toString(bool _short) const override; - virtual u256 literalValue(Literal const* _literal) const override; - virtual TypePointer mobileType() const override; - - /// @returns the smallest integer type that can hold the value or an empty pointer if not possible. - std::shared_ptr getIntegerType() const; - -private: - bigint m_value; -}; - -/** - * Literal string, can be converted to bytes, bytesX or string. - */ -class StringLiteralType: public Type -{ -public: - virtual Category getCategory() const override { return Category::StringLiteral; } - - explicit StringLiteralType(Literal const& _literal); - - virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override - { - return TypePointer(); - } - - virtual bool operator==(Type const& _other) const override; - - virtual bool canBeStored() const override { return false; } - virtual bool canLiveOutsideStorage() const override { return false; } - virtual unsigned getSizeOnStack() const override { return 0; } - - virtual std::string toString(bool) const override { return "literal_string \"" + m_value + "\""; } - virtual TypePointer mobileType() const override; - - std::string const& value() const { return m_value; } - -private: - std::string m_value; -}; - -/** - * Bytes type with fixed length of up to 32 bytes. - */ -class FixedBytesType: public Type -{ -public: - virtual Category getCategory() const override { return Category::FixedBytes; } - - /// @returns the smallest bytes type for the given literal or an empty pointer - /// if no type fits. - static std::shared_ptr smallestTypeForLiteral(std::string const& _literal); - - explicit FixedBytesType(int _bytes); - - virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual bool operator==(Type const& _other) const override; - virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; - virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override; - - virtual unsigned getCalldataEncodedSize(bool _padded) const override { return _padded && m_bytes > 0 ? 32 : m_bytes; } - virtual unsigned getStorageBytes() const override { return m_bytes; } - virtual bool isValueType() const override { return true; } - - virtual std::string toString(bool) const override { return "bytes" + dev::toString(m_bytes); } - virtual TypePointer externalType() const override { return shared_from_this(); } - - int numBytes() const { return m_bytes; } - -private: - int m_bytes; -}; - -/** - * The boolean type. - */ -class BoolType: public Type -{ -public: - BoolType() {} - virtual Category getCategory() const override { return Category::Bool; } - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; - virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override; - - virtual unsigned getCalldataEncodedSize(bool _padded) const override{ return _padded ? 32 : 1; } - virtual unsigned getStorageBytes() const override { return 1; } - virtual bool isValueType() const override { return true; } - - virtual std::string toString(bool) const override { return "bool"; } - virtual u256 literalValue(Literal const* _literal) const override; - virtual TypePointer externalType() const override { return shared_from_this(); } -}; - -/** - * Base class used by types which are not value types and can be stored either in storage, memory - * or calldata. This is currently used by arrays and structs. - */ -class ReferenceType: public Type -{ -public: - explicit ReferenceType(DataLocation _location): m_location(_location) {} - DataLocation location() const { return m_location; } - - virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; - virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override - { - return TypePointer(); - } - virtual unsigned memoryHeadSize() const override { return 32; } - - /// @returns a copy of this type with location (recursively) changed to @a _location, - /// whereas isPointer is only shallowly changed - the deep copy is always a bound reference. - virtual TypePointer copyForLocation(DataLocation _location, bool _isPointer) const = 0; - - virtual TypePointer mobileType() const override { return copyForLocation(m_location, true); } - virtual bool dataStoredIn(DataLocation _location) const override { return m_location == _location; } - - /// Storage references can be pointers or bound references. In general, local variables are of - /// pointer type, state variables are bound references. Assignments to pointers or deleting - /// them will not modify storage (that will only change the pointer). Assignment from - /// non-storage objects to a variable of storage pointer type is not possible. - bool isPointer() const { return m_isPointer; } - - bool operator==(ReferenceType const& _other) const - { - return location() == _other.location() && isPointer() == _other.isPointer(); - } - - /// @returns a copy of @a _type having the same location as this (and is not a pointer type) - /// if _type is a reference type and an unmodified copy of _type otherwise. - /// This function is mostly useful to modify inner types appropriately. - static TypePointer copyForLocationIfReference(DataLocation _location, TypePointer const& _type); - -protected: - TypePointer copyForLocationIfReference(TypePointer const& _type) const; - /// @returns a human-readable description of the reference part of the type. - std::string stringForReferencePart() const; - - DataLocation m_location = DataLocation::Storage; - bool m_isPointer = true; -}; - -/** - * The type of an array. The flavours are byte array (bytes), statically- ([]) - * and dynamically-sized array ([]). - * In storage, all arrays are packed tightly (as long as more than one elementary type fits in - * one slot). Dynamically sized arrays (including byte arrays) start with their size as a uint and - * thus start on their own slot. - */ -class ArrayType: public ReferenceType -{ -public: - virtual Category getCategory() const override { return Category::Array; } - - /// Constructor for a byte array ("bytes") and string. - explicit ArrayType(DataLocation _location, bool _isString = false): - ReferenceType(_location), - m_arrayKind(_isString ? ArrayKind::String : ArrayKind::Bytes), - m_baseType(std::make_shared(1)) - { - } - /// Constructor for a dynamically sized array type ("type[]") - ArrayType(DataLocation _location, TypePointer const& _baseType): - ReferenceType(_location), - m_baseType(copyForLocationIfReference(_baseType)) - { - } - /// Constructor for a fixed-size array type ("type[20]") - ArrayType(DataLocation _location, TypePointer const& _baseType, u256 const& _length): - ReferenceType(_location), - m_baseType(copyForLocationIfReference(_baseType)), - m_hasDynamicLength(false), - m_length(_length) - {} - - virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual bool operator==(const Type& _other) const override; - virtual unsigned getCalldataEncodedSize(bool _padded) const override; - virtual bool isDynamicallySized() const override { return m_hasDynamicLength; } - virtual u256 getStorageSize() const override; - virtual bool canLiveOutsideStorage() const override { return m_baseType->canLiveOutsideStorage(); } - virtual unsigned getSizeOnStack() const override; - virtual std::string toString(bool _short) const override; - virtual MemberList const& getMembers() const override - { - return isString() ? EmptyMemberList : s_arrayTypeMemberList; - } - virtual TypePointer externalType() const override; - - /// @returns true if this is a byte array or a string - bool isByteArray() const { return m_arrayKind != ArrayKind::Ordinary; } - /// @returns true if this is a string - bool isString() const { return m_arrayKind == ArrayKind::String; } - TypePointer const& getBaseType() const { solAssert(!!m_baseType, ""); return m_baseType;} - u256 const& getLength() const { return m_length; } - - TypePointer copyForLocation(DataLocation _location, bool _isPointer) const override; - -private: - /// String is interpreted as a subtype of Bytes. - enum class ArrayKind { Ordinary, Bytes, String }; - - ///< Byte arrays ("bytes") and strings have different semantics from ordinary arrays. - ArrayKind m_arrayKind = ArrayKind::Ordinary; - TypePointer m_baseType; - bool m_hasDynamicLength = true; - u256 m_length; - static const MemberList s_arrayTypeMemberList; -}; - -/** - * The type of a contract instance, there is one distinct type for each contract definition. - */ -class ContractType: public Type -{ -public: - virtual Category getCategory() const override { return Category::Contract; } - explicit ContractType(ContractDefinition const& _contract, bool _super = false): - m_contract(_contract), m_super(_super) {} - /// Contracts can be implicitly converted to super classes and to addresses. - virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; - /// Contracts can be converted to themselves and to integers. - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; - virtual bool operator==(Type const& _other) const override; - virtual unsigned getCalldataEncodedSize(bool _padded ) const override - { - return externalType()->getCalldataEncodedSize(_padded); - } - virtual unsigned getStorageBytes() const override { return 20; } - virtual bool canLiveOutsideStorage() const override { return true; } - virtual bool isValueType() const override { return true; } - virtual std::string toString(bool _short) const override; - - virtual MemberList const& getMembers() const override; - virtual TypePointer externalType() const override - { - return std::make_shared(160, IntegerType::Modifier::Address); - } - - bool isSuper() const { return m_super; } - ContractDefinition const& getContractDefinition() const { return m_contract; } - - /// Returns the function type of the constructor. Note that the location part of the function type - /// is not used, as this type cannot be the type of a variable or expression. - FunctionTypePointer const& getConstructorType() const; - - /// @returns the identifier of the function with the given name or Invalid256 if such a name does - /// not exist. - u256 getFunctionIdentifier(std::string const& _functionName) const; - - /// @returns a list of all state variables (including inherited) of the contract and their - /// offsets in storage. - std::vector> getStateVariables() const; - -private: - ContractDefinition const& m_contract; - /// If true, it is the "super" type of the current contract, i.e. it contains only inherited - /// members. - bool m_super; - /// Type of the constructor, @see getConstructorType. Lazily initialized. - mutable FunctionTypePointer m_constructorType; - /// List of member types, will be lazy-initialized because of recursive references. - mutable std::unique_ptr m_members; -}; - -/** - * The type of a struct instance, there is one distinct type per struct definition. - */ -class StructType: public ReferenceType -{ -public: - virtual Category getCategory() const override { return Category::Struct; } - explicit StructType(StructDefinition const& _struct, DataLocation _location = DataLocation::Storage): - ReferenceType(_location), m_struct(_struct) {} - virtual bool isImplicitlyConvertibleTo(const Type& _convertTo) const override; - virtual bool operator==(Type const& _other) const override; - virtual unsigned getCalldataEncodedSize(bool _padded) const override; - u256 memorySize() const; - virtual u256 getStorageSize() const override; - virtual bool canLiveOutsideStorage() const override { return true; } - virtual std::string toString(bool _short) const override; - - virtual MemberList const& getMembers() const override; - - TypePointer copyForLocation(DataLocation _location, bool _isPointer) const override; - - /// @returns a function that peforms the type conversion between a list of struct members - /// and a memory struct of this type. - FunctionTypePointer constructorType() const; - - std::pair const& getStorageOffsetsOfMember(std::string const& _name) const; - u256 memoryOffsetOfMember(std::string const& _name) const; - - StructDefinition const& structDefinition() const { return m_struct; } - - /// @returns the set of all members that are removed in the memory version (typically mappings). - std::set membersMissingInMemory() const; - -private: - StructDefinition const& m_struct; - /// List of member types, will be lazy-initialized because of recursive references. - mutable std::unique_ptr m_members; -}; - -/** - * The type of an enum instance, there is one distinct type per enum definition. - */ -class EnumType: public Type -{ -public: - virtual Category getCategory() const override { return Category::Enum; } - explicit EnumType(EnumDefinition const& _enum): m_enum(_enum) {} - virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; - virtual bool operator==(Type const& _other) const override; - virtual unsigned getCalldataEncodedSize(bool _padded) const override - { - return externalType()->getCalldataEncodedSize(_padded); - } - virtual unsigned getStorageBytes() const override; - virtual bool canLiveOutsideStorage() const override { return true; } - virtual std::string toString(bool _short) const override; - virtual bool isValueType() const override { return true; } - - virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; - virtual TypePointer externalType() const override - { - return std::make_shared(8 * int(getStorageBytes())); - } - - EnumDefinition const& getEnumDefinition() const { return m_enum; } - /// @returns the value that the string has in the Enum - unsigned int getMemberValue(ASTString const& _member) const; - -private: - EnumDefinition const& m_enum; - /// List of member types, will be lazy-initialized because of recursive references. - mutable std::unique_ptr m_members; -}; - -/** - * The type of a function, identified by its (return) parameter types. - * @todo the return parameters should also have names, i.e. return parameters should be a struct - * type. - */ -class FunctionType: public Type -{ -public: - /// How this function is invoked on the EVM. - /// @todo This documentation is outdated, and Location should rather be named "Type" - enum class Location - { - Internal, ///< stack-call using plain JUMP - External, ///< external call using CALL - CallCode, ///< extercnal call using CALLCODE, i.e. not exchanging the storage - Bare, ///< CALL without function hash - BareCallCode, ///< CALLCODE without function hash - Creation, ///< external call using CREATE - Send, ///< CALL, but without data and gas - SHA3, ///< SHA3 - Suicide, ///< SUICIDE - ECRecover, ///< CALL to special contract for ecrecover - SHA256, ///< CALL to special contract for sha256 - RIPEMD160, ///< CALL to special contract for ripemd160 - Log0, - Log1, - Log2, - Log3, - Log4, - Event, ///< syntactic sugar for LOG* - SetGas, ///< modify the default gas value for the function call - SetValue, ///< modify the default value transfer for the function call - BlockHash ///< BLOCKHASH - }; - - virtual Category getCategory() const override { return Category::Function; } - - /// @returns TypePointer of a new FunctionType object. All input/return parameters are an - /// appropriate external types of input/return parameters of current function. - /// Returns an empty shared pointer if one of the input/return parameters does not have an - /// external type. - FunctionTypePointer externalFunctionType() const; - virtual TypePointer externalType() const override { return externalFunctionType(); } - - /// Creates the type of a function. - explicit FunctionType(FunctionDefinition const& _function, bool _isInternal = true); - /// Creates the accessor function type of a state variable. - explicit FunctionType(VariableDeclaration const& _varDecl); - /// Creates the function type of an event. - explicit FunctionType(EventDefinition const& _event); - FunctionType( - strings const& _parameterTypes, - strings const& _returnParameterTypes, - Location _location = Location::Internal, - bool _arbitraryParameters = false - ): FunctionType( - parseElementaryTypeVector(_parameterTypes), - parseElementaryTypeVector(_returnParameterTypes), - strings(), - strings(), - _location, - _arbitraryParameters - ) - { - } - FunctionType( - TypePointers const& _parameterTypes, - TypePointers const& _returnParameterTypes, - strings _parameterNames = strings(), - strings _returnParameterNames = strings(), - Location _location = Location::Internal, - bool _arbitraryParameters = false, - Declaration const* _declaration = nullptr, - bool _gasSet = false, - bool _valueSet = false - ): - m_parameterTypes(_parameterTypes), - m_returnParameterTypes(_returnParameterTypes), - m_parameterNames(_parameterNames), - m_returnParameterNames(_returnParameterNames), - m_location(_location), - m_arbitraryParameters(_arbitraryParameters), - m_gasSet(_gasSet), - m_valueSet(_valueSet), - m_declaration(_declaration) - {} - - TypePointers const& getParameterTypes() const { return m_parameterTypes; } - std::vector const& getParameterNames() const { return m_parameterNames; } - std::vector const getParameterTypeNames() const; - TypePointers const& getReturnParameterTypes() const { return m_returnParameterTypes; } - std::vector const& getReturnParameterNames() const { return m_returnParameterNames; } - std::vector const getReturnParameterTypeNames() const; - - virtual bool operator==(Type const& _other) const override; - virtual std::string toString(bool _short) const override; - virtual bool canBeStored() const override { return false; } - virtual u256 getStorageSize() const override; - virtual bool canLiveOutsideStorage() const override { return false; } - virtual unsigned getSizeOnStack() const override; - virtual MemberList const& getMembers() const override; - - /// @returns true if this function can take the given argument types (possibly - /// after implicit conversion). - bool canTakeArguments(TypePointers const& _arguments) const; - /// @returns true if the types of parameters are equal (does't check return parameter types) - bool hasEqualArgumentTypes(FunctionType const& _other) const; - - /// @returns true if the ABI is used for this call (only meaningful for external calls) - bool isBareCall() const; - Location const& getLocation() const { return m_location; } - /// @returns the external signature of this function type given the function name - /// If @a _name is not provided (empty string) then the @c m_declaration member of the - /// function type is used - std::string externalSignature(std::string const& _name = "") const; - /// @returns the external identifier of this function (the hash of the signature). - u256 externalIdentifier() const; - Declaration const& getDeclaration() const - { - solAssert(m_declaration, "Requested declaration from a FunctionType that has none"); - return *m_declaration; - } - bool hasDeclaration() const { return !!m_declaration; } - bool isConstant() const { return m_isConstant; } - /// @return A shared pointer of an ASTString. - /// Can contain a nullptr in which case indicates absence of documentation - ASTPointer getDocumentation() const; - - /// true iff arguments are to be padded to multiples of 32 bytes for external calls - bool padArguments() const { return !(m_location == Location::SHA3 || m_location == Location::SHA256 || m_location == Location::RIPEMD160); } - bool takesArbitraryParameters() const { return m_arbitraryParameters; } - bool gasSet() const { return m_gasSet; } - bool valueSet() const { return m_valueSet; } - - /// @returns a copy of this type, where gas or value are set manually. This will never set one - /// of the parameters to fals. - TypePointer copyAndSetGasOrValue(bool _setGas, bool _setValue) const; - - /// @returns a copy of this function type where all return parameters of dynamic size are - /// removed and the location of reference types is changed from CallData to Memory. - /// This is needed if external functions are called on other contracts, as they cannot return - /// dynamic values. - FunctionTypePointer asMemberFunction() const; - -private: - static TypePointers parseElementaryTypeVector(strings const& _types); - - TypePointers m_parameterTypes; - TypePointers m_returnParameterTypes; - std::vector m_parameterNames; - std::vector m_returnParameterNames; - Location const m_location; - /// true if the function takes an arbitrary number of arguments of arbitrary types - bool const m_arbitraryParameters = false; - bool const m_gasSet = false; ///< true iff the gas value to be used is on the stack - bool const m_valueSet = false; ///< true iff the value to be sent is on the stack - bool m_isConstant = false; - mutable std::unique_ptr m_members; - Declaration const* m_declaration = nullptr; -}; - -/** - * The type of a mapping, there is one distinct type per key/value type pair. - * Mappings always occupy their own storage slot, but do not actually use it. - */ -class MappingType: public Type -{ -public: - virtual Category getCategory() const override { return Category::Mapping; } - MappingType(TypePointer const& _keyType, TypePointer const& _valueType): - m_keyType(_keyType), m_valueType(_valueType) {} - - virtual bool operator==(Type const& _other) const override; - virtual std::string toString(bool _short) const override; - virtual bool canLiveOutsideStorage() const override { return false; } - - TypePointer const& getKeyType() const { return m_keyType; } - TypePointer const& getValueType() const { return m_valueType; } - -private: - TypePointer m_keyType; - TypePointer m_valueType; -}; - -/** - * The void type, can only be implicitly used as the type that is returned by functions without - * return parameters. - */ -class VoidType: public Type -{ -public: - virtual Category getCategory() const override { return Category::Void; } - VoidType() {} - - virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); } - virtual std::string toString(bool) const override { return "void"; } - virtual bool canBeStored() const override { return false; } - virtual u256 getStorageSize() const override; - virtual bool canLiveOutsideStorage() const override { return false; } - virtual unsigned getSizeOnStack() const override { return 0; } -}; - -/** - * The type of a type reference. The type of "uint32" when used in "a = uint32(2)" is an example - * of a TypeType. - */ -class TypeType: public Type -{ -public: - virtual Category getCategory() const override { return Category::TypeType; } - explicit TypeType(TypePointer const& _actualType, ContractDefinition const* _currentContract = nullptr): - m_actualType(_actualType), m_currentContract(_currentContract) {} - TypePointer const& getActualType() const { return m_actualType; } - - virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); } - virtual bool operator==(Type const& _other) const override; - virtual bool canBeStored() const override { return false; } - virtual u256 getStorageSize() const override; - virtual bool canLiveOutsideStorage() const override { return false; } - virtual unsigned getSizeOnStack() const override { return 0; } - virtual std::string toString(bool _short) const override { return "type(" + m_actualType->toString(_short) + ")"; } - virtual MemberList const& getMembers() const override; - -private: - TypePointer m_actualType; - /// Context in which this type is used (influences visibility etc.), can be nullptr. - ContractDefinition const* m_currentContract; - /// List of member types, will be lazy-initialized because of recursive references. - mutable std::unique_ptr m_members; -}; - - -/** - * The type of a function modifier. Not used for anything for now. - */ -class ModifierType: public Type -{ -public: - virtual Category getCategory() const override { return Category::Modifier; } - explicit ModifierType(ModifierDefinition const& _modifier); - - virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); } - virtual bool canBeStored() const override { return false; } - virtual u256 getStorageSize() const override; - virtual bool canLiveOutsideStorage() const override { return false; } - virtual unsigned getSizeOnStack() const override { return 0; } - virtual bool operator==(Type const& _other) const override; - virtual std::string toString(bool _short) const override; - -private: - TypePointers m_parameterTypes; -}; - - -/** - * Special type for magic variables (block, msg, tx), similar to a struct but without any reference - * (it always references a global singleton by name). - */ -class MagicType: public Type -{ -public: - enum class Kind { Block, Message, Transaction }; - virtual Category getCategory() const override { return Category::Magic; } - - explicit MagicType(Kind _kind); - - virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override - { - return TypePointer(); - } - - virtual bool operator==(Type const& _other) const override; - virtual bool canBeStored() const override { return false; } - virtual bool canLiveOutsideStorage() const override { return true; } - virtual unsigned getSizeOnStack() const override { return 0; } - virtual MemberList const& getMembers() const override { return m_members; } - - virtual std::string toString(bool _short) const override; - -private: - Kind m_kind; - - MemberList m_members; -}; - -} -} diff --git a/libsolidity/Utils.h b/libsolidity/Utils.h deleted file mode 100644 index 05c5fa6f0..000000000 --- a/libsolidity/Utils.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity Utilities. - */ - -#pragma once - -#include - -/// Assertion that throws an InternalCompilerError containing the given description if it is not met. -#define solAssert(CONDITION, DESCRIPTION) \ - assertThrow(CONDITION, ::dev::solidity::InternalCompilerError, DESCRIPTION) - diff --git a/libsolidity/Version.cpp b/libsolidity/Version.cpp deleted file mode 100644 index 75a0dd256..000000000 --- a/libsolidity/Version.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Versioning. - */ - -#include -#include -#include -#include - -using namespace dev; -using namespace dev::solidity; -using namespace std; - -char const* dev::solidity::VersionNumber = "0.1.1"; -extern string const dev::solidity::VersionString = - string(dev::solidity::VersionNumber) + - "-" + - string(DEV_QUOTED(ETH_COMMIT_HASH)).substr(0, 8) + - (ETH_CLEAN_REPO ? "" : "*") + - "/" DEV_QUOTED(ETH_BUILD_TYPE) "-" DEV_QUOTED(ETH_BUILD_PLATFORM); - diff --git a/libsolidity/Version.h b/libsolidity/Version.h deleted file mode 100644 index 6e00f07b4..000000000 --- a/libsolidity/Version.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Versioning. - */ - -#pragma once - -#include - -namespace dev -{ -namespace solidity -{ - -extern char const* VersionNumber; -extern std::string const VersionString; - -} -} diff --git a/libsolidity/grammar.txt b/libsolidity/grammar.txt deleted file mode 100644 index 6503516c6..000000000 --- a/libsolidity/grammar.txt +++ /dev/null @@ -1,47 +0,0 @@ -ContractDefinition = 'contract' Identifier - ( 'is' InheritanceSpecifier (',' InheritanceSpecifier )* )? - '{' ContractPart* '}' -ContractPart = StateVariableDeclaration | StructDefinition | ModifierDefinition | FunctionDefinition | EnumDefinition - -InheritanceSpecifier = Identifier ( '(' Expression ( ',' Expression )* ')' )? -StructDefinition = 'struct' Identifier '{' - ( VariableDeclaration (';' VariableDeclaration)* )? '} -StateVariableDeclaration = TypeName ( 'public' | 'inheritable' | 'private' )? Identifier ';' -ModifierDefinition = 'modifier' Identifier ParameterList? Block -FunctionDefinition = 'function' Identifier ParameterList - ( Identifier | 'constant' | 'external' | 'public' | 'inheritable' | 'private' )* - ( 'returns' ParameterList )? Block - -EnumValue = Identifier -EnumDefinition = 'enum' '{' EnumValue (',' EnumValue)* '}' -ParameterList = '(' ( VariableDeclaration (',' VariableDeclaration)* )? ')' -// semantic restriction: mappings and structs (recursively) containing mappings -// are not allowed in argument lists -VariableDeclaration = TypeName Identifier -TypeName = ElementaryTypeName | Identifier | Mapping | ArrayTypeName -Mapping = 'mapping' '(' ElementaryTypeName '=>' TypeName ')' -ArrayTypeName = TypeName '[' (Expression)? ']' - -Block = '{' Statement* '}' -Statement = IfStatement | WhileStatement | Block | - ( Continue | Break | Return | VariableDefinition | ExpressionStatement ) ';' - -ExpressionStatement = Expression -IfStatement = 'if' '(' Expression ')' Statement ( 'else' Statement )? -WhileStatement = 'while' '(' Expression ')' Statement -VardefOrExprStmt = Variabledefinition | ExpressionStatement -ForStatement = 'for' '(' (VardefOrExprStmt)? ';' (Expression)? ';' (ExpressionStatement)? ')' Statement -Continue = 'continue' ';' -Break = 'break' ';' -Return = 'return' Expression? ';' -VariableDefinition = VariableDeclaration ( = Expression )? ';' - -Expression = Assignment | UnaryOperation | BinaryOperation | FunctionCall | NewExpression | IndexAccess | - MemberAccess | PrimaryExpression -// The expression syntax is actually much more complicated -Assignment = Expression (AssignmentOp Expression) -FunctionCall = Expression '(' Expression ( ',' Expression )* ')' -NewExpression = 'new' Identifier -MemberAccess = Expression '.' Identifier -IndexAccess = Expression '[' (Expresison)? ']' -PrimaryExpression = Identifier | NumberLiteral | StringLiteral | ElementaryTypeName | '(' Expression ')' diff --git a/solc/CMakeLists.txt b/solc/CMakeLists.txt deleted file mode 100644 index df72f52dd..000000000 --- a/solc/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -cmake_policy(SET CMP0015 NEW) -set(CMAKE_AUTOMOC OFF) - -aux_source_directory(. SRC_LIST) -list(REMOVE_ITEM SRC_LIST "./jsonCompiler.cpp") - -include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS}) -include_directories(BEFORE ..) -include_directories(${Boost_INCLUDE_DIRS}) - -set(EXECUTABLE solc) - -file(GLOB HEADERS "*.h") -add_executable(${EXECUTABLE} ${SRC_LIST} ${HEADERS}) - -add_dependencies(${EXECUTABLE} BuildInfo.h) - -target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARIES}) -target_link_libraries(${EXECUTABLE} ${Boost_PROGRAM_OPTIONS_LIBRARIES}) -target_link_libraries(${EXECUTABLE} solidity) - -if (APPLE) - install(TARGETS ${EXECUTABLE} DESTINATION bin) -else() - eth_install_executable(${EXECUTABLE}) -endif() - -add_library(soljson jsonCompiler.cpp ${HEADERS}) -target_link_libraries(soljson solidity) diff --git a/solc/CommandLineInterface.cpp b/solc/CommandLineInterface.cpp deleted file mode 100644 index e579d8839..000000000 --- a/solc/CommandLineInterface.cpp +++ /dev/null @@ -1,657 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Lefteris - * @author Gav Wood - * @date 2014 - * Solidity command line interface. - */ -#include "CommandLineInterface.h" - -#include -#include -#include - -#include -#include - -#include "BuildInfo.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -namespace po = boost::program_options; - -namespace dev -{ -namespace solidity -{ - -static string const g_argAbiStr = "json-abi"; -static string const g_argSolAbiStr = "sol-abi"; -static string const g_argSignatureHashes = "hashes"; -static string const g_argGas = "gas"; -static string const g_argAsmStr = "asm"; -static string const g_argAsmJsonStr = "asm-json"; -static string const g_argAstStr = "ast"; -static string const g_argAstJson = "ast-json"; -static string const g_argBinaryStr = "binary"; -static string const g_argCloneBinaryStr = "clone-binary"; -static string const g_argOpcodesStr = "opcodes"; -static string const g_argNatspecDevStr = "natspec-dev"; -static string const g_argNatspecUserStr = "natspec-user"; -static string const g_argAddStandard = "add-std"; - -/// Possible arguments to for --combined-json -static set const g_combinedJsonArgs{ - "binary", - "clone-binary", - "opcodes", - "json-abi", - "sol-abi", - "asm", - "ast", - "natspec-user", - "natspec-dev" -}; - -static void version() -{ - cout << - "solc, the solidity compiler commandline interface" << - endl << - "Version: " << - dev::solidity::VersionString << - endl; - exit(0); -} - -static inline bool humanTargetedStdout(po::variables_map const& _args, string const& _name) -{ - return _args.count(_name) && _args[_name].as() != OutputType::FILE; -} - -static bool needsHumanTargetedStdout(po::variables_map const& _args) -{ - - return - _args.count(g_argGas) || - humanTargetedStdout(_args, g_argAbiStr) || - humanTargetedStdout(_args, g_argSolAbiStr) || - humanTargetedStdout(_args, g_argSignatureHashes) || - humanTargetedStdout(_args, g_argNatspecUserStr) || - humanTargetedStdout(_args, g_argAstJson) || - humanTargetedStdout(_args, g_argNatspecDevStr) || - humanTargetedStdout(_args, g_argAsmStr) || - humanTargetedStdout(_args, g_argAsmJsonStr) || - humanTargetedStdout(_args, g_argOpcodesStr) || - humanTargetedStdout(_args, g_argBinaryStr) || - humanTargetedStdout(_args, g_argCloneBinaryStr); -} - -static inline bool outputToFile(OutputType type) -{ - return type == OutputType::FILE || type == OutputType::BOTH; -} - -static inline bool outputToStdout(OutputType type) -{ - return type == OutputType::STDOUT || type == OutputType::BOTH; -} - -static std::istream& operator>>(std::istream& _in, OutputType& io_output) -{ - std::string token; - _in >> token; - if (token == "stdout") - io_output = OutputType::STDOUT; - else if (token == "file") - io_output = OutputType::FILE; - else if (token == "both") - io_output = OutputType::BOTH; - else - throw boost::program_options::invalid_option_value(token); - return _in; -} - -void CommandLineInterface::handleBinary(string const& _contract) -{ - if (m_args.count(g_argBinaryStr)) - { - if (outputToStdout(m_args[g_argBinaryStr].as())) - { - cout << "Binary: " << endl; - cout << toHex(m_compiler->getBytecode(_contract)) << endl; - } - if (outputToFile(m_args[g_argBinaryStr].as())) - { - ofstream outFile(_contract + ".binary"); - outFile << toHex(m_compiler->getBytecode(_contract)); - outFile.close(); - } - } - if (m_args.count(g_argCloneBinaryStr)) - { - if (outputToStdout(m_args[g_argCloneBinaryStr].as())) - { - cout << "Clone Binary: " << endl; - cout << toHex(m_compiler->getCloneBytecode(_contract)) << endl; - } - if (outputToFile(m_args[g_argCloneBinaryStr].as())) - { - ofstream outFile(_contract + ".clone_binary"); - outFile << toHex(m_compiler->getCloneBytecode(_contract)); - outFile.close(); - } - } -} - -void CommandLineInterface::handleOpcode(string const& _contract) -{ - auto choice = m_args[g_argOpcodesStr].as(); - if (outputToStdout(choice)) - { - cout << "Opcodes: " << endl; - cout << eth::disassemble(m_compiler->getBytecode(_contract)); - cout << endl; - } - - if (outputToFile(choice)) - { - ofstream outFile(_contract + ".opcode"); - outFile << eth::disassemble(m_compiler->getBytecode(_contract)); - outFile.close(); - } -} - -void CommandLineInterface::handleBytecode(string const& _contract) -{ - if (m_args.count(g_argOpcodesStr)) - handleOpcode(_contract); - if (m_args.count(g_argBinaryStr) || m_args.count(g_argCloneBinaryStr)) - handleBinary(_contract); -} - -void CommandLineInterface::handleSignatureHashes(string const& _contract) -{ - if (!m_args.count(g_argSignatureHashes)) - return; - - string out; - for (auto const& it: m_compiler->getContractDefinition(_contract).getInterfaceFunctions()) - out += toHex(it.first.ref()) + ": " + it.second->externalSignature() + "\n"; - - auto choice = m_args[g_argSignatureHashes].as(); - if (outputToStdout(choice)) - cout << "Function signatures: " << endl << out; - - if (outputToFile(choice)) - { - ofstream outFile(_contract + ".signatures"); - outFile << out; - outFile.close(); - } -} - -void CommandLineInterface::handleMeta(DocumentationType _type, string const& _contract) -{ - std::string argName; - std::string suffix; - std::string title; - switch(_type) - { - case DocumentationType::ABIInterface: - argName = g_argAbiStr; - suffix = ".abi"; - title = "Contract JSON ABI"; - break; - case DocumentationType::ABISolidityInterface: - argName = g_argSolAbiStr; - suffix = ".sol"; - title = "Contract Solidity ABI"; - break; - case DocumentationType::NatspecUser: - argName = g_argNatspecUserStr; - suffix = ".docuser"; - title = "User Documentation"; - break; - case DocumentationType::NatspecDev: - argName = g_argNatspecDevStr; - suffix = ".docdev"; - title = "Developer Documentation"; - break; - default: - // should never happen - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type")); - } - - if (m_args.count(argName)) - { - auto choice = m_args[argName].as(); - if (outputToStdout(choice)) - { - cout << title << endl; - cout << m_compiler->getMetadata(_contract, _type) << endl; - } - - if (outputToFile(choice)) - { - ofstream outFile(_contract + suffix); - outFile << m_compiler->getMetadata(_contract, _type); - outFile.close(); - } - } -} - -void CommandLineInterface::handleGasEstimation(string const& _contract) -{ - using Gas = GasEstimator::GasConsumption; - if (!m_compiler->getAssemblyItems(_contract) && !m_compiler->getRuntimeAssemblyItems(_contract)) - return; - cout << "Gas estimation:" << endl; - if (eth::AssemblyItems const* items = m_compiler->getAssemblyItems(_contract)) - { - Gas gas = GasEstimator::functionalEstimation(*items); - u256 bytecodeSize(m_compiler->getRuntimeBytecode(_contract).size()); - cout << "construction:" << endl; - cout << " " << gas << " + " << (bytecodeSize * eth::c_createDataGas) << " = "; - gas += bytecodeSize * eth::c_createDataGas; - cout << gas << endl; - } - if (eth::AssemblyItems const* items = m_compiler->getRuntimeAssemblyItems(_contract)) - { - ContractDefinition const& contract = m_compiler->getContractDefinition(_contract); - cout << "external:" << endl; - for (auto it: contract.getInterfaceFunctions()) - { - string sig = it.second->externalSignature(); - GasEstimator::GasConsumption gas = GasEstimator::functionalEstimation(*items, sig); - cout << " " << sig << ":\t" << gas << endl; - } - if (contract.getFallbackFunction()) - { - GasEstimator::GasConsumption gas = GasEstimator::functionalEstimation(*items, "INVALID"); - cout << " fallback:\t" << gas << endl; - } - cout << "internal:" << endl; - for (auto const& it: contract.getDefinedFunctions()) - { - if (it->isPartOfExternalInterface() || it->isConstructor()) - continue; - size_t entry = m_compiler->getFunctionEntryPoint(_contract, *it); - GasEstimator::GasConsumption gas = GasEstimator::GasConsumption::infinite(); - if (entry > 0) - gas = GasEstimator::functionalEstimation(*items, entry, *it); - FunctionType type(*it); - cout << " " << it->getName() << "("; - auto end = type.getParameterTypes().end(); - for (auto it = type.getParameterTypes().begin(); it != end; ++it) - cout << (*it)->toString() << (it + 1 == end ? "" : ","); - cout << "):\t" << gas << endl; - } - } -} - -bool CommandLineInterface::parseArguments(int argc, char** argv) -{ - // Declare the supported options. - po::options_description desc("Allowed options"); - desc.add_options() - ("help", "Show help message and exit") - ("version", "Show version and exit") - ("optimize", po::value()->default_value(false), "Optimize bytecode") - ("optimize-runs", po::value()->default_value(200), "Estimated number of contract runs for optimizer.") - ("add-std", po::value()->default_value(false), "Add standard contracts") - ("input-file", po::value>(), "input file") - ( - "combined-json", - po::value()->value_name(boost::join(g_combinedJsonArgs, ",")), - "Output a single json document containing the specified information, can be combined." - ) - (g_argAstStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the AST of the contract.") - (g_argAstJson.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the AST of the contract in JSON format.") - (g_argAsmStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the EVM assembly of the contract.") - (g_argAsmJsonStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the EVM assembly of the contract in JSON format.") - (g_argOpcodesStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the Opcodes of the contract.") - (g_argBinaryStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the contract in binary (hexadecimal).") - (g_argCloneBinaryStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the clone contract in binary (hexadecimal).") - (g_argAbiStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the contract's JSON ABI interface.") - (g_argSolAbiStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the contract's Solidity ABI interface.") - (g_argSignatureHashes.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the contract's functions' signature hashes.") - (g_argGas.c_str(), - "Request to output an estimate for each function's maximal gas usage.") - (g_argNatspecUserStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the contract's Natspec user documentation.") - (g_argNatspecDevStr.c_str(), po::value()->value_name("stdout|file|both"), - "Request to output the contract's Natspec developer documentation."); - - // All positional options should be interpreted as input files - po::positional_options_description p; - p.add("input-file", -1); - - // parse the compiler arguments - try - { - po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args); - } - catch (po::error const& _exception) - { - cerr << _exception.what() << endl; - return false; - } - if (m_args.count("combined-json")) - { - vector requests; - for (string const& item: boost::split(requests, m_args["combined-json"].as(), boost::is_any_of(","))) - if (!g_combinedJsonArgs.count(item)) - { - cerr << "Invalid option to --combined-json: " << item << endl; - return false; - } - } - po::notify(m_args); - - if (m_args.count("help")) - { - cout << desc; - return false; - } - - if (m_args.count("version")) - { - version(); - return false; - } - - return true; -} - -bool CommandLineInterface::processInput() -{ - if (!m_args.count("input-file")) - { - string s; - while (!cin.eof()) - { - getline(cin, s); - m_sourceCodes[""].append(s + '\n'); - } - } - else - for (string const& infile: m_args["input-file"].as>()) - { - auto path = boost::filesystem::path(infile); - if (!boost::filesystem::exists(path)) - { - cerr << "Skipping non existant input file \"" << infile << "\"" << endl; - continue; - } - - if (!boost::filesystem::is_regular_file(path)) - { - cerr << "\"" << infile << "\" is not a valid file. Skipping" << endl; - continue; - } - - m_sourceCodes[infile] = dev::contentsString(infile); - } - - m_compiler.reset(new CompilerStack(m_args["add-std"].as())); - try - { - for (auto const& sourceCode: m_sourceCodes) - m_compiler->addSource(sourceCode.first, sourceCode.second); - // TODO: Perhaps we should not compile unless requested - bool optimize = m_args["optimize"].as(); - unsigned runs = m_args["optimize-runs"].as(); - m_compiler->compile(optimize, runs); - } - catch (ParserError const& _exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, _exception, "Parser error", *m_compiler); - return false; - } - catch (DeclarationError const& _exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, _exception, "Declaration error", *m_compiler); - return false; - } - catch (TypeError const& _exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, _exception, "Type error", *m_compiler); - return false; - } - catch (CompilerError const& _exception) - { - SourceReferenceFormatter::printExceptionInformation(cerr, _exception, "Compiler error", *m_compiler); - return false; - } - catch (InternalCompilerError const& _exception) - { - cerr << "Internal compiler error during compilation:" << endl - << boost::diagnostic_information(_exception); - return false; - } - catch (DocstringParsingError const& _exception) - { - cerr << "Documentation parsing error: " << *boost::get_error_info(_exception) << endl; - return false; - } - catch (Exception const& _exception) - { - cerr << "Exception during compilation: " << boost::diagnostic_information(_exception) << endl; - return false; - } - catch (...) - { - cerr << "Unknown exception during compilation." << endl; - return false; - } - - return true; -} - -void CommandLineInterface::handleCombinedJSON() -{ - if (!m_args.count("combined-json")) - return; - - Json::Value output(Json::objectValue); - - set requests; - boost::split(requests, m_args["combined-json"].as(), boost::is_any_of(",")); - vector contracts = m_compiler->getContractNames(); - - if (!contracts.empty()) - output["contracts"] = Json::Value(Json::objectValue); - for (string const& contractName: contracts) - { - Json::Value contractData(Json::objectValue); - if (requests.count("sol-abi")) - contractData["sol-abi"] = m_compiler->getSolidityInterface(contractName); - if (requests.count("json-abi")) - contractData["json-abi"] = m_compiler->getInterface(contractName); - if (requests.count("binary")) - contractData["binary"] = toHex(m_compiler->getBytecode(contractName)); - if (requests.count("clone-binary")) - contractData["clone-binary"] = toHex(m_compiler->getCloneBytecode(contractName)); - if (requests.count("opcodes")) - contractData["opcodes"] = eth::disassemble(m_compiler->getBytecode(contractName)); - if (requests.count("asm")) - { - ostringstream unused; - contractData["asm"] = m_compiler->streamAssembly(unused, contractName, m_sourceCodes, true); - } - if (requests.count("natspec-dev")) - contractData["natspec-dev"] = m_compiler->getMetadata(contractName, DocumentationType::NatspecDev); - if (requests.count("natspec-user")) - contractData["natspec-user"] = m_compiler->getMetadata(contractName, DocumentationType::NatspecUser); - output["contracts"][contractName] = contractData; - } - - if (requests.count("ast")) - { - output["sources"] = Json::Value(Json::objectValue); - for (auto const& sourceCode: m_sourceCodes) - { - ASTJsonConverter converter(m_compiler->getAST(sourceCode.first)); - output["sources"][sourceCode.first] = Json::Value(Json::objectValue); - output["sources"][sourceCode.first]["AST"] = converter.json(); - } - } - cout << Json::FastWriter().write(output) << endl; -} - -void CommandLineInterface::handleAst(string const& _argStr) -{ - string title; - - if (_argStr == g_argAstStr) - title = "Syntax trees:"; - else if (_argStr == g_argAstJson) - title = "JSON AST:"; - else - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal argStr for AST")); - - // do we need AST output? - if (m_args.count(_argStr)) - { - vector asts; - for (auto const& sourceCode: m_sourceCodes) - asts.push_back(&m_compiler->getAST(sourceCode.first)); - map gasCosts; - if (m_compiler->getRuntimeAssemblyItems()) - gasCosts = GasEstimator::breakToStatementLevel( - GasEstimator::structuralEstimation(*m_compiler->getRuntimeAssemblyItems(), asts), - asts - ); - - auto choice = m_args[_argStr].as(); - if (outputToStdout(choice)) - { - cout << title << endl << endl; - for (auto const& sourceCode: m_sourceCodes) - { - cout << endl << "======= " << sourceCode.first << " =======" << endl; - if (_argStr == g_argAstStr) - { - ASTPrinter printer( - m_compiler->getAST(sourceCode.first), - sourceCode.second, - gasCosts - ); - printer.print(cout); - } - else - { - ASTJsonConverter converter(m_compiler->getAST(sourceCode.first)); - converter.print(cout); - } - } - } - - if (outputToFile(choice)) - { - for (auto const& sourceCode: m_sourceCodes) - { - boost::filesystem::path p(sourceCode.first); - ofstream outFile(p.stem().string() + ".ast"); - if (_argStr == g_argAstStr) - { - ASTPrinter printer(m_compiler->getAST(sourceCode.first), sourceCode.second); - printer.print(outFile); - } - else - { - ASTJsonConverter converter(m_compiler->getAST(sourceCode.first)); - converter.print(outFile); - } - outFile.close(); - } - } - } -} - -void CommandLineInterface::actOnInput() -{ - handleCombinedJSON(); - - // do we need AST output? - handleAst(g_argAstStr); - handleAst(g_argAstJson); - - vector contracts = m_compiler->getContractNames(); - for (string const& contract: contracts) - { - if (needsHumanTargetedStdout(m_args)) - cout << endl << "======= " << contract << " =======" << endl; - - // do we need EVM assembly? - if (m_args.count(g_argAsmStr) || m_args.count(g_argAsmJsonStr)) - { - auto choice = m_args.count(g_argAsmStr) ? m_args[g_argAsmStr].as() : m_args[g_argAsmJsonStr].as(); - if (outputToStdout(choice)) - { - cout << "EVM assembly:" << endl; - m_compiler->streamAssembly(cout, contract, m_sourceCodes, m_args.count(g_argAsmJsonStr)); - } - - if (outputToFile(choice)) - { - ofstream outFile(contract + (m_args.count(g_argAsmJsonStr) ? "_evm.json" : ".evm")); - m_compiler->streamAssembly(outFile, contract, m_sourceCodes, m_args.count(g_argAsmJsonStr)); - outFile.close(); - } - } - - if (m_args.count(g_argGas)) - handleGasEstimation(contract); - - handleBytecode(contract); - handleSignatureHashes(contract); - handleMeta(DocumentationType::ABIInterface, contract); - handleMeta(DocumentationType::ABISolidityInterface, contract); - handleMeta(DocumentationType::NatspecDev, contract); - handleMeta(DocumentationType::NatspecUser, contract); - } // end of contracts iteration -} - -} -} diff --git a/solc/CommandLineInterface.h b/solc/CommandLineInterface.h deleted file mode 100644 index 46b9b1e22..000000000 --- a/solc/CommandLineInterface.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Lefteris - * @date 2014 - * Solidity command line interface. - */ -#pragma once - -#include -#include -#include - -namespace dev -{ -namespace solidity -{ - -//forward declaration -enum class DocumentationType: uint8_t; - -enum class OutputType: uint8_t -{ - STDOUT, - FILE, - BOTH -}; - -class CommandLineInterface -{ -public: - CommandLineInterface() {} - - /// Parse command line arguments and return false if we should not continue - bool parseArguments(int argc, char** argv); - /// Parse the files and create source code objects - bool processInput(); - /// Perform actions on the input depending on provided compiler arguments - void actOnInput(); - -private: - void handleCombinedJSON(); - void handleAst(std::string const& _argStr); - void handleBinary(std::string const& _contract); - void handleOpcode(std::string const& _contract); - void handleBytecode(std::string const& _contract); - void handleSignatureHashes(std::string const& _contract); - void handleMeta(DocumentationType _type, - std::string const& _contract); - void handleGasEstimation(std::string const& _contract); - - /// Compiler arguments variable map - boost::program_options::variables_map m_args; - /// map of input files to source code strings - std::map m_sourceCodes; - /// Solidity compiler stack - std::unique_ptr m_compiler; -}; - -} -} diff --git a/solc/docker_emscripten/Dockerfile b/solc/docker_emscripten/Dockerfile deleted file mode 100644 index 881f602d9..000000000 --- a/solc/docker_emscripten/Dockerfile +++ /dev/null @@ -1,70 +0,0 @@ -FROM ubuntu:14.04 - -ENV DEBIAN_FRONTEND noninteractive -RUN apt-get update -RUN apt-get upgrade -y - -# Ethereum dependencies -RUN apt-get install -qy build-essential git cmake libcurl4-openssl-dev wget -RUN apt-get install -qy automake libtool yasm scons - -RUN useradd -ms /bin/bash user -USER user -ENV HOME /home/user -WORKDIR /home/user - -# Emscripten SDK -RUN wget -c https://s3.amazonaws.com/mozilla-games/emscripten/releases/emsdk-portable.tar.gz -RUN tar xzf emsdk-portable.tar.gz -WORKDIR /home/user/emsdk_portable -RUN ./emsdk update && ./emsdk install latest && ./emsdk activate latest -ENV PATH $PATH:/home/user/emsdk_portable:/home/user/emsdk_portable/clang/fastcomp/build_master_64/bin:/home/user/emsdk_portable/emscripten/master - -USER root -RUN apt-get install -qy nodejs -USER user -RUN sed -i "s/NODE_JS = 'node'/NODE_JS = 'nodejs'/g" ~/.emscripten - -# CryptoPP -WORKDIR /home/user -RUN git clone https://github.com/mmoss/cryptopp.git -WORKDIR /home/user/cryptopp -RUN emcmake cmake -DCRYPTOPP_LIBRARY_TYPE=STATIC -DCRYPTOPP_RUNTIME_TYPE=STATIC && emmake make -j 4 -RUN ln -s . src/cryptopp - -# Boost -WORKDIR /home/user -RUN wget 'http://downloads.sourceforge.net/project/boost/boost/1.57.0/boost_1_57_0.tar.bz2?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fboost%2Ffiles%2Fboost%2F1.57.0%2F&ts=1421887207&use_mirror=cznic' -O boost_1_57_0.tar.bz2 -RUN tar xjf boost_1_57_0.tar.bz2 -WORKDIR /home/user/boost_1_57_0 -RUN ./bootstrap.sh --with-libraries=thread,system,regex -RUN sed -i 's/using gcc ;/using gcc : : \/home\/user\/emsdk_portable\/emscripten\/master\/em++ ;/g' ./project-config.jam -RUN sed -i 's/$(archiver\[1\])/\/home\/user\/emsdk_portable\/emscripten\/master\/emar/g' ./tools/build/src/tools/gcc.jam -RUN sed -i 's/$(ranlib\[1\])/\/home\/user\/emsdk_portable\/emscripten\/master\/emranlib/g' ./tools/build/src/tools/gcc.jam -RUN ./b2 link=static variant=release threading=single runtime-link=static thread system regex - -# Json-CPP -WORKDIR /home/user -RUN git clone https://github.com/open-source-parsers/jsoncpp.git -WORKDIR /home/user/jsoncpp -RUN emcmake cmake -DJSONCPP_LIB_BUILD_STATIC=ON -DJSONCPP_LIB_BUILD_SHARED=OFF -DJSONCPP_WITH_TESTS=OFF -DJSONCPP_WITH_POST_BUILD_UNITTEST=OFF -G "Unix Makefiles" . -RUN emmake make - -## Build soljs -WORKDIR /home/user -ADD https://api.github.com/repos/ethereum/cpp-ethereum/git/refs/heads/develop unused.txt -RUN git clone --depth=1 https://github.com/ethereum/cpp-ethereum -WORKDIR /home/user/cpp-ethereum -RUN git config --global user.email "me@example.com" -RUN git config --global user.name "Jane Doe" -ADD https://api.github.com/repos/chriseth/cpp-ethereum/git/refs/heads/solidity-js unused2.txt -RUN git remote add -f solidityjs https://github.com/chriseth/cpp-ethereum -# TODO this should be a proper merge but somehow causes problems -# NOTE that we only get the latest commit of that branch -RUN git cherry-pick solidityjs/solidity-js -RUN emcmake cmake -DMINER=0 -DETHKEY=0 -DSERPENT=0 -DTESTS=0 -DETHASHCL=0 -DJSCONSOLE=0 -DEVMJIT=0 -DETH_STATIC=1 -DSOLIDITY=1 -DGUI=0 -DCMAKE_CXX_COMPILER=/home/user/emsdk_portable/emscripten/master/em++ -DCMAKE_C_COMPILER=/home/user/emsdk_portable/emscripten/master/emcc -RUN emmake make -j 6 soljson - -WORKDIR /home/user/cpp-ethereum/solc -ENTRYPOINT cat soljson.js - diff --git a/solc/jsonCompiler.cpp b/solc/jsonCompiler.cpp deleted file mode 100644 index bde13762a..000000000 --- a/solc/jsonCompiler.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * JSON interface for the solidity compiler to be used from Javascript. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev; -using namespace solidity; - -string formatError(Exception const& _exception, string const& _name, CompilerStack const& _compiler) -{ - ostringstream errorOutput; - SourceReferenceFormatter::printExceptionInformation(errorOutput, _exception, _name, _compiler); - - Json::Value output(Json::objectValue); - output["error"] = errorOutput.str(); - return Json::FastWriter().write(output); -} - -Json::Value functionHashes(ContractDefinition const& _contract) -{ - Json::Value functionHashes(Json::objectValue); - for (auto const& it: _contract.getInterfaceFunctions()) - functionHashes[it.second->externalSignature()] = toHex(it.first.ref()); - return functionHashes; -} - -Json::Value gasToJson(GasEstimator::GasConsumption const& _gas) -{ - if (_gas.isInfinite || _gas.value > std::numeric_limits::max()) - return Json::Value(Json::nullValue); - else - return Json::Value(Json::LargestUInt(_gas.value)); -} - -Json::Value estimateGas(CompilerStack const& _compiler, string const& _contract) -{ - Json::Value gasEstimates(Json::objectValue); - using Gas = GasEstimator::GasConsumption; - if (!_compiler.getAssemblyItems(_contract) && !_compiler.getRuntimeAssemblyItems(_contract)) - return gasEstimates; - if (eth::AssemblyItems const* items = _compiler.getAssemblyItems(_contract)) - { - Gas gas = GasEstimator::functionalEstimation(*items); - u256 bytecodeSize(_compiler.getRuntimeBytecode(_contract).size()); - Json::Value creationGas(Json::arrayValue); - creationGas[0] = gasToJson(gas); - creationGas[1] = gasToJson(bytecodeSize * eth::c_createDataGas); - gasEstimates["creation"] = creationGas; - } - if (eth::AssemblyItems const* items = _compiler.getRuntimeAssemblyItems(_contract)) - { - ContractDefinition const& contract = _compiler.getContractDefinition(_contract); - Json::Value externalFunctions(Json::objectValue); - for (auto it: contract.getInterfaceFunctions()) - { - string sig = it.second->externalSignature(); - externalFunctions[sig] = gasToJson(GasEstimator::functionalEstimation(*items, sig)); - } - if (contract.getFallbackFunction()) - externalFunctions[""] = gasToJson(GasEstimator::functionalEstimation(*items, "INVALID")); - gasEstimates["external"] = externalFunctions; - Json::Value internalFunctions(Json::objectValue); - for (auto const& it: contract.getDefinedFunctions()) - { - if (it->isPartOfExternalInterface() || it->isConstructor()) - continue; - size_t entry = _compiler.getFunctionEntryPoint(_contract, *it); - GasEstimator::GasConsumption gas = GasEstimator::GasConsumption::infinite(); - if (entry > 0) - gas = GasEstimator::functionalEstimation(*items, entry, *it); - FunctionType type(*it); - string sig = it->getName() + "("; - auto end = type.getParameterTypes().end(); - for (auto it = type.getParameterTypes().begin(); it != end; ++it) - sig += (*it)->toString() + (it + 1 == end ? "" : ","); - sig += ")"; - internalFunctions[sig] = gasToJson(gas); - } - gasEstimates["internal"] = internalFunctions; - } - return gasEstimates; -} - -string compile(string _input, bool _optimize) -{ - StringMap sources; - sources[""] = _input; - - Json::Value output(Json::objectValue); - CompilerStack compiler; - try - { - compiler.compile(_input, _optimize); - } - catch (ParserError const& exception) - { - return formatError(exception, "Parser error", compiler); - } - catch (DeclarationError const& exception) - { - return formatError(exception, "Declaration error", compiler); - } - catch (TypeError const& exception) - { - return formatError(exception, "Type error", compiler); - } - catch (CompilerError const& exception) - { - return formatError(exception, "Compiler error", compiler); - } - catch (InternalCompilerError const& exception) - { - return formatError(exception, "Internal compiler error", compiler); - } - catch (DocstringParsingError const& exception) - { - return formatError(exception, "Documentation parsing error", compiler); - } - catch (Exception const& exception) - { - output["error"] = "Exception during compilation: " + boost::diagnostic_information(exception); - return Json::FastWriter().write(output); - } - catch (...) - { - output["error"] = "Unknown exception during compilation."; - return Json::FastWriter().write(output); - } - - output["contracts"] = Json::Value(Json::objectValue); - for (string const& contractName: compiler.getContractNames()) - { - Json::Value contractData(Json::objectValue); - contractData["solidity_interface"] = compiler.getSolidityInterface(contractName); - contractData["interface"] = compiler.getInterface(contractName); - contractData["bytecode"] = toHex(compiler.getBytecode(contractName)); - contractData["opcodes"] = eth::disassemble(compiler.getBytecode(contractName)); - contractData["functionHashes"] = functionHashes(compiler.getContractDefinition(contractName)); - contractData["gasEstimates"] = estimateGas(compiler, contractName); - ostringstream unused; - contractData["assembly"] = compiler.streamAssembly(unused, contractName, sources, true); - output["contracts"][contractName] = contractData; - } - - output["sources"] = Json::Value(Json::objectValue); - output["sources"][""] = Json::Value(Json::objectValue); - output["sources"][""]["AST"] = ASTJsonConverter(compiler.getAST("")).json(); - - return Json::FastWriter().write(output); -} - -static string outputBuffer; - -extern "C" -{ -extern char const* compileJSON(char const* _input, bool _optimize) -{ - outputBuffer = compile(_input, _optimize); - return outputBuffer.c_str(); -} -} diff --git a/solc/main.cpp b/solc/main.cpp deleted file mode 100644 index c5f72980d..000000000 --- a/solc/main.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Solidity commandline compiler. - */ - -#include "CommandLineInterface.h" - -int main(int argc, char** argv) -{ - dev::solidity::CommandLineInterface cli; - if (!cli.parseArguments(argc, argv)) - return 1; - if (!cli.processInput()) - return 1; - cli.actOnInput(); - - return 0; -} diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index f74751126..dcc7a405c 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -31,10 +31,6 @@ if (JSCONSOLE) add_subdirectory(libjsengine) endif() -if (SOLIDITY) - add_subdirectory(libsolidity) - add_subdirectory(contracts) -endif () if (JSONRPC) add_subdirectory(libweb3jsonrpc) endif () @@ -84,10 +80,6 @@ if (JSCONSOLE) target_link_libraries(testeth jsengine) endif() -if (SOLIDITY) - target_link_libraries(testeth solidity) -endif () - target_link_libraries(testeth testutils) if (GUI AND NOT JUSTTESTS) diff --git a/test/contracts/AuctionRegistrar.cpp b/test/contracts/AuctionRegistrar.cpp deleted file mode 100644 index 7c5d9fa35..000000000 --- a/test/contracts/AuctionRegistrar.cpp +++ /dev/null @@ -1,497 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Tests for a fixed fee registrar contract. - */ - -#include -#include -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -namespace -{ - -static char const* registrarCode = R"DELIMITER( -//sol - -contract NameRegister { - function addr(string _name) constant returns (address o_owner); - function name(address _owner) constant returns (string o_name); -} - -contract Registrar is NameRegister { - event Changed(string indexed name); - event PrimaryChanged(string indexed name, address indexed addr); - - function owner(string _name) constant returns (address o_owner); - function addr(string _name) constant returns (address o_address); - function subRegistrar(string _name) constant returns (address o_subRegistrar); - function content(string _name) constant returns (bytes32 o_content); - - function name(address _owner) constant returns (string o_name); -} - -contract AuctionSystem { - event AuctionEnded(string indexed _name, address _winner); - event NewBid(string indexed _name, address _bidder, uint _value); - - /// Function that is called once an auction ends. - function onAuctionEnd(string _name) internal; - - function bid(string _name, address _bidder, uint _value) internal { - var auction = m_auctions[_name]; - if (auction.endDate > 0 && now > auction.endDate) - { - AuctionEnded(_name, auction.highestBidder); - onAuctionEnd(_name); - delete m_auctions[_name]; - return; - } - if (msg.value > auction.highestBid) - { - // new bid on auction - auction.secondHighestBid = auction.highestBid; - auction.sumOfBids += _value; - auction.highestBid = _value; - auction.highestBidder = _bidder; - auction.endDate = now + c_biddingTime; - - NewBid(_name, _bidder, _value); - } - } - - uint constant c_biddingTime = 7 days; - - struct Auction { - address highestBidder; - uint highestBid; - uint secondHighestBid; - uint sumOfBids; - uint endDate; - } - mapping(string => Auction) m_auctions; -} - -contract GlobalRegistrar is Registrar, AuctionSystem { - struct Record { - address owner; - address primary; - address subRegistrar; - bytes32 content; - uint renewalDate; - } - - uint constant c_renewalInterval = 1 years; - uint constant c_freeBytes = 12; - - function Registrar() { - // TODO: Populate with hall-of-fame. - } - - function() { - // prevent people from just sending funds to the registrar - __throw(); - } - - function onAuctionEnd(string _name) internal { - var auction = m_auctions[_name]; - var record = m_toRecord[_name]; - if (record.owner != 0) - record.owner.send(auction.sumOfBids - auction.highestBid / 100); - else - auction.highestBidder.send(auction.highestBid - auction.secondHighestBid); - record.renewalDate = now + c_renewalInterval; - record.owner = auction.highestBidder; - Changed(_name); - } - - function reserve(string _name) external { - if (bytes(_name).length == 0) - __throw(); - bool needAuction = requiresAuction(_name); - if (needAuction) - { - if (now < m_toRecord[_name].renewalDate) - __throw(); - bid(_name, msg.sender, msg.value); - } - else - { - Record record = m_toRecord[_name]; - if (record.owner != 0) - __throw(); - m_toRecord[_name].owner = msg.sender; - Changed(_name); - } - } - - function requiresAuction(string _name) internal returns (bool) { - return bytes(_name).length < c_freeBytes; - } - - modifier onlyrecordowner(string _name) { if (m_toRecord[_name].owner == msg.sender) _ } - - function transfer(string _name, address _newOwner) onlyrecordowner(_name) { - m_toRecord[_name].owner = _newOwner; - Changed(_name); - } - - function disown(string _name) onlyrecordowner(_name) { - if (stringsEqual(m_toName[m_toRecord[_name].primary], _name)) - { - PrimaryChanged(_name, m_toRecord[_name].primary); - m_toName[m_toRecord[_name].primary] = ""; - } - delete m_toRecord[_name]; - Changed(_name); - } - - function setAddress(string _name, address _a, bool _primary) onlyrecordowner(_name) { - m_toRecord[_name].primary = _a; - if (_primary) - { - PrimaryChanged(_name, _a); - m_toName[_a] = _name; - } - Changed(_name); - } - function setSubRegistrar(string _name, address _registrar) onlyrecordowner(_name) { - m_toRecord[_name].subRegistrar = _registrar; - Changed(_name); - } - function setContent(string _name, bytes32 _content) onlyrecordowner(_name) { - m_toRecord[_name].content = _content; - Changed(_name); - } - - function stringsEqual(string storage _a, string memory _b) internal returns (bool) { - bytes storage a = bytes(_a); - bytes memory b = bytes(_b); - if (a.length != b.length) - return false; - // @todo unroll this loop - for (uint i = 0; i < a.length; i ++) - if (a[i] != b[i]) - return false; - return true; - } - - function owner(string _name) constant returns (address) { return m_toRecord[_name].owner; } - function addr(string _name) constant returns (address) { return m_toRecord[_name].primary; } - function subRegistrar(string _name) constant returns (address) { return m_toRecord[_name].subRegistrar; } - function content(string _name) constant returns (bytes32) { return m_toRecord[_name].content; } - function name(address _addr) constant returns (string o_name) { return m_toName[_addr]; } - - function __throw() internal { - // workaround until we have "throw" - uint[] x; x[1]; - } - - mapping (address => string) m_toName; - mapping (string => Record) m_toRecord; -} -)DELIMITER"; - -static unique_ptr s_compiledRegistrar; - -class AuctionRegistrarTestFramework: public ExecutionFramework -{ -protected: - void deployRegistrar() - { - if (!s_compiledRegistrar) - { - m_optimize = true; - m_compiler.reset(false, m_addStandardSources); - m_compiler.addSource("", registrarCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); - s_compiledRegistrar.reset(new bytes(m_compiler.getBytecode("GlobalRegistrar"))); - } - sendMessage(*s_compiledRegistrar, true); - BOOST_REQUIRE(!m_output.empty()); - } - - using ContractInterface = ExecutionFramework::ContractInterface; - class RegistrarInterface: public ContractInterface - { - public: - RegistrarInterface(ExecutionFramework& _framework): ContractInterface(_framework) {} - void reserve(string const& _name) - { - callString("reserve", _name); - } - u160 owner(string const& _name) - { - return callStringReturnsAddress("owner", _name); - } - void setAddress(string const& _name, u160 const& _address, bool _primary) - { - callStringAddressBool("setAddress", _name, _address, _primary); - } - u160 addr(string const& _name) - { - return callStringReturnsAddress("addr", _name); - } - string name(u160 const& _addr) - { - return callAddressReturnsString("name", _addr); - } - void setSubRegistrar(string const& _name, u160 const& _address) - { - callStringAddress("setSubRegistrar", _name, _address); - } - u160 subRegistrar(string const& _name) - { - return callStringReturnsAddress("subRegistrar", _name); - } - void setContent(string const& _name, h256 const& _content) - { - callStringBytes32("setContent", _name, _content); - } - h256 content(string const& _name) - { - return callStringReturnsBytes32("content", _name); - } - void transfer(string const& _name, u160 const& _target) - { - return callStringAddress("transfer", _name, _target); - } - void disown(string const& _name) - { - return callString("disown", _name); - } - }; - - u256 const m_biddingTime = u256(7 * 24 * 3600); - u256 const m_renewalInterval = u256(365 * 24 * 3600); -}; - -} - -/// This is a test suite that tests optimised code! -BOOST_FIXTURE_TEST_SUITE(SolidityAuctionRegistrar, AuctionRegistrarTestFramework) - -BOOST_AUTO_TEST_CASE(creation) -{ - deployRegistrar(); -} - -BOOST_AUTO_TEST_CASE(reserve) -{ - // Test that reserving works for long strings - deployRegistrar(); - vector names{"abcabcabcabcabc", "defdefdefdefdef", "ghighighighighighighighighighighighighighighi"}; - m_sender = Address(0x123); - - RegistrarInterface registrar(*this); - - // should not work - registrar.reserve(""); - BOOST_CHECK_EQUAL(registrar.owner(""), u160(0)); - - for (auto const& name: names) - { - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), u160(0x123)); - } -} - -BOOST_AUTO_TEST_CASE(double_reserve_long) -{ - // Test that it is not possible to re-reserve from a different address. - deployRegistrar(); - string name = "abcabcabcabcabcabcabcabcabcabca"; - m_sender = Address(0x123); - RegistrarInterface registrar(*this); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), u160(0x123)); - - m_sender = Address(0x124); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), u160(0x123)); -} - -BOOST_AUTO_TEST_CASE(properties) -{ - // Test setting and retrieving the various properties works. - deployRegistrar(); - RegistrarInterface registrar(*this); - string names[] = {"abcaeouoeuaoeuaoeu", "defncboagufra,fui", "ghagpyajfbcuajouhaeoi"}; - size_t addr = 0x9872543; - for (string const& name: names) - { - addr++; - size_t sender = addr + 10007; - m_sender = Address(sender); - // setting by sender works - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), u160(sender)); - registrar.setAddress(name, addr, true); - BOOST_CHECK_EQUAL(registrar.addr(name), u160(addr)); - registrar.setSubRegistrar(name, addr + 20); - BOOST_CHECK_EQUAL(registrar.subRegistrar(name), u160(addr + 20)); - registrar.setContent(name, h256(u256(addr + 90))); - BOOST_CHECK_EQUAL(registrar.content(name), h256(u256(addr + 90))); - - // but not by someone else - m_sender = Address(h256(addr + 10007 - 1)); - BOOST_CHECK_EQUAL(registrar.owner(name), u160(sender)); - registrar.setAddress(name, addr + 1, true); - BOOST_CHECK_EQUAL(registrar.addr(name), u160(addr)); - registrar.setSubRegistrar(name, addr + 20 + 1); - BOOST_CHECK_EQUAL(registrar.subRegistrar(name), u160(addr + 20)); - registrar.setContent(name, h256(u256(addr + 90 + 1))); - BOOST_CHECK_EQUAL(registrar.content(name), h256(u256(addr + 90))); - } -} - -BOOST_AUTO_TEST_CASE(transfer) -{ - deployRegistrar(); - string name = "abcaoeguaoucaeoduceo"; - m_sender = Address(0x123); - RegistrarInterface registrar(*this); - registrar.reserve(name); - registrar.setContent(name, h256(u256(123))); - registrar.transfer(name, u160(555)); - BOOST_CHECK_EQUAL(registrar.owner(name), u160(555)); - BOOST_CHECK_EQUAL(registrar.content(name), h256(u256(123))); -} - -BOOST_AUTO_TEST_CASE(disown) -{ - deployRegistrar(); - string name = "abcaoeguaoucaeoduceo"; - m_sender = Address(0x123); - RegistrarInterface registrar(*this); - registrar.reserve(name); - registrar.setContent(name, h256(u256(123))); - registrar.setAddress(name, u160(124), true); - registrar.setSubRegistrar(name, u160(125)); - BOOST_CHECK_EQUAL(registrar.name(u160(124)), name); - - // someone else tries disowning - m_sender = Address(0x128); - registrar.disown(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0x123); - - m_sender = Address(0x123); - registrar.disown(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0); - BOOST_CHECK_EQUAL(registrar.addr(name), 0); - BOOST_CHECK_EQUAL(registrar.subRegistrar(name), 0); - BOOST_CHECK_EQUAL(registrar.content(name), h256()); - BOOST_CHECK_EQUAL(registrar.name(u160(124)), ""); -} - -BOOST_AUTO_TEST_CASE(auction_simple) -{ - deployRegistrar(); - string name = "x"; - m_sender = Address(0x123); - RegistrarInterface registrar(*this); - // initiate auction - registrar.setNextValue(8); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0); - // "wait" until auction end - m_envInfo.setTimestamp(m_envInfo.timestamp() + m_biddingTime + 10); - // trigger auction again - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0x123); -} - -BOOST_AUTO_TEST_CASE(auction_bidding) -{ - deployRegistrar(); - string name = "x"; - m_sender = Address(0x123); - RegistrarInterface registrar(*this); - // initiate auction - registrar.setNextValue(8); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0); - // overbid self - m_envInfo.setTimestamp(m_biddingTime - 10); - registrar.setNextValue(12); - registrar.reserve(name); - // another bid by someone else - m_sender = Address(0x124); - m_envInfo.setTimestamp(2 * m_biddingTime - 50); - registrar.setNextValue(13); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0); - // end auction by first bidder (which is not highest) trying to overbid again (too late) - m_sender = Address(0x123); - m_envInfo.setTimestamp(4 * m_biddingTime); - registrar.setNextValue(20); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0x124); -} - -BOOST_AUTO_TEST_CASE(auction_renewal) -{ - deployRegistrar(); - string name = "x"; - RegistrarInterface registrar(*this); - // register name by auction - m_sender = Address(0x123); - registrar.setNextValue(8); - registrar.reserve(name); - m_envInfo.setTimestamp(4 * m_biddingTime); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0x123); - - // try to re-register before interval end - m_sender = Address(0x222); - registrar.setNextValue(80); - m_envInfo.setTimestamp(m_envInfo.timestamp() + m_renewalInterval - 1); - registrar.reserve(name); - m_envInfo.setTimestamp(m_envInfo.timestamp() + m_biddingTime); - // if there is a bug in the renewal logic, this would transfer the ownership to 0x222, - // but if there is no bug, this will initiate the auction, albeit with a zero bid - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0x123); - - m_envInfo.setTimestamp(m_envInfo.timestamp() + 2); - registrar.setNextValue(80); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0x123); - m_envInfo.setTimestamp(m_envInfo.timestamp() + m_biddingTime + 2); - registrar.reserve(name); - BOOST_CHECK_EQUAL(registrar.owner(name), 0x222); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/contracts/CMakeLists.txt b/test/contracts/CMakeLists.txt deleted file mode 100644 index 3ceda13b0..000000000 --- a/test/contracts/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -cmake_policy(SET CMP0015 NEW) - -aux_source_directory(. SRCS) - -add_sources(${SRCS}) diff --git a/test/contracts/FixedFeeRegistrar.cpp b/test/contracts/FixedFeeRegistrar.cpp deleted file mode 100644 index ed2ecf0a1..000000000 --- a/test/contracts/FixedFeeRegistrar.cpp +++ /dev/null @@ -1,242 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Tests for a fixed fee registrar contract. - */ - -#include -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -namespace -{ - -static char const* registrarCode = R"DELIMITER( -//sol FixedFeeRegistrar -// Simple global registrar with fixed-fee reservations. -// @authors: -// Gav Wood - -contract Registrar { - event Changed(string indexed name); - - function owner(string _name) constant returns (address o_owner); - function addr(string _name) constant returns (address o_address); - function subRegistrar(string _name) constant returns (address o_subRegistrar); - function content(string _name) constant returns (bytes32 o_content); -} - -contract FixedFeeRegistrar is Registrar { - struct Record { - address addr; - address subRegistrar; - bytes32 content; - address owner; - } - - modifier onlyrecordowner(string _name) { if (m_record(_name).owner == msg.sender) _ } - - function reserve(string _name) { - Record rec = m_record(_name); - if (rec.owner == 0 && msg.value >= c_fee) { - rec.owner = msg.sender; - Changed(_name); - } - } - function disown(string _name, address _refund) onlyrecordowner(_name) { - delete m_recordData[uint(sha3(_name)) / 8]; - _refund.send(c_fee); - Changed(_name); - } - function transfer(string _name, address _newOwner) onlyrecordowner(_name) { - m_record(_name).owner = _newOwner; - Changed(_name); - } - function setAddr(string _name, address _a) onlyrecordowner(_name) { - m_record(_name).addr = _a; - Changed(_name); - } - function setSubRegistrar(string _name, address _registrar) onlyrecordowner(_name) { - m_record(_name).subRegistrar = _registrar; - Changed(_name); - } - function setContent(string _name, bytes32 _content) onlyrecordowner(_name) { - m_record(_name).content = _content; - Changed(_name); - } - - function record(string _name) constant returns (address o_addr, address o_subRegistrar, bytes32 o_content, address o_owner) { - Record rec = m_record(_name); - o_addr = rec.addr; - o_subRegistrar = rec.subRegistrar; - o_content = rec.content; - o_owner = rec.owner; - } - function addr(string _name) constant returns (address) { return m_record(_name).addr; } - function subRegistrar(string _name) constant returns (address) { return m_record(_name).subRegistrar; } - function content(string _name) constant returns (bytes32) { return m_record(_name).content; } - function owner(string _name) constant returns (address) { return m_record(_name).owner; } - - Record[2**253] m_recordData; - function m_record(string _name) constant internal returns (Record storage o_record) { - return m_recordData[uint(sha3(_name)) / 8]; - } - uint constant c_fee = 69 ether; -} -)DELIMITER"; - -static unique_ptr s_compiledRegistrar; - -class RegistrarTestFramework: public ExecutionFramework -{ -protected: - void deployRegistrar() - { - if (!s_compiledRegistrar) - { - m_optimize = true; - m_compiler.reset(false, m_addStandardSources); - m_compiler.addSource("", registrarCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); - s_compiledRegistrar.reset(new bytes(m_compiler.getBytecode("FixedFeeRegistrar"))); - } - sendMessage(*s_compiledRegistrar, true); - BOOST_REQUIRE(!m_output.empty()); - } - u256 const m_fee = u256("69000000000000000000"); -}; - -} - -/// This is a test suite that tests optimised code! -BOOST_FIXTURE_TEST_SUITE(SolidityFixedFeeRegistrar, RegistrarTestFramework) - -BOOST_AUTO_TEST_CASE(creation) -{ - deployRegistrar(); -} - -BOOST_AUTO_TEST_CASE(reserve) -{ - // Test that reserving works and fee is taken into account. - deployRegistrar(); - string name[] = {"abc", "def", "ghi"}; - m_sender = Address(0x123); - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee, encodeDyn(name[0])) == encodeArgs()); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name[0])) == encodeArgs(h256(0x123))); - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee + 1, encodeDyn(name[1])) == encodeArgs()); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name[1])) == encodeArgs(h256(0x123))); - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee - 1, encodeDyn(name[2])) == encodeArgs()); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name[2])) == encodeArgs(h256(0))); -} - -BOOST_AUTO_TEST_CASE(double_reserve) -{ - // Test that it is not possible to re-reserve from a different address. - deployRegistrar(); - string name = "abc"; - m_sender = Address(0x123); - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee, encodeDyn(name)) == encodeArgs()); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name)) == encodeArgs(h256(0x123))); - - m_sender = Address(0x124); - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee, encodeDyn(name)) == encodeArgs()); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name)) == encodeArgs(h256(0x123))); -} - -BOOST_AUTO_TEST_CASE(properties) -{ - // Test setting and retrieving the various properties works. - deployRegistrar(); - string names[] = {"abc", "def", "ghi"}; - size_t addr = 0x9872543; - for (string const& name: names) - { - addr++; - size_t sender = addr + 10007; - m_sender = Address(sender); - // setting by sender works - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee, encodeDyn(name)) == encodeArgs()); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name)) == encodeArgs(u256(sender))); - BOOST_CHECK(callContractFunction("setAddr(string,address)", u256(0x40), u256(addr), u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("addr(string)", encodeDyn(name)) == encodeArgs(addr)); - BOOST_CHECK(callContractFunction("setSubRegistrar(string,address)", u256(0x40), addr + 20, u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("subRegistrar(string)", encodeDyn(name)) == encodeArgs(addr + 20)); - BOOST_CHECK(callContractFunction("setContent(string,bytes32)", u256(0x40), addr + 90, u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("content(string)", encodeDyn(name)) == encodeArgs(addr + 90)); - // but not by someone else - m_sender = Address(h256(addr + 10007 - 1)); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name)) == encodeArgs(sender)); - BOOST_CHECK(callContractFunction("setAddr(string,address)", u256(0x40), addr + 1, u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("addr(string)", encodeDyn(name)) == encodeArgs(addr)); - BOOST_CHECK(callContractFunction("setSubRegistrar(string,address)", u256(0x40), addr + 20 + 1, u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("subRegistrar(string)", encodeDyn(name)) == encodeArgs(addr + 20)); - BOOST_CHECK(callContractFunction("setContent(string,bytes32)", u256(0x40), addr + 90 + 1, u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("content(string)", encodeDyn(name)) == encodeArgs(addr + 90)); - } -} - -BOOST_AUTO_TEST_CASE(transfer) -{ - deployRegistrar(); - string name = "abc"; - m_sender = Address(0x123); - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee, encodeDyn(name)) == encodeArgs()); - BOOST_CHECK(callContractFunction("setContent(string,bytes32)", u256(0x40), u256(123), u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("transfer(string,address)", u256(0x40), u256(555), u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name)) == encodeArgs(u256(555))); - BOOST_CHECK(callContractFunction("content(string)", encodeDyn(name)) == encodeArgs(u256(123))); -} - -BOOST_AUTO_TEST_CASE(disown) -{ - deployRegistrar(); - string name = "abc"; - m_sender = Address(0x123); - BOOST_REQUIRE(callContractFunctionWithValue("reserve(string)", m_fee, encodeDyn(name)) == encodeArgs()); - BOOST_CHECK(callContractFunction("setContent(string,bytes32)", u256(0x40), u256(123), u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("setAddr(string,address)", u256(0x40), u256(124), u256(name.length()), name) == encodeArgs()); - BOOST_CHECK(callContractFunction("setSubRegistrar(string,address)", u256(0x40), u256(125), u256(name.length()), name) == encodeArgs()); - - BOOST_CHECK_EQUAL(m_state.balance(Address(0x124)), 0); - BOOST_CHECK(callContractFunction("disown(string,address)", u256(0x40), u256(0x124), name.size(), name) == encodeArgs()); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x124)), m_fee); - - BOOST_CHECK(callContractFunction("owner(string)", encodeDyn(name)) == encodeArgs(u256(0))); - BOOST_CHECK(callContractFunction("content(string)", encodeDyn(name)) == encodeArgs(u256(0))); - BOOST_CHECK(callContractFunction("addr(string)", encodeDyn(name)) == encodeArgs(u256(0))); - BOOST_CHECK(callContractFunction("subRegistrar(string)", encodeDyn(name)) == encodeArgs(u256(0))); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/contracts/Wallet.cpp b/test/contracts/Wallet.cpp deleted file mode 100644 index 5f9febd40..000000000 --- a/test/contracts/Wallet.cpp +++ /dev/null @@ -1,668 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Tests for a (comparatively) complex multisig wallet contract. - */ - -#include -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -static char const* walletCode = R"DELIMITER( -//sol Wallet -// Multi-sig, daily-limited account proxy/wallet. -// @authors: -// Gav Wood -// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a -// single, or, crucially, each of a number of, designated owners. -// usage: -// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by -// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the -// interior is executed. -contract multiowned { - - // TYPES - - // struct for the status of a pending operation. - struct PendingState { - uint yetNeeded; - uint ownersDone; - uint index; - } - - // EVENTS - - // this contract only has five types of events: it can accept a confirmation, in which case - // we record owner and operation (hash) alongside it. - event Confirmation(address owner, bytes32 operation); - event Revoke(address owner, bytes32 operation); - // some others are in the case of an owner changing. - event OwnerChanged(address oldOwner, address newOwner); - event OwnerAdded(address newOwner); - event OwnerRemoved(address oldOwner); - // the last one is emitted if the required signatures change - event RequirementChanged(uint newRequirement); - - // MODIFIERS - - // simple single-sig function modifier. - modifier onlyowner { - if (isOwner(msg.sender)) - _ - } - // multi-sig function modifier: the operation must have an intrinsic hash in order - // that later attempts can be realised as the same underlying operation and - // thus count as confirmations. - modifier onlymanyowners(bytes32 _operation) { - if (confirmAndCheck(_operation)) - _ - } - - // METHODS - - // constructor is given number of sigs required to do protected "onlymanyowners" transactions - // as well as the selection of addresses capable of confirming them. - function multiowned(address[] _owners, uint _required) { - m_numOwners = _owners.length + 1; - m_owners[1] = uint(msg.sender); - m_ownerIndex[uint(msg.sender)] = 1; - for (uint i = 0; i < _owners.length; ++i) - { - m_owners[2 + i] = uint(_owners[i]); - m_ownerIndex[uint(_owners[i])] = 2 + i; - } - m_required = _required; - } - - // Revokes a prior confirmation of the given operation - function revoke(bytes32 _operation) external { - uint ownerIndex = m_ownerIndex[uint(msg.sender)]; - // make sure they're an owner - if (ownerIndex == 0) return; - uint ownerIndexBit = 2**ownerIndex; - var pending = m_pending[_operation]; - if (pending.ownersDone & ownerIndexBit > 0) { - pending.yetNeeded++; - pending.ownersDone -= ownerIndexBit; - Revoke(msg.sender, _operation); - } - } - - // Replaces an owner `_from` with another `_to`. - function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { - if (isOwner(_to)) return; - uint ownerIndex = m_ownerIndex[uint(_from)]; - if (ownerIndex == 0) return; - - clearPending(); - m_owners[ownerIndex] = uint(_to); - m_ownerIndex[uint(_from)] = 0; - m_ownerIndex[uint(_to)] = ownerIndex; - OwnerChanged(_from, _to); - } - - function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { - if (isOwner(_owner)) return; - - clearPending(); - if (m_numOwners >= c_maxOwners) - reorganizeOwners(); - if (m_numOwners >= c_maxOwners) - return; - m_numOwners++; - m_owners[m_numOwners] = uint(_owner); - m_ownerIndex[uint(_owner)] = m_numOwners; - OwnerAdded(_owner); - } - - function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { - uint ownerIndex = m_ownerIndex[uint(_owner)]; - if (ownerIndex == 0) return; - if (m_required > m_numOwners - 1) return; - - m_owners[ownerIndex] = 0; - m_ownerIndex[uint(_owner)] = 0; - clearPending(); - reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot - OwnerRemoved(_owner); - } - - function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { - if (_newRequired > m_numOwners) return; - m_required = _newRequired; - clearPending(); - RequirementChanged(_newRequired); - } - - function isOwner(address _addr) returns (bool) { - return m_ownerIndex[uint(_addr)] > 0; - } - - function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) { - var pending = m_pending[_operation]; - uint ownerIndex = m_ownerIndex[uint(_owner)]; - - // make sure they're an owner - if (ownerIndex == 0) return false; - - // determine the bit to set for this owner. - uint ownerIndexBit = 2**ownerIndex; - if (pending.ownersDone & ownerIndexBit == 0) { - return false; - } else { - return true; - } - } - - // INTERNAL METHODS - - function confirmAndCheck(bytes32 _operation) internal returns (bool) { - // determine what index the present sender is: - uint ownerIndex = m_ownerIndex[uint(msg.sender)]; - // make sure they're an owner - if (ownerIndex == 0) return; - - var pending = m_pending[_operation]; - // if we're not yet working on this operation, switch over and reset the confirmation status. - if (pending.yetNeeded == 0) { - // reset count of confirmations needed. - pending.yetNeeded = m_required; - // reset which owners have confirmed (none) - set our bitmap to 0. - pending.ownersDone = 0; - pending.index = m_pendingIndex.length++; - m_pendingIndex[pending.index] = _operation; - } - // determine the bit to set for this owner. - uint ownerIndexBit = 2**ownerIndex; - // make sure we (the message sender) haven't confirmed this operation previously. - if (pending.ownersDone & ownerIndexBit == 0) { - Confirmation(msg.sender, _operation); - // ok - check if count is enough to go ahead. - if (pending.yetNeeded <= 1) { - // enough confirmations: reset and run interior. - delete m_pendingIndex[m_pending[_operation].index]; - delete m_pending[_operation]; - return true; - } - else - { - // not enough: record that this owner in particular confirmed. - pending.yetNeeded--; - pending.ownersDone |= ownerIndexBit; - } - } - } - - function reorganizeOwners() private returns (bool) { - uint free = 1; - while (free < m_numOwners) - { - while (free < m_numOwners && m_owners[free] != 0) free++; - while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; - if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) - { - m_owners[free] = m_owners[m_numOwners]; - m_ownerIndex[m_owners[free]] = free; - m_owners[m_numOwners] = 0; - } - } - } - - function clearPending() internal { - uint length = m_pendingIndex.length; - for (uint i = 0; i < length; ++i) - if (m_pendingIndex[i] != 0) - delete m_pending[m_pendingIndex[i]]; - delete m_pendingIndex; - } - - // FIELDS - - // the number of owners that must confirm the same operation before it is run. - uint public m_required; - // pointer used to find a free slot in m_owners - uint public m_numOwners; - - // list of owners - uint[256] m_owners; - uint constant c_maxOwners = 250; - // index on the list of owners to allow reverse lookup - mapping(uint => uint) m_ownerIndex; - // the ongoing operations. - mapping(bytes32 => PendingState) m_pending; - bytes32[] m_pendingIndex; -} - -// inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable) -// on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method -// uses is specified in the modifier. -contract daylimit is multiowned { - - // MODIFIERS - - // simple modifier for daily limit. - modifier limitedDaily(uint _value) { - if (underLimit(_value)) - _ - } - - // METHODS - - // constructor - stores initial daily limit and records the present day's index. - function daylimit(uint _limit) { - m_dailyLimit = _limit; - m_lastDay = today(); - } - // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. - function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external { - m_dailyLimit = _newLimit; - } - // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. - function resetSpentToday() onlymanyowners(sha3(msg.data)) external { - m_spentToday = 0; - } - - // INTERNAL METHODS - - // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and - // returns true. otherwise just returns false. - function underLimit(uint _value) internal onlyowner returns (bool) { - // reset the spend limit if we're on a different day to last time. - if (today() > m_lastDay) { - m_spentToday = 0; - m_lastDay = today(); - } - // check to see if there's enough left - if so, subtract and return true. - if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { - m_spentToday += _value; - return true; - } - return false; - } - // determines today's index. - function today() private constant returns (uint) { return now / 1 days; } - - // FIELDS - - uint public m_dailyLimit; - uint m_spentToday; - uint m_lastDay; -} - -// interface contract for multisig proxy contracts; see below for docs. -contract multisig { - - // EVENTS - - // logged events: - // Funds has arrived into the wallet (record how much). - event Deposit(address from, uint value); - // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going). - event SingleTransact(address owner, uint value, address to, bytes data); - // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going). - event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data); - // Confirmation still needed for a transaction. - event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); - - // FUNCTIONS - - // TODO: document - function changeOwner(address _from, address _to) external; - function execute(address _to, uint _value, bytes _data) external returns (bytes32); - function confirm(bytes32 _h) returns (bool); -} - -// usage: -// bytes32 h = Wallet(w).from(oneOwner).transact(to, value, data); -// Wallet(w).from(anotherOwner).confirm(h); -contract Wallet is multisig, multiowned, daylimit { - - // TYPES - - // Transaction structure to remember details of transaction lest it need be saved for a later call. - struct Transaction { - address to; - uint value; - bytes data; - } - - // METHODS - - // constructor - just pass on the owner array to the multiowned and - // the limit to daylimit - function Wallet(address[] _owners, uint _required, uint _daylimit) - multiowned(_owners, _required) daylimit(_daylimit) { - } - - // kills the contract sending everything to `_to`. - function kill(address _to) onlymanyowners(sha3(msg.data)) external { - suicide(_to); - } - - // gets called when no other function matches - function() { - // just being sent some cash? - if (msg.value > 0) - Deposit(msg.sender, msg.value); - } - - // Outside-visible transact entry point. Executes transacion immediately if below daily spend limit. - // If not, goes into multisig process. We provide a hash on return to allow the sender to provide - // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value - // and _data arguments). They still get the option of using them if they want, anyways. - function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 _r) { - // first, take the opportunity to check that we're under the daily limit. - if (underLimit(_value)) { - SingleTransact(msg.sender, _value, _to, _data); - // yes - just execute the call. - _to.call.value(_value)(_data); - return 0; - } - // determine our operation hash. - _r = sha3(msg.data, block.number); - if (!confirm(_r) && m_txs[_r].to == 0) { - m_txs[_r].to = _to; - m_txs[_r].value = _value; - m_txs[_r].data = _data; - ConfirmationNeeded(_r, msg.sender, _value, _to, _data); - } - } - - // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order - // to determine the body of the transaction from the hash provided. - function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) { - if (m_txs[_h].to != 0) { - m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data); - MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data); - delete m_txs[_h]; - return true; - } - } - - // INTERNAL METHODS - - function clearPending() internal { - uint length = m_pendingIndex.length; - for (uint i = 0; i < length; ++i) - delete m_txs[m_pendingIndex[i]]; - super.clearPending(); - } - - // FIELDS - - // pending transactions we have at present. - mapping (bytes32 => Transaction) m_txs; -} -)DELIMITER"; - -static unique_ptr s_compiledWallet; - -class WalletTestFramework: public ExecutionFramework -{ -protected: - void deployWallet( - u256 const& _value = 0, - vector const& _owners = vector{}, - u256 _required = 1, - u256 _dailyLimit = 0 - ) - { - if (!s_compiledWallet) - { - m_optimize = true; - m_compiler.reset(false, m_addStandardSources); - m_compiler.addSource("", walletCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); - s_compiledWallet.reset(new bytes(m_compiler.getBytecode("Wallet"))); - } - bytes args = encodeArgs(u256(0x60), _required, _dailyLimit, u256(_owners.size()), _owners); - sendMessage(*s_compiledWallet + args, true, _value); - BOOST_REQUIRE(!m_output.empty()); - } -}; - -/// This is a test suite that tests optimised code! -BOOST_FIXTURE_TEST_SUITE(SolidityWallet, WalletTestFramework) - -BOOST_AUTO_TEST_CASE(creation) -{ - deployWallet(200); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(m_sender, h256::AlignRight)) == encodeArgs(true)); - BOOST_REQUIRE(callContractFunction("isOwner(address)", ~h256(m_sender, h256::AlignRight)) == encodeArgs(false)); -} - -BOOST_AUTO_TEST_CASE(add_owners) -{ - deployWallet(200); - Address originalOwner = m_sender; - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12)) == encodeArgs(true)); - // now let the new owner add someone - m_sender = Address(0x12); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x13)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x13)) == encodeArgs(true)); - // and check that a non-owner cannot add a new owner - m_sender = Address(0x50); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x20)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x20)) == encodeArgs(false)); - // finally check that all the owners are there - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(originalOwner, h256::AlignRight)) == encodeArgs(true)); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12)) == encodeArgs(true)); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x13)) == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(change_owners) -{ - deployWallet(200); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12)) == encodeArgs(true)); - BOOST_REQUIRE(callContractFunction("changeOwner(address,address)", h256(0x12), h256(0x13)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12)) == encodeArgs(false)); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x13)) == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(remove_owner) -{ - deployWallet(200); - // add 10 owners - for (unsigned i = 0; i < 10; ++i) - { - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12 + i)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12 + i)) == encodeArgs(true)); - } - // check they are there again - for (unsigned i = 0; i < 10; ++i) - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12 + i)) == encodeArgs(true)); - // remove the odd owners - for (unsigned i = 0; i < 10; ++i) - if (i % 2 == 1) - BOOST_REQUIRE(callContractFunction("removeOwner(address)", h256(0x12 + i)) == encodeArgs()); - // check the result - for (unsigned i = 0; i < 10; ++i) - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12 + i)) == encodeArgs(i % 2 == 0)); - // add them again - for (unsigned i = 0; i < 10; ++i) - if (i % 2 == 1) - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12 + i)) == encodeArgs()); - // check everyone is there - for (unsigned i = 0; i < 10; ++i) - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x12 + i)) == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(initial_owners) -{ - vector owners{ - u256("0x00000000000000000000000042c56279432962a17176998a4747d1b4d6ed4367"), - u256("0x000000000000000000000000d4d4669f5ba9f4c27d38ef02a358c339b5560c47"), - u256("0x000000000000000000000000e6716f9544a56c530d868e4bfbacb172315bdead"), - u256("0x000000000000000000000000775e18be7a50a0abb8a4e82b1bd697d79f31fe04"), - u256("0x000000000000000000000000f4dd5c3794f1fd0cdc0327a83aa472609c806e99"), - u256("0x0000000000000000000000004c9113886af165b2de069d6e99430647e94a9fff"), - u256("0x0000000000000000000000003fb1cd2cd96c6d5c0b5eb3322d807b34482481d4") - }; - deployWallet(0, owners, 4, 2); - BOOST_CHECK(callContractFunction("m_numOwners()") == encodeArgs(u256(8))); - BOOST_CHECK(callContractFunction("isOwner(address)", h256(m_sender, h256::AlignRight)) == encodeArgs(true)); - for (u256 const& owner: owners) - { - BOOST_CHECK(callContractFunction("isOwner(address)", owner) == encodeArgs(true)); - } -} - -BOOST_AUTO_TEST_CASE(multisig_value_transfer) -{ - deployWallet(200); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x13)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x14)) == encodeArgs()); - // 4 owners, set required to 3 - BOOST_REQUIRE(callContractFunction("changeRequirement(uint256)", u256(3)) == encodeArgs()); - // check that balance is and stays zero at destination address - h256 opHash("6244b4fa93f73e09db0ae52750095ca0364a76b72bc01723c97011fcb876cc9e"); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x12); - BOOST_REQUIRE(callContractFunction("execute(address,uint256,bytes)", h256(0x05), 100, 0x60, 0x00) == encodeArgs(opHash)); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x13); - BOOST_REQUIRE(callContractFunction("execute(address,uint256,bytes)", h256(0x05), 100, 0x60, 0x00) == encodeArgs(opHash)); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x14); - BOOST_REQUIRE(callContractFunction("execute(address,uint256,bytes)", h256(0x05), 100, 0x60, 0x00) == encodeArgs(opHash)); - // now it should go through - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 100); -} - -BOOST_AUTO_TEST_CASE(revoke_addOwner) -{ - deployWallet(); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x13)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x14)) == encodeArgs()); - // 4 owners, set required to 3 - BOOST_REQUIRE(callContractFunction("changeRequirement(uint256)", u256(3)) == encodeArgs()); - // add a new owner - Address deployer = m_sender; - h256 opHash = sha3(FixedHash<4>(dev::sha3("addOwner(address)")).asBytes() + h256(0x33).asBytes()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x33)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x33)) == encodeArgs(false)); - m_sender = Address(0x12); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x33)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x33)) == encodeArgs(false)); - // revoke one confirmation - m_sender = deployer; - BOOST_REQUIRE(callContractFunction("revoke(bytes32)", opHash) == encodeArgs()); - m_sender = Address(0x13); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x33)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x33)) == encodeArgs(false)); - m_sender = Address(0x14); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x33)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("isOwner(address)", h256(0x33)) == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(revoke_transaction) -{ - deployWallet(200); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x13)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x14)) == encodeArgs()); - // 4 owners, set required to 3 - BOOST_REQUIRE(callContractFunction("changeRequirement(uint256)", u256(3)) == encodeArgs()); - // create a transaction - Address deployer = m_sender; - h256 opHash("6244b4fa93f73e09db0ae52750095ca0364a76b72bc01723c97011fcb876cc9e"); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x12); - BOOST_REQUIRE(callContractFunction("execute(address,uint256,bytes)", h256(0x05), 100, 0x60, 0x00) == encodeArgs(opHash)); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x13); - BOOST_REQUIRE(callContractFunction("execute(address,uint256,bytes)", h256(0x05), 100, 0x60, 0x00) == encodeArgs(opHash)); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x12); - BOOST_REQUIRE(callContractFunction("revoke(bytes32)", opHash) == encodeArgs()); - m_sender = deployer; - BOOST_REQUIRE(callContractFunction("execute(address,uint256,bytes)", h256(0x05), 100, 0x60, 0x00) == encodeArgs(opHash)); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x14); - BOOST_REQUIRE(callContractFunction("execute(address,uint256,bytes)", h256(0x05), 100, 0x60, 0x00) == encodeArgs(opHash)); - // now it should go through - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 100); -} - -BOOST_AUTO_TEST_CASE(daylimit) -{ - deployWallet(200); - BOOST_REQUIRE(callContractFunction("m_dailyLimit()") == encodeArgs(u256(0))); - BOOST_REQUIRE(callContractFunction("setDailyLimit(uint256)", h256(100)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("m_dailyLimit()") == encodeArgs(u256(100))); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x12)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x13)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("addOwner(address)", h256(0x14)) == encodeArgs()); - // 4 owners, set required to 3 - BOOST_REQUIRE(callContractFunction("changeRequirement(uint256)", u256(3)) == encodeArgs()); - - // try to send tx over daylimit - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - m_sender = Address(0x12); - BOOST_REQUIRE( - callContractFunction("execute(address,uint256,bytes)", h256(0x05), 150, 0x60, 0x00) != - encodeArgs(u256(0)) - ); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - // try to send tx under daylimit by stranger - m_sender = Address(0x77); - BOOST_REQUIRE( - callContractFunction("execute(address,uint256,bytes)", h256(0x05), 90, 0x60, 0x00) == - encodeArgs(u256(0)) - ); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 0); - // now send below limit by owner - m_sender = Address(0x12); - BOOST_REQUIRE( - callContractFunction("execute(address,uint256,bytes)", h256(0x05), 90, 0x60, 0x00) == - encodeArgs(u256(0)) - ); - BOOST_CHECK_EQUAL(m_state.balance(Address(0x05)), 90); -} - -BOOST_AUTO_TEST_CASE(daylimit_constructor) -{ - deployWallet(200, {}, 1, 20); - BOOST_REQUIRE(callContractFunction("m_dailyLimit()") == encodeArgs(u256(20))); - BOOST_REQUIRE(callContractFunction("setDailyLimit(uint256)", h256(30)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("m_dailyLimit()") == encodeArgs(u256(30))); -} - -//@todo test data calls - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/Assembly.cpp b/test/libsolidity/Assembly.cpp deleted file mode 100644 index 8d316a977..000000000 --- a/test/libsolidity/Assembly.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Lefteris Karapetsas - * @date 2015 - * Unit tests for Assembly Items from evmasm/Assembly.h - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev::eth; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -namespace -{ - -eth::AssemblyItems compileContract(const string& _sourceCode) -{ - Parser parser; - ASTPointer sourceUnit; - BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared(CharStream(_sourceCode)))); - NameAndTypeResolver resolver({}); - resolver.registerDeclarations(*sourceUnit); - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); - } - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - BOOST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract)); - } - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - Compiler compiler; - compiler.compileContract(*contract, map{}); - - return compiler.getRuntimeAssemblyItems(); - } - BOOST_FAIL("No contract found in source."); - return AssemblyItems(); -} - -void checkAssemblyLocations(AssemblyItems const& _items, vector const& _locations) -{ - BOOST_CHECK_EQUAL(_items.size(), _locations.size()); - for (size_t i = 0; i < min(_items.size(), _locations.size()); ++i) - { - BOOST_CHECK_MESSAGE( - _items[i].getLocation() == _locations[i], - "Location mismatch for assembly item " + to_string(i) + ". Found: " + - to_string(_items[i].getLocation().start) + "-" + - to_string(_items[i].getLocation().end) + ", expected: " + - to_string(_locations[i].start) + "-" + - to_string(_locations[i].end)); - } -} - -} // end anonymous namespace - -BOOST_AUTO_TEST_SUITE(Assembly) - -BOOST_AUTO_TEST_CASE(location_test) -{ - char const* sourceCode = R"( - contract test { - function f() returns (uint256 a) { - return 16; - } - } - )"; - shared_ptr n = make_shared("source"); - AssemblyItems items = compileContract(sourceCode); - vector locations = - vector(17, SourceLocation(2, 75, n)) + - vector(26, SourceLocation(20, 72, n)) + - vector{SourceLocation(42, 51, n), SourceLocation(65, 67, n)} + - vector(4, SourceLocation(58, 67, n)) + - vector(3, SourceLocation(20, 72, n)); - checkAssemblyLocations(items, locations); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/CMakeLists.txt b/test/libsolidity/CMakeLists.txt deleted file mode 100644 index 3ceda13b0..000000000 --- a/test/libsolidity/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -cmake_policy(SET CMP0015 NEW) - -aux_source_directory(. SRCS) - -add_sources(${SRCS}) diff --git a/test/libsolidity/GasMeter.cpp b/test/libsolidity/GasMeter.cpp deleted file mode 100644 index 5f4426548..000000000 --- a/test/libsolidity/GasMeter.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Unit tests for the gas estimator. - */ - -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev::eth; -using namespace dev::solidity; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -class GasMeterTestFramework: public ExecutionFramework -{ -public: - GasMeterTestFramework() { } - void compile(string const& _sourceCode) - { - m_compiler.setSource(_sourceCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed"); - - AssemblyItems const* items = m_compiler.getRuntimeAssemblyItems(""); - ASTNode const& sourceUnit = m_compiler.getAST(); - BOOST_REQUIRE(items != nullptr); - m_gasCosts = GasEstimator::breakToStatementLevel( - GasEstimator::structuralEstimation(*items, vector({&sourceUnit})), - {&sourceUnit} - ); - } - - void testCreationTimeGas(string const& _sourceCode) - { - compileAndRun(_sourceCode); - auto state = make_shared(); - PathGasMeter meter(*m_compiler.getAssemblyItems()); - GasMeter::GasConsumption gas = meter.estimateMax(0, state); - u256 bytecodeSize(m_compiler.getRuntimeBytecode().size()); - gas += bytecodeSize * c_createDataGas; - BOOST_REQUIRE(!gas.isInfinite); - BOOST_CHECK(gas.value == m_gasUsed); - } - - /// Compares the gas computed by PathGasMeter for the given signature (but unknown arguments) - /// against the actual gas usage computed by the VM on the given set of argument variants. - void testRunTimeGas(string const& _sig, vector _argumentVariants) - { - u256 gasUsed = 0; - FixedHash<4> hash(dev::sha3(_sig)); - for (bytes const& arguments: _argumentVariants) - { - sendMessage(hash.asBytes() + arguments, false, 0); - gasUsed = max(gasUsed, m_gasUsed); - } - - GasMeter::GasConsumption gas = GasEstimator::functionalEstimation( - *m_compiler.getRuntimeAssemblyItems(), - _sig - ); - BOOST_REQUIRE(!gas.isInfinite); - BOOST_CHECK(gas.value == m_gasUsed); - } - -protected: - map m_gasCosts; -}; - -BOOST_FIXTURE_TEST_SUITE(GasMeterTests, GasMeterTestFramework) - -BOOST_AUTO_TEST_CASE(non_overlapping_filtered_costs) -{ - char const* sourceCode = R"( - contract test { - bytes x; - function f(uint a) returns (uint b) { - x.length = a; - for (; a < 200; ++a) { - x[a] = 9; - b = a * a; - } - return f(a - 1); - } - } - )"; - compile(sourceCode); - for (auto first = m_gasCosts.cbegin(); first != m_gasCosts.cend(); ++first) - { - auto second = first; - for (++second; second != m_gasCosts.cend(); ++second) - if (first->first->getLocation().intersects(second->first->getLocation())) - { - BOOST_CHECK_MESSAGE(false, "Source locations should not overlap!"); - SourceReferenceFormatter::printSourceLocation(cout, first->first->getLocation(), m_compiler.getScanner()); - SourceReferenceFormatter::printSourceLocation(cout, second->first->getLocation(), m_compiler.getScanner()); - } - } -} - -BOOST_AUTO_TEST_CASE(simple_contract) -{ - // Tests a simple "deploy contract" code without constructor. The actual contract is not relevant. - char const* sourceCode = R"( - contract test { - bytes32 public shaValue; - function f(uint a) { - shaValue = sha3(a); - } - } - )"; - testCreationTimeGas(sourceCode); -} - -BOOST_AUTO_TEST_CASE(store_sha3) -{ - char const* sourceCode = R"( - contract test { - bytes32 public shaValue; - function test(uint a) { - shaValue = sha3(a); - } - } - )"; - testCreationTimeGas(sourceCode); -} - -BOOST_AUTO_TEST_CASE(updating_store) -{ - char const* sourceCode = R"( - contract test { - uint data; - uint data2; - function test() { - data = 1; - data = 2; - data2 = 0; - } - } - )"; - testCreationTimeGas(sourceCode); -} - -BOOST_AUTO_TEST_CASE(branches) -{ - char const* sourceCode = R"( - contract test { - uint data; - uint data2; - function f(uint x) { - if (x > 7) - data2 = 1; - else - data = 1; - } - } - )"; - testCreationTimeGas(sourceCode); - testRunTimeGas("f(uint256)", vector{encodeArgs(2), encodeArgs(8)}); -} - -BOOST_AUTO_TEST_CASE(function_calls) -{ - char const* sourceCode = R"( - contract test { - uint data; - uint data2; - function f(uint x) { - if (x > 7) - data2 = g(x**8) + 1; - else - data = 1; - } - function g(uint x) internal returns (uint) { - return data2; - } - } - )"; - testCreationTimeGas(sourceCode); - testRunTimeGas("f(uint256)", vector{encodeArgs(2), encodeArgs(8)}); -} - -BOOST_AUTO_TEST_CASE(multiple_external_functions) -{ - char const* sourceCode = R"( - contract test { - uint data; - uint data2; - function f(uint x) { - if (x > 7) - data2 = g(x**8) + 1; - else - data = 1; - } - function g(uint x) returns (uint) { - return data2; - } - } - )"; - testCreationTimeGas(sourceCode); - testRunTimeGas("f(uint256)", vector{encodeArgs(2), encodeArgs(8)}); - testRunTimeGas("g(uint256)", vector{encodeArgs(2)}); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} diff --git a/test/libsolidity/SolidityABIJSON.cpp b/test/libsolidity/SolidityABIJSON.cpp deleted file mode 100644 index f7390dc93..000000000 --- a/test/libsolidity/SolidityABIJSON.cpp +++ /dev/null @@ -1,602 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . - */ -/** - * @author Marek Kotewicz - * @date 2014 - * Unit tests for the solidity compiler JSON Interface output. - */ - -#include "../TestHelper.h" -#include -#include -#include - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -class JSONInterfaceChecker -{ -public: - JSONInterfaceChecker(): m_compilerStack(false) {} - - void checkInterface(std::string const& _code, std::string const& _expectedInterfaceString) - { - ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing contract failed"); - std::string generatedInterfaceString = m_compilerStack.getMetadata("", DocumentationType::ABIInterface); - Json::Value generatedInterface; - m_reader.parse(generatedInterfaceString, generatedInterface); - Json::Value expectedInterface; - m_reader.parse(_expectedInterfaceString, expectedInterface); - BOOST_CHECK_MESSAGE(expectedInterface == generatedInterface, - "Expected:\n" << expectedInterface.toStyledString() << - "\n but got:\n" << generatedInterface.toStyledString()); - } - -private: - CompilerStack m_compilerStack; - Json::Reader m_reader; -}; - -BOOST_FIXTURE_TEST_SUITE(SolidityABIJSON, JSONInterfaceChecker) - -BOOST_AUTO_TEST_CASE(basic_test) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - "}\n"; - - char const* interface = R"([ - { - "name": "f", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "a", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "d", - "type": "uint256" - } - ] - } - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(empty_contract) -{ - char const* sourceCode = "contract test {\n" - "}\n"; - char const* interface = "[]"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(multiple_methods) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - " function g(uint b) returns(uint e) { return b * 8; }\n" - "}\n"; - - char const* interface = R"([ - { - "name": "f", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "a", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "d", - "type": "uint256" - } - ] - }, - { - "name": "g", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "b", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "e", - "type": "uint256" - } - ] - } - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(multiple_params) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a, uint b) returns(uint d) { return a + b; }\n" - "}\n"; - - char const* interface = R"([ - { - "name": "f", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "a", - "type": "uint256" - }, - { - "name": "b", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "d", - "type": "uint256" - } - ] - } - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(multiple_methods_order) -{ - // methods are expected to be in alpabetical order - char const* sourceCode = "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - " function c(uint b) returns(uint e) { return b * 8; }\n" - "}\n"; - - char const* interface = R"([ - { - "name": "c", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "b", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "e", - "type": "uint256" - } - ] - }, - { - "name": "f", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "a", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "d", - "type": "uint256" - } - ] - } - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(const_function) -{ - char const* sourceCode = "contract test {\n" - " function foo(uint a, uint b) returns(uint d) { return a + b; }\n" - " function boo(uint32 a) constant returns(uint b) { return a * 4; }\n" - "}\n"; - - char const* interface = R"([ - { - "name": "foo", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "a", - "type": "uint256" - }, - { - "name": "b", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "d", - "type": "uint256" - } - ] - }, - { - "name": "boo", - "constant": true, - "type": "function", - "inputs": [{ - "name": "a", - "type": "uint32" - }], - "outputs": [ - { - "name": "b", - "type": "uint256" - } - ] - } - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(exclude_fallback_function) -{ - char const* sourceCode = "contract test { function() {} }"; - - char const* interface = "[]"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(events) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - " event e1(uint b, address indexed c); \n" - " event e2(); \n" - "}\n"; - char const* interface = R"([ - { - "name": "f", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "a", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "d", - "type": "uint256" - } - ] - }, - { - "name": "e1", - "type": "event", - "anonymous": false, - "inputs": [ - { - "indexed": false, - "name": "b", - "type": "uint256" - }, - { - "indexed": true, - "name": "c", - "type": "address" - } - ] - }, - { - "name": "e2", - "type": "event", - "anonymous": false, - "inputs": [] - } - - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(events_anonymous) -{ - char const* sourceCode = "contract test {\n" - " event e() anonymous; \n" - "}\n"; - char const* interface = R"([ - { - "name": "e", - "type": "event", - "anonymous": true, - "inputs": [] - } - - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(inherited) -{ - char const* sourceCode = - " contract Base { \n" - " function baseFunction(uint p) returns (uint i) { return p; } \n" - " event baseEvent(bytes32 indexed evtArgBase); \n" - " } \n" - " contract Derived is Base { \n" - " function derivedFunction(bytes32 p) returns (bytes32 i) { return p; } \n" - " event derivedEvent(uint indexed evtArgDerived); \n" - " }"; - - char const* interface = R"([ - { - "name": "baseFunction", - "constant": false, - "type": "function", - "inputs": - [{ - "name": "p", - "type": "uint256" - }], - "outputs": - [{ - "name": "i", - "type": "uint256" - }] - }, - { - "name": "derivedFunction", - "constant": false, - "type": "function", - "inputs": - [{ - "name": "p", - "type": "bytes32" - }], - "outputs": - [{ - "name": "i", - "type": "bytes32" - }] - }, - { - "name": "derivedEvent", - "type": "event", - "anonymous": false, - "inputs": - [{ - "indexed": true, - "name": "evtArgDerived", - "type": "uint256" - }] - }, - { - "name": "baseEvent", - "type": "event", - "anonymous": false, - "inputs": - [{ - "indexed": true, - "name": "evtArgBase", - "type": "bytes32" - }] - }])"; - - - checkInterface(sourceCode, interface); -} -BOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one) -{ - char const* sourceCode = R"( - contract test { - function f(uint, uint k) returns(uint ret_k, uint ret_g){ - uint g = 8; - ret_k = k; - ret_g = g; - } - })"; - - char const* interface = R"([ - { - "name": "f", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "", - "type": "uint256" - }, - { - "name": "k", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "ret_k", - "type": "uint256" - }, - { - "name": "ret_g", - "type": "uint256" - } - ] - } - ])"; - - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(empty_name_return_parameter) -{ - char const* sourceCode = R"( - contract test { - function f(uint k) returns(uint){ - return k; - } - })"; - - char const* interface = R"([ - { - "name": "f", - "constant": false, - "type": "function", - "inputs": [ - { - "name": "k", - "type": "uint256" - } - ], - "outputs": [ - { - "name": "", - "type": "uint256" - } - ] - } - ])"; - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(constructor_abi) -{ - char const* sourceCode = R"( - contract test { - function test(uint param1, test param2, bool param3) {} - } - )"; - - char const* interface = R"([ - { - "inputs": [ - { - "name": "param1", - "type": "uint256" - }, - { - "name": "param2", - "type": "address" - }, - { - "name": "param3", - "type": "bool" - } - ], - "type": "constructor" - } - ])"; - checkInterface(sourceCode, interface); -} - - -BOOST_AUTO_TEST_CASE(return_param_in_abi) -{ - // bug #1801 - char const* sourceCode = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function test(ActionChoices param) {} - function ret() returns(ActionChoices){ - ActionChoices action = ActionChoices.GoLeft; - return action; - } - } - )"; - - char const* interface = R"( - [ - { - "constant" : false, - "inputs" : [], - "name" : "ret", - "outputs" : [ - { - "name" : "", - "type" : "uint8" - } - ], - "type" : "function" - }, - { - "inputs": [ - { - "name": "param", - "type": "uint8" - } - ], - "type": "constructor" - } - ] - )"; - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_CASE(strings_and_arrays) -{ - // bug #1801 - char const* sourceCode = R"( - contract test { - function f(string a, bytes b, uint[] c) external {} - } - )"; - - char const* interface = R"( - [ - { - "constant" : false, - "name": "f", - "inputs": [ - { "name": "a", "type": "string" }, - { "name": "b", "type": "bytes" }, - { "name": "c", "type": "uint256[]" } - ], - "outputs": [], - "type" : "function" - } - ] - )"; - checkInterface(sourceCode, interface); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} diff --git a/test/libsolidity/SolidityEndToEndTest.cpp b/test/libsolidity/SolidityEndToEndTest.cpp deleted file mode 100644 index ae2fc6dcf..000000000 --- a/test/libsolidity/SolidityEndToEndTest.cpp +++ /dev/null @@ -1,5168 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @author Gav Wood - * @date 2014 - * Unit tests for the solidity expression compiler, testing the behaviour of the code. - */ - -#include -#include -#include -#include -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -BOOST_FIXTURE_TEST_SUITE(SolidityEndToEndTest, ExecutionFramework) - -BOOST_AUTO_TEST_CASE(smoke_test) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - "}\n"; - compileAndRun(sourceCode); - testSolidityAgainstCppOnRange("f(uint256)", [](u256 const& a) -> u256 { return a * 7; }, 0, 100); -} - -BOOST_AUTO_TEST_CASE(empty_contract) -{ - char const* sourceCode = "contract test {\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("i_am_not_there()", bytes()).empty()); -} - -BOOST_AUTO_TEST_CASE(exp_operator) -{ - char const* sourceCode = R"( - contract test { - function f(uint a) returns(uint d) { return 2 ** a; } - })"; - compileAndRun(sourceCode); - testSolidityAgainstCppOnRange("f(uint256)", [](u256 const& a) -> u256 { return u256(1 << a.convert_to()); }, 0, 16); -} - -BOOST_AUTO_TEST_CASE(exp_operator_const) -{ - char const* sourceCode = R"( - contract test { - function f() returns(uint d) { return 2 ** 3; } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f()", bytes()) == toBigEndian(u256(8))); -} - -BOOST_AUTO_TEST_CASE(exp_operator_const_signed) -{ - char const* sourceCode = R"( - contract test { - function f() returns(int d) { return (-2) ** 3; } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f()", bytes()) == toBigEndian(u256(-8))); -} - -BOOST_AUTO_TEST_CASE(recursive_calls) -{ - char const* sourceCode = "contract test {\n" - " function f(uint n) returns(uint nfac) {\n" - " if (n <= 1) return 1;\n" - " else return n * f(n - 1);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - function recursive_calls_cpp = [&recursive_calls_cpp](u256 const& n) -> u256 - { - if (n <= 1) - return 1; - else - return n * recursive_calls_cpp(n - 1); - }; - - testSolidityAgainstCppOnRange("f(uint256)", recursive_calls_cpp, 0, 5); -} - -BOOST_AUTO_TEST_CASE(multiple_functions) -{ - char const* sourceCode = "contract test {\n" - " function a() returns(uint n) { return 0; }\n" - " function b() returns(uint n) { return 1; }\n" - " function c() returns(uint n) { return 2; }\n" - " function f() returns(uint n) { return 3; }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("a()", bytes()) == toBigEndian(u256(0))); - BOOST_CHECK(callContractFunction("b()", bytes()) == toBigEndian(u256(1))); - BOOST_CHECK(callContractFunction("c()", bytes()) == toBigEndian(u256(2))); - BOOST_CHECK(callContractFunction("f()", bytes()) == toBigEndian(u256(3))); - BOOST_CHECK(callContractFunction("i_am_not_there()", bytes()) == bytes()); -} - -BOOST_AUTO_TEST_CASE(named_args) -{ - char const* sourceCode = "contract test {\n" - " function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; }\n" - " function b() returns (uint r) { r = a({a: 1, b: 2, c: 3}); }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("b()", bytes()) == toBigEndian(u256(123))); -} - -BOOST_AUTO_TEST_CASE(disorder_named_args) -{ - char const* sourceCode = "contract test {\n" - " function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; }\n" - " function b() returns (uint r) { r = a({c: 3, a: 1, b: 2}); }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("b()", bytes()) == toBigEndian(u256(123))); -} - -BOOST_AUTO_TEST_CASE(while_loop) -{ - char const* sourceCode = "contract test {\n" - " function f(uint n) returns(uint nfac) {\n" - " nfac = 1;\n" - " var i = 2;\n" - " while (i <= n) nfac *= i++;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - auto while_loop_cpp = [](u256 const& n) -> u256 - { - u256 nfac = 1; - u256 i = 2; - while (i <= n) - nfac *= i++; - - return nfac; - }; - - testSolidityAgainstCppOnRange("f(uint256)", while_loop_cpp, 0, 5); -} - -BOOST_AUTO_TEST_CASE(break_outside_loop) -{ - // break and continue outside loops should be simply ignored - char const* sourceCode = "contract test {\n" - " function f(uint x) returns(uint y) {\n" - " break; continue; return 2;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - testSolidityAgainstCpp("f(uint256)", [](u256 const&) -> u256 { return 2; }, u256(0)); -} - -BOOST_AUTO_TEST_CASE(nested_loops) -{ - // tests that break and continue statements in nested loops jump to the correct place - char const* sourceCode = "contract test {\n" - " function f(uint x) returns(uint y) {\n" - " while (x > 1) {\n" - " if (x == 10) break;\n" - " while (x > 5) {\n" - " if (x == 8) break;\n" - " x--;\n" - " if (x == 6) continue;\n" - " return x;\n" - " }\n" - " x--;\n" - " if (x == 3) continue;\n" - " break;\n" - " }\n" - " return x;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - auto nested_loops_cpp = [](u256 n) -> u256 - { - while (n > 1) - { - if (n == 10) - break; - while (n > 5) - { - if (n == 8) - break; - n--; - if (n == 6) - continue; - return n; - } - n--; - if (n == 3) - continue; - break; - } - - return n; - }; - - testSolidityAgainstCppOnRange("f(uint256)", nested_loops_cpp, 0, 12); -} - -BOOST_AUTO_TEST_CASE(for_loop) -{ - char const* sourceCode = "contract test {\n" - " function f(uint n) returns(uint nfac) {\n" - " nfac = 1;\n" - " for (var i = 2; i <= n; i++)\n" - " nfac *= i;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - auto for_loop_cpp = [](u256 const& n) -> u256 - { - u256 nfac = 1; - for (auto i = 2; i <= n; i++) - nfac *= i; - return nfac; - }; - - testSolidityAgainstCppOnRange("f(uint256)", for_loop_cpp, 0, 5); -} - -BOOST_AUTO_TEST_CASE(for_loop_empty) -{ - char const* sourceCode = "contract test {\n" - " function f() returns(uint ret) {\n" - " ret = 1;\n" - " for (;;)\n" - " {\n" - " ret += 1;\n" - " if (ret >= 10) break;\n" - " }\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - auto for_loop_empty_cpp = []() -> u256 - { - u256 ret = 1; - for (;;) - { - ret += 1; - if (ret >= 10) break; - } - return ret; - }; - - testSolidityAgainstCpp("f()", for_loop_empty_cpp); -} - -BOOST_AUTO_TEST_CASE(for_loop_simple_init_expr) -{ - char const* sourceCode = "contract test {\n" - " function f(uint n) returns(uint nfac) {\n" - " nfac = 1;\n" - " uint256 i;\n" - " for (i = 2; i <= n; i++)\n" - " nfac *= i;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - auto for_loop_simple_init_expr_cpp = [](u256 const& n) -> u256 - { - u256 nfac = 1; - u256 i; - for (i = 2; i <= n; i++) - nfac *= i; - return nfac; - }; - - testSolidityAgainstCppOnRange("f(uint256)", for_loop_simple_init_expr_cpp, 0, 5); -} - -BOOST_AUTO_TEST_CASE(for_loop_break_continue) -{ - char const* sourceCode = R"( - contract test { - function f(uint n) returns (uint r) - { - uint i = 1; - uint k = 0; - for (i *= 5; k < n; i *= 7) - { - k++; - i += 4; - if (n % 3 == 0) - break; - i += 9; - if (n % 2 == 0) - continue; - i += 19; - } - return i; - } - } - )"; - compileAndRun(sourceCode); - - auto breakContinue = [](u256 const& n) -> u256 - { - u256 i = 1; - u256 k = 0; - for (i *= 5; k < n; i *= 7) - { - k++; - i += 4; - if (n % 3 == 0) - break; - i += 9; - if (n % 2 == 0) - continue; - i += 19; - } - return i; - }; - - testSolidityAgainstCppOnRange("f(uint256)", breakContinue, 0, 10); -} - -BOOST_AUTO_TEST_CASE(calling_other_functions) -{ - char const* sourceCode = "contract collatz {\n" - " function run(uint x) returns(uint y) {\n" - " while ((y = x) > 1) {\n" - " if (x % 2 == 0) x = evenStep(x);\n" - " else x = oddStep(x);\n" - " }\n" - " }\n" - " function evenStep(uint x) returns(uint y) {\n" - " return x / 2;\n" - " }\n" - " function oddStep(uint x) returns(uint y) {\n" - " return 3 * x + 1;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - auto evenStep_cpp = [](u256 const& n) -> u256 - { - return n / 2; - }; - - auto oddStep_cpp = [](u256 const& n) -> u256 - { - return 3 * n + 1; - }; - - auto collatz_cpp = [&evenStep_cpp, &oddStep_cpp](u256 n) -> u256 - { - u256 y; - while ((y = n) > 1) - { - if (n % 2 == 0) - n = evenStep_cpp(n); - else - n = oddStep_cpp(n); - } - return y; - }; - - testSolidityAgainstCpp("run(uint256)", collatz_cpp, u256(0)); - testSolidityAgainstCpp("run(uint256)", collatz_cpp, u256(1)); - testSolidityAgainstCpp("run(uint256)", collatz_cpp, u256(2)); - testSolidityAgainstCpp("run(uint256)", collatz_cpp, u256(8)); - testSolidityAgainstCpp("run(uint256)", collatz_cpp, u256(127)); -} - -BOOST_AUTO_TEST_CASE(many_local_variables) -{ - char const* sourceCode = "contract test {\n" - " function run(uint x1, uint x2, uint x3) returns(uint y) {\n" - " var a = 0x1; var b = 0x10; var c = 0x100;\n" - " y = a + b + c + x1 + x2 + x3;\n" - " y += b + x2;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto f = [](u256 const& x1, u256 const& x2, u256 const& x3) -> u256 - { - u256 a = 0x1; - u256 b = 0x10; - u256 c = 0x100; - u256 y = a + b + c + x1 + x2 + x3; - return y + b + x2; - }; - testSolidityAgainstCpp("run(uint256,uint256,uint256)", f, u256(0x1000), u256(0x10000), u256(0x100000)); -} - -BOOST_AUTO_TEST_CASE(packing_unpacking_types) -{ - char const* sourceCode = "contract test {\n" - " function run(bool a, uint32 b, uint64 c) returns(uint256 y) {\n" - " if (a) y = 1;\n" - " y = y * 0x100000000 | ~b;\n" - " y = y * 0x10000000000000000 | ~c;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("run(bool,uint32,uint64)", true, fromHex("0f0f0f0f"), fromHex("f0f0f0f0f0f0f0f0")) - == fromHex("00000000000000000000000000000000000000""01""f0f0f0f0""0f0f0f0f0f0f0f0f")); -} - -BOOST_AUTO_TEST_CASE(packing_signed_types) -{ - char const* sourceCode = "contract test {\n" - " function run() returns(int8 y) {\n" - " uint8 x = 0xfa;\n" - " return int8(x);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("run()") - == fromHex("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa")); -} - -BOOST_AUTO_TEST_CASE(multiple_return_values) -{ - char const* sourceCode = "contract test {\n" - " function run(bool x1, uint x2) returns(uint y1, bool y2, uint y3) {\n" - " y1 = x2; y2 = x1;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("run(bool,uint256)", true, 0xcd) == encodeArgs(0xcd, true, 0)); -} - -BOOST_AUTO_TEST_CASE(short_circuiting) -{ - char const* sourceCode = "contract test {\n" - " function run(uint x) returns(uint y) {\n" - " x == 0 || ((x = 8) > 0);\n" - " return x;" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - auto short_circuiting_cpp = [](u256 n) -> u256 - { - (void)(n == 0 || (n = 8) > 0); - return n; - }; - - testSolidityAgainstCppOnRange("run(uint256)", short_circuiting_cpp, 0, 2); -} - -BOOST_AUTO_TEST_CASE(high_bits_cleaning) -{ - char const* sourceCode = "contract test {\n" - " function run() returns(uint256 y) {\n" - " uint32 t = uint32(0xffffffff);\n" - " uint32 x = t + 10;\n" - " if (x >= 0xffffffff) return 0;\n" - " return x;" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto high_bits_cleaning_cpp = []() -> u256 - { - uint32_t t = uint32_t(0xffffffff); - uint32_t x = t + 10; - if (x >= 0xffffffff) - return 0; - return x; - }; - testSolidityAgainstCpp("run()", high_bits_cleaning_cpp); -} - -BOOST_AUTO_TEST_CASE(sign_extension) -{ - char const* sourceCode = "contract test {\n" - " function run() returns(uint256 y) {\n" - " int64 x = -int32(0xff);\n" - " if (x >= 0xff) return 0;\n" - " return -uint256(x);" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto sign_extension_cpp = []() -> u256 - { - int64_t x = -int32_t(0xff); - if (x >= 0xff) - return 0; - return u256(x) * -1; - }; - testSolidityAgainstCpp("run()", sign_extension_cpp); -} - -BOOST_AUTO_TEST_CASE(small_unsigned_types) -{ - char const* sourceCode = "contract test {\n" - " function run() returns(uint256 y) {\n" - " uint32 t = uint32(0xffffff);\n" - " uint32 x = t * 0xffffff;\n" - " return x / 0x100;" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto small_unsigned_types_cpp = []() -> u256 - { - uint32_t t = uint32_t(0xffffff); - uint32_t x = t * 0xffffff; - return x / 0x100; - }; - testSolidityAgainstCpp("run()", small_unsigned_types_cpp); -} - -BOOST_AUTO_TEST_CASE(small_signed_types) -{ - char const* sourceCode = "contract test {\n" - " function run() returns(int256 y) {\n" - " return -int32(10) * -int64(20);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto small_signed_types_cpp = []() -> u256 - { - return -int32_t(10) * -int64_t(20); - }; - testSolidityAgainstCpp("run()", small_signed_types_cpp); -} - -BOOST_AUTO_TEST_CASE(strings) -{ - char const* sourceCode = "contract test {\n" - " function fixed() returns(bytes32 ret) {\n" - " return \"abc\\x00\\xff__\";\n" - " }\n" - " function pipeThrough(bytes2 small, bool one) returns(bytes16 large, bool oneRet) {\n" - " oneRet = one;\n" - " large = small;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("fixed()") == encodeArgs(string("abc\0\xff__", 7))); - BOOST_CHECK(callContractFunction("pipeThrough(bytes2,bool)", string("\0\x02", 2), true) == encodeArgs(string("\0\x2", 2), true)); -} - -BOOST_AUTO_TEST_CASE(inc_dec_operators) -{ - char const* sourceCode = R"( - contract test { - uint8 x; - uint v; - function f() returns (uint r) { - uint a = 6; - r = a; - r += (a++) * 0x10; - r += (++a) * 0x100; - v = 3; - r += (v++) * 0x1000; - r += (++v) * 0x10000; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(0x53866)); -} - -BOOST_AUTO_TEST_CASE(bytes_comparison) -{ - char const* sourceCode = R"( - contract test { - function f() returns (bool) { - bytes2 a = "a"; - bytes2 x = "aa"; - bytes2 b = "b"; - return a < x && x < b; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(state_smoke_test) -{ - char const* sourceCode = "contract test {\n" - " uint256 value1;\n" - " uint256 value2;\n" - " function get(uint8 which) returns (uint256 value) {\n" - " if (which == 0) return value1;\n" - " else return value2;\n" - " }\n" - " function set(uint8 which, uint256 value) {\n" - " if (which == 0) value1 = value;\n" - " else value2 = value;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(0)); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(0)); - BOOST_CHECK(callContractFunction("set(uint8,uint256)", byte(0x00), 0x1234) == encodeArgs()); - BOOST_CHECK(callContractFunction("set(uint8,uint256)", byte(0x01), 0x8765) == encodeArgs()); - BOOST_CHECK(callContractFunction("get(uint8)", byte( 0x00)) == encodeArgs(0x1234)); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(0x8765)); - BOOST_CHECK(callContractFunction("set(uint8,uint256)", byte(0x00), 0x3) == encodeArgs()); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(0x3)); -} - -BOOST_AUTO_TEST_CASE(compound_assign) -{ - char const* sourceCode = "contract test {\n" - " uint value1;\n" - " uint value2;\n" - " function f(uint x, uint y) returns (uint w) {\n" - " uint value3 = y;" - " value1 += x;\n" - " value3 *= x;" - " value2 *= value3 + value1;\n" - " return value2 += 7;" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - u256 value1; - u256 value2; - auto f = [&](u256 const& _x, u256 const& _y) -> u256 - { - u256 value3 = _y; - value1 += _x; - value3 *= _x; - value2 *= value3 + value1; - return value2 += 7; - }; - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(0), u256(6)); - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(1), u256(3)); - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(2), u256(25)); - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(3), u256(69)); - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(4), u256(84)); - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(5), u256(2)); - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(6), u256(51)); - testSolidityAgainstCpp("f(uint256,uint256)", f, u256(7), u256(48)); -} - -BOOST_AUTO_TEST_CASE(simple_mapping) -{ - char const* sourceCode = "contract test {\n" - " mapping(uint8 => uint8) table;\n" - " function get(uint8 k) returns (uint8 v) {\n" - " return table[k];\n" - " }\n" - " function set(uint8 k, uint8 v) {\n" - " table[k] = v;\n" - " }\n" - "}"; - compileAndRun(sourceCode); - - BOOST_CHECK(callContractFunction("get(uint8)", byte(0)) == encodeArgs(byte(0x00))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0x00))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00))); - callContractFunction("set(uint8,uint8)", byte(0x01), byte(0xa1)); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(byte(0x00))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0xa1))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00))); - callContractFunction("set(uint8,uint8)", byte(0x00), byte(0xef)); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(byte(0xef))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0xa1))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00))); - callContractFunction("set(uint8,uint8)", byte(0x01), byte(0x05)); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x00)) == encodeArgs(byte(0xef))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0x01)) == encodeArgs(byte(0x05))); - BOOST_CHECK(callContractFunction("get(uint8)", byte(0xa7)) == encodeArgs(byte(0x00))); -} - -BOOST_AUTO_TEST_CASE(mapping_state) -{ - char const* sourceCode = "contract Ballot {\n" - " mapping(address => bool) canVote;\n" - " mapping(address => uint) voteCount;\n" - " mapping(address => bool) voted;\n" - " function getVoteCount(address addr) returns (uint retVoteCount) {\n" - " return voteCount[addr];\n" - " }\n" - " function grantVoteRight(address addr) {\n" - " canVote[addr] = true;\n" - " }\n" - " function vote(address voter, address vote) returns (bool success) {\n" - " if (!canVote[voter] || voted[voter]) return false;\n" - " voted[voter] = true;\n" - " voteCount[vote] = voteCount[vote] + 1;\n" - " return true;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - class Ballot - { - public: - u256 getVoteCount(u160 _address) { return m_voteCount[_address]; } - void grantVoteRight(u160 _address) { m_canVote[_address] = true; } - bool vote(u160 _voter, u160 _vote) - { - if (!m_canVote[_voter] || m_voted[_voter]) return false; - m_voted[_voter] = true; - m_voteCount[_vote]++; - return true; - } - private: - map m_canVote; - map m_voteCount; - map m_voted; - } ballot; - - auto getVoteCount = bind(&Ballot::getVoteCount, &ballot, _1); - auto grantVoteRight = bind(&Ballot::grantVoteRight, &ballot, _1); - auto vote = bind(&Ballot::vote, &ballot, _1, _2); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(0)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(2)); - // voting without vote right should be rejected - testSolidityAgainstCpp("vote(address,address)", vote, u160(0), u160(2)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(0)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(2)); - // grant vote rights - testSolidityAgainstCpp("grantVoteRight(address)", grantVoteRight, u160(0)); - testSolidityAgainstCpp("grantVoteRight(address)", grantVoteRight, u160(1)); - // vote, should increase 2's vote count - testSolidityAgainstCpp("vote(address,address)", vote, u160(0), u160(2)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(0)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(2)); - // vote again, should be rejected - testSolidityAgainstCpp("vote(address,address)", vote, u160(0), u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(0)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(2)); - // vote without right to vote - testSolidityAgainstCpp("vote(address,address)", vote, u160(2), u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(0)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(2)); - // grant vote right and now vote again - testSolidityAgainstCpp("grantVoteRight(address)", grantVoteRight, u160(2)); - testSolidityAgainstCpp("vote(address,address)", vote, u160(2), u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(0)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(1)); - testSolidityAgainstCpp("getVoteCount(address)", getVoteCount, u160(2)); -} - -BOOST_AUTO_TEST_CASE(mapping_state_inc_dec) -{ - char const* sourceCode = "contract test {\n" - " uint value;\n" - " mapping(uint => uint) table;\n" - " function f(uint x) returns (uint y) {\n" - " value = x;\n" - " if (x > 0) table[++value] = 8;\n" - " if (x > 1) value--;\n" - " if (x > 2) table[value]++;\n" - " return --table[value++];\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - u256 value = 0; - map table; - auto f = [&](u256 const& _x) -> u256 - { - value = _x; - if (_x > 0) - table[++value] = 8; - if (_x > 1) - value --; - if (_x > 2) - table[value]++; - return --table[value++]; - }; - testSolidityAgainstCppOnRange("f(uint256)", f, 0, 5); -} - -BOOST_AUTO_TEST_CASE(multi_level_mapping) -{ - char const* sourceCode = "contract test {\n" - " mapping(uint => mapping(uint => uint)) table;\n" - " function f(uint x, uint y, uint z) returns (uint w) {\n" - " if (z == 0) return table[x][y];\n" - " else return table[x][y] = z;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - - map> table; - auto f = [&](u256 const& _x, u256 const& _y, u256 const& _z) -> u256 - { - if (_z == 0) return table[_x][_y]; - else return table[_x][_y] = _z; - }; - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(0)); - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(0)); - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(9)); - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(0)); - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(0)); - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(7)); - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(0)); - testSolidityAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(0)); -} - -BOOST_AUTO_TEST_CASE(structs) -{ - char const* sourceCode = "contract test {\n" - " struct s1 {\n" - " uint8 x;\n" - " bool y;\n" - " }\n" - " struct s2 {\n" - " uint32 z;\n" - " s1 s1data;\n" - " mapping(uint8 => s2) recursive;\n" - " }\n" - " s2 data;\n" - " function check() returns (bool ok) {\n" - " return data.z == 1 && data.s1data.x == 2 && \n" - " data.s1data.y == true && \n" - " data.recursive[3].recursive[4].z == 5 && \n" - " data.recursive[4].recursive[3].z == 6 && \n" - " data.recursive[0].s1data.y == false && \n" - " data.recursive[4].z == 9;\n" - " }\n" - " function set() {\n" - " data.z = 1;\n" - " data.s1data.x = 2;\n" - " data.s1data.y = true;\n" - " data.recursive[3].recursive[4].z = 5;\n" - " data.recursive[4].recursive[3].z = 6;\n" - " data.recursive[0].s1data.y = false;\n" - " data.recursive[4].z = 9;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("check()") == encodeArgs(false)); - BOOST_CHECK(callContractFunction("set()") == bytes()); - BOOST_CHECK(callContractFunction("check()") == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(struct_reference) -{ - char const* sourceCode = "contract test {\n" - " struct s2 {\n" - " uint32 z;\n" - " mapping(uint8 => s2) recursive;\n" - " }\n" - " s2 data;\n" - " function check() returns (bool ok) {\n" - " return data.z == 2 && \n" - " data.recursive[0].z == 3 && \n" - " data.recursive[0].recursive[1].z == 0 && \n" - " data.recursive[0].recursive[0].z == 1;\n" - " }\n" - " function set() {\n" - " data.z = 2;\n" - " var map = data.recursive;\n" - " s2 inner = map[0];\n" - " inner.z = 3;\n" - " inner.recursive[0].z = inner.recursive[1].z + 1;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("check()") == encodeArgs(false)); - BOOST_CHECK(callContractFunction("set()") == bytes()); - BOOST_CHECK(callContractFunction("check()") == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(deleteStruct) -{ - char const* sourceCode = R"( - contract test { - struct topStruct { - nestedStruct nstr; - emptyStruct empty; - uint topValue; - mapping (uint => uint) topMapping; - } - uint toDelete; - topStruct str; - struct nestedStruct { - uint nestedValue; - mapping (uint => bool) nestedMapping; - } - struct emptyStruct{ - } - function test(){ - toDelete = 5; - str.topValue = 1; - str.topMapping[0] = 1; - str.topMapping[1] = 2; - - str.nstr.nestedValue = 2; - str.nstr.nestedMapping[0] = true; - str.nstr.nestedMapping[1] = false; - delete str; - delete toDelete; - } - function getToDelete() returns (uint res){ - res = toDelete; - } - function getTopValue() returns(uint topValue){ - topValue = str.topValue; - } - function getNestedValue() returns(uint nestedValue){ - nestedValue = str.nstr.nestedValue; - } - function getTopMapping(uint index) returns(uint ret) { - ret = str.topMapping[index]; - } - function getNestedMapping(uint index) returns(bool ret) { - return str.nstr.nestedMapping[index]; - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getToDelete()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("getTopValue()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("getNestedValue()") == encodeArgs(0)); - // mapping values should be the same - BOOST_CHECK(callContractFunction("getTopMapping(uint256)", 0) == encodeArgs(1)); - BOOST_CHECK(callContractFunction("getTopMapping(uint256)", 1) == encodeArgs(2)); - BOOST_CHECK(callContractFunction("getNestedMapping(uint256)", 0) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("getNestedMapping(uint256)", 1) == encodeArgs(false)); -} - -BOOST_AUTO_TEST_CASE(deleteLocal) -{ - char const* sourceCode = R"( - contract test { - function delLocal() returns (uint res){ - uint v = 5; - delete v; - res = v; - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("delLocal()") == encodeArgs(0)); -} - -BOOST_AUTO_TEST_CASE(deleteLocals) -{ - char const* sourceCode = R"( - contract test { - function delLocal() returns (uint res1, uint res2){ - uint v = 5; - uint w = 6; - uint x = 7; - delete v; - res1 = w; - res2 = x; - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("delLocal()") == encodeArgs(6, 7)); -} - -BOOST_AUTO_TEST_CASE(constructor) -{ - char const* sourceCode = "contract test {\n" - " mapping(uint => uint) data;\n" - " function test() {\n" - " data[7] = 8;\n" - " }\n" - " function get(uint key) returns (uint value) {\n" - " return data[key];" - " }\n" - "}\n"; - compileAndRun(sourceCode); - map data; - data[7] = 8; - auto get = [&](u256 const& _x) -> u256 - { - return data[_x]; - }; - testSolidityAgainstCpp("get(uint256)", get, u256(6)); - testSolidityAgainstCpp("get(uint256)", get, u256(7)); -} - -BOOST_AUTO_TEST_CASE(simple_accessor) -{ - char const* sourceCode = "contract test {\n" - " uint256 public data;\n" - " function test() {\n" - " data = 8;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("data()") == encodeArgs(8)); -} - -BOOST_AUTO_TEST_CASE(array_accessor) -{ - char const* sourceCode = R"( - contract test { - uint[8] public data; - uint[] public dynamicData; - uint24[] public smallTypeData; - struct st { uint a; uint[] finalArray; } - mapping(uint256 => mapping(uint256 => st[5])) public multiple_map; - - function test() { - data[0] = 8; - dynamicData.length = 3; - dynamicData[2] = 8; - smallTypeData.length = 128; - smallTypeData[1] = 22; - smallTypeData[127] = 2; - multiple_map[2][1][2].a = 3; - multiple_map[2][1][2].finalArray.length = 4; - multiple_map[2][1][2].finalArray[3] = 5; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("data(uint256)", 0) == encodeArgs(8)); - BOOST_CHECK(callContractFunction("data(uint256)", 8) == encodeArgs()); - BOOST_CHECK(callContractFunction("dynamicData(uint256)", 2) == encodeArgs(8)); - BOOST_CHECK(callContractFunction("dynamicData(uint256)", 8) == encodeArgs()); - BOOST_CHECK(callContractFunction("smallTypeData(uint256)", 1) == encodeArgs(22)); - BOOST_CHECK(callContractFunction("smallTypeData(uint256)", 127) == encodeArgs(2)); - BOOST_CHECK(callContractFunction("smallTypeData(uint256)", 128) == encodeArgs()); - BOOST_CHECK(callContractFunction("multiple_map(uint256,uint256,uint256)", 2, 1, 2) == encodeArgs(3)); -} - -BOOST_AUTO_TEST_CASE(accessors_mapping_for_array) -{ - char const* sourceCode = R"( - contract test { - mapping(uint => uint[8]) public data; - mapping(uint => uint[]) public dynamicData; - function test() { - data[2][2] = 8; - dynamicData[2].length = 3; - dynamicData[2][2] = 8; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("data(uint256,uint256)", 2, 2) == encodeArgs(8)); - BOOST_CHECK(callContractFunction("data(uint256, 256)", 2, 8) == encodeArgs()); - BOOST_CHECK(callContractFunction("dynamicData(uint256,uint256)", 2, 2) == encodeArgs(8)); - BOOST_CHECK(callContractFunction("dynamicData(uint256,uint256)", 2, 8) == encodeArgs()); -} - -BOOST_AUTO_TEST_CASE(multiple_elementary_accessors) -{ - char const* sourceCode = "contract test {\n" - " uint256 public data;\n" - " bytes6 public name;\n" - " bytes32 public a_hash;\n" - " address public an_address;\n" - " function test() {\n" - " data = 8;\n" - " name = \"Celina\";\n" - " a_hash = sha3(123);\n" - " an_address = address(0x1337);\n" - " super_secret_data = 42;\n" - " }\n" - " uint256 super_secret_data;" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("data()") == encodeArgs(8)); - BOOST_CHECK(callContractFunction("name()") == encodeArgs("Celina")); - BOOST_CHECK(callContractFunction("a_hash()") == encodeArgs(dev::sha3(bytes(1, 0x7b)))); - BOOST_CHECK(callContractFunction("an_address()") == encodeArgs(toBigEndian(u160(0x1337)))); - BOOST_CHECK(callContractFunction("super_secret_data()") == bytes()); -} - -BOOST_AUTO_TEST_CASE(complex_accessors) -{ - char const* sourceCode = R"( - contract test { - mapping(uint256 => bytes4) public to_string_map; - mapping(uint256 => bool) public to_bool_map; - mapping(uint256 => uint256) public to_uint_map; - mapping(uint256 => mapping(uint256 => uint256)) public to_multiple_map; - function test() { - to_string_map[42] = "24"; - to_bool_map[42] = false; - to_uint_map[42] = 12; - to_multiple_map[42][23] = 31; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("to_string_map(uint256)", 42) == encodeArgs("24")); - BOOST_CHECK(callContractFunction("to_bool_map(uint256)", 42) == encodeArgs(false)); - BOOST_CHECK(callContractFunction("to_uint_map(uint256)", 42) == encodeArgs(12)); - BOOST_CHECK(callContractFunction("to_multiple_map(uint256,uint256)", 42, 23) == encodeArgs(31)); -} - -BOOST_AUTO_TEST_CASE(struct_accessor) -{ - char const* sourceCode = R"( - contract test { - struct Data { uint a; uint8 b; mapping(uint => uint) c; bool d; } - mapping(uint => Data) public data; - function test() { - data[7].a = 1; - data[7].b = 2; - data[7].c[0] = 3; - data[7].d = true; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("data(uint256)", 7) == encodeArgs(1, 2, true)); -} - -BOOST_AUTO_TEST_CASE(balance) -{ - char const* sourceCode = "contract test {\n" - " function getBalance() returns (uint256 balance) {\n" - " return address(this).balance;\n" - " }\n" - "}\n"; - compileAndRun(sourceCode, 23); - BOOST_CHECK(callContractFunction("getBalance()") == encodeArgs(23)); -} - -BOOST_AUTO_TEST_CASE(blockchain) -{ - char const* sourceCode = "contract test {\n" - " function someInfo() returns (uint256 value, address coinbase, uint256 blockNumber) {\n" - " value = msg.value;\n" - " coinbase = block.coinbase;\n" - " blockNumber = block.number;\n" - " }\n" - "}\n"; - m_envInfo.setBeneficiary(Address(0x123)); - m_envInfo.setNumber(7); - compileAndRun(sourceCode, 27); - BOOST_CHECK(callContractFunctionWithValue("someInfo()", 28) == encodeArgs(28, 0x123, 7)); -} - -BOOST_AUTO_TEST_CASE(msg_sig) -{ - char const* sourceCode = R"( - contract test { - function foo(uint256 a) returns (bytes4 value) { - return msg.sig; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunctionWithValue("foo(uint256)", 13) == encodeArgs(asString(FixedHash<4>(dev::sha3("foo(uint256)")).asBytes()))); -} - -BOOST_AUTO_TEST_CASE(msg_sig_after_internal_call_is_same) -{ - char const* sourceCode = R"( - contract test { - function boo() returns (bytes4 value) { - return msg.sig; - } - function foo(uint256 a) returns (bytes4 value) { - return boo(); - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunctionWithValue("foo(uint256)", 13) == encodeArgs(asString(FixedHash<4>(dev::sha3("foo(uint256)")).asBytes()))); -} - -BOOST_AUTO_TEST_CASE(now) -{ - char const* sourceCode = "contract test {\n" - " function someInfo() returns (bool equal, uint val) {\n" - " equal = block.timestamp == now;\n" - " val = now;\n" - " }\n" - "}\n"; - m_envInfo.setTimestamp(9); - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("someInfo()") == encodeArgs(true, 9)); -} - -BOOST_AUTO_TEST_CASE(type_conversions_cleanup) -{ - // 22-byte integer converted to a contract (i.e. address, 20 bytes), converted to a 32 byte - // integer should drop the first two bytes - char const* sourceCode = R"( - contract Test { - function test() returns (uint ret) { return uint(address(Test(address(0x11223344556677889900112233445566778899001122)))); } - })"; - compileAndRun(sourceCode); - BOOST_REQUIRE(callContractFunction("test()") == bytes({0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22, - 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22})); -} -// fixed bytes to fixed bytes conversion tests -BOOST_AUTO_TEST_CASE(convert_fixed_bytes_to_fixed_bytes_smaller_size) -{ - char const* sourceCode = R"( - contract Test { - function bytesToBytes(bytes4 input) returns (bytes2 ret) { - return bytes2(input); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("bytesToBytes(bytes4)", "abcd") == encodeArgs("ab")); -} - -BOOST_AUTO_TEST_CASE(convert_fixed_bytes_to_fixed_bytes_greater_size) -{ - char const* sourceCode = R"( - contract Test { - function bytesToBytes(bytes2 input) returns (bytes4 ret) { - return bytes4(input); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("bytesToBytes(bytes2)", "ab") == encodeArgs("ab")); -} - -BOOST_AUTO_TEST_CASE(convert_fixed_bytes_to_fixed_bytes_same_size) -{ - char const* sourceCode = R"( - contract Test { - function bytesToBytes(bytes4 input) returns (bytes4 ret) { - return bytes4(input); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("bytesToBytes(bytes4)", "abcd") == encodeArgs("abcd")); -} -// fixed bytes to uint conversion tests -BOOST_AUTO_TEST_CASE(convert_fixed_bytes_to_uint_same_size) -{ - char const* sourceCode = R"( - contract Test { - function bytesToUint(bytes32 s) returns (uint256 h) { - return uint(s); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("bytesToUint(bytes32)", string("abc2")) == - encodeArgs(u256("0x6162633200000000000000000000000000000000000000000000000000000000"))); -} - -BOOST_AUTO_TEST_CASE(convert_fixed_bytes_to_uint_same_min_size) -{ - char const* sourceCode = R"( - contract Test { - function bytesToUint(bytes1 s) returns (uint8 h) { - return uint8(s); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("bytesToUint(bytes1)", string("a")) == - encodeArgs(u256("0x61"))); -} - -BOOST_AUTO_TEST_CASE(convert_fixed_bytes_to_uint_smaller_size) -{ - char const* sourceCode = R"( - contract Test { - function bytesToUint(bytes4 s) returns (uint16 h) { - return uint16(s); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("bytesToUint(bytes4)", string("abcd")) == - encodeArgs(u256("0x6364"))); -} - -BOOST_AUTO_TEST_CASE(convert_fixed_bytes_to_uint_greater_size) -{ - char const* sourceCode = R"( - contract Test { - function bytesToUint(bytes4 s) returns (uint64 h) { - return uint64(s); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("bytesToUint(bytes4)", string("abcd")) == - encodeArgs(u256("0x61626364"))); -} -// uint fixed bytes conversion tests -BOOST_AUTO_TEST_CASE(convert_uint_to_fixed_bytes_same_size) -{ - char const* sourceCode = R"( - contract Test { - function uintToBytes(uint256 h) returns (bytes32 s) { - return bytes32(h); - } - })"; - compileAndRun(sourceCode); - u256 a("0x6162630000000000000000000000000000000000000000000000000000000000"); - BOOST_CHECK(callContractFunction("uintToBytes(uint256)", a) == encodeArgs(a)); -} - -BOOST_AUTO_TEST_CASE(convert_uint_to_fixed_bytes_same_min_size) -{ - char const* sourceCode = R"( - contract Test { - function UintToBytes(uint8 h) returns (bytes1 s) { - return bytes1(h); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("UintToBytes(uint8)", u256("0x61")) == - encodeArgs(string("a"))); -} - -BOOST_AUTO_TEST_CASE(convert_uint_to_fixed_bytes_smaller_size) -{ - char const* sourceCode = R"( - contract Test { - function uintToBytes(uint32 h) returns (bytes2 s) { - return bytes2(h); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("uintToBytes(uint32)", - u160("0x61626364")) == encodeArgs(string("cd"))); -} - -BOOST_AUTO_TEST_CASE(convert_uint_to_fixed_bytes_greater_size) -{ - char const* sourceCode = R"( - contract Test { - function UintToBytes(uint16 h) returns (bytes8 s) { - return bytes8(h); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("UintToBytes(uint16)", u256("0x6162")) == - encodeArgs(string("\0\0\0\0\0\0ab", 8))); -} - -BOOST_AUTO_TEST_CASE(send_ether) -{ - char const* sourceCode = "contract test {\n" - " function a(address addr, uint amount) returns (uint ret) {\n" - " addr.send(amount);\n" - " return address(this).balance;\n" - " }\n" - "}\n"; - u256 amount(130); - compileAndRun(sourceCode, amount + 1); - u160 address(23); - BOOST_CHECK(callContractFunction("a(address,uint256)", address, amount) == encodeArgs(1)); - BOOST_CHECK_EQUAL(m_state.balance(address), amount); -} - -BOOST_AUTO_TEST_CASE(log0) -{ - char const* sourceCode = "contract test {\n" - " function a() {\n" - " log0(1);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - callContractFunction("a()"); - BOOST_CHECK_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(1))); - BOOST_CHECK_EQUAL(m_logs[0].topics.size(), 0); -} - -BOOST_AUTO_TEST_CASE(log1) -{ - char const* sourceCode = "contract test {\n" - " function a() {\n" - " log1(1, 2);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - callContractFunction("a()"); - BOOST_CHECK_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(1))); - BOOST_CHECK_EQUAL(m_logs[0].topics.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], h256(u256(2))); -} - -BOOST_AUTO_TEST_CASE(log2) -{ - char const* sourceCode = "contract test {\n" - " function a() {\n" - " log2(1, 2, 3);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - callContractFunction("a()"); - BOOST_CHECK_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(1))); - BOOST_CHECK_EQUAL(m_logs[0].topics.size(), 2); - for (unsigned i = 0; i < 2; ++i) - BOOST_CHECK_EQUAL(m_logs[0].topics[i], h256(u256(i + 2))); -} - -BOOST_AUTO_TEST_CASE(log3) -{ - char const* sourceCode = "contract test {\n" - " function a() {\n" - " log3(1, 2, 3, 4);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - callContractFunction("a()"); - BOOST_CHECK_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(1))); - BOOST_CHECK_EQUAL(m_logs[0].topics.size(), 3); - for (unsigned i = 0; i < 3; ++i) - BOOST_CHECK_EQUAL(m_logs[0].topics[i], h256(u256(i + 2))); -} - -BOOST_AUTO_TEST_CASE(log4) -{ - char const* sourceCode = "contract test {\n" - " function a() {\n" - " log4(1, 2, 3, 4, 5);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - callContractFunction("a()"); - BOOST_CHECK_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(1))); - BOOST_CHECK_EQUAL(m_logs[0].topics.size(), 4); - for (unsigned i = 0; i < 4; ++i) - BOOST_CHECK_EQUAL(m_logs[0].topics[i], h256(u256(i + 2))); -} - -BOOST_AUTO_TEST_CASE(log_in_constructor) -{ - char const* sourceCode = "contract test {\n" - " function test() {\n" - " log1(1, 2);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - BOOST_CHECK_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(1))); - BOOST_CHECK_EQUAL(m_logs[0].topics.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], h256(u256(2))); -} - -BOOST_AUTO_TEST_CASE(suicide) -{ - char const* sourceCode = "contract test {\n" - " function a(address receiver) returns (uint ret) {\n" - " suicide(receiver);\n" - " return 10;\n" - " }\n" - "}\n"; - u256 amount(130); - compileAndRun(sourceCode, amount); - u160 address(23); - BOOST_CHECK(callContractFunction("a(address)", address) == bytes()); - BOOST_CHECK(!m_state.addressHasCode(m_contractAddress)); - BOOST_CHECK_EQUAL(m_state.balance(address), amount); -} - -BOOST_AUTO_TEST_CASE(sha3) -{ - char const* sourceCode = "contract test {\n" - " function a(bytes32 input) returns (bytes32 sha3hash) {\n" - " return sha3(input);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto f = [&](u256 const& _x) -> u256 - { - return dev::sha3(toBigEndian(_x)); - }; - testSolidityAgainstCpp("a(bytes32)", f, u256(4)); - testSolidityAgainstCpp("a(bytes32)", f, u256(5)); - testSolidityAgainstCpp("a(bytes32)", f, u256(-1)); -} - -BOOST_AUTO_TEST_CASE(sha256) -{ - char const* sourceCode = "contract test {\n" - " function a(bytes32 input) returns (bytes32 sha256hash) {\n" - " return sha256(input);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto f = [&](u256 const& _input) -> u256 - { - return dev::sha256(dev::ref(toBigEndian(_input))); - }; - testSolidityAgainstCpp("a(bytes32)", f, u256(4)); - testSolidityAgainstCpp("a(bytes32)", f, u256(5)); - testSolidityAgainstCpp("a(bytes32)", f, u256(-1)); -} - -BOOST_AUTO_TEST_CASE(ripemd) -{ - char const* sourceCode = "contract test {\n" - " function a(bytes32 input) returns (bytes32 sha256hash) {\n" - " return ripemd160(input);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - auto f = [&](u256 const& _input) -> u256 - { - return h256(dev::ripemd160(h256(_input).ref()), h256::AlignLeft); // This should be aligned right. i guess it's fixed elsewhere? - }; - testSolidityAgainstCpp("a(bytes32)", f, u256(4)); - testSolidityAgainstCpp("a(bytes32)", f, u256(5)); - testSolidityAgainstCpp("a(bytes32)", f, u256(-1)); -} - -BOOST_AUTO_TEST_CASE(ecrecover) -{ - char const* sourceCode = "contract test {\n" - " function a(bytes32 h, uint8 v, bytes32 r, bytes32 s) returns (address addr) {\n" - " return ecrecover(h, v, r, s);\n" - " }\n" - "}\n"; - compileAndRun(sourceCode); - u256 h("0x18c547e4f7b0f325ad1e56f57e26c745b09a3e503d86e00e5255ff7f715d3d1c"); - byte v = 28; - u256 r("0x73b1693892219d736caba55bdb67216e485557ea6b6af75f37096c9aa6a5a75f"); - u256 s("0xeeb940b1d03b21e36b0e47e79769f095fe2ab855bd91e3a38756b7d75a9c4549"); - u160 addr("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"); - BOOST_CHECK(callContractFunction("a(bytes32,uint8,bytes32,bytes32)", h, v, r, s) == encodeArgs(addr)); -} - -BOOST_AUTO_TEST_CASE(inter_contract_calls) -{ - char const* sourceCode = R"( - contract Helper { - function multiply(uint a, uint b) returns (uint c) { - return a * b; - } - } - contract Main { - Helper h; - function callHelper(uint a, uint b) returns (uint c) { - return h.multiply(a, b); - } - function getHelper() returns (address haddress) { - return address(h); - } - function setHelper(address haddress) { - h = Helper(haddress); - } - })"; - compileAndRun(sourceCode, 0, "Helper"); - u160 const c_helperAddress = m_contractAddress; - compileAndRun(sourceCode, 0, "Main"); - BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes()); - BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress)); - u256 a(3456789); - u256 b("0x282837623374623234aa74"); - BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b)); -} - -BOOST_AUTO_TEST_CASE(inter_contract_calls_with_complex_parameters) -{ - char const* sourceCode = R"( - contract Helper { - function sel(uint a, bool select, uint b) returns (uint c) { - if (select) return a; else return b; - } - } - contract Main { - Helper h; - function callHelper(uint a, bool select, uint b) returns (uint c) { - return h.sel(a, select, b) * 3; - } - function getHelper() returns (address haddress) { - return address(h); - } - function setHelper(address haddress) { - h = Helper(haddress); - } - })"; - compileAndRun(sourceCode, 0, "Helper"); - u160 const c_helperAddress = m_contractAddress; - compileAndRun(sourceCode, 0, "Main"); - BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes()); - BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress)); - u256 a(3456789); - u256 b("0x282837623374623234aa74"); - BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, true, b) == encodeArgs(a * 3)); - BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, false, b) == encodeArgs(b * 3)); -} - -BOOST_AUTO_TEST_CASE(inter_contract_calls_accessing_this) -{ - char const* sourceCode = R"( - contract Helper { - function getAddress() returns (address addr) { - return address(this); - } - } - contract Main { - Helper h; - function callHelper() returns (address addr) { - return h.getAddress(); - } - function getHelper() returns (address addr) { - return address(h); - } - function setHelper(address addr) { - h = Helper(addr); - } - })"; - compileAndRun(sourceCode, 0, "Helper"); - u160 const c_helperAddress = m_contractAddress; - compileAndRun(sourceCode, 0, "Main"); - BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes()); - BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress)); - BOOST_REQUIRE(callContractFunction("callHelper()") == encodeArgs(c_helperAddress)); -} - -BOOST_AUTO_TEST_CASE(calls_to_this) -{ - char const* sourceCode = R"( - contract Helper { - function invoke(uint a, uint b) returns (uint c) { - return this.multiply(a, b, 10); - } - function multiply(uint a, uint b, uint8 c) returns (uint ret) { - return a * b + c; - } - } - contract Main { - Helper h; - function callHelper(uint a, uint b) returns (uint ret) { - return h.invoke(a, b); - } - function getHelper() returns (address addr) { - return address(h); - } - function setHelper(address addr) { - h = Helper(addr); - } - })"; - compileAndRun(sourceCode, 0, "Helper"); - u160 const c_helperAddress = m_contractAddress; - compileAndRun(sourceCode, 0, "Main"); - BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes()); - BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress)); - u256 a(3456789); - u256 b("0x282837623374623234aa74"); - BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b + 10)); -} - -BOOST_AUTO_TEST_CASE(inter_contract_calls_with_local_vars) -{ - // note that a reference to another contract's function occupies two stack slots, - // so this tests correct stack slot allocation - char const* sourceCode = R"( - contract Helper { - function multiply(uint a, uint b) returns (uint c) { - return a * b; - } - } - contract Main { - Helper h; - function callHelper(uint a, uint b) returns (uint c) { - var fu = h.multiply; - var y = 9; - var ret = fu(a, b); - return ret + y; - } - function getHelper() returns (address haddress) { - return address(h); - } - function setHelper(address haddress) { - h = Helper(haddress); - } - })"; - compileAndRun(sourceCode, 0, "Helper"); - u160 const c_helperAddress = m_contractAddress; - compileAndRun(sourceCode, 0, "Main"); - BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes()); - BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress)); - u256 a(3456789); - u256 b("0x282837623374623234aa74"); - BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b + 9)); -} - -BOOST_AUTO_TEST_CASE(fixed_bytes_in_calls) -{ - char const* sourceCode = R"( - contract Helper { - function invoke(bytes3 x, bool stop) returns (bytes4 ret) { - return x; - } - } - contract Main { - Helper h; - function callHelper(bytes2 x, bool stop) returns (bytes5 ret) { - return h.invoke(x, stop); - } - function getHelper() returns (address addr) { - return address(h); - } - function setHelper(address addr) { - h = Helper(addr); - } - })"; - compileAndRun(sourceCode, 0, "Helper"); - u160 const c_helperAddress = m_contractAddress; - compileAndRun(sourceCode, 0, "Main"); - BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes()); - BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress)); - BOOST_CHECK(callContractFunction("callHelper(bytes2,bool)", string("\0a", 2), true) == encodeArgs(string("\0a\0\0\0", 5))); -} - -BOOST_AUTO_TEST_CASE(constructor_arguments_internal) -{ - char const* sourceCode = R"( - contract Helper { - bytes3 name; - bool flag; - - function Helper(bytes3 x, bool f) { - name = x; - flag = f; - } - function getName() returns (bytes3 ret) { return name; } - function getFlag() returns (bool ret) { return flag; } - } - contract Main { - Helper h; - function Main() { - h = new Helper("abc", true); - } - function getFlag() returns (bool ret) { return h.getFlag(); } - function getName() returns (bytes3 ret) { return h.getName(); } - })"; - compileAndRun(sourceCode, 0, "Main"); - BOOST_CHECK(callContractFunction("getFlag()") == encodeArgs(true)); - BOOST_CHECK(callContractFunction("getName()") == encodeArgs("abc")); -} - -BOOST_AUTO_TEST_CASE(constructor_arguments_external) -{ - char const* sourceCode = R"( - contract Main { - bytes3 name; - bool flag; - - function Main(bytes3 x, bool f) { - name = x; - flag = f; - } - function getName() returns (bytes3 ret) { return name; } - function getFlag() returns (bool ret) { return flag; } - } - )"; - compileAndRun(sourceCode, 0, "Main", encodeArgs("abc", true)); - BOOST_CHECK(callContractFunction("getFlag()") == encodeArgs(true)); - BOOST_CHECK(callContractFunction("getName()") == encodeArgs("abc")); -} - -BOOST_AUTO_TEST_CASE(functions_called_by_constructor) -{ - char const* sourceCode = R"( - contract Test { - bytes3 name; - bool flag; - function Test() { - setName("abc"); - } - function getName() returns (bytes3 ret) { return name; } - function setName(bytes3 _name) private { name = _name; } - })"; - compileAndRun(sourceCode); - BOOST_REQUIRE(callContractFunction("getName()") == encodeArgs("abc")); -} - -BOOST_AUTO_TEST_CASE(contracts_as_addresses) -{ - char const* sourceCode = R"( - contract helper { - } - contract test { - helper h; - function test() { h = new helper(); h.send(5); } - function getBalance() returns (uint256 myBalance, uint256 helperBalance) { - myBalance = this.balance; - helperBalance = h.balance; - } - } - )"; - compileAndRun(sourceCode, 20); - BOOST_REQUIRE(callContractFunction("getBalance()") == encodeArgs(u256(20 - 5), u256(5))); -} - -BOOST_AUTO_TEST_CASE(gas_and_value_basic) -{ - char const* sourceCode = R"( - contract helper { - bool flag; - function getBalance() returns (uint256 myBalance) { - return this.balance; - } - function setFlag() { flag = true; } - function getFlag() returns (bool fl) { return flag; } - } - contract test { - helper h; - function test() { h = new helper(); } - function sendAmount(uint amount) returns (uint256 bal) { - return h.getBalance.value(amount)(); - } - function outOfGas() returns (bool ret) { - h.setFlag.gas(2)(); // should fail due to OOG - return true; - } - function checkState() returns (bool flagAfter, uint myBal) { - flagAfter = h.getFlag(); - myBal = this.balance; - } - } - )"; - compileAndRun(sourceCode, 20); - BOOST_REQUIRE(callContractFunction("sendAmount(uint256)", 5) == encodeArgs(5)); - // call to helper should not succeed but amount should be transferred anyway - BOOST_REQUIRE(callContractFunction("outOfGas()", 5) == bytes()); - BOOST_REQUIRE(callContractFunction("checkState()", 5) == encodeArgs(false, 20 - 5)); -} - -BOOST_AUTO_TEST_CASE(gas_for_builtin) -{ - char const* sourceCode = R"( - contract Contract { - function test(uint g) returns (bytes32 data, bool flag) { - data = ripemd160.gas(g)("abc"); - flag = true; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test(uint256)", 500) == bytes()); - BOOST_CHECK(callContractFunction("test(uint256)", 800) == encodeArgs(u256("0x8eb208f7e05d987a9b044a8e98c6b087f15a0bfc000000000000000000000000"), true)); -} - -BOOST_AUTO_TEST_CASE(value_complex) -{ - char const* sourceCode = R"( - contract helper { - function getBalance() returns (uint256 myBalance) { - return this.balance; - } - } - contract test { - helper h; - function test() { h = new helper(); } - function sendAmount(uint amount) returns (uint256 bal) { - var x1 = h.getBalance.value(amount); - uint someStackElement = 20; - var x2 = x1.gas(1000); - return x2.value(amount + 3)();// overwrite value - } - } - )"; - compileAndRun(sourceCode, 20); - BOOST_REQUIRE(callContractFunction("sendAmount(uint256)", 5) == encodeArgs(8)); -} - -BOOST_AUTO_TEST_CASE(value_insane) -{ - char const* sourceCode = R"( - contract helper { - function getBalance() returns (uint256 myBalance) { - return this.balance; - } - } - contract test { - helper h; - function test() { h = new helper(); } - function sendAmount(uint amount) returns (uint256 bal) { - var x1 = h.getBalance.value; - var x2 = x1(amount).gas; - var x3 = x2(1000).value; - return x3(amount + 3)();// overwrite value - } - } - )"; - compileAndRun(sourceCode, 20); - BOOST_REQUIRE(callContractFunction("sendAmount(uint256)", 5) == encodeArgs(8)); -} - -BOOST_AUTO_TEST_CASE(value_for_constructor) -{ - char const* sourceCode = R"( - contract Helper { - bytes3 name; - bool flag; - function Helper(bytes3 x, bool f) { - name = x; - flag = f; - } - function getName() returns (bytes3 ret) { return name; } - function getFlag() returns (bool ret) { return flag; } - } - contract Main { - Helper h; - function Main() { - h = new Helper.value(10)("abc", true); - } - function getFlag() returns (bool ret) { return h.getFlag(); } - function getName() returns (bytes3 ret) { return h.getName(); } - function getBalances() returns (uint me, uint them) { me = this.balance; them = h.balance;} - })"; - compileAndRun(sourceCode, 22, "Main"); - BOOST_REQUIRE(callContractFunction("getFlag()") == encodeArgs(true)); - BOOST_REQUIRE(callContractFunction("getName()") == encodeArgs("abc")); - BOOST_REQUIRE(callContractFunction("getBalances()") == encodeArgs(12, 10)); -} - -BOOST_AUTO_TEST_CASE(virtual_function_calls) -{ - char const* sourceCode = R"( - contract Base { - function f() returns (uint i) { return g(); } - function g() returns (uint i) { return 1; } - } - contract Derived is Base { - function g() returns (uint i) { return 2; } - } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("g()") == encodeArgs(2)); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(access_base_storage) -{ - char const* sourceCode = R"( - contract Base { - uint dataBase; - function getViaBase() returns (uint i) { return dataBase; } - } - contract Derived is Base { - uint dataDerived; - function setData(uint base, uint derived) returns (bool r) { - dataBase = base; - dataDerived = derived; - return true; - } - function getViaDerived() returns (uint base, uint derived) { - base = dataBase; - derived = dataDerived; - } - } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("setData(uint256,uint256)", 1, 2) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("getViaBase()") == encodeArgs(1)); - BOOST_CHECK(callContractFunction("getViaDerived()") == encodeArgs(1, 2)); -} - -BOOST_AUTO_TEST_CASE(single_copy_with_multiple_inheritance) -{ - char const* sourceCode = R"( - contract Base { - uint data; - function setData(uint i) { data = i; } - function getViaBase() returns (uint i) { return data; } - } - contract A is Base { function setViaA(uint i) { setData(i); } } - contract B is Base { function getViaB() returns (uint i) { return getViaBase(); } } - contract Derived is Base, B, A { } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("getViaB()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("setViaA(uint256)", 23) == encodeArgs()); - BOOST_CHECK(callContractFunction("getViaB()") == encodeArgs(23)); -} - -BOOST_AUTO_TEST_CASE(explicit_base_cass) -{ - char const* sourceCode = R"( - contract BaseBase { function g() returns (uint r) { return 1; } } - contract Base is BaseBase { function g() returns (uint r) { return 2; } } - contract Derived is Base { - function f() returns (uint r) { return BaseBase.g(); } - function g() returns (uint r) { return 3; } - } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("g()") == encodeArgs(3)); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(base_constructor_arguments) -{ - char const* sourceCode = R"( - contract BaseBase { - uint m_a; - function BaseBase(uint a) { - m_a = a; - } - } - contract Base is BaseBase(7) { - function Base() { - m_a *= m_a; - } - } - contract Derived is Base() { - function getA() returns (uint r) { return m_a; } - } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("getA()") == encodeArgs(7 * 7)); -} - -BOOST_AUTO_TEST_CASE(function_usage_in_constructor_arguments) -{ - char const* sourceCode = R"( - contract BaseBase { - uint m_a; - function BaseBase(uint a) { - m_a = a; - } - function g() returns (uint r) { return 2; } - } - contract Base is BaseBase(BaseBase.g()) { - } - contract Derived is Base() { - function getA() returns (uint r) { return m_a; } - } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("getA()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(virtual_function_usage_in_constructor_arguments) -{ - char const* sourceCode = R"( - contract BaseBase { - uint m_a; - function BaseBase(uint a) { - m_a = a; - } - function overridden() returns (uint r) { return 1; } - function g() returns (uint r) { return overridden(); } - } - contract Base is BaseBase(BaseBase.g()) { - } - contract Derived is Base() { - function getA() returns (uint r) { return m_a; } - function overridden() returns (uint r) { return 2; } - } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("getA()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(constructor_argument_overriding) -{ - char const* sourceCode = R"( - contract BaseBase { - uint m_a; - function BaseBase(uint a) { - m_a = a; - } - } - contract Base is BaseBase(2) { } - contract Derived is BaseBase(3), Base { - function getA() returns (uint r) { return m_a; } - } - )"; - compileAndRun(sourceCode, 0, "Derived"); - BOOST_CHECK(callContractFunction("getA()") == encodeArgs(3)); -} - -BOOST_AUTO_TEST_CASE(function_modifier) -{ - char const* sourceCode = R"( - contract C { - function getOne() nonFree returns (uint r) { return 1; } - modifier nonFree { if (msg.value > 0) _ } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getOne()") == encodeArgs(0)); - BOOST_CHECK(callContractFunctionWithValue("getOne()", 1) == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(function_modifier_local_variables) -{ - char const* sourceCode = R"( - contract C { - modifier mod1 { var a = 1; var b = 2; _ } - modifier mod2(bool a) { if (a) return; else _ } - function f(bool a) mod1 mod2(a) returns (uint r) { return 3; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f(bool)", true) == encodeArgs(0)); - BOOST_CHECK(callContractFunction("f(bool)", false) == encodeArgs(3)); -} - -BOOST_AUTO_TEST_CASE(function_modifier_loop) -{ - char const* sourceCode = R"( - contract C { - modifier repeat(uint count) { for (var i = 0; i < count; ++i) _ } - function f() repeat(10) returns (uint r) { r += 1; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(10)); -} - -BOOST_AUTO_TEST_CASE(function_modifier_multi_invocation) -{ - char const* sourceCode = R"( - contract C { - modifier repeat(bool twice) { if (twice) _ _ } - function f(bool twice) repeat(twice) returns (uint r) { r += 1; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f(bool)", false) == encodeArgs(1)); - BOOST_CHECK(callContractFunction("f(bool)", true) == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(function_modifier_multi_with_return) -{ - // Here, the explicit return prevents the second execution - char const* sourceCode = R"( - contract C { - modifier repeat(bool twice) { if (twice) _ _ } - function f(bool twice) repeat(twice) returns (uint r) { r += 1; return r; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f(bool)", false) == encodeArgs(1)); - BOOST_CHECK(callContractFunction("f(bool)", true) == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(function_modifier_overriding) -{ - char const* sourceCode = R"( - contract A { - function f() mod returns (bool r) { return true; } - modifier mod { _ } - } - contract C is A { - modifier mod { } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(false)); -} - -BOOST_AUTO_TEST_CASE(function_modifier_calling_functions_in_creation_context) -{ - char const* sourceCode = R"( - contract A { - uint data; - function A() mod1 { f1(); } - function f1() mod2 { data |= 0x1; } - function f2() { data |= 0x20; } - function f3() { } - modifier mod1 { f2(); _ } - modifier mod2 { f3(); } - function getData() returns (uint r) { return data; } - } - contract C is A { - modifier mod1 { f4(); _ } - function f3() { data |= 0x300; } - function f4() { data |= 0x4000; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getData()") == encodeArgs(0x4300)); -} - -BOOST_AUTO_TEST_CASE(function_modifier_for_constructor) -{ - char const* sourceCode = R"( - contract A { - uint data; - function A() mod1 { data |= 2; } - modifier mod1 { data |= 1; _ } - function getData() returns (uint r) { return data; } - } - contract C is A { - modifier mod1 { data |= 4; _ } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getData()") == encodeArgs(4 | 2)); -} - -BOOST_AUTO_TEST_CASE(use_std_lib) -{ - char const* sourceCode = R"( - import "mortal"; - contract Icarus is mortal { } - )"; - m_addStandardSources = true; - u256 amount(130); - u160 address(23); - compileAndRun(sourceCode, amount, "Icarus"); - u256 balanceBefore = m_state.balance(m_sender); - BOOST_CHECK(callContractFunction("kill()") == bytes()); - BOOST_CHECK(!m_state.addressHasCode(m_contractAddress)); - BOOST_CHECK(m_state.balance(m_sender) > balanceBefore); -} - -BOOST_AUTO_TEST_CASE(crazy_elementary_typenames_on_stack) -{ - char const* sourceCode = R"( - contract C { - function f() returns (uint r) { - uint; uint; uint; uint; - int x = -7; - var a = uint; - return a(x); - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(-7))); -} - -BOOST_AUTO_TEST_CASE(super) -{ - char const* sourceCode = R"( - contract A { function f() returns (uint r) { return 1; } } - contract B is A { function f() returns (uint r) { return super.f() | 2; } } - contract C is A { function f() returns (uint r) { return super.f() | 4; } } - contract D is B, C { function f() returns (uint r) { return super.f() | 8; } } - )"; - compileAndRun(sourceCode, 0, "D"); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(1 | 2 | 4 | 8)); -} - -BOOST_AUTO_TEST_CASE(super_in_constructor) -{ - char const* sourceCode = R"( - contract A { function f() returns (uint r) { return 1; } } - contract B is A { function f() returns (uint r) { return super.f() | 2; } } - contract C is A { function f() returns (uint r) { return super.f() | 4; } } - contract D is B, C { uint data; function D() { data = super.f() | 8; } function f() returns (uint r) { return data; } } - )"; - compileAndRun(sourceCode, 0, "D"); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(1 | 2 | 4 | 8)); -} - -BOOST_AUTO_TEST_CASE(fallback_function) -{ - char const* sourceCode = R"( - contract A { - uint data; - function() returns (uint r) { data = 1; return 2; } - function getData() returns (uint r) { return data; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getData()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("") == encodeArgs(2)); - BOOST_CHECK(callContractFunction("getData()") == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(inherited_fallback_function) -{ - char const* sourceCode = R"( - contract A { - uint data; - function() returns (uint r) { data = 1; return 2; } - function getData() returns (uint r) { return data; } - } - contract B is A {} - )"; - compileAndRun(sourceCode, 0, "B"); - BOOST_CHECK(callContractFunction("getData()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("") == encodeArgs(2)); - BOOST_CHECK(callContractFunction("getData()") == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(event) -{ - char const* sourceCode = R"( - contract ClientReceipt { - event Deposit(address indexed _from, bytes32 indexed _id, uint _value); - function deposit(bytes32 _id, bool _manually) { - if (_manually) { - bytes32 s = 0x19dacbf83c5de6658e14cbf7bcae5c15eca2eedecf1c66fbca928e4d351bea0f; - log3(bytes32(msg.value), s, bytes32(msg.sender), _id); - } else - Deposit(msg.sender, _id, msg.value); - } - } - )"; - compileAndRun(sourceCode); - u256 value(18); - u256 id(0x1234); - for (bool manually: {true, false}) - { - callContractFunctionWithValue("deposit(bytes32,bool)", value, id, manually); - BOOST_REQUIRE_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(value))); - BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 3); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(address,bytes32,uint256)"))); - BOOST_CHECK_EQUAL(m_logs[0].topics[1], h256(m_sender)); - BOOST_CHECK_EQUAL(m_logs[0].topics[2], h256(id)); - } -} - -BOOST_AUTO_TEST_CASE(event_no_arguments) -{ - char const* sourceCode = R"( - contract ClientReceipt { - event Deposit; - function deposit() { - Deposit(); - } - } - )"; - compileAndRun(sourceCode); - callContractFunction("deposit()"); - BOOST_REQUIRE_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK(m_logs[0].data.empty()); - BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit()"))); -} - -BOOST_AUTO_TEST_CASE(event_anonymous) -{ - char const* sourceCode = R"( - contract ClientReceipt { - event Deposit() anonymous; - function deposit() { - Deposit(); - } - } - )"; - compileAndRun(sourceCode); - callContractFunction("deposit()"); - BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 0); -} - -BOOST_AUTO_TEST_CASE(event_anonymous_with_topics) -{ - char const* sourceCode = R"( - contract ClientReceipt { - event Deposit(address indexed _from, bytes32 indexed _id, uint _value) anonymous; - function deposit(bytes32 _id, bool _manually) { - Deposit(msg.sender, _id, msg.value); - } - } - )"; - compileAndRun(sourceCode); - u256 value(18); - u256 id(0x1234); - callContractFunctionWithValue("deposit(bytes32,bool)", value, id); - BOOST_REQUIRE_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK_EQUAL(h256(m_logs[0].data), h256(u256(value))); - BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 2); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], h256(m_sender)); - BOOST_CHECK_EQUAL(m_logs[0].topics[1], h256(id)); -} - -BOOST_AUTO_TEST_CASE(event_lots_of_data) -{ - char const* sourceCode = R"( - contract ClientReceipt { - event Deposit(address _from, bytes32 _id, uint _value, bool _flag); - function deposit(bytes32 _id) { - Deposit(msg.sender, _id, msg.value, true); - } - } - )"; - compileAndRun(sourceCode); - u256 value(18); - u256 id(0x1234); - callContractFunctionWithValue("deposit(bytes32)", value, id); - BOOST_REQUIRE_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK(m_logs[0].data == encodeArgs((u160)m_sender, id, value, true)); - BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(address,bytes32,uint256,bool)"))); -} - -BOOST_AUTO_TEST_CASE(event_really_lots_of_data) -{ - char const* sourceCode = R"( - contract ClientReceipt { - event Deposit(uint fixeda, bytes dynx, uint fixedb); - function deposit() { - Deposit(10, msg.data, 15); - } - } - )"; - compileAndRun(sourceCode); - callContractFunction("deposit()"); - BOOST_REQUIRE_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK(m_logs[0].data == encodeArgs(10, 0x60, 15, 4) + FixedHash<4>(dev::sha3("deposit()")).asBytes()); - BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(uint256,bytes,uint256)"))); -} - -BOOST_AUTO_TEST_CASE(event_really_lots_of_data_from_storage) -{ - char const* sourceCode = R"( - contract ClientReceipt { - bytes x; - event Deposit(uint fixeda, bytes dynx, uint fixedb); - function deposit() { - x.length = 3; - x[0] = "A"; - x[1] = "B"; - x[2] = "C"; - Deposit(10, x, 15); - } - } - )"; - compileAndRun(sourceCode); - callContractFunction("deposit()"); - BOOST_REQUIRE_EQUAL(m_logs.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress); - BOOST_CHECK(m_logs[0].data == encodeArgs(10, 0x60, 15, 3, string("ABC"))); - BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 1); - BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(uint256,bytes,uint256)"))); -} - -BOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one) -{ - char const* sourceCode = R"( - contract test { - function f(uint, uint k) returns(uint ret_k, uint ret_g){ - uint g = 8; - ret_k = k; - ret_g = g; - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f(uint256,uint256)", 5, 9) != encodeArgs(5, 8)); - BOOST_CHECK(callContractFunction("f(uint256,uint256)", 5, 9) == encodeArgs(9, 8)); -} - -BOOST_AUTO_TEST_CASE(empty_name_return_parameter) -{ - char const* sourceCode = R"( - contract test { - function f(uint k) returns(uint){ - return k; - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("f(uint256)", 9) == encodeArgs(9)); -} - -BOOST_AUTO_TEST_CASE(sha3_multiple_arguments) -{ - char const* sourceCode = R"( - contract c { - function foo(uint a, uint b, uint c) returns (bytes32 d) - { - d = sha3(a, b, c); - } - })"; - compileAndRun(sourceCode); - - BOOST_CHECK(callContractFunction("foo(uint256,uint256,uint256)", 10, 12, 13) == encodeArgs( - dev::sha3( - toBigEndian(u256(10)) + - toBigEndian(u256(12)) + - toBigEndian(u256(13))))); -} - -BOOST_AUTO_TEST_CASE(sha3_multiple_arguments_with_numeric_literals) -{ - char const* sourceCode = R"( - contract c { - function foo(uint a, uint16 b) returns (bytes32 d) - { - d = sha3(a, b, 145); - } - })"; - compileAndRun(sourceCode); - - BOOST_CHECK(callContractFunction("foo(uint256,uint16)", 10, 12) == encodeArgs( - dev::sha3( - toBigEndian(u256(10)) + - bytes{0x0, 0xc} + - bytes(1, 0x91)))); -} - -BOOST_AUTO_TEST_CASE(sha3_multiple_arguments_with_string_literals) -{ - char const* sourceCode = R"( - contract c { - function foo() returns (bytes32 d) - { - d = sha3("foo"); - } - function bar(uint a, uint16 b) returns (bytes32 d) - { - d = sha3(a, b, 145, "foo"); - } - })"; - compileAndRun(sourceCode); - - BOOST_CHECK(callContractFunction("foo()") == encodeArgs(dev::sha3("foo"))); - - BOOST_CHECK(callContractFunction("bar(uint256,uint16)", 10, 12) == encodeArgs( - dev::sha3( - toBigEndian(u256(10)) + - bytes{0x0, 0xc} + - bytes(1, 0x91) + - bytes{0x66, 0x6f, 0x6f}))); -} - -BOOST_AUTO_TEST_CASE(sha3_with_bytes) -{ - char const* sourceCode = R"( - contract c { - bytes data; - function foo() returns (bool) - { - data.length = 3; - data[0] = "f"; - data[1] = "o"; - data[2] = "o"; - return sha3(data) == sha3("foo"); - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("foo()") == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(iterated_sha3_with_bytes) -{ - char const* sourceCode = R"( - contract c { - bytes data; - function foo() returns (bytes32) - { - data.length = 3; - data[0] = "x"; - data[1] = "y"; - data[2] = "z"; - return sha3("b", sha3(data), "a"); - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("foo()") == encodeArgs( - u256(dev::sha3(bytes{'b'} + dev::sha3("xyz").asBytes() + bytes{'a'})) - )); -} - -BOOST_AUTO_TEST_CASE(generic_call) -{ - char const* sourceCode = R"**( - contract receiver { - uint public received; - function receive(uint256 x) { received = x; } - } - contract sender { - function doSend(address rec) returns (uint d) - { - bytes4 signature = bytes4(bytes32(sha3("receive(uint256)"))); - rec.call.value(2)(signature, 23); - return receiver(rec).received(); - } - } - )**"; - compileAndRun(sourceCode, 0, "receiver"); - u160 const c_receiverAddress = m_contractAddress; - compileAndRun(sourceCode, 50, "sender"); - BOOST_REQUIRE(callContractFunction("doSend(address)", c_receiverAddress) == encodeArgs(23)); - BOOST_CHECK_EQUAL(m_state.balance(m_contractAddress), 50 - 2); -} - -BOOST_AUTO_TEST_CASE(generic_callcode) -{ - char const* sourceCode = R"**( - contract receiver { - uint public received; - function receive(uint256 x) { received = x; } - } - contract sender { - uint public received; - function doSend(address rec) returns (uint d) - { - bytes4 signature = bytes4(bytes32(sha3("receive(uint256)"))); - rec.callcode.value(2)(signature, 23); - return receiver(rec).received(); - } - } - )**"; - compileAndRun(sourceCode, 0, "receiver"); - u160 const c_receiverAddress = m_contractAddress; - compileAndRun(sourceCode, 50, "sender"); - u160 const c_senderAddress = m_contractAddress; - BOOST_CHECK(callContractFunction("doSend(address)", c_receiverAddress) == encodeArgs(0)); - BOOST_CHECK(callContractFunction("received()") == encodeArgs(23)); - m_contractAddress = c_receiverAddress; - BOOST_CHECK(callContractFunction("received()") == encodeArgs(0)); - BOOST_CHECK(m_state.storage(c_receiverAddress).empty()); - BOOST_CHECK(!m_state.storage(c_senderAddress).empty()); - BOOST_CHECK_EQUAL(m_state.balance(c_receiverAddress), 0); - BOOST_CHECK_EQUAL(m_state.balance(c_senderAddress), 50); -} - -BOOST_AUTO_TEST_CASE(store_bytes) -{ - // this test just checks that the copy loop does not mess up the stack - char const* sourceCode = R"( - contract C { - function save() returns (uint r) { - r = 23; - savedData = msg.data; - r = 24; - } - bytes savedData; - } - )"; - compileAndRun(sourceCode); - // empty copy loop - BOOST_CHECK(callContractFunction("save()") == encodeArgs(24)); - BOOST_CHECK(callContractFunction("save()", "abcdefg") == encodeArgs(24)); -} - -BOOST_AUTO_TEST_CASE(bytes_from_calldata_to_memory) -{ - char const* sourceCode = R"( - contract C { - function() returns (bytes32) { - return sha3("abc", msg.data); - } - } - )"; - compileAndRun(sourceCode); - bytes calldata1 = bytes(61, 0x22) + bytes(12, 0x12); - sendMessage(calldata1, false); - BOOST_CHECK(m_output == encodeArgs(dev::sha3(bytes{'a', 'b', 'c'} + calldata1))); -} - -BOOST_AUTO_TEST_CASE(call_forward_bytes) -{ - char const* sourceCode = R"( - contract receiver { - uint public received; - function receive(uint x) { received += x + 1; } - function() { received = 0x80; } - } - contract sender { - function sender() { rec = new receiver(); } - function() { savedData = msg.data; } - function forward() returns (bool) { rec.call(savedData); return true; } - function clear() returns (bool) { delete savedData; return true; } - function val() returns (uint) { return rec.received(); } - receiver rec; - bytes savedData; - } - )"; - compileAndRun(sourceCode, 0, "sender"); - BOOST_CHECK(callContractFunction("receive(uint256)", 7) == bytes()); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("forward()") == encodeArgs(true)); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(8)); - BOOST_CHECK(callContractFunction("clear()") == encodeArgs(true)); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(8)); - BOOST_CHECK(callContractFunction("forward()") == encodeArgs(true)); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(0x80)); -} - -BOOST_AUTO_TEST_CASE(copying_bytes_multiassign) -{ - char const* sourceCode = R"( - contract receiver { - uint public received; - function receive(uint x) { received += x + 1; } - function() { received = 0x80; } - } - contract sender { - function sender() { rec = new receiver(); } - function() { savedData1 = savedData2 = msg.data; } - function forward(bool selector) returns (bool) { - if (selector) { rec.call(savedData1); delete savedData1; } - else { rec.call(savedData2); delete savedData2; } - return true; - } - function val() returns (uint) { return rec.received(); } - receiver rec; - bytes savedData1; - bytes savedData2; - } - )"; - compileAndRun(sourceCode, 0, "sender"); - BOOST_CHECK(callContractFunction("receive(uint256)", 7) == bytes()); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("forward(bool)", true) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(8)); - BOOST_CHECK(callContractFunction("forward(bool)", false) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(16)); - BOOST_CHECK(callContractFunction("forward(bool)", true) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("val()") == encodeArgs(0x80)); -} - -BOOST_AUTO_TEST_CASE(delete_removes_bytes_data) -{ - char const* sourceCode = R"( - contract c { - function() { data = msg.data; } - function del() returns (bool) { delete data; return true; } - bytes data; - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("---", 7) == bytes()); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("del()", 7) == encodeArgs(true)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(copy_from_calldata_removes_bytes_data) -{ - char const* sourceCode = R"( - contract c { - function set() returns (bool) { data = msg.data; return true; } - function() { data = msg.data; } - bytes data; - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("set()", 1, 2, 3, 4, 5) == encodeArgs(true)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - sendMessage(bytes(), false); - BOOST_CHECK(m_output == bytes()); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(copy_removes_bytes_data) -{ - char const* sourceCode = R"( - contract c { - function set() returns (bool) { data1 = msg.data; return true; } - function reset() returns (bool) { data1 = data2; return true; } - bytes data1; - bytes data2; - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("set()", 1, 2, 3, 4, 5) == encodeArgs(true)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("reset()") == encodeArgs(true)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(bytes_inside_mappings) -{ - char const* sourceCode = R"( - contract c { - function set(uint key) returns (bool) { data[key] = msg.data; return true; } - function copy(uint from, uint to) returns (bool) { data[to] = data[from]; return true; } - mapping(uint => bytes) data; - } - )"; - compileAndRun(sourceCode); - // store a short byte array at 1 and a longer one at 2 - BOOST_CHECK(callContractFunction("set(uint256)", 1, 2) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("set(uint256)", 2, 2, 3, 4, 5) == encodeArgs(true)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - // copy shorter to longer - BOOST_CHECK(callContractFunction("copy(uint256,uint256)", 1, 2) == encodeArgs(true)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - // copy empty to both - BOOST_CHECK(callContractFunction("copy(uint256,uint256)", 99, 1) == encodeArgs(true)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("copy(uint256,uint256)", 99, 2) == encodeArgs(true)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(bytes_length_member) -{ - char const* sourceCode = R"( - contract c { - function set() returns (bool) { data = msg.data; return true; } - function getLength() returns (uint) { return data.length; } - bytes data; - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getLength()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("set()", 1, 2) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("getLength()") == encodeArgs(4+32+32)); -} - -BOOST_AUTO_TEST_CASE(struct_copy) -{ - char const* sourceCode = R"( - contract c { - struct Nested { uint x; uint y; } - struct Struct { uint a; mapping(uint => Struct) b; Nested nested; uint c; } - mapping(uint => Struct) data; - function set(uint k) returns (bool) { - data[k].a = 1; - data[k].nested.x = 3; - data[k].nested.y = 4; - data[k].c = 2; - return true; - } - function copy(uint from, uint to) returns (bool) { - data[to] = data[from]; - return true; - } - function retrieve(uint k) returns (uint a, uint x, uint y, uint c) - { - a = data[k].a; - x = data[k].nested.x; - y = data[k].nested.y; - c = data[k].c; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("set(uint256)", 7) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("retrieve(uint256)", 7) == encodeArgs(1, 3, 4, 2)); - BOOST_CHECK(callContractFunction("copy(uint256,uint256)", 7, 8) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("retrieve(uint256)", 7) == encodeArgs(1, 3, 4, 2)); - BOOST_CHECK(callContractFunction("retrieve(uint256)", 8) == encodeArgs(1, 3, 4, 2)); - BOOST_CHECK(callContractFunction("copy(uint256,uint256)", 0, 7) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("retrieve(uint256)", 7) == encodeArgs(0, 0, 0, 0)); - BOOST_CHECK(callContractFunction("retrieve(uint256)", 8) == encodeArgs(1, 3, 4, 2)); - BOOST_CHECK(callContractFunction("copy(uint256,uint256)", 7, 8) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("retrieve(uint256)", 8) == encodeArgs(0, 0, 0, 0)); -} - -BOOST_AUTO_TEST_CASE(struct_containing_bytes_copy_and_delete) -{ - char const* sourceCode = R"( - contract c { - struct Struct { uint a; bytes data; uint b; } - Struct data1; - Struct data2; - function set(uint _a, bytes _data, uint _b) external returns (bool) { - data1.a = _a; - data1.b = _b; - data1.data = _data; - return true; - } - function copy() returns (bool) { - data1 = data2; - return true; - } - function del() returns (bool) { - delete data1; - return true; - } - } - )"; - compileAndRun(sourceCode); - string data = "123456789012345678901234567890123"; - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("set(uint256,bytes,uint256)", 12, u256(data.length()), 13, data) == encodeArgs(true)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("copy()") == encodeArgs(true)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("set(uint256,bytes,uint256)", 12, u256(data.length()), 13, data) == encodeArgs(true)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("del()") == encodeArgs(true)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(struct_copy_via_local) -{ - char const* sourceCode = R"( - contract c { - struct Struct { uint a; uint b; } - Struct data1; - Struct data2; - function test() returns (bool) { - data1.a = 1; - data1.b = 2; - var x = data1; - data2 = x; - return data2.a == data1.a && data2.b == data1.b; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(using_enums) -{ - char const* sourceCode = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function test() - { - choices = ActionChoices.GoStraight; - } - function getChoice() returns (uint d) - { - d = uint256(choices); - } - ActionChoices choices; - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getChoice()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(constructing_enums_from_ints) -{ - char const* sourceCode = R"( - contract c { - enum Truth { False, True } - function test() returns (uint) - { - return uint(Truth(uint8(0x701))); - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(inline_member_init) -{ - char const* sourceCode = R"( - contract test { - function test(){ - m_b = 6; - m_c = 8; - } - uint m_a = 5; - uint m_b; - uint m_c = 7; - function get() returns (uint a, uint b, uint c){ - a = m_a; - b = m_b; - c = m_c; - } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("get()") == encodeArgs(5, 6, 8)); -} - -BOOST_AUTO_TEST_CASE(inline_member_init_inheritence) -{ - char const* sourceCode = R"( - contract Base { - function Base(){} - uint m_base = 5; - function getBMember() returns (uint i) { return m_base; } - } - contract Derived is Base { - function Derived(){} - uint m_derived = 6; - function getDMember() returns (uint i) { return m_derived; } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getBMember()") == encodeArgs(5)); - BOOST_CHECK(callContractFunction("getDMember()") == encodeArgs(6)); -} - -BOOST_AUTO_TEST_CASE(inline_member_init_inheritence_without_constructor) -{ - char const* sourceCode = R"( - contract Base { - uint m_base = 5; - function getBMember() returns (uint i) { return m_base; } - } - contract Derived is Base { - uint m_derived = 6; - function getDMember() returns (uint i) { return m_derived; } - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getBMember()") == encodeArgs(5)); - BOOST_CHECK(callContractFunction("getDMember()") == encodeArgs(6)); -} - -BOOST_AUTO_TEST_CASE(external_function) -{ - char const* sourceCode = R"( - contract c { - function f(uint a) returns (uint) { return a; } - function test(uint a, uint b) external returns (uint r_a, uint r_b) { - r_a = f(a + 7); - r_b = b; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test(uint256,uint256)", 2, 3) == encodeArgs(2+7, 3)); -} - -BOOST_AUTO_TEST_CASE(bytes_in_arguments) -{ - char const* sourceCode = R"( - contract c { - uint result; - function f(uint a, uint b) { result += a + b; } - function g(uint a) { result *= a; } - function test(uint a, bytes data1, bytes data2, uint b) external returns (uint r_a, uint r, uint r_b, uint l) { - r_a = a; - this.call(data1); - this.call(data2); - r = result; - r_b = b; - l = data1.length; - } - } - )"; - compileAndRun(sourceCode); - - string innercalldata1 = asString(FixedHash<4>(dev::sha3("f(uint256,uint256)")).asBytes() + encodeArgs(8, 9)); - string innercalldata2 = asString(FixedHash<4>(dev::sha3("g(uint256)")).asBytes() + encodeArgs(3)); - bytes calldata = encodeArgs( - 12, 32 * 4, u256(32 * 4 + 32 + (innercalldata1.length() + 31) / 32 * 32), 13, - u256(innercalldata1.length()), innercalldata1, - u256(innercalldata2.length()), innercalldata2); - BOOST_CHECK(callContractFunction("test(uint256,bytes,bytes,uint256)", calldata) - == encodeArgs(12, (8 + 9) * 3, 13, u256(innercalldata1.length()))); -} - -BOOST_AUTO_TEST_CASE(fixed_arrays_in_storage) -{ - char const* sourceCode = R"( - contract c { - struct Data { uint x; uint y; } - Data[2**10] data; - uint[2**10 + 3] ids; - function setIDStatic(uint id) { ids[2] = id; } - function setID(uint index, uint id) { ids[index] = id; } - function setData(uint index, uint x, uint y) { data[index].x = x; data[index].y = y; } - function getID(uint index) returns (uint) { return ids[index]; } - function getData(uint index) returns (uint x, uint y) { x = data[index].x; y = data[index].y; } - function getLengths() returns (uint l1, uint l2) { l1 = data.length; l2 = ids.length; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("setIDStatic(uint256)", 11) == bytes()); - BOOST_CHECK(callContractFunction("getID(uint256)", 2) == encodeArgs(11)); - BOOST_CHECK(callContractFunction("setID(uint256,uint256)", 7, 8) == bytes()); - BOOST_CHECK(callContractFunction("getID(uint256)", 7) == encodeArgs(8)); - BOOST_CHECK(callContractFunction("setData(uint256,uint256,uint256)", 7, 8, 9) == bytes()); - BOOST_CHECK(callContractFunction("setData(uint256,uint256,uint256)", 8, 10, 11) == bytes()); - BOOST_CHECK(callContractFunction("getData(uint256)", 7) == encodeArgs(8, 9)); - BOOST_CHECK(callContractFunction("getData(uint256)", 8) == encodeArgs(10, 11)); - BOOST_CHECK(callContractFunction("getLengths()") == encodeArgs(u256(1) << 10, (u256(1) << 10) + 3)); -} - -BOOST_AUTO_TEST_CASE(dynamic_arrays_in_storage) -{ - char const* sourceCode = R"( - contract c { - struct Data { uint x; uint y; } - Data[] data; - uint[] ids; - function setIDStatic(uint id) { ids[2] = id; } - function setID(uint index, uint id) { ids[index] = id; } - function setData(uint index, uint x, uint y) { data[index].x = x; data[index].y = y; } - function getID(uint index) returns (uint) { return ids[index]; } - function getData(uint index) returns (uint x, uint y) { x = data[index].x; y = data[index].y; } - function getLengths() returns (uint l1, uint l2) { l1 = data.length; l2 = ids.length; } - function setLengths(uint l1, uint l2) { data.length = l1; ids.length = l2; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getLengths()") == encodeArgs(0, 0)); - BOOST_CHECK(callContractFunction("setLengths(uint256,uint256)", 48, 49) == bytes()); - BOOST_CHECK(callContractFunction("getLengths()") == encodeArgs(48, 49)); - BOOST_CHECK(callContractFunction("setIDStatic(uint256)", 11) == bytes()); - BOOST_CHECK(callContractFunction("getID(uint256)", 2) == encodeArgs(11)); - BOOST_CHECK(callContractFunction("setID(uint256,uint256)", 7, 8) == bytes()); - BOOST_CHECK(callContractFunction("getID(uint256)", 7) == encodeArgs(8)); - BOOST_CHECK(callContractFunction("setData(uint256,uint256,uint256)", 7, 8, 9) == bytes()); - BOOST_CHECK(callContractFunction("setData(uint256,uint256,uint256)", 8, 10, 11) == bytes()); - BOOST_CHECK(callContractFunction("getData(uint256)", 7) == encodeArgs(8, 9)); - BOOST_CHECK(callContractFunction("getData(uint256)", 8) == encodeArgs(10, 11)); -} - -BOOST_AUTO_TEST_CASE(fixed_out_of_bounds_array_access) -{ - char const* sourceCode = R"( - contract c { - uint[4] data; - function set(uint index, uint value) returns (bool) { data[index] = value; return true; } - function get(uint index) returns (uint) { return data[index]; } - function length() returns (uint) { return data.length; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("length()") == encodeArgs(4)); - BOOST_CHECK(callContractFunction("set(uint256,uint256)", 3, 4) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("set(uint256,uint256)", 4, 5) == bytes()); - BOOST_CHECK(callContractFunction("set(uint256,uint256)", 400, 5) == bytes()); - BOOST_CHECK(callContractFunction("get(uint256)", 3) == encodeArgs(4)); - BOOST_CHECK(callContractFunction("get(uint256)", 4) == bytes()); - BOOST_CHECK(callContractFunction("get(uint256)", 400) == bytes()); - BOOST_CHECK(callContractFunction("length()") == encodeArgs(4)); -} - -BOOST_AUTO_TEST_CASE(dynamic_out_of_bounds_array_access) -{ - char const* sourceCode = R"( - contract c { - uint[] data; - function enlarge(uint amount) returns (uint) { return data.length += amount; } - function set(uint index, uint value) returns (bool) { data[index] = value; return true; } - function get(uint index) returns (uint) { return data[index]; } - function length() returns (uint) { return data.length; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("length()") == encodeArgs(0)); - BOOST_CHECK(callContractFunction("get(uint256)", 3) == bytes()); - BOOST_CHECK(callContractFunction("enlarge(uint256)", 4) == encodeArgs(4)); - BOOST_CHECK(callContractFunction("length()") == encodeArgs(4)); - BOOST_CHECK(callContractFunction("set(uint256,uint256)", 3, 4) == encodeArgs(true)); - BOOST_CHECK(callContractFunction("get(uint256)", 3) == encodeArgs(4)); - BOOST_CHECK(callContractFunction("length()") == encodeArgs(4)); - BOOST_CHECK(callContractFunction("set(uint256,uint256)", 4, 8) == bytes()); - BOOST_CHECK(callContractFunction("length()") == encodeArgs(4)); -} - -BOOST_AUTO_TEST_CASE(fixed_array_cleanup) -{ - char const* sourceCode = R"( - contract c { - uint spacer1; - uint spacer2; - uint[20] data; - function fill() { - for (uint i = 0; i < data.length; ++i) data[i] = i+1; - } - function clear() { delete data; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("fill()") == bytes()); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("clear()") == bytes()); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(short_fixed_array_cleanup) -{ - char const* sourceCode = R"( - contract c { - uint spacer1; - uint spacer2; - uint[3] data; - function fill() { - for (uint i = 0; i < data.length; ++i) data[i] = i+1; - } - function clear() { delete data; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("fill()") == bytes()); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("clear()") == bytes()); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(dynamic_array_cleanup) -{ - char const* sourceCode = R"( - contract c { - uint[20] spacer; - uint[] dynamic; - function fill() { - dynamic.length = 21; - for (uint i = 0; i < dynamic.length; ++i) dynamic[i] = i+1; - } - function halfClear() { dynamic.length = 5; } - function fullClear() { delete dynamic; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("fill()") == bytes()); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("halfClear()") == bytes()); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("fullClear()") == bytes()); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(dynamic_multi_array_cleanup) -{ - char const* sourceCode = R"( - contract c { - struct s { uint[][] d; } - s[] data; - function fill() returns (uint) { - data.length = 3; - data[2].d.length = 4; - data[2].d[3].length = 5; - data[2].d[3][4] = 8; - return data[2].d[3][4]; - } - function clear() { delete data; } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("fill()") == encodeArgs(8)); - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("clear()") == bytes()); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(array_copy_storage_storage_dyn_dyn) -{ - char const* sourceCode = R"( - contract c { - uint[] data1; - uint[] data2; - function setData1(uint length, uint index, uint value) { - data1.length = length; if (index < length) data1[index] = value; - } - function copyStorageStorage() { data2 = data1; } - function getData2(uint index) returns (uint len, uint val) { - len = data2.length; if (index < len) val = data2[index]; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("setData1(uint256,uint256,uint256)", 10, 5, 4) == bytes()); - BOOST_CHECK(callContractFunction("copyStorageStorage()") == bytes()); - BOOST_CHECK(callContractFunction("getData2(uint256)", 5) == encodeArgs(10, 4)); - BOOST_CHECK(callContractFunction("setData1(uint256,uint256,uint256)", 0, 0, 0) == bytes()); - BOOST_CHECK(callContractFunction("copyStorageStorage()") == bytes()); - BOOST_CHECK(callContractFunction("getData2(uint256)", 0) == encodeArgs(0, 0)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(array_copy_storage_storage_static_static) -{ - char const* sourceCode = R"( - contract c { - uint[40] data1; - uint[20] data2; - function test() returns (uint x, uint y){ - data1[30] = 4; - data1[2] = 7; - data1[3] = 9; - data2[3] = 8; - data1 = data2; - x = data1[3]; - y = data1[30]; // should be cleared - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(8, 0)); -} - -BOOST_AUTO_TEST_CASE(array_copy_storage_storage_static_dynamic) -{ - char const* sourceCode = R"( - contract c { - uint[9] data1; - uint[] data2; - function test() returns (uint x, uint y){ - data1[8] = 4; - data2 = data1; - x = data2.length; - y = data2[8]; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(9, 4)); -} - -BOOST_AUTO_TEST_CASE(array_copy_different_packing) -{ - char const* sourceCode = R"( - contract c { - bytes8[] data1; // 4 per slot - bytes10[] data2; // 3 per slot - function test() returns (bytes10 a, bytes10 b, bytes10 c, bytes10 d, bytes10 e) { - data1.length = 9; - for (uint i = 0; i < data1.length; ++i) - data1[i] = bytes8(i); - data2 = data1; - a = data2[1]; - b = data2[2]; - c = data2[3]; - d = data2[4]; - e = data2[5]; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs( - asString(fromHex("0000000000000001")), - asString(fromHex("0000000000000002")), - asString(fromHex("0000000000000003")), - asString(fromHex("0000000000000004")), - asString(fromHex("0000000000000005")) - )); -} - -BOOST_AUTO_TEST_CASE(array_copy_target_simple) -{ - char const* sourceCode = R"( - contract c { - bytes8[9] data1; // 4 per slot - bytes17[10] data2; // 1 per slot, no offset counter - function test() returns (bytes17 a, bytes17 b, bytes17 c, bytes17 d, bytes17 e) { - for (uint i = 0; i < data1.length; ++i) - data1[i] = bytes8(i); - data2[8] = data2[9] = 2; - data2 = data1; - a = data2[1]; - b = data2[2]; - c = data2[3]; - d = data2[4]; - e = data2[9]; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs( - asString(fromHex("0000000000000001")), - asString(fromHex("0000000000000002")), - asString(fromHex("0000000000000003")), - asString(fromHex("0000000000000004")), - asString(fromHex("0000000000000000")) - )); -} - -BOOST_AUTO_TEST_CASE(array_copy_target_leftover) -{ - // test that leftover elements in the last slot of target are correctly cleared during assignment - char const* sourceCode = R"( - contract c { - byte[10] data1; - bytes2[32] data2; - function test() returns (uint check, uint res1, uint res2) { - uint i; - for (i = 0; i < data2.length; ++i) - data2[i] = 0xffff; - check = uint(data2[31]) * 0x10000 | uint(data2[14]); - for (i = 0; i < data1.length; ++i) - data1[i] = byte(uint8(1 + i)); - data2 = data1; - for (i = 0; i < 16; ++i) - res1 |= uint(data2[i]) * 0x10000**i; - for (i = 0; i < 16; ++i) - res2 |= uint(data2[16 + i]) * 0x10000**i; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs( - u256("0xffffffff"), - asString(fromHex("0000000000000000""000000000a000900""0800070006000500""0400030002000100")), - asString(fromHex("0000000000000000""0000000000000000""0000000000000000""0000000000000000")) - )); -} - -BOOST_AUTO_TEST_CASE(array_copy_target_leftover2) -{ - // since the copy always copies whole slots, we have to make sure that the source size maxes - // out a whole slot and at the same time there are still elements left in the target at that point - char const* sourceCode = R"( - contract c { - bytes8[4] data1; // fits into one slot - bytes10[6] data2; // 4 elements need two slots - function test() returns (bytes10 r1, bytes10 r2, bytes10 r3) { - data1[0] = 1; - data1[1] = 2; - data1[2] = 3; - data1[3] = 4; - for (uint i = 0; i < data2.length; ++i) - data2[i] = bytes10(0xffff00 | (1 + i)); - data2 = data1; - r1 = data2[3]; - r2 = data2[4]; - r3 = data2[5]; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs( - asString(fromHex("0000000000000004")), - asString(fromHex("0000000000000000")), - asString(fromHex("0000000000000000")) - )); -} -BOOST_AUTO_TEST_CASE(array_copy_storage_storage_struct) -{ - char const* sourceCode = R"( - contract c { - struct Data { uint x; uint y; } - Data[] data1; - Data[] data2; - function test() returns (uint x, uint y) { - data1.length = 9; - data1[8].x = 4; - data1[8].y = 5; - data2 = data1; - x = data2[8].x; - y = data2[8].y; - data1.length = 0; - data2 = data1; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(4, 5)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(external_array_args) -{ - char const* sourceCode = R"( - contract c { - function test(uint[8] a, uint[] b, uint[5] c, uint a_index, uint b_index, uint c_index) - external returns (uint av, uint bv, uint cv) { - av = a[a_index]; - bv = b[b_index]; - cv = c[c_index]; - } - } - )"; - compileAndRun(sourceCode); - bytes params = encodeArgs( - 1, 2, 3, 4, 5, 6, 7, 8, // a - 32 * (8 + 1 + 5 + 1 + 1 + 1), // offset to b - 21, 22, 23, 24, 25, // c - 0, 1, 2, // (a,b,c)_index - 3, // b.length - 11, 12, 13 // b - ); - BOOST_CHECK(callContractFunction("test(uint256[8],uint256[],uint256[5],uint256,uint256,uint256)", params) == encodeArgs(1, 12, 23)); -} - -BOOST_AUTO_TEST_CASE(bytes_index_access) -{ - char const* sourceCode = R"( - contract c { - bytes data; - function direct(bytes arg, uint index) external returns (uint) { - return uint(arg[index]); - } - function storageCopyRead(bytes arg, uint index) external returns (uint) { - data = arg; - return uint(data[index]); - } - function storageWrite() external returns (uint) { - data.length = 35; - data[31] = 0x77; - data[32] = 0x14; - - data[31] = 1; - data[31] |= 8; - data[30] = 1; - data[32] = 3; - return uint(data[30]) * 0x100 | uint(data[31]) * 0x10 | uint(data[32]); - } - } - )"; - compileAndRun(sourceCode); - string array{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, 32, 33}; - BOOST_CHECK(callContractFunction("direct(bytes,uint256)", 64, 33, u256(array.length()), array) == encodeArgs(33)); - BOOST_CHECK(callContractFunction("storageCopyRead(bytes,uint256)", 64, 33, u256(array.length()), array) == encodeArgs(33)); - BOOST_CHECK(callContractFunction("storageWrite()") == encodeArgs(0x193)); -} - -BOOST_AUTO_TEST_CASE(bytes_delete_element) -{ - char const* sourceCode = R"( - contract c { - bytes data; - function test1() external returns (bool) { - data.length = 100; - for (uint i = 0; i < data.length; i++) - data[i] = byte(i); - delete data[94]; - delete data[96]; - delete data[98]; - return data[94] == 0 && data[95] == 95 && data[96] == 0 && data[97] == 97; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test1()") == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(array_copy_calldata_storage) -{ - char const* sourceCode = R"( - contract c { - uint[9] m_data; - uint[] m_data_dyn; - uint8[][] m_byte_data; - function store(uint[9] a, uint8[3][] b) external returns (uint8) { - m_data = a; - m_data_dyn = a; - m_byte_data = b; - return b[3][1]; // note that access and declaration are reversed to each other - } - function retrieve() returns (uint a, uint b, uint c, uint d, uint e, uint f, uint g) { - a = m_data.length; - b = m_data[7]; - c = m_data_dyn.length; - d = m_data_dyn[7]; - e = m_byte_data.length; - f = m_byte_data[3].length; - g = m_byte_data[3][1]; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("store(uint256[9],uint8[3][])", encodeArgs( - 21, 22, 23, 24, 25, 26, 27, 28, 29, // a - u256(32 * (9 + 1)), - 4, // size of b - 1, 2, 3, // b[0] - 11, 12, 13, // b[1] - 21, 22, 23, // b[2] - 31, 32, 33 // b[3] - )) == encodeArgs(32)); - BOOST_CHECK(callContractFunction("retrieve()") == encodeArgs( - 9, 28, 9, 28, - 4, 3, 32)); -} - -BOOST_AUTO_TEST_CASE(array_copy_nested_array) -{ - char const* sourceCode = R"( - contract c { - uint[4][] a; - uint[10][] b; - uint[][] c; - function test(uint[2][] d) external returns (uint) { - a = d; - b = a; - c = b; - return c[1][1] | c[1][2] | c[1][3] | c[1][4]; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test(uint256[2][])", encodeArgs( - 32, 3, - 7, 8, - 9, 10, - 11, 12 - )) == encodeArgs(10)); -} - -BOOST_AUTO_TEST_CASE(array_copy_including_mapping) -{ - char const* sourceCode = R"( - contract c { - mapping(uint=>uint)[90][] large; - mapping(uint=>uint)[3][] small; - function test() returns (uint r) { - large.length = small.length = 7; - large[3][2][0] = 2; - large[1] = large[3]; - small[3][2][0] = 2; - small[1] = small[2]; - r = (( - small[3][2][0] * 0x100 | - small[1][2][0]) * 0x100 | - large[3][2][0]) * 0x100 | - large[1][2][0]; - delete small; - delete large; - } - function clear() returns (uint r) { - large.length = small.length = 7; - small[3][2][0] = 0; - large[3][2][0] = 0; - small.length = large.length = 0; - return 7; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(0x02000200)); - // storage is not empty because we cannot delete the mappings - BOOST_CHECK(!m_state.storage(m_contractAddress).empty()); - BOOST_CHECK(callContractFunction("clear()") == encodeArgs(7)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(pass_dynamic_arguments_to_the_base) -{ - char const* sourceCode = R"( - contract Base { - function Base(uint i) - { - m_i = i; - } - uint public m_i; - } - contract Derived is Base(2) { - function Derived(uint i) Base(i) - {} - } - contract Final is Derived(4) { - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("m_i()") == encodeArgs(4)); -} - -BOOST_AUTO_TEST_CASE(pass_dynamic_arguments_to_the_base_base) -{ - char const* sourceCode = R"( - contract Base { - function Base(uint j) - { - m_i = j; - } - uint public m_i; - } - contract Base1 is Base(3) { - function Base1(uint k) Base(k*k) {} - } - contract Derived is Base(3), Base1(2) { - function Derived(uint i) Base(i) Base1(i) - {} - } - contract Final is Derived(4) { - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("m_i()") == encodeArgs(4)); -} - -BOOST_AUTO_TEST_CASE(pass_dynamic_arguments_to_the_base_base_with_gap) -{ - char const* sourceCode = R"( - contract Base { - function Base(uint i) - { - m_i = i; - } - uint public m_i; - } - contract Base1 is Base(3) {} - contract Derived is Base(2), Base1 { - function Derived(uint i) Base(i) {} - } - contract Final is Derived(4) { - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("m_i()") == encodeArgs(4)); -} - -BOOST_AUTO_TEST_CASE(simple_constant_variables_test) -{ - char const* sourceCode = R"( - contract Foo { - function getX() returns (uint r) { return x; } - uint constant x = 56; - })"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("getX()") == encodeArgs(56)); -} - -BOOST_AUTO_TEST_CASE(constant_variables) -{ - //for now constant specifier is valid only for uint bytesXX and enums - char const* sourceCode = R"( - contract Foo { - uint constant x = 56; - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - ActionChoices constant choices = ActionChoices.GoLeft; - bytes32 constant st = "abc\x00\xff__"; - })"; - compileAndRun(sourceCode); -} - -BOOST_AUTO_TEST_CASE(packed_storage_structs_uint) -{ - char const* sourceCode = R"( - contract C { - struct str { uint8 a; uint16 b; uint248 c; } - str data; - function test() returns (uint) { - data.a = 2; - if (data.a != 2) return 2; - data.b = 0xabcd; - if (data.b != 0xabcd) return 3; - data.c = 0x1234567890; - if (data.c != 0x1234567890) return 4; - if (data.a != 2) return 5; - data.a = 8; - if (data.a != 8) return 6; - if (data.b != 0xabcd) return 7; - data.b = 0xdcab; - if (data.b != 0xdcab) return 8; - if (data.c != 0x1234567890) return 9; - data.c = 0x9876543210; - if (data.c != 0x9876543210) return 10; - return 1; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(packed_storage_structs_enum) -{ - char const* sourceCode = R"( - contract C { - enum small { A, B, C, D } - enum larger { A, B, C, D, E} - struct str { small a; small b; larger c; larger d; } - str data; - function test() returns (uint) { - data.a = small.B; - if (data.a != small.B) return 2; - data.b = small.C; - if (data.b != small.C) return 3; - data.c = larger.D; - if (data.c != larger.D) return 4; - if (data.a != small.B) return 5; - data.a = small.C; - if (data.a != small.C) return 6; - if (data.b != small.C) return 7; - data.b = small.D; - if (data.b != small.D) return 8; - if (data.c != larger.D) return 9; - data.c = larger.B; - if (data.c != larger.B) return 10; - return 1; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(1)); -} - -BOOST_AUTO_TEST_CASE(packed_storage_structs_bytes) -{ - char const* sourceCode = R"( - contract C { - struct s1 { byte a; byte b; bytes10 c; bytes9 d; bytes10 e; } - struct s2 { byte a; s1 inner; byte b; byte c; } - byte x; - s2 data; - byte y; - function test() returns (bool) { - x = 1; - data.a = 2; - data.inner.a = 3; - data.inner.b = 4; - data.inner.c = "1234567890"; - data.inner.d = "123456789"; - data.inner.e = "abcdefghij"; - data.b = 5; - data.c = 6; - y = 7; - return x == 1 && data.a == 2 && data.inner.a == 3 && data.inner.b == 4 && - data.inner.c == "1234567890" && data.inner.d == "123456789" && - data.inner.e == "abcdefghij" && data.b == 5 && data.c == 6 && y == 7; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(true)); -} - -BOOST_AUTO_TEST_CASE(packed_storage_structs_delete) -{ - char const* sourceCode = R"( - contract C { - struct str { uint8 a; uint16 b; uint8 c; } - uint8 x; - uint16 y; - str data; - function test() returns (uint) { - x = 1; - y = 2; - data.a = 2; - data.b = 0xabcd; - data.c = 0xfa; - if (x != 1 || y != 2 || data.a != 2 || data.b != 0xabcd || data.c != 0xfa) - return 2; - delete y; - delete data.b; - if (x != 1 || y != 0 || data.a != 2 || data.b != 0 || data.c != 0xfa) - return 3; - delete x; - delete data; - return 1; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(1)); - BOOST_CHECK(m_state.storage(m_contractAddress).empty()); -} - -BOOST_AUTO_TEST_CASE(overloaded_function_call_resolve_to_first) -{ - char const* sourceCode = R"( - contract test { - function f(uint k) returns(uint d) { return k; } - function f(uint a, uint b) returns(uint d) { return a + b; } - function g() returns(uint d) { return f(3); } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("g()") == encodeArgs(3)); -} - -BOOST_AUTO_TEST_CASE(overloaded_function_call_resolve_to_second) -{ - char const* sourceCode = R"( - contract test { - function f(uint a, uint b) returns(uint d) { return a + b; } - function f(uint k) returns(uint d) { return k; } - function g() returns(uint d) { return f(3, 7); } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("g()") == encodeArgs(10)); -} - -BOOST_AUTO_TEST_CASE(overloaded_function_call_with_if_else) -{ - char const* sourceCode = R"( - contract test { - function f(uint a, uint b) returns(uint d) { return a + b; } - function f(uint k) returns(uint d) { return k; } - function g(bool flag) returns(uint d) { - if (flag) - return f(3); - else - return f(3, 7); - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK(callContractFunction("g(bool)", true) == encodeArgs(3)); - BOOST_CHECK(callContractFunction("g(bool)", false) == encodeArgs(10)); -} - -BOOST_AUTO_TEST_CASE(derived_overload_base_function_direct) -{ - char const* sourceCode = R"( - contract B { function f() returns(uint) { return 10; } } - contract C is B { - function f(uint i) returns(uint) { return 2 * i; } - function g() returns(uint) { return f(1); } - } - )"; - compileAndRun(sourceCode, 0, "C"); - BOOST_CHECK(callContractFunction("g()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(derived_overload_base_function_indirect) -{ - char const* sourceCode = R"( - contract A { function f(uint a) returns(uint) { return 2 * a; } } - contract B { function f() returns(uint) { return 10; } } - contract C is A, B { - function g() returns(uint) { return f(); } - function h() returns(uint) { return f(1); } - } - )"; - compileAndRun(sourceCode, 0, "C"); - BOOST_CHECK(callContractFunction("g()") == encodeArgs(10)); - BOOST_CHECK(callContractFunction("h()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(super_overload) -{ - char const* sourceCode = R"( - contract A { function f(uint a) returns(uint) { return 2 * a; } } - contract B { function f(bool b) returns(uint) { return 10; } } - contract C is A, B { - function g() returns(uint) { return super.f(true); } - function h() returns(uint) { return super.f(1); } - } - )"; - compileAndRun(sourceCode, 0, "C"); - BOOST_CHECK(callContractFunction("g()") == encodeArgs(10)); - BOOST_CHECK(callContractFunction("h()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(packed_storage_signed) -{ - char const* sourceCode = R"( - contract C { - int8 a; - uint8 b; - int8 c; - uint8 d; - function test() returns (uint x1, uint x2, uint x3, uint x4) { - a = -2; - b = -uint8(a) * 2; - c = a * int8(120) * int8(121); - x1 = uint(a); - x2 = b; - x3 = uint(c); - x4 = d; - } - } - )"; - compileAndRun(sourceCode); - BOOST_CHECK( callContractFunction("test()") == encodeArgs(u256(-2), u256(4), u256(-112), u256(0))); -} - -BOOST_AUTO_TEST_CASE(external_types_in_calls) -{ - char const* sourceCode = R"( - contract C1 { C1 public bla; function C1(C1 x) { bla = x; } } - contract C { - function test() returns (C1 x, C1 y) { - C1 c = new C1(C1(9)); - x = c.bla(); - y = this.t1(C1(7)); - } - function t1(C1 a) returns (C1) { return a; } - function() returns (C1) { return C1(9); } - } - )"; - compileAndRun(sourceCode, 0, "C"); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(u256(9), u256(7))); - BOOST_CHECK(callContractFunction("nonexisting") == encodeArgs(u256(9))); -} - -BOOST_AUTO_TEST_CASE(proper_order_of_overwriting_of_attributes) -{ - // bug #1798 - char const* sourceCode = R"( - contract init { - function isOk() returns (bool) { return false; } - bool public ok = false; - } - contract fix { - function isOk() returns (bool) { return true; } - bool public ok = true; - } - - contract init_fix is init, fix { - function checkOk() returns (bool) { return ok; } - } - contract fix_init is fix, init { - function checkOk() returns (bool) { return ok; } - } - )"; - compileAndRun(sourceCode, 0, "init_fix"); - BOOST_CHECK(callContractFunction("isOk()") == encodeArgs(true)); - BOOST_CHECK(callContractFunction("ok()") == encodeArgs(true)); - - compileAndRun(sourceCode, 0, "fix_init"); - BOOST_CHECK(callContractFunction("isOk()") == encodeArgs(false)); - BOOST_CHECK(callContractFunction("ok()") == encodeArgs(false)); -} - -BOOST_AUTO_TEST_CASE(proper_overwriting_accessor_by_function) -{ - // bug #1798 - char const* sourceCode = R"( - contract attribute { - bool ok = false; - } - contract func { - function ok() returns (bool) { return true; } - } - - contract attr_func is attribute, func { - function checkOk() returns (bool) { return ok(); } - } - contract func_attr is func, attribute { - function checkOk() returns (bool) { return ok; } - } - )"; - compileAndRun(sourceCode, 0, "attr_func"); - BOOST_CHECK(callContractFunction("ok()") == encodeArgs(true)); - compileAndRun(sourceCode, 0, "func_attr"); - BOOST_CHECK(callContractFunction("checkOk()") == encodeArgs(false)); -} - - -BOOST_AUTO_TEST_CASE(overwriting_inheritance) -{ - // bug #1798 - char const* sourceCode = R"( - contract A { - function ok() returns (uint) { return 1; } - } - contract B { - function ok() returns (uint) { return 2; } - } - contract C { - uint ok = 6; - } - contract AB is A, B { - function ok() returns (uint) { return 4; } - } - contract reversedE is C, AB { - function checkOk() returns (uint) { return ok(); } - } - contract E is AB, C { - function checkOk() returns (uint) { return ok; } - } - )"; - compileAndRun(sourceCode, 0, "reversedE"); - BOOST_CHECK(callContractFunction("checkOk()") == encodeArgs(4)); - compileAndRun(sourceCode, 0, "E"); - BOOST_CHECK(callContractFunction("checkOk()") == encodeArgs(6)); -} - -BOOST_AUTO_TEST_CASE(struct_assign_reference_to_struct) -{ - char const* sourceCode = R"( - contract test { - struct testStruct - { - uint m_value; - } - testStruct data1; - testStruct data2; - testStruct data3; - function test() - { - data1.m_value = 2; - } - function assign() returns (uint ret_local, uint ret_global, uint ret_global3, uint ret_global1) - { - testStruct x = data1; //x is a reference data1.m_value == 2 as well as x.m_value = 2 - data2 = data1; // should copy data. data2.m_value == 2 - - ret_local = x.m_value; // = 2 - ret_global = data2.m_value; // = 2 - - x.m_value = 3; - data3 = x; //should copy the data. data3.m_value == 3 - ret_global3 = data3.m_value; // = 3 - ret_global1 = data1.m_value; // = 3. Changed due to the assignment to x.m_value - } - } - )"; - compileAndRun(sourceCode, 0, "test"); - BOOST_CHECK(callContractFunction("assign()") == encodeArgs(2, 2, 3, 3)); -} - -BOOST_AUTO_TEST_CASE(struct_delete_member) -{ - char const* sourceCode = R"( - contract test { - struct testStruct - { - uint m_value; - } - testStruct data1; - function test() - { - data1.m_value = 2; - } - function deleteMember() returns (uint ret_value) - { - testStruct x = data1; //should not copy the data. data1.m_value == 2 but x.m_value = 0 - x.m_value = 4; - delete x.m_value; - ret_value = data1.m_value; - } - } - )"; - compileAndRun(sourceCode, 0, "test"); - BOOST_CHECK(callContractFunction("deleteMember()") == encodeArgs(0)); -} - -BOOST_AUTO_TEST_CASE(struct_delete_struct_in_mapping) -{ - char const* sourceCode = R"( - contract test { - struct testStruct - { - uint m_value; - } - mapping (uint => testStruct) campaigns; - - function test() - { - campaigns[0].m_value = 2; - } - function deleteIt() returns (uint) - { - delete campaigns[0]; - return campaigns[0].m_value; - } - } - )"; - compileAndRun(sourceCode, 0, "test"); - BOOST_CHECK(callContractFunction("deleteIt()") == encodeArgs(0)); -} - -BOOST_AUTO_TEST_CASE(evm_exceptions_out_of_band_access) -{ - char const* sourceCode = R"( - contract A { - uint[3] arr; - bool public test = false; - function getElement(uint i) returns (uint) - { - return arr[i]; - } - function testIt() returns (bool) - { - uint i = this.getElement(5); - test = true; - return true; - } - } - )"; - compileAndRun(sourceCode, 0, "A"); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(false)); - BOOST_CHECK(callContractFunction("testIt()") == encodeArgs()); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(false)); -} - -BOOST_AUTO_TEST_CASE(evm_exceptions_in_constructor_call_fail) -{ - char const* sourceCode = R"( - contract A { - function A() - { - this.call("123"); - } - } - contract B { - uint public test = 1; - function testIt() - { - A a = new A(); - ++test; - } - } - )"; - compileAndRun(sourceCode, 0, "B"); - - BOOST_CHECK(callContractFunction("testIt()") == encodeArgs()); - BOOST_CHECK(callContractFunction("test()") == encodeArgs(2)); -} - -BOOST_AUTO_TEST_CASE(evm_exceptions_in_constructor_out_of_baund) -{ - char const* sourceCode = R"( - contract A { - uint public test = 1; - uint[3] arr; - function A() - { - test = arr[5]; - ++test; - } - } - )"; - BOOST_CHECK(compileAndRunWithoutCheck(sourceCode, 0, "A").empty()); -} - -BOOST_AUTO_TEST_CASE(positive_integers_to_signed) -{ - char const* sourceCode = R"( - contract test { - int8 public x = 2; - int8 public y = 127; - int16 public q = 250; - } - )"; - compileAndRun(sourceCode, 0, "test"); - BOOST_CHECK(callContractFunction("x()") == encodeArgs(2)); - BOOST_CHECK(callContractFunction("y()") == encodeArgs(127)); - BOOST_CHECK(callContractFunction("q()") == encodeArgs(250)); -} - -BOOST_AUTO_TEST_CASE(failing_send) -{ - char const* sourceCode = R"( - contract Helper { - uint[] data; - function () { - data[9]; // trigger exception - } - } - contract Main { - function callHelper(address _a) returns (bool r, uint bal) { - r = !_a.send(5); - bal = this.balance; - } - } - )"; - compileAndRun(sourceCode, 0, "Helper"); - u160 const c_helperAddress = m_contractAddress; - compileAndRun(sourceCode, 20, "Main"); - BOOST_REQUIRE(callContractFunction("callHelper(address)", c_helperAddress) == encodeArgs(true, 20)); -} - -BOOST_AUTO_TEST_CASE(reusing_memory) -{ - // Invoke some features that use memory and test that they do not interfere with each other. - char const* sourceCode = R"( - contract Helper { - uint public flag; - function Helper(uint x) { - flag = x; - } - } - contract Main { - mapping(uint => uint) map; - function f(uint x) returns (uint) { - map[x] = x; - return (new Helper(uint(sha3(this.g(map[x]))))).flag(); - } - function g(uint a) returns (uint) - { - return map[a]; - } - } - )"; - compileAndRun(sourceCode, 0, "Main"); - BOOST_REQUIRE(callContractFunction("f(uint256)", 0x34) == encodeArgs(dev::sha3(dev::toBigEndian(u256(0x34))))); -} - -BOOST_AUTO_TEST_CASE(return_string) -{ - char const* sourceCode = R"( - contract Main { - string public s; - function set(string _s) external { - s = _s; - } - function get1() returns (string r) { - return s; - } - function get2() returns (string r) { - r = s; - } - } - )"; - compileAndRun(sourceCode, 0, "Main"); - string s("Julia"); - bytes args = encodeArgs(u256(0x20), u256(s.length()), s); - BOOST_REQUIRE(callContractFunction("set(string)", asString(args)) == encodeArgs()); - BOOST_CHECK(callContractFunction("get1()") == args); - BOOST_CHECK(callContractFunction("get2()") == args); - BOOST_CHECK(callContractFunction("s()") == args); -} - -BOOST_AUTO_TEST_CASE(return_multiple_strings_of_various_sizes) -{ - char const* sourceCode = R"( - contract Main { - string public s1; - string public s2; - function set(string _s1, uint x, string _s2) external returns (uint) { - s1 = _s1; - s2 = _s2; - return x; - } - function get() returns (string r1, string r2) { - r1 = s1; - r2 = s2; - } - } - )"; - compileAndRun(sourceCode, 0, "Main"); - string s1( - "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" - ); - string s2( - "ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ" - "ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ" - "ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ" - "ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ" - "ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ" - ); - vector lengthes{0, 30, 32, 63, 64, 65, 210, 300}; - for (auto l1: lengthes) - for (auto l2: lengthes) - { - bytes dyn1 = encodeArgs(u256(l1), s1.substr(0, l1)); - bytes dyn2 = encodeArgs(u256(l2), s2.substr(0, l2)); - bytes args = encodeArgs(u256(0x60), u256(l1), u256(0x60 + dyn1.size())) + dyn1 + dyn2; - BOOST_REQUIRE( - callContractFunction("set(string,uint256,string)", asString(args)) == - encodeArgs(u256(l1)) - ); - bytes result = encodeArgs(u256(0x40), u256(0x40 + dyn1.size())) + dyn1 + dyn2; - BOOST_CHECK(callContractFunction("get()") == result); - BOOST_CHECK(callContractFunction("s1()") == encodeArgs(0x20) + dyn1); - BOOST_CHECK(callContractFunction("s2()") == encodeArgs(0x20) + dyn2); - } -} - -BOOST_AUTO_TEST_CASE(accessor_involving_strings) -{ - char const* sourceCode = R"( - contract Main { - struct stringData { string a; uint b; string c; } - mapping(uint => stringData[]) public data; - function set(uint x, uint y, string a, uint b, string c) external returns (bool) { - data[x].length = y + 1; - data[x][y].a = a; - data[x][y].b = b; - data[x][y].c = c; - return true; - } - } - )"; - compileAndRun(sourceCode, 0, "Main"); - string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); - string s2("ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ"); - bytes s1Data = encodeArgs(u256(s1.length()), s1); - bytes s2Data = encodeArgs(u256(s2.length()), s2); - u256 b = 765; - u256 x = 7; - u256 y = 123; - bytes args = encodeArgs(x, y, u256(0xa0), b, u256(0xa0 + s1Data.size()), s1Data, s2Data); - bytes result = encodeArgs(u256(0x60), b, u256(0x60 + s1Data.size()), s1Data, s2Data); - BOOST_REQUIRE(callContractFunction("set(uint256,uint256,string,uint256,string)", asString(args)) == encodeArgs(true)); - BOOST_REQUIRE(callContractFunction("data(uint256,uint256)", x, y) == result); -} - -BOOST_AUTO_TEST_CASE(bytes_in_function_calls) -{ - char const* sourceCode = R"( - contract Main { - string public s1; - string public s2; - function set(string _s1, uint x, string _s2) returns (uint) { - s1 = _s1; - s2 = _s2; - return x; - } - function setIndirectFromMemory(string _s1, uint x, string _s2) returns (uint) { - return this.set(_s1, x, _s2); - } - function setIndirectFromCalldata(string _s1, uint x, string _s2) external returns (uint) { - return this.set(_s1, x, _s2); - } - } - )"; - compileAndRun(sourceCode, 0, "Main"); - string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); - string s2("ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ"); - vector lengthes{0, 31, 64, 65}; - for (auto l1: lengthes) - for (auto l2: lengthes) - { - bytes dyn1 = encodeArgs(u256(l1), s1.substr(0, l1)); - bytes dyn2 = encodeArgs(u256(l2), s2.substr(0, l2)); - bytes args1 = encodeArgs(u256(0x60), u256(l1), u256(0x60 + dyn1.size())) + dyn1 + dyn2; - BOOST_REQUIRE( - callContractFunction("setIndirectFromMemory(string,uint256,string)", asString(args1)) == - encodeArgs(u256(l1)) - ); - BOOST_CHECK(callContractFunction("s1()") == encodeArgs(0x20) + dyn1); - BOOST_CHECK(callContractFunction("s2()") == encodeArgs(0x20) + dyn2); - // swapped - bytes args2 = encodeArgs(u256(0x60), u256(l1), u256(0x60 + dyn2.size())) + dyn2 + dyn1; - BOOST_REQUIRE( - callContractFunction("setIndirectFromCalldata(string,uint256,string)", asString(args2)) == - encodeArgs(u256(l1)) - ); - BOOST_CHECK(callContractFunction("s1()") == encodeArgs(0x20) + dyn2); - BOOST_CHECK(callContractFunction("s2()") == encodeArgs(0x20) + dyn1); - } -} - -BOOST_AUTO_TEST_CASE(return_bytes_internal) -{ - char const* sourceCode = R"( - contract Main { - bytes s1; - function doSet(bytes _s1) returns (bytes _r1) { - s1 = _s1; - _r1 = s1; - } - function set(bytes _s1) external returns (uint _r, bytes _r1) { - _r1 = doSet(_s1); - _r = _r1.length; - } - } - )"; - compileAndRun(sourceCode, 0, "Main"); - string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); - vector lengthes{0, 31, 64, 65}; - for (auto l1: lengthes) - { - bytes dyn1 = encodeArgs(u256(l1), s1.substr(0, l1)); - bytes args1 = encodeArgs(u256(0x20)) + dyn1; - BOOST_REQUIRE( - callContractFunction("set(bytes)", asString(args1)) == - encodeArgs(u256(l1), u256(0x40)) + dyn1 - ); - } -} - -BOOST_AUTO_TEST_CASE(bytes_index_access_memory) -{ - char const* sourceCode = R"( - contract Main { - function f(bytes _s1, uint i1, uint i2, uint i3) returns (byte c1, byte c2, byte c3) { - c1 = _s1[i1]; - c2 = intern(_s1, i2); - c3 = internIndirect(_s1)[i3]; - } - function intern(bytes _s1, uint i) returns (byte c) { - return _s1[i]; - } - function internIndirect(bytes _s1) returns (bytes) { - return _s1; - } - } - )"; - compileAndRun(sourceCode, 0, "Main"); - string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); - bytes dyn1 = encodeArgs(u256(s1.length()), s1); - bytes args1 = encodeArgs(u256(0x80), u256(3), u256(4), u256(5)) + dyn1; - BOOST_REQUIRE( - callContractFunction("f(bytes,uint256,uint256,uint256)", asString(args1)) == - encodeArgs(string{s1[3]}, string{s1[4]}, string{s1[5]}) - ); -} - -BOOST_AUTO_TEST_CASE(bytes_in_constructors_unpacker) -{ - char const* sourceCode = R"( - contract Test { - uint public m_x; - bytes public m_s; - function Test(uint x, bytes s) { - m_x = x; - m_s = s; - } - } - )"; - string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); - bytes dyn1 = encodeArgs(u256(s1.length()), s1); - u256 x = 7; - bytes args1 = encodeArgs(x, u256(0x40)) + dyn1; - compileAndRun(sourceCode, 0, "Test", args1); - BOOST_REQUIRE(callContractFunction("m_x()") == encodeArgs(x)); - BOOST_REQUIRE(callContractFunction("m_s()") == encodeArgs(u256(0x20)) + dyn1); -} - -BOOST_AUTO_TEST_CASE(bytes_in_constructors_packer) -{ - char const* sourceCode = R"( - contract Base { - uint public m_x; - bytes m_s; - function Base(uint x, bytes s) { - m_x = x; - m_s = s; - } - function part(uint i) returns (byte) { - return m_s[i]; - } - } - contract Main is Base { - function Main(bytes s, uint x) Base(x, f(s)) {} - function f(bytes s) returns (bytes) { - return s; - } - } - contract Creator { - function f(uint x, bytes s) returns (uint r, byte ch) { - var c = new Main(s, x); - r = c.m_x(); - ch = c.part(x); - } - } - )"; - compileAndRun(sourceCode, 0, "Creator"); - string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); - bytes dyn1 = encodeArgs(u256(s1.length()), s1); - u256 x = 7; - bytes args1 = encodeArgs(x, u256(0x40)) + dyn1; - BOOST_REQUIRE( - callContractFunction("f(uint256,bytes)", asString(args1)) == - encodeArgs(x, string{s1[unsigned(x)]}) - ); -} - -BOOST_AUTO_TEST_CASE(arrays_in_constructors) -{ - char const* sourceCode = R"( - contract Base { - uint public m_x; - address[] m_s; - function Base(uint x, address[] s) { - m_x = x; - m_s = s; - } - function part(uint i) returns (address) { - return m_s[i]; - } - } - contract Main is Base { - function Main(address[] s, uint x) Base(x, f(s)) {} - function f(address[] s) returns (address[]) { - return s; - } - } - contract Creator { - function f(uint x, address[] s) returns (uint r, address ch) { - var c = new Main(s, x); - r = c.m_x(); - ch = c.part(x); - } - } - )"; - compileAndRun(sourceCode, 0, "Creator"); - vector s1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - bytes dyn1 = encodeArgs(u256(s1.size()), s1); - u256 x = 7; - bytes args1 = encodeArgs(x, u256(0x40)) + dyn1; - BOOST_REQUIRE( - callContractFunction("f(uint256,address[])", asString(args1)) == - encodeArgs(x, s1[unsigned(x)]) - ); -} - -BOOST_AUTO_TEST_CASE(arrays_from_and_to_storage) -{ - char const* sourceCode = R"( - contract Test { - uint24[] public data; - function set(uint24[] _data) returns (uint) { - data = _data; - return data.length; - } - function get() returns (uint24[]) { - return data; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - vector data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}; - BOOST_REQUIRE( - callContractFunction("set(uint24[])", u256(0x20), u256(data.size()), data) == - encodeArgs(u256(data.size())) - ); - BOOST_CHECK(callContractFunction("data(uint256)", u256(7)) == encodeArgs(u256(8))); - BOOST_CHECK(callContractFunction("data(uint256)", u256(15)) == encodeArgs(u256(16))); - BOOST_CHECK(callContractFunction("data(uint256)", u256(18)) == encodeArgs()); - BOOST_CHECK(callContractFunction("get()") == encodeArgs(u256(0x20), u256(data.size()), data)); -} - -BOOST_AUTO_TEST_CASE(arrays_complex_from_and_to_storage) -{ - char const* sourceCode = R"( - contract Test { - uint24[3][] public data; - function set(uint24[3][] _data) returns (uint) { - data = _data; - return data.length; - } - function get() returns (uint24[3][]) { - return data; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - vector data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}; - BOOST_REQUIRE( - callContractFunction("set(uint24[3][])", u256(0x20), u256(data.size() / 3), data) == - encodeArgs(u256(data.size() / 3)) - ); - BOOST_CHECK(callContractFunction("data(uint256,uint256)", u256(2), u256(2)) == encodeArgs(u256(9))); - BOOST_CHECK(callContractFunction("data(uint256,uint256)", u256(5), u256(1)) == encodeArgs(u256(17))); - BOOST_CHECK(callContractFunction("data(uint256,uint256)", u256(6), u256(0)) == encodeArgs()); - BOOST_CHECK(callContractFunction("get()") == encodeArgs(u256(0x20), u256(data.size() / 3), data)); -} - -BOOST_AUTO_TEST_CASE(arrays_complex_memory_index_access) -{ - char const* sourceCode = R"( - contract Test { - function set(uint24[3][] _data, uint a, uint b) returns (uint l, uint e) { - l = _data.length; - e = _data[a][b]; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - vector data{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}; - BOOST_REQUIRE(callContractFunction( - "set(uint24[3][],uint256,uint256)", - u256(0x60), - u256(3), - u256(2), - u256(data.size() / 3), - data - ) == encodeArgs(u256(data.size() / 3), u256(data[3 * 3 + 2]))); -} - -BOOST_AUTO_TEST_CASE(bytes_memory_index_access) -{ - char const* sourceCode = R"( - contract Test { - function set(bytes _data, uint i) returns (uint l, byte c) { - l = _data.length; - c = _data[i]; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - string data("abcdefgh"); - BOOST_REQUIRE(callContractFunction( - "set(bytes,uint256)", - u256(0x40), - u256(3), - u256(data.size()), - data - ) == encodeArgs(u256(data.size()), string("d"))); -} - -BOOST_AUTO_TEST_CASE(dev_title_at_function_error) -{ - char const* sourceCode = " /// @author Lefteris\n" - " /// @title Just a test contract\n" - "contract test {\n" - " /// @dev Mul function\n" - " /// @title I really should not be here\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - compileRequireThrow(sourceCode); -} - -BOOST_AUTO_TEST_CASE(dev_documenting_nonexistant_param) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter\n" - " /// @param not_existing Documentation for the second parameter\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - compileRequireThrow(sourceCode); -} - - -BOOST_AUTO_TEST_CASE(storage_array_ref) -{ - char const* sourceCode = R"( - contract BinarySearch { - /// Finds the position of _value in the sorted list _data. - /// Note that "internal" is important here, because storage references only work for internal or private functions - function find(uint[] storage _data, uint _value) internal returns (uint o_position) { - return find(_data, 0, _data.length, _value); - } - function find(uint[] storage _data, uint _begin, uint _len, uint _value) private returns (uint o_position) { - if (_len == 0 || (_len == 1 && _data[_begin] != _value)) - return uint(-1); // failure - uint halfLen = _len / 2; - uint v = _data[_begin + halfLen]; - if (_value < v) - return find(_data, _begin, halfLen, _value); - else if (_value > v) - return find(_data, _begin + halfLen + 1, halfLen - 1, _value); - else - return _begin + halfLen; - } - } - - contract Store is BinarySearch { - uint[] data; - function add(uint v) { - data.length++; - data[data.length - 1] = v; - } - function find(uint v) returns (uint) { - return find(data, v); - } - } - )"; - compileAndRun(sourceCode, 0, "Store"); - BOOST_REQUIRE(callContractFunction("find(uint256)", u256(7)) == encodeArgs(u256(-1))); - BOOST_REQUIRE(callContractFunction("add(uint256)", u256(7)) == encodeArgs()); - BOOST_REQUIRE(callContractFunction("find(uint256)", u256(7)) == encodeArgs(u256(0))); - BOOST_CHECK(callContractFunction("add(uint256)", u256(11)) == encodeArgs()); - BOOST_CHECK(callContractFunction("add(uint256)", u256(17)) == encodeArgs()); - BOOST_CHECK(callContractFunction("add(uint256)", u256(27)) == encodeArgs()); - BOOST_CHECK(callContractFunction("add(uint256)", u256(31)) == encodeArgs()); - BOOST_CHECK(callContractFunction("add(uint256)", u256(32)) == encodeArgs()); - BOOST_CHECK(callContractFunction("add(uint256)", u256(66)) == encodeArgs()); - BOOST_CHECK(callContractFunction("add(uint256)", u256(177)) == encodeArgs()); - BOOST_CHECK(callContractFunction("find(uint256)", u256(7)) == encodeArgs(u256(0))); - BOOST_CHECK(callContractFunction("find(uint256)", u256(27)) == encodeArgs(u256(3))); - BOOST_CHECK(callContractFunction("find(uint256)", u256(32)) == encodeArgs(u256(5))); - BOOST_CHECK(callContractFunction("find(uint256)", u256(176)) == encodeArgs(u256(-1))); - BOOST_CHECK(callContractFunction("find(uint256)", u256(0)) == encodeArgs(u256(-1))); - BOOST_CHECK(callContractFunction("find(uint256)", u256(400)) == encodeArgs(u256(-1))); -} - -BOOST_AUTO_TEST_CASE(memory_types_initialisation) -{ - char const* sourceCode = R"( - contract Test { - mapping(uint=>uint) data; - function stat() returns (uint[5]) - { - data[2] = 3; // make sure to use some memory - } - function dyn() returns (uint[]) { stat(); } - function nested() returns (uint[3][]) { stat(); } - function nestedStat() returns (uint[3][7]) { stat(); } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - BOOST_CHECK(callContractFunction("stat()") == encodeArgs(vector(5))); - BOOST_CHECK(callContractFunction("dyn()") == encodeArgs(u256(0x20), u256(0))); - BOOST_CHECK(callContractFunction("nested()") == encodeArgs(u256(0x20), u256(0))); - BOOST_CHECK(callContractFunction("nestedStat()") == encodeArgs(vector(3 * 7))); -} - -BOOST_AUTO_TEST_CASE(memory_arrays_delete) -{ - char const* sourceCode = R"( - contract Test { - function del() returns (uint24[3][4]) { - uint24[3][4] memory x; - for (uint24 i = 0; i < x.length; i ++) - for (uint24 j = 0; j < x[i].length; j ++) - x[i][j] = i * 0x10 + j; - delete x[1]; - delete x[3][2]; - return x; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - vector data(3 * 4); - for (unsigned i = 0; i < 4; i++) - for (unsigned j = 0; j < 3; j++) - { - u256 v = 0; - if (!(i == 1 || (i == 3 && j == 2))) - v = i * 0x10 + j; - data[i * 3 + j] = v; - } - BOOST_CHECK(callContractFunction("del()") == encodeArgs(data)); -} - -BOOST_AUTO_TEST_CASE(memory_arrays_index_access_write) -{ - char const* sourceCode = R"( - contract Test { - function set(uint24[3][4] x) { - x[2][2] = 1; - x[3][2] = 7; - } - function f() returns (uint24[3][4]){ - uint24[3][4] memory data; - set(data); - return data; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - vector data(3 * 4); - data[3 * 2 + 2] = 1; - data[3 * 3 + 2] = 7; - BOOST_CHECK(callContractFunction("f()") == encodeArgs(data)); -} - -BOOST_AUTO_TEST_CASE(memory_arrays_dynamic_index_access_write) -{ - char const* sourceCode = R"( - contract Test { - uint24[3][][4] data; - function set(uint24[3][][4] x) internal returns (uint24[3][][4]) { - x[1][2][2] = 1; - x[1][3][2] = 7; - return x; - } - function f() returns (uint24[3][]) { - data[1].length = 4; - return set(data)[1]; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - vector data(3 * 4); - data[3 * 2 + 2] = 1; - data[3 * 3 + 2] = 7; - BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(0x20), u256(4), data)); -} - -BOOST_AUTO_TEST_CASE(memory_structs_read_write) -{ - char const* sourceCode = R"( - contract Test { - struct S { uint8 x; uint16 y; uint z; uint8[2] a; } - S[5] data; - function testInit() returns (uint8 x, uint16 y, uint z, uint8 a, bool flag) { - S[2] memory d; - x = d[0].x; - y = d[0].y; - z = d[0].z; - a = d[0].a[1]; - flag = true; - } - function testCopyRead() returns (uint8 x, uint16 y, uint z, uint8 a) { - data[2].x = 1; - data[2].y = 2; - data[2].z = 3; - data[2].a[1] = 4; - S memory s = data[2]; - x = s.x; - y = s.y; - z = s.z; - a = s.a[1]; - } - function testAssign() returns (uint8 x, uint16 y, uint z, uint8 a) { - S memory s; - s.x = 1; - s.y = 2; - s.z = 3; - s.a[1] = 4; - x = s.x; - y = s.y; - z = s.z; - a = s.a[1]; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - BOOST_CHECK(callContractFunction("testInit()") == encodeArgs(u256(0), u256(0), u256(0), u256(0), true)); - BOOST_CHECK(callContractFunction("testCopyRead()") == encodeArgs(u256(1), u256(2), u256(3), u256(4))); - BOOST_CHECK(callContractFunction("testAssign()") == encodeArgs(u256(1), u256(2), u256(3), u256(4))); -} - -BOOST_AUTO_TEST_CASE(memory_structs_as_function_args) -{ - char const* sourceCode = R"( - contract Test { - struct S { uint8 x; uint16 y; uint z; } - function test() returns (uint x, uint y, uint z) { - S memory data = combine(1, 2, 3); - x = extract(data, 0); - y = extract(data, 1); - z = extract(data, 2); - } - function extract(S s, uint which) internal returns (uint x) { - if (which == 0) return s.x; - else if (which == 1) return s.y; - else return s.z; - } - function combine(uint8 x, uint16 y, uint z) internal returns (S s) { - s.x = x; - s.y = y; - s.z = z; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - BOOST_CHECK(callContractFunction("test()") == encodeArgs(u256(1), u256(2), u256(3))); -} - -BOOST_AUTO_TEST_CASE(memory_structs_nested) -{ - char const* sourceCode = R"( - contract Test { - struct S { uint8 x; uint16 y; uint z; } - struct X { uint8 x; S s; } - function test() returns (uint a, uint x, uint y, uint z) { - X memory d = combine(1, 2, 3, 4); - a = extract(d, 0); - x = extract(d, 1); - y = extract(d, 2); - z = extract(d, 3); - } - function extract(X s, uint which) internal returns (uint x) { - if (which == 0) return s.x; - else if (which == 1) return s.s.x; - else if (which == 2) return s.s.y; - else return s.s.z; - } - function combine(uint8 a, uint8 x, uint16 y, uint z) internal returns (X s) { - s.x = a; - s.s.x = x; - s.s.y = y; - s.s.z = z; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - BOOST_CHECK(callContractFunction("test()") == encodeArgs(u256(1), u256(2), u256(3), u256(4))); -} - -BOOST_AUTO_TEST_CASE(memory_structs_nested_load) -{ - char const* sourceCode = R"( - contract Test { - struct S { uint8 x; uint16 y; uint z; } - struct X { uint8 x; S s; uint8[2] a; } - X m_x; - function load() returns (uint a, uint x, uint y, uint z, uint a1, uint a2) { - m_x.x = 1; - m_x.s.x = 2; - m_x.s.y = 3; - m_x.s.z = 4; - m_x.a[0] = 5; - m_x.a[1] = 6; - X memory d = m_x; - a = d.x; - x = d.s.x; - y = d.s.y; - z = d.s.z; - a1 = d.a[0]; - a2 = d.a[1]; - } - function store() returns (uint a, uint x, uint y, uint z, uint a1, uint a2) { - X memory d; - d.x = 1; - d.s.x = 2; - d.s.y = 3; - d.s.z = 4; - d.a[0] = 5; - d.a[1] = 6; - m_x = d; - a = m_x.x; - x = m_x.s.x; - y = m_x.s.y; - z = m_x.s.z; - a1 = m_x.a[0]; - a2 = m_x.a[1]; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - - auto out = encodeArgs(u256(1), u256(2), u256(3), u256(4), u256(5), u256(6)); - BOOST_CHECK(callContractFunction("load()") == out); - BOOST_CHECK(callContractFunction("store()") == out); -} - -BOOST_AUTO_TEST_CASE(struct_constructor_nested) -{ - char const* sourceCode = R"( - contract C { - struct X { uint x1; uint x2; } - struct S { uint s1; uint[3] s2; X s3; } - S s; - function C() { - uint[3] memory s2; - s2[1] = 9; - s = S(1, s2, X(4, 5)); - } - function get() returns (uint s1, uint[3] s2, uint x1, uint x2) - { - s1 = s.s1; - s2 = s.s2; - x1 = s.s3.x1; - x2 = s.s3.x2; - } - } - )"; - compileAndRun(sourceCode, 0, "C"); - - auto out = encodeArgs(u256(1), u256(0), u256(9), u256(0), u256(4), u256(5)); - BOOST_CHECK(callContractFunction("get()") == out); -} - -BOOST_AUTO_TEST_CASE(struct_named_constructor) -{ - char const* sourceCode = R"( - contract C { - struct S { uint a; bool x; } - S public s; - function C() { - s = S({a: 1, x: true}); - } - } - )"; - compileAndRun(sourceCode, 0, "C"); - - BOOST_CHECK(callContractFunction("s()") == encodeArgs(u256(1), true)); -} - -BOOST_AUTO_TEST_CASE(literal_strings) -{ - char const* sourceCode = R"( - contract Test { - string public long; - string public medium; - string public short; - string public empty; - function f() returns (string) { - long = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; - medium = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; - short = "123"; - empty = ""; - return "Hello, World!"; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - string longStr = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; - string medium = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; - string shortStr = "123"; - string hello = "Hello, World!"; - - BOOST_CHECK(callContractFunction("f()") == encodeDyn(hello)); - BOOST_CHECK(callContractFunction("long()") == encodeDyn(longStr)); - BOOST_CHECK(callContractFunction("medium()") == encodeDyn(medium)); - BOOST_CHECK(callContractFunction("short()") == encodeDyn(shortStr)); - BOOST_CHECK(callContractFunction("empty()") == encodeDyn(string())); -} - -BOOST_AUTO_TEST_CASE(initialise_string_constant) -{ - char const* sourceCode = R"( - contract Test { - string public short = "abcdef"; - string public long = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; - } - )"; - compileAndRun(sourceCode, 0, "Test"); - string longStr = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; - string shortStr = "abcdef"; - - BOOST_CHECK(callContractFunction("long()") == encodeDyn(longStr)); - BOOST_CHECK(callContractFunction("short()") == encodeDyn(shortStr)); -} - -BOOST_AUTO_TEST_CASE(memory_structs_with_mappings) -{ - char const* sourceCode = R"( - contract Test { - struct S { uint8 a; mapping(uint => uint) b; uint8 c; } - S s; - function f() returns (uint) { - S memory x; - if (x.a != 0 || x.c != 0) return 1; - x.a = 4; x.c = 5; - s = x; - if (s.a != 4 || s.c != 5) return 2; - x = S(2, 3); - if (x.a != 2 || x.c != 3) return 3; - x = s; - if (s.a != 4 || s.c != 5) return 4; - } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(0))); -} - -BOOST_AUTO_TEST_CASE(string_bytes_conversion) -{ - char const* sourceCode = R"( - contract Test { - string s; - bytes b; - function f(string _s, uint n) returns (byte) { - b = bytes(_s); - s = string(b); - return bytes(s)[n]; - } - function l() returns (uint) { return bytes(s).length; } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - BOOST_CHECK(callContractFunction( - "f(string,uint256)", - u256(0x40), - u256(2), - u256(6), - string("abcdef") - ) == encodeArgs("c")); - BOOST_CHECK(callContractFunction("l()") == encodeArgs(u256(6))); -} - -BOOST_AUTO_TEST_CASE(string_as_mapping_key) -{ - char const* sourceCode = R"( - contract Test { - mapping(string => uint) data; - function set(string _s, uint _v) { data[_s] = _v; } - function get(string _s) returns (uint) { return data[_s]; } - } - )"; - compileAndRun(sourceCode, 0, "Test"); - vector strings{ - "Hello, World!", - "Hello, World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1111", - "", - "1" - }; - for (unsigned i = 0; i < strings.size(); i++) - BOOST_CHECK(callContractFunction( - "set(string,uint256)", - u256(0x40), - u256(7 + i), - u256(strings[i].size()), - strings[i] - ) == encodeArgs()); - for (unsigned i = 0; i < strings.size(); i++) - BOOST_CHECK(callContractFunction( - "get(string)", - u256(0x20), - u256(strings[i].size()), - strings[i] - ) == encodeArgs(u256(7 + i))); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/SolidityExpressionCompiler.cpp b/test/libsolidity/SolidityExpressionCompiler.cpp deleted file mode 100644 index ee631197e..000000000 --- a/test/libsolidity/SolidityExpressionCompiler.cpp +++ /dev/null @@ -1,491 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Unit tests for the solidity expression compiler. - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include "../TestHelper.h" - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -namespace -{ - -/// Helper class that extracts the first expression in an AST. -class FirstExpressionExtractor: private ASTVisitor -{ -public: - FirstExpressionExtractor(ASTNode& _node): m_expression(nullptr) { _node.accept(*this); } - Expression* getExpression() const { return m_expression; } -private: - virtual bool visit(Assignment& _expression) override { return checkExpression(_expression); } - virtual bool visit(UnaryOperation& _expression) override { return checkExpression(_expression); } - virtual bool visit(BinaryOperation& _expression) override { return checkExpression(_expression); } - virtual bool visit(FunctionCall& _expression) override { return checkExpression(_expression); } - virtual bool visit(MemberAccess& _expression) override { return checkExpression(_expression); } - virtual bool visit(IndexAccess& _expression) override { return checkExpression(_expression); } - virtual bool visit(Identifier& _expression) override { return checkExpression(_expression); } - virtual bool visit(ElementaryTypeNameExpression& _expression) override { return checkExpression(_expression); } - virtual bool visit(Literal& _expression) override { return checkExpression(_expression); } - bool checkExpression(Expression& _expression) - { - if (m_expression == nullptr) - m_expression = &_expression; - return false; - } -private: - Expression* m_expression; -}; - -Declaration const& resolveDeclaration( - vector const& _namespacedName, NameAndTypeResolver const& _resolver) -{ - Declaration const* declaration = nullptr; - // bracers are required, cause msvc couldnt handle this macro in for statement - for (string const& namePart: _namespacedName) - { - auto declarations = _resolver.resolveName(namePart, declaration); - BOOST_REQUIRE(!declarations.empty()); - BOOST_REQUIRE(declaration = *declarations.begin()); - } - BOOST_REQUIRE(declaration); - return *declaration; -} - -bytes compileFirstExpression(const string& _sourceCode, vector> _functions = {}, - vector> _localVariables = {}, - vector> _globalDeclarations = {}) -{ - Parser parser; - ASTPointer sourceUnit; - try - { - sourceUnit = parser.parse(make_shared(CharStream(_sourceCode))); - } - catch(boost::exception const& _e) - { - auto msg = std::string("Parsing source code failed with: \n") + boost::diagnostic_information(_e); - BOOST_FAIL(msg); - } - - vector declarations; - declarations.reserve(_globalDeclarations.size() + 1); - for (ASTPointer const& variable: _globalDeclarations) - declarations.push_back(variable.get()); - NameAndTypeResolver resolver(declarations); - resolver.registerDeclarations(*sourceUnit); - - vector inheritanceHierarchy; - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - ETH_TEST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract), "Resolving names failed"); - inheritanceHierarchy = vector(1, contract); - } - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - ETH_TEST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract), "Checking type Requirements failed"); - } - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - FirstExpressionExtractor extractor(*contract); - BOOST_REQUIRE(extractor.getExpression() != nullptr); - - CompilerContext context; - context.resetVisitedNodes(contract); - context.setInheritanceHierarchy(inheritanceHierarchy); - unsigned parametersSize = _localVariables.size(); // assume they are all one slot on the stack - context.adjustStackOffset(parametersSize); - for (vector const& variable: _localVariables) - context.addVariable(dynamic_cast(resolveDeclaration(variable, resolver)), - parametersSize--); - - ExpressionCompiler(context).compile(*extractor.getExpression()); - - for (vector const& function: _functions) - context << context.getFunctionEntryLabel(dynamic_cast(resolveDeclaration(function, resolver))); - bytes instructions = context.getAssembledBytecode(); - // debug - // cout << eth::disassemble(instructions) << endl; - return instructions; - } - BOOST_FAIL("No contract found in source."); - return bytes(); -} - -} // end anonymous namespace - -BOOST_AUTO_TEST_SUITE(SolidityExpressionCompiler) - -BOOST_AUTO_TEST_CASE(literal_true) -{ - char const* sourceCode = "contract test {\n" - " function f() { var x = true; }" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH1), 0x1}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(literal_false) -{ - char const* sourceCode = "contract test {\n" - " function f() { var x = false; }" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH1), 0x0}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(int_literal) -{ - char const* sourceCode = "contract test {\n" - " function f() { var x = 0x12345678901234567890; }" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH10), 0x12, 0x34, 0x56, 0x78, 0x90, - 0x12, 0x34, 0x56, 0x78, 0x90}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(int_with_wei_ether_subdenomination) -{ - char const* sourceCode = R"( - contract test { - function test () - { - var x = 1 wei; - } - })"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH1), 0x1}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(int_with_szabo_ether_subdenomination) -{ - char const* sourceCode = R"( - contract test { - function test () - { - var x = 1 szabo; - } - })"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH5), 0xe8, 0xd4, 0xa5, 0x10, 0x00}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(int_with_finney_ether_subdenomination) -{ - char const* sourceCode = R"( - contract test { - function test () - { - var x = 1 finney; - } - })"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH7), 0x3, 0x8d, 0x7e, 0xa4, 0xc6, 0x80, 0x00}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(int_with_ether_ether_subdenomination) -{ - char const* sourceCode = R"( - contract test { - function test () - { - var x = 1 ether; - } - })"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH8), 0xd, 0xe0, 0xb6, 0xb3, 0xa7, 0x64, 0x00, 0x00}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(comparison) -{ - char const* sourceCode = "contract test {\n" - " function f() { var x = (0x10aa < 0x11aa) != true; }" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH1), 0x1, - byte(eth::Instruction::PUSH2), 0x11, 0xaa, - byte(eth::Instruction::PUSH2), 0x10, 0xaa, - byte(eth::Instruction::LT), - byte(eth::Instruction::EQ), - byte(eth::Instruction::ISZERO)}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(short_circuiting) -{ - char const* sourceCode = "contract test {\n" - " function f() { var x = true != (4 <= 8 + 10 || 9 != 2); }" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation({byte(eth::Instruction::PUSH1), 0x12, // 8 + 10 - byte(eth::Instruction::PUSH1), 0x4, - byte(eth::Instruction::GT), - byte(eth::Instruction::ISZERO), // after this we have 4 <= 8 + 10 - byte(eth::Instruction::DUP1), - byte(eth::Instruction::PUSH1), 0x11, - byte(eth::Instruction::JUMPI), // short-circuit if it is true - byte(eth::Instruction::POP), - byte(eth::Instruction::PUSH1), 0x2, - byte(eth::Instruction::PUSH1), 0x9, - byte(eth::Instruction::EQ), - byte(eth::Instruction::ISZERO), // after this we have 9 != 2 - byte(eth::Instruction::JUMPDEST), - byte(eth::Instruction::PUSH1), 0x1, - byte(eth::Instruction::EQ), - byte(eth::Instruction::ISZERO)}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(arithmetics) -{ - char const* sourceCode = "contract test {\n" - " function f(uint y) { var x = ((((((((y ^ 8) & 7) | 6) - 5) + 4) % 3) / 2) * 1); }" - "}\n"; - bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "y"}, {"test", "f", "x"}}); - bytes expectation({byte(eth::Instruction::PUSH1), 0x1, - byte(eth::Instruction::PUSH1), 0x2, - byte(eth::Instruction::PUSH1), 0x3, - byte(eth::Instruction::PUSH1), 0x4, - byte(eth::Instruction::PUSH1), 0x5, - byte(eth::Instruction::PUSH1), 0x6, - byte(eth::Instruction::PUSH1), 0x7, - byte(eth::Instruction::PUSH1), 0x8, - byte(eth::Instruction::DUP10), - byte(eth::Instruction::XOR), - byte(eth::Instruction::AND), - byte(eth::Instruction::OR), - byte(eth::Instruction::SUB), - byte(eth::Instruction::ADD), - byte(eth::Instruction::MOD), - byte(eth::Instruction::DIV), - byte(eth::Instruction::MUL)}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(unary_operators) -{ - char const* sourceCode = "contract test {\n" - " function f(int y) { var x = !(~+- y == 2); }" - "}\n"; - bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "y"}, {"test", "f", "x"}}); - - bytes expectation({byte(eth::Instruction::PUSH1), 0x2, - byte(eth::Instruction::DUP3), - byte(eth::Instruction::PUSH1), 0x0, - byte(eth::Instruction::SUB), - byte(eth::Instruction::NOT), - byte(eth::Instruction::EQ), - byte(eth::Instruction::ISZERO)}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(unary_inc_dec) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a) { var x = --a ^ (a-- ^ (++a ^ a++)); }" - "}\n"; - bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "a"}, {"test", "f", "x"}}); - - // Stack: a, x - bytes expectation({byte(eth::Instruction::DUP2), - byte(eth::Instruction::DUP1), - byte(eth::Instruction::PUSH1), 0x1, - byte(eth::Instruction::ADD), - // Stack here: a x a (a+1) - byte(eth::Instruction::SWAP3), - byte(eth::Instruction::POP), // first ++ - // Stack here: (a+1) x a - byte(eth::Instruction::DUP3), - byte(eth::Instruction::PUSH1), 0x1, - byte(eth::Instruction::ADD), - // Stack here: (a+1) x a (a+2) - byte(eth::Instruction::SWAP3), - byte(eth::Instruction::POP), - // Stack here: (a+2) x a - byte(eth::Instruction::DUP3), // second ++ - byte(eth::Instruction::XOR), - // Stack here: (a+2) x a^(a+2) - byte(eth::Instruction::DUP3), - byte(eth::Instruction::DUP1), - byte(eth::Instruction::PUSH1), 0x1, - byte(eth::Instruction::SWAP1), - byte(eth::Instruction::SUB), - // Stack here: (a+2) x a^(a+2) (a+2) (a+1) - byte(eth::Instruction::SWAP4), - byte(eth::Instruction::POP), // first -- - byte(eth::Instruction::XOR), - // Stack here: (a+1) x a^(a+2)^(a+2) - byte(eth::Instruction::DUP3), - byte(eth::Instruction::PUSH1), 0x1, - byte(eth::Instruction::SWAP1), - byte(eth::Instruction::SUB), - // Stack here: (a+1) x a^(a+2)^(a+2) a - byte(eth::Instruction::SWAP3), - byte(eth::Instruction::POP), // second ++ - // Stack here: a x a^(a+2)^(a+2) - byte(eth::Instruction::DUP3), // will change - byte(eth::Instruction::XOR)}); - // Stack here: a x a^(a+2)^(a+2)^a - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(assignment) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a, uint b) { (a += b) * 2; }" - "}\n"; - bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "a"}, {"test", "f", "b"}}); - - // Stack: a, b - bytes expectation({byte(eth::Instruction::PUSH1), 0x2, - byte(eth::Instruction::DUP2), - byte(eth::Instruction::DUP4), - byte(eth::Instruction::ADD), - // Stack here: a b 2 a+b - byte(eth::Instruction::SWAP3), - byte(eth::Instruction::POP), - byte(eth::Instruction::DUP3), - // Stack here: a+b b 2 a+b - byte(eth::Instruction::MUL)}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(function_call) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a, uint b) { a += g(a + 1, b) * 2; }\n" - " function g(uint a, uint b) returns (uint c) {}\n" - "}\n"; - bytes code = compileFirstExpression(sourceCode, {{"test", "g"}}, - {{"test", "f", "a"}, {"test", "f", "b"}}); - - // Stack: a, b - bytes expectation({byte(eth::Instruction::PUSH1), 0x02, - byte(eth::Instruction::PUSH1), 0x0c, - byte(eth::Instruction::PUSH1), 0x01, - byte(eth::Instruction::DUP5), - byte(eth::Instruction::ADD), - // Stack here: a b 2 (a+1) - byte(eth::Instruction::DUP4), - byte(eth::Instruction::PUSH1), 0x13, - byte(eth::Instruction::JUMP), - byte(eth::Instruction::JUMPDEST), - // Stack here: a b 2 g(a+1, b) - byte(eth::Instruction::MUL), - // Stack here: a b g(a+1, b)*2 - byte(eth::Instruction::DUP3), - byte(eth::Instruction::ADD), - // Stack here: a b a+g(a+1, b)*2 - byte(eth::Instruction::SWAP2), - byte(eth::Instruction::POP), - byte(eth::Instruction::DUP2), - byte(eth::Instruction::JUMPDEST)}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(negative_literals_8bits) -{ - char const* sourceCode = "contract test {\n" - " function f() { int8 x = -0x80; }\n" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation(bytes({byte(eth::Instruction::PUSH32)}) + bytes(31, 0xff) + bytes(1, 0x80)); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(negative_literals_16bits) -{ - char const* sourceCode = "contract test {\n" - " function f() { int64 x = ~0xabc; }\n" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation(bytes({byte(eth::Instruction::PUSH32)}) + bytes(30, 0xff) + bytes{0xf5, 0x43}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(intermediately_overflowing_literals) -{ - // first literal itself is too large for 256 bits but it fits after all constant operations - // have been applied - char const* sourceCode = "contract test {\n" - " function f() { var x = (0xffffffffffffffffffffffffffffffffffffffff * 0xffffffffffffffffffffffffff01) & 0xbf; }\n" - "}\n"; - bytes code = compileFirstExpression(sourceCode); - - bytes expectation(bytes({byte(eth::Instruction::PUSH1), 0xbf})); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_CASE(blockhash) -{ - char const* sourceCode = "contract test {\n" - " function f() {\n" - " block.blockhash(3);\n" - " }\n" - "}\n"; - bytes code = compileFirstExpression(sourceCode, {}, {}, - {make_shared("block", make_shared(MagicType::Kind::Block))}); - - bytes expectation({byte(eth::Instruction::PUSH1), 0x03, - byte(eth::Instruction::BLOCKHASH)}); - BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end()); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/SolidityInterface.cpp b/test/libsolidity/SolidityInterface.cpp deleted file mode 100644 index 9c9373f04..000000000 --- a/test/libsolidity/SolidityInterface.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . - */ -/** - * @author Christian - * @date 2015 - * Unit tests for generating source interfaces for Solidity contracts. - */ - -#include "../TestHelper.h" -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -class SolidityInterfaceChecker -{ -public: - SolidityInterfaceChecker(): m_compilerStack(false) {} - - /// Compiles the given code, generates the interface and parses that again. - ContractDefinition const& checkInterface(string const& _code, string const& _contractName = "") - { - m_code = _code; - ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing failed"); - m_interface = m_compilerStack.getMetadata("", DocumentationType::ABISolidityInterface); - ETH_TEST_REQUIRE_NO_THROW(m_reCompiler.parse(m_interface), "Interface parsing failed"); - return m_reCompiler.getContractDefinition(_contractName); - } - - string getSourcePart(ASTNode const& _node) const - { - SourceLocation location = _node.getLocation(); - BOOST_REQUIRE(!location.isEmpty()); - return m_interface.substr(location.start, location.end - location.start); - } - -protected: - string m_code; - string m_interface; - CompilerStack m_compilerStack; - CompilerStack m_reCompiler; -}; - -BOOST_FIXTURE_TEST_SUITE(SolidityInterface, SolidityInterfaceChecker) - -BOOST_AUTO_TEST_CASE(empty_contract) -{ - ContractDefinition const& contract = checkInterface("contract test {}"); - BOOST_CHECK_EQUAL(getSourcePart(contract), "contract test{}"); -} - -BOOST_AUTO_TEST_CASE(single_function) -{ - ContractDefinition const& contract = checkInterface( - "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - "}\n"); - BOOST_REQUIRE_EQUAL(1, contract.getDefinedFunctions().size()); - BOOST_CHECK_EQUAL(getSourcePart(*contract.getDefinedFunctions().front()), - "function f(uint256 a)returns(uint256 d);"); -} - -BOOST_AUTO_TEST_CASE(single_constant_function) -{ - ContractDefinition const& contract = checkInterface( - "contract test { function f(uint a) constant returns(bytes1 x) { 1==2; } }"); - BOOST_REQUIRE_EQUAL(1, contract.getDefinedFunctions().size()); - BOOST_CHECK_EQUAL(getSourcePart(*contract.getDefinedFunctions().front()), - "function f(uint256 a)constant returns(bytes1 x);"); -} - -BOOST_AUTO_TEST_CASE(multiple_functions) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - " function g(uint b) returns(uint e) { return b * 8; }\n" - "}\n"; - ContractDefinition const& contract = checkInterface(sourceCode); - set expectation({"function f(uint256 a)returns(uint256 d);", - "function g(uint256 b)returns(uint256 e);"}); - BOOST_REQUIRE_EQUAL(2, contract.getDefinedFunctions().size()); - BOOST_CHECK(expectation == set({getSourcePart(*contract.getDefinedFunctions().at(0)), - getSourcePart(*contract.getDefinedFunctions().at(1))})); -} - -BOOST_AUTO_TEST_CASE(exclude_fallback_function) -{ - char const* sourceCode = "contract test { function() {} }"; - ContractDefinition const& contract = checkInterface(sourceCode); - BOOST_CHECK_EQUAL(getSourcePart(contract), "contract test{}"); -} - -BOOST_AUTO_TEST_CASE(events) -{ - char const* sourceCode = "contract test {\n" - " function f(uint a) returns(uint d) { return a * 7; }\n" - " event e1(uint b, address indexed c); \n" - " event e2(); \n" - "}\n"; - ContractDefinition const& contract = checkInterface(sourceCode); - // events should not appear in the Solidity Interface - BOOST_REQUIRE_EQUAL(0, contract.getEvents().size()); -} - -BOOST_AUTO_TEST_CASE(inheritance) -{ - char const* sourceCode = - " contract Base { \n" - " function baseFunction(uint p) returns (uint i) { return p; } \n" - " event baseEvent(bytes32 indexed evtArgBase); \n" - " } \n" - " contract Derived is Base { \n" - " function derivedFunction(bytes32 p) returns (bytes32 i) { return p; } \n" - " event derivedEvent(uint indexed evtArgDerived); \n" - " }"; - ContractDefinition const& contract = checkInterface(sourceCode); - set expectedFunctions({"function baseFunction(uint256 p)returns(uint256 i);", - "function derivedFunction(bytes32 p)returns(bytes32 i);"}); - BOOST_REQUIRE_EQUAL(2, contract.getDefinedFunctions().size()); - BOOST_CHECK(expectedFunctions == set({getSourcePart(*contract.getDefinedFunctions().at(0)), - getSourcePart(*contract.getDefinedFunctions().at(1))})); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} diff --git a/test/libsolidity/SolidityNameAndTypeResolution.cpp b/test/libsolidity/SolidityNameAndTypeResolution.cpp deleted file mode 100644 index 3daabc85e..000000000 --- a/test/libsolidity/SolidityNameAndTypeResolution.cpp +++ /dev/null @@ -1,2201 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Unit tests for the name and type resolution of the solidity parser. - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include "../TestHelper.h" - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -namespace -{ - -ASTPointer parseTextAndResolveNames(std::string const& _source) -{ - Parser parser; - ASTPointer sourceUnit = parser.parse(std::make_shared(CharStream(_source))); - NameAndTypeResolver resolver({}); - resolver.registerDeclarations(*sourceUnit); - std::shared_ptr globalContext = make_shared(); - - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - globalContext->setCurrentContract(*contract); - resolver.updateDeclaration(*globalContext->getCurrentThis()); - resolver.updateDeclaration(*globalContext->getCurrentSuper()); - resolver.resolveNamesAndTypes(*contract); - } - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - globalContext->setCurrentContract(*contract); - resolver.updateDeclaration(*globalContext->getCurrentThis()); - resolver.checkTypeRequirements(*contract); - } - - return sourceUnit; -} - - -static ContractDefinition const* retrieveContract(ASTPointer _source, unsigned index) -{ - ContractDefinition* contract; - unsigned counter = 0; - for (ASTPointer const& node: _source->getNodes()) - if ((contract = dynamic_cast(node.get())) && counter == index) - return contract; - - return NULL; -} - -static FunctionTypePointer const& retrieveFunctionBySignature(ContractDefinition const* _contract, - std::string const& _signature) -{ - FixedHash<4> hash(dev::sha3(_signature)); - return _contract->getInterfaceFunctions()[hash]; -} - -} - -BOOST_AUTO_TEST_SUITE(SolidityNameAndTypeResolution) - -BOOST_AUTO_TEST_CASE(smoke_test) -{ - char const* text = "contract test {\n" - " uint256 stateVariable1;\n" - " function fun(uint256 arg1) { uint256 y; }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(double_stateVariable_declaration) -{ - char const* text = "contract test {\n" - " uint256 variable;\n" - " uint128 variable;\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(double_function_declaration) -{ - char const* text = "contract test {\n" - " function fun() { var x; }\n" - " function fun() { var x; }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(double_variable_declaration) -{ - char const* text = "contract test {\n" - " function f() { uint256 x; if (true) { uint256 x; } }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(name_shadowing) -{ - char const* text = "contract test {\n" - " uint256 variable;\n" - " function f() { uint32 variable ; }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(name_references) -{ - char const* text = "contract test {\n" - " uint256 variable;\n" - " function f(uint256 arg) returns (uint out) { f(variable); test; out; }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(undeclared_name) -{ - char const* text = "contract test {\n" - " uint256 variable;\n" - " function f(uint256 arg) { f(notfound); }" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(reference_to_later_declaration) -{ - char const* text = "contract test {\n" - " function g() { f(); }" - " function f() { }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(struct_definition_directly_recursive) -{ - char const* text = "contract test {\n" - " struct MyStructName {\n" - " address addr;\n" - " MyStructName x;\n" - " }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(struct_definition_indirectly_recursive) -{ - char const* text = "contract test {\n" - " struct MyStructName1 {\n" - " address addr;\n" - " uint256 count;\n" - " MyStructName2 x;\n" - " }\n" - " struct MyStructName2 {\n" - " MyStructName1 x;\n" - " }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(struct_definition_not_really_recursive) -{ - char const* text = R"( - contract test { - struct s1 { uint a; } - struct s2 { s1 x; s1 y; } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_CASE(struct_definition_recursion_via_mapping) -{ - char const* text = "contract test {\n" - " struct MyStructName1 {\n" - " address addr;\n" - " uint256 count;\n" - " mapping(uint => MyStructName1) x;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(type_inference_smoke_test) -{ - char const* text = "contract test {\n" - " function f(uint256 arg1, uint32 arg2) returns (bool ret) { var x = arg1 + arg2 == 8; ret = x; }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(type_checking_return) -{ - char const* text = "contract test {\n" - " function f() returns (bool r) { return 1 >= 2; }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(type_checking_return_wrong_number) -{ - char const* text = "contract test {\n" - " function f() returns (bool r1, bool r2) { return 1 >= 2; }" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(type_checking_return_wrong_type) -{ - char const* text = "contract test {\n" - " function f() returns (uint256 r) { return 1 >= 2; }" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(type_checking_function_call) -{ - char const* text = "contract test {\n" - " function f() returns (bool r) { return g(12, true) == 3; }\n" - " function g(uint256 a, bool b) returns (uint256 r) { }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(type_conversion_for_comparison) -{ - char const* text = "contract test {\n" - " function f() { uint32(2) == int64(2); }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(type_conversion_for_comparison_invalid) -{ - char const* text = "contract test {\n" - " function f() { int32(2) == uint64(2); }" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(type_inference_explicit_conversion) -{ - char const* text = "contract test {\n" - " function f() returns (int256 r) { var x = int256(uint32(2)); return x; }" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(large_string_literal) -{ - char const* text = "contract test {\n" - " function f() { var x = \"123456789012345678901234567890123\"; }" - "}\n"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_CASE(balance) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " uint256 x = address(0).balance;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(balance_invalid) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " address(0).balance = 7;\n" - " }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(assignment_to_mapping) -{ - char const* text = "contract test {\n" - " struct str {\n" - " mapping(uint=>uint) map;\n" - " }\n" - " str data;" - " function fun() {\n" - " var a = data.map;\n" - " data.map = a;\n" - " }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(assignment_to_struct) -{ - char const* text = "contract test {\n" - " struct str {\n" - " mapping(uint=>uint) map;\n" - " }\n" - " str data;" - " function fun() {\n" - " var a = data;\n" - " data = a;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(returns_in_constructor) -{ - char const* text = "contract test {\n" - " function test() returns (uint a) {\n" - " }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(forward_function_reference) -{ - char const* text = "contract First {\n" - " function fun() returns (bool ret) {\n" - " return Second(1).fun(1, true, 3) > 0;\n" - " }\n" - "}\n" - "contract Second {\n" - " function fun(uint a, bool b, uint c) returns (uint ret) {\n" - " if (First(2).fun() == true) return 1;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(comparison_bitop_precedence) -{ - char const* text = "contract First {\n" - " function fun() returns (bool ret) {\n" - " return 1 & 2 == 8 & 9 && 1 ^ 2 < 4 | 6;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(function_no_implementation) -{ - ASTPointer sourceUnit; - char const* text = "contract test {\n" - " function functionName(bytes32 input) returns (bytes32 out);\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); - std::vector> nodes = sourceUnit->getNodes(); - ContractDefinition* contract = dynamic_cast(nodes[0].get()); - BOOST_CHECK(contract); - BOOST_CHECK(!contract->isFullyImplemented()); - BOOST_CHECK(!contract->getDefinedFunctions()[0]->isFullyImplemented()); -} - -BOOST_AUTO_TEST_CASE(abstract_contract) -{ - ASTPointer sourceUnit; - char const* text = R"( - contract base { function foo(); } - contract derived is base { function foo() {} } - )"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); - std::vector> nodes = sourceUnit->getNodes(); - ContractDefinition* base = dynamic_cast(nodes[0].get()); - ContractDefinition* derived = dynamic_cast(nodes[1].get()); - BOOST_CHECK(base); - BOOST_CHECK(!base->isFullyImplemented()); - BOOST_CHECK(!base->getDefinedFunctions()[0]->isFullyImplemented()); - BOOST_CHECK(derived); - BOOST_CHECK(derived->isFullyImplemented()); - BOOST_CHECK(derived->getDefinedFunctions()[0]->isFullyImplemented()); -} - -BOOST_AUTO_TEST_CASE(abstract_contract_with_overload) -{ - ASTPointer sourceUnit; - char const* text = R"( - contract base { function foo(bool); } - contract derived is base { function foo(uint) {} } - )"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); - std::vector> nodes = sourceUnit->getNodes(); - ContractDefinition* base = dynamic_cast(nodes[0].get()); - ContractDefinition* derived = dynamic_cast(nodes[1].get()); - BOOST_REQUIRE(base); - BOOST_CHECK(!base->isFullyImplemented()); - BOOST_REQUIRE(derived); - BOOST_CHECK(!derived->isFullyImplemented()); -} - -BOOST_AUTO_TEST_CASE(create_abstract_contract) -{ - ASTPointer sourceUnit; - char const* text = R"( - contract base { function foo(); } - contract derived { - base b; - function foo() { b = new base();} - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(abstract_contract_constructor_args_optional) -{ - ASTPointer sourceUnit; - char const* text = R"( - contract BaseBase { function BaseBase(uint j); } - contract base is BaseBase { function foo(); } - contract derived is base { - function derived(uint i) BaseBase(i){} - function foo() {} - } - )"; - ETH_TEST_REQUIRE_NO_THROW(parseTextAndResolveNames(text), "Parsing and name resolving failed"); -} - -BOOST_AUTO_TEST_CASE(abstract_contract_constructor_args_not_provided) -{ - ASTPointer sourceUnit; - char const* text = R"( - contract BaseBase { function BaseBase(uint j); } - contract base is BaseBase { function foo(); } - contract derived is base { - function derived(uint i) {} - function foo() {} - } - )"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name resolving failed"); - std::vector> nodes = sourceUnit->getNodes(); - BOOST_CHECK_EQUAL(nodes.size(), 3); - ContractDefinition* derived = dynamic_cast(nodes[2].get()); - BOOST_CHECK(derived); - BOOST_CHECK(!derived->isFullyImplemented()); -} - -BOOST_AUTO_TEST_CASE(redeclare_implemented_abstract_function_as_abstract) -{ - ASTPointer sourceUnit; - char const* text = R"( - contract base { function foo(); } - contract derived is base { function foo() {} } - contract wrong is derived { function foo(); } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(function_canonical_signature) -{ - ASTPointer sourceUnit; - char const* text = "contract Test {\n" - " function foo(uint256 arg1, uint64 arg2, bool arg3) returns (uint256 ret) {\n" - " ret = arg1 + arg2;\n" - " }\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - auto functions = contract->getDefinedFunctions(); - BOOST_CHECK_EQUAL("foo(uint256,uint64,bool)", functions[0]->externalSignature()); - } -} - -BOOST_AUTO_TEST_CASE(function_canonical_signature_type_aliases) -{ - ASTPointer sourceUnit; - char const* text = "contract Test {\n" - " function boo(uint arg1, bytes32 arg2, address arg3) returns (uint ret) {\n" - " ret = 5;\n" - " }\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - auto functions = contract->getDefinedFunctions(); - if (functions.empty()) - continue; - BOOST_CHECK_EQUAL("boo(uint256,bytes32,address)", functions[0]->externalSignature()); - } -} - -BOOST_AUTO_TEST_CASE(function_external_types) -{ - ASTPointer sourceUnit; - char const* text = R"( - contract C { - uint a; - } - contract Test { - function boo(uint arg2, bool arg3, bytes8 arg4, bool[2] pairs, uint[] dynamic, C carg, address[] addresses) external returns (uint ret) { - ret = 5; - } - })"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - auto functions = contract->getDefinedFunctions(); - if (functions.empty()) - continue; - BOOST_CHECK_EQUAL("boo(uint256,bool,bytes8,bool[2],uint256[],address,address[])", functions[0]->externalSignature()); - } -} - -BOOST_AUTO_TEST_CASE(enum_external_type) -{ - // bug #1801 - ASTPointer sourceUnit; - char const* text = R"( - contract Test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function boo(ActionChoices enumArg) external returns (uint ret) { - ret = 5; - } - })"; - ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ContractDefinition* contract = dynamic_cast(node.get())) - { - auto functions = contract->getDefinedFunctions(); - if (functions.empty()) - continue; - BOOST_CHECK_EQUAL("boo(uint8)", functions[0]->externalSignature()); - } -} - -BOOST_AUTO_TEST_CASE(function_external_call_allowed_conversion) -{ - char const* text = R"( - contract C {} - contract Test { - function externalCall() { - C arg; - this.g(arg); - } - function g (C c) external {} - })"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_CASE(function_external_call_not_allowed_conversion) -{ - char const* text = R"( - contract C {} - contract Test { - function externalCall() { - address arg; - this.g(arg); - } - function g (C c) external {} - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(function_internal_allowed_conversion) -{ - char const* text = R"( - contract C { - uint a; - } - contract Test { - C a; - function g (C c) {} - function internalCall() { - g(a); - } - })"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_CASE(function_internal_not_allowed_conversion) -{ - char const* text = R"( - contract C { - uint a; - } - contract Test { - address a; - function g (C c) {} - function internalCall() { - g(a); - } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(hash_collision_in_interface) -{ - char const* text = "contract test {\n" - " function gsf() {\n" - " }\n" - " function tgeo() {\n" - " }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(inheritance_basic) -{ - char const* text = R"( - contract base { uint baseMember; struct BaseType { uint element; } } - contract derived is base { - BaseType data; - function f() { baseMember = 7; } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(inheritance_diamond_basic) -{ - char const* text = R"( - contract root { function rootFunction() {} } - contract inter1 is root { function f() {} } - contract inter2 is root { function f() {} } - contract derived is root, inter2, inter1 { - function g() { f(); rootFunction(); } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(cyclic_inheritance) -{ - char const* text = R"( - contract A is B { } - contract B is A { } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(legal_override_direct) -{ - char const* text = R"( - contract B { function f() {} } - contract C is B { function f(uint i) {} } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_CASE(legal_override_indirect) -{ - char const* text = R"( - contract A { function f(uint a) {} } - contract B { function f() {} } - contract C is A, B { } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_CASE(illegal_override_visibility) -{ - char const* text = R"( - contract B { function f() internal {} } - contract C is B { function f() public {} } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(illegal_override_constness) -{ - char const* text = R"( - contract B { function f() constant {} } - contract C is B { function f() {} } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(complex_inheritance) -{ - char const* text = R"( - contract A { function f() { uint8 x = C(0).g(); } } - contract B { function f() {} function g() returns (uint8 r) {} } - contract C is A, B { } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(constructor_visibility) -{ - // The constructor of a base class should not be visible in the derived class - char const* text = R"( - contract A { function A() { } } - contract B is A { function f() { A x = A(0); } } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(overriding_constructor) -{ - // It is fine to "override" constructor of a base class since it is invisible - char const* text = R"( - contract A { function A() { } } - contract B is A { function A() returns (uint8 r) {} } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(missing_base_constructor_arguments) -{ - char const* text = R"( - contract A { function A(uint a) { } } - contract B is A { } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(base_constructor_arguments_override) -{ - char const* text = R"( - contract A { function A(uint a) { } } - contract B is A { } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(implicit_derived_to_base_conversion) -{ - char const* text = R"( - contract A { } - contract B is A { - function f() { A a = B(1); } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(implicit_base_to_derived_conversion) -{ - char const* text = R"( - contract A { } - contract B is A { - function f() { B b = A(1); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(function_modifier_invocation) -{ - char const* text = R"( - contract B { - function f() mod1(2, true) mod2("0123456") { } - modifier mod1(uint a, bool b) { if (b) _ } - modifier mod2(bytes7 a) { while (a == "1234567") _ } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(invalid_function_modifier_type) -{ - char const* text = R"( - contract B { - function f() mod1(true) { } - modifier mod1(uint a) { if (a > 0) _ } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(function_modifier_invocation_parameters) -{ - char const* text = R"( - contract B { - function f(uint8 a) mod1(a, true) mod2(r) returns (bytes7 r) { } - modifier mod1(uint a, bool b) { if (b) _ } - modifier mod2(bytes7 a) { while (a == "1234567") _ } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(function_modifier_invocation_local_variables) -{ - char const* text = R"( - contract B { - function f() mod(x) { uint x = 7; } - modifier mod(uint a) { if (a > 0) _ } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(legal_modifier_override) -{ - char const* text = R"( - contract A { modifier mod(uint a) {} } - contract B is A { modifier mod(uint a) {} } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(illegal_modifier_override) -{ - char const* text = R"( - contract A { modifier mod(uint a) {} } - contract B is A { modifier mod(uint8 a) {} } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(modifier_overrides_function) -{ - char const* text = R"( - contract A { modifier mod(uint a) {} } - contract B is A { function mod(uint a) {} } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(function_overrides_modifier) -{ - char const* text = R"( - contract A { function mod(uint a) {} } - contract B is A { modifier mod(uint a) {} } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(modifier_returns_value) -{ - char const* text = R"( - contract A { - function f(uint a) mod(2) returns (uint r) {} - modifier mod(uint a) { return 7; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(state_variable_accessors) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "uint256 public foo;\n" - "mapping(uint=>bytes4) public map;\n" - "mapping(uint=>mapping(uint=>bytes4)) public multiple_map;\n" - "}\n"; - - ASTPointer source; - ContractDefinition const* contract; - ETH_TEST_CHECK_NO_THROW(source = parseTextAndResolveNames(text), "Parsing and Resolving names failed"); - BOOST_REQUIRE((contract = retrieveContract(source, 0)) != nullptr); - FunctionTypePointer function = retrieveFunctionBySignature(contract, "foo()"); - BOOST_REQUIRE(function && function->hasDeclaration()); - auto returnParams = function->getReturnParameterTypeNames(); - BOOST_CHECK_EQUAL(returnParams.at(0), "uint256"); - BOOST_CHECK(function->isConstant()); - - function = retrieveFunctionBySignature(contract, "map(uint256)"); - BOOST_REQUIRE(function && function->hasDeclaration()); - auto params = function->getParameterTypeNames(); - BOOST_CHECK_EQUAL(params.at(0), "uint256"); - returnParams = function->getReturnParameterTypeNames(); - BOOST_CHECK_EQUAL(returnParams.at(0), "bytes4"); - BOOST_CHECK(function->isConstant()); - - function = retrieveFunctionBySignature(contract, "multiple_map(uint256,uint256)"); - BOOST_REQUIRE(function && function->hasDeclaration()); - params = function->getParameterTypeNames(); - BOOST_CHECK_EQUAL(params.at(0), "uint256"); - BOOST_CHECK_EQUAL(params.at(1), "uint256"); - returnParams = function->getReturnParameterTypeNames(); - BOOST_CHECK_EQUAL(returnParams.at(0), "bytes4"); - BOOST_CHECK(function->isConstant()); -} - -BOOST_AUTO_TEST_CASE(function_clash_with_state_variable_accessor) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "uint256 foo;\n" - " function foo() {}\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(private_state_variable) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "uint256 private foo;\n" - "uint256 internal bar;\n" - "}\n"; - - ASTPointer source; - ContractDefinition const* contract; - ETH_TEST_CHECK_NO_THROW(source = parseTextAndResolveNames(text), "Parsing and Resolving names failed"); - BOOST_CHECK((contract = retrieveContract(source, 0)) != nullptr); - FunctionTypePointer function; - function = retrieveFunctionBySignature(contract, "foo()"); - BOOST_CHECK_MESSAGE(function == nullptr, "Accessor function of a private variable should not exist"); - function = retrieveFunctionBySignature(contract, "bar()"); - BOOST_CHECK_MESSAGE(function == nullptr, "Accessor function of an internal variable should not exist"); -} - -BOOST_AUTO_TEST_CASE(base_class_state_variable_accessor) -{ - // test for issue #1126 https://github.com/ethereum/cpp-ethereum/issues/1126 - char const* text = "contract Parent {\n" - " uint256 public m_aMember;\n" - "}\n" - "contract Child is Parent{\n" - " function foo() returns (uint256) { return Parent.m_aMember; }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(base_class_state_variable_internal_member) -{ - char const* text = "contract Parent {\n" - " uint256 internal m_aMember;\n" - "}\n" - "contract Child is Parent{\n" - " function foo() returns (uint256) { return Parent.m_aMember; }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(state_variable_member_of_wrong_class1) -{ - char const* text = "contract Parent1 {\n" - " uint256 internal m_aMember1;\n" - "}\n" - "contract Parent2 is Parent1{\n" - " uint256 internal m_aMember2;\n" - "}\n" - "contract Child is Parent2{\n" - " function foo() returns (uint256) { return Parent2.m_aMember1; }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(state_variable_member_of_wrong_class2) -{ - char const* text = "contract Parent1 {\n" - " uint256 internal m_aMember1;\n" - "}\n" - "contract Parent2 is Parent1{\n" - " uint256 internal m_aMember2;\n" - "}\n" - "contract Child is Parent2{\n" - " function foo() returns (uint256) { return Child.m_aMember2; }\n" - " uint256 public m_aMember3;\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(fallback_function) -{ - char const* text = R"( - contract C { - uint x; - function() { x = 2; } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(fallback_function_with_arguments) -{ - char const* text = R"( - contract C { - uint x; - function(uint a) { x = 2; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(fallback_function_twice) -{ - char const* text = R"( - contract C { - uint x; - function() { x = 2; } - function() { x = 3; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(fallback_function_inheritance) -{ - char const* text = R"( - contract A { - uint x; - function() { x = 1; } - } - contract C is A { - function() { x = 2; } - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(event) -{ - char const* text = R"( - contract c { - event e(uint indexed a, bytes3 indexed s, bool indexed b); - function f() { e(2, "abc", true); } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(event_too_many_indexed) -{ - char const* text = R"( - contract c { - event e(uint indexed a, bytes3 indexed b, bool indexed c, uint indexed d); - function f() { e(2, "abc", true); } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(event_call) -{ - char const* text = R"( - contract c { - event e(uint a, bytes3 indexed s, bool indexed b); - function f() { e(2, "abc", true); } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(event_inheritance) -{ - char const* text = R"( - contract base { - event e(uint a, bytes3 indexed s, bool indexed b); - } - contract c is base { - function f() { e(2, "abc", true); } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(multiple_events_argument_clash) -{ - char const* text = R"( - contract c { - event e1(uint a, uint e1, uint e2); - event e2(uint a, uint e1, uint e2); - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(access_to_default_function_visibility) -{ - char const* text = R"( - contract c { - function f() {} - } - contract d { - function g() { c(0).f(); } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(access_to_internal_function) -{ - char const* text = R"( - contract c { - function f() internal {} - } - contract d { - function g() { c(0).f(); } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(access_to_default_state_variable_visibility) -{ - char const* text = R"( - contract c { - uint a; - } - contract d { - function g() { c(0).a(); } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(access_to_internal_state_variable) -{ - char const* text = R"( - contract c { - uint public a; - } - contract d { - function g() { c(0).a(); } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(error_count_in_named_args) -{ - char const* sourceCode = "contract test {\n" - " function a(uint a, uint b) returns (uint r) { r = a + b; }\n" - " function b() returns (uint r) { r = a({a: 1}); }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(empty_in_named_args) -{ - char const* sourceCode = "contract test {\n" - " function a(uint a, uint b) returns (uint r) { r = a + b; }\n" - " function b() returns (uint r) { r = a({}); }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(duplicate_parameter_names_in_named_args) -{ - char const* sourceCode = "contract test {\n" - " function a(uint a, uint b) returns (uint r) { r = a + b; }\n" - " function b() returns (uint r) { r = a({a: 1, a: 2}); }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(invalid_parameter_names_in_named_args) -{ - char const* sourceCode = "contract test {\n" - " function a(uint a, uint b) returns (uint r) { r = a + b; }\n" - " function b() returns (uint r) { r = a({a: 1, c: 2}); }\n" - "}\n"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(empty_name_input_parameter) -{ - char const* text = R"( - contract test { - function f(uint){ - } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(empty_name_return_parameter) -{ - char const* text = R"( - contract test { - function f() returns(bool){ - } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one) -{ - char const* text = R"( - contract test { - function f(uint, uint k) returns(uint ret_k){ - return k; - } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(empty_name_return_parameter_with_named_one) -{ - char const* text = R"( - contract test { - function f() returns(uint ret_k, uint){ - return 5; - } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(disallow_declaration_of_void_type) -{ - char const* sourceCode = "contract c { function f() { var x = f(); } }"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(overflow_caused_by_ether_units) -{ - char const* sourceCodeFine = R"( - contract c { - function c () - { - a = 115792089237316195423570985008687907853269984665640564039458; - } - uint256 a; - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCodeFine), - "Parsing and Resolving names failed"); - char const* sourceCode = R"( - contract c { - function c () - { - a = 115792089237316195423570985008687907853269984665640564039458 ether; - } - uint256 a; - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(exp_operator_negative_exponent) -{ - char const* sourceCode = R"( - contract test { - function f() returns(uint d) { return 2 ** -3; } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(exp_operator_exponent_too_big) -{ - char const* sourceCode = R"( - contract test { - function f() returns(uint d) { return 2 ** 10000000000; } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(enum_member_access) -{ - char const* text = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function test() - { - choices = ActionChoices.GoStraight; - } - ActionChoices choices; - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(enum_invalid_member_access) -{ - char const* text = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function test() - { - choices = ActionChoices.RunAroundWavingYourHands; - } - ActionChoices choices; - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(enum_explicit_conversion_is_okay) -{ - char const* text = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function test() - { - a = uint256(ActionChoices.GoStraight); - b = uint64(ActionChoices.Sit); - } - uint256 a; - uint64 b; - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(int_to_enum_explicit_conversion_is_okay) -{ - char const* text = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function test() - { - a = 2; - b = ActionChoices(a); - } - uint256 a; - ActionChoices b; - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(enum_implicit_conversion_is_not_okay) -{ - char const* text = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoStraight, Sit } - function test() - { - a = ActionChoices.GoStraight; - b = ActionChoices.Sit; - } - uint256 a; - uint64 b; - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(enum_duplicate_values) -{ - char const* text = R"( - contract test { - enum ActionChoices { GoLeft, GoRight, GoLeft, Sit } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(private_visibility) -{ - char const* sourceCode = R"( - contract base { - function f() private {} - } - contract derived is base { - function g() { f(); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(private_visibility_via_explicit_base_access) -{ - char const* sourceCode = R"( - contract base { - function f() private {} - } - contract derived is base { - function g() { base.f(); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(external_visibility) -{ - char const* sourceCode = R"( - contract c { - function f() external {} - function g() { f(); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(external_base_visibility) -{ - char const* sourceCode = R"( - contract base { - function f() external {} - } - contract derived is base { - function g() { base.f(); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(external_argument_assign) -{ - char const* sourceCode = R"( - contract c { - function f(uint a) external { a = 1; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(external_argument_increment) -{ - char const* sourceCode = R"( - contract c { - function f(uint a) external { a++; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(external_argument_delete) -{ - char const* sourceCode = R"( - contract c { - function f(uint a) external { delete a; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(test_for_bug_override_function_with_bytearray_type) -{ - char const* sourceCode = R"( - contract Vehicle { - function f(bytes _a) external returns (uint256 r) {r = 1;} - } - contract Bike is Vehicle { - function f(bytes _a) external returns (uint256 r) {r = 42;} - } - )"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode), "Parsing and Name Resolving failed"); -} - -BOOST_AUTO_TEST_CASE(array_with_nonconstant_length) -{ - char const* text = R"( - contract c { - function f(uint a) { uint8[a] x; } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(array_copy_with_different_types1) -{ - char const* text = R"( - contract c { - bytes a; - uint[] b; - function f() { b = a; } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(array_copy_with_different_types2) -{ - char const* text = R"( - contract c { - uint32[] a; - uint8[] b; - function f() { b = a; } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(array_copy_with_different_types_conversion_possible) -{ - char const* text = R"( - contract c { - uint32[] a; - uint8[] b; - function f() { a = b; } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(array_copy_with_different_types_static_dynamic) -{ - char const* text = R"( - contract c { - uint32[] a; - uint8[80] b; - function f() { a = b; } - })"; - ETH_TEST_CHECK_NO_THROW(parseTextAndResolveNames(text), "Parsing and Name Resolving Failed"); -} - -BOOST_AUTO_TEST_CASE(array_copy_with_different_types_dynamic_static) -{ - char const* text = R"( - contract c { - uint[] a; - uint[80] b; - function f() { b = a; } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(storage_variable_initialization_with_incorrect_type_int) -{ - char const* text = R"( - contract c { - uint8 a = 1000; - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(storage_variable_initialization_with_incorrect_type_string) -{ - char const* text = R"( - contract c { - uint a = "abc"; - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(test_fromElementaryTypeName) -{ - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int) == *make_shared(256, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int8) == *make_shared(8, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int16) == *make_shared(16, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int24) == *make_shared(24, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int32) == *make_shared(32, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int40) == *make_shared(40, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int48) == *make_shared(48, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int56) == *make_shared(56, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int64) == *make_shared(64, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int72) == *make_shared(72, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int80) == *make_shared(80, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int88) == *make_shared(88, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int96) == *make_shared(96, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int104) == *make_shared(104, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int112) == *make_shared(112, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int120) == *make_shared(120, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int128) == *make_shared(128, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int136) == *make_shared(136, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int144) == *make_shared(144, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int152) == *make_shared(152, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int160) == *make_shared(160, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int168) == *make_shared(168, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int176) == *make_shared(176, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int184) == *make_shared(184, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int192) == *make_shared(192, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int200) == *make_shared(200, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int208) == *make_shared(208, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int216) == *make_shared(216, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int224) == *make_shared(224, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int232) == *make_shared(232, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int240) == *make_shared(240, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int248) == *make_shared(248, IntegerType::Modifier::Signed)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Int256) == *make_shared(256, IntegerType::Modifier::Signed)); - - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt) == *make_shared(256, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt8) == *make_shared(8, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt16) == *make_shared(16, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt24) == *make_shared(24, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt32) == *make_shared(32, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt40) == *make_shared(40, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt48) == *make_shared(48, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt56) == *make_shared(56, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt64) == *make_shared(64, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt72) == *make_shared(72, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt80) == *make_shared(80, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt88) == *make_shared(88, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt96) == *make_shared(96, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt104) == *make_shared(104, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt112) == *make_shared(112, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt120) == *make_shared(120, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt128) == *make_shared(128, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt136) == *make_shared(136, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt144) == *make_shared(144, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt152) == *make_shared(152, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt160) == *make_shared(160, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt168) == *make_shared(168, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt176) == *make_shared(176, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt184) == *make_shared(184, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt192) == *make_shared(192, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt200) == *make_shared(200, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt208) == *make_shared(208, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt216) == *make_shared(216, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt224) == *make_shared(224, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt232) == *make_shared(232, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt240) == *make_shared(240, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt248) == *make_shared(248, IntegerType::Modifier::Unsigned)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::UInt256) == *make_shared(256, IntegerType::Modifier::Unsigned)); - - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Byte) == *make_shared(1)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes1) == *make_shared(1)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes2) == *make_shared(2)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes3) == *make_shared(3)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes4) == *make_shared(4)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes5) == *make_shared(5)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes6) == *make_shared(6)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes7) == *make_shared(7)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes8) == *make_shared(8)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes9) == *make_shared(9)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes10) == *make_shared(10)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes11) == *make_shared(11)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes12) == *make_shared(12)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes13) == *make_shared(13)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes14) == *make_shared(14)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes15) == *make_shared(15)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes16) == *make_shared(16)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes17) == *make_shared(17)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes18) == *make_shared(18)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes19) == *make_shared(19)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes20) == *make_shared(20)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes21) == *make_shared(21)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes22) == *make_shared(22)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes23) == *make_shared(23)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes24) == *make_shared(24)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes25) == *make_shared(25)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes26) == *make_shared(26)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes27) == *make_shared(27)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes28) == *make_shared(28)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes29) == *make_shared(29)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes30) == *make_shared(30)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes31) == *make_shared(31)); - BOOST_CHECK(*Type::fromElementaryTypeName(Token::Bytes32) == *make_shared(32)); -} - -BOOST_AUTO_TEST_CASE(test_byte_is_alias_of_byte1) -{ - char const* text = R"( - contract c { - bytes arr; - function f() { byte a = arr[0];} - })"; - ETH_TEST_REQUIRE_NO_THROW(parseTextAndResolveNames(text), "Type resolving failed"); -} - -BOOST_AUTO_TEST_CASE(assigning_value_to_const_variable) -{ - char const* text = R"( - contract Foo { - function changeIt() { x = 9; } - uint constant x = 56; - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(complex_const_variable) -{ - //for now constant specifier is valid only for uint bytesXX and enums - char const* text = R"( - contract Foo { - mapping(uint => bool) constant mapVar; - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(uninitialized_const_variable) -{ - char const* text = R"( - contract Foo { - uint constant y; - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(local_const_variable) -{ - char const* text = R"( - contract Foo { - function localConst() returns (uint ret) - { - uint constant local = 4; - return local; - } - })"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(overloaded_function_cannot_resolve) -{ - char const* sourceCode = R"( - contract test { - function f() returns(uint) { return 1; } - function f(uint a) returns(uint) { return a; } - function g() returns(uint) { return f(3, 5); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(ambiguous_overloaded_function) -{ - // literal 1 can be both converted to uint and uint8, so the call is ambiguous. - char const* sourceCode = R"( - contract test { - function f(uint8 a) returns(uint) { return a; } - function f(uint a) returns(uint) { return 2*a; } - function g() returns(uint) { return f(1); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(assignment_of_nonoverloaded_function) -{ - char const* sourceCode = R"( - contract test { - function f(uint a) returns(uint) { return 2 * a; } - function g() returns(uint) { var x = f; return x(7); } - } - )"; - ETH_TEST_REQUIRE_NO_THROW(parseTextAndResolveNames(sourceCode), "Type resolving failed"); -} - -BOOST_AUTO_TEST_CASE(assignment_of_overloaded_function) -{ - char const* sourceCode = R"( - contract test { - function f() returns(uint) { return 1; } - function f(uint a) returns(uint) { return 2 * a; } - function g() returns(uint) { var x = f; return x(7); } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(external_types_clash) -{ - char const* sourceCode = R"( - contract base { - enum a { X } - function f(a) { } - } - contract test is base { - function f(uint8 a) { } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(override_changes_return_types) -{ - char const* sourceCode = R"( - contract base { - function f(uint a) returns (uint) { } - } - contract test is base { - function f(uint a) returns (uint8) { } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(multiple_constructors) -{ - char const* sourceCode = R"( - contract test { - function test(uint a) { } - function test() {} - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(equal_overload) -{ - char const* sourceCode = R"( - contract test { - function test(uint a) returns (uint b) { } - function test(uint a) external {} - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), DeclarationError); -} - -BOOST_AUTO_TEST_CASE(uninitialized_var) -{ - char const* sourceCode = R"( - contract C { - function f() returns (uint) { var x; return 2; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(string) -{ - char const* sourceCode = R"( - contract C { - string s; - function f(string x) external { s = x; } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(string_index) -{ - char const* sourceCode = R"( - contract C { - string s; - function f() { var a = s[2]; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(string_length) -{ - char const* sourceCode = R"( - contract C { - string s; - function f() { var a = s.length; } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(negative_integers_to_signed_out_of_bound) -{ - char const* sourceCode = R"( - contract test { - int8 public i = -129; - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(negative_integers_to_signed_min) -{ - char const* sourceCode = R"( - contract test { - int8 public i = -128; - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(positive_integers_to_signed_out_of_bound) -{ - char const* sourceCode = R"( - contract test { - int8 public j = 128; - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(positive_integers_to_signed_out_of_bound_max) -{ - char const* sourceCode = R"( - contract test { - int8 public j = 127; - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(negative_integers_to_unsigned) -{ - char const* sourceCode = R"( - contract test { - uint8 public x = -1; - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(positive_integers_to_unsigned_out_of_bound) -{ - char const* sourceCode = R"( - contract test { - uint8 public x = 700; - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(integer_boolean_operators) -{ - char const* sourceCode1 = R"( - contract test { function() { uint x = 1; uint y = 2; x || y; } } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode1), TypeError); - char const* sourceCode2 = R"( - contract test { function() { uint x = 1; uint y = 2; x && y; } } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode2), TypeError); - char const* sourceCode3 = R"( - contract test { function() { uint x = 1; !x; } } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode3), TypeError); -} - -BOOST_AUTO_TEST_CASE(reference_compare_operators) -{ - char const* sourceCode1 = R"( - contract test { bytes a; bytes b; function() { a == b; } } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode1), TypeError); - char const* sourceCode2 = R"( - contract test { struct s {uint a;} s x; s y; function() { x == y; } } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode2), TypeError); -} - -BOOST_AUTO_TEST_CASE(overwrite_memory_location_external) -{ - char const* sourceCode = R"( - contract C { - function f(uint[] memory a) external {} - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(overwrite_storage_location_external) -{ - char const* sourceCode = R"( - contract C { - function f(uint[] storage a) external {} - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(storage_location_local_variables) -{ - char const* sourceCode = R"( - contract C { - function f() { - uint[] storage x; - uint[] memory y; - uint[] memory z; - } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(no_mappings_in_memory_array) -{ - char const* sourceCode = R"( - contract C { - function f() { - mapping(uint=>uint)[] memory x; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(assignment_mem_to_local_storage_variable) -{ - char const* sourceCode = R"( - contract C { - uint[] data; - function f(uint[] x) { - var dataRef = data; - dataRef = x; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(storage_assign_to_different_local_variable) -{ - char const* sourceCode = R"( - contract C { - uint[] data; - uint8[] otherData; - function f() { - uint8[] storage x = otherData; - uint[] storage y = data; - y = x; - // note that data = otherData works - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(no_delete_on_storage_pointers) -{ - char const* sourceCode = R"( - contract C { - uint[] data; - function f() { - var x = data; - delete x; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(assignment_mem_storage_variable_directly) -{ - char const* sourceCode = R"( - contract C { - uint[] data; - function f(uint[] x) { - data = x; - } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(function_argument_mem_to_storage) -{ - char const* sourceCode = R"( - contract C { - function f(uint[] storage x) private { - } - function g(uint[] x) { - f(x); - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(function_argument_storage_to_mem) -{ - char const* sourceCode = R"( - contract C { - function f(uint[] storage x) private { - g(x); - } - function g(uint[] x) { - } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(mem_array_assignment_changes_base_type) -{ - // Such an assignment is possible in storage, but not in memory - // (because it would incur an otherwise unnecessary copy). - // This requirement might be lifted, though. - char const* sourceCode = R"( - contract C { - function f(uint8[] memory x) private { - uint[] memory y = x; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(dynamic_return_types_not_possible) -{ - char const* sourceCode = R"( - contract C { - function f(uint) returns (string); - function g() { - var x = this.f(2); - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(memory_arrays_not_resizeable) -{ - char const* sourceCode = R"( - contract C { - function f() { - uint[] memory x; - x.length = 2; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(sourceCode), TypeError); -} - -BOOST_AUTO_TEST_CASE(struct_constructor) -{ - char const* sourceCode = R"( - contract C { - struct S { uint a; bool x; } - function f() { - S memory s = S(1, true); - } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(struct_constructor_nested) -{ - char const* sourceCode = R"( - contract C { - struct X { uint x1; uint x2; } - struct S { uint s1; uint[3] s2; X s3; } - function f() { - uint[3] memory s2; - S memory s = S(1, s2, X(4, 5)); - } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(struct_named_constructor) -{ - char const* sourceCode = R"( - contract C { - struct S { uint a; bool x; } - function f() { - S memory s = S({a: 1, x: true}); - } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(sourceCode)); -} - -BOOST_AUTO_TEST_CASE(literal_strings) -{ - char const* text = R"( - contract Foo { - function f() { - string memory long = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; - string memory short = "123"; - } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_CASE(invalid_integer_literal_fraction) -{ - char const* text = R"( - contract Foo { - function f() { - var x = 1.20; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(invalid_integer_literal_exp) -{ - char const* text = R"( - contract Foo { - function f() { - var x = 1e2; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(memory_structs_with_mappings) -{ - char const* text = R"( - contract Test { - struct S { uint8 a; mapping(uint => uint) b; uint8 c; } - S s; - function f() { - S memory x; - x.b[1]; - } - } - )"; - BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); -} - -BOOST_AUTO_TEST_CASE(string_bytes_conversion) -{ - char const* text = R"( - contract Test { - string s; - bytes b; - function h(string _s) external { bytes(_s).length; } - function i(string _s) internal { bytes(_s).length; } - function j() internal { bytes(s).length; } - function k(bytes _b) external { string(_b); } - function l(bytes _b) internal { string(_b); } - function m() internal { string(b); } - } - )"; - BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/SolidityNatspecJSON.cpp b/test/libsolidity/SolidityNatspecJSON.cpp deleted file mode 100644 index 73c080f70..000000000 --- a/test/libsolidity/SolidityNatspecJSON.cpp +++ /dev/null @@ -1,534 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . - */ -/** - * @author Lefteris Karapetsas - * @date 2014 - * Unit tests for the solidity compiler JSON Interface output. - */ - -#include "../TestHelper.h" -#include -#include -#include -#include -#include - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -class DocumentationChecker -{ -public: - DocumentationChecker(): m_compilerStack(false) {} - - void checkNatspec( - std::string const& _code, - std::string const& _expectedDocumentationString, - bool _userDocumentation - ) - { - std::string generatedDocumentationString; - ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing failed"); - - if (_userDocumentation) - generatedDocumentationString = m_compilerStack.getMetadata("", DocumentationType::NatspecUser); - else - generatedDocumentationString = m_compilerStack.getMetadata("", DocumentationType::NatspecDev); - Json::Value generatedDocumentation; - m_reader.parse(generatedDocumentationString, generatedDocumentation); - Json::Value expectedDocumentation; - m_reader.parse(_expectedDocumentationString, expectedDocumentation); - BOOST_CHECK_MESSAGE( - expectedDocumentation == generatedDocumentation, - "Expected " << _expectedDocumentationString << - "\n but got:\n" << generatedDocumentationString - ); - } - -private: - CompilerStack m_compilerStack; - Json::Reader m_reader; -}; - -BOOST_FIXTURE_TEST_SUITE(SolidityNatspecJSON, DocumentationChecker) - -BOOST_AUTO_TEST_CASE(user_basic_test) -{ - char const* sourceCode = "contract test {\n" - " /// @notice Multiplies `a` by 7\n" - " function mul(uint a) returns(uint d) { return a * 7; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256)\":{ \"notice\": \"Multiplies `a` by 7\"}" - "}}"; - - checkNatspec(sourceCode, natspec, true); -} - -BOOST_AUTO_TEST_CASE(dev_and_user_basic_test) -{ - char const* sourceCode = "contract test {\n" - " /// @notice Multiplies `a` by 7\n" - " /// @dev Multiplies a number by 7\n" - " function mul(uint a) returns(uint d) { return a * 7; }\n" - "}\n"; - - char const* devNatspec = "{" - "\"methods\":{" - " \"mul(uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7\"\n" - " }\n" - " }\n" - "}}"; - - char const* userNatspec = "{" - "\"methods\":{" - " \"mul(uint256)\":{ \"notice\": \"Multiplies `a` by 7\"}" - "}}"; - - checkNatspec(sourceCode, devNatspec, false); - checkNatspec(sourceCode, userNatspec, true); -} - -BOOST_AUTO_TEST_CASE(user_multiline_comment) -{ - char const* sourceCode = "contract test {\n" - " /// @notice Multiplies `a` by 7\n" - " /// and then adds `b`\n" - " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" - " {\n" - " return (a * 7) + b;\n" - " }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul_and_add(uint256,uint256)\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}" - "}}"; - - checkNatspec(sourceCode, natspec, true); -} - -BOOST_AUTO_TEST_CASE(user_multiple_functions) -{ - char const* sourceCode = "contract test {\n" - " /// @notice Multiplies `a` by 7 and then adds `b`\n" - " function mul_and_add(uint a, uint256 b) returns(uint256 d)\n" - " {\n" - " return (a * 7) + b;\n" - " }\n" - "\n" - " /// @notice Divides `input` by `div`\n" - " function divide(uint input, uint div) returns(uint d)\n" - " {\n" - " return input / div;\n" - " }\n" - " /// @notice Subtracts 3 from `input`\n" - " function sub(int input) returns(int d)\n" - " {\n" - " return input - 3;\n" - " }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul_and_add(uint256,uint256)\":{ \"notice\": \"Multiplies `a` by 7 and then adds `b`\"}," - " \"divide(uint256,uint256)\":{ \"notice\": \"Divides `input` by `div`\"}," - " \"sub(int256)\":{ \"notice\": \"Subtracts 3 from `input`\"}" - "}}"; - - checkNatspec(sourceCode, natspec, true); -} - -BOOST_AUTO_TEST_CASE(user_empty_contract) -{ - char const* sourceCode = "contract test {\n" - "}\n"; - - char const* natspec = "{\"methods\":{} }"; - - checkNatspec(sourceCode, natspec, true); -} - -BOOST_AUTO_TEST_CASE(dev_and_user_no_doc) -{ - char const* sourceCode = "contract test {\n" - " function mul(uint a) returns(uint d) { return a * 7; }\n" - " function sub(int input) returns(int d)\n" - " {\n" - " return input - 3;\n" - " }\n" - "}\n"; - - char const* devNatspec = "{\"methods\":{}}"; - char const* userNatspec = "{\"methods\":{}}"; - - checkNatspec(sourceCode, devNatspec, false); - checkNatspec(sourceCode, userNatspec, true); -} - -BOOST_AUTO_TEST_CASE(dev_desc_after_nl) -{ - char const* sourceCode = "contract test {\n" - " /// @dev\n" - " /// Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter\n" - " /// @param second Documentation for the second parameter\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \" Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " }\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_multiple_params) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter\n" - " /// @param second Documentation for the second parameter\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " }\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_mutiline_param_description) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter starts here.\n" - " /// Since it's a really complicated parameter we need 2 lines\n" - " /// @param second Documentation for the second parameter\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " }\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_multiple_functions) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter\n" - " /// @param second Documentation for the second parameter\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - " \n" - " /// @dev Divides 2 numbers\n" - " /// @param input Documentation for the input parameter\n" - " /// @param div Documentation for the div parameter\n" - " function divide(uint input, uint div) returns(uint d)\n" - " {\n" - " return input / div;\n" - " }\n" - " /// @dev Subtracts 3 from `input`\n" - " /// @param input Documentation for the input parameter\n" - " function sub(int input) returns(int d)\n" - " {\n" - " return input - 3;\n" - " }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " }\n" - " },\n" - " \"divide(uint256,uint256)\":{ \n" - " \"details\": \"Divides 2 numbers\",\n" - " \"params\": {\n" - " \"input\": \"Documentation for the input parameter\",\n" - " \"div\": \"Documentation for the div parameter\"\n" - " }\n" - " },\n" - " \"sub(int256)\":{ \n" - " \"details\": \"Subtracts 3 from `input`\",\n" - " \"params\": {\n" - " \"input\": \"Documentation for the input parameter\"\n" - " }\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_return) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter starts here.\n" - " /// Since it's a really complicated parameter we need 2 lines\n" - " /// @param second Documentation for the second parameter\n" - " /// @return The result of the multiplication\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " },\n" - " \"return\": \"The result of the multiplication\"\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} -BOOST_AUTO_TEST_CASE(dev_return_desc_after_nl) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter starts here.\n" - " /// Since it's a really complicated parameter we need 2 lines\n" - " /// @param second Documentation for the second parameter\n" - " /// @return\n" - " /// The result of the multiplication\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " },\n" - " \"return\": \" The result of the multiplication\"\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} - - -BOOST_AUTO_TEST_CASE(dev_multiline_return) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Multiplies a number by 7 and adds second parameter\n" - " /// @param a Documentation for the first parameter starts here.\n" - " /// Since it's a really complicated parameter we need 2 lines\n" - " /// @param second Documentation for the second parameter\n" - " /// @return The result of the multiplication\n" - " /// and cookies with nutella\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " },\n" - " \"return\": \"The result of the multiplication and cookies with nutella\"\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_multiline_comment) -{ - char const* sourceCode = "contract test {\n" - " /**\n" - " * @dev Multiplies a number by 7 and adds second parameter\n" - " * @param a Documentation for the first parameter starts here.\n" - " * Since it's a really complicated parameter we need 2 lines\n" - " * @param second Documentation for the second parameter\n" - " * @return The result of the multiplication\n" - " * and cookies with nutella\n" - " */" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - "\"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Multiplies a number by 7 and adds second parameter\",\n" - " \"params\": {\n" - " \"a\": \"Documentation for the first parameter starts here. Since it's a really complicated parameter we need 2 lines\",\n" - " \"second\": \"Documentation for the second parameter\"\n" - " },\n" - " \"return\": \"The result of the multiplication and cookies with nutella\"\n" - " }\n" - "}}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_contract_no_doc) -{ - char const* sourceCode = "contract test {\n" - " /// @dev Mul function\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - " \"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Mul function\"\n" - " }\n" - " }\n" - "}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_contract_doc) -{ - char const* sourceCode = " /// @author Lefteris\n" - " /// @title Just a test contract\n" - "contract test {\n" - " /// @dev Mul function\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - " \"author\": \"Lefteris\"," - " \"title\": \"Just a test contract\"," - " \"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Mul function\"\n" - " }\n" - " }\n" - "}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(dev_author_at_function) -{ - char const* sourceCode = " /// @author Lefteris\n" - " /// @title Just a test contract\n" - "contract test {\n" - " /// @dev Mul function\n" - " /// @author John Doe\n" - " function mul(uint a, uint second) returns(uint d) { return a * 7 + second; }\n" - "}\n"; - - char const* natspec = "{" - " \"author\": \"Lefteris\"," - " \"title\": \"Just a test contract\"," - " \"methods\":{" - " \"mul(uint256,uint256)\":{ \n" - " \"details\": \"Mul function\",\n" - " \"author\": \"John Doe\",\n" - " }\n" - " }\n" - "}"; - - checkNatspec(sourceCode, natspec, false); -} - -BOOST_AUTO_TEST_CASE(natspec_notice_without_tag) -{ - char const* sourceCode = R"( - contract test { - /// I do something awesome - function mul(uint a) returns(uint d) { return a * 7; } - } - )"; - - - char const* natspec = R"ABCDEF( - { - "methods" : { - "mul(uint256)" : { - "notice" : "I do something awesome" - } - } - } - )ABCDEF"; - - checkNatspec(sourceCode, natspec, true); -} - -BOOST_AUTO_TEST_CASE(natspec_multiline_notice_without_tag) -{ - char const* sourceCode = R"( - contract test { - /// I do something awesome - /// which requires two lines to explain - function mul(uint a) returns(uint d) { return a * 7; } - } - )"; - - char const* natspec = R"ABCDEF( - { - "methods" : { - "mul(uint256)" : { - "notice" : "I do something awesome which requires two lines to explain" - } - } - } - )ABCDEF"; - - checkNatspec(sourceCode, natspec, true); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} diff --git a/test/libsolidity/SolidityOptimizer.cpp b/test/libsolidity/SolidityOptimizer.cpp deleted file mode 100644 index 85a88c030..000000000 --- a/test/libsolidity/SolidityOptimizer.cpp +++ /dev/null @@ -1,1132 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Tests for the Solidity optimizer. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; -using namespace dev::eth; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -class OptimizerTestFramework: public ExecutionFramework -{ -public: - OptimizerTestFramework() { } - /// Compiles the source code with and without optimizing. - void compileBothVersions( - std::string const& _sourceCode, - u256 const& _value = 0, - std::string const& _contractName = "" - ) - { - m_optimize = false; - bytes nonOptimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); - m_nonOptimizedContract = m_contractAddress; - m_optimize = true; - bytes optimizedBytecode = compileAndRun(_sourceCode, _value, _contractName); - size_t nonOptimizedSize = 0; - eth::eachInstruction(nonOptimizedBytecode, [&](Instruction, u256 const&) { - nonOptimizedSize++; - }); - size_t optimizedSize = 0; - eth::eachInstruction(optimizedBytecode, [&](Instruction, u256 const&) { - optimizedSize++; - }); - BOOST_CHECK_MESSAGE( - nonOptimizedSize > optimizedSize, - "Optimizer did not reduce bytecode size." - ); - m_optimizedContract = m_contractAddress; - } - - template - void compareVersions(std::string _sig, Args const&... _arguments) - { - m_contractAddress = m_nonOptimizedContract; - bytes nonOptimizedOutput = callContractFunction(_sig, _arguments...); - m_contractAddress = m_optimizedContract; - bytes optimizedOutput = callContractFunction(_sig, _arguments...); - BOOST_CHECK_MESSAGE(nonOptimizedOutput == optimizedOutput, "Computed values do not match." - "\nNon-Optimized: " + toHex(nonOptimizedOutput) + - "\nOptimized: " + toHex(optimizedOutput)); - } - - AssemblyItems addDummyLocations(AssemblyItems const& _input) - { - // add dummy locations to each item so that we can check that they are not deleted - AssemblyItems input = _input; - for (AssemblyItem& item: input) - item.setLocation(SourceLocation(1, 3, make_shared(""))); - return input; - } - - eth::KnownState createInitialState(AssemblyItems const& _input) - { - eth::KnownState state; - for (auto const& item: addDummyLocations(_input)) - state.feedItem(item, true); - return state; - } - - AssemblyItems getCSE(AssemblyItems const& _input, eth::KnownState const& _state = eth::KnownState()) - { - AssemblyItems input = addDummyLocations(_input); - - eth::CommonSubexpressionEliminator cse(_state); - BOOST_REQUIRE(cse.feedItems(input.begin(), input.end()) == input.end()); - AssemblyItems output = cse.getOptimizedItems(); - - for (AssemblyItem const& item: output) - { - BOOST_CHECK(item == Instruction::POP || !item.getLocation().isEmpty()); - } - return output; - } - - void checkCSE( - AssemblyItems const& _input, - AssemblyItems const& _expectation, - KnownState const& _state = eth::KnownState() - ) - { - AssemblyItems output = getCSE(_input, _state); - BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end()); - } - - AssemblyItems getCFG(AssemblyItems const& _input) - { - AssemblyItems output = _input; - // Running it four times should be enough for these tests. - for (unsigned i = 0; i < 4; ++i) - { - ControlFlowGraph cfg(output); - AssemblyItems optItems; - for (BasicBlock const& block: cfg.optimisedBlocks()) - copy(output.begin() + block.begin, output.begin() + block.end, - back_inserter(optItems)); - output = move(optItems); - } - return output; - } - - void checkCFG(AssemblyItems const& _input, AssemblyItems const& _expectation) - { - AssemblyItems output = getCFG(_input); - BOOST_CHECK_EQUAL_COLLECTIONS(_expectation.begin(), _expectation.end(), output.begin(), output.end()); - } - -protected: - Address m_optimizedContract; - Address m_nonOptimizedContract; -}; - -BOOST_FIXTURE_TEST_SUITE(SolidityOptimizer, OptimizerTestFramework) - -BOOST_AUTO_TEST_CASE(smoke_test) -{ - char const* sourceCode = R"( - contract test { - function f(uint a) returns (uint b) { - return a; - } - })"; - compileBothVersions(sourceCode); - compareVersions("f(uint256)", u256(7)); -} - -BOOST_AUTO_TEST_CASE(identities) -{ - char const* sourceCode = R"( - contract test { - function f(int a) returns (int b) { - return int(0) | (int(1) * (int(0) ^ (0 + a))); - } - })"; - compileBothVersions(sourceCode); - compareVersions("f(uint256)", u256(0x12334664)); -} - -BOOST_AUTO_TEST_CASE(unused_expressions) -{ - char const* sourceCode = R"( - contract test { - uint data; - function f() returns (uint a, uint b) { - 10 + 20; - data; - } - })"; - compileBothVersions(sourceCode); - compareVersions("f()"); -} - -BOOST_AUTO_TEST_CASE(constant_folding_both_sides) -{ - // if constants involving the same associative and commutative operator are applied from both - // sides, the operator should be applied only once, because the expression compiler pushes - // literals as late as possible - char const* sourceCode = R"( - contract test { - function f(uint x) returns (uint y) { - return 98 ^ (7 * ((1 | (x | 1000)) * 40) ^ 102); - } - })"; - compileBothVersions(sourceCode); - compareVersions("f(uint256)"); -} - -BOOST_AUTO_TEST_CASE(storage_access) -{ - char const* sourceCode = R"( - contract test { - uint8[40] data; - function f(uint x) returns (uint y) { - data[2] = data[7] = uint8(x); - data[4] = data[2] * 10 + data[3]; - } - } - )"; - compileBothVersions(sourceCode); - compareVersions("f(uint256)"); -} - -BOOST_AUTO_TEST_CASE(array_copy) -{ - char const* sourceCode = R"( - contract test { - bytes2[] data1; - bytes5[] data2; - function f(uint x) returns (uint l, uint y) { - for (uint i = 0; i < msg.data.length; ++i) - data1[i] = msg.data[i]; - data2 = data1; - l = data2.length; - y = uint(data2[x]); - } - } - )"; - compileBothVersions(sourceCode); - compareVersions("f(uint256)", 0); - compareVersions("f(uint256)", 10); - compareVersions("f(uint256)", 36); -} - -BOOST_AUTO_TEST_CASE(function_calls) -{ - char const* sourceCode = R"( - contract test { - function f1(uint x) returns (uint) { return x*x; } - function f(uint x) returns (uint) { return f1(7+x) - this.f1(x**9); } - } - )"; - compileBothVersions(sourceCode); - compareVersions("f(uint256)", 0); - compareVersions("f(uint256)", 10); - compareVersions("f(uint256)", 36); -} - -BOOST_AUTO_TEST_CASE(storage_write_in_loops) -{ - char const* sourceCode = R"( - contract test { - uint d; - function f(uint a) returns (uint r) { - var x = d; - for (uint i = 1; i < a * a; i++) { - r = d; - d = i; - } - - } - } - )"; - compileBothVersions(sourceCode); - compareVersions("f(uint256)", 0); - compareVersions("f(uint256)", 10); - compareVersions("f(uint256)", 36); -} - -BOOST_AUTO_TEST_CASE(retain_information_in_branches) -{ - // This tests that the optimizer knows that we already have "z == sha3(y)" inside both branches. - char const* sourceCode = R"( - contract c { - bytes32 d; - uint a; - function f(uint x, bytes32 y) returns (uint r_a, bytes32 r_d) { - bytes32 z = sha3(y); - if (x > 8) { - z = sha3(y); - a = x; - } else { - z = sha3(y); - a = x; - } - r_a = a; - r_d = d; - } - } - )"; - compileBothVersions(sourceCode); - compareVersions("f(uint256,bytes32)", 0, "abc"); - compareVersions("f(uint256,bytes32)", 8, "def"); - compareVersions("f(uint256,bytes32)", 10, "ghi"); - - m_optimize = true; - bytes optimizedBytecode = compileAndRun(sourceCode, 0, "c"); - size_t numSHA3s = 0; - eth::eachInstruction(optimizedBytecode, [&](Instruction _instr, u256 const&) { - if (_instr == eth::Instruction::SHA3) - numSHA3s++; - }); - BOOST_CHECK_EQUAL(1, numSHA3s); -} - -BOOST_AUTO_TEST_CASE(store_tags_as_unions) -{ - // This calls the same function from two sources and both calls have a certain sha3 on - // the stack at the same position. - // Without storing tags as unions, the return from the shared function would not know where to - // jump and thus all jumpdests are forced to clear their state and we do not know about the - // sha3 anymore. - // Note that, for now, this only works if the functions have the same number of return - // parameters since otherwise, the return jump addresses are at different stack positions - // which triggers the "unknown jump target" situation. - char const* sourceCode = R"( - contract test { - bytes32 data; - function f(uint x, bytes32 y) external returns (uint r_a, bytes32 r_d) { - r_d = sha3(y); - shared(y); - r_d = sha3(y); - r_a = 5; - } - function g(uint x, bytes32 y) external returns (uint r_a, bytes32 r_d) { - r_d = sha3(y); - shared(y); - r_d = bytes32(uint(sha3(y)) + 2); - r_a = 7; - } - function shared(bytes32 y) internal { - data = sha3(y); - } - } - )"; - compileBothVersions(sourceCode); - compareVersions("f()", 7, "abc"); - - m_optimize = true; - bytes optimizedBytecode = compileAndRun(sourceCode, 0, "test"); - size_t numSHA3s = 0; - eth::eachInstruction(optimizedBytecode, [&](Instruction _instr, u256 const&) { - if (_instr == eth::Instruction::SHA3) - numSHA3s++; - }); -// TEST DISABLED UNTIL 93693404 IS IMPLEMENTED -// BOOST_CHECK_EQUAL(2, numSHA3s); -} - -BOOST_AUTO_TEST_CASE(cse_intermediate_swap) -{ - eth::KnownState state; - eth::CommonSubexpressionEliminator cse(state); - AssemblyItems input{ - Instruction::SWAP1, Instruction::POP, Instruction::ADD, u256(0), Instruction::SWAP1, - Instruction::SLOAD, Instruction::SWAP1, u256(100), Instruction::EXP, Instruction::SWAP1, - Instruction::DIV, u256(0xff), Instruction::AND - }; - BOOST_REQUIRE(cse.feedItems(input.begin(), input.end()) == input.end()); - AssemblyItems output = cse.getOptimizedItems(); - BOOST_CHECK(!output.empty()); -} - -BOOST_AUTO_TEST_CASE(cse_negative_stack_access) -{ - AssemblyItems input{Instruction::DUP2, u256(0)}; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_negative_stack_end) -{ - AssemblyItems input{Instruction::ADD}; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_intermediate_negative_stack) -{ - AssemblyItems input{Instruction::ADD, u256(1), Instruction::DUP1}; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_pop) -{ - checkCSE({Instruction::POP}, {Instruction::POP}); -} - -BOOST_AUTO_TEST_CASE(cse_unneeded_items) -{ - AssemblyItems input{ - Instruction::ADD, - Instruction::SWAP1, - Instruction::POP, - u256(7), - u256(8), - }; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_constant_addition) -{ - AssemblyItems input{u256(7), u256(8), Instruction::ADD}; - checkCSE(input, {u256(7 + 8)}); -} - -BOOST_AUTO_TEST_CASE(cse_invariants) -{ - AssemblyItems input{ - Instruction::DUP1, - Instruction::DUP1, - u256(0), - Instruction::OR, - Instruction::OR - }; - checkCSE(input, {Instruction::DUP1}); -} - -BOOST_AUTO_TEST_CASE(cse_subself) -{ - checkCSE({Instruction::DUP1, Instruction::SUB}, {Instruction::POP, u256(0)}); -} - -BOOST_AUTO_TEST_CASE(cse_subother) -{ - checkCSE({Instruction::SUB}, {Instruction::SUB}); -} - -BOOST_AUTO_TEST_CASE(cse_double_negation) -{ - checkCSE({Instruction::DUP5, Instruction::NOT, Instruction::NOT}, {Instruction::DUP5}); -} - -BOOST_AUTO_TEST_CASE(cse_double_iszero) -{ - checkCSE({Instruction::GT, Instruction::ISZERO, Instruction::ISZERO}, {Instruction::GT}); - checkCSE({Instruction::GT, Instruction::ISZERO}, {Instruction::GT, Instruction::ISZERO}); - checkCSE( - {Instruction::ISZERO, Instruction::ISZERO, Instruction::ISZERO}, - {Instruction::ISZERO} - ); -} - -BOOST_AUTO_TEST_CASE(cse_associativity) -{ - AssemblyItems input{ - Instruction::DUP1, - Instruction::DUP1, - u256(0), - Instruction::OR, - Instruction::OR - }; - checkCSE(input, {Instruction::DUP1}); -} - -BOOST_AUTO_TEST_CASE(cse_associativity2) -{ - AssemblyItems input{ - u256(0), - Instruction::DUP2, - u256(2), - u256(1), - Instruction::DUP6, - Instruction::ADD, - u256(2), - Instruction::ADD, - Instruction::ADD, - Instruction::ADD, - Instruction::ADD - }; - checkCSE(input, {Instruction::DUP2, Instruction::DUP2, Instruction::ADD, u256(5), Instruction::ADD}); -} - -BOOST_AUTO_TEST_CASE(cse_storage) -{ - AssemblyItems input{ - u256(0), - Instruction::SLOAD, - u256(0), - Instruction::SLOAD, - Instruction::ADD, - u256(0), - Instruction::SSTORE - }; - checkCSE(input, { - u256(0), - Instruction::DUP1, - Instruction::SLOAD, - Instruction::DUP1, - Instruction::ADD, - Instruction::SWAP1, - Instruction::SSTORE - }); -} - -BOOST_AUTO_TEST_CASE(cse_noninterleaved_storage) -{ - // two stores to the same location should be replaced by only one store, even if we - // read in the meantime - AssemblyItems input{ - u256(7), - Instruction::DUP2, - Instruction::SSTORE, - Instruction::DUP1, - Instruction::SLOAD, - u256(8), - Instruction::DUP3, - Instruction::SSTORE - }; - checkCSE(input, { - u256(8), - Instruction::DUP2, - Instruction::SSTORE, - u256(7) - }); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage) -{ - // stores and reads to/from two unknown locations, should not optimize away the first store - AssemblyItems input{ - u256(7), - Instruction::DUP2, - Instruction::SSTORE, // store to "DUP1" - Instruction::DUP2, - Instruction::SLOAD, // read from "DUP2", might be equal to "DUP1" - u256(0), - Instruction::DUP3, - Instruction::SSTORE // store different value to "DUP1" - }; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage_same_value) -{ - // stores and reads to/from two unknown locations, should not optimize away the first store - // but it should optimize away the second, since we already know the value will be the same - AssemblyItems input{ - u256(7), - Instruction::DUP2, - Instruction::SSTORE, // store to "DUP1" - Instruction::DUP2, - Instruction::SLOAD, // read from "DUP2", might be equal to "DUP1" - u256(6), - u256(1), - Instruction::ADD, - Instruction::DUP3, - Instruction::SSTORE // store same value to "DUP1" - }; - checkCSE(input, { - u256(7), - Instruction::DUP2, - Instruction::SSTORE, - Instruction::DUP2, - Instruction::SLOAD - }); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage_at_known_location) -{ - // stores and reads to/from two known locations, should optimize away the first store, - // because we know that the location is different - AssemblyItems input{ - u256(0x70), - u256(1), - Instruction::SSTORE, // store to 1 - u256(2), - Instruction::SLOAD, // read from 2, is different from 1 - u256(0x90), - u256(1), - Instruction::SSTORE // store different value at 1 - }; - checkCSE(input, { - u256(2), - Instruction::SLOAD, - u256(0x90), - u256(1), - Instruction::SSTORE - }); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_storage_at_known_location_offset) -{ - // stores and reads to/from two locations which are known to be different, - // should optimize away the first store, because we know that the location is different - AssemblyItems input{ - u256(0x70), - Instruction::DUP2, - u256(1), - Instruction::ADD, - Instruction::SSTORE, // store to "DUP1"+1 - Instruction::DUP1, - u256(2), - Instruction::ADD, - Instruction::SLOAD, // read from "DUP1"+2, is different from "DUP1"+1 - u256(0x90), - Instruction::DUP3, - u256(1), - Instruction::ADD, - Instruction::SSTORE // store different value at "DUP1"+1 - }; - checkCSE(input, { - u256(2), - Instruction::DUP2, - Instruction::ADD, - Instruction::SLOAD, - u256(0x90), - u256(1), - Instruction::DUP4, - Instruction::ADD, - Instruction::SSTORE - }); -} - -BOOST_AUTO_TEST_CASE(cse_interleaved_memory_at_known_location_offset) -{ - // stores and reads to/from two locations which are known to be different, - // should not optimize away the first store, because the location overlaps with the load, - // but it should optimize away the second, because we know that the location is different by 32 - AssemblyItems input{ - u256(0x50), - Instruction::DUP2, - u256(2), - Instruction::ADD, - Instruction::MSTORE, // ["DUP1"+2] = 0x50 - u256(0x60), - Instruction::DUP2, - u256(32), - Instruction::ADD, - Instruction::MSTORE, // ["DUP1"+32] = 0x60 - Instruction::DUP1, - Instruction::MLOAD, // read from "DUP1" - u256(0x70), - Instruction::DUP3, - u256(32), - Instruction::ADD, - Instruction::MSTORE, // ["DUP1"+32] = 0x70 - u256(0x80), - Instruction::DUP3, - u256(2), - Instruction::ADD, - Instruction::MSTORE, // ["DUP1"+2] = 0x80 - }; - // If the actual code changes too much, we could also simply check that the output contains - // exactly 3 MSTORE and exactly 1 MLOAD instruction. - checkCSE(input, { - u256(0x50), - u256(2), - Instruction::DUP3, - Instruction::ADD, - Instruction::SWAP1, - Instruction::DUP2, - Instruction::MSTORE, // ["DUP1"+2] = 0x50 - Instruction::DUP2, - Instruction::MLOAD, // read from "DUP1" - u256(0x70), - u256(32), - Instruction::DUP5, - Instruction::ADD, - Instruction::MSTORE, // ["DUP1"+32] = 0x70 - u256(0x80), - Instruction::SWAP1, - Instruction::SWAP2, - Instruction::MSTORE // ["DUP1"+2] = 0x80 - }); -} - -BOOST_AUTO_TEST_CASE(cse_deep_stack) -{ - AssemblyItems input{ - Instruction::ADD, - Instruction::SWAP1, - Instruction::POP, - Instruction::SWAP8, - Instruction::POP, - Instruction::SWAP8, - Instruction::POP, - Instruction::SWAP8, - Instruction::SWAP5, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - }; - checkCSE(input, { - Instruction::SWAP4, - Instruction::SWAP12, - Instruction::SWAP3, - Instruction::SWAP11, - Instruction::POP, - Instruction::SWAP1, - Instruction::SWAP3, - Instruction::ADD, - Instruction::SWAP8, - Instruction::POP, - Instruction::SWAP6, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - Instruction::POP, - }); -} - -BOOST_AUTO_TEST_CASE(cse_jumpi_no_jump) -{ - AssemblyItems input{ - u256(0), - u256(1), - Instruction::DUP2, - AssemblyItem(PushTag, 1), - Instruction::JUMPI - }; - checkCSE(input, { - u256(0), - u256(1) - }); -} - -BOOST_AUTO_TEST_CASE(cse_jumpi_jump) -{ - AssemblyItems input{ - u256(1), - u256(1), - Instruction::DUP2, - AssemblyItem(PushTag, 1), - Instruction::JUMPI - }; - checkCSE(input, { - u256(1), - Instruction::DUP1, - AssemblyItem(PushTag, 1), - Instruction::JUMP - }); -} - -BOOST_AUTO_TEST_CASE(cse_empty_sha3) -{ - AssemblyItems input{ - u256(0), - Instruction::DUP2, - Instruction::SHA3 - }; - checkCSE(input, { - u256(sha3(bytesConstRef())) - }); -} - -BOOST_AUTO_TEST_CASE(cse_partial_sha3) -{ - AssemblyItems input{ - u256(0xabcd) << (256 - 16), - u256(0), - Instruction::MSTORE, - u256(2), - u256(0), - Instruction::SHA3 - }; - checkCSE(input, { - u256(0xabcd) << (256 - 16), - u256(0), - Instruction::MSTORE, - u256(sha3(bytes{0xab, 0xcd})) - }); -} - -BOOST_AUTO_TEST_CASE(cse_sha3_twice_same_location) -{ - // sha3 twice from same dynamic location - AssemblyItems input{ - Instruction::DUP2, - Instruction::DUP1, - Instruction::MSTORE, - u256(64), - Instruction::DUP2, - Instruction::SHA3, - u256(64), - Instruction::DUP3, - Instruction::SHA3 - }; - checkCSE(input, { - Instruction::DUP2, - Instruction::DUP1, - Instruction::MSTORE, - u256(64), - Instruction::DUP2, - Instruction::SHA3, - Instruction::DUP1 - }); -} - -BOOST_AUTO_TEST_CASE(cse_sha3_twice_same_content) -{ - // sha3 twice from different dynamic location but with same content - AssemblyItems input{ - Instruction::DUP1, - u256(0x80), - Instruction::MSTORE, // m[128] = DUP1 - u256(0x20), - u256(0x80), - Instruction::SHA3, // sha3(m[128..(128+32)]) - Instruction::DUP2, - u256(12), - Instruction::MSTORE, // m[12] = DUP1 - u256(0x20), - u256(12), - Instruction::SHA3 // sha3(m[12..(12+32)]) - }; - checkCSE(input, { - u256(0x80), - Instruction::DUP2, - Instruction::DUP2, - Instruction::MSTORE, - u256(0x20), - Instruction::SWAP1, - Instruction::SHA3, - u256(12), - Instruction::DUP3, - Instruction::SWAP1, - Instruction::MSTORE, - Instruction::DUP1 - }); -} - -BOOST_AUTO_TEST_CASE(cse_sha3_twice_same_content_dynamic_store_in_between) -{ - // sha3 twice from different dynamic location but with same content, - // dynamic mstore in between, which forces us to re-calculate the sha3 - AssemblyItems input{ - u256(0x80), - Instruction::DUP2, - Instruction::DUP2, - Instruction::MSTORE, // m[128] = DUP1 - u256(0x20), - Instruction::DUP1, - Instruction::DUP3, - Instruction::SHA3, // sha3(m[128..(128+32)]) - u256(12), - Instruction::DUP5, - Instruction::DUP2, - Instruction::MSTORE, // m[12] = DUP1 - Instruction::DUP12, - Instruction::DUP14, - Instruction::MSTORE, // destroys memory knowledge - Instruction::SWAP2, - Instruction::SWAP1, - Instruction::SWAP2, - Instruction::SHA3 // sha3(m[12..(12+32)]) - }; - checkCSE(input, input); -} - -BOOST_AUTO_TEST_CASE(cse_sha3_twice_same_content_noninterfering_store_in_between) -{ - // sha3 twice from different dynamic location but with same content, - // dynamic mstore in between, but does not force us to re-calculate the sha3 - AssemblyItems input{ - u256(0x80), - Instruction::DUP2, - Instruction::DUP2, - Instruction::MSTORE, // m[128] = DUP1 - u256(0x20), - Instruction::DUP1, - Instruction::DUP3, - Instruction::SHA3, // sha3(m[128..(128+32)]) - u256(12), - Instruction::DUP5, - Instruction::DUP2, - Instruction::MSTORE, // m[12] = DUP1 - Instruction::DUP12, - u256(12 + 32), - Instruction::MSTORE, // does not destoy memory knowledge - Instruction::DUP13, - u256(128 - 32), - Instruction::MSTORE, // does not destoy memory knowledge - u256(0x20), - u256(12), - Instruction::SHA3 // sha3(m[12..(12+32)]) - }; - // if this changes too often, only count the number of SHA3 and MSTORE instructions - AssemblyItems output = getCSE(input); - BOOST_CHECK_EQUAL(4, count(output.begin(), output.end(), AssemblyItem(Instruction::MSTORE))); - BOOST_CHECK_EQUAL(1, count(output.begin(), output.end(), AssemblyItem(Instruction::SHA3))); -} - -BOOST_AUTO_TEST_CASE(cse_with_initially_known_stack) -{ - eth::KnownState state = createInitialState(AssemblyItems{ - u256(0x12), - u256(0x20), - Instruction::ADD - }); - AssemblyItems input{ - u256(0x12 + 0x20) - }; - checkCSE(input, AssemblyItems{Instruction::DUP1}, state); -} - -BOOST_AUTO_TEST_CASE(cse_equality_on_initially_known_stack) -{ - eth::KnownState state = createInitialState(AssemblyItems{Instruction::DUP1}); - AssemblyItems input{ - Instruction::EQ - }; - AssemblyItems output = getCSE(input, state); - // check that it directly pushes 1 (true) - BOOST_CHECK(find(output.begin(), output.end(), AssemblyItem(u256(1))) != output.end()); -} - -BOOST_AUTO_TEST_CASE(cse_access_previous_sequence) -{ - // Tests that the code generator detects whether it tries to access SLOAD instructions - // from a sequenced expression which is not in its scope. - eth::KnownState state = createInitialState(AssemblyItems{ - u256(0), - Instruction::SLOAD, - u256(1), - Instruction::ADD, - u256(0), - Instruction::SSTORE - }); - // now stored: val_1 + 1 (value at sequence 1) - // if in the following instructions, the SLOAD cresolves to "val_1 + 1", - // this cannot be generated because we cannot load from sequence 1 anymore. - AssemblyItems input{ - u256(0), - Instruction::SLOAD, - }; - BOOST_CHECK_THROW(getCSE(input, state), StackTooDeepException); - // @todo for now, this throws an exception, but it should recover to the following - // (or an even better version) at some point: - // 0, SLOAD, 1, ADD, SSTORE, 0 SLOAD -} - -BOOST_AUTO_TEST_CASE(cse_optimise_return) -{ - checkCSE( - AssemblyItems{u256(0), u256(7), Instruction::RETURN}, - AssemblyItems{Instruction::STOP} - ); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_remove_unused) -{ - // remove parts of the code that are unused - AssemblyItems input{ - AssemblyItem(PushTag, 1), - Instruction::JUMP, - u256(7), - AssemblyItem(Tag, 1), - }; - checkCFG(input, {}); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_remove_unused_loop) -{ - AssemblyItems input{ - AssemblyItem(PushTag, 3), - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(7), - AssemblyItem(PushTag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(8), - AssemblyItem(PushTag, 1), - Instruction::JUMP, - AssemblyItem(Tag, 3), - u256(11) - }; - checkCFG(input, {u256(11)}); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_reconnect_single_jump_source) -{ - // move code that has only one unconditional jump source - AssemblyItems input{ - u256(1), - AssemblyItem(PushTag, 1), - Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(2), - AssemblyItem(PushTag, 3), - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(3), - AssemblyItem(PushTag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 3), - u256(4), - }; - checkCFG(input, {u256(1), u256(3), u256(2), u256(4)}); -} - -BOOST_AUTO_TEST_CASE(control_flow_graph_do_not_remove_returned_to) -{ - // do not remove parts that are "returned to" - AssemblyItems input{ - AssemblyItem(PushTag, 1), - AssemblyItem(PushTag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 2), - Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(2) - }; - checkCFG(input, {u256(2)}); -} - -BOOST_AUTO_TEST_CASE(block_deduplicator) -{ - AssemblyItems input{ - AssemblyItem(PushTag, 2), - AssemblyItem(PushTag, 1), - AssemblyItem(PushTag, 3), - u256(6), - eth::Instruction::SWAP3, - eth::Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(6), - eth::Instruction::SWAP3, - eth::Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(6), - eth::Instruction::SWAP3, - eth::Instruction::JUMP, - AssemblyItem(Tag, 3) - }; - BlockDeduplicator dedup(input); - dedup.deduplicate(); - - set pushTags; - for (AssemblyItem const& item: input) - if (item.type() == PushTag) - pushTags.insert(item.data()); - BOOST_CHECK_EQUAL(pushTags.size(), 2); -} - -BOOST_AUTO_TEST_CASE(block_deduplicator_loops) -{ - AssemblyItems input{ - u256(0), - eth::Instruction::SLOAD, - AssemblyItem(PushTag, 1), - AssemblyItem(PushTag, 2), - eth::Instruction::JUMPI, - eth::Instruction::JUMP, - AssemblyItem(Tag, 1), - u256(5), - u256(6), - eth::Instruction::SSTORE, - AssemblyItem(PushTag, 1), - eth::Instruction::JUMP, - AssemblyItem(Tag, 2), - u256(5), - u256(6), - eth::Instruction::SSTORE, - AssemblyItem(PushTag, 2), - eth::Instruction::JUMP, - }; - BlockDeduplicator dedup(input); - dedup.deduplicate(); - - set pushTags; - for (AssemblyItem const& item: input) - if (item.type() == PushTag) - pushTags.insert(item.data()); - BOOST_CHECK_EQUAL(pushTags.size(), 1); -} - -BOOST_AUTO_TEST_CASE(computing_constants) -{ - char const* sourceCode = R"( - contract c { - uint a; - uint b; - uint c; - function set() returns (uint a, uint b, uint c) { - a = 0x77abc0000000000000000000000000000000000000000000000000000000001; - b = 0x817416927846239487123469187231298734162934871263941234127518276; - g(); - } - function g() { - b = 0x817416927846239487123469187231298734162934871263941234127518276; - c = 0x817416927846239487123469187231298734162934871263941234127518276; - } - function get() returns (uint ra, uint rb, uint rc) { - ra = a; - rb = b; - rc = c ; - } - } - )"; - compileBothVersions(sourceCode); - compareVersions("set()"); - compareVersions("get()"); - - m_optimize = true; - m_optimizeRuns = 1; - bytes optimizedBytecode = compileAndRun(sourceCode, 0, "c"); - bytes complicatedConstant = toBigEndian(u256("0x817416927846239487123469187231298734162934871263941234127518276")); - unsigned occurrences = 0; - for (auto iter = optimizedBytecode.cbegin(); iter < optimizedBytecode.cend(); ++occurrences) - iter = search(iter, optimizedBytecode.cend(), complicatedConstant.cbegin(), complicatedConstant.cend()) + 1; - BOOST_CHECK_EQUAL(2, occurrences); - - bytes constantWithZeros = toBigEndian(u256("0x77abc0000000000000000000000000000000000000000000000000000000001")); - BOOST_CHECK(search( - optimizedBytecode.cbegin(), - optimizedBytecode.cend(), - constantWithZeros.cbegin(), - constantWithZeros.cend() - ) == optimizedBytecode.cend()); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/SolidityParser.cpp b/test/libsolidity/SolidityParser.cpp deleted file mode 100644 index 438e650bf..000000000 --- a/test/libsolidity/SolidityParser.cpp +++ /dev/null @@ -1,921 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Unit tests for the solidity parser. - */ - -#include -#include -#include -#include -#include -#include -#include "../TestHelper.h" - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -namespace -{ -ASTPointer parseText(std::string const& _source) -{ - Parser parser; - ASTPointer sourceUnit = parser.parse(std::make_shared(CharStream(_source))); - for (ASTPointer const& node: sourceUnit->getNodes()) - if (ASTPointer contract = dynamic_pointer_cast(node)) - return contract; - BOOST_FAIL("No contract found in source."); - return ASTPointer(); -} - -static void checkFunctionNatspec(ASTPointer _function, - std::string const& _expectedDoc) -{ - auto doc = _function->getDocumentation(); - BOOST_CHECK_MESSAGE(doc != nullptr, "Function does not have Natspec Doc as expected"); - BOOST_CHECK_EQUAL(*doc, _expectedDoc); -} - -} - - -BOOST_AUTO_TEST_SUITE(SolidityParser) - -BOOST_AUTO_TEST_CASE(smoke_test) -{ - char const* text = "contract test {\n" - " uint256 stateVariable1;\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed."); -} - -BOOST_AUTO_TEST_CASE(missing_variable_name_in_declaration) -{ - char const* text = "contract test {\n" - " uint256 ;\n" - "}\n"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(empty_function) -{ - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " function functionName(bytes20 arg1, address addr) constant\n" - " returns (int id)\n" - " { }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed."); -} - -BOOST_AUTO_TEST_CASE(no_function_params) -{ - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " function functionName() {}\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed."); -} - -BOOST_AUTO_TEST_CASE(single_function_param) -{ - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " function functionName(bytes32 input) returns (bytes32 out) {}\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed."); -} - -BOOST_AUTO_TEST_CASE(function_no_body) -{ - char const* text = "contract test {\n" - " function functionName(bytes32 input) returns (bytes32 out);\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed."); -} - -BOOST_AUTO_TEST_CASE(missing_parameter_name_in_named_args) -{ - char const* text = "contract test {\n" - " function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; }\n" - " function b() returns (uint r) { r = a({: 1, : 2, : 3}); }\n" - "}\n"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(missing_argument_in_named_args) -{ - char const* text = "contract test {\n" - " function a(uint a, uint b, uint c) returns (uint r) { r = a * 100 + b * 10 + c * 1; }\n" - " function b() returns (uint r) { r = a({a: , b: , c: }); }\n" - "}\n"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(two_exact_functions) -{ - char const* text = R"( - contract test { - function fun(uint a) returns(uint r) { return a; } - function fun(uint a) returns(uint r) { return a; } - } - )"; - // with support of overloaded functions, during parsing, - // we can't determine whether they match exactly, however - // it will throw DeclarationError in following stage. - BOOST_CHECK_NO_THROW(parseText(text)); -} - -BOOST_AUTO_TEST_CASE(overloaded_functions) -{ - char const* text = R"( - contract test { - function fun(uint a) returns(uint r) { return a; } - function fun(uint a, uint b) returns(uint r) { return a + b; } - } - )"; - BOOST_CHECK_NO_THROW(parseText(text)); -} - -BOOST_AUTO_TEST_CASE(function_natspec_documentation) -{ - ASTPointer contract; - ASTPointer function; - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " /// This is a test function\n" - " function functionName(bytes32 input) returns (bytes32 out) {}\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); - auto functions = contract->getDefinedFunctions(); - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); - checkFunctionNatspec(function, "This is a test function"); -} - -BOOST_AUTO_TEST_CASE(function_normal_comments) -{ - ASTPointer contract; - ASTPointer function; - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " // We won't see this comment\n" - " function functionName(bytes32 input) returns (bytes32 out) {}\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); - auto functions = contract->getDefinedFunctions(); - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); - BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, - "Should not have gotten a Natspecc comment for this function"); -} - -BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation) -{ - ASTPointer contract; - ASTPointer function; - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " /// This is test function 1\n" - " function functionName1(bytes32 input) returns (bytes32 out) {}\n" - " /// This is test function 2\n" - " function functionName2(bytes32 input) returns (bytes32 out) {}\n" - " // nothing to see here\n" - " function functionName3(bytes32 input) returns (bytes32 out) {}\n" - " /// This is test function 4\n" - " function functionName4(bytes32 input) returns (bytes32 out) {}\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); - auto functions = contract->getDefinedFunctions(); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); - checkFunctionNatspec(function, "This is test function 1"); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(1), "Failed to retrieve function"); - checkFunctionNatspec(function, "This is test function 2"); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(2), "Failed to retrieve function"); - BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, - "Should not have gotten natspec comment for functionName3()"); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(3), "Failed to retrieve function"); - checkFunctionNatspec(function, "This is test function 4"); -} - -BOOST_AUTO_TEST_CASE(multiline_function_documentation) -{ - ASTPointer contract; - ASTPointer function; - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " /// This is a test function\n" - " /// and it has 2 lines\n" - " function functionName1(bytes32 input) returns (bytes32 out) {}\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); - auto functions = contract->getDefinedFunctions(); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); - checkFunctionNatspec(function, "This is a test function\n" - " and it has 2 lines"); -} - -BOOST_AUTO_TEST_CASE(natspec_comment_in_function_body) -{ - ASTPointer contract; - ASTPointer function; - char const* text = "contract test {\n" - " /// fun1 description\n" - " function fun1(uint256 a) {\n" - " var b;\n" - " /// I should not interfere with actual natspec comments\n" - " uint256 c;\n" - " mapping(address=>bytes32) d;\n" - " bytes7 name = \"Solidity\";" - " }\n" - " /// This is a test function\n" - " /// and it has 2 lines\n" - " function fun(bytes32 input) returns (bytes32 out) {}\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); - auto functions = contract->getDefinedFunctions(); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); - checkFunctionNatspec(function, "fun1 description"); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(1), "Failed to retrieve function"); - checkFunctionNatspec(function, "This is a test function\n" - " and it has 2 lines"); -} - -BOOST_AUTO_TEST_CASE(natspec_docstring_between_keyword_and_signature) -{ - ASTPointer contract; - ASTPointer function; - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " function ///I am in the wrong place \n" - " fun1(uint256 a) {\n" - " var b;\n" - " /// I should not interfere with actual natspec comments\n" - " uint256 c;\n" - " mapping(address=>bytes32) d;\n" - " bytes7 name = \"Solidity\";" - " }\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); - auto functions = contract->getDefinedFunctions(); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); - BOOST_CHECK_MESSAGE(!function->getDocumentation(), - "Shouldn't get natspec docstring for this function"); -} - -BOOST_AUTO_TEST_CASE(natspec_docstring_after_signature) -{ - ASTPointer contract; - ASTPointer function; - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " function fun1(uint256 a) {\n" - " /// I should have been above the function signature\n" - " var b;\n" - " /// I should not interfere with actual natspec comments\n" - " uint256 c;\n" - " mapping(address=>bytes32) d;\n" - " bytes7 name = \"Solidity\";" - " }\n" - "}\n"; - ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); - auto functions = contract->getDefinedFunctions(); - - ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); - BOOST_CHECK_MESSAGE(!function->getDocumentation(), - "Shouldn't get natspec docstring for this function"); -} - -BOOST_AUTO_TEST_CASE(struct_definition) -{ - char const* text = "contract test {\n" - " uint256 stateVar;\n" - " struct MyStructName {\n" - " address addr;\n" - " uint256 count;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(mapping) -{ - char const* text = "contract test {\n" - " mapping(address => bytes32) names;\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(mapping_in_struct) -{ - char const* text = "contract test {\n" - " struct test_struct {\n" - " address addr;\n" - " uint256 count;\n" - " mapping(bytes32 => test_struct) self_reference;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(mapping_to_mapping_in_struct) -{ - char const* text = "contract test {\n" - " struct test_struct {\n" - " address addr;\n" - " mapping (uint64 => mapping (bytes32 => uint)) complex_mapping;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(variable_definition) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " var b;\n" - " uint256 c;\n" - " mapping(address=>bytes32) d;\n" - " customtype varname;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(variable_definition_with_initialization) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " var b = 2;\n" - " uint256 c = 0x87;\n" - " mapping(address=>bytes32) d;\n" - " bytes7 name = \"Solidity\";" - " customtype varname;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(variable_definition_in_function_parameter) -{ - char const* text = R"( - contract test { - function fun(var a) {} - } - )"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(variable_definition_in_mapping) -{ - char const* text = R"( - contract test { - function fun() { - mapping(var=>bytes32) d; - } - } - )"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(variable_definition_in_function_return) -{ - char const* text = R"( - contract test { - function fun() returns(var d) { - return 1; - } - } - )"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(operator_expression) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " uint256 x = (1 + 4) || false && (1 - 12) + -9;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(complex_expression) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " uint256 x = (1 + 4).member(++67)[a/=9] || true;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(exp_expression) -{ - char const* text = R"( - contract test { - function fun(uint256 a) { - uint256 x = 3 ** a; - } - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(while_loop) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " while (true) { uint256 x = 1; break; continue; } x = 9;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(for_loop_vardef_initexpr) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " for (uint256 i = 0; i < 10; i++)\n" - " { uint256 x = i; break; continue; }\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(for_loop_simple_initexpr) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " uint256 i =0;\n" - " for (i = 0; i < 10; i++)\n" - " { uint256 x = i; break; continue; }\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(for_loop_simple_noexpr) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " uint256 i =0;\n" - " for (;;)\n" - " { uint256 x = i; break; continue; }\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(for_loop_single_stmt_body) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " uint256 i =0;\n" - " for (i = 0; i < 10; i++)\n" - " continue;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(if_statement) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) {\n" - " if (a >= 8) return 2; else { var b = 7; }\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(else_if_statement) -{ - char const* text = "contract test {\n" - " function fun(uint256 a) returns (address b) {\n" - " if (a < 0) b = 0x67; else if (a == 0) b = 0x12; else b = 0x78;\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(statement_starting_with_type_conversion) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " uint64(2);\n" - " uint64[7](3);\n" - " uint64[](3);\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(type_conversion_to_dynamic_array) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " var x = uint64[](3);\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(import_directive) -{ - char const* text = "import \"abc\";\n" - "contract test {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(multiple_contracts) -{ - char const* text = "contract test {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n" - "contract test2 {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(multiple_contracts_and_imports) -{ - char const* text = "import \"abc\";\n" - "contract test {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n" - "import \"def\";\n" - "contract test2 {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n" - "import \"ghi\";\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(contract_inheritance) -{ - char const* text = "contract base {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n" - "contract derived is base {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(contract_multiple_inheritance) -{ - char const* text = "contract base {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n" - "contract derived is base, nonExisting {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(contract_multiple_inheritance_with_arguments) -{ - char const* text = "contract base {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n" - "contract derived is base(2), nonExisting(\"abc\", \"def\", base.fun()) {\n" - " function fun() {\n" - " uint64(2);\n" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(placeholder_in_function_context) -{ - char const* text = "contract c {\n" - " function fun() returns (uint r) {\n" - " var _ = 8;\n" - " return _ + 1;" - " }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(modifier) -{ - char const* text = "contract c {\n" - " modifier mod { if (msg.sender == 0) _ }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(modifier_arguments) -{ - char const* text = "contract c {\n" - " modifier mod(uint a) { if (msg.sender == a) _ }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(modifier_invocation) -{ - char const* text = "contract c {\n" - " modifier mod1(uint a) { if (msg.sender == a) _ }\n" - " modifier mod2 { if (msg.sender == 2) _ }\n" - " function f() mod1(7) mod2 { }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(fallback_function) -{ - char const* text = "contract c {\n" - " function() { }\n" - "}\n"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(event) -{ - char const* text = R"( - contract c { - event e(); - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(event_arguments) -{ - char const* text = R"( - contract c { - event e(uint a, bytes32 s); - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(event_arguments_indexed) -{ - char const* text = R"( - contract c { - event e(uint a, bytes32 indexed s, bool indexed b); - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(visibility_specifiers) -{ - char const* text = R"( - contract c { - uint private a; - uint internal b; - uint public c; - uint d; - function f() {} - function f_priv() private {} - function f_public() public {} - function f_internal() internal {} - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(multiple_visibility_specifiers) -{ - char const* text = R"( - contract c { - uint private internal a; - })"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(literal_constants_with_ether_subdenominations) -{ - char const* text = R"( - contract c { - function c () - { - a = 1 wei; - b = 2 szabo; - c = 3 finney; - b = 4 ether; - } - uint256 a; - uint256 b; - uint256 c; - uint256 d; - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(literal_constants_with_ether_subdenominations_in_expressions) -{ - char const* text = R"( - contract c { - function c () - { - a = 1 wei * 100 wei + 7 szabo - 3; - } - uint256 a; - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(enum_valid_declaration) -{ - char const* text = R"( - contract c { - enum validEnum { Value1, Value2, Value3, Value4 } - function c () - { - a = foo.Value3; - } - uint256 a; - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(empty_enum_declaration) -{ - char const* text = R"( - contract c { - enum foo { } - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(malformed_enum_declaration) -{ - char const* text = R"( - contract c { - enum foo { WARNING,} - })"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(external_function) -{ - char const* text = R"( - contract c { - function x() external {} - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(external_variable) -{ - char const* text = R"( - contract c { - uint external x; - })"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(arrays_in_storage) -{ - char const* text = R"( - contract c { - uint[10] a; - uint[] a2; - struct x { uint[2**20] b; y[0] c; } - struct y { uint d; mapping(uint=>x)[] e; } - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(arrays_in_events) -{ - char const* text = R"( - contract c { - event e(uint[10] a, bytes7[8] indexed b, c[3] x); - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(arrays_in_expressions) -{ - char const* text = R"( - contract c { - function f() { c[10] a = 7; uint8[10 * 2] x; } - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(multi_arrays) -{ - char const* text = R"( - contract c { - mapping(uint => mapping(uint => int8)[8][][9])[] x; - })"; - ETH_TEST_CHECK_NO_THROW(parseText(text), "Parsing failed"); -} - -BOOST_AUTO_TEST_CASE(constant_is_keyword) -{ - char const* text = R"( - contract Foo { - uint constant = 4; - })"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(var_array) -{ - char const* text = R"( - contract Foo { - function f() { var[] a; } - })"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(location_specifiers_for_params) -{ - char const* text = R"( - contract Foo { - function f(uint[] storage constant x, uint[] memory y) { } - } - )"; - BOOST_CHECK_NO_THROW(parseText(text)); -} - -BOOST_AUTO_TEST_CASE(location_specifiers_for_locals) -{ - char const* text = R"( - contract Foo { - function f() { - uint[] storage x; - uint[] memory y; - } - } - )"; - BOOST_CHECK_NO_THROW(parseText(text)); -} - -BOOST_AUTO_TEST_CASE(location_specifiers_for_state) -{ - char const* text = R"( - contract Foo { - uint[] memory x; - })"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_CASE(location_specifiers_with_var) -{ - char const* text = R"( - contract Foo { - function f() { var memory x; } - })"; - BOOST_CHECK_THROW(parseText(text), ParserError); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/SolidityScanner.cpp b/test/libsolidity/SolidityScanner.cpp deleted file mode 100644 index 8d3e53929..000000000 --- a/test/libsolidity/SolidityScanner.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Unit tests for the solidity scanner. - */ - -#include -#include - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -BOOST_AUTO_TEST_SUITE(SolidityScanner) - -BOOST_AUTO_TEST_CASE(test_empty) -{ - Scanner scanner(CharStream("")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); -} - -BOOST_AUTO_TEST_CASE(smoke_test) -{ - Scanner scanner(CharStream("function break;765 \t \"string1\",'string2'\nidentifier1")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Function); - BOOST_CHECK_EQUAL(scanner.next(), Token::Break); - BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); - BOOST_CHECK_EQUAL(scanner.next(), Token::Number); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "765"); - BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string1"); - BOOST_CHECK_EQUAL(scanner.next(), Token::Comma); - BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string2"); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "identifier1"); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); -} - -BOOST_AUTO_TEST_CASE(string_escapes) -{ - Scanner scanner(CharStream(" { \"a\\x61\"")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBrace); - BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "aa"); -} - -BOOST_AUTO_TEST_CASE(string_escapes_with_zero) -{ - Scanner scanner(CharStream(" { \"a\\x61\\x00abc\"")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBrace); - BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), std::string("aa\0abc", 6)); -} - -BOOST_AUTO_TEST_CASE(string_escape_illegal) -{ - Scanner scanner(CharStream(" bla \"\\x6rf\" (illegalescape)")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), ""); - // TODO recovery from illegal tokens should be improved - BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); -} - -BOOST_AUTO_TEST_CASE(hex_numbers) -{ - Scanner scanner(CharStream("var x = 0x765432536763762734623472346;")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Var); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Assign); - BOOST_CHECK_EQUAL(scanner.next(), Token::Number); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "0x765432536763762734623472346"); - BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); -} - -BOOST_AUTO_TEST_CASE(negative_numbers) -{ - Scanner scanner(CharStream("var x = -.2 + -0x78 + -7.3 + 8.9;")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Var); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Assign); - BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); - BOOST_CHECK_EQUAL(scanner.next(), Token::Number); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), ".2"); - BOOST_CHECK_EQUAL(scanner.next(), Token::Add); - BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); - BOOST_CHECK_EQUAL(scanner.next(), Token::Number); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "0x78"); - BOOST_CHECK_EQUAL(scanner.next(), Token::Add); - BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); - BOOST_CHECK_EQUAL(scanner.next(), Token::Number); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "7.3"); - BOOST_CHECK_EQUAL(scanner.next(), Token::Add); - BOOST_CHECK_EQUAL(scanner.next(), Token::Number); - BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "8.9"); - BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); -} - -BOOST_AUTO_TEST_CASE(locations) -{ - Scanner scanner(CharStream("function_identifier has ; -0x743/*comment*/\n ident //comment")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 0); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 19); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 20); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 23); - BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 24); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 25); - BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); - BOOST_CHECK_EQUAL(scanner.next(), Token::Number); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 27); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 32); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 45); - BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 50); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); -} - -BOOST_AUTO_TEST_CASE(ambiguities) -{ - // test scanning of some operators which need look-ahead - Scanner scanner(CharStream("<=""<""+ +=a++ =>""<<")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LessThanOrEqual); - BOOST_CHECK_EQUAL(scanner.next(), Token::LessThan); - BOOST_CHECK_EQUAL(scanner.next(), Token::Add); - BOOST_CHECK_EQUAL(scanner.next(), Token::AssignAdd); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Inc); - BOOST_CHECK_EQUAL(scanner.next(), Token::Arrow); - BOOST_CHECK_EQUAL(scanner.next(), Token::SHL); -} - -BOOST_AUTO_TEST_CASE(documentation_comments_parsed_begin) -{ - Scanner scanner(CharStream("/// Send $(value / 1000) chocolates to the user")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); -} - -BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed_begin) -{ - Scanner scanner(CharStream("/** Send $(value / 1000) chocolates to the user*/")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); -} - -BOOST_AUTO_TEST_CASE(documentation_comments_parsed) -{ - Scanner scanner(CharStream("some other tokens /// Send $(value / 1000) chocolates to the user")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); -} - -BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed) -{ - Scanner scanner(CharStream("some other tokens /**\n" - "* Send $(value / 1000) chocolates to the user\n" - "*/")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); -} - -BOOST_AUTO_TEST_CASE(multiline_documentation_no_stars) -{ - Scanner scanner(CharStream("some other tokens /**\n" - " Send $(value / 1000) chocolates to the user\n" - "*/")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); -} - -BOOST_AUTO_TEST_CASE(multiline_documentation_whitespace_hell) -{ - Scanner scanner(CharStream("some other tokens /** \t \r \n" - "\t \r * Send $(value / 1000) chocolates to the user\n" - "*/")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); -} - -BOOST_AUTO_TEST_CASE(comment_before_eos) -{ - Scanner scanner(CharStream("//")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); -} - -BOOST_AUTO_TEST_CASE(documentation_comment_before_eos) -{ - Scanner scanner(CharStream("///")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); -} - -BOOST_AUTO_TEST_CASE(empty_multiline_comment) -{ - Scanner scanner(CharStream("/**/")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); -} - -BOOST_AUTO_TEST_CASE(empty_multiline_documentation_comment_before_eos) -{ - Scanner scanner(CharStream("/***/")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); -} - -BOOST_AUTO_TEST_CASE(comments_mixed_in_sequence) -{ - Scanner scanner(CharStream("hello_world ///documentation comment \n" - "//simple comment \n" - "<<")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); - BOOST_CHECK_EQUAL(scanner.next(), Token::SHL); - BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "documentation comment "); -} - -BOOST_AUTO_TEST_CASE(ether_subdenominations) -{ - Scanner scanner(CharStream("wei szabo finney ether")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::SubWei); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubSzabo); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubFinney); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubEther); -} - -BOOST_AUTO_TEST_CASE(time_subdenominations) -{ - Scanner scanner(CharStream("seconds minutes hours days weeks years")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::SubSecond); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubMinute); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubHour); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubDay); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubWeek); - BOOST_CHECK_EQUAL(scanner.next(), Token::SubYear); -} - -BOOST_AUTO_TEST_CASE(time_after) -{ - Scanner scanner(CharStream("after 1")); - BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::After); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} // end namespaces diff --git a/test/libsolidity/SolidityTypes.cpp b/test/libsolidity/SolidityTypes.cpp deleted file mode 100644 index 7892de673..000000000 --- a/test/libsolidity/SolidityTypes.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2015 - * Unit tests for the type system of Solidity. - */ - -#include -#include - -using namespace std; - -namespace dev -{ -namespace solidity -{ -namespace test -{ - -BOOST_AUTO_TEST_SUITE(SolidityTypes) - -BOOST_AUTO_TEST_CASE(storage_layout_simple) -{ - MemberList members(MemberList::MemberMap({ - {string("first"), Type::fromElementaryTypeName("uint128")}, - {string("second"), Type::fromElementaryTypeName("uint120")}, - {string("wraps"), Type::fromElementaryTypeName("uint16")} - })); - BOOST_REQUIRE_EQUAL(u256(2), members.getStorageSize()); - BOOST_REQUIRE(members.getMemberStorageOffset("first") != nullptr); - BOOST_REQUIRE(members.getMemberStorageOffset("second") != nullptr); - BOOST_REQUIRE(members.getMemberStorageOffset("wraps") != nullptr); - BOOST_CHECK(*members.getMemberStorageOffset("first") == make_pair(u256(0), unsigned(0))); - BOOST_CHECK(*members.getMemberStorageOffset("second") == make_pair(u256(0), unsigned(16))); - BOOST_CHECK(*members.getMemberStorageOffset("wraps") == make_pair(u256(1), unsigned(0))); -} - -BOOST_AUTO_TEST_CASE(storage_layout_mapping) -{ - MemberList members(MemberList::MemberMap({ - {string("first"), Type::fromElementaryTypeName("uint128")}, - {string("second"), make_shared( - Type::fromElementaryTypeName("uint8"), - Type::fromElementaryTypeName("uint8") - )}, - {string("third"), Type::fromElementaryTypeName("uint16")}, - {string("final"), make_shared( - Type::fromElementaryTypeName("uint8"), - Type::fromElementaryTypeName("uint8") - )}, - })); - BOOST_REQUIRE_EQUAL(u256(4), members.getStorageSize()); - BOOST_REQUIRE(members.getMemberStorageOffset("first") != nullptr); - BOOST_REQUIRE(members.getMemberStorageOffset("second") != nullptr); - BOOST_REQUIRE(members.getMemberStorageOffset("third") != nullptr); - BOOST_REQUIRE(members.getMemberStorageOffset("final") != nullptr); - BOOST_CHECK(*members.getMemberStorageOffset("first") == make_pair(u256(0), unsigned(0))); - BOOST_CHECK(*members.getMemberStorageOffset("second") == make_pair(u256(1), unsigned(0))); - BOOST_CHECK(*members.getMemberStorageOffset("third") == make_pair(u256(2), unsigned(0))); - BOOST_CHECK(*members.getMemberStorageOffset("final") == make_pair(u256(3), unsigned(0))); -} - -BOOST_AUTO_TEST_CASE(storage_layout_arrays) -{ - BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared(1), 32).getStorageSize() == 1); - BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared(1), 33).getStorageSize() == 2); - BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared(2), 31).getStorageSize() == 2); - BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared(7), 8).getStorageSize() == 2); - BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared(7), 9).getStorageSize() == 3); - BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared(31), 9).getStorageSize() == 9); - BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared(32), 9).getStorageSize() == 9); -} - -BOOST_AUTO_TEST_SUITE_END() - -} -} -} diff --git a/test/libsolidity/solidityExecutionFramework.h b/test/libsolidity/solidityExecutionFramework.h deleted file mode 100644 index 05f93bb60..000000000 --- a/test/libsolidity/solidityExecutionFramework.h +++ /dev/null @@ -1,310 +0,0 @@ -/* - This file is part of cpp-ethereum. - - cpp-ethereum 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. - - cpp-ethereum 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 cpp-ethereum. If not, see . -*/ -/** - * @author Christian - * @date 2014 - * Framework for executing Solidity contracts and testing them against C++ implementation. - */ - -#pragma once - -#include -#include -#include "../TestHelper.h" -#include -#include -#include -#include -#include - -namespace dev -{ - -namespace solidity -{ -namespace test -{ - -class ExecutionFramework -{ -public: - ExecutionFramework() - { - if (g_logVerbosity != -1) - g_logVerbosity = 0; - //m_state.resetCurrent(); - } - - bytes const& compileAndRunWithoutCheck( - std::string const& _sourceCode, - u256 const& _value = 0, - std::string const& _contractName = "", - bytes const& _arguments = bytes() - ) - { - m_compiler.reset(false, m_addStandardSources); - m_compiler.addSource("", _sourceCode); - ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); - bytes code = m_compiler.getBytecode(_contractName); - sendMessage(code + _arguments, true, _value); - return m_output; - } - - template - void compileRequireThrow(std::string const& _sourceCode) - { - m_compiler.reset(false, m_addStandardSources); - m_compiler.addSource("", _sourceCode); - BOOST_REQUIRE_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), Exceptiontype); - } - - bytes const& compileAndRun( - std::string const& _sourceCode, - u256 const& _value = 0, - std::string const& _contractName = "", - bytes const& _arguments = bytes() - ) - { - compileAndRunWithoutCheck(_sourceCode, _value, _contractName, _arguments); - BOOST_REQUIRE(!m_output.empty()); - return m_output; - } - - template - bytes const& callContractFunctionWithValue(std::string _sig, u256 const& _value, Args const&... _arguments) - { - FixedHash<4> hash(dev::sha3(_sig)); - sendMessage(hash.asBytes() + encodeArgs(_arguments...), false, _value); - return m_output; - } - - template - bytes const& callContractFunction(std::string _sig, Args const&... _arguments) - { - return callContractFunctionWithValue(_sig, 0, _arguments...); - } - - template - void testSolidityAgainstCpp(std::string _sig, CppFunction const& _cppFunction, Args const&... _arguments) - { - bytes solidityResult = callContractFunction(_sig, _arguments...); - bytes cppResult = callCppAndEncodeResult(_cppFunction, _arguments...); - BOOST_CHECK_MESSAGE( - solidityResult == cppResult, - "Computed values do not match.\nSolidity: " + - toHex(solidityResult) + - "\nC++: " + - toHex(cppResult)); - } - - template - void testSolidityAgainstCppOnRange(std::string _sig, CppFunction const& _cppFunction, u256 const& _rangeStart, u256 const& _rangeEnd) - { - for (u256 argument = _rangeStart; argument < _rangeEnd; ++argument) - { - bytes solidityResult = callContractFunction(_sig, argument); - bytes cppResult = callCppAndEncodeResult(_cppFunction, argument); - BOOST_CHECK_MESSAGE( - solidityResult == cppResult, - "Computed values do not match.\nSolidity: " + - toHex(solidityResult) + - "\nC++: " + - toHex(cppResult) + - "\nArgument: " + - toHex(encode(argument)) - ); - } - } - - static bytes encode(bool _value) { return encode(byte(_value)); } - static bytes encode(int _value) { return encode(u256(_value)); } - static bytes encode(size_t _value) { return encode(u256(_value)); } - static bytes encode(char const* _value) { return encode(std::string(_value)); } - static bytes encode(byte _value) { return bytes(31, 0) + bytes{_value}; } - static bytes encode(u256 const& _value) { return toBigEndian(_value); } - static bytes encode(h256 const& _value) { return _value.asBytes(); } - static bytes encode(bytes const& _value, bool _padLeft = true) - { - bytes padding = bytes((32 - _value.size() % 32) % 32, 0); - return _padLeft ? padding + _value : _value + padding; - } - static bytes encode(std::string const& _value) { return encode(asBytes(_value), false); } - template - static bytes encode(std::vector<_T> const& _value) - { - bytes ret; - for (auto const& v: _value) - ret += encode(v); - return ret; - } - - template - static bytes encodeArgs(FirstArg const& _firstArg, Args const&... _followingArgs) - { - return encode(_firstArg) + encodeArgs(_followingArgs...); - } - static bytes encodeArgs() - { - return bytes(); - } - //@todo might be extended in the future - template - static bytes encodeDyn(Arg const& _arg) - { - return encodeArgs(u256(0x20), u256(_arg.size()), _arg); - } - - class ContractInterface - { - public: - ContractInterface(ExecutionFramework& _framework): m_framework(_framework) {} - - void setNextValue(u256 const& _value) { m_nextValue = _value; } - - protected: - template - bytes const& call(std::string const& _sig, Args const&... _arguments) - { - auto const& ret = m_framework.callContractFunctionWithValue(_sig, m_nextValue, _arguments...); - m_nextValue = 0; - return ret; - } - - void callString(std::string const& _name, std::string const& _arg) - { - BOOST_CHECK(call(_name + "(string)", u256(0x20), _arg.length(), _arg).empty()); - } - - void callStringAddress(std::string const& _name, std::string const& _arg1, u160 const& _arg2) - { - BOOST_CHECK(call(_name + "(string,address)", u256(0x40), _arg2, _arg1.length(), _arg1).empty()); - } - - void callStringAddressBool(std::string const& _name, std::string const& _arg1, u160 const& _arg2, bool _arg3) - { - BOOST_CHECK(call(_name + "(string,address,bool)", u256(0x60), _arg2, _arg3, _arg1.length(), _arg1).empty()); - } - - void callStringBytes32(std::string const& _name, std::string const& _arg1, h256 const& _arg2) - { - BOOST_CHECK(call(_name + "(string,bytes32)", u256(0x40), _arg2, _arg1.length(), _arg1).empty()); - } - - u160 callStringReturnsAddress(std::string const& _name, std::string const& _arg) - { - bytes const& ret = call(_name + "(string)", u256(0x20), _arg.length(), _arg); - BOOST_REQUIRE(ret.size() == 0x20); - BOOST_CHECK(std::count(ret.begin(), ret.begin() + 12, 0) == 12); - return eth::abiOut(ret); - } - - std::string callAddressReturnsString(std::string const& _name, u160 const& _arg) - { - bytesConstRef ret = ref(call(_name + "(address)", _arg)); - BOOST_REQUIRE(ret.size() >= 0x20); - u256 offset = eth::abiOut(ret); - BOOST_REQUIRE_EQUAL(offset, 0x20); - u256 len = eth::abiOut(ret); - BOOST_REQUIRE_EQUAL(ret.size(), ((len + 0x1f) / 0x20) * 0x20); - return ret.cropped(0, size_t(len)).toString(); - } - - h256 callStringReturnsBytes32(std::string const& _name, std::string const& _arg) - { - bytes const& ret = call(_name + "(string)", u256(0x20), _arg.length(), _arg); - BOOST_REQUIRE(ret.size() == 0x20); - return eth::abiOut(ret); - } - - private: - u256 m_nextValue; - ExecutionFramework& m_framework; - }; - -private: - template - auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments) - -> typename std::enable_if::value, bytes>::type - { - _cppFunction(_arguments...); - return bytes(); - } - template - auto callCppAndEncodeResult(CppFunction const& _cppFunction, Args const&... _arguments) - -> typename std::enable_if::value, bytes>::type - { - return encode(_cppFunction(_arguments...)); - } - -protected: - void sendMessage(bytes const& _data, bool _isCreation, u256 const& _value = 0) - { - m_state.addBalance(m_sender, _value); // just in case - eth::Executive executive(m_state, m_envInfo, 0); - eth::ExecutionResult res; - executive.setResultRecipient(res); - eth::Transaction t = - _isCreation ? - eth::Transaction(_value, m_gasPrice, m_gas, _data, 0, KeyPair::create().sec()) : - eth::Transaction(_value, m_gasPrice, m_gas, m_contractAddress, _data, 0, KeyPair::create().sec()); - bytes transactionRLP = t.rlp(); - try - { - // this will throw since the transaction is invalid, but it should nevertheless store the transaction - executive.initialize(&transactionRLP); - executive.execute(); - } - catch (...) {} - if (_isCreation) - { - BOOST_REQUIRE(!executive.create(m_sender, _value, m_gasPrice, m_gas, &_data, m_sender)); - m_contractAddress = executive.newAddress(); - BOOST_REQUIRE(m_contractAddress); - BOOST_REQUIRE(m_state.addressHasCode(m_contractAddress)); - } - else - { - BOOST_REQUIRE(m_state.addressHasCode(m_contractAddress)); - BOOST_REQUIRE(!executive.call(m_contractAddress, m_sender, _value, m_gasPrice, &_data, m_gas)); - } - BOOST_REQUIRE(executive.go(/* DEBUG eth::Executive::simpleTrace() */)); - m_state.noteSending(m_sender); - executive.finalize(); - m_gasUsed = res.gasUsed; - m_output = std::move(res.output); - m_logs = executive.logs(); - } - - size_t m_optimizeRuns = 200; - bool m_optimize = false; - bool m_addStandardSources = false; - dev::solidity::CompilerStack m_compiler; - Address m_sender; - Address m_contractAddress; - eth::EnvInfo m_envInfo; - eth::State m_state; - u256 const m_gasPrice = 100 * eth::szabo; - u256 const m_gas = 100000000; - bytes m_output; - eth::LogEntries m_logs; - u256 m_gasUsed; -}; - -} -} -} // end namespaces -