Merge remote-tracking branch 'orig/develop' into hot_gav

This commit is contained in:
Gav Wood 2015-11-23 12:44:41 +01:00
commit 4a1b22f043
16 changed files with 494 additions and 229 deletions

View File

@ -8,7 +8,7 @@ include(EthPolicy)
eth_policy() eth_policy()
# project name and version should be set after cmake_policy CMP0048 # project name and version should be set after cmake_policy CMP0048
set(PROJECT_VERSION "0.1.6") set(PROJECT_VERSION "0.1.7")
project(solidity VERSION ${PROJECT_VERSION}) project(solidity VERSION ${PROJECT_VERSION})
# Let's find our dependencies # Let's find our dependencies

View File

@ -40,6 +40,10 @@ m_magicVariables(vector<shared_ptr<MagicVariableDeclaration const>>{make_shared<
make_shared<MagicVariableDeclaration>("now", make_shared<IntegerType>(256)), make_shared<MagicVariableDeclaration>("now", make_shared<IntegerType>(256)),
make_shared<MagicVariableDeclaration>("suicide", make_shared<MagicVariableDeclaration>("suicide",
make_shared<FunctionType>(strings{"address"}, strings{}, FunctionType::Location::Suicide)), make_shared<FunctionType>(strings{"address"}, strings{}, FunctionType::Location::Suicide)),
make_shared<MagicVariableDeclaration>("addmod",
make_shared<FunctionType>(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Location::AddMod)),
make_shared<MagicVariableDeclaration>("mulmod",
make_shared<FunctionType>(strings{"uint256", "uint256", "uint256"}, strings{"uint256"}, FunctionType::Location::MulMod)),
make_shared<MagicVariableDeclaration>("sha3", make_shared<MagicVariableDeclaration>("sha3",
make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Location::SHA3, true)), make_shared<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Location::SHA3, true)),
make_shared<MagicVariableDeclaration>("log0", make_shared<MagicVariableDeclaration>("log0",

View File

@ -64,11 +64,16 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
{ {
m_currentScope = &m_scopes[nullptr]; m_currentScope = &m_scopes[nullptr];
ReferencesResolver resolver(m_errors, *this, &_contract, nullptr);
bool success = true;
for (ASTPointer<InheritanceSpecifier> const& baseContract: _contract.baseContracts()) for (ASTPointer<InheritanceSpecifier> const& baseContract: _contract.baseContracts())
ReferencesResolver resolver(*baseContract, *this, &_contract, nullptr); if (!resolver.resolve(*baseContract))
success = false;
m_currentScope = &m_scopes[&_contract]; m_currentScope = &m_scopes[&_contract];
if (success)
{
linearizeBaseContracts(_contract); linearizeBaseContracts(_contract);
std::vector<ContractDefinition const*> properBases( std::vector<ContractDefinition const*> properBases(
++_contract.annotation().linearizedBaseContracts.begin(), ++_contract.annotation().linearizedBaseContracts.begin(),
@ -77,52 +82,69 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
for (ContractDefinition const* base: properBases) for (ContractDefinition const* base: properBases)
importInheritedScope(*base); importInheritedScope(*base);
}
for (ASTPointer<StructDefinition> const& structDef: _contract.definedStructs()) for (ASTPointer<StructDefinition> const& structDef: _contract.definedStructs())
ReferencesResolver resolver(*structDef, *this, &_contract, nullptr); if (!resolver.resolve(*structDef))
success = false;
for (ASTPointer<EnumDefinition> const& enumDef: _contract.definedEnums()) for (ASTPointer<EnumDefinition> const& enumDef: _contract.definedEnums())
ReferencesResolver resolver(*enumDef, *this, &_contract, nullptr); if (!resolver.resolve(*enumDef))
success = false;
for (ASTPointer<VariableDeclaration> const& variable: _contract.stateVariables()) for (ASTPointer<VariableDeclaration> const& variable: _contract.stateVariables())
ReferencesResolver resolver(*variable, *this, &_contract, nullptr); if (!resolver.resolve(*variable))
success = false;
for (ASTPointer<EventDefinition> const& event: _contract.events()) for (ASTPointer<EventDefinition> const& event: _contract.events())
ReferencesResolver resolver(*event, *this, &_contract, nullptr); if (!resolver.resolve(*event))
success = false;
// these can contain code, only resolve parameters for now // these can contain code, only resolve parameters for now
for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers()) for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers())
{ {
m_currentScope = &m_scopes[modifier.get()]; m_currentScope = &m_scopes[modifier.get()];
ReferencesResolver resolver(*modifier, *this, &_contract, nullptr); ReferencesResolver resolver(m_errors, *this, &_contract, nullptr);
if (!resolver.resolve(*modifier))
success = false;
} }
for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
{ {
m_currentScope = &m_scopes[function.get()]; m_currentScope = &m_scopes[function.get()];
ReferencesResolver referencesResolver( if (!ReferencesResolver(
*function, m_errors,
*this, *this,
&_contract, &_contract,
function->returnParameterList().get() function->returnParameterList().get()
); ).resolve(*function))
success = false;
} }
if (!success)
return false;
m_currentScope = &m_scopes[&_contract]; m_currentScope = &m_scopes[&_contract];
// now resolve references inside the code // now resolve references inside the code
for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers()) for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers())
{ {
m_currentScope = &m_scopes[modifier.get()]; m_currentScope = &m_scopes[modifier.get()];
ReferencesResolver resolver(*modifier, *this, &_contract, nullptr, true); ReferencesResolver resolver(m_errors, *this, &_contract, nullptr, true);
if (!resolver.resolve(*modifier))
success = false;
} }
for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
{ {
m_currentScope = &m_scopes[function.get()]; m_currentScope = &m_scopes[function.get()];
ReferencesResolver referencesResolver( if (!ReferencesResolver(
*function, m_errors,
*this, *this,
&_contract, &_contract,
function->returnParameterList().get(), function->returnParameterList().get(),
true true
); ).resolve(*function))
success = false;
} }
if (!success)
return false;
} }
catch (FatalError const& _e) catch (FatalError const& _e)
{ {

View File

@ -31,21 +31,6 @@ using namespace dev;
using namespace dev::solidity; using namespace dev::solidity;
ReferencesResolver::ReferencesResolver(
ASTNode& _root,
NameAndTypeResolver& _resolver,
ContractDefinition const* _currentContract,
ParameterList const* _returnParameters,
bool _resolveInsideCode
):
m_resolver(_resolver),
m_currentContract(_currentContract),
m_returnParameters(_returnParameters),
m_resolveInsideCode(_resolveInsideCode)
{
_root.accept(*this);
}
bool ReferencesResolver::visit(Return const& _return) bool ReferencesResolver::visit(Return const& _return)
{ {
_return.annotation().functionReturnParameters = m_returnParameters; _return.annotation().functionReturnParameters = m_returnParameters;
@ -56,24 +41,30 @@ bool ReferencesResolver::visit(UserDefinedTypeName const& _typeName)
{ {
Declaration const* declaration = m_resolver.pathFromCurrentScope(_typeName.namePath()); Declaration const* declaration = m_resolver.pathFromCurrentScope(_typeName.namePath());
if (!declaration) if (!declaration)
BOOST_THROW_EXCEPTION( fatalDeclarationError(_typeName.location(), "Identifier not found or not unique.");
Error(Error::Type::DeclarationError) <<
errinfo_sourceLocation(_typeName.location()) <<
errinfo_comment("Identifier not found or not unique.")
);
_typeName.annotation().referencedDeclaration = declaration; _typeName.annotation().referencedDeclaration = declaration;
return true; return true;
} }
bool ReferencesResolver::resolve(ASTNode& _root)
{
try
{
_root.accept(*this);
}
catch (FatalError const& e)
{
solAssert(m_errorOccurred, "");
}
return !m_errorOccurred;
}
bool ReferencesResolver::visit(Identifier const& _identifier) bool ReferencesResolver::visit(Identifier const& _identifier)
{ {
auto declarations = m_resolver.nameFromCurrentScope(_identifier.name()); auto declarations = m_resolver.nameFromCurrentScope(_identifier.name());
if (declarations.empty()) if (declarations.empty())
BOOST_THROW_EXCEPTION( fatalDeclarationError(_identifier.location(), "Undeclared identifier.");
Error(Error::Type::DeclarationError) <<
errinfo_sourceLocation(_identifier.location()) <<
errinfo_comment("Undeclared identifier.")
);
else if (declarations.size() == 1) else if (declarations.size() == 1)
{ {
_identifier.annotation().referencedDeclaration = declarations.front(); _identifier.annotation().referencedDeclaration = declarations.front();
@ -108,19 +99,19 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
if (contract.isLibrary()) if (contract.isLibrary())
{ {
if (loc == Location::Memory) if (loc == Location::Memory)
BOOST_THROW_EXCEPTION(_variable.createTypeError( fatalTypeError(_variable.location(),
"Location has to be calldata or storage for external " "Location has to be calldata or storage for external "
"library functions (remove the \"memory\" keyword)." "library functions (remove the \"memory\" keyword)."
)); );
} }
else else
{ {
// force location of external function parameters (not return) to calldata // force location of external function parameters (not return) to calldata
if (loc != Location::Default) if (loc != Location::Default)
BOOST_THROW_EXCEPTION(_variable.createTypeError( fatalTypeError(_variable.location(),
"Location has to be calldata for external functions " "Location has to be calldata for external functions "
"(remove the \"memory\" or \"storage\" keyword)." "(remove the \"memory\" or \"storage\" keyword)."
)); );
} }
if (loc == Location::Default) if (loc == Location::Default)
type = ref->copyForLocation(DataLocation::CallData, true); type = ref->copyForLocation(DataLocation::CallData, true);
@ -130,10 +121,10 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
auto const& contract = dynamic_cast<ContractDefinition const&>(*_variable.scope()->scope()); auto const& contract = dynamic_cast<ContractDefinition const&>(*_variable.scope()->scope());
// force locations of public or external function (return) parameters to memory // force locations of public or external function (return) parameters to memory
if (loc == Location::Storage && !contract.isLibrary()) if (loc == Location::Storage && !contract.isLibrary())
BOOST_THROW_EXCEPTION(_variable.createTypeError( fatalTypeError(_variable.location(),
"Location has to be memory for publicly visible functions " "Location has to be memory for publicly visible functions "
"(remove the \"storage\" keyword)." "(remove the \"storage\" keyword)."
)); );
if (loc == Location::Default || !contract.isLibrary()) if (loc == Location::Default || !contract.isLibrary())
type = ref->copyForLocation(DataLocation::Memory, true); type = ref->copyForLocation(DataLocation::Memory, true);
} }
@ -142,9 +133,10 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
if (_variable.isConstant()) if (_variable.isConstant())
{ {
if (loc != Location::Default && loc != Location::Memory) if (loc != Location::Default && loc != Location::Memory)
BOOST_THROW_EXCEPTION(_variable.createTypeError( fatalTypeError(
_variable.location(),
"Storage location has to be \"memory\" (or unspecified) for constants." "Storage location has to be \"memory\" (or unspecified) for constants."
)); );
loc = Location::Memory; loc = Location::Memory;
} }
if (loc == Location::Default) if (loc == Location::Default)
@ -159,16 +151,14 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
} }
} }
else if (loc != Location::Default && !ref) else if (loc != Location::Default && !ref)
BOOST_THROW_EXCEPTION(_variable.createTypeError( fatalTypeError(_variable.location(), "Storage location can only be given for array or struct types.");
"Storage location can only be given for array or struct types."
));
if (!type) if (!type)
BOOST_THROW_EXCEPTION(_variable.typeName()->createTypeError("Invalid type name.")); fatalTypeError(_variable.location(), "Invalid type name.");
} }
else if (!_variable.canHaveAutoType()) else if (!_variable.canHaveAutoType())
BOOST_THROW_EXCEPTION(_variable.createTypeError("Explicit type needed.")); fatalTypeError(_variable.location(), "Explicit type needed.");
// otherwise we have a "var"-declaration whose type is resolved by the first assignment // otherwise we have a "var"-declaration whose type is resolved by the first assignment
_variable.annotation().type = type; _variable.annotation().type = type;
@ -194,9 +184,7 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration)) else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration))
type = make_shared<ContractType>(*contract); type = make_shared<ContractType>(*contract);
else else
BOOST_THROW_EXCEPTION(typeName->createTypeError( fatalTypeError(typeName->location(), "Name has to refer to a struct, enum or contract.");
"Name has to refer to a struct, enum or contract."
));
} }
else if (auto mapping = dynamic_cast<Mapping const*>(&_typeName)) else if (auto mapping = dynamic_cast<Mapping const*>(&_typeName))
{ {
@ -212,9 +200,7 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
{ {
TypePointer baseType = typeFor(arrayType->baseType()); TypePointer baseType = typeFor(arrayType->baseType());
if (baseType->storageBytes() == 0) if (baseType->storageBytes() == 0)
BOOST_THROW_EXCEPTION(arrayType->baseType().createTypeError( fatalTypeError(arrayType->baseType().location(), "Illegal base type of storage size zero for array.");
"Illegal base type of storage size zero for array."
));
if (Expression const* length = arrayType->length()) if (Expression const* length = arrayType->length())
{ {
if (!length->annotation().type) if (!length->annotation().type)
@ -222,7 +208,8 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
auto const* lengthType = dynamic_cast<IntegerConstantType const*>(length->annotation().type.get()); auto const* lengthType = dynamic_cast<IntegerConstantType const*>(length->annotation().type.get());
if (!lengthType) if (!lengthType)
BOOST_THROW_EXCEPTION(length->createTypeError("Invalid array length.")); fatalTypeError(length->location(), "Invalid array length.");
else
type = make_shared<ArrayType>(DataLocation::Storage, baseType, lengthType->literalValue(nullptr)); type = make_shared<ArrayType>(DataLocation::Storage, baseType, lengthType->literalValue(nullptr));
} }
else else
@ -232,3 +219,31 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
return _typeName.annotation().type = move(type); return _typeName.annotation().type = move(type);
} }
void ReferencesResolver::typeError(SourceLocation const& _location, string const& _description)
{
auto err = make_shared<Error>(Error::Type::TypeError);
*err << errinfo_sourceLocation(_location) << errinfo_comment(_description);
m_errorOccurred = true;
m_errors.push_back(err);
}
void ReferencesResolver::fatalTypeError(SourceLocation const& _location, string const& _description)
{
typeError(_location, _description);
BOOST_THROW_EXCEPTION(FatalError());
}
void ReferencesResolver::declarationError(SourceLocation const& _location, string const& _description)
{
auto err = make_shared<Error>(Error::Type::DeclarationError);
*err << errinfo_sourceLocation(_location) << errinfo_comment(_description);
m_errorOccurred = true;
m_errors.push_back(err);
}
void ReferencesResolver::fatalDeclarationError(SourceLocation const& _location, string const& _description)
{
declarationError(_location, _description);
BOOST_THROW_EXCEPTION(FatalError());
}

View File

@ -43,12 +43,21 @@ class ReferencesResolver: private ASTConstVisitor
{ {
public: public:
ReferencesResolver( ReferencesResolver(
ASTNode& _root, ErrorList& _errors,
NameAndTypeResolver& _resolver, NameAndTypeResolver& _resolver,
ContractDefinition const* _currentContract, ContractDefinition const* _currentContract,
ParameterList const* _returnParameters, ParameterList const* _returnParameters,
bool _resolveInsideCode = false bool _resolveInsideCode = false
); ):
m_errors(_errors),
m_resolver(_resolver),
m_currentContract(_currentContract),
m_returnParameters(_returnParameters),
m_resolveInsideCode(_resolveInsideCode)
{}
/// @returns true if no errors during resolving
bool resolve(ASTNode& _root);
private: private:
virtual bool visit(Block const&) override { return m_resolveInsideCode; } virtual bool visit(Block const&) override { return m_resolveInsideCode; }
@ -59,10 +68,24 @@ private:
TypePointer typeFor(TypeName const& _typeName); TypePointer typeFor(TypeName const& _typeName);
/// Adds a new error to the list of errors.
void typeError(SourceLocation const& _location, std::string const& _description);
/// Adds a new error to the list of errors and throws to abort type checking.
void fatalTypeError(SourceLocation const& _location, std::string const& _description);
/// Adds a new error to the list of errors.
void declarationError(const SourceLocation& _location, std::string const& _description);
/// Adds a new error to the list of errors and throws to abort type checking.
void fatalDeclarationError(const SourceLocation& _location, std::string const& _description);
ErrorList& m_errors;
NameAndTypeResolver& m_resolver; NameAndTypeResolver& m_resolver;
ContractDefinition const* m_currentContract; ContractDefinition const* m_currentContract;
ParameterList const* m_returnParameters; ParameterList const* m_returnParameters;
bool m_resolveInsideCode; bool const m_resolveInsideCode;
bool m_errorOccurred = false;
}; };
} }

View File

@ -71,7 +71,7 @@ bool TypeChecker::visit(ContractDefinition const& _contract)
FunctionDefinition const* function = _contract.constructor(); FunctionDefinition const* function = _contract.constructor();
if (function && !function->returnParameters().empty()) if (function && !function->returnParameters().empty())
typeError(*function->returnParameterList(), "Non-empty \"returns\" directive for constructor."); typeError(function->returnParameterList()->location(), "Non-empty \"returns\" directive for constructor.");
FunctionDefinition const* fallbackFunction = nullptr; FunctionDefinition const* fallbackFunction = nullptr;
for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
@ -88,7 +88,7 @@ bool TypeChecker::visit(ContractDefinition const& _contract)
{ {
fallbackFunction = function.get(); fallbackFunction = function.get();
if (!fallbackFunction->parameters().empty()) if (!fallbackFunction->parameters().empty())
typeError(fallbackFunction->parameterList(), "Fallback function cannot take parameters."); typeError(fallbackFunction->parameterList().location(), "Fallback function cannot take parameters.");
} }
} }
if (!function->isImplemented()) if (!function->isImplemented())
@ -108,7 +108,7 @@ bool TypeChecker::visit(ContractDefinition const& _contract)
FixedHash<4> const& hash = it.first; FixedHash<4> const& hash = it.first;
if (hashes.count(hash)) if (hashes.count(hash))
typeError( typeError(
_contract, _contract.location(),
string("Function signature hash collision for ") + it.second->externalSignature() string("Function signature hash collision for ") + it.second->externalSignature()
); );
hashes.insert(hash); hashes.insert(hash);
@ -183,7 +183,7 @@ void TypeChecker::checkContractAbstractFunctions(ContractDefinition const& _cont
else if (it->second) else if (it->second)
{ {
if (!function->isImplemented()) if (!function->isImplemented())
typeError(*function, "Redeclaring an already implemented function as abstract"); typeError(function->location(), "Redeclaring an already implemented function as abstract");
} }
else if (function->isImplemented()) else if (function->isImplemented())
it->second = true; it->second = true;
@ -252,7 +252,7 @@ void TypeChecker::checkContractIllegalOverrides(ContractDefinition const& _contr
continue; // constructors can neither be overridden nor override anything continue; // constructors can neither be overridden nor override anything
string const& name = function->name(); string const& name = function->name();
if (modifiers.count(name)) if (modifiers.count(name))
typeError(*modifiers[name], "Override changes function to modifier."); typeError(modifiers[name]->location(), "Override changes function to modifier.");
FunctionType functionType(*function); FunctionType functionType(*function);
// function should not change the return type // function should not change the return type
for (FunctionDefinition const* overriding: functions[name]) for (FunctionDefinition const* overriding: functions[name])
@ -265,7 +265,7 @@ void TypeChecker::checkContractIllegalOverrides(ContractDefinition const& _contr
overriding->isDeclaredConst() != function->isDeclaredConst() || overriding->isDeclaredConst() != function->isDeclaredConst() ||
overridingType != functionType overridingType != functionType
) )
typeError(*overriding, "Override changes extended function signature."); typeError(overriding->location(), "Override changes extended function signature.");
} }
functions[name].push_back(function.get()); functions[name].push_back(function.get());
} }
@ -276,9 +276,9 @@ void TypeChecker::checkContractIllegalOverrides(ContractDefinition const& _contr
if (!override) if (!override)
override = modifier.get(); override = modifier.get();
else if (ModifierType(*override) != ModifierType(*modifier)) else if (ModifierType(*override) != ModifierType(*modifier))
typeError(*override, "Override changes modifier signature."); typeError(override->location(), "Override changes modifier signature.");
if (!functions[name].empty()) if (!functions[name].empty())
typeError(*override, "Override changes modifier to function."); typeError(override->location(), "Override changes modifier to function.");
} }
} }
} }
@ -310,7 +310,7 @@ void TypeChecker::checkContractExternalTypeClashes(ContractDefinition const& _co
for (size_t j = i + 1; j < it.second.size(); ++j) for (size_t j = i + 1; j < it.second.size(); ++j)
if (!it.second[i].second->hasEqualArgumentTypes(*it.second[j].second)) if (!it.second[i].second->hasEqualArgumentTypes(*it.second[j].second))
typeError( typeError(
*it.second[j].first, it.second[j].first->location(),
"Function overload clash during conversion to external types for arguments." "Function overload clash during conversion to external types for arguments."
); );
} }
@ -319,11 +319,11 @@ void TypeChecker::checkLibraryRequirements(ContractDefinition const& _contract)
{ {
solAssert(_contract.isLibrary(), ""); solAssert(_contract.isLibrary(), "");
if (!_contract.baseContracts().empty()) if (!_contract.baseContracts().empty())
typeError(_contract, "Library is not allowed to inherit."); typeError(_contract.location(), "Library is not allowed to inherit.");
for (auto const& var: _contract.stateVariables()) for (auto const& var: _contract.stateVariables())
if (!var->isConstant()) if (!var->isConstant())
typeError(*var, "Library cannot have non-constant state variables"); typeError(var->location(), "Library cannot have non-constant state variables");
} }
void TypeChecker::endVisit(InheritanceSpecifier const& _inheritance) void TypeChecker::endVisit(InheritanceSpecifier const& _inheritance)
@ -332,13 +332,13 @@ void TypeChecker::endVisit(InheritanceSpecifier const& _inheritance)
solAssert(base, "Base contract not available."); solAssert(base, "Base contract not available.");
if (base->isLibrary()) if (base->isLibrary())
typeError(_inheritance, "Libraries cannot be inherited from."); typeError(_inheritance.location(), "Libraries cannot be inherited from.");
auto const& arguments = _inheritance.arguments(); auto const& arguments = _inheritance.arguments();
TypePointers parameterTypes = ContractType(*base).constructorType()->parameterTypes(); TypePointers parameterTypes = ContractType(*base).constructorType()->parameterTypes();
if (!arguments.empty() && parameterTypes.size() != arguments.size()) if (!arguments.empty() && parameterTypes.size() != arguments.size())
typeError( typeError(
_inheritance, _inheritance.location(),
"Wrong argument count for constructor call: " + "Wrong argument count for constructor call: " +
toString(arguments.size()) + toString(arguments.size()) +
" arguments given but expected " + " arguments given but expected " +
@ -349,7 +349,7 @@ void TypeChecker::endVisit(InheritanceSpecifier const& _inheritance)
for (size_t i = 0; i < arguments.size(); ++i) for (size_t i = 0; i < arguments.size(); ++i)
if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[i])) if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[i]))
typeError( typeError(
*arguments[i], arguments[i]->location(),
"Invalid type for argument in constructor call. " "Invalid type for argument in constructor call. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
type(*arguments[i])->toString() + type(*arguments[i])->toString() +
@ -363,7 +363,7 @@ bool TypeChecker::visit(StructDefinition const& _struct)
{ {
for (ASTPointer<VariableDeclaration> const& member: _struct.members()) for (ASTPointer<VariableDeclaration> const& member: _struct.members())
if (!type(*member)->canBeStored()) if (!type(*member)->canBeStored())
typeError(*member, "Type cannot be used in struct."); typeError(member->location(), "Type cannot be used in struct.");
// Check recursion, fatal error if detected. // Check recursion, fatal error if detected.
using StructPointer = StructDefinition const*; using StructPointer = StructDefinition const*;
@ -371,7 +371,7 @@ bool TypeChecker::visit(StructDefinition const& _struct)
function<void(StructPointer,StructPointersSet const&)> check = [&](StructPointer _struct, StructPointersSet const& _parents) function<void(StructPointer,StructPointersSet const&)> check = [&](StructPointer _struct, StructPointersSet const& _parents)
{ {
if (_parents.count(_struct)) if (_parents.count(_struct))
fatalTypeError(*_struct, "Recursive struct definition."); fatalTypeError(_struct->location(), "Recursive struct definition.");
StructPointersSet parents = _parents; StructPointersSet parents = _parents;
parents.insert(_struct); parents.insert(_struct);
for (ASTPointer<VariableDeclaration> const& member: _struct->members()) for (ASTPointer<VariableDeclaration> const& member: _struct->members())
@ -394,9 +394,9 @@ bool TypeChecker::visit(FunctionDefinition const& _function)
for (ASTPointer<VariableDeclaration> const& var: _function.parameters() + _function.returnParameters()) for (ASTPointer<VariableDeclaration> const& var: _function.parameters() + _function.returnParameters())
{ {
if (!type(*var)->canLiveOutsideStorage()) if (!type(*var)->canLiveOutsideStorage())
typeError(*var, "Type is required to live outside storage."); typeError(var->location(), "Type is required to live outside storage.");
if (_function.visibility() >= FunctionDefinition::Visibility::Public && !(type(*var)->interfaceType(isLibraryFunction))) if (_function.visibility() >= FunctionDefinition::Visibility::Public && !(type(*var)->interfaceType(isLibraryFunction)))
fatalTypeError(*var, "Internal type is not allowed for public or external functions."); fatalTypeError(var->location(), "Internal type is not allowed for public or external functions.");
} }
for (ASTPointer<ModifierInvocation> const& modifier: _function.modifiers()) for (ASTPointer<ModifierInvocation> const& modifier: _function.modifiers())
visitManually( visitManually(
@ -424,9 +424,9 @@ bool TypeChecker::visit(VariableDeclaration const& _variable)
if (_variable.isConstant()) if (_variable.isConstant())
{ {
if (!dynamic_cast<ContractDefinition const*>(_variable.scope())) if (!dynamic_cast<ContractDefinition const*>(_variable.scope()))
typeError(_variable, "Illegal use of \"constant\" specifier."); typeError(_variable.location(), "Illegal use of \"constant\" specifier.");
if (!_variable.value()) if (!_variable.value())
typeError(_variable, "Uninitialized \"constant\" variable."); typeError(_variable.location(), "Uninitialized \"constant\" variable.");
if (!varType->isValueType()) if (!varType->isValueType())
{ {
bool constImplemented = false; bool constImplemented = false;
@ -434,7 +434,7 @@ bool TypeChecker::visit(VariableDeclaration const& _variable)
constImplemented = arrayType->isByteArray(); constImplemented = arrayType->isByteArray();
if (!constImplemented) if (!constImplemented)
typeError( typeError(
_variable, _variable.location(),
"Illegal use of \"constant\" specifier. \"constant\" " "Illegal use of \"constant\" specifier. \"constant\" "
"is not yet implemented for this type." "is not yet implemented for this type."
); );
@ -446,13 +446,13 @@ bool TypeChecker::visit(VariableDeclaration const& _variable)
{ {
if (varType->dataStoredIn(DataLocation::Memory) || varType->dataStoredIn(DataLocation::CallData)) if (varType->dataStoredIn(DataLocation::Memory) || varType->dataStoredIn(DataLocation::CallData))
if (!varType->canLiveOutsideStorage()) if (!varType->canLiveOutsideStorage())
typeError(_variable, "Type " + varType->toString() + " is only valid in storage."); typeError(_variable.location(), "Type " + varType->toString() + " is only valid in storage.");
} }
else if ( else if (
_variable.visibility() >= VariableDeclaration::Visibility::Public && _variable.visibility() >= VariableDeclaration::Visibility::Public &&
!FunctionType(_variable).interfaceFunctionType() !FunctionType(_variable).interfaceFunctionType()
) )
typeError(_variable, "Internal type is not allowed for public state variables."); typeError(_variable.location(), "Internal type is not allowed for public state variables.");
return false; return false;
} }
@ -483,10 +483,10 @@ void TypeChecker::visitManually(
break; break;
} }
if (!parameters) if (!parameters)
typeError(_modifier, "Referenced declaration is neither modifier nor base class."); typeError(_modifier.location(), "Referenced declaration is neither modifier nor base class.");
if (parameters->size() != arguments.size()) if (parameters->size() != arguments.size())
typeError( typeError(
_modifier, _modifier.location(),
"Wrong argument count for modifier invocation: " + "Wrong argument count for modifier invocation: " +
toString(arguments.size()) + toString(arguments.size()) +
" arguments given but expected " + " arguments given but expected " +
@ -496,7 +496,7 @@ void TypeChecker::visitManually(
for (size_t i = 0; i < _modifier.arguments().size(); ++i) for (size_t i = 0; i < _modifier.arguments().size(); ++i)
if (!type(*arguments[i])->isImplicitlyConvertibleTo(*type(*(*parameters)[i]))) if (!type(*arguments[i])->isImplicitlyConvertibleTo(*type(*(*parameters)[i])))
typeError( typeError(
*arguments[i], arguments[i]->location(),
"Invalid type for argument in modifier invocation. " "Invalid type for argument in modifier invocation. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
type(*arguments[i])->toString() + type(*arguments[i])->toString() +
@ -514,13 +514,13 @@ bool TypeChecker::visit(EventDefinition const& _eventDef)
if (var->isIndexed()) if (var->isIndexed())
numIndexed++; numIndexed++;
if (_eventDef.isAnonymous() && numIndexed > 4) if (_eventDef.isAnonymous() && numIndexed > 4)
typeError(_eventDef, "More than 4 indexed arguments for anonymous event."); typeError(_eventDef.location(), "More than 4 indexed arguments for anonymous event.");
else if (!_eventDef.isAnonymous() && numIndexed > 3) else if (!_eventDef.isAnonymous() && numIndexed > 3)
typeError(_eventDef, "More than 3 indexed arguments for event."); typeError(_eventDef.location(), "More than 3 indexed arguments for event.");
if (!type(*var)->canLiveOutsideStorage()) if (!type(*var)->canLiveOutsideStorage())
typeError(*var, "Type is required to live outside storage."); typeError(var->location(), "Type is required to live outside storage.");
if (!type(*var)->interfaceType(false)) if (!type(*var)->interfaceType(false))
typeError(*var, "Internal type is not allowed as event parameter type."); typeError(var->location(), "Internal type is not allowed as event parameter type.");
} }
return false; return false;
} }
@ -561,7 +561,7 @@ void TypeChecker::endVisit(Return const& _return)
ParameterList const* params = _return.annotation().functionReturnParameters; ParameterList const* params = _return.annotation().functionReturnParameters;
if (!params) if (!params)
{ {
typeError(_return, "Return arguments not allowed."); typeError(_return.location(), "Return arguments not allowed.");
return; return;
} }
TypePointers returnTypes; TypePointers returnTypes;
@ -570,10 +570,10 @@ void TypeChecker::endVisit(Return const& _return)
if (auto tupleType = dynamic_cast<TupleType const*>(type(*_return.expression()).get())) if (auto tupleType = dynamic_cast<TupleType const*>(type(*_return.expression()).get()))
{ {
if (tupleType->components().size() != params->parameters().size()) if (tupleType->components().size() != params->parameters().size())
typeError(_return, "Different number of arguments in return statement than in returns declaration."); typeError(_return.location(), "Different number of arguments in return statement than in returns declaration.");
else if (!tupleType->isImplicitlyConvertibleTo(TupleType(returnTypes))) else if (!tupleType->isImplicitlyConvertibleTo(TupleType(returnTypes)))
typeError( typeError(
*_return.expression(), _return.expression()->location(),
"Return argument type " + "Return argument type " +
type(*_return.expression())->toString() + type(*_return.expression())->toString() +
" is not implicitly convertible to expected type " + " is not implicitly convertible to expected type " +
@ -582,13 +582,13 @@ void TypeChecker::endVisit(Return const& _return)
); );
} }
else if (params->parameters().size() != 1) else if (params->parameters().size() != 1)
typeError(_return, "Different number of arguments in return statement than in returns declaration."); typeError(_return.location(), "Different number of arguments in return statement than in returns declaration.");
else else
{ {
TypePointer const& expected = type(*params->parameters().front()); TypePointer const& expected = type(*params->parameters().front());
if (!type(*_return.expression())->isImplicitlyConvertibleTo(*expected)) if (!type(*_return.expression())->isImplicitlyConvertibleTo(*expected))
typeError( typeError(
*_return.expression(), _return.expression()->location(),
"Return argument type " + "Return argument type " +
type(*_return.expression())->toString() + type(*_return.expression())->toString() +
" is not implicitly convertible to expected type (type of first return variable) " + " is not implicitly convertible to expected type (type of first return variable) " +
@ -604,10 +604,10 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
{ {
// No initial value is only permitted for single variables with specified type. // No initial value is only permitted for single variables with specified type.
if (_statement.declarations().size() != 1 || !_statement.declarations().front()) if (_statement.declarations().size() != 1 || !_statement.declarations().front())
fatalTypeError(_statement, "Assignment necessary for type detection."); fatalTypeError(_statement.location(), "Assignment necessary for type detection.");
VariableDeclaration const& varDecl = *_statement.declarations().front(); VariableDeclaration const& varDecl = *_statement.declarations().front();
if (!varDecl.annotation().type) if (!varDecl.annotation().type)
fatalTypeError(_statement, "Assignment necessary for type detection."); fatalTypeError(_statement.location(), "Assignment necessary for type detection.");
if (auto ref = dynamic_cast<ReferenceType const*>(type(varDecl).get())) if (auto ref = dynamic_cast<ReferenceType const*>(type(varDecl).get()))
{ {
if (ref->dataStoredIn(DataLocation::Storage)) if (ref->dataStoredIn(DataLocation::Storage))
@ -642,7 +642,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
{ {
if (!valueTypes.empty()) if (!valueTypes.empty())
fatalTypeError( fatalTypeError(
_statement, _statement.location(),
"Too many components (" + "Too many components (" +
toString(valueTypes.size()) + toString(valueTypes.size()) +
") in value for variable assignment (0) needed" ") in value for variable assignment (0) needed"
@ -650,7 +650,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
} }
else if (valueTypes.size() != variables.size() && !variables.front() && !variables.back()) else if (valueTypes.size() != variables.size() && !variables.front() && !variables.back())
fatalTypeError( fatalTypeError(
_statement, _statement.location(),
"Wildcard both at beginning and end of variable declaration list is only allowed " "Wildcard both at beginning and end of variable declaration list is only allowed "
"if the number of components is equal." "if the number of components is equal."
); );
@ -659,7 +659,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
--minNumValues; --minNumValues;
if (valueTypes.size() < minNumValues) if (valueTypes.size() < minNumValues)
fatalTypeError( fatalTypeError(
_statement, _statement.location(),
"Not enough components (" + "Not enough components (" +
toString(valueTypes.size()) + toString(valueTypes.size()) +
") in value to assign all variables (" + ") in value to assign all variables (" +
@ -667,7 +667,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
); );
if (valueTypes.size() > variables.size() && variables.front() && variables.back()) if (valueTypes.size() > variables.size() && variables.front() && variables.back())
fatalTypeError( fatalTypeError(
_statement, _statement.location(),
"Too many components (" + "Too many components (" +
toString(valueTypes.size()) + toString(valueTypes.size()) +
") in value for variable assignment (" + ") in value for variable assignment (" +
@ -697,7 +697,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
valueComponentType->category() == Type::Category::IntegerConstant && valueComponentType->category() == Type::Category::IntegerConstant &&
!dynamic_pointer_cast<IntegerConstantType const>(valueComponentType)->integerType() !dynamic_pointer_cast<IntegerConstantType const>(valueComponentType)->integerType()
) )
fatalTypeError(*_statement.initialValue(), "Invalid integer constant " + valueComponentType->toString() + "."); fatalTypeError(_statement.initialValue()->location(), "Invalid integer constant " + valueComponentType->toString() + ".");
var.annotation().type = valueComponentType->mobileType(); var.annotation().type = valueComponentType->mobileType();
var.accept(*this); var.accept(*this);
} }
@ -706,7 +706,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
var.accept(*this); var.accept(*this);
if (!valueComponentType->isImplicitlyConvertibleTo(*var.annotation().type)) if (!valueComponentType->isImplicitlyConvertibleTo(*var.annotation().type))
typeError( typeError(
_statement, _statement.location(),
"Type " + "Type " +
valueComponentType->toString() + valueComponentType->toString() +
" is not implicitly convertible to expected type " + " is not implicitly convertible to expected type " +
@ -722,7 +722,7 @@ void TypeChecker::endVisit(ExpressionStatement const& _statement)
{ {
if (type(_statement.expression())->category() == Type::Category::IntegerConstant) if (type(_statement.expression())->category() == Type::Category::IntegerConstant)
if (!dynamic_pointer_cast<IntegerConstantType const>(type(_statement.expression()))->integerType()) if (!dynamic_pointer_cast<IntegerConstantType const>(type(_statement.expression()))->integerType())
typeError(_statement.expression(), "Invalid integer constant."); typeError(_statement.expression().location(), "Invalid integer constant.");
} }
bool TypeChecker::visit(Assignment const& _assignment) bool TypeChecker::visit(Assignment const& _assignment)
@ -738,7 +738,7 @@ bool TypeChecker::visit(Assignment const& _assignment)
} }
else if (t->category() == Type::Category::Mapping) else if (t->category() == Type::Category::Mapping)
{ {
typeError(_assignment, "Mappings cannot be assigned to."); typeError(_assignment.location(), "Mappings cannot be assigned to.");
_assignment.rightHandSide().accept(*this); _assignment.rightHandSide().accept(*this);
} }
else if (_assignment.assignmentOperator() == Token::Assign) else if (_assignment.assignmentOperator() == Token::Assign)
@ -753,7 +753,7 @@ bool TypeChecker::visit(Assignment const& _assignment)
); );
if (!resultType || *resultType != *t) if (!resultType || *resultType != *t)
typeError( typeError(
_assignment, _assignment.location(),
"Operator " + "Operator " +
string(Token::toString(_assignment.assignmentOperator())) + string(Token::toString(_assignment.assignmentOperator())) +
" not compatible with types " + " not compatible with types " +
@ -789,7 +789,7 @@ bool TypeChecker::visit(TupleExpression const& _tuple)
{ {
// Outside of an lvalue-context, the only situation where a component can be empty is (x,). // Outside of an lvalue-context, the only situation where a component can be empty is (x,).
if (!components[i] && !(i == 1 && components.size() == 2)) if (!components[i] && !(i == 1 && components.size() == 2))
fatalTypeError(_tuple, "Tuple component cannot be empty."); fatalTypeError(_tuple.location(), "Tuple component cannot be empty.");
else if (components[i]) else if (components[i])
{ {
components[i]->accept(*this); components[i]->accept(*this);
@ -823,7 +823,7 @@ bool TypeChecker::visit(UnaryOperation const& _operation)
if (!t) if (!t)
{ {
typeError( typeError(
_operation, _operation.location(),
"Unary operator " + "Unary operator " +
string(Token::toString(op)) + string(Token::toString(op)) +
" cannot be applied to type " + " cannot be applied to type " +
@ -843,7 +843,7 @@ void TypeChecker::endVisit(BinaryOperation const& _operation)
if (!commonType) if (!commonType)
{ {
typeError( typeError(
_operation, _operation.location(),
"Operator " + "Operator " +
string(Token::toString(_operation.getOperator())) + string(Token::toString(_operation.getOperator())) +
" not compatible with types " + " not compatible with types " +
@ -896,9 +896,9 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
TypeType const& t = dynamic_cast<TypeType const&>(*expressionType); TypeType const& t = dynamic_cast<TypeType const&>(*expressionType);
TypePointer resultType = t.actualType(); TypePointer resultType = t.actualType();
if (arguments.size() != 1) if (arguments.size() != 1)
typeError(_functionCall, "Exactly one argument expected for explicit type conversion."); typeError(_functionCall.location(), "Exactly one argument expected for explicit type conversion.");
else if (!isPositionalCall) else if (!isPositionalCall)
typeError(_functionCall, "Type conversion cannot allow named arguments."); typeError(_functionCall.location(), "Type conversion cannot allow named arguments.");
else else
{ {
TypePointer const& argType = type(*arguments.front()); TypePointer const& argType = type(*arguments.front());
@ -907,7 +907,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
// (data location cannot yet be specified for type conversions) // (data location cannot yet be specified for type conversions)
resultType = ReferenceType::copyForLocationIfReference(argRefType->location(), resultType); resultType = ReferenceType::copyForLocationIfReference(argRefType->location(), resultType);
if (!argType->isExplicitlyConvertibleTo(*resultType)) if (!argType->isExplicitlyConvertibleTo(*resultType))
typeError(_functionCall, "Explicit type conversion not allowed."); typeError(_functionCall.location(), "Explicit type conversion not allowed.");
} }
_functionCall.annotation().type = resultType; _functionCall.annotation().type = resultType;
@ -932,7 +932,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
if (!functionType) if (!functionType)
{ {
typeError(_functionCall, "Type is not callable"); typeError(_functionCall.location(), "Type is not callable");
_functionCall.annotation().type = make_shared<TupleType>(); _functionCall.annotation().type = make_shared<TupleType>();
return false; return false;
} }
@ -957,7 +957,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
for (auto const& member: membersRemovedForStructConstructor) for (auto const& member: membersRemovedForStructConstructor)
msg += " " + member; msg += " " + member;
} }
typeError(_functionCall, msg); typeError(_functionCall.location(), msg);
} }
else if (isPositionalCall) else if (isPositionalCall)
{ {
@ -969,11 +969,11 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
{ {
if (auto t = dynamic_cast<IntegerConstantType const*>(argType.get())) if (auto t = dynamic_cast<IntegerConstantType const*>(argType.get()))
if (!t->integerType()) if (!t->integerType())
typeError(*arguments[i], "Integer constant too large."); typeError(arguments[i]->location(), "Integer constant too large.");
} }
else if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[i])) else if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[i]))
typeError( typeError(
*arguments[i], arguments[i]->location(),
"Invalid type for argument in function call. " "Invalid type for argument in function call. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
type(*arguments[i])->toString() + type(*arguments[i])->toString() +
@ -989,13 +989,13 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
auto const& parameterNames = functionType->parameterNames(); auto const& parameterNames = functionType->parameterNames();
if (functionType->takesArbitraryParameters()) if (functionType->takesArbitraryParameters())
typeError( typeError(
_functionCall, _functionCall.location(),
"Named arguments cannnot be used for functions that take arbitrary parameters." "Named arguments cannnot be used for functions that take arbitrary parameters."
); );
else if (parameterNames.size() > argumentNames.size()) else if (parameterNames.size() > argumentNames.size())
typeError(_functionCall, "Some argument names are missing."); typeError(_functionCall.location(), "Some argument names are missing.");
else if (parameterNames.size() < argumentNames.size()) else if (parameterNames.size() < argumentNames.size())
typeError(_functionCall, "Too many arguments."); typeError(_functionCall.location(), "Too many arguments.");
else else
{ {
// check duplicate names // check duplicate names
@ -1005,7 +1005,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
if (*argumentNames[i] == *argumentNames[j]) if (*argumentNames[i] == *argumentNames[j])
{ {
duplication = true; duplication = true;
typeError(*arguments[i], "Duplicate named argument."); typeError(arguments[i]->location(), "Duplicate named argument.");
} }
// check actual types // check actual types
@ -1020,7 +1020,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
// check type convertible // check type convertible
if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[j])) if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[j]))
typeError( typeError(
*arguments[i], arguments[i]->location(),
"Invalid type for argument in function call. " "Invalid type for argument in function call. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
type(*arguments[i])->toString() + type(*arguments[i])->toString() +
@ -1033,7 +1033,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
if (!found) if (!found)
typeError( typeError(
_functionCall, _functionCall.location(),
"Named argument does not match function declaration." "Named argument does not match function declaration."
); );
} }
@ -1048,9 +1048,9 @@ void TypeChecker::endVisit(NewExpression const& _newExpression)
auto contract = dynamic_cast<ContractDefinition const*>(&dereference(_newExpression.contractName())); auto contract = dynamic_cast<ContractDefinition const*>(&dereference(_newExpression.contractName()));
if (!contract) if (!contract)
fatalTypeError(_newExpression, "Identifier is not a contract."); fatalTypeError(_newExpression.location(), "Identifier is not a contract.");
if (!contract->annotation().isFullyImplemented) if (!contract->annotation().isFullyImplemented)
typeError(_newExpression, "Trying to create an instance of an abstract contract."); typeError(_newExpression.location(), "Trying to create an instance of an abstract contract.");
auto scopeContract = _newExpression.contractName().annotation().contractScope; auto scopeContract = _newExpression.contractName().annotation().contractScope;
scopeContract->annotation().contractDependencies.insert(contract); scopeContract->annotation().contractDependencies.insert(contract);
@ -1060,7 +1060,7 @@ void TypeChecker::endVisit(NewExpression const& _newExpression)
); );
if (contractDependenciesAreCyclic(*scopeContract)) if (contractDependenciesAreCyclic(*scopeContract))
typeError( typeError(
_newExpression, _newExpression.location(),
"Circular reference for contract creation (cannot create instance of derived or same contract)." "Circular reference for contract creation (cannot create instance of derived or same contract)."
); );
@ -1104,20 +1104,20 @@ bool TypeChecker::visit(MemberAccess const& _memberAccess)
); );
if (!storageType->members().membersByName(memberName).empty()) if (!storageType->members().membersByName(memberName).empty())
fatalTypeError( fatalTypeError(
_memberAccess, _memberAccess.location(),
"Member \"" + memberName + "\" is not available in " + "Member \"" + memberName + "\" is not available in " +
exprType->toString() + exprType->toString() +
" outside of storage." " outside of storage."
); );
fatalTypeError( fatalTypeError(
_memberAccess, _memberAccess.location(),
"Member \"" + memberName + "\" not found or not visible " "Member \"" + memberName + "\" not found or not visible "
"after argument-dependent lookup in " + exprType->toString() "after argument-dependent lookup in " + exprType->toString()
); );
} }
else if (possibleMembers.size() > 1) else if (possibleMembers.size() > 1)
fatalTypeError( fatalTypeError(
_memberAccess, _memberAccess.location(),
"Member \"" + memberName + "\" not unique " "Member \"" + memberName + "\" not unique "
"after argument-dependent lookup in " + exprType->toString() "after argument-dependent lookup in " + exprType->toString()
); );
@ -1153,10 +1153,10 @@ bool TypeChecker::visit(IndexAccess const& _access)
{ {
ArrayType const& actualType = dynamic_cast<ArrayType const&>(*baseType); ArrayType const& actualType = dynamic_cast<ArrayType const&>(*baseType);
if (!index) if (!index)
typeError(_access, "Index expression cannot be omitted."); typeError(_access.location(), "Index expression cannot be omitted.");
else if (actualType.isString()) else if (actualType.isString())
{ {
typeError(_access, "Index access for string is not possible."); typeError(_access.location(), "Index access for string is not possible.");
index->accept(*this); index->accept(*this);
} }
else else
@ -1164,7 +1164,7 @@ bool TypeChecker::visit(IndexAccess const& _access)
expectType(*index, IntegerType(256)); expectType(*index, IntegerType(256));
if (auto integerType = dynamic_cast<IntegerConstantType const*>(type(*index).get())) if (auto integerType = dynamic_cast<IntegerConstantType const*>(type(*index).get()))
if (!actualType.isDynamicallySized() && actualType.length() <= integerType->literalValue(nullptr)) if (!actualType.isDynamicallySized() && actualType.length() <= integerType->literalValue(nullptr))
typeError(_access, "Out of bounds array access."); typeError(_access.location(), "Out of bounds array access.");
} }
resultType = actualType.baseType(); resultType = actualType.baseType();
isLValue = actualType.location() != DataLocation::CallData; isLValue = actualType.location() != DataLocation::CallData;
@ -1174,7 +1174,7 @@ bool TypeChecker::visit(IndexAccess const& _access)
{ {
MappingType const& actualType = dynamic_cast<MappingType const&>(*baseType); MappingType const& actualType = dynamic_cast<MappingType const&>(*baseType);
if (!index) if (!index)
typeError(_access, "Index expression cannot be omitted."); typeError(_access.location(), "Index expression cannot be omitted.");
else else
expectType(*index, *actualType.keyType()); expectType(*index, *actualType.keyType());
resultType = actualType.valueType(); resultType = actualType.valueType();
@ -1196,13 +1196,13 @@ bool TypeChecker::visit(IndexAccess const& _access)
length->literalValue(nullptr) length->literalValue(nullptr)
)); ));
else else
typeError(*index, "Integer constant expected."); typeError(index->location(), "Integer constant expected.");
} }
break; break;
} }
default: default:
fatalTypeError( fatalTypeError(
_access.baseExpression(), _access.baseExpression().location(),
"Indexed expression has to be a type, mapping or array (is " + baseType->toString() + ")" "Indexed expression has to be a type, mapping or array (is " + baseType->toString() + ")"
); );
} }
@ -1218,9 +1218,9 @@ bool TypeChecker::visit(Identifier const& _identifier)
if (!annotation.referencedDeclaration) if (!annotation.referencedDeclaration)
{ {
if (!annotation.argumentTypes) if (!annotation.argumentTypes)
fatalTypeError(_identifier, "Unable to determine overloaded type."); fatalTypeError(_identifier.location(), "Unable to determine overloaded type.");
if (annotation.overloadedDeclarations.empty()) if (annotation.overloadedDeclarations.empty())
fatalTypeError(_identifier, "No candidates for overload resolution found."); fatalTypeError(_identifier.location(), "No candidates for overload resolution found.");
else if (annotation.overloadedDeclarations.size() == 1) else if (annotation.overloadedDeclarations.size() == 1)
annotation.referencedDeclaration = *annotation.overloadedDeclarations.begin(); annotation.referencedDeclaration = *annotation.overloadedDeclarations.begin();
else else
@ -1236,11 +1236,11 @@ bool TypeChecker::visit(Identifier const& _identifier)
candidates.push_back(declaration); candidates.push_back(declaration);
} }
if (candidates.empty()) if (candidates.empty())
fatalTypeError(_identifier, "No matching declaration found after argument-dependent lookup."); fatalTypeError(_identifier.location(), "No matching declaration found after argument-dependent lookup.");
else if (candidates.size() == 1) else if (candidates.size() == 1)
annotation.referencedDeclaration = candidates.front(); annotation.referencedDeclaration = candidates.front();
else else
fatalTypeError(_identifier, "No unique declaration found after argument-dependent lookup."); fatalTypeError(_identifier.location(), "No unique declaration found after argument-dependent lookup.");
} }
} }
solAssert( solAssert(
@ -1250,7 +1250,7 @@ bool TypeChecker::visit(Identifier const& _identifier)
annotation.isLValue = annotation.referencedDeclaration->isLValue(); annotation.isLValue = annotation.referencedDeclaration->isLValue();
annotation.type = annotation.referencedDeclaration->type(_identifier.annotation().contractScope); annotation.type = annotation.referencedDeclaration->type(_identifier.annotation().contractScope);
if (!annotation.type) if (!annotation.type)
fatalTypeError(_identifier, "Declaration referenced before type could be determined."); fatalTypeError(_identifier.location(), "Declaration referenced before type could be determined.");
return false; return false;
} }
@ -1263,7 +1263,7 @@ void TypeChecker::endVisit(Literal const& _literal)
{ {
_literal.annotation().type = Type::forLiteral(_literal); _literal.annotation().type = Type::forLiteral(_literal);
if (!_literal.annotation().type) if (!_literal.annotation().type)
fatalTypeError(_literal, "Invalid literal value."); fatalTypeError(_literal.location(), "Invalid literal value.");
} }
bool TypeChecker::contractDependenciesAreCyclic( bool TypeChecker::contractDependenciesAreCyclic(
@ -1294,7 +1294,7 @@ void TypeChecker::expectType(Expression const& _expression, Type const& _expecte
if (!type(_expression)->isImplicitlyConvertibleTo(_expectedType)) if (!type(_expression)->isImplicitlyConvertibleTo(_expectedType))
typeError( typeError(
_expression, _expression.location(),
"Type " + "Type " +
type(_expression)->toString() + type(_expression)->toString() +
" is not implicitly convertible to expected type " + " is not implicitly convertible to expected type " +
@ -1308,21 +1308,21 @@ void TypeChecker::requireLValue(Expression const& _expression)
_expression.annotation().lValueRequested = true; _expression.annotation().lValueRequested = true;
_expression.accept(*this); _expression.accept(*this);
if (!_expression.annotation().isLValue) if (!_expression.annotation().isLValue)
typeError(_expression, "Expression has to be an lvalue."); typeError(_expression.location(), "Expression has to be an lvalue.");
} }
void TypeChecker::typeError(ASTNode const& _node, string const& _description) void TypeChecker::typeError(SourceLocation const& _location, string const& _description)
{ {
auto err = make_shared<Error>(Error::Type::TypeError); auto err = make_shared<Error>(Error::Type::TypeError);
*err << *err <<
errinfo_sourceLocation(_node.location()) << errinfo_sourceLocation(_location) <<
errinfo_comment(_description); errinfo_comment(_description);
m_errors.push_back(err); m_errors.push_back(err);
} }
void TypeChecker::fatalTypeError(ASTNode const& _node, string const& _description) void TypeChecker::fatalTypeError(SourceLocation const& _location, string const& _description)
{ {
typeError(_node, _description); typeError(_location, _description);
BOOST_THROW_EXCEPTION(FatalError()); BOOST_THROW_EXCEPTION(FatalError());
} }

View File

@ -57,10 +57,10 @@ public:
private: private:
/// Adds a new error to the list of errors. /// Adds a new error to the list of errors.
void typeError(ASTNode const& _node, std::string const& _description); void typeError(SourceLocation const& _location, std::string const& _description);
/// Adds a new error to the list of errors and throws to abort type checking. /// Adds a new error to the list of errors and throws to abort type checking.
void fatalTypeError(ASTNode const& _node, std::string const& _description); void fatalTypeError(SourceLocation const& _location, std::string const& _description);
virtual bool visit(ContractDefinition const& _contract) override; virtual bool visit(ContractDefinition const& _contract) override;
/// Checks that two functions defined in this contract with the same name have different /// Checks that two functions defined in this contract with the same name have different

View File

@ -818,6 +818,8 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
std::vector<ASTPointer<Statement>> const& statements() const { return m_statements; }
private: private:
std::vector<ASTPointer<Statement>> m_statements; std::vector<ASTPointer<Statement>> m_statements;
}; };

View File

@ -747,6 +747,8 @@ public:
SetGas, ///< modify the default gas value for the function call SetGas, ///< modify the default gas value for the function call
SetValue, ///< modify the default value transfer for the function call SetValue, ///< modify the default value transfer for the function call
BlockHash, ///< BLOCKHASH BlockHash, ///< BLOCKHASH
AddMod, ///< ADDMOD
MulMod, ///< MULMOD
ArrayPush, ///< .push() to a dynamically sized array in storage ArrayPush, ///< .push() to a dynamically sized array in storage
ByteArrayPush ///< .push() to a dynamically sized byte array in storage ByteArrayPush ///< .push() to a dynamically sized byte array in storage
}; };

View File

@ -588,6 +588,19 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
{ {
++numIndexed; ++numIndexed;
arguments[arg - 1]->accept(*this); arguments[arg - 1]->accept(*this);
if (auto const& arrayType = dynamic_pointer_cast<ArrayType const>(function.parameterTypes()[arg - 1]))
{
utils().fetchFreeMemoryPointer();
utils().encodeToMemory(
{arguments[arg - 1]->annotation().type},
{arrayType},
false,
true
);
utils().toSizeAfterFreeMemoryPointer();
m_context << eth::Instruction::SHA3;
}
else
utils().convertType( utils().convertType(
*arguments[arg - 1]->annotation().type, *arguments[arg - 1]->annotation().type,
*function.parameterTypes()[arg - 1], *function.parameterTypes()[arg - 1],
@ -625,6 +638,20 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
m_context << eth::Instruction::BLOCKHASH; m_context << eth::Instruction::BLOCKHASH;
break; break;
} }
case Location::AddMod:
case Location::MulMod:
{
for (unsigned i = 0; i < 3; i ++)
{
arguments[2 - i]->accept(*this);
utils().convertType(*arguments[2 - i]->annotation().type, IntegerType(256));
}
if (function.location() == Location::AddMod)
m_context << eth::Instruction::ADDMOD;
else
m_context << eth::Instruction::MULMOD;
break;
}
case Location::ECRecover: case Location::ECRecover:
case Location::SHA256: case Location::SHA256:
case Location::RIPEMD160: case Location::RIPEMD160:

View File

@ -103,11 +103,21 @@ void MemoryItem::storeValue(Type const& _sourceType, SourceLocation const&, bool
if (!_move) if (!_move)
{ {
utils.moveToStackTop(m_dataType->sizeOnStack()); utils.moveToStackTop(m_dataType->sizeOnStack());
utils.copyToStackTop(2, m_dataType->sizeOnStack()); utils.copyToStackTop(1 + m_dataType->sizeOnStack(), m_dataType->sizeOnStack());
} }
if (!m_padded)
{
solAssert(m_dataType->calldataEncodedSize(false) == 1, "Invalid non-padded type.");
if (m_dataType->category() == Type::Category::FixedBytes)
m_context << u256(0) << eth::Instruction::BYTE;
m_context << eth::Instruction::SWAP1 << eth::Instruction::MSTORE8;
}
else
{
utils.storeInMemoryDynamic(*m_dataType, m_padded); utils.storeInMemoryDynamic(*m_dataType, m_padded);
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
} }
}
else else
{ {
solAssert(_sourceType == *m_dataType, "Conversion not implemented for assignment to memory."); solAssert(_sourceType == *m_dataType, "Conversion not implemented for assignment to memory.");

View File

@ -35,7 +35,6 @@ bool Why3Translator::process(SourceUnit const& _source)
fatalError(_source, "Multiple source units not yet supported"); fatalError(_source, "Multiple source units not yet supported");
appendPreface(); appendPreface();
_source.accept(*this); _source.accept(*this);
addLine("end");
} }
catch (FatalError& _e) catch (FatalError& _e)
{ {
@ -71,18 +70,6 @@ module UInt256
type t = uint256, type t = uint256,
constant max = max_uint256 constant max = max_uint256
end end
module Solidity
use import int.Int
use import ref.Ref
use import map.Map
use import array.Array
use import int.ComputerDivision
use import mach.int.Unsigned
use import UInt256
exception Ret
type state = StateUnused
)"; )";
} }
@ -113,6 +100,8 @@ void Why3Translator::addLine(string const& _line)
void Why3Translator::add(string const& _str) void Why3Translator::add(string const& _str)
{ {
if (m_currentLine.empty())
m_indentationAtLineStart = m_indentation;
m_currentLine += _str; m_currentLine += _str;
} }
@ -120,7 +109,7 @@ void Why3Translator::newLine()
{ {
if (!m_currentLine.empty()) if (!m_currentLine.empty())
{ {
for (size_t i = 0; i < m_indentation; ++i) for (size_t i = 0; i < m_indentationAtLineStart; ++i)
m_result.push_back('\t'); m_result.push_back('\t');
m_result += m_currentLine; m_result += m_currentLine;
m_result.push_back('\n'); m_result.push_back('\n');
@ -130,6 +119,7 @@ void Why3Translator::newLine()
void Why3Translator::unindent() void Why3Translator::unindent()
{ {
newLine();
solAssert(m_indentation > 0, ""); solAssert(m_indentation > 0, "");
m_indentation--; m_indentation--;
} }
@ -142,9 +132,52 @@ bool Why3Translator::visit(ContractDefinition const& _contract)
if (_contract.isLibrary()) if (_contract.isLibrary())
error(_contract, "Libraries not supported."); error(_contract, "Libraries not supported.");
addSourceFromDocStrings(_contract.annotation()); addLine("module Contract_" + _contract.name());
indent();
addLine("use import int.Int");
addLine("use import ref.Ref");
addLine("use import map.Map");
addLine("use import array.Array");
addLine("use import int.ComputerDivision");
addLine("use import mach.int.Unsigned");
addLine("use import UInt256");
addLine("exception Ret");
return true; addLine("type state = {");
indent();
m_stateVariables = &_contract.stateVariables();
for (auto const& variable: _contract.stateVariables())
{
string varType = toFormalType(*variable->annotation().type);
if (varType.empty())
fatalError(*variable, "Type not supported.");
addLine("mutable _" + variable->name() + ": ref " + varType);
}
unindent();
addLine("}");
if (!_contract.baseContracts().empty())
error(*_contract.baseContracts().front(), "Inheritance not supported.");
if (!_contract.definedStructs().empty())
error(*_contract.definedStructs().front(), "User-defined types not supported.");
if (!_contract.definedEnums().empty())
error(*_contract.definedEnums().front(), "User-defined types not supported.");
if (!_contract.events().empty())
error(*_contract.events().front(), "Events not supported.");
if (!_contract.functionModifiers().empty())
error(*_contract.functionModifiers().front(), "Modifiers not supported.");
ASTNode::listAccept(_contract.definedFunctions(), *this);
return false;
}
void Why3Translator::endVisit(ContractDefinition const& _contract)
{
m_stateVariables = nullptr;
addSourceFromDocStrings(_contract.annotation());
unindent();
addLine("end");
} }
bool Why3Translator::visit(FunctionDefinition const& _function) bool Why3Translator::visit(FunctionDefinition const& _function)
@ -177,7 +210,6 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
add(" (arg_" + param->name() + ": " + paramType + ")"); add(" (arg_" + param->name() + ": " + paramType + ")");
} }
add(":"); add(":");
newLine();
indent(); indent();
indent(); indent();
@ -191,7 +223,7 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
retString += ", "; retString += ", ";
retString += paramType; retString += paramType;
} }
addLine(retString + ")"); add(retString + ")");
unindent(); unindent();
addSourceFromDocStrings(_function.annotation()); addSourceFromDocStrings(_function.annotation());
@ -218,6 +250,7 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
addLine("try"); addLine("try");
_function.body().accept(*this); _function.body().accept(*this);
add(";");
addLine("raise Ret"); addLine("raise Ret");
string retVals; string retVals;
@ -238,9 +271,18 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
bool Why3Translator::visit(Block const& _node) bool Why3Translator::visit(Block const& _node)
{ {
addSourceFromDocStrings(_node.annotation()); addSourceFromDocStrings(_node.annotation());
addLine("begin"); add("begin");
indent(); indent();
return true; for (size_t i = 0; i < _node.statements().size(); ++i)
{
_node.statements()[i]->accept(*this);
if (!m_currentLine.empty() && i != _node.statements().size() - 1)
add(";");
newLine();
}
unindent();
add("end");
return false;
} }
bool Why3Translator::visit(IfStatement const& _node) bool Why3Translator::visit(IfStatement const& _node)
@ -250,12 +292,12 @@ bool Why3Translator::visit(IfStatement const& _node)
add("if "); add("if ");
_node.condition().accept(*this); _node.condition().accept(*this);
add(" then"); add(" then");
newLine(); visitIndentedUnlessBlock(_node.trueStatement());
_node.trueStatement().accept(*this);
if (_node.falseStatement()) if (_node.falseStatement())
{ {
addLine("else"); newLine();
_node.falseStatement()->accept(*this); add("else");
visitIndentedUnlessBlock(*_node.falseStatement());
} }
return false; return false;
} }
@ -266,10 +308,10 @@ bool Why3Translator::visit(WhileStatement const& _node)
add("while "); add("while ");
_node.condition().accept(*this); _node.condition().accept(*this);
add(" do");
newLine(); newLine();
_node.body().accept(*this); add("do");
addLine("done;"); visitIndentedUnlessBlock(_node.body());
add("done");
return false; return false;
} }
@ -286,14 +328,12 @@ bool Why3Translator::visit(Return const& _node)
error(_node, "Directly returning tuples not supported. Rather assign to return variable."); error(_node, "Directly returning tuples not supported. Rather assign to return variable.");
return false; return false;
} }
newLine();
add("begin _" + params.front()->name() + " := "); add("begin _" + params.front()->name() + " := ");
_node.expression()->accept(*this); _node.expression()->accept(*this);
add("; raise Ret end"); add("; raise Ret end");
newLine();
} }
else else
addLine("raise Ret;"); add("raise Ret");
return false; return false;
} }
@ -310,8 +350,6 @@ bool Why3Translator::visit(VariableDeclarationStatement const& _node)
{ {
add("_" + _node.declarations().front()->name() + " := "); add("_" + _node.declarations().front()->name() + " := ");
_node.initialValue()->accept(*this); _node.initialValue()->accept(*this);
add(";");
newLine();
} }
return false; return false;
} }
@ -429,7 +467,7 @@ bool Why3Translator::visit(FunctionCall const& _node)
add("("); add("(");
_node.expression().accept(*this); _node.expression().accept(*this);
add(" StateUnused"); add(" state");
for (auto const& arg: _node.arguments()) for (auto const& arg: _node.arguments())
{ {
add(" "); add(" ");
@ -487,10 +525,15 @@ bool Why3Translator::visit(Identifier const& _identifier)
add("_" + functionDef->name()); add("_" + functionDef->name());
else if (auto variable = dynamic_cast<VariableDeclaration const*>(declaration)) else if (auto variable = dynamic_cast<VariableDeclaration const*>(declaration))
{ {
if (_identifier.annotation().lValueRequested) bool isStateVar = isStateVariable(variable);
bool lvalue = _identifier.annotation().lValueRequested;
if (!lvalue)
add("!(");
if (isStateVar)
add("state.");
add("_" + variable->name()); add("_" + variable->name());
else if (!lvalue)
add("!_" + variable->name()); add(")");
} }
else else
error(_identifier, "Not supported."); error(_identifier, "Not supported.");
@ -517,7 +560,30 @@ bool Why3Translator::visit(Literal const& _literal)
return false; return false;
} }
void Why3Translator::addSourceFromDocStrings(const DocumentedAnnotation& _annotation) bool Why3Translator::isStateVariable(VariableDeclaration const* _var) const
{
solAssert(!!m_stateVariables, "");
for (auto const& var: *m_stateVariables)
if (var.get() == _var)
return true;
return false;
}
void Why3Translator::visitIndentedUnlessBlock(Statement const& _statement)
{
bool isBlock = !!dynamic_cast<Block const*>(&_statement);
if (isBlock)
newLine();
else
indent();
_statement.accept(*this);
if (isBlock)
newLine();
else
unindent();
}
void Why3Translator::addSourceFromDocStrings(DocumentedAnnotation const& _annotation)
{ {
auto why3Range = _annotation.docTags.equal_range("why3"); auto why3Range = _annotation.docTags.equal_range("why3");
for (auto i = why3Range.first; i != why3Range.second; ++i) for (auto i = why3Range.first; i != why3Range.second; ++i)

View File

@ -64,7 +64,7 @@ private:
/// if the type is not supported. /// if the type is not supported.
std::string toFormalType(Type const& _type) const; std::string toFormalType(Type const& _type) const;
void indent() { m_indentation++; } void indent() { newLine(); m_indentation++; }
void unindent(); void unindent();
void addLine(std::string const& _line); void addLine(std::string const& _line);
void add(std::string const& _str); void add(std::string const& _str);
@ -72,15 +72,14 @@ private:
virtual bool visit(SourceUnit const&) override { return true; } virtual bool visit(SourceUnit const&) override { return true; }
virtual bool visit(ContractDefinition const& _contract) override; virtual bool visit(ContractDefinition const& _contract) override;
virtual void endVisit(ContractDefinition const& _contract) override;
virtual bool visit(FunctionDefinition const& _function) override; virtual bool visit(FunctionDefinition const& _function) override;
virtual bool visit(Block const&) override; virtual bool visit(Block const&) override;
virtual void endVisit(Block const&) override { unindent(); addLine("end;"); }
virtual bool visit(IfStatement const& _node) override; virtual bool visit(IfStatement const& _node) override;
virtual bool visit(WhileStatement const& _node) override; virtual bool visit(WhileStatement const& _node) override;
virtual bool visit(Return const& _node) override; virtual bool visit(Return const& _node) override;
virtual bool visit(VariableDeclarationStatement const& _node) override; virtual bool visit(VariableDeclarationStatement const& _node) override;
virtual bool visit(ExpressionStatement const&) override; virtual bool visit(ExpressionStatement const&) override;
virtual void endVisit(ExpressionStatement const&) override { add(";"); newLine(); }
virtual bool visit(Assignment const& _node) override; virtual bool visit(Assignment const& _node) override;
virtual bool visit(TupleExpression const& _node) override; virtual bool visit(TupleExpression const& _node) override;
virtual void endVisit(TupleExpression const&) override { add(")"); } virtual void endVisit(TupleExpression const&) override { add(")"); }
@ -98,14 +97,24 @@ private:
return false; return false;
} }
bool isStateVariable(VariableDeclaration const* _var) const;
/// Visits the givin statement and indents it unless it is a block
/// (which does its own indentation).
void visitIndentedUnlessBlock(Statement const& _statement);
void addSourceFromDocStrings(DocumentedAnnotation const& _annotation); void addSourceFromDocStrings(DocumentedAnnotation const& _annotation);
size_t m_indentationAtLineStart = 0;
size_t m_indentation = 0; size_t m_indentation = 0;
std::string m_currentLine; std::string m_currentLine;
/// True if we have already seen a contract. For now, only a single contract /// True if we have already seen a contract. For now, only a single contract
/// is supported. /// is supported.
bool m_seenContract = false; bool m_seenContract = false;
bool m_errorOccured = false; bool m_errorOccured = false;
std::vector<ASTPointer<VariableDeclaration>> const* m_stateVariables = nullptr;
std::string m_result; std::string m_result;
ErrorList& m_errors; ErrorList& m_errors;
}; };

View File

@ -2484,6 +2484,41 @@ BOOST_AUTO_TEST_CASE(event_really_lots_of_data_from_storage)
BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(uint256,bytes,uint256)"))); BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("Deposit(uint256,bytes,uint256)")));
} }
BOOST_AUTO_TEST_CASE(event_indexed_string)
{
char const* sourceCode = R"(
contract C {
string x;
uint[4] y;
event E(string indexed r, uint[4] indexed t);
function deposit() {
bytes(x).length = 90;
for (uint i = 0; i < 90; i++)
bytes(x)[i] = byte(i);
y[0] = 4;
y[1] = 5;
y[2] = 6;
y[3] = 7;
E(x, y);
}
}
)";
compileAndRun(sourceCode);
callContractFunction("deposit()");
BOOST_REQUIRE_EQUAL(m_logs.size(), 1);
BOOST_CHECK_EQUAL(m_logs[0].address, m_contractAddress);
string dynx(90, 0);
for (size_t i = 0; i < dynx.size(); ++i)
dynx[i] = i;
BOOST_CHECK(m_logs[0].data == bytes());
BOOST_REQUIRE_EQUAL(m_logs[0].topics.size(), 3);
BOOST_CHECK_EQUAL(m_logs[0].topics[1], dev::sha3(dynx));
BOOST_CHECK_EQUAL(m_logs[0].topics[2], dev::sha3(
encodeArgs(u256(4), u256(5), u256(6), u256(7))
));
BOOST_CHECK_EQUAL(m_logs[0].topics[0], dev::sha3(string("E(string,uint256[4])")));
}
BOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one) BOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one)
{ {
char const* sourceCode = R"( char const* sourceCode = R"(
@ -5781,6 +5816,39 @@ BOOST_AUTO_TEST_CASE(lone_struct_array_type)
BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(3))); BOOST_CHECK(callContractFunction("f()") == encodeArgs(u256(3)));
} }
BOOST_AUTO_TEST_CASE(memory_overwrite)
{
char const* sourceCode = R"(
contract C {
function f() returns (bytes x) {
x = "12345";
x[3] = 0x61;
x[0] = 0x62;
}
}
)";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("f()") == encodeDyn(string("b23a5")));
}
BOOST_AUTO_TEST_CASE(addmod_mulmod)
{
char const* sourceCode = R"(
contract C {
function test() returns (uint) {
// Note that this only works because computation on literals is done using
// unbounded integers.
if ((2**255 + 2**255) % 7 != addmod(2**255, 2**255, 7))
return 1;
if ((2**255 + 2**255) % 7 != addmod(2**255, 2**255, 7))
return 2;
return 0;
}
}
)";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("test()") == encodeArgs(u256(0)));
}
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
} }

View File

@ -62,14 +62,17 @@ parseAnalyseAndReturnError(string const& _source, bool _reportWarnings = false)
solAssert(Error::containsOnlyWarnings(errors), ""); solAssert(Error::containsOnlyWarnings(errors), "");
resolver.registerDeclarations(*sourceUnit); resolver.registerDeclarations(*sourceUnit);
bool success = true;
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
globalContext->setCurrentContract(*contract); globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*globalContext->currentThis()); resolver.updateDeclaration(*globalContext->currentThis());
resolver.updateDeclaration(*globalContext->currentSuper()); resolver.updateDeclaration(*globalContext->currentSuper());
resolver.resolveNamesAndTypes(*contract); if (!resolver.resolveNamesAndTypes(*contract))
success = false;
} }
if (success)
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
@ -80,6 +83,7 @@ parseAnalyseAndReturnError(string const& _source, bool _reportWarnings = false)
bool success = typeChecker.checkTypeRequirements(*contract); bool success = typeChecker.checkTypeRequirements(*contract);
BOOST_CHECK(success || !errors.empty()); BOOST_CHECK(success || !errors.empty());
}
for (auto const& currentError: errors) for (auto const& currentError: errors)
{ {
if ( if (
@ -89,7 +93,6 @@ parseAnalyseAndReturnError(string const& _source, bool _reportWarnings = false)
return make_pair(sourceUnit, std::make_shared<Error::Type const>(currentError->type())); return make_pair(sourceUnit, std::make_shared<Error::Type const>(currentError->type()));
} }
} }
}
catch (Error const& _e) catch (Error const& _e)
{ {
return make_pair(sourceUnit, std::make_shared<Error::Type const>(_e.type())); return make_pair(sourceUnit, std::make_shared<Error::Type const>(_e.type()));
@ -133,7 +136,7 @@ static ContractDefinition const* retrieveContract(ASTPointer<SourceUnit> _source
return nullptr; return nullptr;
} }
static FunctionTypePointer const& retrieveFunctionBySignature( static FunctionTypePointer retrieveFunctionBySignature(
ContractDefinition const* _contract, ContractDefinition const* _contract,
std::string const& _signature std::string const& _signature
) )

View File

@ -359,6 +359,16 @@ BOOST_AUTO_TEST_CASE(store_tags_as_unions)
// BOOST_CHECK_EQUAL(2, numSHA3s); // BOOST_CHECK_EQUAL(2, numSHA3s);
} }
BOOST_AUTO_TEST_CASE(successor_not_found_bug)
{
// This bug was caused because MSVC chose to use the u256->bool conversion
// instead of u256->unsigned
char const* sourceCode = R"(
contract greeter { function greeter() {} }
)";
compileBothVersions(sourceCode);
}
BOOST_AUTO_TEST_CASE(cse_intermediate_swap) BOOST_AUTO_TEST_CASE(cse_intermediate_swap)
{ {
eth::KnownState state; eth::KnownState state;
@ -1113,7 +1123,11 @@ BOOST_AUTO_TEST_CASE(computing_constants)
bytes complicatedConstant = toBigEndian(u256("0x817416927846239487123469187231298734162934871263941234127518276")); bytes complicatedConstant = toBigEndian(u256("0x817416927846239487123469187231298734162934871263941234127518276"));
unsigned occurrences = 0; unsigned occurrences = 0;
for (auto iter = optimizedBytecode.cbegin(); iter < optimizedBytecode.cend(); ++occurrences) for (auto iter = optimizedBytecode.cbegin(); iter < optimizedBytecode.cend(); ++occurrences)
iter = search(iter, optimizedBytecode.cend(), complicatedConstant.cbegin(), complicatedConstant.cend()) + 1; {
iter = search(iter, optimizedBytecode.cend(), complicatedConstant.cbegin(), complicatedConstant.cend());
if (iter < optimizedBytecode.cend())
++iter;
}
BOOST_CHECK_EQUAL(2, occurrences); BOOST_CHECK_EQUAL(2, occurrences);
bytes constantWithZeros = toBigEndian(u256("0x77abc0000000000000000000000000000000000000000000000000000000001")); bytes constantWithZeros = toBigEndian(u256("0x77abc0000000000000000000000000000000000000000000000000000000001"));