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()
# 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})
# 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>("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<FunctionType>(strings(), strings{"bytes32"}, FunctionType::Location::SHA3, true)),
make_shared<MagicVariableDeclaration>("log0",

View File

@ -64,65 +64,87 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
{
m_currentScope = &m_scopes[nullptr];
ReferencesResolver resolver(m_errors, *this, &_contract, nullptr);
bool success = true;
for (ASTPointer<InheritanceSpecifier> const& baseContract: _contract.baseContracts())
ReferencesResolver resolver(*baseContract, *this, &_contract, nullptr);
if (!resolver.resolve(*baseContract))
success = false;
m_currentScope = &m_scopes[&_contract];
linearizeBaseContracts(_contract);
std::vector<ContractDefinition const*> properBases(
++_contract.annotation().linearizedBaseContracts.begin(),
_contract.annotation().linearizedBaseContracts.end()
);
if (success)
{
linearizeBaseContracts(_contract);
std::vector<ContractDefinition const*> properBases(
++_contract.annotation().linearizedBaseContracts.begin(),
_contract.annotation().linearizedBaseContracts.end()
);
for (ContractDefinition const* base: properBases)
importInheritedScope(*base);
for (ContractDefinition const* base: properBases)
importInheritedScope(*base);
}
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())
ReferencesResolver resolver(*enumDef, *this, &_contract, nullptr);
if (!resolver.resolve(*enumDef))
success = false;
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())
ReferencesResolver resolver(*event, *this, &_contract, nullptr);
if (!resolver.resolve(*event))
success = false;
// these can contain code, only resolve parameters for now
for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers())
{
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())
{
m_currentScope = &m_scopes[function.get()];
ReferencesResolver referencesResolver(
*function,
if (!ReferencesResolver(
m_errors,
*this,
&_contract,
function->returnParameterList().get()
);
).resolve(*function))
success = false;
}
if (!success)
return false;
m_currentScope = &m_scopes[&_contract];
// now resolve references inside the code
for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers())
{
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())
{
m_currentScope = &m_scopes[function.get()];
ReferencesResolver referencesResolver(
*function,
if (!ReferencesResolver(
m_errors,
*this,
&_contract,
function->returnParameterList().get(),
true
);
).resolve(*function))
success = false;
}
if (!success)
return false;
}
catch (FatalError const& _e)
{

View File

@ -31,21 +31,6 @@ using namespace dev;
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)
{
_return.annotation().functionReturnParameters = m_returnParameters;
@ -56,24 +41,30 @@ bool ReferencesResolver::visit(UserDefinedTypeName const& _typeName)
{
Declaration const* declaration = m_resolver.pathFromCurrentScope(_typeName.namePath());
if (!declaration)
BOOST_THROW_EXCEPTION(
Error(Error::Type::DeclarationError) <<
errinfo_sourceLocation(_typeName.location()) <<
errinfo_comment("Identifier not found or not unique.")
);
fatalDeclarationError(_typeName.location(), "Identifier not found or not unique.");
_typeName.annotation().referencedDeclaration = declaration;
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)
{
auto declarations = m_resolver.nameFromCurrentScope(_identifier.name());
if (declarations.empty())
BOOST_THROW_EXCEPTION(
Error(Error::Type::DeclarationError) <<
errinfo_sourceLocation(_identifier.location()) <<
errinfo_comment("Undeclared identifier.")
);
fatalDeclarationError(_identifier.location(), "Undeclared identifier.");
else if (declarations.size() == 1)
{
_identifier.annotation().referencedDeclaration = declarations.front();
@ -108,19 +99,19 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
if (contract.isLibrary())
{
if (loc == Location::Memory)
BOOST_THROW_EXCEPTION(_variable.createTypeError(
fatalTypeError(_variable.location(),
"Location has to be calldata or storage for external "
"library functions (remove the \"memory\" keyword)."
));
);
}
else
{
// force location of external function parameters (not return) to calldata
if (loc != Location::Default)
BOOST_THROW_EXCEPTION(_variable.createTypeError(
fatalTypeError(_variable.location(),
"Location has to be calldata for external functions "
"(remove the \"memory\" or \"storage\" keyword)."
));
);
}
if (loc == Location::Default)
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());
// force locations of public or external function (return) parameters to memory
if (loc == Location::Storage && !contract.isLibrary())
BOOST_THROW_EXCEPTION(_variable.createTypeError(
fatalTypeError(_variable.location(),
"Location has to be memory for publicly visible functions "
"(remove the \"storage\" keyword)."
));
);
if (loc == Location::Default || !contract.isLibrary())
type = ref->copyForLocation(DataLocation::Memory, true);
}
@ -142,9 +133,10 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
if (_variable.isConstant())
{
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."
));
);
loc = Location::Memory;
}
if (loc == Location::Default)
@ -159,16 +151,14 @@ void ReferencesResolver::endVisit(VariableDeclaration const& _variable)
}
}
else if (loc != Location::Default && !ref)
BOOST_THROW_EXCEPTION(_variable.createTypeError(
"Storage location can only be given for array or struct types."
));
fatalTypeError(_variable.location(), "Storage location can only be given for array or struct types.");
if (!type)
BOOST_THROW_EXCEPTION(_variable.typeName()->createTypeError("Invalid type name."));
fatalTypeError(_variable.location(), "Invalid type name.");
}
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
_variable.annotation().type = type;
@ -194,9 +184,7 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration))
type = make_shared<ContractType>(*contract);
else
BOOST_THROW_EXCEPTION(typeName->createTypeError(
"Name has to refer to a struct, enum or contract."
));
fatalTypeError(typeName->location(), "Name has to refer to a struct, enum or contract.");
}
else if (auto mapping = dynamic_cast<Mapping const*>(&_typeName))
{
@ -212,9 +200,7 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
{
TypePointer baseType = typeFor(arrayType->baseType());
if (baseType->storageBytes() == 0)
BOOST_THROW_EXCEPTION(arrayType->baseType().createTypeError(
"Illegal base type of storage size zero for array."
));
fatalTypeError(arrayType->baseType().location(), "Illegal base type of storage size zero for array.");
if (Expression const* length = arrayType->length())
{
if (!length->annotation().type)
@ -222,8 +208,9 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
auto const* lengthType = dynamic_cast<IntegerConstantType const*>(length->annotation().type.get());
if (!lengthType)
BOOST_THROW_EXCEPTION(length->createTypeError("Invalid array length."));
type = make_shared<ArrayType>(DataLocation::Storage, baseType, lengthType->literalValue(nullptr));
fatalTypeError(length->location(), "Invalid array length.");
else
type = make_shared<ArrayType>(DataLocation::Storage, baseType, lengthType->literalValue(nullptr));
}
else
type = make_shared<ArrayType>(DataLocation::Storage, baseType);
@ -232,3 +219,31 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
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:
ReferencesResolver(
ASTNode& _root,
ErrorList& _errors,
NameAndTypeResolver& _resolver,
ContractDefinition const* _currentContract,
ParameterList const* _returnParameters,
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:
virtual bool visit(Block const&) override { return m_resolveInsideCode; }
@ -59,10 +68,24 @@ private:
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;
ContractDefinition const* m_currentContract;
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();
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;
for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
@ -88,7 +88,7 @@ bool TypeChecker::visit(ContractDefinition const& _contract)
{
fallbackFunction = function.get();
if (!fallbackFunction->parameters().empty())
typeError(fallbackFunction->parameterList(), "Fallback function cannot take parameters.");
typeError(fallbackFunction->parameterList().location(), "Fallback function cannot take parameters.");
}
}
if (!function->isImplemented())
@ -108,7 +108,7 @@ bool TypeChecker::visit(ContractDefinition const& _contract)
FixedHash<4> const& hash = it.first;
if (hashes.count(hash))
typeError(
_contract,
_contract.location(),
string("Function signature hash collision for ") + it.second->externalSignature()
);
hashes.insert(hash);
@ -183,7 +183,7 @@ void TypeChecker::checkContractAbstractFunctions(ContractDefinition const& _cont
else if (it->second)
{
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())
it->second = true;
@ -252,7 +252,7 @@ void TypeChecker::checkContractIllegalOverrides(ContractDefinition const& _contr
continue; // constructors can neither be overridden nor override anything
string const& name = function->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);
// function should not change the return type
for (FunctionDefinition const* overriding: functions[name])
@ -265,7 +265,7 @@ void TypeChecker::checkContractIllegalOverrides(ContractDefinition const& _contr
overriding->isDeclaredConst() != function->isDeclaredConst() ||
overridingType != functionType
)
typeError(*overriding, "Override changes extended function signature.");
typeError(overriding->location(), "Override changes extended function signature.");
}
functions[name].push_back(function.get());
}
@ -276,9 +276,9 @@ void TypeChecker::checkContractIllegalOverrides(ContractDefinition const& _contr
if (!override)
override = modifier.get();
else if (ModifierType(*override) != ModifierType(*modifier))
typeError(*override, "Override changes modifier signature.");
typeError(override->location(), "Override changes modifier signature.");
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)
if (!it.second[i].second->hasEqualArgumentTypes(*it.second[j].second))
typeError(
*it.second[j].first,
it.second[j].first->location(),
"Function overload clash during conversion to external types for arguments."
);
}
@ -319,11 +319,11 @@ void TypeChecker::checkLibraryRequirements(ContractDefinition const& _contract)
{
solAssert(_contract.isLibrary(), "");
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())
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)
@ -332,13 +332,13 @@ void TypeChecker::endVisit(InheritanceSpecifier const& _inheritance)
solAssert(base, "Base contract not available.");
if (base->isLibrary())
typeError(_inheritance, "Libraries cannot be inherited from.");
typeError(_inheritance.location(), "Libraries cannot be inherited from.");
auto const& arguments = _inheritance.arguments();
TypePointers parameterTypes = ContractType(*base).constructorType()->parameterTypes();
if (!arguments.empty() && parameterTypes.size() != arguments.size())
typeError(
_inheritance,
_inheritance.location(),
"Wrong argument count for constructor call: " +
toString(arguments.size()) +
" arguments given but expected " +
@ -349,7 +349,7 @@ void TypeChecker::endVisit(InheritanceSpecifier const& _inheritance)
for (size_t i = 0; i < arguments.size(); ++i)
if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[i]))
typeError(
*arguments[i],
arguments[i]->location(),
"Invalid type for argument in constructor call. "
"Invalid implicit conversion from " +
type(*arguments[i])->toString() +
@ -363,7 +363,7 @@ bool TypeChecker::visit(StructDefinition const& _struct)
{
for (ASTPointer<VariableDeclaration> const& member: _struct.members())
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.
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)
{
if (_parents.count(_struct))
fatalTypeError(*_struct, "Recursive struct definition.");
fatalTypeError(_struct->location(), "Recursive struct definition.");
StructPointersSet parents = _parents;
parents.insert(_struct);
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())
{
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)))
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())
visitManually(
@ -424,9 +424,9 @@ bool TypeChecker::visit(VariableDeclaration const& _variable)
if (_variable.isConstant())
{
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())
typeError(_variable, "Uninitialized \"constant\" variable.");
typeError(_variable.location(), "Uninitialized \"constant\" variable.");
if (!varType->isValueType())
{
bool constImplemented = false;
@ -434,7 +434,7 @@ bool TypeChecker::visit(VariableDeclaration const& _variable)
constImplemented = arrayType->isByteArray();
if (!constImplemented)
typeError(
_variable,
_variable.location(),
"Illegal use of \"constant\" specifier. \"constant\" "
"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->canLiveOutsideStorage())
typeError(_variable, "Type " + varType->toString() + " is only valid in storage.");
typeError(_variable.location(), "Type " + varType->toString() + " is only valid in storage.");
}
else if (
_variable.visibility() >= VariableDeclaration::Visibility::Public &&
!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;
}
@ -483,10 +483,10 @@ void TypeChecker::visitManually(
break;
}
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())
typeError(
_modifier,
_modifier.location(),
"Wrong argument count for modifier invocation: " +
toString(arguments.size()) +
" arguments given but expected " +
@ -496,7 +496,7 @@ void TypeChecker::visitManually(
for (size_t i = 0; i < _modifier.arguments().size(); ++i)
if (!type(*arguments[i])->isImplicitlyConvertibleTo(*type(*(*parameters)[i])))
typeError(
*arguments[i],
arguments[i]->location(),
"Invalid type for argument in modifier invocation. "
"Invalid implicit conversion from " +
type(*arguments[i])->toString() +
@ -514,13 +514,13 @@ bool TypeChecker::visit(EventDefinition const& _eventDef)
if (var->isIndexed())
numIndexed++;
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)
typeError(_eventDef, "More than 3 indexed arguments for event.");
typeError(_eventDef.location(), "More than 3 indexed arguments for event.");
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))
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;
}
@ -561,7 +561,7 @@ void TypeChecker::endVisit(Return const& _return)
ParameterList const* params = _return.annotation().functionReturnParameters;
if (!params)
{
typeError(_return, "Return arguments not allowed.");
typeError(_return.location(), "Return arguments not allowed.");
return;
}
TypePointers returnTypes;
@ -570,10 +570,10 @@ void TypeChecker::endVisit(Return const& _return)
if (auto tupleType = dynamic_cast<TupleType const*>(type(*_return.expression()).get()))
{
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)))
typeError(
*_return.expression(),
_return.expression()->location(),
"Return argument type " +
type(*_return.expression())->toString() +
" is not implicitly convertible to expected type " +
@ -582,13 +582,13 @@ void TypeChecker::endVisit(Return const& _return)
);
}
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
{
TypePointer const& expected = type(*params->parameters().front());
if (!type(*_return.expression())->isImplicitlyConvertibleTo(*expected))
typeError(
*_return.expression(),
_return.expression()->location(),
"Return argument type " +
type(*_return.expression())->toString() +
" 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.
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();
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 (ref->dataStoredIn(DataLocation::Storage))
@ -642,7 +642,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
{
if (!valueTypes.empty())
fatalTypeError(
_statement,
_statement.location(),
"Too many components (" +
toString(valueTypes.size()) +
") 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())
fatalTypeError(
_statement,
_statement.location(),
"Wildcard both at beginning and end of variable declaration list is only allowed "
"if the number of components is equal."
);
@ -659,7 +659,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
--minNumValues;
if (valueTypes.size() < minNumValues)
fatalTypeError(
_statement,
_statement.location(),
"Not enough components (" +
toString(valueTypes.size()) +
") 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())
fatalTypeError(
_statement,
_statement.location(),
"Too many components (" +
toString(valueTypes.size()) +
") in value for variable assignment (" +
@ -697,7 +697,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
valueComponentType->category() == Type::Category::IntegerConstant &&
!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.accept(*this);
}
@ -706,7 +706,7 @@ bool TypeChecker::visit(VariableDeclarationStatement const& _statement)
var.accept(*this);
if (!valueComponentType->isImplicitlyConvertibleTo(*var.annotation().type))
typeError(
_statement,
_statement.location(),
"Type " +
valueComponentType->toString() +
" 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 (!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)
@ -738,7 +738,7 @@ bool TypeChecker::visit(Assignment const& _assignment)
}
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);
}
else if (_assignment.assignmentOperator() == Token::Assign)
@ -753,7 +753,7 @@ bool TypeChecker::visit(Assignment const& _assignment)
);
if (!resultType || *resultType != *t)
typeError(
_assignment,
_assignment.location(),
"Operator " +
string(Token::toString(_assignment.assignmentOperator())) +
" 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,).
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])
{
components[i]->accept(*this);
@ -823,7 +823,7 @@ bool TypeChecker::visit(UnaryOperation const& _operation)
if (!t)
{
typeError(
_operation,
_operation.location(),
"Unary operator " +
string(Token::toString(op)) +
" cannot be applied to type " +
@ -843,7 +843,7 @@ void TypeChecker::endVisit(BinaryOperation const& _operation)
if (!commonType)
{
typeError(
_operation,
_operation.location(),
"Operator " +
string(Token::toString(_operation.getOperator())) +
" not compatible with types " +
@ -896,9 +896,9 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
TypeType const& t = dynamic_cast<TypeType const&>(*expressionType);
TypePointer resultType = t.actualType();
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)
typeError(_functionCall, "Type conversion cannot allow named arguments.");
typeError(_functionCall.location(), "Type conversion cannot allow named arguments.");
else
{
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)
resultType = ReferenceType::copyForLocationIfReference(argRefType->location(), resultType);
if (!argType->isExplicitlyConvertibleTo(*resultType))
typeError(_functionCall, "Explicit type conversion not allowed.");
typeError(_functionCall.location(), "Explicit type conversion not allowed.");
}
_functionCall.annotation().type = resultType;
@ -932,7 +932,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
if (!functionType)
{
typeError(_functionCall, "Type is not callable");
typeError(_functionCall.location(), "Type is not callable");
_functionCall.annotation().type = make_shared<TupleType>();
return false;
}
@ -957,7 +957,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
for (auto const& member: membersRemovedForStructConstructor)
msg += " " + member;
}
typeError(_functionCall, msg);
typeError(_functionCall.location(), msg);
}
else if (isPositionalCall)
{
@ -969,11 +969,11 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
{
if (auto t = dynamic_cast<IntegerConstantType const*>(argType.get()))
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]))
typeError(
*arguments[i],
arguments[i]->location(),
"Invalid type for argument in function call. "
"Invalid implicit conversion from " +
type(*arguments[i])->toString() +
@ -989,13 +989,13 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
auto const& parameterNames = functionType->parameterNames();
if (functionType->takesArbitraryParameters())
typeError(
_functionCall,
_functionCall.location(),
"Named arguments cannnot be used for functions that take arbitrary parameters."
);
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())
typeError(_functionCall, "Too many arguments.");
typeError(_functionCall.location(), "Too many arguments.");
else
{
// check duplicate names
@ -1005,7 +1005,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
if (*argumentNames[i] == *argumentNames[j])
{
duplication = true;
typeError(*arguments[i], "Duplicate named argument.");
typeError(arguments[i]->location(), "Duplicate named argument.");
}
// check actual types
@ -1020,7 +1020,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
// check type convertible
if (!type(*arguments[i])->isImplicitlyConvertibleTo(*parameterTypes[j]))
typeError(
*arguments[i],
arguments[i]->location(),
"Invalid type for argument in function call. "
"Invalid implicit conversion from " +
type(*arguments[i])->toString() +
@ -1033,7 +1033,7 @@ bool TypeChecker::visit(FunctionCall const& _functionCall)
if (!found)
typeError(
_functionCall,
_functionCall.location(),
"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()));
if (!contract)
fatalTypeError(_newExpression, "Identifier is not a contract.");
fatalTypeError(_newExpression.location(), "Identifier is not a contract.");
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;
scopeContract->annotation().contractDependencies.insert(contract);
@ -1060,7 +1060,7 @@ void TypeChecker::endVisit(NewExpression const& _newExpression)
);
if (contractDependenciesAreCyclic(*scopeContract))
typeError(
_newExpression,
_newExpression.location(),
"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())
fatalTypeError(
_memberAccess,
_memberAccess.location(),
"Member \"" + memberName + "\" is not available in " +
exprType->toString() +
" outside of storage."
);
fatalTypeError(
_memberAccess,
_memberAccess.location(),
"Member \"" + memberName + "\" not found or not visible "
"after argument-dependent lookup in " + exprType->toString()
);
}
else if (possibleMembers.size() > 1)
fatalTypeError(
_memberAccess,
_memberAccess.location(),
"Member \"" + memberName + "\" not unique "
"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);
if (!index)
typeError(_access, "Index expression cannot be omitted.");
typeError(_access.location(), "Index expression cannot be omitted.");
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);
}
else
@ -1164,7 +1164,7 @@ bool TypeChecker::visit(IndexAccess const& _access)
expectType(*index, IntegerType(256));
if (auto integerType = dynamic_cast<IntegerConstantType const*>(type(*index).get()))
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();
isLValue = actualType.location() != DataLocation::CallData;
@ -1174,7 +1174,7 @@ bool TypeChecker::visit(IndexAccess const& _access)
{
MappingType const& actualType = dynamic_cast<MappingType const&>(*baseType);
if (!index)
typeError(_access, "Index expression cannot be omitted.");
typeError(_access.location(), "Index expression cannot be omitted.");
else
expectType(*index, *actualType.keyType());
resultType = actualType.valueType();
@ -1196,13 +1196,13 @@ bool TypeChecker::visit(IndexAccess const& _access)
length->literalValue(nullptr)
));
else
typeError(*index, "Integer constant expected.");
typeError(index->location(), "Integer constant expected.");
}
break;
}
default:
fatalTypeError(
_access.baseExpression(),
_access.baseExpression().location(),
"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.argumentTypes)
fatalTypeError(_identifier, "Unable to determine overloaded type.");
fatalTypeError(_identifier.location(), "Unable to determine overloaded type.");
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)
annotation.referencedDeclaration = *annotation.overloadedDeclarations.begin();
else
@ -1236,11 +1236,11 @@ bool TypeChecker::visit(Identifier const& _identifier)
candidates.push_back(declaration);
}
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)
annotation.referencedDeclaration = candidates.front();
else
fatalTypeError(_identifier, "No unique declaration found after argument-dependent lookup.");
fatalTypeError(_identifier.location(), "No unique declaration found after argument-dependent lookup.");
}
}
solAssert(
@ -1250,7 +1250,7 @@ bool TypeChecker::visit(Identifier const& _identifier)
annotation.isLValue = annotation.referencedDeclaration->isLValue();
annotation.type = annotation.referencedDeclaration->type(_identifier.annotation().contractScope);
if (!annotation.type)
fatalTypeError(_identifier, "Declaration referenced before type could be determined.");
fatalTypeError(_identifier.location(), "Declaration referenced before type could be determined.");
return false;
}
@ -1263,7 +1263,7 @@ void TypeChecker::endVisit(Literal const& _literal)
{
_literal.annotation().type = Type::forLiteral(_literal);
if (!_literal.annotation().type)
fatalTypeError(_literal, "Invalid literal value.");
fatalTypeError(_literal.location(), "Invalid literal value.");
}
bool TypeChecker::contractDependenciesAreCyclic(
@ -1294,7 +1294,7 @@ void TypeChecker::expectType(Expression const& _expression, Type const& _expecte
if (!type(_expression)->isImplicitlyConvertibleTo(_expectedType))
typeError(
_expression,
_expression.location(),
"Type " +
type(_expression)->toString() +
" is not implicitly convertible to expected type " +
@ -1308,21 +1308,21 @@ void TypeChecker::requireLValue(Expression const& _expression)
_expression.annotation().lValueRequested = true;
_expression.accept(*this);
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);
*err <<
errinfo_sourceLocation(_node.location()) <<
errinfo_sourceLocation(_location) <<
errinfo_comment(_description);
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());
}

View File

@ -57,10 +57,10 @@ public:
private:
/// 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.
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;
/// 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(ASTConstVisitor& _visitor) const override;
std::vector<ASTPointer<Statement>> const& statements() const { return m_statements; }
private:
std::vector<ASTPointer<Statement>> m_statements;
};

View File

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

View File

@ -588,11 +588,24 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
{
++numIndexed;
arguments[arg - 1]->accept(*this);
utils().convertType(
*arguments[arg - 1]->annotation().type,
*function.parameterTypes()[arg - 1],
true
);
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(
*arguments[arg - 1]->annotation().type,
*function.parameterTypes()[arg - 1],
true
);
}
if (!event.isAnonymous())
{
@ -625,6 +638,20 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
m_context << eth::Instruction::BLOCKHASH;
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::SHA256:
case Location::RIPEMD160:

View File

@ -103,10 +103,20 @@ void MemoryItem::storeValue(Type const& _sourceType, SourceLocation const&, bool
if (!_move)
{
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);
m_context << eth::Instruction::POP;
}
utils.storeInMemoryDynamic(*m_dataType, m_padded);
m_context << eth::Instruction::POP;
}
else
{

View File

@ -35,7 +35,6 @@ bool Why3Translator::process(SourceUnit const& _source)
fatalError(_source, "Multiple source units not yet supported");
appendPreface();
_source.accept(*this);
addLine("end");
}
catch (FatalError& _e)
{
@ -71,18 +70,6 @@ module UInt256
type t = uint256,
constant max = max_uint256
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)
{
if (m_currentLine.empty())
m_indentationAtLineStart = m_indentation;
m_currentLine += _str;
}
@ -120,7 +109,7 @@ void Why3Translator::newLine()
{
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 += m_currentLine;
m_result.push_back('\n');
@ -130,6 +119,7 @@ void Why3Translator::newLine()
void Why3Translator::unindent()
{
newLine();
solAssert(m_indentation > 0, "");
m_indentation--;
}
@ -142,9 +132,52 @@ bool Why3Translator::visit(ContractDefinition const& _contract)
if (_contract.isLibrary())
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)
@ -177,7 +210,6 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
add(" (arg_" + param->name() + ": " + paramType + ")");
}
add(":");
newLine();
indent();
indent();
@ -191,7 +223,7 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
retString += ", ";
retString += paramType;
}
addLine(retString + ")");
add(retString + ")");
unindent();
addSourceFromDocStrings(_function.annotation());
@ -218,6 +250,7 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
addLine("try");
_function.body().accept(*this);
add(";");
addLine("raise Ret");
string retVals;
@ -238,9 +271,18 @@ bool Why3Translator::visit(FunctionDefinition const& _function)
bool Why3Translator::visit(Block const& _node)
{
addSourceFromDocStrings(_node.annotation());
addLine("begin");
add("begin");
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)
@ -250,12 +292,12 @@ bool Why3Translator::visit(IfStatement const& _node)
add("if ");
_node.condition().accept(*this);
add(" then");
newLine();
_node.trueStatement().accept(*this);
visitIndentedUnlessBlock(_node.trueStatement());
if (_node.falseStatement())
{
addLine("else");
_node.falseStatement()->accept(*this);
newLine();
add("else");
visitIndentedUnlessBlock(*_node.falseStatement());
}
return false;
}
@ -266,10 +308,10 @@ bool Why3Translator::visit(WhileStatement const& _node)
add("while ");
_node.condition().accept(*this);
add(" do");
newLine();
_node.body().accept(*this);
addLine("done;");
add("do");
visitIndentedUnlessBlock(_node.body());
add("done");
return false;
}
@ -286,14 +328,12 @@ bool Why3Translator::visit(Return const& _node)
error(_node, "Directly returning tuples not supported. Rather assign to return variable.");
return false;
}
newLine();
add("begin _" + params.front()->name() + " := ");
_node.expression()->accept(*this);
add("; raise Ret end");
newLine();
}
else
addLine("raise Ret;");
add("raise Ret");
return false;
}
@ -310,8 +350,6 @@ bool Why3Translator::visit(VariableDeclarationStatement const& _node)
{
add("_" + _node.declarations().front()->name() + " := ");
_node.initialValue()->accept(*this);
add(";");
newLine();
}
return false;
}
@ -429,7 +467,7 @@ bool Why3Translator::visit(FunctionCall const& _node)
add("(");
_node.expression().accept(*this);
add(" StateUnused");
add(" state");
for (auto const& arg: _node.arguments())
{
add(" ");
@ -487,10 +525,15 @@ bool Why3Translator::visit(Identifier const& _identifier)
add("_" + functionDef->name());
else if (auto variable = dynamic_cast<VariableDeclaration const*>(declaration))
{
if (_identifier.annotation().lValueRequested)
add("_" + variable->name());
else
add("!_" + variable->name());
bool isStateVar = isStateVariable(variable);
bool lvalue = _identifier.annotation().lValueRequested;
if (!lvalue)
add("!(");
if (isStateVar)
add("state.");
add("_" + variable->name());
if (!lvalue)
add(")");
}
else
error(_identifier, "Not supported.");
@ -517,7 +560,30 @@ bool Why3Translator::visit(Literal const& _literal)
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");
for (auto i = why3Range.first; i != why3Range.second; ++i)

View File

@ -64,7 +64,7 @@ private:
/// if the type is not supported.
std::string toFormalType(Type const& _type) const;
void indent() { m_indentation++; }
void indent() { newLine(); m_indentation++; }
void unindent();
void addLine(std::string const& _line);
void add(std::string const& _str);
@ -72,15 +72,14 @@ private:
virtual bool visit(SourceUnit const&) override { return true; }
virtual bool visit(ContractDefinition const& _contract) override;
virtual void endVisit(ContractDefinition const& _contract) override;
virtual bool visit(FunctionDefinition const& _function) 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(WhileStatement const& _node) override;
virtual bool visit(Return const& _node) override;
virtual bool visit(VariableDeclarationStatement const& _node) 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(TupleExpression const& _node) override;
virtual void endVisit(TupleExpression const&) override { add(")"); }
@ -98,14 +97,24 @@ private:
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);
size_t m_indentationAtLineStart = 0;
size_t m_indentation = 0;
std::string m_currentLine;
/// True if we have already seen a contract. For now, only a single contract
/// is supported.
bool m_seenContract = false;
bool m_errorOccured = false;
std::vector<ASTPointer<VariableDeclaration>> const* m_stateVariables = nullptr;
std::string m_result;
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_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)
{
char const* sourceCode = R"(
@ -5781,6 +5816,39 @@ BOOST_AUTO_TEST_CASE(lone_struct_array_type)
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()
}

View File

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

View File

@ -359,6 +359,16 @@ BOOST_AUTO_TEST_CASE(store_tags_as_unions)
// 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)
{
eth::KnownState state;
@ -1113,7 +1123,11 @@ BOOST_AUTO_TEST_CASE(computing_constants)
bytes complicatedConstant = toBigEndian(u256("0x817416927846239487123469187231298734162934871263941234127518276"));
unsigned occurrences = 0;
for (auto iter = optimizedBytecode.cbegin(); iter < optimizedBytecode.cend(); ++occurrences)
iter = search(iter, optimizedBytecode.cend(), complicatedConstant.cbegin(), complicatedConstant.cend()) + 1;
{
iter = search(iter, optimizedBytecode.cend(), complicatedConstant.cbegin(), complicatedConstant.cend());
if (iter < optimizedBytecode.cend())
++iter;
}
BOOST_CHECK_EQUAL(2, occurrences);
bytes constantWithZeros = toBigEndian(u256("0x77abc0000000000000000000000000000000000000000000000000000000001"));