passed SourceLocations instead of nodes to the error reporting function

This commit is contained in:
LianaHus 2015-11-04 11:49:26 +01:00
parent 02d060ea5c
commit ff421a9d65
5 changed files with 116 additions and 109 deletions

View File

@ -65,15 +65,15 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
m_currentScope = &m_scopes[nullptr]; m_currentScope = &m_scopes[nullptr];
ReferencesResolver resolver(m_errors, *this, &_contract, nullptr); ReferencesResolver resolver(m_errors, *this, &_contract, nullptr);
bool result = true; bool success = true;
for (ASTPointer<InheritanceSpecifier> const& baseContract: _contract.baseContracts()) for (ASTPointer<InheritanceSpecifier> const& baseContract: _contract.baseContracts())
result = resolver.resolve(*baseContract); if (!resolver.resolve(*baseContract))
success = false;
m_currentScope = &m_scopes[&_contract]; m_currentScope = &m_scopes[&_contract];
if (result) if (success)
{ {
linearizeBaseContracts(_contract); linearizeBaseContracts(_contract);
std::vector<ContractDefinition const*> properBases( std::vector<ContractDefinition const*> properBases(
++_contract.annotation().linearizedBaseContracts.begin(), ++_contract.annotation().linearizedBaseContracts.begin(),
@ -84,21 +84,25 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
importInheritedScope(*base); importInheritedScope(*base);
} }
for (ASTPointer<StructDefinition> const& structDef: _contract.definedStructs()) for (ASTPointer<StructDefinition> const& structDef: _contract.definedStructs())
result = result && resolver.resolve(*structDef); if (!resolver.resolve(*structDef))
success = false;
for (ASTPointer<EnumDefinition> const& enumDef: _contract.definedEnums()) for (ASTPointer<EnumDefinition> const& enumDef: _contract.definedEnums())
result = result && resolver.resolve(*enumDef); if (!resolver.resolve(*enumDef))
success = false;
for (ASTPointer<VariableDeclaration> const& variable: _contract.stateVariables()) for (ASTPointer<VariableDeclaration> const& variable: _contract.stateVariables())
result = result && resolver.resolve(*variable); if (!resolver.resolve(*variable))
success = false;
for (ASTPointer<EventDefinition> const& event: _contract.events()) for (ASTPointer<EventDefinition> const& event: _contract.events())
result = result && resolver.resolve(*event); 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(m_errors, *this, &_contract, nullptr); ReferencesResolver resolver(m_errors, *this, &_contract, nullptr);
result = result && resolver.resolve(*modifier); if (!resolver.resolve(*modifier))
success = false;
} }
for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
{ {
@ -109,7 +113,8 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
&_contract, &_contract,
function->returnParameterList().get() function->returnParameterList().get()
); );
result = result && referencesResolver.resolve(*function); if (!resolver.resolve(*function))
success = false;
} }
m_currentScope = &m_scopes[&_contract]; m_currentScope = &m_scopes[&_contract];
@ -119,7 +124,8 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
{ {
m_currentScope = &m_scopes[modifier.get()]; m_currentScope = &m_scopes[modifier.get()];
ReferencesResolver resolver(m_errors, *this, &_contract, nullptr, true); ReferencesResolver resolver(m_errors, *this, &_contract, nullptr, true);
result = result && resolver.resolve(*modifier); if (!resolver.resolve(*modifier))
success = false;
} }
for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
{ {
@ -131,15 +137,16 @@ bool NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
function->returnParameterList().get(), function->returnParameterList().get(),
true true
); );
result = result && resolver.resolve(*function); if (!resolver.resolve(*function))
success = false;
} }
if (!result) // if (!result)
return false; // return false;
} }
catch (FatalError const& _e) catch (FatalError const& _e)
{ {
if (m_errors.empty()) // if (m_errors.empty())
throw; // Something is weird here, rather throw again. // throw; // Something is weird here, rather throw again.
return false; return false;
} }
return true; return true;

View File

@ -209,10 +209,10 @@ TypePointer ReferencesResolver::typeFor(TypeName const& _typeName)
return _typeName.annotation().type = move(type); return _typeName.annotation().type = move(type);
} }
void ReferencesResolver::typeError(string const& _description) void ReferencesResolver::typeError(string const& _description, SourceLocation const& _location)
{ {
auto err = make_shared<Error>(Error::Type::TypeError); auto err = make_shared<Error>(Error::Type::TypeError);
*err << errinfo_comment(_description); *err << errinfo_sourceLocation(_location) << errinfo_comment(_description);
m_errors.push_back(err); m_errors.push_back(err);
} }

View File

@ -60,7 +60,7 @@ public:
bool resolve(ASTNode& _root) bool resolve(ASTNode& _root)
{ {
_root.accept(*this); _root.accept(*this);
return m_errors.empty(); return true;//m_errors.empty();
} }
private: private:
@ -73,7 +73,7 @@ private:
TypePointer typeFor(TypeName const& _typeName); TypePointer typeFor(TypeName const& _typeName);
/// Adds a new error to the list of errors. /// Adds a new error to the list of errors.
void typeError(std::string const& _description); void typeError(std::string const& _description, SourceLocation const& _location);
/// 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(std::string const& _description); void fatalTypeError(std::string const& _description);

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