solidity/AST.cpp

1007 lines
36 KiB
C++
Raw Normal View History

/*
2014-10-16 12:08:54 +00:00
This file is part of cpp-ethereum.
2014-10-16 12:08:54 +00:00
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.
2014-10-16 12:08:54 +00:00
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.
2014-10-16 12:08:54 +00:00
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Solidity abstract syntax tree.
*/
2014-10-13 16:22:15 +00:00
#include <algorithm>
#include <boost/range/adaptor/reversed.hpp>
#include <libsolidity/Utils.h>
#include <libsolidity/AST.h>
#include <libsolidity/ASTVisitor.h>
2014-10-15 12:45:51 +00:00
#include <libsolidity/Exceptions.h>
#include <libsolidity/AST_accept.h>
#include <libdevcore/SHA3.h>
2014-10-24 17:06:30 +00:00
using namespace std;
2014-10-16 12:08:54 +00:00
namespace dev
{
namespace solidity
{
TypeError ASTNode::createTypeError(string const& _description) const
2014-10-23 17:22:30 +00:00
{
return TypeError() << errinfo_sourceLocation(getLocation()) << errinfo_comment(_description);
}
TypePointer ContractDefinition::getType(ContractDefinition const* _currentContract) const
{
return make_shared<TypeType>(make_shared<ContractType>(*this), _currentContract);
}
void ContractDefinition::checkTypeRequirements()
{
for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: getBaseContracts())
baseSpecifier->checkTypeRequirements();
checkDuplicateFunctions();
checkIllegalOverrides();
checkAbstractFunctions();
checkAbstractConstructors();
FunctionDefinition const* constructor = getConstructor();
if (constructor && !constructor->getReturnParameters().empty())
BOOST_THROW_EXCEPTION(constructor->getReturnParameterList()->createTypeError(
2015-01-29 21:50:20 +00:00
"Non-empty \"returns\" directive for constructor."));
FunctionDefinition const* fallbackFunction = nullptr;
for (ASTPointer<FunctionDefinition> 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<ModifierDefinition> const& modifier: getFunctionModifiers())
modifier->checkTypeRequirements();
for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
function->checkTypeRequirements();
for (ASTPointer<VariableDeclaration> const& variable: m_stateVariables)
variable->checkTypeRequirements();
checkExternalTypeClashes();
// check for hash collisions in function signatures
set<FixedHash<4>> hashes;
for (auto const& it: getInterfaceFunctionList())
{
FixedHash<4> const& hash = it.first;
if (hashes.count(hash))
2015-05-04 15:28:28 +00:00
BOOST_THROW_EXCEPTION(createTypeError(
string("Function signature hash collision for ") + it.second->externalSignature()
));
hashes.insert(hash);
}
}
map<FixedHash<4>, FunctionTypePointer> ContractDefinition::getInterfaceFunctions() const
{
auto exportedFunctionList = getInterfaceFunctionList();
map<FixedHash<4>, FunctionTypePointer> exportedFunctions;
for (auto const& it: exportedFunctionList)
exportedFunctions.insert(it);
solAssert(exportedFunctionList.size() == exportedFunctions.size(),
"Hash collision at Function Definition Hash calculation");
return exportedFunctions;
}
2014-12-12 15:49:26 +00:00
FunctionDefinition const* ContractDefinition::getConstructor() const
{
for (ASTPointer<FunctionDefinition> const& f: m_definedFunctions)
if (f->isConstructor())
2014-12-12 15:49:26 +00:00
return f.get();
return nullptr;
}
2015-01-29 21:50:20 +00:00
FunctionDefinition const* ContractDefinition::getFallbackFunction() const
{
for (ContractDefinition const* contract: getLinearizedBaseContracts())
for (ASTPointer<FunctionDefinition> 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<string, vector<FunctionDefinition const*>> functions;
for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
functions[function->getName()].push_back(function.get());
if (functions[getName()].size() > 1)
{
SecondarySourceLocation ssl;
auto it = functions[getName()].begin();
++it;
2015-05-04 15:21:59 +00:00
for (; it != functions[getName()].end(); ++it)
ssl.append("Another declaration is here:", (*it)->getLocation());
BOOST_THROW_EXCEPTION(
DeclarationError() <<
2015-05-04 13:46:46 +00:00
errinfo_sourceLocation(functions[getName()].front()->getLocation()) <<
errinfo_comment("More than one constructor defined.") <<
errinfo_secondarySourceLocation(ssl)
);
}
for (auto const& it: functions)
{
vector<FunctionDefinition const*> 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()) <<
2015-05-04 13:46:46 +00:00
errinfo_comment("Function with same name and arguments defined twice.") <<
errinfo_secondarySourceLocation(SecondarySourceLocation().append(
2015-05-04 13:46:46 +00:00
"Other declaration is here:", overloads[i]->getLocation()))
);
}
}
void ContractDefinition::checkAbstractFunctions()
{
map<string, bool> functions;
// Search from base to derived
for (ContractDefinition const* contract: boost::adaptors::reverse(getLinearizedBaseContracts()))
for (ASTPointer<FunctionDefinition> const& function: contract->getDefinedFunctions())
{
string const& name = function->getName();
if (!function->isFullyImplemented() && functions.count(name) && functions[name])
BOOST_THROW_EXCEPTION(function->createTypeError("Redeclaring an already implemented function as abstract"));
functions[name] = function->isFullyImplemented();
}
for (auto const& it: functions)
if (!it.second)
{
setFullyImplemented(false);
break;
}
}
void ContractDefinition::checkAbstractConstructors()
{
2015-04-17 14:17:21 +00:00
set<ContractDefinition const*> argumentsNeeded;
// check that we get arguments for all base constructors that need it.
// If not mark the contract as abstract (not fully implemented)
2015-04-17 14:17:21 +00:00
vector<ContractDefinition const*> const& bases = getLinearizedBaseContracts();
2015-04-17 14:17:21 +00:00
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)
{
2015-04-17 14:17:21 +00:00
if (FunctionDefinition const* constructor = contract->getConstructor())
for (auto const& modifier: constructor->getModifiers())
{
auto baseContract = dynamic_cast<ContractDefinition const*>(
&modifier->getName()->getReferencedDeclaration()
2015-04-17 14:17:21 +00:00
);
if (baseContract)
2015-04-17 14:17:21 +00:00
argumentsNeeded.erase(baseContract);
}
2015-04-17 14:17:21 +00:00
for (ASTPointer<InheritanceSpecifier> const& base: contract->getBaseContracts())
{
2015-04-17 14:17:21 +00:00
auto baseContract = dynamic_cast<ContractDefinition const*>(
&base->getName()->getReferencedDeclaration()
2015-04-17 14:17:21 +00:00
);
solAssert(baseContract, "");
2015-04-17 14:17:21 +00:00
if (!base->getArguments().empty())
argumentsNeeded.erase(baseContract);
}
}
2015-04-17 14:17:21 +00:00
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<string, vector<FunctionDefinition const*>> functions;
map<string, ModifierDefinition const*> modifiers;
// We search from derived to base, so the stored item causes the error.
for (ContractDefinition const* contract: getLinearizedBaseContracts())
{
for (ASTPointer<FunctionDefinition> 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<ModifierDefinition> 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())
2015-03-01 03:34:39 +00:00
BOOST_THROW_EXCEPTION(override->createTypeError("Override changes modifier to function."));
}
}
}
void ContractDefinition::checkExternalTypeClashes() const
{
map<string, vector<pair<Declaration const*, shared_ptr<FunctionType>>>> externalDeclarations;
for (ContractDefinition const* contract: getLinearizedBaseContracts())
{
for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
if (f->isPartOfExternalInterface())
{
auto functionType = make_shared<FunctionType>(*f);
externalDeclarations[functionType->externalSignature(f->getName())].push_back(
make_pair(f.get(), functionType)
);
}
for (ASTPointer<VariableDeclaration> const& v: contract->getStateVariables())
if (v->isPartOfExternalInterface())
{
auto functionType = make_shared<FunctionType>(*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."
));
}
2015-05-04 15:18:01 +00:00
vector<ASTPointer<EventDefinition>> const& ContractDefinition::getInterfaceEvents() const
{
if (!m_interfaceEvents)
{
set<string> eventsSeen;
2015-05-04 15:18:01 +00:00
m_interfaceEvents.reset(new vector<ASTPointer<EventDefinition>>());
for (ContractDefinition const* contract: getLinearizedBaseContracts())
for (ASTPointer<EventDefinition> const& e: contract->getEvents())
if (eventsSeen.count(e->getName()) == 0)
{
eventsSeen.insert(e->getName());
m_interfaceEvents->push_back(e);
}
}
return *m_interfaceEvents;
}
2015-01-29 16:28:14 +00:00
vector<pair<FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::getInterfaceFunctionList() const
{
if (!m_interfaceFunctionList)
{
set<string> functionsSeen;
2015-03-01 03:34:39 +00:00
set<string> signaturesSeen;
2015-01-29 16:28:14 +00:00
m_interfaceFunctionList.reset(new vector<pair<FixedHash<4>, FunctionTypePointer>>());
for (ContractDefinition const* contract: getLinearizedBaseContracts())
{
for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
2015-03-01 03:34:39 +00:00
{
string functionSignature = f->externalSignature();
if (f->isPartOfExternalInterface() && signaturesSeen.count(functionSignature) == 0)
{
functionsSeen.insert(f->getName());
2015-03-01 03:34:39 +00:00
signaturesSeen.insert(functionSignature);
FixedHash<4> hash(dev::sha3(functionSignature));
m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*f, false)));
}
2015-03-01 03:34:39 +00:00
}
for (ASTPointer<VariableDeclaration> 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<FunctionType>(*v)));
}
}
}
return *m_interfaceFunctionList;
}
vector<Declaration const*> const& ContractDefinition::getInheritableMembers() const
{
if (!m_inheritableMembers)
{
set<string> memberSeen;
m_inheritableMembers.reset(new vector<Declaration const*>());
auto addInheritableMember = [&](Declaration const* _decl)
{
if (memberSeen.count(_decl->getName()) == 0 && _decl->isVisibleInDerivedContracts())
{
memberSeen.insert(_decl->getName());
m_inheritableMembers->push_back(_decl);
}
};
for (ASTPointer<FunctionDefinition> const& f: getDefinedFunctions())
addInheritableMember(f.get());
for (ASTPointer<VariableDeclaration> const& v: getStateVariables())
addInheritableMember(v.get());
2015-02-26 11:11:54 +00:00
for (ASTPointer<StructDefinition> const& s: getDefinedStructs())
addInheritableMember(s.get());
}
return *m_inheritableMembers;
}
2015-02-13 16:34:46 +00:00
TypePointer EnumValue::getType(ContractDefinition const*) const
2015-02-10 12:40:21 +00:00
{
2015-02-13 16:32:34 +00:00
EnumDefinition const* parentDef = dynamic_cast<EnumDefinition const*>(getScope());
solAssert(parentDef, "Enclosing Scope of EnumValue was not set");
2015-02-13 16:32:34 +00:00
return make_shared<EnumType>(*parentDef);
2015-02-10 12:40:21 +00:00
}
void InheritanceSpecifier::checkTypeRequirements()
{
m_baseName->checkTypeRequirements(nullptr);
for (ASTPointer<Expression> const& argument: m_arguments)
argument->checkTypeRequirements(nullptr);
ContractDefinition const* base = dynamic_cast<ContractDefinition const*>(&m_baseName->getReferencedDeclaration());
solAssert(base, "Base contract not available.");
TypePointers parameterTypes = ContractType(*base).getConstructorType()->getParameterTypes();
2015-04-02 15:05:27 +00:00
if (!m_arguments.empty() && parameterTypes.size() != m_arguments.size())
BOOST_THROW_EXCEPTION(createTypeError("Wrong argument count for constructor call."));
for (size_t i = 0; i < m_arguments.size(); ++i)
if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i]))
BOOST_THROW_EXCEPTION(createTypeError("Invalid type for argument in constructer call."));
}
TypePointer StructDefinition::getType(ContractDefinition const*) const
{
return make_shared<TypeType>(make_shared<StructType>(*this));
}
void StructDefinition::checkMemberTypes() const
2014-12-03 06:46:55 +00:00
{
for (ASTPointer<VariableDeclaration> const& member: getMembers())
if (!member->getType()->canBeStored())
BOOST_THROW_EXCEPTION(member->createTypeError("Type cannot be used in struct."));
}
void StructDefinition::checkRecursion() const
2014-12-03 06:46:55 +00:00
{
set<StructDefinition const*> definitionsSeen;
vector<StructDefinition const*> queue = {this};
while (!queue.empty())
{
StructDefinition const* def = queue.back();
queue.pop_back();
if (definitionsSeen.count(def))
BOOST_THROW_EXCEPTION(ParserError() << errinfo_sourceLocation(def->getLocation())
<< errinfo_comment("Recursive struct definition."));
definitionsSeen.insert(def);
for (ASTPointer<VariableDeclaration> const& member: def->getMembers())
if (member->getType()->getCategory() == Type::Category::Struct)
2014-12-03 06:46:55 +00:00
{
UserDefinedTypeName const& typeName = dynamic_cast<UserDefinedTypeName const&>(*member->getTypeName());
2014-12-03 06:46:55 +00:00
queue.push_back(&dynamic_cast<StructDefinition const&>(*typeName.getReferencedDeclaration()));
}
}
}
2015-02-09 17:08:56 +00:00
TypePointer EnumDefinition::getType(ContractDefinition const*) const
{
return make_shared<TypeType>(make_shared<EnumType>(*this));
2015-02-09 17:08:56 +00:00
}
TypePointer FunctionDefinition::getType(ContractDefinition const*) const
{
return make_shared<FunctionType>(*this);
}
2014-11-10 16:31:09 +00:00
void FunctionDefinition::checkTypeRequirements()
{
for (ASTPointer<VariableDeclaration> const& var: getParameters() + getReturnParameters())
{
2014-11-10 16:31:09 +00:00
if (!var->getType()->canLiveOutsideStorage())
BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage."));
2015-03-27 16:07:32 +00:00
if (getVisibility() >= Visibility::Public && !(var->getType()->externalType()))
2015-04-21 08:59:48 +00:00
BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed for public and external functions."));
}
for (ASTPointer<ModifierInvocation> const& modifier: m_functionModifiers)
modifier->checkTypeRequirements(isConstructor() ?
dynamic_cast<ContractDefinition const&>(*getScope()).getLinearizedBaseContracts() :
vector<ContractDefinition const*>());
if (m_body)
m_body->checkTypeRequirements();
2014-11-10 16:31:09 +00:00
}
string FunctionDefinition::externalSignature() const
{
return FunctionType(*this).externalSignature(getName());
}
bool VariableDeclaration::isLValue() const
{
2015-03-03 11:58:01 +00:00
// External function parameters and constant declared variables are Read-Only
return !isExternalFunctionParameter() && !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<ContractDefinition const*>(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);
2015-03-08 22:26:36 +00:00
TypePointer type = m_value->getType();
if (type->getCategory() == Type::Category::IntegerConstant)
{
auto intType = dynamic_pointer_cast<IntegerConstantType const>(type)->getIntegerType();
if (!intType)
BOOST_THROW_EXCEPTION(m_value->createTypeError("Invalid integer constant " + type->toString() + "."));
type = intType;
}
else if (type->getCategory() == Type::Category::Void)
BOOST_THROW_EXCEPTION(createTypeError("Variable cannot have void type."));
m_type = type;
}
if (m_isStateVariable && getVisibility() >= Visibility::Public && !FunctionType(*this).externalType())
BOOST_THROW_EXCEPTION(createTypeError("Internal type is not allowed for public state variables."));
}
bool VariableDeclaration::isFunctionParameter() const
{
auto const* function = dynamic_cast<FunctionDefinition const*>(getScope());
if (!function)
return false;
for (auto const& variable: function->getParameters() + function->getReturnParameters())
if (variable.get() == this)
return true;
return false;
}
bool VariableDeclaration::isExternalFunctionParameter() const
{
auto const* function = dynamic_cast<FunctionDefinition const*>(getScope());
if (!function || function->getVisibility() != Declaration::Visibility::External)
return false;
for (auto const& variable: function->getParameters())
if (variable.get() == this)
return true;
return false;
}
TypePointer ModifierDefinition::getType(ContractDefinition const*) const
{
return make_shared<ModifierType>(*this);
}
2015-01-21 10:16:18 +00:00
void ModifierDefinition::checkTypeRequirements()
{
m_body->checkTypeRequirements();
}
void ModifierInvocation::checkTypeRequirements(vector<ContractDefinition const*> const& _bases)
{
TypePointers argumentTypes;
for (ASTPointer<Expression> const& argument: m_arguments)
{
argument->checkTypeRequirements(nullptr);
argumentTypes.push_back(argument->getType());
}
m_modifierName->checkTypeRequirements(&argumentTypes);
auto const* declaration = &m_modifierName->getReferencedDeclaration();
vector<ASTPointer<VariableDeclaration>> emptyParameterList;
vector<ASTPointer<VariableDeclaration>> const* parameters = nullptr;
if (auto modifier = dynamic_cast<ModifierDefinition const*>(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."));
for (size_t i = 0; i < m_arguments.size(); ++i)
if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*(*parameters)[i]->getType()))
BOOST_THROW_EXCEPTION(createTypeError("Invalid type for argument in modifier invocation."));
}
2015-01-29 13:35:28 +00:00
void EventDefinition::checkTypeRequirements()
{
int numIndexed = 0;
for (ASTPointer<VariableDeclaration> 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())
2015-03-26 13:11:24 +00:00
BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed as event parameter type."));
2015-01-29 13:35:28 +00:00
}
if (numIndexed > 3)
BOOST_THROW_EXCEPTION(createTypeError("More than 3 indexed arguments for event."));
}
void Block::checkTypeRequirements()
2014-10-13 16:22:15 +00:00
{
2014-10-24 17:06:30 +00:00
for (shared_ptr<Statement> const& statement: m_statements)
2014-10-13 16:22:15 +00:00
statement->checkTypeRequirements();
}
void IfStatement::checkTypeRequirements()
2014-10-13 16:22:15 +00:00
{
m_condition->expectType(BoolType());
2014-10-13 16:22:15 +00:00
m_trueBody->checkTypeRequirements();
2014-10-16 21:49:45 +00:00
if (m_falseBody)
m_falseBody->checkTypeRequirements();
2014-10-13 16:22:15 +00:00
}
void WhileStatement::checkTypeRequirements()
2014-10-13 16:22:15 +00:00
{
m_condition->expectType(BoolType());
2014-10-13 16:22:15 +00:00
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()
2014-10-13 16:22:15 +00:00
{
if (!m_expression)
return;
2015-01-23 01:35:27 +00:00
if (!m_returnParameters)
BOOST_THROW_EXCEPTION(createTypeError("Return arguments not allowed."));
2014-10-13 16:22:15 +00:00
if (m_returnParameters->getParameters().size() != 1)
2014-10-23 17:22:30 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Different number of arguments in return statement "
"than in returns declaration."));
2014-10-13 16:22:15 +00:00
// 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());
2014-10-13 16:22:15 +00:00
}
void VariableDeclarationStatement::checkTypeRequirements()
2014-10-13 16:22:15 +00:00
{
m_variable->checkTypeRequirements();
2014-10-13 16:22:15 +00:00
}
void Assignment::checkTypeRequirements(TypePointers const*)
2014-10-13 16:22:15 +00:00
{
m_leftHandSide->checkTypeRequirements(nullptr);
2014-11-10 16:31:09 +00:00
m_leftHandSide->requireLValue();
2015-02-12 17:38:07 +00:00
if (m_leftHandSide->getType()->getCategory() == Type::Category::Mapping)
BOOST_THROW_EXCEPTION(createTypeError("Mappings cannot be assigned to."));
2014-10-13 16:22:15 +00:00
m_type = m_leftHandSide->getType();
if (m_assigmentOperator == Token::Assign)
m_rightHandSide->expectType(*m_type);
else
{
2014-10-20 10:41:56 +00:00
// compound assignment
m_rightHandSide->checkTypeRequirements(nullptr);
TypePointer resultType = m_type->binaryOperatorResult(Token::AssignmentToBinaryOp(m_assigmentOperator),
m_rightHandSide->getType());
if (!resultType || *resultType != *m_type)
2014-12-19 10:31:17 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_assigmentOperator)) +
" not compatible with types " +
m_type->toString() + " and " +
m_rightHandSide->getType()->toString()));
}
2014-10-13 16:22:15 +00:00
}
void ExpressionStatement::checkTypeRequirements()
{
m_expression->checkTypeRequirements(nullptr);
if (m_expression->getType()->getCategory() == Type::Category::IntegerConstant)
2014-12-19 10:31:17 +00:00
if (!dynamic_pointer_cast<IntegerConstantType const>(m_expression->getType())->getIntegerType())
BOOST_THROW_EXCEPTION(m_expression->createTypeError("Invalid integer constant."));
}
2014-11-05 14:04:33 +00:00
void Expression::expectType(Type const& _expectedType)
{
checkTypeRequirements(nullptr);
2014-11-06 21:04:10 +00:00
Type const& type = *getType();
if (!type.isImplicitlyConvertibleTo(_expectedType))
BOOST_THROW_EXCEPTION(createTypeError(
"Type " +
type.toString() +
" is not implicitly convertible to expected type " +
_expectedType.toString() +
"."
)
);
}
2014-11-10 16:31:09 +00:00
void Expression::requireLValue()
{
if (!isLValue())
2014-11-10 16:31:09 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue."));
m_lvalueRequested = true;
}
void UnaryOperation::checkTypeRequirements(TypePointers const*)
2014-10-13 16:22:15 +00:00
{
2015-02-10 08:52:19 +00:00
// 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)
2014-11-10 16:31:09 +00:00
m_subExpression->requireLValue();
m_type = m_subExpression->getType()->unaryOperatorResult(m_operator);
if (!m_type)
2014-10-23 17:22:30 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type."));
2014-10-13 16:22:15 +00:00
}
void BinaryOperation::checkTypeRequirements(TypePointers const*)
2014-10-13 16:22:15 +00:00
{
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<BoolType>() : m_commonType;
2014-10-13 16:22:15 +00:00
}
void FunctionCall::checkTypeRequirements(TypePointers const*)
2014-10-13 16:22:15 +00:00
{
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<Expression> const& argument: m_arguments)
{
argument->checkTypeRequirements(nullptr);
// only store them for positional calls
if (isPositionalCall)
argumentTypes.push_back(argument->getType());
}
2014-10-20 10:41:56 +00:00
m_expression->checkTypeRequirements(isPositionalCall ? &argumentTypes : nullptr);
2015-03-01 03:34:39 +00:00
2014-10-20 10:41:56 +00:00
Type const* expressionType = m_expression->getType().get();
if (isTypeConversion())
2014-10-16 12:08:54 +00:00
{
2014-11-05 13:20:56 +00:00
TypeType const& type = dynamic_cast<TypeType const&>(*expressionType);
2014-10-13 16:22:15 +00:00
//@todo for structs, we have to check the number of arguments to be equal to the
// number of non-mapping members
if (m_arguments.size() != 1)
BOOST_THROW_EXCEPTION(createTypeError("Exactly one argument expected for explicit type conversion."));
if (!isPositionalCall)
2015-02-08 23:49:35 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Type conversion cannot allow named arguments."));
2014-11-05 13:20:56 +00:00
if (!m_arguments.front()->getType()->isExplicitlyConvertibleTo(*type.getActualType()))
2014-10-23 17:22:30 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Explicit type conversion not allowed."));
2014-11-05 13:20:56 +00:00
m_type = type.getActualType();
2014-10-16 12:08:54 +00:00
}
2014-12-12 15:49:26 +00:00
else if (FunctionType const* functionType = dynamic_cast<FunctionType const*>(expressionType))
2014-10-16 12:08:54 +00:00
{
2014-10-13 16:22:15 +00:00
//@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
2014-12-12 15:49:26 +00:00
TypePointers const& parameterTypes = functionType->getParameterTypes();
if (!functionType->takesArbitraryParameters() && parameterTypes.size() != m_arguments.size())
2014-10-23 17:22:30 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Wrong argument count for function call."));
2015-01-29 17:26:00 +00:00
if (isPositionalCall)
2015-01-29 17:26:00 +00:00
{
// call by positional arguments
2015-01-29 17:26:00 +00:00
for (size_t i = 0; i < m_arguments.size(); ++i)
if (!functionType->takesArbitraryParameters() &&
2015-02-08 23:49:35 +00:00
!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i]))
BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError("Invalid type for argument in function call."));
2015-01-29 17:26:00 +00:00
}
else
{
// call by named arguments
if (functionType->takesArbitraryParameters())
BOOST_THROW_EXCEPTION(createTypeError("Named arguments cannnot be used for functions "
"that take arbitrary parameters."));
2015-01-29 17:26:00 +00:00
auto const& parameterNames = functionType->getParameterNames();
if (parameterNames.size() != m_names.size())
BOOST_THROW_EXCEPTION(createTypeError("Some argument names are missing."));
// check duplicate names
2015-02-08 23:49:35 +00:00
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])
2015-02-08 23:49:35 +00:00
BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError("Duplicate named argument."));
2015-01-29 17:26:00 +00:00
for (size_t i = 0; i < m_names.size(); i++) {
bool found = false;
for (size_t j = 0; j < parameterNames.size(); j++) {
2015-02-03 20:25:08 +00:00
if (parameterNames[j] == *m_names[i]) {
2015-01-29 17:26:00 +00:00
// check type convertible
if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[j]))
BOOST_THROW_EXCEPTION(createTypeError("Invalid type for argument in function call."));
found = true;
break;
}
}
if (!found)
2015-02-08 23:49:35 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Named argument does not match function declaration."));
2015-01-29 17:26:00 +00:00
}
}
2014-10-13 16:22:15 +00:00
// @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 structs
2014-12-12 15:49:26 +00:00
if (functionType->getReturnParameterTypes().empty())
2014-10-24 17:06:30 +00:00
m_type = make_shared<VoidType>();
2014-10-13 16:22:15 +00:00
else
2014-12-12 15:49:26 +00:00
m_type = functionType->getReturnParameterTypes().front();
2014-10-16 12:08:54 +00:00
}
2014-12-12 15:49:26 +00:00
else
BOOST_THROW_EXCEPTION(createTypeError("Type is not callable."));
2014-10-20 10:41:56 +00:00
}
bool FunctionCall::isTypeConversion() const
{
2015-02-10 08:52:19 +00:00
return m_expression->getType()->getCategory() == Type::Category::TypeType;
2014-10-13 16:22:15 +00:00
}
void NewExpression::checkTypeRequirements(TypePointers const*)
2014-12-12 15:49:26 +00:00
{
m_contractName->checkTypeRequirements(nullptr);
m_contract = dynamic_cast<ContractDefinition const*>(&m_contractName->getReferencedDeclaration());
2014-12-12 15:49:26 +00:00
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."));
2015-01-13 17:12:19 +00:00
shared_ptr<ContractType const> contractType = make_shared<ContractType>(*m_contract);
TypePointers const& parameterTypes = contractType->getConstructorType()->getParameterTypes();
m_type = make_shared<FunctionType>(
parameterTypes,
TypePointers{contractType},
strings(),
strings(),
FunctionType::Location::Creation);
2014-12-12 15:49:26 +00:00
}
void MemberAccess::checkTypeRequirements(TypePointers const* _argumentTypes)
2014-10-13 16:22:15 +00:00
{
m_expression->checkTypeRequirements(nullptr);
2014-11-20 09:19:43 +00:00
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<FunctionType const&>(*it->type).canTakeArguments(*_argumentTypes)
)
it = possibleMembers.erase(it);
else
++it;
}
if (possibleMembers.size() == 0)
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<ArrayType const&>(type));
m_isLValue = (*m_memberName == "length" &&
arrayType.location() != ReferenceType::Location::CallData && arrayType.isDynamicallySized());
}
else
m_isLValue = false;
2014-10-13 16:22:15 +00:00
}
void IndexAccess::checkTypeRequirements(TypePointers const*)
2014-10-13 16:22:15 +00:00
{
m_base->checkTypeRequirements(nullptr);
2015-02-20 23:46:35 +00:00
switch (m_base->getType()->getCategory())
{
case Type::Category::Array:
{
ArrayType const& type = dynamic_cast<ArrayType const&>(*m_base->getType());
if (!m_index)
BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted."));
2015-05-28 14:20:50 +00:00
if (type.isString())
BOOST_THROW_EXCEPTION(createTypeError("Index access for string is not possible."));
2015-02-20 23:46:35 +00:00
m_index->expectType(IntegerType(256));
2015-03-03 16:55:28 +00:00
if (type.isByteArray())
2015-03-06 16:20:00 +00:00
m_type = make_shared<FixedBytesType>(1);
2015-03-03 16:55:28 +00:00
else
m_type = type.getBaseType();
m_isLValue = type.location() != ReferenceType::Location::CallData;
2015-02-20 23:46:35 +00:00
break;
}
case Type::Category::Mapping:
{
MappingType const& type = dynamic_cast<MappingType const&>(*m_base->getType());
if (!m_index)
BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted."));
2015-02-20 23:46:35 +00:00
m_index->expectType(*type.getKeyType());
m_type = type.getValueType();
m_isLValue = true;
break;
}
case Type::Category::TypeType:
{
TypeType const& type = dynamic_cast<TypeType const&>(*m_base->getType());
if (!m_index)
m_type = make_shared<TypeType>(make_shared<ArrayType>(ReferenceType::Location::Memory, type.getActualType()));
else
{
m_index->checkTypeRequirements(nullptr);
auto length = dynamic_cast<IntegerConstantType const*>(m_index->getType().get());
if (!length)
BOOST_THROW_EXCEPTION(m_index->createTypeError("Integer constant expected."));
m_type = make_shared<TypeType>(make_shared<ArrayType>(
ReferenceType::Location::Memory, type.getActualType(), length->literalValue(nullptr)));
}
break;
}
2015-02-20 23:46:35 +00:00
default:
BOOST_THROW_EXCEPTION(m_base->createTypeError(
"Indexed expression has to be a type, mapping or array (is " + m_base->getType()->toString() + ")"));
2015-02-20 23:46:35 +00:00
}
2014-10-13 16:22:15 +00:00
}
void Identifier::checkTypeRequirements(TypePointers const* _argumentTypes)
2015-03-01 03:34:39 +00:00
{
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."));
2014-10-13 16:22:15 +00:00
}
Declaration const& Identifier::getReferencedDeclaration() const
{
solAssert(!!m_referencedDeclaration, "Identifier not resolved.");
return *m_referencedDeclaration;
}
void Identifier::overloadResolution(TypePointers const& _argumentTypes)
2015-03-01 03:34:39 +00:00
{
solAssert(!m_referencedDeclaration, "Referenced declaration should be null before overload resolution.");
solAssert(!m_overloadedDeclarations.empty(), "No candidates for overload resolution found.");
2015-03-01 03:34:39 +00:00
2015-05-04 15:18:01 +00:00
vector<Declaration const*> possibles;
if (m_overloadedDeclarations.size() == 1)
m_referencedDeclaration = *m_overloadedDeclarations.begin();
2015-03-01 03:34:39 +00:00
for (Declaration const* declaration: m_overloadedDeclarations)
2015-03-01 03:34:39 +00:00
{
TypePointer const& function = declaration->getType();
auto const* functionType = dynamic_cast<FunctionType const*>(function.get());
if (functionType && functionType->canTakeArguments(_argumentTypes))
possibles.push_back(declaration);
2015-03-01 03:34:39 +00:00
}
if (possibles.size() == 1)
m_referencedDeclaration = possibles.front();
else if (possibles.empty())
BOOST_THROW_EXCEPTION(createTypeError("No matching declaration found after argument-dependent lookup."));
2015-03-01 03:34:39 +00:00
else
BOOST_THROW_EXCEPTION(createTypeError("No unique declaration found after argument-dependent lookup."));
2015-03-01 03:34:39 +00:00
}
void ElementaryTypeNameExpression::checkTypeRequirements(TypePointers const*)
2014-10-13 16:22:15 +00:00
{
m_type = make_shared<TypeType>(Type::fromElementaryTypeName(m_typeToken));
2014-10-13 16:22:15 +00:00
}
void Literal::checkTypeRequirements(TypePointers const*)
2014-10-13 16:22:15 +00:00
{
m_type = Type::forLiteral(*this);
if (!m_type)
2014-12-19 10:31:17 +00:00
BOOST_THROW_EXCEPTION(createTypeError("Invalid literal value."));
2014-10-13 16:22:15 +00:00
}
2014-10-16 12:08:54 +00:00
}
}