renamed getter functions

This commit is contained in:
LianaHus 2015-08-31 18:44:29 +02:00
parent 6f4a39c183
commit 1b5e6fc9e7
51 changed files with 1615 additions and 1608 deletions

View File

@ -40,17 +40,17 @@ namespace solidity
TypeError ASTNode::createTypeError(string const& _description) const TypeError ASTNode::createTypeError(string const& _description) const
{ {
return TypeError() << errinfo_sourceLocation(getLocation()) << errinfo_comment(_description); return TypeError() << errinfo_sourceLocation(location()) << errinfo_comment(_description);
} }
TypePointer ContractDefinition::getType(ContractDefinition const* _currentContract) const TypePointer ContractDefinition::type(ContractDefinition const* _currentContract) const
{ {
return make_shared<TypeType>(make_shared<ContractType>(*this), _currentContract); return make_shared<TypeType>(make_shared<ContractType>(*this), _currentContract);
} }
void ContractDefinition::checkTypeRequirements() void ContractDefinition::checkTypeRequirements()
{ {
for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: getBaseContracts()) for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: baseContracts())
baseSpecifier->checkTypeRequirements(); baseSpecifier->checkTypeRequirements();
checkDuplicateFunctions(); checkDuplicateFunctions();
@ -58,32 +58,33 @@ void ContractDefinition::checkTypeRequirements()
checkAbstractFunctions(); checkAbstractFunctions();
checkAbstractConstructors(); checkAbstractConstructors();
FunctionDefinition const* constructor = getConstructor(); FunctionDefinition const* function = constructor();
if (constructor && !constructor->getReturnParameters().empty()) if (function && !function->returnParameters().empty())
BOOST_THROW_EXCEPTION(constructor->getReturnParameterList()->createTypeError( BOOST_THROW_EXCEPTION(
"Non-empty \"returns\" directive for constructor.")); function->returnParameterList()->createTypeError("Non-empty \"returns\" directive for constructor.")
);
FunctionDefinition const* fallbackFunction = nullptr; FunctionDefinition const* fallbackFunction = nullptr;
for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: definedFunctions())
{ {
if (function->getName().empty()) if (function->name().empty())
{ {
if (fallbackFunction) if (fallbackFunction)
BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_comment("Only one fallback function is allowed.")); BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_comment("Only one fallback function is allowed."));
else else
{ {
fallbackFunction = function.get(); fallbackFunction = function.get();
if (!fallbackFunction->getParameters().empty()) if (!fallbackFunction->parameters().empty())
BOOST_THROW_EXCEPTION(fallbackFunction->getParameterList().createTypeError("Fallback function cannot take parameters.")); BOOST_THROW_EXCEPTION(fallbackFunction->parameterList().createTypeError("Fallback function cannot take parameters."));
} }
} }
if (!function->isFullyImplemented()) if (!function->isFullyImplemented())
setFullyImplemented(false); setFullyImplemented(false);
} }
for (ASTPointer<ModifierDefinition> const& modifier: getFunctionModifiers()) for (ASTPointer<ModifierDefinition> const& modifier: functionModifiers())
modifier->checkTypeRequirements(); modifier->checkTypeRequirements();
for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: definedFunctions())
function->checkTypeRequirements(); function->checkTypeRequirements();
for (ASTPointer<VariableDeclaration> const& variable: m_stateVariables) for (ASTPointer<VariableDeclaration> const& variable: m_stateVariables)
@ -92,7 +93,7 @@ void ContractDefinition::checkTypeRequirements()
checkExternalTypeClashes(); checkExternalTypeClashes();
// check for hash collisions in function signatures // check for hash collisions in function signatures
set<FixedHash<4>> hashes; set<FixedHash<4>> hashes;
for (auto const& it: getInterfaceFunctionList()) for (auto const& it: interfaceFunctionList())
{ {
FixedHash<4> const& hash = it.first; FixedHash<4> const& hash = it.first;
if (hashes.count(hash)) if (hashes.count(hash))
@ -103,9 +104,9 @@ void ContractDefinition::checkTypeRequirements()
} }
} }
map<FixedHash<4>, FunctionTypePointer> ContractDefinition::getInterfaceFunctions() const map<FixedHash<4>, FunctionTypePointer> ContractDefinition::interfaceFunctions() const
{ {
auto exportedFunctionList = getInterfaceFunctionList(); auto exportedFunctionList = interfaceFunctionList();
map<FixedHash<4>, FunctionTypePointer> exportedFunctions; map<FixedHash<4>, FunctionTypePointer> exportedFunctions;
for (auto const& it: exportedFunctionList) for (auto const& it: exportedFunctionList)
@ -117,7 +118,7 @@ map<FixedHash<4>, FunctionTypePointer> ContractDefinition::getInterfaceFunctions
return exportedFunctions; return exportedFunctions;
} }
FunctionDefinition const* ContractDefinition::getConstructor() const FunctionDefinition const* ContractDefinition::constructor() const
{ {
for (ASTPointer<FunctionDefinition> const& f: m_definedFunctions) for (ASTPointer<FunctionDefinition> const& f: m_definedFunctions)
if (f->isConstructor()) if (f->isConstructor())
@ -125,11 +126,11 @@ FunctionDefinition const* ContractDefinition::getConstructor() const
return nullptr; return nullptr;
} }
FunctionDefinition const* ContractDefinition::getFallbackFunction() const FunctionDefinition const* ContractDefinition::fallbackFunction() const
{ {
for (ContractDefinition const* contract: getLinearizedBaseContracts()) for (ContractDefinition const* contract: linearizedBaseContracts())
for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& f: contract->definedFunctions())
if (f->getName().empty()) if (f->name().empty())
return f.get(); return f.get();
return nullptr; return nullptr;
} }
@ -139,20 +140,20 @@ void ContractDefinition::checkDuplicateFunctions() const
/// Checks that two functions with the same name defined in this contract have different /// Checks that two functions with the same name defined in this contract have different
/// argument types and that there is at most one constructor. /// argument types and that there is at most one constructor.
map<string, vector<FunctionDefinition const*>> functions; map<string, vector<FunctionDefinition const*>> functions;
for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: definedFunctions())
functions[function->getName()].push_back(function.get()); functions[function->name()].push_back(function.get());
if (functions[getName()].size() > 1) if (functions[name()].size() > 1)
{ {
SecondarySourceLocation ssl; SecondarySourceLocation ssl;
auto it = functions[getName()].begin(); auto it = functions[name()].begin();
++it; ++it;
for (; it != functions[getName()].end(); ++it) for (; it != functions[name()].end(); ++it)
ssl.append("Another declaration is here:", (*it)->getLocation()); ssl.append("Another declaration is here:", (*it)->location());
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
DeclarationError() << DeclarationError() <<
errinfo_sourceLocation(functions[getName()].front()->getLocation()) << errinfo_sourceLocation(functions[name()].front()->location()) <<
errinfo_comment("More than one constructor defined.") << errinfo_comment("More than one constructor defined.") <<
errinfo_secondarySourceLocation(ssl) errinfo_secondarySourceLocation(ssl)
); );
@ -165,10 +166,10 @@ void ContractDefinition::checkDuplicateFunctions() const
if (FunctionType(*overloads[i]).hasEqualArgumentTypes(FunctionType(*overloads[j]))) if (FunctionType(*overloads[i]).hasEqualArgumentTypes(FunctionType(*overloads[j])))
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
DeclarationError() << DeclarationError() <<
errinfo_sourceLocation(overloads[j]->getLocation()) << errinfo_sourceLocation(overloads[j]->location()) <<
errinfo_comment("Function with same name and arguments defined twice.") << errinfo_comment("Function with same name and arguments defined twice.") <<
errinfo_secondarySourceLocation(SecondarySourceLocation().append( errinfo_secondarySourceLocation(SecondarySourceLocation().append(
"Other declaration is here:", overloads[i]->getLocation())) "Other declaration is here:", overloads[i]->location()))
); );
} }
} }
@ -181,10 +182,10 @@ void ContractDefinition::checkAbstractFunctions()
map<string, vector<FunTypeAndFlag>> functions; map<string, vector<FunTypeAndFlag>> functions;
// Search from base to derived // Search from base to derived
for (ContractDefinition const* contract: boost::adaptors::reverse(getLinearizedBaseContracts())) for (ContractDefinition const* contract: boost::adaptors::reverse(linearizedBaseContracts()))
for (ASTPointer<FunctionDefinition> const& function: contract->getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: contract->definedFunctions())
{ {
auto& overloads = functions[function->getName()]; auto& overloads = functions[function->name()];
FunctionTypePointer funType = make_shared<FunctionType>(*function); FunctionTypePointer funType = make_shared<FunctionType>(*function);
auto it = find_if(overloads.begin(), overloads.end(), [&](FunTypeAndFlag const& _funAndFlag) auto it = find_if(overloads.begin(), overloads.end(), [&](FunTypeAndFlag const& _funAndFlag)
{ {
@ -217,32 +218,32 @@ void ContractDefinition::checkAbstractConstructors()
// check that we get arguments for all base constructors that need it. // check that we get arguments for all base constructors that need it.
// If not mark the contract as abstract (not fully implemented) // If not mark the contract as abstract (not fully implemented)
vector<ContractDefinition const*> const& bases = getLinearizedBaseContracts(); vector<ContractDefinition const*> const& bases = linearizedBaseContracts();
for (ContractDefinition const* contract: bases) for (ContractDefinition const* contract: bases)
if (FunctionDefinition const* constructor = contract->getConstructor()) if (FunctionDefinition const* constructor = contract->constructor())
if (contract != this && !constructor->getParameters().empty()) if (contract != this && !constructor->parameters().empty())
argumentsNeeded.insert(contract); argumentsNeeded.insert(contract);
for (ContractDefinition const* contract: bases) for (ContractDefinition const* contract: bases)
{ {
if (FunctionDefinition const* constructor = contract->getConstructor()) if (FunctionDefinition const* constructor = contract->constructor())
for (auto const& modifier: constructor->getModifiers()) for (auto const& modifier: constructor->modifiers())
{ {
auto baseContract = dynamic_cast<ContractDefinition const*>( auto baseContract = dynamic_cast<ContractDefinition const*>(
&modifier->getName()->getReferencedDeclaration() &modifier->name()->referencedDeclaration()
); );
if (baseContract) if (baseContract)
argumentsNeeded.erase(baseContract); argumentsNeeded.erase(baseContract);
} }
for (ASTPointer<InheritanceSpecifier> const& base: contract->getBaseContracts()) for (ASTPointer<InheritanceSpecifier> const& base: contract->baseContracts())
{ {
auto baseContract = dynamic_cast<ContractDefinition const*>( auto baseContract = dynamic_cast<ContractDefinition const*>(
&base->getName()->getReferencedDeclaration() &base->name()->referencedDeclaration()
); );
solAssert(baseContract, ""); solAssert(baseContract, "");
if (!base->getArguments().empty()) if (!base->arguments().empty())
argumentsNeeded.erase(baseContract); argumentsNeeded.erase(baseContract);
} }
} }
@ -258,13 +259,13 @@ void ContractDefinition::checkIllegalOverrides() const
map<string, ModifierDefinition const*> modifiers; map<string, ModifierDefinition const*> modifiers;
// We search from derived to base, so the stored item causes the error. // We search from derived to base, so the stored item causes the error.
for (ContractDefinition const* contract: getLinearizedBaseContracts()) for (ContractDefinition const* contract: linearizedBaseContracts())
{ {
for (ASTPointer<FunctionDefinition> const& function: contract->getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: contract->definedFunctions())
{ {
if (function->isConstructor()) if (function->isConstructor())
continue; // constructors can neither be overridden nor override anything continue; // constructors can neither be overridden nor override anything
string const& name = function->getName(); string const& name = function->name();
if (modifiers.count(name)) if (modifiers.count(name))
BOOST_THROW_EXCEPTION(modifiers[name]->createTypeError("Override changes function to modifier.")); BOOST_THROW_EXCEPTION(modifiers[name]->createTypeError("Override changes function to modifier."));
FunctionType functionType(*function); FunctionType functionType(*function);
@ -275,7 +276,7 @@ void ContractDefinition::checkIllegalOverrides() const
if (!overridingType.hasEqualArgumentTypes(functionType)) if (!overridingType.hasEqualArgumentTypes(functionType))
continue; continue;
if ( if (
overriding->getVisibility() != function->getVisibility() || overriding->visibility() != function->visibility() ||
overriding->isDeclaredConst() != function->isDeclaredConst() || overriding->isDeclaredConst() != function->isDeclaredConst() ||
overridingType != functionType overridingType != functionType
) )
@ -283,9 +284,9 @@ void ContractDefinition::checkIllegalOverrides() const
} }
functions[name].push_back(function.get()); functions[name].push_back(function.get());
} }
for (ASTPointer<ModifierDefinition> const& modifier: contract->getFunctionModifiers()) for (ASTPointer<ModifierDefinition> const& modifier: contract->functionModifiers())
{ {
string const& name = modifier->getName(); string const& name = modifier->name();
ModifierDefinition const*& override = modifiers[name]; ModifierDefinition const*& override = modifiers[name];
if (!override) if (!override)
override = modifier.get(); override = modifier.get();
@ -300,21 +301,21 @@ void ContractDefinition::checkIllegalOverrides() const
void ContractDefinition::checkExternalTypeClashes() const void ContractDefinition::checkExternalTypeClashes() const
{ {
map<string, vector<pair<Declaration const*, shared_ptr<FunctionType>>>> externalDeclarations; map<string, vector<pair<Declaration const*, shared_ptr<FunctionType>>>> externalDeclarations;
for (ContractDefinition const* contract: getLinearizedBaseContracts()) for (ContractDefinition const* contract: linearizedBaseContracts())
{ {
for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& f: contract->definedFunctions())
if (f->isPartOfExternalInterface()) if (f->isPartOfExternalInterface())
{ {
auto functionType = make_shared<FunctionType>(*f); auto functionType = make_shared<FunctionType>(*f);
externalDeclarations[functionType->externalSignature(f->getName())].push_back( externalDeclarations[functionType->externalSignature(f->name())].push_back(
make_pair(f.get(), functionType) make_pair(f.get(), functionType)
); );
} }
for (ASTPointer<VariableDeclaration> const& v: contract->getStateVariables()) for (ASTPointer<VariableDeclaration> const& v: contract->stateVariables())
if (v->isPartOfExternalInterface()) if (v->isPartOfExternalInterface())
{ {
auto functionType = make_shared<FunctionType>(*v); auto functionType = make_shared<FunctionType>(*v);
externalDeclarations[functionType->externalSignature(v->getName())].push_back( externalDeclarations[functionType->externalSignature(v->name())].push_back(
make_pair(v.get(), functionType) make_pair(v.get(), functionType)
); );
} }
@ -328,53 +329,53 @@ void ContractDefinition::checkExternalTypeClashes() const
)); ));
} }
vector<ASTPointer<EventDefinition>> const& ContractDefinition::getInterfaceEvents() const vector<ASTPointer<EventDefinition>> const& ContractDefinition::interfaceEvents() const
{ {
if (!m_interfaceEvents) if (!m_interfaceEvents)
{ {
set<string> eventsSeen; set<string> eventsSeen;
m_interfaceEvents.reset(new vector<ASTPointer<EventDefinition>>()); m_interfaceEvents.reset(new vector<ASTPointer<EventDefinition>>());
for (ContractDefinition const* contract: getLinearizedBaseContracts()) for (ContractDefinition const* contract: linearizedBaseContracts())
for (ASTPointer<EventDefinition> const& e: contract->getEvents()) for (ASTPointer<EventDefinition> const& e: contract->events())
if (eventsSeen.count(e->getName()) == 0) if (eventsSeen.count(e->name()) == 0)
{ {
eventsSeen.insert(e->getName()); eventsSeen.insert(e->name());
m_interfaceEvents->push_back(e); m_interfaceEvents->push_back(e);
} }
} }
return *m_interfaceEvents; return *m_interfaceEvents;
} }
vector<pair<FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::getInterfaceFunctionList() const vector<pair<FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::interfaceFunctionList() const
{ {
if (!m_interfaceFunctionList) if (!m_interfaceFunctionList)
{ {
set<string> functionsSeen; set<string> functionsSeen;
set<string> signaturesSeen; set<string> signaturesSeen;
m_interfaceFunctionList.reset(new vector<pair<FixedHash<4>, FunctionTypePointer>>()); m_interfaceFunctionList.reset(new vector<pair<FixedHash<4>, FunctionTypePointer>>());
for (ContractDefinition const* contract: getLinearizedBaseContracts()) for (ContractDefinition const* contract: linearizedBaseContracts())
{ {
for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& f: contract->definedFunctions())
{ {
if (!f->isPartOfExternalInterface()) if (!f->isPartOfExternalInterface())
continue; continue;
string functionSignature = f->externalSignature(); string functionSignature = f->externalSignature();
if (signaturesSeen.count(functionSignature) == 0) if (signaturesSeen.count(functionSignature) == 0)
{ {
functionsSeen.insert(f->getName()); functionsSeen.insert(f->name());
signaturesSeen.insert(functionSignature); signaturesSeen.insert(functionSignature);
FixedHash<4> hash(dev::sha3(functionSignature)); FixedHash<4> hash(dev::sha3(functionSignature));
m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*f, false))); m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*f, false)));
} }
} }
for (ASTPointer<VariableDeclaration> const& v: contract->getStateVariables()) for (ASTPointer<VariableDeclaration> const& v: contract->stateVariables())
if (functionsSeen.count(v->getName()) == 0 && v->isPartOfExternalInterface()) if (functionsSeen.count(v->name()) == 0 && v->isPartOfExternalInterface())
{ {
FunctionType ftype(*v); FunctionType ftype(*v);
solAssert(v->getType().get(), ""); solAssert(v->type().get(), "");
functionsSeen.insert(v->getName()); functionsSeen.insert(v->name());
FixedHash<4> hash(dev::sha3(ftype.externalSignature(v->getName()))); FixedHash<4> hash(dev::sha3(ftype.externalSignature(v->name())));
m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*v))); m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*v)));
} }
} }
@ -403,7 +404,7 @@ void ContractDefinition::setUserDocumentation(string const& _userDocumentation)
} }
vector<Declaration const*> const& ContractDefinition::getInheritableMembers() const vector<Declaration const*> const& ContractDefinition::inheritableMembers() const
{ {
if (!m_inheritableMembers) if (!m_inheritableMembers)
{ {
@ -411,28 +412,28 @@ vector<Declaration const*> const& ContractDefinition::getInheritableMembers() co
m_inheritableMembers.reset(new vector<Declaration const*>()); m_inheritableMembers.reset(new vector<Declaration const*>());
auto addInheritableMember = [&](Declaration const* _decl) auto addInheritableMember = [&](Declaration const* _decl)
{ {
if (memberSeen.count(_decl->getName()) == 0 && _decl->isVisibleInDerivedContracts()) if (memberSeen.count(_decl->name()) == 0 && _decl->isVisibleInDerivedContracts())
{ {
memberSeen.insert(_decl->getName()); memberSeen.insert(_decl->name());
m_inheritableMembers->push_back(_decl); m_inheritableMembers->push_back(_decl);
} }
}; };
for (ASTPointer<FunctionDefinition> const& f: getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& f: definedFunctions())
addInheritableMember(f.get()); addInheritableMember(f.get());
for (ASTPointer<VariableDeclaration> const& v: getStateVariables()) for (ASTPointer<VariableDeclaration> const& v: stateVariables())
addInheritableMember(v.get()); addInheritableMember(v.get());
for (ASTPointer<StructDefinition> const& s: getDefinedStructs()) for (ASTPointer<StructDefinition> const& s: definedStructs())
addInheritableMember(s.get()); addInheritableMember(s.get());
} }
return *m_inheritableMembers; return *m_inheritableMembers;
} }
TypePointer EnumValue::getType(ContractDefinition const*) const TypePointer EnumValue::type(ContractDefinition const*) const
{ {
EnumDefinition const* parentDef = dynamic_cast<EnumDefinition const*>(getScope()); EnumDefinition const* parentDef = dynamic_cast<EnumDefinition const*>(scope());
solAssert(parentDef, "Enclosing Scope of EnumValue was not set"); solAssert(parentDef, "Enclosing Scope of EnumValue was not set");
return make_shared<EnumType>(*parentDef); return make_shared<EnumType>(*parentDef);
} }
@ -443,9 +444,9 @@ void InheritanceSpecifier::checkTypeRequirements()
for (ASTPointer<Expression> const& argument: m_arguments) for (ASTPointer<Expression> const& argument: m_arguments)
argument->checkTypeRequirements(nullptr); argument->checkTypeRequirements(nullptr);
ContractDefinition const* base = dynamic_cast<ContractDefinition const*>(&m_baseName->getReferencedDeclaration()); ContractDefinition const* base = dynamic_cast<ContractDefinition const*>(&m_baseName->referencedDeclaration());
solAssert(base, "Base contract not available."); solAssert(base, "Base contract not available.");
TypePointers parameterTypes = ContractType(*base).getConstructorType()->getParameterTypes(); TypePointers parameterTypes = ContractType(*base).constructorType()->parameterTypes();
if (!m_arguments.empty() && parameterTypes.size() != m_arguments.size()) if (!m_arguments.empty() && parameterTypes.size() != m_arguments.size())
BOOST_THROW_EXCEPTION(createTypeError( BOOST_THROW_EXCEPTION(createTypeError(
"Wrong argument count for constructor call: " + "Wrong argument count for constructor call: " +
@ -456,26 +457,26 @@ void InheritanceSpecifier::checkTypeRequirements()
)); ));
for (size_t i = 0; i < m_arguments.size(); ++i) for (size_t i = 0; i < m_arguments.size(); ++i)
if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i])) if (!m_arguments[i]->type()->isImplicitlyConvertibleTo(*parameterTypes[i]))
BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError(
"Invalid type for argument in constructor call. " "Invalid type for argument in constructor call. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
m_arguments[i]->getType()->toString() + m_arguments[i]->type()->toString() +
" to " + " to " +
parameterTypes[i]->toString() + parameterTypes[i]->toString() +
" requested." " requested."
)); ));
} }
TypePointer StructDefinition::getType(ContractDefinition const*) const TypePointer StructDefinition::type(ContractDefinition const*) const
{ {
return make_shared<TypeType>(make_shared<StructType>(*this)); return make_shared<TypeType>(make_shared<StructType>(*this));
} }
void StructDefinition::checkMemberTypes() const void StructDefinition::checkMemberTypes() const
{ {
for (ASTPointer<VariableDeclaration> const& member: getMembers()) for (ASTPointer<VariableDeclaration> const& member: members())
if (!member->getType()->canBeStored()) if (!member->type()->canBeStored())
BOOST_THROW_EXCEPTION(member->createTypeError("Type cannot be used in struct.")); BOOST_THROW_EXCEPTION(member->createTypeError("Type cannot be used in struct."));
} }
@ -488,17 +489,17 @@ void StructDefinition::checkRecursion() const
if (_parents.count(_struct)) if (_parents.count(_struct))
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
ParserError() << ParserError() <<
errinfo_sourceLocation(_struct->getLocation()) << errinfo_sourceLocation(_struct->location()) <<
errinfo_comment("Recursive struct definition.") errinfo_comment("Recursive struct definition.")
); );
set<StructDefinition const*> parents = _parents; set<StructDefinition const*> parents = _parents;
parents.insert(_struct); parents.insert(_struct);
for (ASTPointer<VariableDeclaration> const& member: _struct->getMembers()) for (ASTPointer<VariableDeclaration> const& member: _struct->members())
if (member->getType()->getCategory() == Type::Category::Struct) if (member->type()->category() == Type::Category::Struct)
{ {
auto const& typeName = dynamic_cast<UserDefinedTypeName const&>(*member->getTypeName()); auto const& typeName = dynamic_cast<UserDefinedTypeName const&>(*member->typeName());
check( check(
&dynamic_cast<StructDefinition const&>(*typeName.getReferencedDeclaration()), &dynamic_cast<StructDefinition const&>(*typeName.referencedDeclaration()),
parents parents
); );
} }
@ -506,28 +507,28 @@ void StructDefinition::checkRecursion() const
check(this, StructPointersSet{}); check(this, StructPointersSet{});
} }
TypePointer EnumDefinition::getType(ContractDefinition const*) const TypePointer EnumDefinition::type(ContractDefinition const*) const
{ {
return make_shared<TypeType>(make_shared<EnumType>(*this)); return make_shared<TypeType>(make_shared<EnumType>(*this));
} }
TypePointer FunctionDefinition::getType(ContractDefinition const*) const TypePointer FunctionDefinition::type(ContractDefinition const*) const
{ {
return make_shared<FunctionType>(*this); return make_shared<FunctionType>(*this);
} }
void FunctionDefinition::checkTypeRequirements() void FunctionDefinition::checkTypeRequirements()
{ {
for (ASTPointer<VariableDeclaration> const& var: getParameters() + getReturnParameters()) for (ASTPointer<VariableDeclaration> const& var: parameters() + returnParameters())
{ {
if (!var->getType()->canLiveOutsideStorage()) if (!var->type()->canLiveOutsideStorage())
BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage.")); BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage."));
if (getVisibility() >= Visibility::Public && !(var->getType()->externalType())) if (visibility() >= Visibility::Public && !(var->type()->externalType()))
BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed for public and external functions.")); BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed for public and external functions."));
} }
for (ASTPointer<ModifierInvocation> const& modifier: m_functionModifiers) for (ASTPointer<ModifierInvocation> const& modifier: m_functionModifiers)
modifier->checkTypeRequirements(isConstructor() ? modifier->checkTypeRequirements(isConstructor() ?
dynamic_cast<ContractDefinition const&>(*getScope()).getLinearizedBaseContracts() : dynamic_cast<ContractDefinition const&>(*scope()).linearizedBaseContracts() :
vector<ContractDefinition const*>()); vector<ContractDefinition const*>());
if (m_body) if (m_body)
m_body->checkTypeRequirements(); m_body->checkTypeRequirements();
@ -535,7 +536,7 @@ void FunctionDefinition::checkTypeRequirements()
string FunctionDefinition::externalSignature() const string FunctionDefinition::externalSignature() const
{ {
return FunctionType(*this).externalSignature(getName()); return FunctionType(*this).externalSignature(name());
} }
bool VariableDeclaration::isLValue() const bool VariableDeclaration::isLValue() const
@ -552,7 +553,7 @@ void VariableDeclaration::checkTypeRequirements()
// rules inherited from JavaScript. // rules inherited from JavaScript.
if (m_isConstant) if (m_isConstant)
{ {
if (!dynamic_cast<ContractDefinition const*>(getScope())) if (!dynamic_cast<ContractDefinition const*>(scope()))
BOOST_THROW_EXCEPTION(createTypeError("Illegal use of \"constant\" specifier.")); BOOST_THROW_EXCEPTION(createTypeError("Illegal use of \"constant\" specifier."));
if (!m_value) if (!m_value)
BOOST_THROW_EXCEPTION(createTypeError("Uninitialized \"constant\" variable.")); BOOST_THROW_EXCEPTION(createTypeError("Uninitialized \"constant\" variable."));
@ -572,13 +573,13 @@ void VariableDeclaration::checkTypeRequirements()
BOOST_THROW_EXCEPTION(createTypeError("Assignment necessary for type detection.")); BOOST_THROW_EXCEPTION(createTypeError("Assignment necessary for type detection."));
m_value->checkTypeRequirements(nullptr); m_value->checkTypeRequirements(nullptr);
TypePointer const& type = m_value->getType(); TypePointer const& type = m_value->type();
if ( if (
type->getCategory() == Type::Category::IntegerConstant && type->category() == Type::Category::IntegerConstant &&
!dynamic_pointer_cast<IntegerConstantType const>(type)->getIntegerType() !dynamic_pointer_cast<IntegerConstantType const>(type)->integerType()
) )
BOOST_THROW_EXCEPTION(m_value->createTypeError("Invalid integer constant " + type->toString() + ".")); BOOST_THROW_EXCEPTION(m_value->createTypeError("Invalid integer constant " + type->toString() + "."));
else if (type->getCategory() == Type::Category::Void) else if (type->category() == Type::Category::Void)
BOOST_THROW_EXCEPTION(createTypeError("Variable cannot have void type.")); BOOST_THROW_EXCEPTION(createTypeError("Variable cannot have void type."));
m_type = type->mobileType(); m_type = type->mobileType();
} }
@ -591,20 +592,20 @@ void VariableDeclaration::checkTypeRequirements()
"Type " + m_type->toString() + " is only valid in storage." "Type " + m_type->toString() + " is only valid in storage."
)); ));
} }
else if (getVisibility() >= Visibility::Public && !FunctionType(*this).externalType()) else if (visibility() >= Visibility::Public && !FunctionType(*this).externalType())
BOOST_THROW_EXCEPTION(createTypeError("Internal type is not allowed for public state variables.")); BOOST_THROW_EXCEPTION(createTypeError("Internal type is not allowed for public state variables."));
} }
bool VariableDeclaration::isCallableParameter() const bool VariableDeclaration::isCallableParameter() const
{ {
auto const* callable = dynamic_cast<CallableDeclaration const*>(getScope()); auto const* callable = dynamic_cast<CallableDeclaration const*>(scope());
if (!callable) if (!callable)
return false; return false;
for (auto const& variable: callable->getParameters()) for (auto const& variable: callable->parameters())
if (variable.get() == this) if (variable.get() == this)
return true; return true;
if (callable->getReturnParameterList()) if (callable->returnParameterList())
for (auto const& variable: callable->getReturnParameterList()->getParameters()) for (auto const& variable: callable->returnParameterList()->parameters())
if (variable.get() == this) if (variable.get() == this)
return true; return true;
return false; return false;
@ -612,16 +613,16 @@ bool VariableDeclaration::isCallableParameter() const
bool VariableDeclaration::isExternalCallableParameter() const bool VariableDeclaration::isExternalCallableParameter() const
{ {
auto const* callable = dynamic_cast<CallableDeclaration const*>(getScope()); auto const* callable = dynamic_cast<CallableDeclaration const*>(scope());
if (!callable || callable->getVisibility() != Declaration::Visibility::External) if (!callable || callable->visibility() != Declaration::Visibility::External)
return false; return false;
for (auto const& variable: callable->getParameters()) for (auto const& variable: callable->parameters())
if (variable.get() == this) if (variable.get() == this)
return true; return true;
return false; return false;
} }
TypePointer ModifierDefinition::getType(ContractDefinition const*) const TypePointer ModifierDefinition::type(ContractDefinition const*) const
{ {
return make_shared<ModifierType>(*this); return make_shared<ModifierType>(*this);
} }
@ -637,22 +638,22 @@ void ModifierInvocation::checkTypeRequirements(vector<ContractDefinition const*>
for (ASTPointer<Expression> const& argument: m_arguments) for (ASTPointer<Expression> const& argument: m_arguments)
{ {
argument->checkTypeRequirements(nullptr); argument->checkTypeRequirements(nullptr);
argumentTypes.push_back(argument->getType()); argumentTypes.push_back(argument->type());
} }
m_modifierName->checkTypeRequirements(&argumentTypes); m_modifierName->checkTypeRequirements(&argumentTypes);
auto const* declaration = &m_modifierName->getReferencedDeclaration(); auto const* declaration = &m_modifierName->referencedDeclaration();
vector<ASTPointer<VariableDeclaration>> emptyParameterList; vector<ASTPointer<VariableDeclaration>> emptyParameterList;
vector<ASTPointer<VariableDeclaration>> const* parameters = nullptr; vector<ASTPointer<VariableDeclaration>> const* parameters = nullptr;
if (auto modifier = dynamic_cast<ModifierDefinition const*>(declaration)) if (auto modifier = dynamic_cast<ModifierDefinition const*>(declaration))
parameters = &modifier->getParameters(); parameters = &modifier->parameters();
else else
// check parameters for Base constructors // check parameters for Base constructors
for (ContractDefinition const* base: _bases) for (ContractDefinition const* base: _bases)
if (declaration == base) if (declaration == base)
{ {
if (auto referencedConstructor = base->getConstructor()) if (auto referencedConstructor = base->constructor())
parameters = &referencedConstructor->getParameters(); parameters = &referencedConstructor->parameters();
else else
parameters = &emptyParameterList; parameters = &emptyParameterList;
break; break;
@ -668,13 +669,13 @@ void ModifierInvocation::checkTypeRequirements(vector<ContractDefinition const*>
"." "."
)); ));
for (size_t i = 0; i < m_arguments.size(); ++i) for (size_t i = 0; i < m_arguments.size(); ++i)
if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*(*parameters)[i]->getType())) if (!m_arguments[i]->type()->isImplicitlyConvertibleTo(*(*parameters)[i]->type()))
BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError(
"Invalid type for argument in modifier invocation. " "Invalid type for argument in modifier invocation. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
m_arguments[i]->getType()->toString() + m_arguments[i]->type()->toString() +
" to " + " to " +
(*parameters)[i]->getType()->toString() + (*parameters)[i]->type()->toString() +
" requested." " requested."
)); ));
} }
@ -682,13 +683,13 @@ void ModifierInvocation::checkTypeRequirements(vector<ContractDefinition const*>
void EventDefinition::checkTypeRequirements() void EventDefinition::checkTypeRequirements()
{ {
int numIndexed = 0; int numIndexed = 0;
for (ASTPointer<VariableDeclaration> const& var: getParameters()) for (ASTPointer<VariableDeclaration> const& var: parameters())
{ {
if (var->isIndexed()) if (var->isIndexed())
numIndexed++; numIndexed++;
if (!var->getType()->canLiveOutsideStorage()) if (!var->type()->canLiveOutsideStorage())
BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage.")); BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage."));
if (!var->getType()->externalType()) if (!var->type()->externalType())
BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed as event parameter type.")); BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed as event parameter type."));
} }
if (numIndexed > 3) if (numIndexed > 3)
@ -732,12 +733,12 @@ void Return::checkTypeRequirements()
return; return;
if (!m_returnParameters) if (!m_returnParameters)
BOOST_THROW_EXCEPTION(createTypeError("Return arguments not allowed.")); BOOST_THROW_EXCEPTION(createTypeError("Return arguments not allowed."));
if (m_returnParameters->getParameters().size() != 1) if (m_returnParameters->parameters().size() != 1)
BOOST_THROW_EXCEPTION(createTypeError("Different number of arguments in return statement " BOOST_THROW_EXCEPTION(createTypeError("Different number of arguments in return statement "
"than in returns declaration.")); "than in returns declaration."));
// this could later be changed such that the paramaters type is an anonymous struct type, // this could later be changed such that the paramaters type is an anonymous struct type,
// but for now, we only allow one return parameter // but for now, we only allow one return parameter
m_expression->expectType(*m_returnParameters->getParameters().front()->getType()); m_expression->expectType(*m_returnParameters->parameters().front()->type());
} }
void VariableDeclarationStatement::checkTypeRequirements() void VariableDeclarationStatement::checkTypeRequirements()
@ -749,9 +750,9 @@ void Assignment::checkTypeRequirements(TypePointers const*)
{ {
m_leftHandSide->checkTypeRequirements(nullptr); m_leftHandSide->checkTypeRequirements(nullptr);
m_leftHandSide->requireLValue(); m_leftHandSide->requireLValue();
if (m_leftHandSide->getType()->getCategory() == Type::Category::Mapping) if (m_leftHandSide->type()->category() == Type::Category::Mapping)
BOOST_THROW_EXCEPTION(createTypeError("Mappings cannot be assigned to.")); BOOST_THROW_EXCEPTION(createTypeError("Mappings cannot be assigned to."));
m_type = m_leftHandSide->getType(); m_type = m_leftHandSide->type();
if (m_assigmentOperator == Token::Assign) if (m_assigmentOperator == Token::Assign)
m_rightHandSide->expectType(*m_type); m_rightHandSide->expectType(*m_type);
else else
@ -759,35 +760,37 @@ void Assignment::checkTypeRequirements(TypePointers const*)
// compound assignment // compound assignment
m_rightHandSide->checkTypeRequirements(nullptr); m_rightHandSide->checkTypeRequirements(nullptr);
TypePointer resultType = m_type->binaryOperatorResult(Token::AssignmentToBinaryOp(m_assigmentOperator), TypePointer resultType = m_type->binaryOperatorResult(Token::AssignmentToBinaryOp(m_assigmentOperator),
m_rightHandSide->getType()); m_rightHandSide->type());
if (!resultType || *resultType != *m_type) if (!resultType || *resultType != *m_type)
BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_assigmentOperator)) + BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_assigmentOperator)) +
" not compatible with types " + " not compatible with types " +
m_type->toString() + " and " + m_type->toString() + " and " +
m_rightHandSide->getType()->toString())); m_rightHandSide->type()->toString()));
} }
} }
void ExpressionStatement::checkTypeRequirements() void ExpressionStatement::checkTypeRequirements()
{ {
m_expression->checkTypeRequirements(nullptr); m_expression->checkTypeRequirements(nullptr);
if (m_expression->getType()->getCategory() == Type::Category::IntegerConstant) if (m_expression->type()->category() == Type::Category::IntegerConstant)
if (!dynamic_pointer_cast<IntegerConstantType const>(m_expression->getType())->getIntegerType()) if (!dynamic_pointer_cast<IntegerConstantType const>(m_expression->type())->integerType())
BOOST_THROW_EXCEPTION(m_expression->createTypeError("Invalid integer constant.")); BOOST_THROW_EXCEPTION(m_expression->createTypeError("Invalid integer constant."));
} }
void Expression::expectType(Type const& _expectedType) void Expression::expectType(Type const& _expectedType)
{ {
checkTypeRequirements(nullptr); checkTypeRequirements(nullptr);
Type const& type = *getType(); Type const& currentType = *type();
if (!type.isImplicitlyConvertibleTo(_expectedType)) if (!currentType.isImplicitlyConvertibleTo(_expectedType))
BOOST_THROW_EXCEPTION(createTypeError( BOOST_THROW_EXCEPTION(
"Type " + createTypeError(
type.toString() + "Type " +
" is not implicitly convertible to expected type " + currentType.toString() +
_expectedType.toString() + " is not implicitly convertible to expected type " +
"." _expectedType.toString() +
)); "."
)
);
} }
void Expression::requireLValue() void Expression::requireLValue()
@ -803,7 +806,7 @@ void UnaryOperation::checkTypeRequirements(TypePointers const*)
m_subExpression->checkTypeRequirements(nullptr); m_subExpression->checkTypeRequirements(nullptr);
if (m_operator == Token::Value::Inc || m_operator == Token::Value::Dec || m_operator == Token::Value::Delete) if (m_operator == Token::Value::Inc || m_operator == Token::Value::Dec || m_operator == Token::Value::Delete)
m_subExpression->requireLValue(); m_subExpression->requireLValue();
m_type = m_subExpression->getType()->unaryOperatorResult(m_operator); m_type = m_subExpression->type()->unaryOperatorResult(m_operator);
if (!m_type) if (!m_type)
BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type.")); BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type."));
} }
@ -812,12 +815,12 @@ void BinaryOperation::checkTypeRequirements(TypePointers const*)
{ {
m_left->checkTypeRequirements(nullptr); m_left->checkTypeRequirements(nullptr);
m_right->checkTypeRequirements(nullptr); m_right->checkTypeRequirements(nullptr);
m_commonType = m_left->getType()->binaryOperatorResult(m_operator, m_right->getType()); m_commonType = m_left->type()->binaryOperatorResult(m_operator, m_right->type());
if (!m_commonType) if (!m_commonType)
BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_operator)) + BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_operator)) +
" not compatible with types " + " not compatible with types " +
m_left->getType()->toString() + " and " + m_left->type()->toString() + " and " +
m_right->getType()->toString())); m_right->type()->toString()));
m_type = Token::isCompareOp(m_operator) ? make_shared<BoolType>() : m_commonType; m_type = Token::isCompareOp(m_operator) ? make_shared<BoolType>() : m_commonType;
} }
@ -833,12 +836,12 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
argument->checkTypeRequirements(nullptr); argument->checkTypeRequirements(nullptr);
// only store them for positional calls // only store them for positional calls
if (isPositionalCall) if (isPositionalCall)
argumentTypes.push_back(argument->getType()); argumentTypes.push_back(argument->type());
} }
m_expression->checkTypeRequirements(isPositionalCall ? &argumentTypes : nullptr); m_expression->checkTypeRequirements(isPositionalCall ? &argumentTypes : nullptr);
TypePointer const& expressionType = m_expression->getType(); TypePointer const& expressionType = m_expression->type();
FunctionTypePointer functionType; FunctionTypePointer functionType;
if (isTypeConversion()) if (isTypeConversion())
{ {
@ -847,8 +850,8 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
BOOST_THROW_EXCEPTION(createTypeError("Exactly one argument expected for explicit type conversion.")); BOOST_THROW_EXCEPTION(createTypeError("Exactly one argument expected for explicit type conversion."));
if (!isPositionalCall) if (!isPositionalCall)
BOOST_THROW_EXCEPTION(createTypeError("Type conversion cannot allow named arguments.")); BOOST_THROW_EXCEPTION(createTypeError("Type conversion cannot allow named arguments."));
m_type = type.getActualType(); m_type = type.actualType();
auto argType = m_arguments.front()->getType(); auto argType = m_arguments.front()->type();
if (auto argRefType = dynamic_cast<ReferenceType const*>(argType.get())) if (auto argRefType = dynamic_cast<ReferenceType const*>(argType.get()))
// do not change the data location when converting // do not change the data location when converting
// (data location cannot yet be specified for type conversions) // (data location cannot yet be specified for type conversions)
@ -864,7 +867,7 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
if (isStructConstructorCall()) if (isStructConstructorCall())
{ {
TypeType const& type = dynamic_cast<TypeType const&>(*expressionType); TypeType const& type = dynamic_cast<TypeType const&>(*expressionType);
auto const& structType = dynamic_cast<StructType const&>(*type.getActualType()); auto const& structType = dynamic_cast<StructType const&>(*type.actualType());
functionType = structType.constructorType(); functionType = structType.constructorType();
membersRemovedForStructConstructor = structType.membersMissingInMemory(); membersRemovedForStructConstructor = structType.membersMissingInMemory();
} }
@ -877,7 +880,7 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
//@todo would be nice to create a struct type from the arguments //@todo would be nice to create a struct type from the arguments
// and then ask if that is implicitly convertible to the struct represented by the // and then ask if that is implicitly convertible to the struct represented by the
// function parameters // function parameters
TypePointers const& parameterTypes = functionType->getParameterTypes(); TypePointers const& parameterTypes = functionType->parameterTypes();
if (!functionType->takesArbitraryParameters() && parameterTypes.size() != m_arguments.size()) if (!functionType->takesArbitraryParameters() && parameterTypes.size() != m_arguments.size())
{ {
string msg = string msg =
@ -902,12 +905,12 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
for (size_t i = 0; i < m_arguments.size(); ++i) for (size_t i = 0; i < m_arguments.size(); ++i)
if ( if (
!functionType->takesArbitraryParameters() && !functionType->takesArbitraryParameters() &&
!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i]) !m_arguments[i]->type()->isImplicitlyConvertibleTo(*parameterTypes[i])
) )
BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError(
"Invalid type for argument in function call. " "Invalid type for argument in function call. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
m_arguments[i]->getType()->toString() + m_arguments[i]->type()->toString() +
" to " + " to " +
parameterTypes[i]->toString() + parameterTypes[i]->toString() +
" requested." " requested."
@ -920,7 +923,7 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
BOOST_THROW_EXCEPTION(createTypeError( BOOST_THROW_EXCEPTION(createTypeError(
"Named arguments cannnot be used for functions that take arbitrary parameters." "Named arguments cannnot be used for functions that take arbitrary parameters."
)); ));
auto const& parameterNames = functionType->getParameterNames(); auto const& parameterNames = functionType->parameterNames();
if (parameterNames.size() != m_names.size()) if (parameterNames.size() != m_names.size())
BOOST_THROW_EXCEPTION(createTypeError("Some argument names are missing.")); BOOST_THROW_EXCEPTION(createTypeError("Some argument names are missing."));
@ -935,11 +938,11 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
for (size_t j = 0; j < parameterNames.size(); j++) { for (size_t j = 0; j < parameterNames.size(); j++) {
if (parameterNames[j] == *m_names[i]) { if (parameterNames[j] == *m_names[i]) {
// check type convertible // check type convertible
if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[j])) if (!m_arguments[i]->type()->isImplicitlyConvertibleTo(*parameterTypes[j]))
BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError( BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError(
"Invalid type for argument in function call. " "Invalid type for argument in function call. "
"Invalid implicit conversion from " + "Invalid implicit conversion from " +
m_arguments[i]->getType()->toString() + m_arguments[i]->type()->toString() +
" to " + " to " +
parameterTypes[i]->toString() + parameterTypes[i]->toString() +
" requested." " requested."
@ -957,21 +960,21 @@ void FunctionCall::checkTypeRequirements(TypePointers const*)
// @todo actually the return type should be an anonymous struct, // @todo actually the return type should be an anonymous struct,
// but we change it to the type of the first return value until we have anonymous // but we change it to the type of the first return value until we have anonymous
// structs and tuples // structs and tuples
if (functionType->getReturnParameterTypes().empty()) if (functionType->returnParameterTypes().empty())
m_type = make_shared<VoidType>(); m_type = make_shared<VoidType>();
else else
m_type = functionType->getReturnParameterTypes().front(); m_type = functionType->returnParameterTypes().front();
} }
bool FunctionCall::isTypeConversion() const bool FunctionCall::isTypeConversion() const
{ {
return m_expression->getType()->getCategory() == Type::Category::TypeType && !isStructConstructorCall(); return m_expression->type()->category() == Type::Category::TypeType && !isStructConstructorCall();
} }
bool FunctionCall::isStructConstructorCall() const bool FunctionCall::isStructConstructorCall() const
{ {
if (auto const* type = dynamic_cast<TypeType const*>(m_expression->getType().get())) if (auto const* type = dynamic_cast<TypeType const*>(m_expression->type().get()))
return type->getActualType()->getCategory() == Type::Category::Struct; return type->actualType()->category() == Type::Category::Struct;
else else
return false; return false;
} }
@ -979,13 +982,13 @@ bool FunctionCall::isStructConstructorCall() const
void NewExpression::checkTypeRequirements(TypePointers const*) void NewExpression::checkTypeRequirements(TypePointers const*)
{ {
m_contractName->checkTypeRequirements(nullptr); m_contractName->checkTypeRequirements(nullptr);
m_contract = dynamic_cast<ContractDefinition const*>(&m_contractName->getReferencedDeclaration()); m_contract = dynamic_cast<ContractDefinition const*>(&m_contractName->referencedDeclaration());
if (!m_contract) if (!m_contract)
BOOST_THROW_EXCEPTION(createTypeError("Identifier is not a contract.")); BOOST_THROW_EXCEPTION(createTypeError("Identifier is not a contract."));
if (!m_contract->isFullyImplemented()) if (!m_contract->isFullyImplemented())
BOOST_THROW_EXCEPTION(createTypeError("Trying to create an instance of an abstract contract.")); BOOST_THROW_EXCEPTION(createTypeError("Trying to create an instance of an abstract contract."));
shared_ptr<ContractType const> contractType = make_shared<ContractType>(*m_contract); shared_ptr<ContractType const> contractType = make_shared<ContractType>(*m_contract);
TypePointers const& parameterTypes = contractType->getConstructorType()->getParameterTypes(); TypePointers const& parameterTypes = contractType->constructorType()->parameterTypes();
m_type = make_shared<FunctionType>( m_type = make_shared<FunctionType>(
parameterTypes, parameterTypes,
TypePointers{contractType}, TypePointers{contractType},
@ -997,15 +1000,15 @@ void NewExpression::checkTypeRequirements(TypePointers const*)
void MemberAccess::checkTypeRequirements(TypePointers const* _argumentTypes) void MemberAccess::checkTypeRequirements(TypePointers const* _argumentTypes)
{ {
m_expression->checkTypeRequirements(nullptr); m_expression->checkTypeRequirements(nullptr);
Type const& type = *m_expression->getType(); Type const& type = *m_expression->type();
MemberList::MemberMap possibleMembers = type.getMembers().membersByName(*m_memberName); MemberList::MemberMap possibleMembers = type.members().membersByName(*m_memberName);
if (possibleMembers.size() > 1 && _argumentTypes) if (possibleMembers.size() > 1 && _argumentTypes)
{ {
// do override resolution // do override resolution
for (auto it = possibleMembers.begin(); it != possibleMembers.end();) for (auto it = possibleMembers.begin(); it != possibleMembers.end();)
if ( if (
it->type->getCategory() == Type::Category::Function && it->type->category() == Type::Category::Function &&
!dynamic_cast<FunctionType const&>(*it->type).canTakeArguments(*_argumentTypes) !dynamic_cast<FunctionType const&>(*it->type).canTakeArguments(*_argumentTypes)
) )
it = possibleMembers.erase(it); it = possibleMembers.erase(it);
@ -1016,9 +1019,9 @@ void MemberAccess::checkTypeRequirements(TypePointers const* _argumentTypes)
{ {
auto storageType = ReferenceType::copyForLocationIfReference( auto storageType = ReferenceType::copyForLocationIfReference(
DataLocation::Storage, DataLocation::Storage,
m_expression->getType() m_expression->type()
); );
if (!storageType->getMembers().membersByName(*m_memberName).empty()) if (!storageType->members().membersByName(*m_memberName).empty())
BOOST_THROW_EXCEPTION(createTypeError( BOOST_THROW_EXCEPTION(createTypeError(
"Member \"" + *m_memberName + "\" is not available in " + "Member \"" + *m_memberName + "\" is not available in " +
type.toString() + type.toString() +
@ -1037,9 +1040,9 @@ void MemberAccess::checkTypeRequirements(TypePointers const* _argumentTypes)
m_referencedDeclaration = possibleMembers.front().declaration; m_referencedDeclaration = possibleMembers.front().declaration;
m_type = possibleMembers.front().type; m_type = possibleMembers.front().type;
if (type.getCategory() == Type::Category::Struct) if (type.category() == Type::Category::Struct)
m_isLValue = true; m_isLValue = true;
else if (type.getCategory() == Type::Category::Array) else if (type.category() == Type::Category::Array)
{ {
auto const& arrayType(dynamic_cast<ArrayType const&>(type)); auto const& arrayType(dynamic_cast<ArrayType const&>(type));
m_isLValue = ( m_isLValue = (
@ -1055,11 +1058,11 @@ void MemberAccess::checkTypeRequirements(TypePointers const* _argumentTypes)
void IndexAccess::checkTypeRequirements(TypePointers const*) void IndexAccess::checkTypeRequirements(TypePointers const*)
{ {
m_base->checkTypeRequirements(nullptr); m_base->checkTypeRequirements(nullptr);
switch (m_base->getType()->getCategory()) switch (m_base->type()->category())
{ {
case Type::Category::Array: case Type::Category::Array:
{ {
ArrayType const& type = dynamic_cast<ArrayType const&>(*m_base->getType()); ArrayType const& type = dynamic_cast<ArrayType const&>(*m_base->type());
if (!m_index) if (!m_index)
BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted.")); BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted."));
if (type.isString()) if (type.isString())
@ -1068,33 +1071,33 @@ void IndexAccess::checkTypeRequirements(TypePointers const*)
if (type.isByteArray()) if (type.isByteArray())
m_type = make_shared<FixedBytesType>(1); m_type = make_shared<FixedBytesType>(1);
else else
m_type = type.getBaseType(); m_type = type.baseType();
m_isLValue = type.location() != DataLocation::CallData; m_isLValue = type.location() != DataLocation::CallData;
break; break;
} }
case Type::Category::Mapping: case Type::Category::Mapping:
{ {
MappingType const& type = dynamic_cast<MappingType const&>(*m_base->getType()); MappingType const& type = dynamic_cast<MappingType const&>(*m_base->type());
if (!m_index) if (!m_index)
BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted.")); BOOST_THROW_EXCEPTION(createTypeError("Index expression cannot be omitted."));
m_index->expectType(*type.getKeyType()); m_index->expectType(*type.keyType());
m_type = type.getValueType(); m_type = type.valueType();
m_isLValue = true; m_isLValue = true;
break; break;
} }
case Type::Category::TypeType: case Type::Category::TypeType:
{ {
TypeType const& type = dynamic_cast<TypeType const&>(*m_base->getType()); TypeType const& type = dynamic_cast<TypeType const&>(*m_base->type());
if (!m_index) if (!m_index)
m_type = make_shared<TypeType>(make_shared<ArrayType>(DataLocation::Memory, type.getActualType())); m_type = make_shared<TypeType>(make_shared<ArrayType>(DataLocation::Memory, type.actualType()));
else else
{ {
m_index->checkTypeRequirements(nullptr); m_index->checkTypeRequirements(nullptr);
auto length = dynamic_cast<IntegerConstantType const*>(m_index->getType().get()); auto length = dynamic_cast<IntegerConstantType const*>(m_index->type().get());
if (!length) if (!length)
BOOST_THROW_EXCEPTION(m_index->createTypeError("Integer constant expected.")); BOOST_THROW_EXCEPTION(m_index->createTypeError("Integer constant expected."));
m_type = make_shared<TypeType>(make_shared<ArrayType>( m_type = make_shared<TypeType>(make_shared<ArrayType>(
DataLocation::Memory, type.getActualType(), DataLocation::Memory, type.actualType(),
length->literalValue(nullptr) length->literalValue(nullptr)
)); ));
} }
@ -1102,7 +1105,7 @@ void IndexAccess::checkTypeRequirements(TypePointers const*)
} }
default: default:
BOOST_THROW_EXCEPTION(m_base->createTypeError( BOOST_THROW_EXCEPTION(m_base->createTypeError(
"Indexed expression has to be a type, mapping or array (is " + m_base->getType()->toString() + ")")); "Indexed expression has to be a type, mapping or array (is " + m_base->type()->toString() + ")"));
} }
} }
@ -1116,12 +1119,12 @@ void Identifier::checkTypeRequirements(TypePointers const* _argumentTypes)
} }
solAssert(!!m_referencedDeclaration, "Referenced declaration is null after overload resolution."); solAssert(!!m_referencedDeclaration, "Referenced declaration is null after overload resolution.");
m_isLValue = m_referencedDeclaration->isLValue(); m_isLValue = m_referencedDeclaration->isLValue();
m_type = m_referencedDeclaration->getType(m_currentContract); m_type = m_referencedDeclaration->type(m_currentContract);
if (!m_type) if (!m_type)
BOOST_THROW_EXCEPTION(createTypeError("Declaration referenced before type could be determined.")); BOOST_THROW_EXCEPTION(createTypeError("Declaration referenced before type could be determined."));
} }
Declaration const& Identifier::getReferencedDeclaration() const Declaration const& Identifier::referencedDeclaration() const
{ {
solAssert(!!m_referencedDeclaration, "Identifier not resolved."); solAssert(!!m_referencedDeclaration, "Identifier not resolved.");
return *m_referencedDeclaration; return *m_referencedDeclaration;
@ -1138,7 +1141,7 @@ void Identifier::overloadResolution(TypePointers const& _argumentTypes)
for (Declaration const* declaration: m_overloadedDeclarations) for (Declaration const* declaration: m_overloadedDeclarations)
{ {
TypePointer const& function = declaration->getType(); TypePointer const& function = declaration->type();
auto const* functionType = dynamic_cast<FunctionType const*>(function.get()); auto const* functionType = dynamic_cast<FunctionType const*>(function.get());
if (functionType && functionType->canTakeArguments(_argumentTypes)) if (functionType && functionType->canTakeArguments(_argumentTypes))
possibles.push_back(declaration); possibles.push_back(declaration);

View File

@ -71,7 +71,7 @@ public:
} }
/// Returns the source code location of this node. /// Returns the source code location of this node.
SourceLocation const& getLocation() const { return m_location; } SourceLocation const& location() const { return m_location; }
/// Creates a @ref TypeError exception and decorates it with the location of the node and /// Creates a @ref TypeError exception and decorates it with the location of the node and
/// the given description /// the given description
@ -100,7 +100,7 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
std::vector<ASTPointer<ASTNode>> getNodes() const { return m_nodes; } std::vector<ASTPointer<ASTNode>> nodes() const { return m_nodes; }
private: private:
std::vector<ASTPointer<ASTNode>> m_nodes; std::vector<ASTPointer<ASTNode>> m_nodes;
@ -120,7 +120,7 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
ASTString const& getIdentifier() const { return *m_identifier; } ASTString const& identifier() const { return *m_identifier; }
private: private:
ASTPointer<ASTString> m_identifier; ASTPointer<ASTString> m_identifier;
@ -140,26 +140,26 @@ public:
ASTNode(_location), m_name(_name), m_visibility(_visibility), m_scope(nullptr) {} ASTNode(_location), m_name(_name), m_visibility(_visibility), m_scope(nullptr) {}
/// @returns the declared name. /// @returns the declared name.
ASTString const& getName() const { return *m_name; } ASTString const& name() const { return *m_name; }
Visibility getVisibility() const { return m_visibility == Visibility::Default ? getDefaultVisibility() : m_visibility; } Visibility visibility() const { return m_visibility == Visibility::Default ? defaultVisibility() : m_visibility; }
bool isPublic() const { return getVisibility() >= Visibility::Public; } bool isPublic() const { return visibility() >= Visibility::Public; }
virtual bool isVisibleInContract() const { return getVisibility() != Visibility::External; } virtual bool isVisibleInContract() const { return visibility() != Visibility::External; }
bool isVisibleInDerivedContracts() const { return isVisibleInContract() && getVisibility() >= Visibility::Internal; } bool isVisibleInDerivedContracts() const { return isVisibleInContract() && visibility() >= Visibility::Internal; }
/// @returns the scope this declaration resides in. Can be nullptr if it is the global scope. /// @returns the scope this declaration resides in. Can be nullptr if it is the global scope.
/// Available only after name and type resolution step. /// Available only after name and type resolution step.
Declaration const* getScope() const { return m_scope; } Declaration const* scope() const { return m_scope; }
void setScope(Declaration const* _scope) { m_scope = _scope; } void setScope(Declaration const* _scope) { m_scope = _scope; }
/// @returns the type of expressions referencing this declaration. /// @returns the type of expressions referencing this declaration.
/// The current contract has to be given since this context can change the type, especially of /// The current contract has to be given since this context can change the type, especially of
/// contract types. /// contract types.
virtual TypePointer getType(ContractDefinition const* m_currentContract = nullptr) const = 0; virtual TypePointer type(ContractDefinition const* m_currentContract = nullptr) const = 0;
virtual bool isLValue() const { return false; } virtual bool isLValue() const { return false; }
virtual bool isPartOfExternalInterface() const { return false; } virtual bool isPartOfExternalInterface() const { return false; }
protected: protected:
virtual Visibility getDefaultVisibility() const { return Visibility::Public; } virtual Visibility defaultVisibility() const { return Visibility::Public; }
private: private:
ASTPointer<ASTString> m_name; ASTPointer<ASTString> m_name;
@ -174,7 +174,7 @@ class VariableScope
{ {
public: public:
void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); } void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); }
std::vector<VariableDeclaration const*> const& getLocalVariables() const { return m_localVariables; } std::vector<VariableDeclaration const*> const& localVariables() const { return m_localVariables; }
private: private:
std::vector<VariableDeclaration const*> m_localVariables; std::vector<VariableDeclaration const*> m_localVariables;
@ -190,7 +190,7 @@ public:
/// @return A shared pointer of an ASTString. /// @return A shared pointer of an ASTString.
/// Can contain a nullptr in which case indicates absence of documentation /// Can contain a nullptr in which case indicates absence of documentation
ASTPointer<ASTString> const& getDocumentation() const { return m_documentation; } ASTPointer<ASTString> const& documentation() const { return m_documentation; }
protected: protected:
ASTPointer<ASTString> m_documentation; ASTPointer<ASTString> m_documentation;
@ -249,16 +249,16 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
std::vector<ASTPointer<InheritanceSpecifier>> const& getBaseContracts() const { return m_baseContracts; } std::vector<ASTPointer<InheritanceSpecifier>> const& baseContracts() const { return m_baseContracts; }
std::vector<ASTPointer<StructDefinition>> const& getDefinedStructs() const { return m_definedStructs; } std::vector<ASTPointer<StructDefinition>> const& definedStructs() const { return m_definedStructs; }
std::vector<ASTPointer<EnumDefinition>> const& getDefinedEnums() const { return m_definedEnums; } std::vector<ASTPointer<EnumDefinition>> const& definedEnums() const { return m_definedEnums; }
std::vector<ASTPointer<VariableDeclaration>> const& getStateVariables() const { return m_stateVariables; } std::vector<ASTPointer<VariableDeclaration>> const& stateVariables() const { return m_stateVariables; }
std::vector<ASTPointer<ModifierDefinition>> const& getFunctionModifiers() const { return m_functionModifiers; } std::vector<ASTPointer<ModifierDefinition>> const& functionModifiers() const { return m_functionModifiers; }
std::vector<ASTPointer<FunctionDefinition>> const& getDefinedFunctions() const { return m_definedFunctions; } std::vector<ASTPointer<FunctionDefinition>> const& definedFunctions() const { return m_definedFunctions; }
std::vector<ASTPointer<EventDefinition>> const& getEvents() const { return m_events; } std::vector<ASTPointer<EventDefinition>> const& events() const { return m_events; }
std::vector<ASTPointer<EventDefinition>> const& getInterfaceEvents() const; std::vector<ASTPointer<EventDefinition>> const& interfaceEvents() const;
virtual TypePointer getType(ContractDefinition const* m_currentContract) const override; virtual TypePointer type(ContractDefinition const* m_currentContract) const override;
/// Checks that there are no illegal overrides, that the constructor does not have a "returns" /// Checks that there are no illegal overrides, that the constructor does not have a "returns"
/// and calls checkTypeRequirements on all its functions. /// and calls checkTypeRequirements on all its functions.
@ -266,20 +266,20 @@ public:
/// @returns a map of canonical function signatures to FunctionDefinitions /// @returns a map of canonical function signatures to FunctionDefinitions
/// as intended for use by the ABI. /// as intended for use by the ABI.
std::map<FixedHash<4>, FunctionTypePointer> getInterfaceFunctions() const; std::map<FixedHash<4>, FunctionTypePointer> interfaceFunctions() const;
/// @returns a list of the inheritable members of this contract /// @returns a list of the inheritable members of this contract
std::vector<Declaration const*> const& getInheritableMembers() const; std::vector<Declaration const*> const& inheritableMembers() const;
/// List of all (direct and indirect) base contracts in order from derived to base, including /// List of all (direct and indirect) base contracts in order from derived to base, including
/// the contract itself. Available after name resolution /// the contract itself. Available after name resolution
std::vector<ContractDefinition const*> const& getLinearizedBaseContracts() const { return m_linearizedBaseContracts; } std::vector<ContractDefinition const*> const& linearizedBaseContracts() const { return m_linearizedBaseContracts; }
void setLinearizedBaseContracts(std::vector<ContractDefinition const*> const& _bases) { m_linearizedBaseContracts = _bases; } void setLinearizedBaseContracts(std::vector<ContractDefinition const*> const& _bases) { m_linearizedBaseContracts = _bases; }
/// Returns the constructor or nullptr if no constructor was specified. /// Returns the constructor or nullptr if no constructor was specified.
FunctionDefinition const* getConstructor() const; FunctionDefinition const* constructor() const;
/// Returns the fallback function or nullptr if no fallback function was specified. /// Returns the fallback function or nullptr if no fallback function was specified.
FunctionDefinition const* getFallbackFunction() const; FunctionDefinition const* fallbackFunction() const;
std::string const& userDocumentation() const; std::string const& userDocumentation() const;
void setUserDocumentation(std::string const& _userDocumentation); void setUserDocumentation(std::string const& _userDocumentation);
@ -298,7 +298,7 @@ private:
/// external argument types (i.e. different signature). /// external argument types (i.e. different signature).
void checkExternalTypeClashes() const; void checkExternalTypeClashes() const;
std::vector<std::pair<FixedHash<4>, FunctionTypePointer>> const& getInterfaceFunctionList() const; std::vector<std::pair<FixedHash<4>, FunctionTypePointer>> const& interfaceFunctionList() const;
std::vector<ASTPointer<InheritanceSpecifier>> m_baseContracts; std::vector<ASTPointer<InheritanceSpecifier>> m_baseContracts;
std::vector<ASTPointer<StructDefinition>> m_definedStructs; std::vector<ASTPointer<StructDefinition>> m_definedStructs;
@ -328,8 +328,8 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
ASTPointer<Identifier> const& getName() const { return m_baseName; } ASTPointer<Identifier> const& name() const { return m_baseName; }
std::vector<ASTPointer<Expression>> const& getArguments() const { return m_arguments; } std::vector<ASTPointer<Expression>> const& arguments() const { return m_arguments; }
void checkTypeRequirements(); void checkTypeRequirements();
@ -348,9 +348,9 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
std::vector<ASTPointer<VariableDeclaration>> const& getMembers() const { return m_members; } std::vector<ASTPointer<VariableDeclaration>> const& members() const { return m_members; }
virtual TypePointer getType(ContractDefinition const*) const override; virtual TypePointer type(ContractDefinition const*) const override;
/// Checks that the members do not include any recursive structs and have valid types /// Checks that the members do not include any recursive structs and have valid types
/// (e.g. no functions). /// (e.g. no functions).
@ -373,9 +373,9 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
std::vector<ASTPointer<EnumValue>> const& getMembers() const { return m_members; } std::vector<ASTPointer<EnumValue>> const& members() const { return m_members; }
virtual TypePointer getType(ContractDefinition const*) const override; virtual TypePointer type(ContractDefinition const*) const override;
private: private:
std::vector<ASTPointer<EnumValue>> m_members; std::vector<ASTPointer<EnumValue>> m_members;
@ -393,7 +393,7 @@ class EnumValue: public Declaration
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual TypePointer getType(ContractDefinition const* = nullptr) const override; virtual TypePointer type(ContractDefinition const* = nullptr) const override;
}; };
/** /**
@ -410,7 +410,7 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
std::vector<ASTPointer<VariableDeclaration>> const& getParameters() const { return m_parameters; } std::vector<ASTPointer<VariableDeclaration>> const& parameters() const { return m_parameters; }
private: private:
std::vector<ASTPointer<VariableDeclaration>> m_parameters; std::vector<ASTPointer<VariableDeclaration>> m_parameters;
@ -436,9 +436,9 @@ public:
{ {
} }
std::vector<ASTPointer<VariableDeclaration>> const& getParameters() const { return m_parameters->getParameters(); } std::vector<ASTPointer<VariableDeclaration>> const& parameters() const { return m_parameters->parameters(); }
ParameterList const& getParameterList() const { return *m_parameters; } ParameterList const& parameterList() const { return *m_parameters; }
ASTPointer<ParameterList> const& getReturnParameterList() const { return m_returnParameters; } ASTPointer<ParameterList> const& returnParameterList() const { return m_returnParameters; }
protected: protected:
ASTPointer<ParameterList> m_parameters; ASTPointer<ParameterList> m_parameters;
@ -474,16 +474,16 @@ public:
bool isConstructor() const { return m_isConstructor; } bool isConstructor() const { return m_isConstructor; }
bool isDeclaredConst() const { return m_isDeclaredConst; } bool isDeclaredConst() const { return m_isDeclaredConst; }
std::vector<ASTPointer<ModifierInvocation>> const& getModifiers() const { return m_functionModifiers; } std::vector<ASTPointer<ModifierInvocation>> const& modifiers() const { return m_functionModifiers; }
std::vector<ASTPointer<VariableDeclaration>> const& getReturnParameters() const { return m_returnParameters->getParameters(); } std::vector<ASTPointer<VariableDeclaration>> const& returnParameters() const { return m_returnParameters->parameters(); }
Block const& getBody() const { return *m_body; } Block const& body() const { return *m_body; }
virtual bool isVisibleInContract() const override virtual bool isVisibleInContract() const override
{ {
return Declaration::isVisibleInContract() && !isConstructor() && !getName().empty(); return Declaration::isVisibleInContract() && !isConstructor() && !name().empty();
} }
virtual TypePointer getType(ContractDefinition const*) const override; virtual TypePointer type(ContractDefinition const*) const override;
virtual bool isPartOfExternalInterface() const override { return isPublic() && !m_isConstructor && !getName().empty(); } virtual bool isPartOfExternalInterface() const override { return isPublic() && !m_isConstructor && !name().empty(); }
/// Checks that all parameters have allowed types and calls checkTypeRequirements on the body. /// Checks that all parameters have allowed types and calls checkTypeRequirements on the body.
void checkTypeRequirements(); void checkTypeRequirements();
@ -531,19 +531,19 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
TypeName* getTypeName() { return m_typeName.get(); } TypeName* typeName() { return m_typeName.get(); }
ASTPointer<Expression> const& getValue() const { return m_value; } ASTPointer<Expression> const& value() const { return m_value; }
/// Returns the declared or inferred type. Can be an empty pointer if no type was explicitly /// Returns the declared or inferred type. Can be an empty pointer if no type was explicitly
/// declared and there is no assignment to the variable that fixes the type. /// declared and there is no assignment to the variable that fixes the type.
TypePointer getType(ContractDefinition const* = nullptr) const override { return m_type; } TypePointer type(ContractDefinition const* = nullptr) const override { return m_type; }
void setType(std::shared_ptr<Type const> const& _type) { m_type = _type; } void setType(std::shared_ptr<Type const> const& _type) { m_type = _type; }
virtual bool isLValue() const override; virtual bool isLValue() const override;
virtual bool isPartOfExternalInterface() const override { return isPublic(); } virtual bool isPartOfExternalInterface() const override { return isPublic(); }
void checkTypeRequirements(); void checkTypeRequirements();
bool isLocalVariable() const { return !!dynamic_cast<FunctionDefinition const*>(getScope()); } bool isLocalVariable() const { return !!dynamic_cast<FunctionDefinition const*>(scope()); }
/// @returns true if this variable is a parameter or return parameter of a function. /// @returns true if this variable is a parameter or return parameter of a function.
bool isCallableParameter() const; bool isCallableParameter() const;
/// @returns true if this variable is a parameter (not return parameter) of an external function. /// @returns true if this variable is a parameter (not return parameter) of an external function.
@ -554,7 +554,7 @@ public:
Location referenceLocation() const { return m_location; } Location referenceLocation() const { return m_location; }
protected: protected:
Visibility getDefaultVisibility() const override { return Visibility::Internal; } Visibility defaultVisibility() const override { return Visibility::Internal; }
private: private:
ASTPointer<TypeName> m_typeName; ///< can be empty ("var") ASTPointer<TypeName> m_typeName; ///< can be empty ("var")
@ -589,9 +589,9 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
Block const& getBody() const { return *m_body; } Block const& body() const { return *m_body; }
virtual TypePointer getType(ContractDefinition const* = nullptr) const override; virtual TypePointer type(ContractDefinition const* = nullptr) const override;
void checkTypeRequirements(); void checkTypeRequirements();
@ -612,8 +612,8 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
ASTPointer<Identifier> const& getName() const { return m_modifierName; } ASTPointer<Identifier> const& name() const { return m_modifierName; }
std::vector<ASTPointer<Expression>> const& getArguments() const { return m_arguments; } std::vector<ASTPointer<Expression>> const& arguments() const { return m_arguments; }
/// @param _bases is the list of base contracts for base constructor calls. For modifiers an empty vector should be passed. /// @param _bases is the list of base contracts for base constructor calls. For modifiers an empty vector should be passed.
void checkTypeRequirements(std::vector<ContractDefinition const*> const& _bases); void checkTypeRequirements(std::vector<ContractDefinition const*> const& _bases);
@ -647,7 +647,7 @@ public:
bool isAnonymous() const { return m_anonymous; } bool isAnonymous() const { return m_anonymous; }
virtual TypePointer getType(ContractDefinition const* = nullptr) const override virtual TypePointer type(ContractDefinition const* = nullptr) const override
{ {
return std::make_shared<FunctionType>(*this); return std::make_shared<FunctionType>(*this);
} }
@ -672,7 +672,7 @@ public:
virtual void accept(ASTConstVisitor&) const override { BOOST_THROW_EXCEPTION(InternalCompilerError() virtual void accept(ASTConstVisitor&) const override { BOOST_THROW_EXCEPTION(InternalCompilerError()
<< errinfo_comment("MagicVariableDeclaration used inside real AST.")); } << errinfo_comment("MagicVariableDeclaration used inside real AST.")); }
virtual TypePointer getType(ContractDefinition const* = nullptr) const override { return m_type; } virtual TypePointer type(ContractDefinition const* = nullptr) const override { return m_type; }
private: private:
std::shared_ptr<Type const> m_type; std::shared_ptr<Type const> m_type;
@ -713,7 +713,7 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual std::shared_ptr<Type const> toType() override { return Type::fromElementaryTypeName(m_type); } virtual std::shared_ptr<Type const> toType() override { return Type::fromElementaryTypeName(m_type); }
Token::Value getTypeName() const { return m_type; } Token::Value typeName() const { return m_type; }
private: private:
Token::Value m_type; Token::Value m_type;
@ -731,9 +731,9 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual std::shared_ptr<Type const> toType() override { return Type::fromUserDefinedTypeName(*this); } virtual std::shared_ptr<Type const> toType() override { return Type::fromUserDefinedTypeName(*this); }
ASTString const& getName() const { return *m_name; } ASTString const& name() const { return *m_name; }
void setReferencedDeclaration(Declaration const& _referencedDeclaration) { m_referencedDeclaration = &_referencedDeclaration; } void setReferencedDeclaration(Declaration const& _referencedDeclaration) { m_referencedDeclaration = &_referencedDeclaration; }
Declaration const* getReferencedDeclaration() const { return m_referencedDeclaration; } Declaration const* referencedDeclaration() const { return m_referencedDeclaration; }
private: private:
ASTPointer<ASTString> m_name; ASTPointer<ASTString> m_name;
@ -754,8 +754,8 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual TypePointer toType() override { return Type::fromMapping(*m_keyType, *m_valueType); } virtual TypePointer toType() override { return Type::fromMapping(*m_keyType, *m_valueType); }
ElementaryTypeName const& getKeyType() const { return *m_keyType; } ElementaryTypeName const& keyType() const { return *m_keyType; }
TypeName const& getValueType() const { return *m_valueType; } TypeName const& valueType() const { return *m_valueType; }
private: private:
ASTPointer<ElementaryTypeName> m_keyType; ASTPointer<ElementaryTypeName> m_keyType;
@ -775,8 +775,8 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual std::shared_ptr<Type const> toType() override { return Type::fromArrayTypeName(*m_baseType, m_length.get()); } virtual std::shared_ptr<Type const> toType() override { return Type::fromArrayTypeName(*m_baseType, m_length.get()); }
TypeName const& getBaseType() const { return *m_baseType; } TypeName const& baseType() const { return *m_baseType; }
Expression const* getLength() const { return m_length.get(); } Expression const* length() const { return m_length.get(); }
private: private:
ASTPointer<TypeName> m_baseType; ASTPointer<TypeName> m_baseType;
@ -850,10 +850,10 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
Expression const& getCondition() const { return *m_condition; } Expression const& condition() const { return *m_condition; }
Statement const& getTrueStatement() const { return *m_trueBody; } Statement const& trueStatement() const { return *m_trueBody; }
/// @returns the "else" part of the if statement or nullptr if there is no "else" part. /// @returns the "else" part of the if statement or nullptr if there is no "else" part.
Statement const* getFalseStatement() const { return m_falseBody.get(); } Statement const* falseStatement() const { return m_falseBody.get(); }
private: private:
ASTPointer<Expression> m_condition; ASTPointer<Expression> m_condition;
@ -880,8 +880,8 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
Expression const& getCondition() const { return *m_condition; } Expression const& condition() const { return *m_condition; }
Statement const& getBody() const { return *m_body; } Statement const& body() const { return *m_body; }
private: private:
ASTPointer<Expression> m_condition; ASTPointer<Expression> m_condition;
@ -908,10 +908,10 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
Statement const* getInitializationExpression() const { return m_initExpression.get(); } Statement const* initializationExpression() const { return m_initExpression.get(); }
Expression const* getCondition() const { return m_condExpression.get(); } Expression const* condition() const { return m_condExpression.get(); }
ExpressionStatement const* getLoopExpression() const { return m_loopExpression.get(); } ExpressionStatement const* loopExpression() const { return m_loopExpression.get(); }
Statement const& getBody() const { return *m_body; } Statement const& body() const { return *m_body; }
private: private:
/// For statement's initialization expresion. for(XXX; ; ). Can be empty /// For statement's initialization expresion. for(XXX; ; ). Can be empty
@ -952,8 +952,8 @@ public:
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
void setFunctionReturnParameters(ParameterList const* _parameters) { m_returnParameters = _parameters; } void setFunctionReturnParameters(ParameterList const* _parameters) { m_returnParameters = _parameters; }
ParameterList const* getFunctionReturnParameters() const { return m_returnParameters; } ParameterList const* functionReturnParameters() const { return m_returnParameters; }
Expression const* getExpression() const { return m_expression.get(); } Expression const* expression() const { return m_expression.get(); }
private: private:
ASTPointer<Expression> m_expression; ///< value to return, optional ASTPointer<Expression> m_expression; ///< value to return, optional
@ -976,8 +976,8 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
VariableDeclaration const& getDeclaration() const { return *m_variable; } VariableDeclaration const& declaration() const { return *m_variable; }
Expression const* getExpression() const { return m_variable->getValue().get(); } Expression const* expression() const { return m_variable->value().get(); }
private: private:
ASTPointer<VariableDeclaration> m_variable; ASTPointer<VariableDeclaration> m_variable;
@ -995,7 +995,7 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
Expression const& getExpression() const { return *m_expression; } Expression const& expression() const { return *m_expression; }
private: private:
ASTPointer<Expression> m_expression; ASTPointer<Expression> m_expression;
@ -1020,7 +1020,7 @@ public:
/// is used in the context of a call, used for function overload resolution. /// is used in the context of a call, used for function overload resolution.
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) = 0; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) = 0;
std::shared_ptr<Type const> const& getType() const { return m_type; } std::shared_ptr<Type const> const& type() const { return m_type; }
bool isLValue() const { return m_isLValue; } bool isLValue() const { return m_isLValue; }
/// Helper function, infer the type via @ref checkTypeRequirements and then check that it /// Helper function, infer the type via @ref checkTypeRequirements and then check that it
@ -1059,9 +1059,9 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
Expression const& getLeftHandSide() const { return *m_leftHandSide; } Expression const& leftHandSide() const { return *m_leftHandSide; }
Token::Value getAssignmentOperator() const { return m_assigmentOperator; } Token::Value assignmentOperator() const { return m_assigmentOperator; }
Expression const& getRightHandSide() const { return *m_rightHandSide; } Expression const& rightHandSide() const { return *m_rightHandSide; }
private: private:
ASTPointer<Expression> m_leftHandSide; ASTPointer<Expression> m_leftHandSide;
@ -1089,7 +1089,7 @@ public:
Token::Value getOperator() const { return m_operator; } Token::Value getOperator() const { return m_operator; }
bool isPrefixOperation() const { return m_isPrefix; } bool isPrefixOperation() const { return m_isPrefix; }
Expression const& getSubExpression() const { return *m_subExpression; } Expression const& subExpression() const { return *m_subExpression; }
private: private:
Token::Value m_operator; Token::Value m_operator;
@ -1114,10 +1114,10 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
Expression const& getLeftExpression() const { return *m_left; } Expression const& leftExpression() const { return *m_left; }
Expression const& getRightExpression() const { return *m_right; } Expression const& rightExpression() const { return *m_right; }
Token::Value getOperator() const { return m_operator; } Token::Value getOperator() const { return m_operator; }
Type const& getCommonType() const { return *m_commonType; } Type const& commonType() const { return *m_commonType; }
private: private:
ASTPointer<Expression> m_left; ASTPointer<Expression> m_left;
@ -1142,9 +1142,9 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
Expression const& getExpression() const { return *m_expression; } Expression const& expression() const { return *m_expression; }
std::vector<ASTPointer<Expression const>> getArguments() const { return {m_arguments.begin(), m_arguments.end()}; } std::vector<ASTPointer<Expression const>> arguments() const { return {m_arguments.begin(), m_arguments.end()}; }
std::vector<ASTPointer<ASTString>> const& getNames() const { return m_names; } std::vector<ASTPointer<ASTString>> const& names() const { return m_names; }
/// @returns true if this is not an actual function call, but an explicit type conversion. /// @returns true if this is not an actual function call, but an explicit type conversion.
/// Returns false for struct constructor calls. /// Returns false for struct constructor calls.
@ -1171,7 +1171,7 @@ public:
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
/// Returns the referenced contract. Can only be called after type checking. /// Returns the referenced contract. Can only be called after type checking.
ContractDefinition const* getContract() const { solAssert(m_contract, ""); return m_contract; } ContractDefinition const* contract() const { solAssert(m_contract, ""); return m_contract; }
private: private:
ASTPointer<Identifier> m_contractName; ASTPointer<Identifier> m_contractName;
@ -1190,8 +1190,8 @@ public:
Expression(_location), m_expression(_expression), m_memberName(_memberName) {} Expression(_location), m_expression(_expression), m_memberName(_memberName) {}
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
Expression const& getExpression() const { return *m_expression; } Expression const& expression() const { return *m_expression; }
ASTString const& getMemberName() const { return *m_memberName; } ASTString const& memberName() const { return *m_memberName; }
/// @returns the declaration referenced by this expression. Might return nullptr even if the /// @returns the declaration referenced by this expression. Might return nullptr even if the
/// expression is valid, e.g. if the member does not correspond to an AST node. /// expression is valid, e.g. if the member does not correspond to an AST node.
Declaration const* referencedDeclaration() const { return m_referencedDeclaration; } Declaration const* referencedDeclaration() const { return m_referencedDeclaration; }
@ -1219,8 +1219,8 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
Expression const& getBaseExpression() const { return *m_base; } Expression const& baseExpression() const { return *m_base; }
Expression const* getIndexExpression() const { return m_index.get(); } Expression const* indexExpression() const { return m_index.get(); }
private: private:
ASTPointer<Expression> m_base; ASTPointer<Expression> m_base;
@ -1249,7 +1249,7 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
ASTString const& getName() const { return *m_name; } ASTString const& name() const { return *m_name; }
void setReferencedDeclaration( void setReferencedDeclaration(
Declaration const& _referencedDeclaration, Declaration const& _referencedDeclaration,
@ -1259,7 +1259,7 @@ public:
m_referencedDeclaration = &_referencedDeclaration; m_referencedDeclaration = &_referencedDeclaration;
m_currentContract = _currentContract; m_currentContract = _currentContract;
} }
Declaration const& getReferencedDeclaration() const; Declaration const& referencedDeclaration() const;
/// Stores a set of possible declarations referenced by this identifier. Has to be resolved /// Stores a set of possible declarations referenced by this identifier. Has to be resolved
/// providing argument types using overloadResolution before the referenced declaration /// providing argument types using overloadResolution before the referenced declaration
@ -1302,7 +1302,7 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
Token::Value getTypeToken() const { return m_typeToken; } Token::Value typeToken() const { return m_typeToken; }
private: private:
Token::Value m_typeToken; Token::Value m_typeToken;
@ -1336,11 +1336,11 @@ public:
virtual void accept(ASTConstVisitor& _visitor) const override; virtual void accept(ASTConstVisitor& _visitor) const override;
virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override; virtual void checkTypeRequirements(TypePointers const* _argumentTypes) override;
Token::Value getToken() const { return m_token; } Token::Value token() const { return m_token; }
/// @returns the non-parsed value of the literal /// @returns the non-parsed value of the literal
ASTString const& getValue() const { return *m_value; } ASTString const& value() const { return *m_value; }
SubDenomination getSubDenomination() const { return m_subDenomination; } SubDenomination subDenomination() const { return m_subDenomination; }
private: private:
Token::Value m_token; Token::Value m_token;

View File

@ -90,19 +90,19 @@ Json::Value const& ASTJsonConverter::json()
bool ASTJsonConverter::visit(ImportDirective const& _node) bool ASTJsonConverter::visit(ImportDirective const& _node)
{ {
addJsonNode("Import", { make_pair("file", _node.getIdentifier())}); addJsonNode("Import", { make_pair("file", _node.identifier())});
return true; return true;
} }
bool ASTJsonConverter::visit(ContractDefinition const& _node) bool ASTJsonConverter::visit(ContractDefinition const& _node)
{ {
addJsonNode("Contract", { make_pair("name", _node.getName()) }, true); addJsonNode("Contract", { make_pair("name", _node.name()) }, true);
return true; return true;
} }
bool ASTJsonConverter::visit(StructDefinition const& _node) bool ASTJsonConverter::visit(StructDefinition const& _node)
{ {
addJsonNode("Struct", { make_pair("name", _node.getName()) }, true); addJsonNode("Struct", { make_pair("name", _node.name()) }, true);
return true; return true;
} }
@ -115,7 +115,7 @@ bool ASTJsonConverter::visit(ParameterList const&)
bool ASTJsonConverter::visit(FunctionDefinition const& _node) bool ASTJsonConverter::visit(FunctionDefinition const& _node)
{ {
addJsonNode("Function", addJsonNode("Function",
{ make_pair("name", _node.getName()), { make_pair("name", _node.name()),
make_pair("public", boost::lexical_cast<std::string>(_node.isPublic())), make_pair("public", boost::lexical_cast<std::string>(_node.isPublic())),
make_pair("const", boost::lexical_cast<std::string>(_node.isDeclaredConst())) }, make_pair("const", boost::lexical_cast<std::string>(_node.isDeclaredConst())) },
true); true);
@ -124,7 +124,7 @@ bool ASTJsonConverter::visit(FunctionDefinition const& _node)
bool ASTJsonConverter::visit(VariableDeclaration const& _node) bool ASTJsonConverter::visit(VariableDeclaration const& _node)
{ {
addJsonNode("VariableDeclaration", { make_pair("name", _node.getName()) }, true); addJsonNode("VariableDeclaration", { make_pair("name", _node.name()) }, true);
return true; return true;
} }
@ -135,13 +135,13 @@ bool ASTJsonConverter::visit(TypeName const&)
bool ASTJsonConverter::visit(ElementaryTypeName const& _node) bool ASTJsonConverter::visit(ElementaryTypeName const& _node)
{ {
addJsonNode("ElementaryTypeName", { make_pair("name", Token::toString(_node.getTypeName())) }); addJsonNode("ElementaryTypeName", { make_pair("name", Token::toString(_node.typeName())) });
return true; return true;
} }
bool ASTJsonConverter::visit(UserDefinedTypeName const& _node) bool ASTJsonConverter::visit(UserDefinedTypeName const& _node)
{ {
addJsonNode("UserDefinedTypeName", { make_pair("name", _node.getName()) }); addJsonNode("UserDefinedTypeName", { make_pair("name", _node.name()) });
return true; return true;
} }
@ -208,7 +208,7 @@ bool ASTJsonConverter::visit(ExpressionStatement const&)
bool ASTJsonConverter::visit(Assignment const& _node) bool ASTJsonConverter::visit(Assignment const& _node)
{ {
addJsonNode("Assignment", addJsonNode("Assignment",
{ make_pair("operator", Token::toString(_node.getAssignmentOperator())), { make_pair("operator", Token::toString(_node.assignmentOperator())),
make_pair("type", getType(_node)) }, make_pair("type", getType(_node)) },
true); true);
return true; return true;
@ -251,7 +251,7 @@ bool ASTJsonConverter::visit(NewExpression const& _node)
bool ASTJsonConverter::visit(MemberAccess const& _node) bool ASTJsonConverter::visit(MemberAccess const& _node)
{ {
addJsonNode("MemberAccess", addJsonNode("MemberAccess",
{ make_pair("member_name", _node.getMemberName()), { make_pair("member_name", _node.memberName()),
make_pair("type", getType(_node)) }, make_pair("type", getType(_node)) },
true); true);
return true; return true;
@ -266,23 +266,23 @@ bool ASTJsonConverter::visit(IndexAccess const& _node)
bool ASTJsonConverter::visit(Identifier const& _node) bool ASTJsonConverter::visit(Identifier const& _node)
{ {
addJsonNode("Identifier", addJsonNode("Identifier",
{ make_pair("value", _node.getName()), make_pair("type", getType(_node)) }); { make_pair("value", _node.name()), make_pair("type", getType(_node)) });
return true; return true;
} }
bool ASTJsonConverter::visit(ElementaryTypeNameExpression const& _node) bool ASTJsonConverter::visit(ElementaryTypeNameExpression const& _node)
{ {
addJsonNode("ElementaryTypenameExpression", addJsonNode("ElementaryTypenameExpression",
{ make_pair("value", Token::toString(_node.getTypeToken())), make_pair("type", getType(_node)) }); { make_pair("value", Token::toString(_node.typeToken())), make_pair("type", getType(_node)) });
return true; return true;
} }
bool ASTJsonConverter::visit(Literal const& _node) bool ASTJsonConverter::visit(Literal const& _node)
{ {
char const* tokenString = Token::toString(_node.getToken()); char const* tokenString = Token::toString(_node.token());
addJsonNode("Literal", addJsonNode("Literal",
{ make_pair("string", (tokenString) ? tokenString : "null"), { make_pair("string", (tokenString) ? tokenString : "null"),
make_pair("value", _node.getValue()), make_pair("value", _node.value()),
make_pair("type", getType(_node)) }); make_pair("type", getType(_node)) });
return true; return true;
} }
@ -430,7 +430,7 @@ void ASTJsonConverter::process()
string ASTJsonConverter::getType(Expression const& _expression) string ASTJsonConverter::getType(Expression const& _expression)
{ {
return (_expression.getType()) ? _expression.getType()->toString() : "Unknown"; return (_expression.type()) ? _expression.type()->toString() : "Unknown";
} }
} }

View File

@ -48,41 +48,41 @@ void ASTPrinter::print(ostream& _stream)
bool ASTPrinter::visit(ImportDirective const& _node) bool ASTPrinter::visit(ImportDirective const& _node)
{ {
writeLine("ImportDirective \"" + _node.getIdentifier() + "\""); writeLine("ImportDirective \"" + _node.identifier() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(ContractDefinition const& _node) bool ASTPrinter::visit(ContractDefinition const& _node)
{ {
writeLine("ContractDefinition \"" + _node.getName() + "\""); writeLine("ContractDefinition \"" + _node.name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(InheritanceSpecifier const& _node) bool ASTPrinter::visit(InheritanceSpecifier const& _node)
{ {
writeLine("InheritanceSpecifier \"" + _node.getName()->getName() + "\""); writeLine("InheritanceSpecifier \"" + _node.name()->name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(StructDefinition const& _node) bool ASTPrinter::visit(StructDefinition const& _node)
{ {
writeLine("StructDefinition \"" + _node.getName() + "\""); writeLine("StructDefinition \"" + _node.name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(EnumDefinition const& _node) bool ASTPrinter::visit(EnumDefinition const& _node)
{ {
writeLine("EnumDefinition \"" + _node.getName() + "\""); writeLine("EnumDefinition \"" + _node.name() + "\"");
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(EnumValue const& _node) bool ASTPrinter::visit(EnumValue const& _node)
{ {
writeLine("EnumValue \"" + _node.getName() + "\""); writeLine("EnumValue \"" + _node.name() + "\"");
return goDeeper(); return goDeeper();
} }
@ -95,7 +95,7 @@ bool ASTPrinter::visit(ParameterList const& _node)
bool ASTPrinter::visit(FunctionDefinition const& _node) bool ASTPrinter::visit(FunctionDefinition const& _node)
{ {
writeLine("FunctionDefinition \"" + _node.getName() + "\"" + writeLine("FunctionDefinition \"" + _node.name() + "\"" +
(_node.isPublic() ? " - public" : "") + (_node.isPublic() ? " - public" : "") +
(_node.isDeclaredConst() ? " - const" : "")); (_node.isDeclaredConst() ? " - const" : ""));
printSourcePart(_node); printSourcePart(_node);
@ -104,28 +104,28 @@ bool ASTPrinter::visit(FunctionDefinition const& _node)
bool ASTPrinter::visit(VariableDeclaration const& _node) bool ASTPrinter::visit(VariableDeclaration const& _node)
{ {
writeLine("VariableDeclaration \"" + _node.getName() + "\""); writeLine("VariableDeclaration \"" + _node.name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(ModifierDefinition const& _node) bool ASTPrinter::visit(ModifierDefinition const& _node)
{ {
writeLine("ModifierDefinition \"" + _node.getName() + "\""); writeLine("ModifierDefinition \"" + _node.name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(ModifierInvocation const& _node) bool ASTPrinter::visit(ModifierInvocation const& _node)
{ {
writeLine("ModifierInvocation \"" + _node.getName()->getName() + "\""); writeLine("ModifierInvocation \"" + _node.name()->name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(EventDefinition const& _node) bool ASTPrinter::visit(EventDefinition const& _node)
{ {
writeLine("EventDefinition \"" + _node.getName() + "\""); writeLine("EventDefinition \"" + _node.name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
@ -139,14 +139,14 @@ bool ASTPrinter::visit(TypeName const& _node)
bool ASTPrinter::visit(ElementaryTypeName const& _node) bool ASTPrinter::visit(ElementaryTypeName const& _node)
{ {
writeLine(string("ElementaryTypeName ") + Token::toString(_node.getTypeName())); writeLine(string("ElementaryTypeName ") + Token::toString(_node.typeName()));
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
bool ASTPrinter::visit(UserDefinedTypeName const& _node) bool ASTPrinter::visit(UserDefinedTypeName const& _node)
{ {
writeLine("UserDefinedTypeName \"" + _node.getName() + "\""); writeLine("UserDefinedTypeName \"" + _node.name() + "\"");
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
} }
@ -237,7 +237,7 @@ bool ASTPrinter::visit(ExpressionStatement const& _node)
bool ASTPrinter::visit(Assignment const& _node) bool ASTPrinter::visit(Assignment const& _node)
{ {
writeLine(string("Assignment using operator ") + Token::toString(_node.getAssignmentOperator())); writeLine(string("Assignment using operator ") + Token::toString(_node.assignmentOperator()));
printType(_node); printType(_node);
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
@ -278,7 +278,7 @@ bool ASTPrinter::visit(NewExpression const& _node)
bool ASTPrinter::visit(MemberAccess const& _node) bool ASTPrinter::visit(MemberAccess const& _node)
{ {
writeLine("MemberAccess to member " + _node.getMemberName()); writeLine("MemberAccess to member " + _node.memberName());
printType(_node); printType(_node);
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
@ -294,7 +294,7 @@ bool ASTPrinter::visit(IndexAccess const& _node)
bool ASTPrinter::visit(Identifier const& _node) bool ASTPrinter::visit(Identifier const& _node)
{ {
writeLine(string("Identifier ") + _node.getName()); writeLine(string("Identifier ") + _node.name());
printType(_node); printType(_node);
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
@ -302,7 +302,7 @@ bool ASTPrinter::visit(Identifier const& _node)
bool ASTPrinter::visit(ElementaryTypeNameExpression const& _node) bool ASTPrinter::visit(ElementaryTypeNameExpression const& _node)
{ {
writeLine(string("ElementaryTypeNameExpression ") + Token::toString(_node.getTypeToken())); writeLine(string("ElementaryTypeNameExpression ") + Token::toString(_node.typeToken()));
printType(_node); printType(_node);
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
@ -310,10 +310,10 @@ bool ASTPrinter::visit(ElementaryTypeNameExpression const& _node)
bool ASTPrinter::visit(Literal const& _node) bool ASTPrinter::visit(Literal const& _node)
{ {
char const* tokenString = Token::toString(_node.getToken()); char const* tokenString = Token::toString(_node.token());
if (!tokenString) if (!tokenString)
tokenString = "[no token]"; tokenString = "[no token]";
writeLine(string("Literal, token: ") + tokenString + " value: " + _node.getValue()); writeLine(string("Literal, token: ") + tokenString + " value: " + _node.value());
printType(_node); printType(_node);
printSourcePart(_node); printSourcePart(_node);
return goDeeper(); return goDeeper();
@ -510,7 +510,7 @@ void ASTPrinter::printSourcePart(ASTNode const& _node)
*m_ostream << getIndentation() << " Gas costs: " << m_gasCosts.at(&_node) << endl; *m_ostream << getIndentation() << " Gas costs: " << m_gasCosts.at(&_node) << endl;
if (!m_source.empty()) if (!m_source.empty())
{ {
SourceLocation const& location(_node.getLocation()); SourceLocation const& location(_node.location());
*m_ostream << getIndentation() << " Source: " *m_ostream << getIndentation() << " Source: "
<< escaped(m_source.substr(location.start, location.end - location.start), false) << endl; << escaped(m_source.substr(location.start, location.end - location.start), false) << endl;
} }
@ -518,8 +518,8 @@ void ASTPrinter::printSourcePart(ASTNode const& _node)
void ASTPrinter::printType(Expression const& _expression) void ASTPrinter::printType(Expression const& _expression)
{ {
if (_expression.getType()) if (_expression.type())
*m_ostream << getIndentation() << " Type: " << _expression.getType()->toString() << "\n"; *m_ostream << getIndentation() << " Type: " << _expression.type()->toString() << "\n";
else else
*m_ostream << getIndentation() << " Type unknown.\n"; *m_ostream << getIndentation() << " Type unknown.\n";
} }

View File

@ -39,7 +39,7 @@ ASTNode const* LocationFinder::leastUpperBound()
bool LocationFinder::visitNode(const ASTNode& _node) bool LocationFinder::visitNode(const ASTNode& _node)
{ {
if (_node.getLocation().contains(m_location)) if (_node.location().contains(m_location))
{ {
m_bestMatch = &_node; m_bestMatch = &_node;
return true; return true;

View File

@ -41,21 +41,21 @@ void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType cons
solAssert(_targetType.location() == DataLocation::Storage, ""); solAssert(_targetType.location() == DataLocation::Storage, "");
IntegerType uint256(256); IntegerType uint256(256);
Type const* targetBaseType = _targetType.isByteArray() ? &uint256 : &(*_targetType.getBaseType()); Type const* targetBaseType = _targetType.isByteArray() ? &uint256 : &(*_targetType.baseType());
Type const* sourceBaseType = _sourceType.isByteArray() ? &uint256 : &(*_sourceType.getBaseType()); Type const* sourceBaseType = _sourceType.isByteArray() ? &uint256 : &(*_sourceType.baseType());
// TODO unroll loop for small sizes // TODO unroll loop for small sizes
bool sourceIsStorage = _sourceType.location() == DataLocation::Storage; bool sourceIsStorage = _sourceType.location() == DataLocation::Storage;
bool fromCalldata = _sourceType.location() == DataLocation::CallData; bool fromCalldata = _sourceType.location() == DataLocation::CallData;
bool directCopy = sourceIsStorage && sourceBaseType->isValueType() && *sourceBaseType == *targetBaseType; bool directCopy = sourceIsStorage && sourceBaseType->isValueType() && *sourceBaseType == *targetBaseType;
bool haveByteOffsetSource = !directCopy && sourceIsStorage && sourceBaseType->getStorageBytes() <= 16; bool haveByteOffsetSource = !directCopy && sourceIsStorage && sourceBaseType->storageBytes() <= 16;
bool haveByteOffsetTarget = !directCopy && targetBaseType->getStorageBytes() <= 16; bool haveByteOffsetTarget = !directCopy && targetBaseType->storageBytes() <= 16;
unsigned byteOffsetSize = (haveByteOffsetSource ? 1 : 0) + (haveByteOffsetTarget ? 1 : 0); unsigned byteOffsetSize = (haveByteOffsetSource ? 1 : 0) + (haveByteOffsetTarget ? 1 : 0);
// stack: source_ref [source_length] target_ref // stack: source_ref [source_length] target_ref
// store target_ref // store target_ref
for (unsigned i = _sourceType.getSizeOnStack(); i > 0; --i) for (unsigned i = _sourceType.sizeOnStack(); i > 0; --i)
m_context << eth::swapInstruction(i); m_context << eth::swapInstruction(i);
// stack: target_ref source_ref [source_length] // stack: target_ref source_ref [source_length]
// stack: target_ref source_ref [source_length] // stack: target_ref source_ref [source_length]
@ -77,9 +77,9 @@ void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType cons
if (_targetType.isDynamicallySized()) if (_targetType.isDynamicallySized())
// store new target length // store new target length
m_context << eth::Instruction::DUP3 << eth::Instruction::DUP3 << eth::Instruction::SSTORE; m_context << eth::Instruction::DUP3 << eth::Instruction::DUP3 << eth::Instruction::SSTORE;
if (sourceBaseType->getCategory() == Type::Category::Mapping) if (sourceBaseType->category() == Type::Category::Mapping)
{ {
solAssert(targetBaseType->getCategory() == Type::Category::Mapping, ""); solAssert(targetBaseType->category() == Type::Category::Mapping, "");
solAssert(_sourceType.location() == DataLocation::Storage, ""); solAssert(_sourceType.location() == DataLocation::Storage, "");
// nothing to copy // nothing to copy
m_context m_context
@ -125,7 +125,7 @@ void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType cons
m_context.appendConditionalJumpTo(copyLoopEnd); m_context.appendConditionalJumpTo(copyLoopEnd);
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset]
// copy // copy
if (sourceBaseType->getCategory() == Type::Category::Array) if (sourceBaseType->category() == Type::Category::Array)
{ {
solAssert(byteOffsetSize == 0, "Byte offset for array as base type."); solAssert(byteOffsetSize == 0, "Byte offset for array as base type.");
auto const& sourceBaseArrayType = dynamic_cast<ArrayType const&>(*sourceBaseType); auto const& sourceBaseArrayType = dynamic_cast<ArrayType const&>(*sourceBaseType);
@ -164,13 +164,13 @@ void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType cons
solAssert(false, "Copying of type " + _sourceType.toString(false) + " to storage not yet supported."); solAssert(false, "Copying of type " + _sourceType.toString(false) + " to storage not yet supported.");
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] <source_value>... // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] <source_value>...
solAssert( solAssert(
2 + byteOffsetSize + sourceBaseType->getSizeOnStack() <= 16, 2 + byteOffsetSize + sourceBaseType->sizeOnStack() <= 16,
"Stack too deep, try removing local variables." "Stack too deep, try removing local variables."
); );
// fetch target storage reference // fetch target storage reference
m_context << eth::dupInstruction(2 + byteOffsetSize + sourceBaseType->getSizeOnStack()); m_context << eth::dupInstruction(2 + byteOffsetSize + sourceBaseType->sizeOnStack());
if (haveByteOffsetTarget) if (haveByteOffsetTarget)
m_context << eth::dupInstruction(1 + byteOffsetSize + sourceBaseType->getSizeOnStack()); m_context << eth::dupInstruction(1 + byteOffsetSize + sourceBaseType->sizeOnStack());
else else
m_context << u256(0); m_context << u256(0);
StorageItem(m_context, *targetBaseType).storeValue(*sourceBaseType, SourceLocation(), true); StorageItem(m_context, *targetBaseType).storeValue(*sourceBaseType, SourceLocation(), true);
@ -178,27 +178,27 @@ void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType cons
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] // stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset]
// increment source // increment source
if (haveByteOffsetSource) if (haveByteOffsetSource)
incrementByteOffset(sourceBaseType->getStorageBytes(), 1, haveByteOffsetTarget ? 5 : 4); incrementByteOffset(sourceBaseType->storageBytes(), 1, haveByteOffsetTarget ? 5 : 4);
else else
{ {
m_context << eth::swapInstruction(2 + byteOffsetSize); m_context << eth::swapInstruction(2 + byteOffsetSize);
if (sourceIsStorage) if (sourceIsStorage)
m_context << sourceBaseType->getStorageSize(); m_context << sourceBaseType->storageSize();
else if (_sourceType.location() == DataLocation::Memory) else if (_sourceType.location() == DataLocation::Memory)
m_context << sourceBaseType->memoryHeadSize(); m_context << sourceBaseType->memoryHeadSize();
else else
m_context << sourceBaseType->getCalldataEncodedSize(true); m_context << sourceBaseType->calldataEncodedSize(true);
m_context m_context
<< eth::Instruction::ADD << eth::Instruction::ADD
<< eth::swapInstruction(2 + byteOffsetSize); << eth::swapInstruction(2 + byteOffsetSize);
} }
// increment target // increment target
if (haveByteOffsetTarget) if (haveByteOffsetTarget)
incrementByteOffset(targetBaseType->getStorageBytes(), byteOffsetSize, byteOffsetSize + 2); incrementByteOffset(targetBaseType->storageBytes(), byteOffsetSize, byteOffsetSize + 2);
else else
m_context m_context
<< eth::swapInstruction(1 + byteOffsetSize) << eth::swapInstruction(1 + byteOffsetSize)
<< targetBaseType->getStorageSize() << targetBaseType->storageSize()
<< eth::Instruction::ADD << eth::Instruction::ADD
<< eth::swapInstruction(1 + byteOffsetSize); << eth::swapInstruction(1 + byteOffsetSize);
m_context.appendJumpTo(copyLoopStart); m_context.appendJumpTo(copyLoopStart);
@ -211,7 +211,7 @@ void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType cons
eth::AssemblyItem copyCleanupLoopEnd = m_context.appendConditionalJump(); eth::AssemblyItem copyCleanupLoopEnd = m_context.appendConditionalJump();
m_context << eth::dupInstruction(2 + byteOffsetSize) << eth::dupInstruction(1 + byteOffsetSize); m_context << eth::dupInstruction(2 + byteOffsetSize) << eth::dupInstruction(1 + byteOffsetSize);
StorageItem(m_context, *targetBaseType).setToZero(SourceLocation(), true); StorageItem(m_context, *targetBaseType).setToZero(SourceLocation(), true);
incrementByteOffset(targetBaseType->getStorageBytes(), byteOffsetSize, byteOffsetSize + 2); incrementByteOffset(targetBaseType->storageBytes(), byteOffsetSize, byteOffsetSize + 2);
m_context.appendJumpTo(copyLoopEnd); m_context.appendJumpTo(copyLoopEnd);
m_context << copyCleanupLoopEnd; m_context << copyCleanupLoopEnd;
@ -232,19 +232,19 @@ void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType cons
void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWordBoundaries) const void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWordBoundaries) const
{ {
solAssert( solAssert(
_sourceType.getBaseType()->getCalldataEncodedSize() > 0, _sourceType.baseType()->calldataEncodedSize() > 0,
"Nested dynamic arrays not implemented here." "Nested dynamic arrays not implemented here."
); );
CompilerUtils utils(m_context); CompilerUtils utils(m_context);
unsigned baseSize = 1; unsigned baseSize = 1;
if (!_sourceType.isByteArray()) if (!_sourceType.isByteArray())
// We always pad the elements, regardless of _padToWordBoundaries. // We always pad the elements, regardless of _padToWordBoundaries.
baseSize = _sourceType.getBaseType()->getCalldataEncodedSize(); baseSize = _sourceType.baseType()->calldataEncodedSize();
if (_sourceType.location() == DataLocation::CallData) if (_sourceType.location() == DataLocation::CallData)
{ {
if (!_sourceType.isDynamicallySized()) if (!_sourceType.isDynamicallySized())
m_context << _sourceType.getLength(); m_context << _sourceType.length();
if (baseSize > 1) if (baseSize > 1)
m_context << u256(baseSize) << eth::Instruction::MUL; m_context << u256(baseSize) << eth::Instruction::MUL;
// stack: target source_offset source_len // stack: target source_offset source_len
@ -258,7 +258,7 @@ void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWord
{ {
retrieveLength(_sourceType); retrieveLength(_sourceType);
// stack: target source length // stack: target source length
if (!_sourceType.getBaseType()->isValueType()) if (!_sourceType.baseType()->isValueType())
{ {
// copy using a loop // copy using a loop
m_context << u256(0) << eth::Instruction::SWAP3; m_context << u256(0) << eth::Instruction::SWAP3;
@ -270,11 +270,11 @@ void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWord
auto loopEnd = m_context.appendConditionalJump(); auto loopEnd = m_context.appendConditionalJump();
m_context << eth::Instruction::DUP3 << eth::Instruction::DUP5; m_context << eth::Instruction::DUP3 << eth::Instruction::DUP5;
accessIndex(_sourceType, false); accessIndex(_sourceType, false);
MemoryItem(m_context, *_sourceType.getBaseType(), true).retrieveValue(SourceLocation(), true); MemoryItem(m_context, *_sourceType.baseType(), true).retrieveValue(SourceLocation(), true);
if (auto baseArray = dynamic_cast<ArrayType const*>(_sourceType.getBaseType().get())) if (auto baseArray = dynamic_cast<ArrayType const*>(_sourceType.baseType().get()))
copyArrayToMemory(*baseArray, _padToWordBoundaries); copyArrayToMemory(*baseArray, _padToWordBoundaries);
else else
utils.storeInMemoryDynamic(*_sourceType.getBaseType()); utils.storeInMemoryDynamic(*_sourceType.baseType());
m_context << eth::Instruction::SWAP3 << u256(1) << eth::Instruction::ADD; m_context << eth::Instruction::SWAP3 << u256(1) << eth::Instruction::ADD;
m_context << eth::Instruction::SWAP3; m_context << eth::Instruction::SWAP3;
m_context.appendJumpTo(repeat); m_context.appendJumpTo(repeat);
@ -307,7 +307,7 @@ void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWord
if (_sourceType.isDynamicallySized()) if (_sourceType.isDynamicallySized())
paddingNeeded = _padToWordBoundaries && ((baseSize % 32) != 0); paddingNeeded = _padToWordBoundaries && ((baseSize % 32) != 0);
else else
paddingNeeded = _padToWordBoundaries && (((_sourceType.getLength() * baseSize) % 32) != 0); paddingNeeded = _padToWordBoundaries && (((_sourceType.length() * baseSize) % 32) != 0);
if (paddingNeeded) if (paddingNeeded)
{ {
// stack: <target> <size> // stack: <target> <size>
@ -352,8 +352,8 @@ void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWord
else else
{ {
solAssert(_sourceType.location() == DataLocation::Storage, ""); solAssert(_sourceType.location() == DataLocation::Storage, "");
unsigned storageBytes = _sourceType.getBaseType()->getStorageBytes(); unsigned storageBytes = _sourceType.baseType()->storageBytes();
u256 storageSize = _sourceType.getBaseType()->getStorageSize(); u256 storageSize = _sourceType.baseType()->storageSize();
solAssert(storageSize > 1 || (storageSize == 1 && storageBytes > 0), ""); solAssert(storageSize > 1 || (storageSize == 1 && storageBytes > 0), "");
retrieveLength(_sourceType); retrieveLength(_sourceType);
@ -400,11 +400,11 @@ void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWord
m_context << eth::Instruction::DUP3 << eth::Instruction::DUP3; m_context << eth::Instruction::DUP3 << eth::Instruction::DUP3;
else else
m_context << eth::Instruction::DUP2 << u256(0); m_context << eth::Instruction::DUP2 << u256(0);
StorageItem(m_context, *_sourceType.getBaseType()).retrieveValue(SourceLocation(), true); StorageItem(m_context, *_sourceType.baseType()).retrieveValue(SourceLocation(), true);
if (auto baseArray = dynamic_cast<ArrayType const*>(_sourceType.getBaseType().get())) if (auto baseArray = dynamic_cast<ArrayType const*>(_sourceType.baseType().get()))
copyArrayToMemory(*baseArray, _padToWordBoundaries); copyArrayToMemory(*baseArray, _padToWordBoundaries);
else else
utils.storeInMemoryDynamic(*_sourceType.getBaseType()); utils.storeInMemoryDynamic(*_sourceType.baseType());
// increment storage_data_offset and byte offset // increment storage_data_offset and byte offset
if (haveByteOffset) if (haveByteOffset)
incrementByteOffset(storageBytes, 2, 3); incrementByteOffset(storageBytes, 2, 3);
@ -438,58 +438,58 @@ void ArrayUtils::copyArrayToMemory(const ArrayType& _sourceType, bool _padToWord
void ArrayUtils::clearArray(ArrayType const& _type) const void ArrayUtils::clearArray(ArrayType const& _type) const
{ {
unsigned stackHeightStart = m_context.getStackHeight(); unsigned stackHeightStart = m_context.stackHeight();
solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.location() == DataLocation::Storage, "");
if (_type.getBaseType()->getStorageBytes() < 32) if (_type.baseType()->storageBytes() < 32)
{ {
solAssert(_type.getBaseType()->isValueType(), "Invalid storage size for non-value type."); solAssert(_type.baseType()->isValueType(), "Invalid storage size for non-value type.");
solAssert(_type.getBaseType()->getStorageSize() <= 1, "Invalid storage size for type."); solAssert(_type.baseType()->storageSize() <= 1, "Invalid storage size for type.");
} }
if (_type.getBaseType()->isValueType()) if (_type.baseType()->isValueType())
solAssert(_type.getBaseType()->getStorageSize() <= 1, "Invalid size for value type."); solAssert(_type.baseType()->storageSize() <= 1, "Invalid size for value type.");
m_context << eth::Instruction::POP; // remove byte offset m_context << eth::Instruction::POP; // remove byte offset
if (_type.isDynamicallySized()) if (_type.isDynamicallySized())
clearDynamicArray(_type); clearDynamicArray(_type);
else if (_type.getLength() == 0 || _type.getBaseType()->getCategory() == Type::Category::Mapping) else if (_type.length() == 0 || _type.baseType()->category() == Type::Category::Mapping)
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
else if (_type.getBaseType()->isValueType() && _type.getStorageSize() <= 5) else if (_type.baseType()->isValueType() && _type.storageSize() <= 5)
{ {
// unroll loop for small arrays @todo choose a good value // unroll loop for small arrays @todo choose a good value
// Note that we loop over storage slots here, not elements. // Note that we loop over storage slots here, not elements.
for (unsigned i = 1; i < _type.getStorageSize(); ++i) for (unsigned i = 1; i < _type.storageSize(); ++i)
m_context m_context
<< u256(0) << eth::Instruction::DUP2 << eth::Instruction::SSTORE << u256(0) << eth::Instruction::DUP2 << eth::Instruction::SSTORE
<< u256(1) << eth::Instruction::ADD; << u256(1) << eth::Instruction::ADD;
m_context << u256(0) << eth::Instruction::SWAP1 << eth::Instruction::SSTORE; m_context << u256(0) << eth::Instruction::SWAP1 << eth::Instruction::SSTORE;
} }
else if (!_type.getBaseType()->isValueType() && _type.getLength() <= 4) else if (!_type.baseType()->isValueType() && _type.length() <= 4)
{ {
// unroll loop for small arrays @todo choose a good value // unroll loop for small arrays @todo choose a good value
solAssert(_type.getBaseType()->getStorageBytes() >= 32, "Invalid storage size."); solAssert(_type.baseType()->storageBytes() >= 32, "Invalid storage size.");
for (unsigned i = 1; i < _type.getLength(); ++i) for (unsigned i = 1; i < _type.length(); ++i)
{ {
m_context << u256(0); m_context << u256(0);
StorageItem(m_context, *_type.getBaseType()).setToZero(SourceLocation(), false); StorageItem(m_context, *_type.baseType()).setToZero(SourceLocation(), false);
m_context m_context
<< eth::Instruction::POP << eth::Instruction::POP
<< u256(_type.getBaseType()->getStorageSize()) << eth::Instruction::ADD; << u256(_type.baseType()->storageSize()) << eth::Instruction::ADD;
} }
m_context << u256(0); m_context << u256(0);
StorageItem(m_context, *_type.getBaseType()).setToZero(SourceLocation(), true); StorageItem(m_context, *_type.baseType()).setToZero(SourceLocation(), true);
} }
else else
{ {
m_context << eth::Instruction::DUP1 << _type.getLength(); m_context << eth::Instruction::DUP1 << _type.length();
convertLengthToSize(_type); convertLengthToSize(_type);
m_context << eth::Instruction::ADD << eth::Instruction::SWAP1; m_context << eth::Instruction::ADD << eth::Instruction::SWAP1;
if (_type.getBaseType()->getStorageBytes() < 32) if (_type.baseType()->storageBytes() < 32)
clearStorageLoop(IntegerType(256)); clearStorageLoop(IntegerType(256));
else else
clearStorageLoop(*_type.getBaseType()); clearStorageLoop(*_type.baseType());
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
} }
solAssert(m_context.getStackHeight() == stackHeightStart - 2, ""); solAssert(m_context.stackHeight() == stackHeightStart - 2, "");
} }
void ArrayUtils::clearDynamicArray(ArrayType const& _type) const void ArrayUtils::clearDynamicArray(ArrayType const& _type) const
@ -497,7 +497,7 @@ void ArrayUtils::clearDynamicArray(ArrayType const& _type) const
solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.location() == DataLocation::Storage, "");
solAssert(_type.isDynamicallySized(), ""); solAssert(_type.isDynamicallySized(), "");
unsigned stackHeightStart = m_context.getStackHeight(); unsigned stackHeightStart = m_context.stackHeight();
// fetch length // fetch length
m_context << eth::Instruction::DUP1 << eth::Instruction::SLOAD; m_context << eth::Instruction::DUP1 << eth::Instruction::SLOAD;
// set length to zero // set length to zero
@ -511,23 +511,23 @@ void ArrayUtils::clearDynamicArray(ArrayType const& _type) const
m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2 << eth::Instruction::ADD m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2 << eth::Instruction::ADD
<< eth::Instruction::SWAP1; << eth::Instruction::SWAP1;
// stack: data_pos_end data_pos // stack: data_pos_end data_pos
if (_type.isByteArray() || _type.getBaseType()->getStorageBytes() < 32) if (_type.isByteArray() || _type.baseType()->storageBytes() < 32)
clearStorageLoop(IntegerType(256)); clearStorageLoop(IntegerType(256));
else else
clearStorageLoop(*_type.getBaseType()); clearStorageLoop(*_type.baseType());
// cleanup // cleanup
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
solAssert(m_context.getStackHeight() == stackHeightStart - 1, ""); solAssert(m_context.stackHeight() == stackHeightStart - 1, "");
} }
void ArrayUtils::resizeDynamicArray(const ArrayType& _type) const void ArrayUtils::resizeDynamicArray(const ArrayType& _type) const
{ {
solAssert(_type.location() == DataLocation::Storage, ""); solAssert(_type.location() == DataLocation::Storage, "");
solAssert(_type.isDynamicallySized(), ""); solAssert(_type.isDynamicallySized(), "");
if (!_type.isByteArray() && _type.getBaseType()->getStorageBytes() < 32) if (!_type.isByteArray() && _type.baseType()->storageBytes() < 32)
solAssert(_type.getBaseType()->isValueType(), "Invalid storage size for non-value type."); solAssert(_type.baseType()->isValueType(), "Invalid storage size for non-value type.");
unsigned stackHeightStart = m_context.getStackHeight(); unsigned stackHeightStart = m_context.stackHeight();
eth::AssemblyItem resizeEnd = m_context.newTag(); eth::AssemblyItem resizeEnd = m_context.newTag();
// stack: ref new_length // stack: ref new_length
@ -555,21 +555,21 @@ void ArrayUtils::resizeDynamicArray(const ArrayType& _type) const
// stack: ref new_length data_pos new_size delete_end // stack: ref new_length data_pos new_size delete_end
m_context << eth::Instruction::SWAP2 << eth::Instruction::ADD; m_context << eth::Instruction::SWAP2 << eth::Instruction::ADD;
// stack: ref new_length delete_end delete_start // stack: ref new_length delete_end delete_start
if (_type.isByteArray() || _type.getBaseType()->getStorageBytes() < 32) if (_type.isByteArray() || _type.baseType()->storageBytes() < 32)
clearStorageLoop(IntegerType(256)); clearStorageLoop(IntegerType(256));
else else
clearStorageLoop(*_type.getBaseType()); clearStorageLoop(*_type.baseType());
m_context << resizeEnd; m_context << resizeEnd;
// cleanup // cleanup
m_context << eth::Instruction::POP << eth::Instruction::POP << eth::Instruction::POP; m_context << eth::Instruction::POP << eth::Instruction::POP << eth::Instruction::POP;
solAssert(m_context.getStackHeight() == stackHeightStart - 2, ""); solAssert(m_context.stackHeight() == stackHeightStart - 2, "");
} }
void ArrayUtils::clearStorageLoop(Type const& _type) const void ArrayUtils::clearStorageLoop(Type const& _type) const
{ {
unsigned stackHeightStart = m_context.getStackHeight(); unsigned stackHeightStart = m_context.stackHeight();
if (_type.getCategory() == Type::Category::Mapping) if (_type.category() == Type::Category::Mapping)
{ {
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
return; return;
@ -602,16 +602,16 @@ void ArrayUtils::clearStorageLoop(Type const& _type) const
m_context << eth::Instruction::JUMP; m_context << eth::Instruction::JUMP;
m_context << returnTag; m_context << returnTag;
solAssert(m_context.getStackHeight() == stackHeightStart - 1, ""); solAssert(m_context.stackHeight() == stackHeightStart - 1, "");
} }
void ArrayUtils::convertLengthToSize(ArrayType const& _arrayType, bool _pad) const void ArrayUtils::convertLengthToSize(ArrayType const& _arrayType, bool _pad) const
{ {
if (_arrayType.location() == DataLocation::Storage) if (_arrayType.location() == DataLocation::Storage)
{ {
if (_arrayType.getBaseType()->getStorageSize() <= 1) if (_arrayType.baseType()->storageSize() <= 1)
{ {
unsigned baseBytes = _arrayType.getBaseType()->getStorageBytes(); unsigned baseBytes = _arrayType.baseType()->storageBytes();
if (baseBytes == 0) if (baseBytes == 0)
m_context << eth::Instruction::POP << u256(1); m_context << eth::Instruction::POP << u256(1);
else if (baseBytes <= 16) else if (baseBytes <= 16)
@ -623,16 +623,16 @@ void ArrayUtils::convertLengthToSize(ArrayType const& _arrayType, bool _pad) con
} }
} }
else else
m_context << _arrayType.getBaseType()->getStorageSize() << eth::Instruction::MUL; m_context << _arrayType.baseType()->storageSize() << eth::Instruction::MUL;
} }
else else
{ {
if (!_arrayType.isByteArray()) if (!_arrayType.isByteArray())
{ {
if (_arrayType.location() == DataLocation::Memory) if (_arrayType.location() == DataLocation::Memory)
m_context << _arrayType.getBaseType()->memoryHeadSize(); m_context << _arrayType.baseType()->memoryHeadSize();
else else
m_context << _arrayType.getBaseType()->getCalldataEncodedSize(); m_context << _arrayType.baseType()->calldataEncodedSize();
m_context << eth::Instruction::MUL; m_context << eth::Instruction::MUL;
} }
else if (_pad) else if (_pad)
@ -645,7 +645,7 @@ void ArrayUtils::convertLengthToSize(ArrayType const& _arrayType, bool _pad) con
void ArrayUtils::retrieveLength(ArrayType const& _arrayType) const void ArrayUtils::retrieveLength(ArrayType const& _arrayType) const
{ {
if (!_arrayType.isDynamicallySized()) if (!_arrayType.isDynamicallySized())
m_context << _arrayType.getLength(); m_context << _arrayType.length();
else else
{ {
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
@ -676,7 +676,7 @@ void ArrayUtils::accessIndex(ArrayType const& _arrayType, bool _doBoundsCheck) c
{ {
// retrieve length // retrieve length
if (!_arrayType.isDynamicallySized()) if (!_arrayType.isDynamicallySized())
m_context << _arrayType.getLength(); m_context << _arrayType.length();
else if (location == DataLocation::CallData) else if (location == DataLocation::CallData)
// length is stored on the stack // length is stored on the stack
m_context << eth::Instruction::SWAP1; m_context << eth::Instruction::SWAP1;
@ -710,7 +710,7 @@ void ArrayUtils::accessIndex(ArrayType const& _arrayType, bool _doBoundsCheck) c
{ {
m_context << eth::Instruction::SWAP1; m_context << eth::Instruction::SWAP1;
if (location == DataLocation::CallData) if (location == DataLocation::CallData)
m_context << _arrayType.getBaseType()->getCalldataEncodedSize(); m_context << _arrayType.baseType()->calldataEncodedSize();
else else
m_context << u256(_arrayType.memoryHeadSize()); m_context << u256(_arrayType.memoryHeadSize());
m_context << eth::Instruction::MUL; m_context << eth::Instruction::MUL;
@ -719,12 +719,12 @@ void ArrayUtils::accessIndex(ArrayType const& _arrayType, bool _doBoundsCheck) c
break; break;
case DataLocation::Storage: case DataLocation::Storage:
m_context << eth::Instruction::SWAP1; m_context << eth::Instruction::SWAP1;
if (_arrayType.getBaseType()->getStorageBytes() <= 16) if (_arrayType.baseType()->storageBytes() <= 16)
{ {
// stack: <data_ref> <index> // stack: <data_ref> <index>
// goal: // goal:
// <ref> <byte_number> = <base_ref + index / itemsPerSlot> <(index % itemsPerSlot) * byteSize> // <ref> <byte_number> = <base_ref + index / itemsPerSlot> <(index % itemsPerSlot) * byteSize>
unsigned byteSize = _arrayType.getBaseType()->getStorageBytes(); unsigned byteSize = _arrayType.baseType()->storageBytes();
solAssert(byteSize != 0, ""); solAssert(byteSize != 0, "");
unsigned itemsPerSlot = 32 / byteSize; unsigned itemsPerSlot = 32 / byteSize;
m_context << u256(itemsPerSlot) << eth::Instruction::SWAP2; m_context << u256(itemsPerSlot) << eth::Instruction::SWAP2;
@ -740,8 +740,8 @@ void ArrayUtils::accessIndex(ArrayType const& _arrayType, bool _doBoundsCheck) c
} }
else else
{ {
if (_arrayType.getBaseType()->getStorageSize() != 1) if (_arrayType.baseType()->storageSize() != 1)
m_context << _arrayType.getBaseType()->getStorageSize() << eth::Instruction::MUL; m_context << _arrayType.baseType()->storageSize() << eth::Instruction::MUL;
m_context << eth::Instruction::ADD << u256(0); m_context << eth::Instruction::ADD << u256(0);
} }
break; break;

View File

@ -41,8 +41,8 @@ class StackHeightChecker
{ {
public: public:
StackHeightChecker(CompilerContext const& _context): StackHeightChecker(CompilerContext const& _context):
m_context(_context), stackHeight(m_context.getStackHeight()) {} m_context(_context), stackHeight(m_context.stackHeight()) {}
void check() { solAssert(m_context.getStackHeight() == stackHeight, "I sense a disturbance in the stack."); } void check() { solAssert(m_context.stackHeight() == stackHeight, "I sense a disturbance in the stack."); }
private: private:
CompilerContext const& m_context; CompilerContext const& m_context;
unsigned stackHeight; unsigned stackHeight;
@ -79,7 +79,7 @@ void Compiler::compileClone(
appendInitAndConstructorCode(_contract); appendInitAndConstructorCode(_contract);
//@todo determine largest return size of all runtime functions //@todo determine largest return size of all runtime functions
eth::AssemblyItem runtimeSub = m_context.addSubroutine(getCloneRuntime()); eth::AssemblyItem runtimeSub = m_context.addSubroutine(cloneRuntime());
solAssert(runtimeSub.data() < numeric_limits<size_t>::max(), ""); solAssert(runtimeSub.data() < numeric_limits<size_t>::max(), "");
m_runtimeSub = size_t(runtimeSub.data()); m_runtimeSub = size_t(runtimeSub.data());
@ -93,9 +93,9 @@ void Compiler::compileClone(
m_context.optimise(m_optimizeRuns); m_context.optimise(m_optimizeRuns);
} }
eth::AssemblyItem Compiler::getFunctionEntryLabel(FunctionDefinition const& _function) const eth::AssemblyItem Compiler::functionEntryLabel(FunctionDefinition const& _function) const
{ {
return m_runtimeContext.getFunctionEntryLabelIfExists(_function); return m_runtimeContext.functionEntryLabelIfExists(_function);
} }
void Compiler::initializeContext(ContractDefinition const& _contract, void Compiler::initializeContext(ContractDefinition const& _contract,
@ -103,7 +103,7 @@ void Compiler::initializeContext(ContractDefinition const& _contract,
{ {
CompilerUtils(m_context).initialiseFreeMemoryPointer(); CompilerUtils(m_context).initialiseFreeMemoryPointer();
m_context.setCompiledContracts(_contracts); m_context.setCompiledContracts(_contracts);
m_context.setInheritanceHierarchy(_contract.getLinearizedBaseContracts()); m_context.setInheritanceHierarchy(_contract.linearizedBaseContracts());
registerStateVariables(_contract); registerStateVariables(_contract);
m_context.resetVisitedNodes(&_contract); m_context.resetVisitedNodes(&_contract);
} }
@ -111,36 +111,36 @@ void Compiler::initializeContext(ContractDefinition const& _contract,
void Compiler::appendInitAndConstructorCode(ContractDefinition const& _contract) void Compiler::appendInitAndConstructorCode(ContractDefinition const& _contract)
{ {
// Determine the arguments that are used for the base constructors. // Determine the arguments that are used for the base constructors.
std::vector<ContractDefinition const*> const& bases = _contract.getLinearizedBaseContracts(); std::vector<ContractDefinition const*> const& bases = _contract.linearizedBaseContracts();
for (ContractDefinition const* contract: bases) for (ContractDefinition const* contract: bases)
{ {
if (FunctionDefinition const* constructor = contract->getConstructor()) if (FunctionDefinition const* constructor = contract->constructor())
for (auto const& modifier: constructor->getModifiers()) for (auto const& modifier: constructor->modifiers())
{ {
auto baseContract = dynamic_cast<ContractDefinition const*>( auto baseContract = dynamic_cast<ContractDefinition const*>(
&modifier->getName()->getReferencedDeclaration()); &modifier->name()->referencedDeclaration());
if (baseContract) if (baseContract)
if (m_baseArguments.count(baseContract->getConstructor()) == 0) if (m_baseArguments.count(baseContract->constructor()) == 0)
m_baseArguments[baseContract->getConstructor()] = &modifier->getArguments(); m_baseArguments[baseContract->constructor()] = &modifier->arguments();
} }
for (ASTPointer<InheritanceSpecifier> const& base: contract->getBaseContracts()) for (ASTPointer<InheritanceSpecifier> const& base: contract->baseContracts())
{ {
ContractDefinition const* baseContract = dynamic_cast<ContractDefinition const*>( ContractDefinition const* baseContract = dynamic_cast<ContractDefinition const*>(
&base->getName()->getReferencedDeclaration()); &base->name()->referencedDeclaration());
solAssert(baseContract, ""); solAssert(baseContract, "");
if (m_baseArguments.count(baseContract->getConstructor()) == 0) if (m_baseArguments.count(baseContract->constructor()) == 0)
m_baseArguments[baseContract->getConstructor()] = &base->getArguments(); m_baseArguments[baseContract->constructor()] = &base->arguments();
} }
} }
// Initialization of state variables in base-to-derived order. // Initialization of state variables in base-to-derived order.
for (ContractDefinition const* contract: boost::adaptors::reverse(bases)) for (ContractDefinition const* contract: boost::adaptors::reverse(bases))
initializeStateVariables(*contract); initializeStateVariables(*contract);
if (FunctionDefinition const* constructor = _contract.getConstructor()) if (FunctionDefinition const* constructor = _contract.constructor())
appendConstructor(*constructor); appendConstructor(*constructor);
else if (auto c = m_context.getNextConstructor(_contract)) else if (auto c = m_context.nextConstructor(_contract))
appendBaseConstructor(*c); appendBaseConstructor(*c);
} }
@ -148,7 +148,7 @@ void Compiler::packIntoContractCreator(ContractDefinition const& _contract, Comp
{ {
appendInitAndConstructorCode(_contract); appendInitAndConstructorCode(_contract);
eth::AssemblyItem runtimeSub = m_context.addSubroutine(_runtimeContext.getAssembly()); eth::AssemblyItem runtimeSub = m_context.addSubroutine(_runtimeContext.assembly());
solAssert(runtimeSub.data() < numeric_limits<size_t>::max(), ""); solAssert(runtimeSub.data() < numeric_limits<size_t>::max(), "");
m_runtimeSub = size_t(runtimeSub.data()); m_runtimeSub = size_t(runtimeSub.data());
@ -164,13 +164,13 @@ void Compiler::appendBaseConstructor(FunctionDefinition const& _constructor)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _constructor); CompilerContext::LocationSetter locationSetter(m_context, _constructor);
FunctionType constructorType(_constructor); FunctionType constructorType(_constructor);
if (!constructorType.getParameterTypes().empty()) if (!constructorType.parameterTypes().empty())
{ {
solAssert(m_baseArguments.count(&_constructor), ""); solAssert(m_baseArguments.count(&_constructor), "");
std::vector<ASTPointer<Expression>> const* arguments = m_baseArguments[&_constructor]; std::vector<ASTPointer<Expression>> const* arguments = m_baseArguments[&_constructor];
solAssert(arguments, ""); solAssert(arguments, "");
for (unsigned i = 0; i < arguments->size(); ++i) for (unsigned i = 0; i < arguments->size(); ++i)
compileExpression(*(arguments->at(i)), constructorType.getParameterTypes()[i]); compileExpression(*(arguments->at(i)), constructorType.parameterTypes()[i]);
} }
_constructor.accept(*this); _constructor.accept(*this);
} }
@ -179,17 +179,17 @@ void Compiler::appendConstructor(FunctionDefinition const& _constructor)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _constructor); CompilerContext::LocationSetter locationSetter(m_context, _constructor);
// copy constructor arguments from code to memory and then to stack, they are supplied after the actual program // copy constructor arguments from code to memory and then to stack, they are supplied after the actual program
if (!_constructor.getParameters().empty()) if (!_constructor.parameters().empty())
{ {
unsigned argumentSize = 0; unsigned argumentSize = 0;
for (ASTPointer<VariableDeclaration> const& var: _constructor.getParameters()) for (ASTPointer<VariableDeclaration> const& var: _constructor.parameters())
if (var->getType()->isDynamicallySized()) if (var->type()->isDynamicallySized())
{ {
argumentSize = 0; argumentSize = 0;
break; break;
} }
else else
argumentSize += var->getType()->getCalldataEncodedSize(); argumentSize += var->type()->calldataEncodedSize();
CompilerUtils(m_context).fetchFreeMemoryPointer(); CompilerUtils(m_context).fetchFreeMemoryPointer();
if (argumentSize == 0) if (argumentSize == 0)
@ -208,7 +208,7 @@ void Compiler::appendConstructor(FunctionDefinition const& _constructor)
m_context << eth::Instruction::ADD; m_context << eth::Instruction::ADD;
CompilerUtils(m_context).storeFreeMemoryPointer(); CompilerUtils(m_context).storeFreeMemoryPointer();
appendCalldataUnpacker( appendCalldataUnpacker(
FunctionType(_constructor).getParameterTypes(), FunctionType(_constructor).parameterTypes(),
true, true,
CompilerUtils::freeMemoryPointer + 0x20 CompilerUtils::freeMemoryPointer + 0x20
); );
@ -218,10 +218,10 @@ void Compiler::appendConstructor(FunctionDefinition const& _constructor)
void Compiler::appendFunctionSelector(ContractDefinition const& _contract) void Compiler::appendFunctionSelector(ContractDefinition const& _contract)
{ {
map<FixedHash<4>, FunctionTypePointer> interfaceFunctions = _contract.getInterfaceFunctions(); map<FixedHash<4>, FunctionTypePointer> interfaceFunctions = _contract.interfaceFunctions();
map<FixedHash<4>, const eth::AssemblyItem> callDataUnpackerEntryPoints; map<FixedHash<4>, const eth::AssemblyItem> callDataUnpackerEntryPoints;
FunctionDefinition const* fallback = _contract.getFallbackFunction(); FunctionDefinition const* fallback = _contract.fallbackFunction();
eth::AssemblyItem notFound = m_context.newTag(); eth::AssemblyItem notFound = m_context.newTag();
// shortcut messages without data if we have many functions in order to be able to receive // shortcut messages without data if we have many functions in order to be able to receive
// ether with constant gas // ether with constant gas
@ -250,7 +250,7 @@ void Compiler::appendFunctionSelector(ContractDefinition const& _contract)
eth::AssemblyItem returnTag = m_context.pushNewTag(); eth::AssemblyItem returnTag = m_context.pushNewTag();
fallback->accept(*this); fallback->accept(*this);
m_context << returnTag; m_context << returnTag;
appendReturnValuePacker(FunctionType(*fallback).getReturnParameterTypes()); appendReturnValuePacker(FunctionType(*fallback).returnParameterTypes());
} }
else else
m_context << eth::Instruction::STOP; // function not found m_context << eth::Instruction::STOP; // function not found
@ -259,13 +259,13 @@ void Compiler::appendFunctionSelector(ContractDefinition const& _contract)
{ {
FunctionTypePointer const& functionType = it.second; FunctionTypePointer const& functionType = it.second;
solAssert(functionType->hasDeclaration(), ""); solAssert(functionType->hasDeclaration(), "");
CompilerContext::LocationSetter locationSetter(m_context, functionType->getDeclaration()); CompilerContext::LocationSetter locationSetter(m_context, functionType->declaration());
m_context << callDataUnpackerEntryPoints.at(it.first); m_context << callDataUnpackerEntryPoints.at(it.first);
eth::AssemblyItem returnTag = m_context.pushNewTag(); eth::AssemblyItem returnTag = m_context.pushNewTag();
appendCalldataUnpacker(functionType->getParameterTypes()); appendCalldataUnpacker(functionType->parameterTypes());
m_context.appendJumpTo(m_context.getFunctionEntryLabel(functionType->getDeclaration())); m_context.appendJumpTo(m_context.functionEntryLabel(functionType->declaration()));
m_context << returnTag; m_context << returnTag;
appendReturnValuePacker(functionType->getReturnParameterTypes()); appendReturnValuePacker(functionType->returnParameterTypes());
} }
} }
@ -286,17 +286,17 @@ void Compiler::appendCalldataUnpacker(
for (TypePointer const& type: _typeParameters) for (TypePointer const& type: _typeParameters)
{ {
// stack: v1 v2 ... v(k-1) mem_offset // stack: v1 v2 ... v(k-1) mem_offset
switch (type->getCategory()) switch (type->category())
{ {
case Type::Category::Array: case Type::Category::Array:
{ {
auto const& arrayType = dynamic_cast<ArrayType const&>(*type); auto const& arrayType = dynamic_cast<ArrayType const&>(*type);
solAssert(arrayType.location() != DataLocation::Storage, ""); solAssert(arrayType.location() != DataLocation::Storage, "");
solAssert(!arrayType.getBaseType()->isDynamicallySized(), "Nested arrays not yet implemented."); solAssert(!arrayType.baseType()->isDynamicallySized(), "Nested arrays not yet implemented.");
if (_fromMemory) if (_fromMemory)
{ {
solAssert( solAssert(
arrayType.getBaseType()->isValueType(), arrayType.baseType()->isValueType(),
"Nested memory arrays not yet implemented here." "Nested memory arrays not yet implemented here."
); );
// @todo If base type is an array or struct, it is still calldata-style encoded, so // @todo If base type is an array or struct, it is still calldata-style encoded, so
@ -329,17 +329,17 @@ void Compiler::appendCalldataUnpacker(
{ {
// leave the pointer on the stack // leave the pointer on the stack
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
m_context << u256(calldataType->getCalldataEncodedSize()) << eth::Instruction::ADD; m_context << u256(calldataType->calldataEncodedSize()) << eth::Instruction::ADD;
} }
if (arrayType.location() == DataLocation::Memory) if (arrayType.location() == DataLocation::Memory)
{ {
// stack: calldata_ref [length] next_calldata // stack: calldata_ref [length] next_calldata
// copy to memory // copy to memory
// move calldata type up again // move calldata type up again
CompilerUtils(m_context).moveIntoStack(calldataType->getSizeOnStack()); CompilerUtils(m_context).moveIntoStack(calldataType->sizeOnStack());
CompilerUtils(m_context).convertType(*calldataType, arrayType); CompilerUtils(m_context).convertType(*calldataType, arrayType);
// fetch next pointer again // fetch next pointer again
CompilerUtils(m_context).moveToStackTop(arrayType.getSizeOnStack()); CompilerUtils(m_context).moveToStackTop(arrayType.sizeOnStack());
} }
} }
break; break;
@ -370,14 +370,14 @@ void Compiler::appendReturnValuePacker(TypePointers const& _typeParameters)
void Compiler::registerStateVariables(ContractDefinition const& _contract) void Compiler::registerStateVariables(ContractDefinition const& _contract)
{ {
for (auto const& var: ContractType(_contract).getStateVariables()) for (auto const& var: ContractType(_contract).stateVariables())
m_context.addStateVariable(*get<0>(var), get<1>(var), get<2>(var)); m_context.addStateVariable(*get<0>(var), get<1>(var), get<2>(var));
} }
void Compiler::initializeStateVariables(ContractDefinition const& _contract) void Compiler::initializeStateVariables(ContractDefinition const& _contract)
{ {
for (ASTPointer<VariableDeclaration> const& variable: _contract.getStateVariables()) for (ASTPointer<VariableDeclaration> const& variable: _contract.stateVariables())
if (variable->getValue() && !variable->isConstant()) if (variable->value() && !variable->isConstant())
ExpressionCompiler(m_context, m_optimize).appendStateVariableInitialization(*variable); ExpressionCompiler(m_context, m_optimize).appendStateVariableInitialization(*variable);
} }
@ -407,23 +407,23 @@ bool Compiler::visit(FunctionDefinition const& _function)
// stack upon entry: [return address] [arg0] [arg1] ... [argn] // stack upon entry: [return address] [arg0] [arg1] ... [argn]
// reserve additional slots: [retarg0] ... [retargm] [localvar0] ... [localvarp] // reserve additional slots: [retarg0] ... [retargm] [localvar0] ... [localvarp]
unsigned parametersSize = CompilerUtils::getSizeOnStack(_function.getParameters()); unsigned parametersSize = CompilerUtils::sizeOnStack(_function.parameters());
if (!_function.isConstructor()) if (!_function.isConstructor())
// adding 1 for return address. // adding 1 for return address.
m_context.adjustStackOffset(parametersSize + 1); m_context.adjustStackOffset(parametersSize + 1);
for (ASTPointer<VariableDeclaration const> const& variable: _function.getParameters()) for (ASTPointer<VariableDeclaration const> const& variable: _function.parameters())
{ {
m_context.addVariable(*variable, parametersSize); m_context.addVariable(*variable, parametersSize);
parametersSize -= variable->getType()->getSizeOnStack(); parametersSize -= variable->type()->sizeOnStack();
} }
for (ASTPointer<VariableDeclaration const> const& variable: _function.getReturnParameters()) for (ASTPointer<VariableDeclaration const> const& variable: _function.returnParameters())
appendStackVariableInitialisation(*variable); appendStackVariableInitialisation(*variable);
for (VariableDeclaration const* localVariable: _function.getLocalVariables()) for (VariableDeclaration const* localVariable: _function.localVariables())
appendStackVariableInitialisation(*localVariable); appendStackVariableInitialisation(*localVariable);
if (_function.isConstructor()) if (_function.isConstructor())
if (auto c = m_context.getNextConstructor(dynamic_cast<ContractDefinition const&>(*_function.getScope()))) if (auto c = m_context.nextConstructor(dynamic_cast<ContractDefinition const&>(*_function.scope())))
appendBaseConstructor(*c); appendBaseConstructor(*c);
m_returnTag = m_context.newTag(); m_returnTag = m_context.newTag();
@ -443,9 +443,9 @@ bool Compiler::visit(FunctionDefinition const& _function)
// Note that the fact that the return arguments are of increasing index is vital for this // Note that the fact that the return arguments are of increasing index is vital for this
// algorithm to work. // algorithm to work.
unsigned const c_argumentsSize = CompilerUtils::getSizeOnStack(_function.getParameters()); unsigned const c_argumentsSize = CompilerUtils::sizeOnStack(_function.parameters());
unsigned const c_returnValuesSize = CompilerUtils::getSizeOnStack(_function.getReturnParameters()); unsigned const c_returnValuesSize = CompilerUtils::sizeOnStack(_function.returnParameters());
unsigned const c_localVariablesSize = CompilerUtils::getSizeOnStack(_function.getLocalVariables()); unsigned const c_localVariablesSize = CompilerUtils::sizeOnStack(_function.localVariables());
vector<int> stackLayout; vector<int> stackLayout;
stackLayout.push_back(c_returnValuesSize); // target of return address stackLayout.push_back(c_returnValuesSize); // target of return address
@ -468,9 +468,9 @@ bool Compiler::visit(FunctionDefinition const& _function)
} }
//@todo assert that everything is in place now //@todo assert that everything is in place now
for (ASTPointer<VariableDeclaration const> const& variable: _function.getParameters() + _function.getReturnParameters()) for (ASTPointer<VariableDeclaration const> const& variable: _function.parameters() + _function.returnParameters())
m_context.removeVariable(*variable); m_context.removeVariable(*variable);
for (VariableDeclaration const* localVariable: _function.getLocalVariables()) for (VariableDeclaration const* localVariable: _function.localVariables())
m_context.removeVariable(*localVariable); m_context.removeVariable(*localVariable);
m_context.adjustStackOffset(-(int)c_returnValuesSize); m_context.adjustStackOffset(-(int)c_returnValuesSize);
@ -484,16 +484,16 @@ bool Compiler::visit(IfStatement const& _ifStatement)
{ {
StackHeightChecker checker(m_context); StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _ifStatement); CompilerContext::LocationSetter locationSetter(m_context, _ifStatement);
compileExpression(_ifStatement.getCondition()); compileExpression(_ifStatement.condition());
m_context << eth::Instruction::ISZERO; m_context << eth::Instruction::ISZERO;
eth::AssemblyItem falseTag = m_context.appendConditionalJump(); eth::AssemblyItem falseTag = m_context.appendConditionalJump();
eth::AssemblyItem endTag = falseTag; eth::AssemblyItem endTag = falseTag;
_ifStatement.getTrueStatement().accept(*this); _ifStatement.trueStatement().accept(*this);
if (_ifStatement.getFalseStatement()) if (_ifStatement.falseStatement())
{ {
endTag = m_context.appendJumpToNew(); endTag = m_context.appendJumpToNew();
m_context << falseTag; m_context << falseTag;
_ifStatement.getFalseStatement()->accept(*this); _ifStatement.falseStatement()->accept(*this);
} }
m_context << endTag; m_context << endTag;
@ -511,11 +511,11 @@ bool Compiler::visit(WhileStatement const& _whileStatement)
m_breakTags.push_back(loopEnd); m_breakTags.push_back(loopEnd);
m_context << loopStart; m_context << loopStart;
compileExpression(_whileStatement.getCondition()); compileExpression(_whileStatement.condition());
m_context << eth::Instruction::ISZERO; m_context << eth::Instruction::ISZERO;
m_context.appendConditionalJumpTo(loopEnd); m_context.appendConditionalJumpTo(loopEnd);
_whileStatement.getBody().accept(*this); _whileStatement.body().accept(*this);
m_context.appendJumpTo(loopStart); m_context.appendJumpTo(loopStart);
m_context << loopEnd; m_context << loopEnd;
@ -537,26 +537,26 @@ bool Compiler::visit(ForStatement const& _forStatement)
m_continueTags.push_back(loopNext); m_continueTags.push_back(loopNext);
m_breakTags.push_back(loopEnd); m_breakTags.push_back(loopEnd);
if (_forStatement.getInitializationExpression()) if (_forStatement.initializationExpression())
_forStatement.getInitializationExpression()->accept(*this); _forStatement.initializationExpression()->accept(*this);
m_context << loopStart; m_context << loopStart;
// if there is no terminating condition in for, default is to always be true // if there is no terminating condition in for, default is to always be true
if (_forStatement.getCondition()) if (_forStatement.condition())
{ {
compileExpression(*_forStatement.getCondition()); compileExpression(*_forStatement.condition());
m_context << eth::Instruction::ISZERO; m_context << eth::Instruction::ISZERO;
m_context.appendConditionalJumpTo(loopEnd); m_context.appendConditionalJumpTo(loopEnd);
} }
_forStatement.getBody().accept(*this); _forStatement.body().accept(*this);
m_context << loopNext; m_context << loopNext;
// for's loop expression if existing // for's loop expression if existing
if (_forStatement.getLoopExpression()) if (_forStatement.loopExpression())
_forStatement.getLoopExpression()->accept(*this); _forStatement.loopExpression()->accept(*this);
m_context.appendJumpTo(loopStart); m_context.appendJumpTo(loopStart);
m_context << loopEnd; m_context << loopEnd;
@ -588,11 +588,11 @@ bool Compiler::visit(Return const& _return)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _return); CompilerContext::LocationSetter locationSetter(m_context, _return);
//@todo modifications are needed to make this work with functions returning multiple values //@todo modifications are needed to make this work with functions returning multiple values
if (Expression const* expression = _return.getExpression()) if (Expression const* expression = _return.expression())
{ {
solAssert(_return.getFunctionReturnParameters(), "Invalid return parameters pointer."); solAssert(_return.functionReturnParameters(), "Invalid return parameters pointer.");
VariableDeclaration const& firstVariable = *_return.getFunctionReturnParameters()->getParameters().front(); VariableDeclaration const& firstVariable = *_return.functionReturnParameters()->parameters().front();
compileExpression(*expression, firstVariable.getType()); compileExpression(*expression, firstVariable.type());
CompilerUtils(m_context).moveToStackVariable(firstVariable); CompilerUtils(m_context).moveToStackVariable(firstVariable);
} }
for (unsigned i = 0; i < m_stackCleanupForReturn; ++i) for (unsigned i = 0; i < m_stackCleanupForReturn; ++i)
@ -606,10 +606,10 @@ bool Compiler::visit(VariableDeclarationStatement const& _variableDeclarationSta
{ {
StackHeightChecker checker(m_context); StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _variableDeclarationStatement); CompilerContext::LocationSetter locationSetter(m_context, _variableDeclarationStatement);
if (Expression const* expression = _variableDeclarationStatement.getExpression()) if (Expression const* expression = _variableDeclarationStatement.expression())
{ {
compileExpression(*expression, _variableDeclarationStatement.getDeclaration().getType()); compileExpression(*expression, _variableDeclarationStatement.declaration().type());
CompilerUtils(m_context).moveToStackVariable(_variableDeclarationStatement.getDeclaration()); CompilerUtils(m_context).moveToStackVariable(_variableDeclarationStatement.declaration());
} }
checker.check(); checker.check();
return false; return false;
@ -619,9 +619,9 @@ bool Compiler::visit(ExpressionStatement const& _expressionStatement)
{ {
StackHeightChecker checker(m_context); StackHeightChecker checker(m_context);
CompilerContext::LocationSetter locationSetter(m_context, _expressionStatement); CompilerContext::LocationSetter locationSetter(m_context, _expressionStatement);
Expression const& expression = _expressionStatement.getExpression(); Expression const& expression = _expressionStatement.expression();
compileExpression(expression); compileExpression(expression);
CompilerUtils(m_context).popStackElement(*expression.getType()); CompilerUtils(m_context).popStackElement(*expression.type());
checker.check(); checker.check();
return false; return false;
} }
@ -639,7 +639,7 @@ bool Compiler::visit(PlaceholderStatement const& _placeholderStatement)
void Compiler::appendFunctionsWithoutCode() void Compiler::appendFunctionsWithoutCode()
{ {
set<Declaration const*> functions = m_context.getFunctionsWithoutCode(); set<Declaration const*> functions = m_context.functionsWithoutCode();
while (!functions.empty()) while (!functions.empty())
{ {
for (Declaration const* function: functions) for (Declaration const* function: functions)
@ -647,21 +647,21 @@ void Compiler::appendFunctionsWithoutCode()
m_context.setStackOffset(0); m_context.setStackOffset(0);
function->accept(*this); function->accept(*this);
} }
functions = m_context.getFunctionsWithoutCode(); functions = m_context.functionsWithoutCode();
} }
} }
void Compiler::appendModifierOrFunctionCode() void Compiler::appendModifierOrFunctionCode()
{ {
solAssert(m_currentFunction, ""); solAssert(m_currentFunction, "");
if (m_modifierDepth >= m_currentFunction->getModifiers().size()) if (m_modifierDepth >= m_currentFunction->modifiers().size())
m_currentFunction->getBody().accept(*this); m_currentFunction->body().accept(*this);
else else
{ {
ASTPointer<ModifierInvocation> const& modifierInvocation = m_currentFunction->getModifiers()[m_modifierDepth]; ASTPointer<ModifierInvocation> const& modifierInvocation = m_currentFunction->modifiers()[m_modifierDepth];
// constructor call should be excluded // constructor call should be excluded
if (dynamic_cast<ContractDefinition const*>(&modifierInvocation->getName()->getReferencedDeclaration())) if (dynamic_cast<ContractDefinition const*>(&modifierInvocation->name()->referencedDeclaration()))
{ {
++m_modifierDepth; ++m_modifierDepth;
appendModifierOrFunctionCode(); appendModifierOrFunctionCode();
@ -669,23 +669,25 @@ void Compiler::appendModifierOrFunctionCode()
return; return;
} }
ModifierDefinition const& modifier = m_context.getFunctionModifier(modifierInvocation->getName()->getName()); ModifierDefinition const& modifier = m_context.functionModifier(modifierInvocation->name()->name());
CompilerContext::LocationSetter locationSetter(m_context, modifier); CompilerContext::LocationSetter locationSetter(m_context, modifier);
solAssert(modifier.getParameters().size() == modifierInvocation->getArguments().size(), ""); solAssert(modifier.parameters().size() == modifierInvocation->arguments().size(), "");
for (unsigned i = 0; i < modifier.getParameters().size(); ++i) for (unsigned i = 0; i < modifier.parameters().size(); ++i)
{ {
m_context.addVariable(*modifier.getParameters()[i]); m_context.addVariable(*modifier.parameters()[i]);
compileExpression(*modifierInvocation->getArguments()[i], compileExpression(
modifier.getParameters()[i]->getType()); *modifierInvocation->arguments()[i],
modifier.parameters()[i]->type()
);
} }
for (VariableDeclaration const* localVariable: modifier.getLocalVariables()) for (VariableDeclaration const* localVariable: modifier.localVariables())
appendStackVariableInitialisation(*localVariable); appendStackVariableInitialisation(*localVariable);
unsigned const c_stackSurplus = CompilerUtils::getSizeOnStack(modifier.getParameters()) + unsigned const c_stackSurplus = CompilerUtils::sizeOnStack(modifier.parameters()) +
CompilerUtils::getSizeOnStack(modifier.getLocalVariables()); CompilerUtils::sizeOnStack(modifier.localVariables());
m_stackCleanupForReturn += c_stackSurplus; m_stackCleanupForReturn += c_stackSurplus;
modifier.getBody().accept(*this); modifier.body().accept(*this);
for (unsigned i = 0; i < c_stackSurplus; ++i) for (unsigned i = 0; i < c_stackSurplus; ++i)
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
@ -697,7 +699,7 @@ void Compiler::appendStackVariableInitialisation(VariableDeclaration const& _var
{ {
CompilerContext::LocationSetter location(m_context, _variable); CompilerContext::LocationSetter location(m_context, _variable);
m_context.addVariable(_variable); m_context.addVariable(_variable);
CompilerUtils(m_context).pushZeroValue(*_variable.getType()); CompilerUtils(m_context).pushZeroValue(*_variable.type());
} }
void Compiler::compileExpression(Expression const& _expression, TypePointer const& _targetType) void Compiler::compileExpression(Expression const& _expression, TypePointer const& _targetType)
@ -705,10 +707,10 @@ void Compiler::compileExpression(Expression const& _expression, TypePointer cons
ExpressionCompiler expressionCompiler(m_context, m_optimize); ExpressionCompiler expressionCompiler(m_context, m_optimize);
expressionCompiler.compile(_expression); expressionCompiler.compile(_expression);
if (_targetType) if (_targetType)
CompilerUtils(m_context).convertType(*_expression.getType(), *_targetType); CompilerUtils(m_context).convertType(*_expression.type(), *_targetType);
} }
eth::Assembly Compiler::getCloneRuntime() eth::Assembly Compiler::cloneRuntime()
{ {
eth::Assembly a; eth::Assembly a;
a << eth::Instruction::CALLDATASIZE; a << eth::Instruction::CALLDATASIZE;

View File

@ -50,8 +50,8 @@ public:
ContractDefinition const& _contract, ContractDefinition const& _contract,
std::map<ContractDefinition const*, bytes const*> const& _contracts std::map<ContractDefinition const*, bytes const*> const& _contracts
); );
bytes getAssembledBytecode() { return m_context.getAssembledBytecode(); } bytes assembledBytecode() { return m_context.assembledBytecode(); }
bytes getRuntimeBytecode() { return m_context.getAssembledRuntimeBytecode(m_runtimeSub); } bytes runtimeBytecode() { return m_context.assembledRuntimeBytecode(m_runtimeSub); }
/// @arg _sourceCodes is the map of input files to source code strings /// @arg _sourceCodes is the map of input files to source code strings
/// @arg _inJsonFromat shows whether the out should be in Json format /// @arg _inJsonFromat shows whether the out should be in Json format
Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const
@ -59,13 +59,13 @@ public:
return m_context.streamAssembly(_stream, _sourceCodes, _inJsonFormat); return m_context.streamAssembly(_stream, _sourceCodes, _inJsonFormat);
} }
/// @returns Assembly items of the normal compiler context /// @returns Assembly items of the normal compiler context
eth::AssemblyItems const& getAssemblyItems() const { return m_context.getAssembly().getItems(); } eth::AssemblyItems const& assemblyItems() const { return m_context.assembly().getItems(); }
/// @returns Assembly items of the runtime compiler context /// @returns Assembly items of the runtime compiler context
eth::AssemblyItems const& getRuntimeAssemblyItems() const { return m_context.getAssembly().getSub(m_runtimeSub).getItems(); } eth::AssemblyItems const& runtimeAssemblyItems() const { return m_context.assembly().getSub(m_runtimeSub).getItems(); }
/// @returns the entry label of the given function. Might return an AssemblyItem of type /// @returns the entry label of the given function. Might return an AssemblyItem of type
/// UndefinedItem if it does not exist yet. /// UndefinedItem if it does not exist yet.
eth::AssemblyItem getFunctionEntryLabel(FunctionDefinition const& _function) const; eth::AssemblyItem functionEntryLabel(FunctionDefinition const& _function) const;
private: private:
/// Registers the non-function objects inside the contract with the context. /// Registers the non-function objects inside the contract with the context.
@ -122,7 +122,7 @@ private:
void compileExpression(Expression const& _expression, TypePointer const& _targetType = TypePointer()); void compileExpression(Expression const& _expression, TypePointer const& _targetType = TypePointer());
/// @returns the runtime assembly for clone contracts. /// @returns the runtime assembly for clone contracts.
static eth::Assembly getCloneRuntime(); static eth::Assembly cloneRuntime();
bool const m_optimize; bool const m_optimize;
unsigned const m_optimizeRuns; unsigned const m_optimizeRuns;

View File

@ -49,7 +49,7 @@ void CompilerContext::addStateVariable(
void CompilerContext::startFunction(Declaration const& _function) void CompilerContext::startFunction(Declaration const& _function)
{ {
m_functionsWithCode.insert(&_function); m_functionsWithCode.insert(&_function);
*this << getFunctionEntryLabel(_function); *this << functionEntryLabel(_function);
} }
void CompilerContext::addVariable(VariableDeclaration const& _declaration, void CompilerContext::addVariable(VariableDeclaration const& _declaration,
@ -65,7 +65,7 @@ void CompilerContext::removeVariable(VariableDeclaration const& _declaration)
m_localVariables.erase(&_declaration); m_localVariables.erase(&_declaration);
} }
bytes const& CompilerContext::getCompiledContract(const ContractDefinition& _contract) const bytes const& CompilerContext::compiledContract(const ContractDefinition& _contract) const
{ {
auto ret = m_compiledContracts.find(&_contract); auto ret = m_compiledContracts.find(&_contract);
solAssert(ret != m_compiledContracts.end(), "Compiled contract not found."); solAssert(ret != m_compiledContracts.end(), "Compiled contract not found.");
@ -77,7 +77,7 @@ bool CompilerContext::isLocalVariable(Declaration const* _declaration) const
return !!m_localVariables.count(_declaration); return !!m_localVariables.count(_declaration);
} }
eth::AssemblyItem CompilerContext::getFunctionEntryLabel(Declaration const& _declaration) eth::AssemblyItem CompilerContext::functionEntryLabel(Declaration const& _declaration)
{ {
auto res = m_functionEntryLabels.find(&_declaration); auto res = m_functionEntryLabels.find(&_declaration);
if (res == m_functionEntryLabels.end()) if (res == m_functionEntryLabels.end())
@ -90,35 +90,35 @@ eth::AssemblyItem CompilerContext::getFunctionEntryLabel(Declaration const& _dec
return res->second.tag(); return res->second.tag();
} }
eth::AssemblyItem CompilerContext::getFunctionEntryLabelIfExists(Declaration const& _declaration) const eth::AssemblyItem CompilerContext::functionEntryLabelIfExists(Declaration const& _declaration) const
{ {
auto res = m_functionEntryLabels.find(&_declaration); auto res = m_functionEntryLabels.find(&_declaration);
return res == m_functionEntryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag(); return res == m_functionEntryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag();
} }
eth::AssemblyItem CompilerContext::getVirtualFunctionEntryLabel(FunctionDefinition const& _function) eth::AssemblyItem CompilerContext::virtualFunctionEntryLabel(FunctionDefinition const& _function)
{ {
solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set.");
return getVirtualFunctionEntryLabel(_function, m_inheritanceHierarchy.begin()); return virtualFunctionEntryLabel(_function, m_inheritanceHierarchy.begin());
} }
eth::AssemblyItem CompilerContext::getSuperFunctionEntryLabel(FunctionDefinition const& _function, ContractDefinition const& _base) eth::AssemblyItem CompilerContext::superFunctionEntryLabel(FunctionDefinition const& _function, ContractDefinition const& _base)
{ {
solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set.");
return getVirtualFunctionEntryLabel(_function, getSuperContract(_base)); return virtualFunctionEntryLabel(_function, superContract(_base));
} }
FunctionDefinition const* CompilerContext::getNextConstructor(ContractDefinition const& _contract) const FunctionDefinition const* CompilerContext::nextConstructor(ContractDefinition const& _contract) const
{ {
vector<ContractDefinition const*>::const_iterator it = getSuperContract(_contract); vector<ContractDefinition const*>::const_iterator it = superContract(_contract);
for (; it != m_inheritanceHierarchy.end(); ++it) for (; it != m_inheritanceHierarchy.end(); ++it)
if ((*it)->getConstructor()) if ((*it)->constructor())
return (*it)->getConstructor(); return (*it)->constructor();
return nullptr; return nullptr;
} }
set<Declaration const*> CompilerContext::getFunctionsWithoutCode() set<Declaration const*> CompilerContext::functionsWithoutCode()
{ {
set<Declaration const*> functions; set<Declaration const*> functions;
for (auto const& it: m_functionEntryLabels) for (auto const& it: m_functionEntryLabels)
@ -127,18 +127,18 @@ set<Declaration const*> CompilerContext::getFunctionsWithoutCode()
return functions; return functions;
} }
ModifierDefinition const& CompilerContext::getFunctionModifier(string const& _name) const ModifierDefinition const& CompilerContext::functionModifier(string const& _name) const
{ {
solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set.");
for (ContractDefinition const* contract: m_inheritanceHierarchy) for (ContractDefinition const* contract: m_inheritanceHierarchy)
for (ASTPointer<ModifierDefinition> const& modifier: contract->getFunctionModifiers()) for (ASTPointer<ModifierDefinition> const& modifier: contract->functionModifiers())
if (modifier->getName() == _name) if (modifier->name() == _name)
return *modifier.get(); return *modifier.get();
BOOST_THROW_EXCEPTION(InternalCompilerError() BOOST_THROW_EXCEPTION(InternalCompilerError()
<< errinfo_comment("Function modifier " + _name + " not found.")); << errinfo_comment("Function modifier " + _name + " not found."));
} }
unsigned CompilerContext::getBaseStackOffsetOfVariable(Declaration const& _declaration) const unsigned CompilerContext::baseStackOffsetOfVariable(Declaration const& _declaration) const
{ {
auto res = m_localVariables.find(&_declaration); auto res = m_localVariables.find(&_declaration);
solAssert(res != m_localVariables.end(), "Variable not found on stack."); solAssert(res != m_localVariables.end(), "Variable not found on stack.");
@ -155,7 +155,7 @@ unsigned CompilerContext::currentToBaseStackOffset(unsigned _offset) const
return m_asm.deposit() - _offset - 1; return m_asm.deposit() - _offset - 1;
} }
pair<u256, unsigned> CompilerContext::getStorageLocationOfVariable(const Declaration& _declaration) const pair<u256, unsigned> CompilerContext::storageLocationOfVariable(const Declaration& _declaration) const
{ {
auto it = m_stateVariables.find(&_declaration); auto it = m_stateVariables.find(&_declaration);
solAssert(it != m_stateVariables.end(), "Variable not found in storage."); solAssert(it != m_stateVariables.end(), "Variable not found in storage.");
@ -177,27 +177,27 @@ void CompilerContext::resetVisitedNodes(ASTNode const* _node)
updateSourceLocation(); updateSourceLocation();
} }
eth::AssemblyItem CompilerContext::getVirtualFunctionEntryLabel( eth::AssemblyItem CompilerContext::virtualFunctionEntryLabel(
FunctionDefinition const& _function, FunctionDefinition const& _function,
vector<ContractDefinition const*>::const_iterator _searchStart vector<ContractDefinition const*>::const_iterator _searchStart
) )
{ {
string name = _function.getName(); string name = _function.name();
FunctionType functionType(_function); FunctionType functionType(_function);
auto it = _searchStart; auto it = _searchStart;
for (; it != m_inheritanceHierarchy.end(); ++it) for (; it != m_inheritanceHierarchy.end(); ++it)
for (ASTPointer<FunctionDefinition> const& function: (*it)->getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: (*it)->definedFunctions())
if ( if (
function->getName() == name && function->name() == name &&
!function->isConstructor() && !function->isConstructor() &&
FunctionType(*function).hasEqualArgumentTypes(functionType) FunctionType(*function).hasEqualArgumentTypes(functionType)
) )
return getFunctionEntryLabel(*function); return functionEntryLabel(*function);
solAssert(false, "Super function " + name + " not found."); solAssert(false, "Super function " + name + " not found.");
return m_asm.newTag(); // not reached return m_asm.newTag(); // not reached
} }
vector<ContractDefinition const*>::const_iterator CompilerContext::getSuperContract(ContractDefinition const& _contract) const vector<ContractDefinition const*>::const_iterator CompilerContext::superContract(ContractDefinition const& _contract) const
{ {
solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set.");
auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract); auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract);
@ -207,7 +207,7 @@ vector<ContractDefinition const*>::const_iterator CompilerContext::getSuperContr
void CompilerContext::updateSourceLocation() void CompilerContext::updateSourceLocation()
{ {
m_asm.setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->getLocation()); m_asm.setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->location());
} }
} }

View File

@ -48,46 +48,46 @@ public:
void removeVariable(VariableDeclaration const& _declaration); void removeVariable(VariableDeclaration const& _declaration);
void setCompiledContracts(std::map<ContractDefinition const*, bytes const*> const& _contracts) { m_compiledContracts = _contracts; } void setCompiledContracts(std::map<ContractDefinition const*, bytes const*> const& _contracts) { m_compiledContracts = _contracts; }
bytes const& getCompiledContract(ContractDefinition const& _contract) const; bytes const& compiledContract(ContractDefinition const& _contract) const;
void setStackOffset(int _offset) { m_asm.setDeposit(_offset); } void setStackOffset(int _offset) { m_asm.setDeposit(_offset); }
void adjustStackOffset(int _adjustment) { m_asm.adjustDeposit(_adjustment); } void adjustStackOffset(int _adjustment) { m_asm.adjustDeposit(_adjustment); }
unsigned getStackHeight() const { solAssert(m_asm.deposit() >= 0, ""); return unsigned(m_asm.deposit()); } unsigned stackHeight() const { solAssert(m_asm.deposit() >= 0, ""); return unsigned(m_asm.deposit()); }
bool isMagicGlobal(Declaration const* _declaration) const { return m_magicGlobals.count(_declaration) != 0; } bool isMagicGlobal(Declaration const* _declaration) const { return m_magicGlobals.count(_declaration) != 0; }
bool isLocalVariable(Declaration const* _declaration) const; bool isLocalVariable(Declaration const* _declaration) const;
bool isStateVariable(Declaration const* _declaration) const { return m_stateVariables.count(_declaration) != 0; } bool isStateVariable(Declaration const* _declaration) const { return m_stateVariables.count(_declaration) != 0; }
/// @returns the entry label of the given function and creates it if it does not exist yet. /// @returns the entry label of the given function and creates it if it does not exist yet.
eth::AssemblyItem getFunctionEntryLabel(Declaration const& _declaration); eth::AssemblyItem functionEntryLabel(Declaration const& _declaration);
/// @returns the entry label of the given function. Might return an AssemblyItem of type /// @returns the entry label of the given function. Might return an AssemblyItem of type
/// UndefinedItem if it does not exist yet. /// UndefinedItem if it does not exist yet.
eth::AssemblyItem getFunctionEntryLabelIfExists(Declaration const& _declaration) const; eth::AssemblyItem functionEntryLabelIfExists(Declaration const& _declaration) const;
void setInheritanceHierarchy(std::vector<ContractDefinition const*> const& _hierarchy) { m_inheritanceHierarchy = _hierarchy; } void setInheritanceHierarchy(std::vector<ContractDefinition const*> const& _hierarchy) { m_inheritanceHierarchy = _hierarchy; }
/// @returns the entry label of the given function and takes overrides into account. /// @returns the entry label of the given function and takes overrides into account.
eth::AssemblyItem getVirtualFunctionEntryLabel(FunctionDefinition const& _function); eth::AssemblyItem virtualFunctionEntryLabel(FunctionDefinition const& _function);
/// @returns the entry label of a function that overrides the given declaration from the most derived class just /// @returns the entry label of a function that overrides the given declaration from the most derived class just
/// above _base in the current inheritance hierarchy. /// above _base in the current inheritance hierarchy.
eth::AssemblyItem getSuperFunctionEntryLabel(FunctionDefinition const& _function, ContractDefinition const& _base); eth::AssemblyItem superFunctionEntryLabel(FunctionDefinition const& _function, ContractDefinition const& _base);
FunctionDefinition const* getNextConstructor(ContractDefinition const& _contract) const; FunctionDefinition const* nextConstructor(ContractDefinition const& _contract) const;
/// @returns the set of functions for which we still need to generate code /// @returns the set of functions for which we still need to generate code
std::set<Declaration const*> getFunctionsWithoutCode(); std::set<Declaration const*> functionsWithoutCode();
/// Resets function specific members, inserts the function entry label and marks the function /// Resets function specific members, inserts the function entry label and marks the function
/// as "having code". /// as "having code".
void startFunction(Declaration const& _function); void startFunction(Declaration const& _function);
ModifierDefinition const& getFunctionModifier(std::string const& _name) const; ModifierDefinition const& functionModifier(std::string const& _name) const;
/// Returns the distance of the given local variable from the bottom of the stack (of the current function). /// Returns the distance of the given local variable from the bottom of the stack (of the current function).
unsigned getBaseStackOffsetOfVariable(Declaration const& _declaration) const; unsigned baseStackOffsetOfVariable(Declaration const& _declaration) const;
/// If supplied by a value returned by @ref getBaseStackOffsetOfVariable(variable), returns /// If supplied by a value returned by @ref baseStackOffsetOfVariable(variable), returns
/// the distance of that variable from the current top of the stack. /// the distance of that variable from the current top of the stack.
unsigned baseToCurrentStackOffset(unsigned _baseOffset) const; unsigned baseToCurrentStackOffset(unsigned _baseOffset) const;
/// Converts an offset relative to the current stack height to a value that can be used later /// Converts an offset relative to the current stack height to a value that can be used later
/// with baseToCurrentStackOffset to point to the same stack element. /// with baseToCurrentStackOffset to point to the same stack element.
unsigned currentToBaseStackOffset(unsigned _offset) const; unsigned currentToBaseStackOffset(unsigned _offset) const;
/// @returns pair of slot and byte offset of the value inside this slot. /// @returns pair of slot and byte offset of the value inside this slot.
std::pair<u256, unsigned> getStorageLocationOfVariable(Declaration const& _declaration) const; std::pair<u256, unsigned> storageLocationOfVariable(Declaration const& _declaration) const;
/// Appends a JUMPI instruction to a new tag and @returns the tag /// Appends a JUMPI instruction to a new tag and @returns the tag
eth::AssemblyItem appendConditionalJump() { return m_asm.appendJumpI().tag(); } eth::AssemblyItem appendConditionalJump() { return m_asm.appendJumpI().tag(); }
@ -127,7 +127,7 @@ public:
void optimise(unsigned _runs = 200) { m_asm.optimise(true, true, _runs); } void optimise(unsigned _runs = 200) { m_asm.optimise(true, true, _runs); }
eth::Assembly const& getAssembly() const { return m_asm; } eth::Assembly const& assembly() const { return m_asm; }
/// @arg _sourceCodes is the map of input files to source code strings /// @arg _sourceCodes is the map of input files to source code strings
/// @arg _inJsonFormat shows whether the out should be in Json format /// @arg _inJsonFormat shows whether the out should be in Json format
Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const
@ -135,8 +135,8 @@ public:
return m_asm.stream(_stream, "", _sourceCodes, _inJsonFormat); return m_asm.stream(_stream, "", _sourceCodes, _inJsonFormat);
} }
bytes getAssembledBytecode() { return m_asm.assemble(); } bytes assembledBytecode() { return m_asm.assemble(); }
bytes getAssembledRuntimeBytecode(size_t _subIndex) { m_asm.assemble(); return m_asm.data(u256(_subIndex)); } bytes assembledRuntimeBytecode(size_t _subIndex) { m_asm.assemble(); return m_asm.data(u256(_subIndex)); }
/** /**
* Helper class to pop the visited nodes stack when a scope closes * Helper class to pop the visited nodes stack when a scope closes
@ -151,12 +151,12 @@ public:
private: private:
/// @returns the entry label of the given function - searches the inheritance hierarchy /// @returns the entry label of the given function - searches the inheritance hierarchy
/// startig from the given point towards the base. /// startig from the given point towards the base.
eth::AssemblyItem getVirtualFunctionEntryLabel( eth::AssemblyItem virtualFunctionEntryLabel(
FunctionDefinition const& _function, FunctionDefinition const& _function,
std::vector<ContractDefinition const*>::const_iterator _searchStart std::vector<ContractDefinition const*>::const_iterator _searchStart
); );
/// @returns an iterator to the contract directly above the given contract. /// @returns an iterator to the contract directly above the given contract.
std::vector<ContractDefinition const*>::const_iterator getSuperContract(const ContractDefinition &_contract) const; std::vector<ContractDefinition const*>::const_iterator superContract(const ContractDefinition &_contract) const;
/// Updates source location set in the assembly. /// Updates source location set in the assembly.
void updateSourceLocation(); void updateSourceLocation();

View File

@ -103,30 +103,30 @@ void CompilerStack::parse()
resolveImports(); resolveImports();
m_globalContext = make_shared<GlobalContext>(); m_globalContext = make_shared<GlobalContext>();
NameAndTypeResolver resolver(m_globalContext->getDeclarations()); NameAndTypeResolver resolver(m_globalContext->declarations());
for (Source const* source: m_sourceOrder) for (Source const* source: m_sourceOrder)
resolver.registerDeclarations(*source->ast); resolver.registerDeclarations(*source->ast);
for (Source const* source: m_sourceOrder) for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes()) for (ASTPointer<ASTNode> const& node: source->ast->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
m_globalContext->setCurrentContract(*contract); m_globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*m_globalContext->getCurrentThis()); resolver.updateDeclaration(*m_globalContext->currentThis());
resolver.updateDeclaration(*m_globalContext->getCurrentSuper()); resolver.updateDeclaration(*m_globalContext->currentSuper());
resolver.resolveNamesAndTypes(*contract); resolver.resolveNamesAndTypes(*contract);
m_contracts[contract->getName()].contract = contract; m_contracts[contract->name()].contract = contract;
} }
InterfaceHandler interfaceHandler; InterfaceHandler interfaceHandler;
for (Source const* source: m_sourceOrder) for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes()) for (ASTPointer<ASTNode> const& node: source->ast->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
m_globalContext->setCurrentContract(*contract); m_globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*m_globalContext->getCurrentThis()); resolver.updateDeclaration(*m_globalContext->currentThis());
resolver.checkTypeRequirements(*contract); resolver.checkTypeRequirements(*contract);
contract->setDevDocumentation(interfaceHandler.devDocumentation(*contract)); contract->setDevDocumentation(interfaceHandler.devDocumentation(*contract));
contract->setUserDocumentation(interfaceHandler.userDocumentation(*contract)); contract->setUserDocumentation(interfaceHandler.userDocumentation(*contract));
m_contracts[contract->getName()].contract = contract; m_contracts[contract->name()].contract = contract;
} }
m_parseSuccessful = true; m_parseSuccessful = true;
} }
@ -137,7 +137,7 @@ void CompilerStack::parse(string const& _sourceCode)
parse(); parse();
} }
vector<string> CompilerStack::getContractNames() const vector<string> CompilerStack::contractNames() const
{ {
if (!m_parseSuccessful) if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
@ -155,16 +155,16 @@ void CompilerStack::compile(bool _optimize, unsigned _runs)
map<ContractDefinition const*, bytes const*> contractBytecode; map<ContractDefinition const*, bytes const*> contractBytecode;
for (Source const* source: m_sourceOrder) for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes()) for (ASTPointer<ASTNode> const& node: source->ast->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
if (!contract->isFullyImplemented()) if (!contract->isFullyImplemented())
continue; continue;
shared_ptr<Compiler> compiler = make_shared<Compiler>(_optimize, _runs); shared_ptr<Compiler> compiler = make_shared<Compiler>(_optimize, _runs);
compiler->compileContract(*contract, contractBytecode); compiler->compileContract(*contract, contractBytecode);
Contract& compiledContract = m_contracts.at(contract->getName()); Contract& compiledContract = m_contracts.at(contract->name());
compiledContract.bytecode = compiler->getAssembledBytecode(); compiledContract.bytecode = compiler->assembledBytecode();
compiledContract.runtimeBytecode = compiler->getRuntimeBytecode(); compiledContract.runtimeBytecode = compiler->runtimeBytecode();
compiledContract.compiler = move(compiler); compiledContract.compiler = move(compiler);
compiler = make_shared<Compiler>(_optimize, _runs); compiler = make_shared<Compiler>(_optimize, _runs);
compiler->compileContract(*contract, contractBytecode); compiler->compileContract(*contract, contractBytecode);
@ -172,7 +172,7 @@ void CompilerStack::compile(bool _optimize, unsigned _runs)
Compiler cloneCompiler(_optimize, _runs); Compiler cloneCompiler(_optimize, _runs);
cloneCompiler.compileClone(*contract, contractBytecode); cloneCompiler.compileClone(*contract, contractBytecode);
compiledContract.cloneBytecode = cloneCompiler.getAssembledBytecode(); compiledContract.cloneBytecode = cloneCompiler.assembledBytecode();
} }
} }
@ -180,46 +180,46 @@ bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{ {
parse(_sourceCode); parse(_sourceCode);
compile(_optimize); compile(_optimize);
return getBytecode(); return bytecode();
} }
eth::AssemblyItems const* CompilerStack::getAssemblyItems(string const& _contractName) const eth::AssemblyItems const* CompilerStack::assemblyItems(string const& _contractName) const
{ {
Contract const& contract = getContract(_contractName); Contract const& currentContract = contract(_contractName);
return contract.compiler ? &getContract(_contractName).compiler->getAssemblyItems() : nullptr; return currentContract.compiler ? &contract(_contractName).compiler->assemblyItems() : nullptr;
} }
eth::AssemblyItems const* CompilerStack::getRuntimeAssemblyItems(string const& _contractName) const eth::AssemblyItems const* CompilerStack::runtimeAssemblyItems(string const& _contractName) const
{ {
Contract const& contract = getContract(_contractName); Contract const& currentContract = contract(_contractName);
return contract.compiler ? &getContract(_contractName).compiler->getRuntimeAssemblyItems() : nullptr; return currentContract.compiler ? &contract(_contractName).compiler->runtimeAssemblyItems() : nullptr;
} }
bytes const& CompilerStack::getBytecode(string const& _contractName) const bytes const& CompilerStack::bytecode(string const& _contractName) const
{ {
return getContract(_contractName).bytecode; return contract(_contractName).bytecode;
} }
bytes const& CompilerStack::getRuntimeBytecode(string const& _contractName) const bytes const& CompilerStack::runtimeBytecode(string const& _contractName) const
{ {
return getContract(_contractName).runtimeBytecode; return contract(_contractName).runtimeBytecode;
} }
bytes const& CompilerStack::getCloneBytecode(string const& _contractName) const bytes const& CompilerStack::cloneBytecode(string const& _contractName) const
{ {
return getContract(_contractName).cloneBytecode; return contract(_contractName).cloneBytecode;
} }
dev::h256 CompilerStack::getContractCodeHash(string const& _contractName) const dev::h256 CompilerStack::contractCodeHash(string const& _contractName) const
{ {
return dev::sha3(getRuntimeBytecode(_contractName)); return dev::sha3(runtimeBytecode(_contractName));
} }
Json::Value CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName, StringMap _sourceCodes, bool _inJsonFormat) const Json::Value CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName, StringMap _sourceCodes, bool _inJsonFormat) const
{ {
Contract const& contract = getContract(_contractName); Contract const& currentContract = contract(_contractName);
if (contract.compiler) if (currentContract.compiler)
return contract.compiler->streamAssembly(_outStream, _sourceCodes, _inJsonFormat); return currentContract.compiler->streamAssembly(_outStream, _sourceCodes, _inJsonFormat);
else else
{ {
_outStream << "Contract not fully implemented" << endl; _outStream << "Contract not fully implemented" << endl;
@ -227,22 +227,22 @@ Json::Value CompilerStack::streamAssembly(ostream& _outStream, string const& _co
} }
} }
string const& CompilerStack::getInterface(string const& _contractName) const string const& CompilerStack::interface(string const& _contractName) const
{ {
return getMetadata(_contractName, DocumentationType::ABIInterface); return metadata(_contractName, DocumentationType::ABIInterface);
} }
string const& CompilerStack::getSolidityInterface(string const& _contractName) const string const& CompilerStack::solidityInterface(string const& _contractName) const
{ {
return getMetadata(_contractName, DocumentationType::ABISolidityInterface); return metadata(_contractName, DocumentationType::ABISolidityInterface);
} }
string const& CompilerStack::getMetadata(string const& _contractName, DocumentationType _type) const string const& CompilerStack::metadata(string const& _contractName, DocumentationType _type) const
{ {
if (!m_parseSuccessful) if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful.")); BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
Contract const& contract = getContract(_contractName); Contract const& currentContract = contract(_contractName);
std::unique_ptr<string const>* doc; std::unique_ptr<string const>* doc;
@ -250,16 +250,16 @@ string const& CompilerStack::getMetadata(string const& _contractName, Documentat
switch (_type) switch (_type)
{ {
case DocumentationType::NatspecUser: case DocumentationType::NatspecUser:
doc = &contract.userDocumentation; doc = &currentContract.userDocumentation;
break; break;
case DocumentationType::NatspecDev: case DocumentationType::NatspecDev:
doc = &contract.devDocumentation; doc = &currentContract.devDocumentation;
break; break;
case DocumentationType::ABIInterface: case DocumentationType::ABIInterface:
doc = &contract.interface; doc = &currentContract.interface;
break; break;
case DocumentationType::ABISolidityInterface: case DocumentationType::ABISolidityInterface:
doc = &contract.solidityInterface; doc = &currentContract.solidityInterface;
break; break;
default: default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type."));
@ -267,38 +267,38 @@ string const& CompilerStack::getMetadata(string const& _contractName, Documentat
// caches the result // caches the result
if (!*doc) if (!*doc)
doc->reset(new string(contract.interfaceHandler->getDocumentation(*contract.contract, _type))); doc->reset(new string(currentContract.interfaceHandler->documentation(*currentContract.contract, _type)));
return *(*doc); return *(*doc);
} }
Scanner const& CompilerStack::getScanner(string const& _sourceName) const Scanner const& CompilerStack::scanner(string const& _sourceName) const
{ {
return *getSource(_sourceName).scanner; return *source(_sourceName).scanner;
} }
SourceUnit const& CompilerStack::getAST(string const& _sourceName) const SourceUnit const& CompilerStack::AST(string const& _sourceName) const
{ {
return *getSource(_sourceName).ast; return *source(_sourceName).ast;
} }
ContractDefinition const& CompilerStack::getContractDefinition(string const& _contractName) const ContractDefinition const& CompilerStack::contractDefinition(string const& _contractName) const
{ {
return *getContract(_contractName).contract; return *contract(_contractName).contract;
} }
size_t CompilerStack::getFunctionEntryPoint( size_t CompilerStack::functionEntryPoint(
std::string const& _contractName, std::string const& _contractName,
FunctionDefinition const& _function FunctionDefinition const& _function
) const ) const
{ {
shared_ptr<Compiler> const& compiler = getContract(_contractName).compiler; shared_ptr<Compiler> const& compiler = contract(_contractName).compiler;
if (!compiler) if (!compiler)
return 0; return 0;
eth::AssemblyItem tag = compiler->getFunctionEntryLabel(_function); eth::AssemblyItem tag = compiler->functionEntryLabel(_function);
if (tag.type() == eth::UndefinedItem) if (tag.type() == eth::UndefinedItem)
return 0; return 0;
eth::AssemblyItems const& items = compiler->getRuntimeAssemblyItems(); eth::AssemblyItems const& items = compiler->runtimeAssemblyItems();
for (size_t i = 0; i < items.size(); ++i) for (size_t i = 0; i < items.size(); ++i)
if (items.at(i).type() == eth::Tag && items.at(i).data() == tag.data()) if (items.at(i).type() == eth::Tag && items.at(i).data() == tag.data())
return i; return i;
@ -317,8 +317,8 @@ tuple<int, int, int, int> CompilerStack::positionFromSourceLocation(SourceLocati
int startColumn; int startColumn;
int endLine; int endLine;
int endColumn; int endColumn;
tie(startLine, startColumn) = getScanner(*_sourceLocation.sourceName).translatePositionToLineColumn(_sourceLocation.start); tie(startLine, startColumn) = scanner(*_sourceLocation.sourceName).translatePositionToLineColumn(_sourceLocation.start);
tie(endLine, endColumn) = getScanner(*_sourceLocation.sourceName).translatePositionToLineColumn(_sourceLocation.end); tie(endLine, endColumn) = scanner(*_sourceLocation.sourceName).translatePositionToLineColumn(_sourceLocation.end);
return make_tuple(++startLine, ++startColumn, ++endLine, ++endColumn); return make_tuple(++startLine, ++startColumn, ++endLine, ++endColumn);
} }
@ -334,13 +334,13 @@ void CompilerStack::resolveImports()
if (sourcesSeen.count(_source)) if (sourcesSeen.count(_source))
return; return;
sourcesSeen.insert(_source); sourcesSeen.insert(_source);
for (ASTPointer<ASTNode> const& node: _source->ast->getNodes()) for (ASTPointer<ASTNode> const& node: _source->ast->nodes())
if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get())) if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get()))
{ {
string const& id = import->getIdentifier(); string const& id = import->identifier();
if (!m_sources.count(id)) if (!m_sources.count(id))
BOOST_THROW_EXCEPTION(ParserError() BOOST_THROW_EXCEPTION(ParserError()
<< errinfo_sourceLocation(import->getLocation()) << errinfo_sourceLocation(import->location())
<< errinfo_comment("Source not found.")); << errinfo_comment("Source not found."));
toposort(&m_sources[id]); toposort(&m_sources[id]);
} }
@ -356,10 +356,10 @@ void CompilerStack::resolveImports()
std::string CompilerStack::defaultContractName() const std::string CompilerStack::defaultContractName() const
{ {
return getContract("").contract->getName(); return contract("").contract->name();
} }
CompilerStack::Contract const& CompilerStack::getContract(string const& _contractName) const CompilerStack::Contract const& CompilerStack::contract(string const& _contractName) const
{ {
if (m_contracts.empty()) if (m_contracts.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found.")); BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found."));
@ -368,16 +368,16 @@ CompilerStack::Contract const& CompilerStack::getContract(string const& _contrac
// try to find some user-supplied contract // try to find some user-supplied contract
for (auto const& it: m_sources) for (auto const& it: m_sources)
if (!StandardSources.count(it.first)) if (!StandardSources.count(it.first))
for (ASTPointer<ASTNode> const& node: it.second.ast->getNodes()) for (ASTPointer<ASTNode> const& node: it.second.ast->nodes())
if (auto contract = dynamic_cast<ContractDefinition const*>(node.get())) if (auto contract = dynamic_cast<ContractDefinition const*>(node.get()))
contractName = contract->getName(); contractName = contract->name();
auto it = m_contracts.find(contractName); auto it = m_contracts.find(contractName);
if (it == m_contracts.end()) if (it == m_contracts.end())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found.")); BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found."));
return it->second; return it->second;
} }
CompilerStack::Source const& CompilerStack::getSource(string const& _sourceName) const CompilerStack::Source const& CompilerStack::source(string const& _sourceName) const
{ {
auto it = m_sources.find(_sourceName); auto it = m_sources.find(_sourceName);
if (it == m_sources.end()) if (it == m_sources.end())

View File

@ -86,7 +86,7 @@ public:
/// Sets the given source code as the only source unit apart from standard sources and parses it. /// Sets the given source code as the only source unit apart from standard sources and parses it.
void parse(std::string const& _sourceCode); void parse(std::string const& _sourceCode);
/// Returns a list of the contract names in the sources. /// Returns a list of the contract names in the sources.
std::vector<std::string> getContractNames() const; std::vector<std::string> contractNames() const;
std::string defaultContractName() const; std::string defaultContractName() const;
/// Compiles the source units that were previously added and parsed. /// Compiles the source units that were previously added and parsed.
@ -96,20 +96,20 @@ public:
bytes const& compile(std::string const& _sourceCode, bool _optimize = false); bytes const& compile(std::string const& _sourceCode, bool _optimize = false);
/// @returns the assembled bytecode for a contract. /// @returns the assembled bytecode for a contract.
bytes const& getBytecode(std::string const& _contractName = "") const; bytes const& bytecode(std::string const& _contractName = "") const;
/// @returns the runtime bytecode for the contract, i.e. the code that is returned by the constructor. /// @returns the runtime bytecode for the contract, i.e. the code that is returned by the constructor.
bytes const& getRuntimeBytecode(std::string const& _contractName = "") const; bytes const& runtimeBytecode(std::string const& _contractName = "") const;
/// @returns the bytecode of a contract that uses an already deployed contract via CALLCODE. /// @returns the bytecode of a contract that uses an already deployed contract via CALLCODE.
/// The returned bytes will contain a sequence of 20 bytes of the format "XXX...XXX" which have to /// The returned bytes will contain a sequence of 20 bytes of the format "XXX...XXX" which have to
/// substituted by the actual address. Note that this sequence starts end ends in three X /// substituted by the actual address. Note that this sequence starts end ends in three X
/// characters but can contain anything in between. /// characters but can contain anything in between.
bytes const& getCloneBytecode(std::string const& _contractName = "") const; bytes const& cloneBytecode(std::string const& _contractName = "") const;
/// @returns normal contract assembly items /// @returns normal contract assembly items
eth::AssemblyItems const* getAssemblyItems(std::string const& _contractName = "") const; eth::AssemblyItems const* assemblyItems(std::string const& _contractName = "") const;
/// @returns runtime contract assembly items /// @returns runtime contract assembly items
eth::AssemblyItems const* getRuntimeAssemblyItems(std::string const& _contractName = "") const; eth::AssemblyItems const* runtimeAssemblyItems(std::string const& _contractName = "") const;
/// @returns hash of the runtime bytecode for the contract, i.e. the code that is returned by the constructor. /// @returns hash of the runtime bytecode for the contract, i.e. the code that is returned by the constructor.
dev::h256 getContractCodeHash(std::string const& _contractName = "") const; dev::h256 contractCodeHash(std::string const& _contractName = "") const;
/// Streams a verbose version of the assembly to @a _outStream. /// Streams a verbose version of the assembly to @a _outStream.
/// @arg _sourceCodes is the map of input files to source code strings /// @arg _sourceCodes is the map of input files to source code strings
@ -119,27 +119,27 @@ public:
/// Returns a string representing the contract interface in JSON. /// Returns a string representing the contract interface in JSON.
/// Prerequisite: Successful call to parse or compile. /// Prerequisite: Successful call to parse or compile.
std::string const& getInterface(std::string const& _contractName = "") const; std::string const& interface(std::string const& _contractName = "") const;
/// Returns a string representing the contract interface in Solidity. /// Returns a string representing the contract interface in Solidity.
/// Prerequisite: Successful call to parse or compile. /// Prerequisite: Successful call to parse or compile.
std::string const& getSolidityInterface(std::string const& _contractName = "") const; std::string const& solidityInterface(std::string const& _contractName = "") const;
/// Returns a string representing the contract's documentation in JSON. /// Returns a string representing the contract's documentation in JSON.
/// Prerequisite: Successful call to parse or compile. /// Prerequisite: Successful call to parse or compile.
/// @param type The type of the documentation to get. /// @param type The type of the documentation to get.
/// Can be one of 4 types defined at @c DocumentationType /// Can be one of 4 types defined at @c DocumentationType
std::string const& getMetadata(std::string const& _contractName, DocumentationType _type) const; std::string const& metadata(std::string const& _contractName, DocumentationType _type) const;
/// @returns the previously used scanner, useful for counting lines during error reporting. /// @returns the previously used scanner, useful for counting lines during error reporting.
Scanner const& getScanner(std::string const& _sourceName = "") const; Scanner const& scanner(std::string const& _sourceName = "") const;
/// @returns the parsed source unit with the supplied name. /// @returns the parsed source unit with the supplied name.
SourceUnit const& getAST(std::string const& _sourceName = "") const; SourceUnit const& AST(std::string const& _sourceName = "") const;
/// @returns the parsed contract with the supplied name. Throws an exception if the contract /// @returns the parsed contract with the supplied name. Throws an exception if the contract
/// does not exist. /// does not exist.
ContractDefinition const& getContractDefinition(std::string const& _contractName) const; ContractDefinition const& contractDefinition(std::string const& _contractName) const;
/// @returns the offset of the entry point of the given function into the list of assembly items /// @returns the offset of the entry point of the given function into the list of assembly items
/// or zero if it is not found or does not exist. /// or zero if it is not found or does not exist.
size_t getFunctionEntryPoint( size_t functionEntryPoint(
std::string const& _contractName, std::string const& _contractName,
FunctionDefinition const& _function FunctionDefinition const& _function
) const; ) const;
@ -184,8 +184,8 @@ private:
void resolveImports(); void resolveImports();
Contract const& getContract(std::string const& _contractName = "") const; Contract const& contract(std::string const& _contractName = "") const;
Source const& getSource(std::string const& _sourceName = "") const; Source const& source(std::string const& _sourceName = "") const;
bool m_parseSuccessful; bool m_parseSuccessful;
std::map<std::string const, Source> m_sources; std::map<std::string const, Source> m_sources;

View File

@ -75,7 +75,7 @@ unsigned CompilerUtils::loadFromMemory(
bool _padToWordBoundaries bool _padToWordBoundaries
) )
{ {
solAssert(_type.getCategory() != Type::Category::Array, "Unable to statically load dynamic type."); solAssert(_type.category() != Type::Category::Array, "Unable to statically load dynamic type.");
m_context << u256(_offset); m_context << u256(_offset);
return loadFromMemoryHelper(_type, _fromCalldata, _padToWordBoundaries); return loadFromMemoryHelper(_type, _fromCalldata, _padToWordBoundaries);
} }
@ -87,14 +87,14 @@ void CompilerUtils::loadFromMemoryDynamic(
bool _keepUpdatedMemoryOffset bool _keepUpdatedMemoryOffset
) )
{ {
solAssert(_type.getCategory() != Type::Category::Array, "Arrays not yet implemented."); solAssert(_type.category() != Type::Category::Array, "Arrays not yet implemented.");
if (_keepUpdatedMemoryOffset) if (_keepUpdatedMemoryOffset)
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
unsigned numBytes = loadFromMemoryHelper(_type, _fromCalldata, _padToWordBoundaries); unsigned numBytes = loadFromMemoryHelper(_type, _fromCalldata, _padToWordBoundaries);
if (_keepUpdatedMemoryOffset) if (_keepUpdatedMemoryOffset)
{ {
// update memory counter // update memory counter
moveToStackTop(_type.getSizeOnStack()); moveToStackTop(_type.sizeOnStack());
m_context << u256(numBytes) << eth::Instruction::ADD; m_context << u256(numBytes) << eth::Instruction::ADD;
} }
} }
@ -129,7 +129,7 @@ void CompilerUtils::storeInMemoryDynamic(Type const& _type, bool _padToWordBound
if (numBytes > 0) if (numBytes > 0)
{ {
solAssert( solAssert(
_type.getSizeOnStack() == 1, _type.sizeOnStack() == 1,
"Memory store of types with stack size != 1 not implemented." "Memory store of types with stack size != 1 not implemented."
); );
m_context << eth::Instruction::DUP2 << eth::Instruction::MSTORE; m_context << eth::Instruction::DUP2 << eth::Instruction::MSTORE;
@ -159,7 +159,7 @@ void CompilerUtils::encodeToMemory(
// store memory start pointer // store memory start pointer
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
unsigned argSize = CompilerUtils::getSizeOnStack(_givenTypes); unsigned argSize = CompilerUtils::sizeOnStack(_givenTypes);
unsigned stackPos = 0; // advances through the argument values unsigned stackPos = 0; // advances through the argument values
unsigned dynPointers = 0; // number of dynamic head pointers on the stack unsigned dynPointers = 0; // number of dynamic head pointers on the stack
for (size_t i = 0; i < _givenTypes.size(); ++i) for (size_t i = 0; i < _givenTypes.size(); ++i)
@ -174,13 +174,13 @@ void CompilerUtils::encodeToMemory(
} }
else else
{ {
copyToStackTop(argSize - stackPos + dynPointers + 2, _givenTypes[i]->getSizeOnStack()); copyToStackTop(argSize - stackPos + dynPointers + 2, _givenTypes[i]->sizeOnStack());
solAssert(!!targetType, "Externalable type expected."); solAssert(!!targetType, "Externalable type expected.");
TypePointer type = targetType; TypePointer type = targetType;
if ( if (
_givenTypes[i]->dataStoredIn(DataLocation::Storage) || _givenTypes[i]->dataStoredIn(DataLocation::Storage) ||
_givenTypes[i]->dataStoredIn(DataLocation::CallData) || _givenTypes[i]->dataStoredIn(DataLocation::CallData) ||
_givenTypes[i]->getCategory() == Type::Category::StringLiteral _givenTypes[i]->category() == Type::Category::StringLiteral
) )
type = _givenTypes[i]; // delay conversion type = _givenTypes[i]; // delay conversion
else else
@ -190,7 +190,7 @@ void CompilerUtils::encodeToMemory(
else else
storeInMemoryDynamic(*type, _padToWordBoundaries); storeInMemoryDynamic(*type, _padToWordBoundaries);
} }
stackPos += _givenTypes[i]->getSizeOnStack(); stackPos += _givenTypes[i]->sizeOnStack();
} }
// now copy the dynamic part // now copy the dynamic part
@ -209,7 +209,7 @@ void CompilerUtils::encodeToMemory(
m_context << eth::dupInstruction(2 + dynPointers - thisDynPointer); m_context << eth::dupInstruction(2 + dynPointers - thisDynPointer);
m_context << eth::Instruction::MSTORE; m_context << eth::Instruction::MSTORE;
// stack: ... <end_of_mem> // stack: ... <end_of_mem>
if (_givenTypes[i]->getCategory() == Type::Category::StringLiteral) if (_givenTypes[i]->category() == Type::Category::StringLiteral)
{ {
auto const& strType = dynamic_cast<StringLiteralType const&>(*_givenTypes[i]); auto const& strType = dynamic_cast<StringLiteralType const&>(*_givenTypes[i]);
m_context << u256(strType.value().size()); m_context << u256(strType.value().size());
@ -219,13 +219,13 @@ void CompilerUtils::encodeToMemory(
} }
else else
{ {
solAssert(_givenTypes[i]->getCategory() == Type::Category::Array, "Unknown dynamic type."); solAssert(_givenTypes[i]->category() == Type::Category::Array, "Unknown dynamic type.");
auto const& arrayType = dynamic_cast<ArrayType const&>(*_givenTypes[i]); auto const& arrayType = dynamic_cast<ArrayType const&>(*_givenTypes[i]);
// now copy the array // now copy the array
copyToStackTop(argSize - stackPos + dynPointers + 2, arrayType.getSizeOnStack()); copyToStackTop(argSize - stackPos + dynPointers + 2, arrayType.sizeOnStack());
// stack: ... <end_of_mem> <value...> // stack: ... <end_of_mem> <value...>
// copy length to memory // copy length to memory
m_context << eth::dupInstruction(1 + arrayType.getSizeOnStack()); m_context << eth::dupInstruction(1 + arrayType.sizeOnStack());
if (arrayType.location() == DataLocation::CallData) if (arrayType.location() == DataLocation::CallData)
m_context << eth::Instruction::DUP2; // length is on stack m_context << eth::Instruction::DUP2; // length is on stack
else if (arrayType.location() == DataLocation::Storage) else if (arrayType.location() == DataLocation::Storage)
@ -239,7 +239,7 @@ void CompilerUtils::encodeToMemory(
storeInMemoryDynamic(IntegerType(256), true); storeInMemoryDynamic(IntegerType(256), true);
// stack: ... <end_of_mem> <value...> <end_of_mem''> // stack: ... <end_of_mem> <value...> <end_of_mem''>
// copy the new memory pointer // copy the new memory pointer
m_context << eth::swapInstruction(arrayType.getSizeOnStack() + 1) << eth::Instruction::POP; m_context << eth::swapInstruction(arrayType.sizeOnStack() + 1) << eth::Instruction::POP;
// stack: ... <end_of_mem''> <value...> // stack: ... <end_of_mem''> <value...>
// copy data part // copy data part
ArrayUtils(m_context).copyArrayToMemory(arrayType, _padToWordBoundaries); ArrayUtils(m_context).copyArrayToMemory(arrayType, _padToWordBoundaries);
@ -248,7 +248,7 @@ void CompilerUtils::encodeToMemory(
thisDynPointer++; thisDynPointer++;
} }
stackPos += _givenTypes[i]->getSizeOnStack(); stackPos += _givenTypes[i]->sizeOnStack();
} }
// remove unneeded stack elements (and retain memory pointer) // remove unneeded stack elements (and retain memory pointer)
@ -279,8 +279,8 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
if (_typeOnStack == _targetType && !_cleanupNeeded) if (_typeOnStack == _targetType && !_cleanupNeeded)
return; return;
Type::Category stackTypeCategory = _typeOnStack.getCategory(); Type::Category stackTypeCategory = _typeOnStack.category();
Type::Category targetTypeCategory = _targetType.getCategory(); Type::Category targetTypeCategory = _targetType.category();
switch (stackTypeCategory) switch (stackTypeCategory)
{ {
@ -293,7 +293,7 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
// only to shift right because of opposite alignment // only to shift right because of opposite alignment
IntegerType const& targetIntegerType = dynamic_cast<IntegerType const&>(_targetType); IntegerType const& targetIntegerType = dynamic_cast<IntegerType const&>(_targetType);
m_context << (u256(1) << (256 - typeOnStack.numBytes() * 8)) << eth::Instruction::SWAP1 << eth::Instruction::DIV; m_context << (u256(1) << (256 - typeOnStack.numBytes() * 8)) << eth::Instruction::SWAP1 << eth::Instruction::DIV;
if (targetIntegerType.getNumBits() < typeOnStack.numBytes() * 8) if (targetIntegerType.numBits() < typeOnStack.numBytes() * 8)
convertType(IntegerType(typeOnStack.numBytes() * 8), _targetType, _cleanupNeeded); convertType(IntegerType(typeOnStack.numBytes() * 8), _targetType, _cleanupNeeded);
} }
else else
@ -329,7 +329,7 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
// only to shift left because of opposite alignment // only to shift left because of opposite alignment
FixedBytesType const& targetBytesType = dynamic_cast<FixedBytesType const&>(_targetType); FixedBytesType const& targetBytesType = dynamic_cast<FixedBytesType const&>(_targetType);
if (auto typeOnStack = dynamic_cast<IntegerType const*>(&_typeOnStack)) if (auto typeOnStack = dynamic_cast<IntegerType const*>(&_typeOnStack))
if (targetBytesType.numBytes() * 8 > typeOnStack->getNumBits()) if (targetBytesType.numBytes() * 8 > typeOnStack->numBits())
cleanHigherOrderBits(*typeOnStack); cleanHigherOrderBits(*typeOnStack);
m_context << (u256(1) << (256 - targetBytesType.numBytes() * 8)) << eth::Instruction::MUL; m_context << (u256(1) << (256 - targetBytesType.numBytes() * 8)) << eth::Instruction::MUL;
} }
@ -347,7 +347,7 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
IntegerConstantType const& constType = dynamic_cast<IntegerConstantType const&>(_typeOnStack); IntegerConstantType const& constType = dynamic_cast<IntegerConstantType const&>(_typeOnStack);
// We know that the stack is clean, we only have to clean for a narrowing conversion // We know that the stack is clean, we only have to clean for a narrowing conversion
// where cleanup is forced. // where cleanup is forced.
if (targetType.getNumBits() < constType.getIntegerType()->getNumBits() && _cleanupNeeded) if (targetType.numBits() < constType.integerType()->numBits() && _cleanupNeeded)
cleanHigherOrderBits(targetType); cleanHigherOrderBits(targetType);
} }
else else
@ -356,7 +356,7 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
? dynamic_cast<IntegerType const&>(_typeOnStack) : addressType; ? dynamic_cast<IntegerType const&>(_typeOnStack) : addressType;
// Widening: clean up according to source type width // Widening: clean up according to source type width
// Non-widening and force: clean up according to target type bits // Non-widening and force: clean up according to target type bits
if (targetType.getNumBits() > typeOnStack.getNumBits()) if (targetType.numBits() > typeOnStack.numBits())
cleanHigherOrderBits(typeOnStack); cleanHigherOrderBits(typeOnStack);
else if (_cleanupNeeded) else if (_cleanupNeeded)
cleanHigherOrderBits(targetType); cleanHigherOrderBits(targetType);
@ -415,7 +415,7 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
if (typeOnStack.location() != DataLocation::Memory) if (typeOnStack.location() != DataLocation::Memory)
{ {
// stack: <source ref> (variably sized) // stack: <source ref> (variably sized)
unsigned stackSize = typeOnStack.getSizeOnStack(); unsigned stackSize = typeOnStack.sizeOnStack();
ArrayUtils(m_context).retrieveLength(typeOnStack); ArrayUtils(m_context).retrieveLength(typeOnStack);
// allocate memory // allocate memory
@ -435,9 +435,9 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
storeInMemoryDynamic(IntegerType(256)); storeInMemoryDynamic(IntegerType(256));
} }
// stack: <mem start> <source ref> (variably sized) <length> <mem data pos> // stack: <mem start> <source ref> (variably sized) <length> <mem data pos>
if (targetType.getBaseType()->isValueType()) if (targetType.baseType()->isValueType())
{ {
solAssert(typeOnStack.getBaseType()->isValueType(), ""); solAssert(typeOnStack.baseType()->isValueType(), "");
copyToStackTop(2 + stackSize, stackSize); copyToStackTop(2 + stackSize, stackSize);
ArrayUtils(m_context).copyArrayToMemory(typeOnStack); ArrayUtils(m_context).copyArrayToMemory(typeOnStack);
} }
@ -454,9 +454,9 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
copyToStackTop(2 + stackSize, 1); copyToStackTop(2 + stackSize, 1);
ArrayUtils(m_context).accessIndex(typeOnStack, false); ArrayUtils(m_context).accessIndex(typeOnStack, false);
if (typeOnStack.location() == DataLocation::Storage) if (typeOnStack.location() == DataLocation::Storage)
StorageItem(m_context, *typeOnStack.getBaseType()).retrieveValue(SourceLocation(), true); StorageItem(m_context, *typeOnStack.baseType()).retrieveValue(SourceLocation(), true);
convertType(*typeOnStack.getBaseType(), *targetType.getBaseType(), _cleanupNeeded); convertType(*typeOnStack.baseType(), *targetType.baseType(), _cleanupNeeded);
storeInMemoryDynamic(*targetType.getBaseType(), true); storeInMemoryDynamic(*targetType.baseType(), true);
m_context << eth::Instruction::SWAP1 << u256(1) << eth::Instruction::ADD; m_context << eth::Instruction::SWAP1 << u256(1) << eth::Instruction::ADD;
m_context << eth::Instruction::SWAP1; m_context << eth::Instruction::SWAP1;
m_context.appendJumpTo(repeat); m_context.appendJumpTo(repeat);
@ -517,15 +517,15 @@ void CompilerUtils::convertType(Type const& _typeOnStack, Type const& _targetTyp
allocateMemory(); allocateMemory();
m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2; m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2;
// stack: <memory ptr> <source ref> <memory ptr> // stack: <memory ptr> <source ref> <memory ptr>
for (auto const& member: typeOnStack.getMembers()) for (auto const& member: typeOnStack.members())
{ {
if (!member.type->canLiveOutsideStorage()) if (!member.type->canLiveOutsideStorage())
continue; continue;
pair<u256, unsigned> const& offsets = typeOnStack.getStorageOffsetsOfMember(member.name); pair<u256, unsigned> const& offsets = typeOnStack.storageOffsetsOfMember(member.name);
m_context << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD; m_context << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD;
m_context << u256(offsets.second); m_context << u256(offsets.second);
StorageItem(m_context, *member.type).retrieveValue(SourceLocation(), true); StorageItem(m_context, *member.type).retrieveValue(SourceLocation(), true);
TypePointer targetMemberType = targetType.getMemberType(member.name); TypePointer targetMemberType = targetType.memberType(member.name);
solAssert(!!targetMemberType, "Member not found in target type."); solAssert(!!targetMemberType, "Member not found in target type.");
convertType(*member.type, *targetMemberType, true); convertType(*member.type, *targetMemberType, true);
storeInMemoryDynamic(*targetMemberType, true); storeInMemoryDynamic(*targetMemberType, true);
@ -551,18 +551,18 @@ void CompilerUtils::pushZeroValue(const Type& _type)
auto const* referenceType = dynamic_cast<ReferenceType const*>(&_type); auto const* referenceType = dynamic_cast<ReferenceType const*>(&_type);
if (!referenceType || referenceType->location() == DataLocation::Storage) if (!referenceType || referenceType->location() == DataLocation::Storage)
{ {
for (size_t i = 0; i < _type.getSizeOnStack(); ++i) for (size_t i = 0; i < _type.sizeOnStack(); ++i)
m_context << u256(0); m_context << u256(0);
return; return;
} }
solAssert(referenceType->location() == DataLocation::Memory, ""); solAssert(referenceType->location() == DataLocation::Memory, "");
m_context << u256(max(32u, _type.getCalldataEncodedSize())); m_context << u256(max(32u, _type.calldataEncodedSize()));
allocateMemory(); allocateMemory();
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
if (auto structType = dynamic_cast<StructType const*>(&_type)) if (auto structType = dynamic_cast<StructType const*>(&_type))
for (auto const& member: structType->getMembers()) for (auto const& member: structType->members())
{ {
pushZeroValue(*member.type); pushZeroValue(*member.type);
storeInMemoryDynamic(*member.type); storeInMemoryDynamic(*member.type);
@ -575,14 +575,14 @@ void CompilerUtils::pushZeroValue(const Type& _type)
m_context << u256(0); m_context << u256(0);
storeInMemoryDynamic(IntegerType(256)); storeInMemoryDynamic(IntegerType(256));
} }
else if (arrayType->getLength() > 0) else if (arrayType->length() > 0)
{ {
m_context << arrayType->getLength() << eth::Instruction::SWAP1; m_context << arrayType->length() << eth::Instruction::SWAP1;
// stack: items_to_do memory_pos // stack: items_to_do memory_pos
auto repeat = m_context.newTag(); auto repeat = m_context.newTag();
m_context << repeat; m_context << repeat;
pushZeroValue(*arrayType->getBaseType()); pushZeroValue(*arrayType->baseType());
storeInMemoryDynamic(*arrayType->getBaseType()); storeInMemoryDynamic(*arrayType->baseType());
m_context << eth::Instruction::SWAP1 << u256(1) << eth::Instruction::SWAP1; m_context << eth::Instruction::SWAP1 << u256(1) << eth::Instruction::SWAP1;
m_context << eth::Instruction::SUB << eth::Instruction::SWAP1; m_context << eth::Instruction::SUB << eth::Instruction::SWAP1;
m_context << eth::Instruction::DUP2; m_context << eth::Instruction::DUP2;
@ -599,14 +599,14 @@ void CompilerUtils::pushZeroValue(const Type& _type)
void CompilerUtils::moveToStackVariable(VariableDeclaration const& _variable) void CompilerUtils::moveToStackVariable(VariableDeclaration const& _variable)
{ {
unsigned const stackPosition = m_context.baseToCurrentStackOffset(m_context.getBaseStackOffsetOfVariable(_variable)); unsigned const stackPosition = m_context.baseToCurrentStackOffset(m_context.baseStackOffsetOfVariable(_variable));
unsigned const size = _variable.getType()->getSizeOnStack(); unsigned const size = _variable.type()->sizeOnStack();
solAssert(stackPosition >= size, "Variable size and position mismatch."); solAssert(stackPosition >= size, "Variable size and position mismatch.");
// move variable starting from its top end in the stack // move variable starting from its top end in the stack
if (stackPosition - size + 1 > 16) if (stackPosition - size + 1 > 16)
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
CompilerError() << CompilerError() <<
errinfo_sourceLocation(_variable.getLocation()) << errinfo_sourceLocation(_variable.location()) <<
errinfo_comment("Stack too deep, try removing local variables.") errinfo_comment("Stack too deep, try removing local variables.")
); );
for (unsigned i = 0; i < size; ++i) for (unsigned i = 0; i < size; ++i)
@ -636,7 +636,7 @@ void CompilerUtils::moveIntoStack(unsigned _stackDepth)
void CompilerUtils::popStackElement(Type const& _type) void CompilerUtils::popStackElement(Type const& _type)
{ {
popStackSlots(_type.getSizeOnStack()); popStackSlots(_type.sizeOnStack());
} }
void CompilerUtils::popStackSlots(size_t _amount) void CompilerUtils::popStackSlots(size_t _amount)
@ -645,11 +645,11 @@ void CompilerUtils::popStackSlots(size_t _amount)
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
} }
unsigned CompilerUtils::getSizeOnStack(vector<shared_ptr<Type const>> const& _variableTypes) unsigned CompilerUtils::sizeOnStack(vector<shared_ptr<Type const>> const& _variableTypes)
{ {
unsigned size = 0; unsigned size = 0;
for (shared_ptr<Type const> const& type: _variableTypes) for (shared_ptr<Type const> const& type: _variableTypes)
size += type->getSizeOnStack(); size += type->sizeOnStack();
return size; return size;
} }
@ -683,8 +683,8 @@ void CompilerUtils::storeStringData(bytesConstRef _data)
unsigned CompilerUtils::loadFromMemoryHelper(Type const& _type, bool _fromCalldata, bool _padToWordBoundaries) unsigned CompilerUtils::loadFromMemoryHelper(Type const& _type, bool _fromCalldata, bool _padToWordBoundaries)
{ {
unsigned numBytes = _type.getCalldataEncodedSize(_padToWordBoundaries); unsigned numBytes = _type.calldataEncodedSize(_padToWordBoundaries);
bool leftAligned = _type.getCategory() == Type::Category::FixedBytes; bool leftAligned = _type.category() == Type::Category::FixedBytes;
if (numBytes == 0) if (numBytes == 0)
m_context << eth::Instruction::POP << u256(0); m_context << eth::Instruction::POP << u256(0);
else else
@ -706,18 +706,18 @@ unsigned CompilerUtils::loadFromMemoryHelper(Type const& _type, bool _fromCallda
void CompilerUtils::cleanHigherOrderBits(IntegerType const& _typeOnStack) void CompilerUtils::cleanHigherOrderBits(IntegerType const& _typeOnStack)
{ {
if (_typeOnStack.getNumBits() == 256) if (_typeOnStack.numBits() == 256)
return; return;
else if (_typeOnStack.isSigned()) else if (_typeOnStack.isSigned())
m_context << u256(_typeOnStack.getNumBits() / 8 - 1) << eth::Instruction::SIGNEXTEND; m_context << u256(_typeOnStack.numBits() / 8 - 1) << eth::Instruction::SIGNEXTEND;
else else
m_context << ((u256(1) << _typeOnStack.getNumBits()) - 1) << eth::Instruction::AND; m_context << ((u256(1) << _typeOnStack.numBits()) - 1) << eth::Instruction::AND;
} }
unsigned CompilerUtils::prepareMemoryStore(Type const& _type, bool _padToWordBoundaries) const unsigned CompilerUtils::prepareMemoryStore(Type const& _type, bool _padToWordBoundaries) const
{ {
unsigned numBytes = _type.getCalldataEncodedSize(_padToWordBoundaries); unsigned numBytes = _type.calldataEncodedSize(_padToWordBoundaries);
bool leftAligned = _type.getCategory() == Type::Category::FixedBytes; bool leftAligned = _type.category() == Type::Category::FixedBytes;
if (numBytes == 0) if (numBytes == 0)
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
else else

View File

@ -131,8 +131,8 @@ public:
void popStackSlots(size_t _amount); void popStackSlots(size_t _amount);
template <class T> template <class T>
static unsigned getSizeOnStack(std::vector<T> const& _variables); static unsigned sizeOnStack(std::vector<T> const& _variables);
static unsigned getSizeOnStack(std::vector<std::shared_ptr<Type const>> const& _variableTypes); static unsigned sizeOnStack(std::vector<std::shared_ptr<Type const>> const& _variableTypes);
/// Appends code that computes tha SHA3 hash of the topmost stack element of 32 byte type. /// Appends code that computes tha SHA3 hash of the topmost stack element of 32 byte type.
void computeHashStatic(); void computeHashStatic();
@ -166,11 +166,11 @@ private:
template <class T> template <class T>
unsigned CompilerUtils::getSizeOnStack(std::vector<T> const& _variables) unsigned CompilerUtils::sizeOnStack(std::vector<T> const& _variables)
{ {
unsigned size = 0; unsigned size = 0;
for (T const& variable: _variables) for (T const& variable: _variables)
size += variable->getType()->getSizeOnStack(); size += variable->type()->sizeOnStack();
return size; return size;
} }

View File

@ -30,13 +30,13 @@ using namespace dev::solidity;
Declaration const* DeclarationContainer::conflictingDeclaration(Declaration const& _declaration) const Declaration const* DeclarationContainer::conflictingDeclaration(Declaration const& _declaration) const
{ {
ASTString const& name(_declaration.getName()); ASTString const& declarationName(_declaration.name());
solAssert(!name.empty(), ""); solAssert(!declarationName.empty(), "");
vector<Declaration const*> declarations; vector<Declaration const*> declarations;
if (m_declarations.count(name)) if (m_declarations.count(declarationName))
declarations += m_declarations.at(name); declarations += m_declarations.at(declarationName);
if (m_invisibleDeclarations.count(name)) if (m_invisibleDeclarations.count(declarationName))
declarations += m_invisibleDeclarations.at(name); declarations += m_invisibleDeclarations.at(declarationName);
if (dynamic_cast<FunctionDefinition const*>(&_declaration)) if (dynamic_cast<FunctionDefinition const*>(&_declaration))
{ {
@ -53,23 +53,23 @@ Declaration const* DeclarationContainer::conflictingDeclaration(Declaration cons
bool DeclarationContainer::registerDeclaration(Declaration const& _declaration, bool _invisible, bool _update) bool DeclarationContainer::registerDeclaration(Declaration const& _declaration, bool _invisible, bool _update)
{ {
ASTString const& name(_declaration.getName()); ASTString const& declarationName(_declaration.name());
if (name.empty()) if (declarationName.empty())
return true; return true;
if (_update) if (_update)
{ {
solAssert(!dynamic_cast<FunctionDefinition const*>(&_declaration), "Attempt to update function definition."); solAssert(!dynamic_cast<FunctionDefinition const*>(&_declaration), "Attempt to update function definition.");
m_declarations.erase(name); m_declarations.erase(declarationName);
m_invisibleDeclarations.erase(name); m_invisibleDeclarations.erase(declarationName);
} }
else if (conflictingDeclaration(_declaration)) else if (conflictingDeclaration(_declaration))
return false; return false;
if (_invisible) if (_invisible)
m_invisibleDeclarations[name].push_back(&_declaration); m_invisibleDeclarations[declarationName].push_back(&_declaration);
else else
m_declarations[name].push_back(&_declaration); m_declarations[declarationName].push_back(&_declaration);
return true; return true;
} }

View File

@ -49,8 +49,8 @@ public:
/// @returns false if the name was already declared. /// @returns false if the name was already declared.
bool registerDeclaration(Declaration const& _declaration, bool _invisible = false, bool _update = false); bool registerDeclaration(Declaration const& _declaration, bool _invisible = false, bool _update = false);
std::vector<Declaration const*> resolveName(ASTString const& _name, bool _recursive = false) const; std::vector<Declaration const*> resolveName(ASTString const& _name, bool _recursive = false) const;
Declaration const* getEnclosingDeclaration() const { return m_enclosingDeclaration; } Declaration const* enclosingDeclaration() const { return m_enclosingDeclaration; }
std::map<ASTString, std::vector<Declaration const*>> const& getDeclarations() const { return m_declarations; } std::map<ASTString, std::vector<Declaration const*>> const& declarations() const { return m_declarations; }
/// @returns whether declaration is valid, and if not also returns previous declaration. /// @returns whether declaration is valid, and if not also returns previous declaration.
Declaration const* conflictingDeclaration(Declaration const& _declaration) const; Declaration const* conflictingDeclaration(Declaration const& _declaration) const;

View File

@ -46,14 +46,14 @@ void ExpressionCompiler::compile(Expression const& _expression)
void ExpressionCompiler::appendStateVariableInitialization(VariableDeclaration const& _varDecl) void ExpressionCompiler::appendStateVariableInitialization(VariableDeclaration const& _varDecl)
{ {
if (!_varDecl.getValue()) if (!_varDecl.value())
return; return;
TypePointer type = _varDecl.getValue()->getType(); TypePointer type = _varDecl.value()->type();
solAssert(!!type, "Type information not available."); solAssert(!!type, "Type information not available.");
CompilerContext::LocationSetter locationSetter(m_context, _varDecl); CompilerContext::LocationSetter locationSetter(m_context, _varDecl);
_varDecl.getValue()->accept(*this); _varDecl.value()->accept(*this);
if (_varDecl.getType()->dataStoredIn(DataLocation::Storage)) if (_varDecl.type()->dataStoredIn(DataLocation::Storage))
{ {
// reference type, only convert value to mobile type and do final conversion in storeValue. // reference type, only convert value to mobile type and do final conversion in storeValue.
utils().convertType(*type, *type->mobileType()); utils().convertType(*type, *type->mobileType());
@ -61,19 +61,19 @@ void ExpressionCompiler::appendStateVariableInitialization(VariableDeclaration c
} }
else else
{ {
utils().convertType(*type, *_varDecl.getType()); utils().convertType(*type, *_varDecl.type());
type = _varDecl.getType(); type = _varDecl.type();
} }
StorageItem(m_context, _varDecl).storeValue(*type, _varDecl.getLocation(), true); StorageItem(m_context, _varDecl).storeValue(*type, _varDecl.location(), true);
} }
void ExpressionCompiler::appendConstStateVariableAccessor(VariableDeclaration const& _varDecl) void ExpressionCompiler::appendConstStateVariableAccessor(VariableDeclaration const& _varDecl)
{ {
solAssert(_varDecl.isConstant(), ""); solAssert(_varDecl.isConstant(), "");
_varDecl.getValue()->accept(*this); _varDecl.value()->accept(*this);
// append return // append return
m_context << eth::dupInstruction(_varDecl.getType()->getSizeOnStack() + 1); m_context << eth::dupInstruction(_varDecl.type()->sizeOnStack() + 1);
m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction); m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction);
} }
@ -83,13 +83,13 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
CompilerContext::LocationSetter locationSetter(m_context, _varDecl); CompilerContext::LocationSetter locationSetter(m_context, _varDecl);
FunctionType accessorType(_varDecl); FunctionType accessorType(_varDecl);
TypePointers const& paramTypes = accessorType.getParameterTypes(); TypePointers const& paramTypes = accessorType.parameterTypes();
// retrieve the position of the variable // retrieve the position of the variable
auto const& location = m_context.getStorageLocationOfVariable(_varDecl); auto const& location = m_context.storageLocationOfVariable(_varDecl);
m_context << location.first << u256(location.second); m_context << location.first << u256(location.second);
TypePointer returnType = _varDecl.getType(); TypePointer returnType = _varDecl.type();
for (size_t i = 0; i < paramTypes.size(); ++i) for (size_t i = 0; i < paramTypes.size(); ++i)
{ {
@ -110,7 +110,7 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
m_context << u256(64) << u256(0) << eth::Instruction::SHA3; m_context << u256(64) << u256(0) << eth::Instruction::SHA3;
// push offset // push offset
m_context << u256(0); m_context << u256(0);
returnType = mappingType->getValueType(); returnType = mappingType->valueType();
} }
else if (auto arrayType = dynamic_cast<ArrayType const*>(returnType.get())) else if (auto arrayType = dynamic_cast<ArrayType const*>(returnType.get()))
{ {
@ -118,7 +118,7 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
utils().copyToStackTop(paramTypes.size() - i + 1, 1); utils().copyToStackTop(paramTypes.size() - i + 1, 1);
ArrayUtils(m_context).accessIndex(*arrayType); ArrayUtils(m_context).accessIndex(*arrayType);
returnType = arrayType->getBaseType(); returnType = arrayType->baseType();
} }
else else
solAssert(false, "Index access is allowed only for \"mapping\" and \"array\" types."); solAssert(false, "Index access is allowed only for \"mapping\" and \"array\" types.");
@ -134,28 +134,28 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
utils().popStackSlots(paramTypes.size() - 1); utils().popStackSlots(paramTypes.size() - 1);
} }
unsigned retSizeOnStack = 0; unsigned retSizeOnStack = 0;
solAssert(accessorType.getReturnParameterTypes().size() >= 1, ""); solAssert(accessorType.returnParameterTypes().size() >= 1, "");
auto const& returnTypes = accessorType.getReturnParameterTypes(); auto const& returnTypes = accessorType.returnParameterTypes();
if (StructType const* structType = dynamic_cast<StructType const*>(returnType.get())) if (StructType const* structType = dynamic_cast<StructType const*>(returnType.get()))
{ {
// remove offset // remove offset
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
auto const& names = accessorType.getReturnParameterNames(); auto const& names = accessorType.returnParameterNames();
// struct // struct
for (size_t i = 0; i < names.size(); ++i) for (size_t i = 0; i < names.size(); ++i)
{ {
if (returnTypes[i]->getCategory() == Type::Category::Mapping) if (returnTypes[i]->category() == Type::Category::Mapping)
continue; continue;
if (auto arrayType = dynamic_cast<ArrayType const*>(returnTypes[i].get())) if (auto arrayType = dynamic_cast<ArrayType const*>(returnTypes[i].get()))
if (!arrayType->isByteArray()) if (!arrayType->isByteArray())
continue; continue;
pair<u256, unsigned> const& offsets = structType->getStorageOffsetsOfMember(names[i]); pair<u256, unsigned> const& offsets = structType->storageOffsetsOfMember(names[i]);
m_context << eth::Instruction::DUP1 << u256(offsets.first) << eth::Instruction::ADD << u256(offsets.second); m_context << eth::Instruction::DUP1 << u256(offsets.first) << eth::Instruction::ADD << u256(offsets.second);
TypePointer memberType = structType->getMemberType(names[i]); TypePointer memberType = structType->memberType(names[i]);
StorageItem(m_context, *memberType).retrieveValue(SourceLocation(), true); StorageItem(m_context, *memberType).retrieveValue(SourceLocation(), true);
utils().convertType(*memberType, *returnTypes[i]); utils().convertType(*memberType, *returnTypes[i]);
utils().moveToStackTop(returnTypes[i]->getSizeOnStack()); utils().moveToStackTop(returnTypes[i]->sizeOnStack());
retSizeOnStack += returnTypes[i]->getSizeOnStack(); retSizeOnStack += returnTypes[i]->sizeOnStack();
} }
// remove slot // remove slot
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
@ -166,9 +166,9 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
solAssert(returnTypes.size() == 1, ""); solAssert(returnTypes.size() == 1, "");
StorageItem(m_context, *returnType).retrieveValue(SourceLocation(), true); StorageItem(m_context, *returnType).retrieveValue(SourceLocation(), true);
utils().convertType(*returnType, *returnTypes.front()); utils().convertType(*returnType, *returnTypes.front());
retSizeOnStack = returnTypes.front()->getSizeOnStack(); retSizeOnStack = returnTypes.front()->sizeOnStack();
} }
solAssert(retSizeOnStack == utils().getSizeOnStack(returnTypes), ""); solAssert(retSizeOnStack == utils().sizeOnStack(returnTypes), "");
solAssert(retSizeOnStack <= 15, "Stack is too deep."); solAssert(retSizeOnStack <= 15, "Stack is too deep.");
m_context << eth::dupInstruction(retSizeOnStack + 1); m_context << eth::dupInstruction(retSizeOnStack + 1);
m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction); m_context.appendJump(eth::AssemblyItem::JumpType::OutOfFunction);
@ -177,12 +177,12 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
bool ExpressionCompiler::visit(Assignment const& _assignment) bool ExpressionCompiler::visit(Assignment const& _assignment)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _assignment); CompilerContext::LocationSetter locationSetter(m_context, _assignment);
_assignment.getRightHandSide().accept(*this); _assignment.rightHandSide().accept(*this);
TypePointer type = _assignment.getRightHandSide().getType(); TypePointer type = _assignment.rightHandSide().type();
if (!_assignment.getType()->dataStoredIn(DataLocation::Storage)) if (!_assignment.type()->dataStoredIn(DataLocation::Storage))
{ {
utils().convertType(*type, *_assignment.getType()); utils().convertType(*type, *_assignment.type());
type = _assignment.getType(); type = _assignment.type();
} }
else else
{ {
@ -190,23 +190,23 @@ bool ExpressionCompiler::visit(Assignment const& _assignment)
type = type->mobileType(); type = type->mobileType();
} }
_assignment.getLeftHandSide().accept(*this); _assignment.leftHandSide().accept(*this);
solAssert(!!m_currentLValue, "LValue not retrieved."); solAssert(!!m_currentLValue, "LValue not retrieved.");
Token::Value op = _assignment.getAssignmentOperator(); Token::Value op = _assignment.assignmentOperator();
if (op != Token::Assign) // compound assignment if (op != Token::Assign) // compound assignment
{ {
solAssert(_assignment.getType()->isValueType(), "Compound operators not implemented for non-value types."); solAssert(_assignment.type()->isValueType(), "Compound operators not implemented for non-value types.");
unsigned lvalueSize = m_currentLValue->sizeOnStack(); unsigned lvalueSize = m_currentLValue->sizeOnStack();
unsigned itemSize = _assignment.getType()->getSizeOnStack(); unsigned itemSize = _assignment.type()->sizeOnStack();
if (lvalueSize > 0) if (lvalueSize > 0)
{ {
utils().copyToStackTop(lvalueSize + itemSize, itemSize); utils().copyToStackTop(lvalueSize + itemSize, itemSize);
utils().copyToStackTop(itemSize + lvalueSize, lvalueSize); utils().copyToStackTop(itemSize + lvalueSize, lvalueSize);
// value lvalue_ref value lvalue_ref // value lvalue_ref value lvalue_ref
} }
m_currentLValue->retrieveValue(_assignment.getLocation(), true); m_currentLValue->retrieveValue(_assignment.location(), true);
appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), *_assignment.getType()); appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), *_assignment.type());
if (lvalueSize > 0) if (lvalueSize > 0)
{ {
solAssert(itemSize + lvalueSize <= 16, "Stack too deep, try removing local variables."); solAssert(itemSize + lvalueSize <= 16, "Stack too deep, try removing local variables.");
@ -215,7 +215,7 @@ bool ExpressionCompiler::visit(Assignment const& _assignment)
m_context << eth::swapInstruction(itemSize + lvalueSize) << eth::Instruction::POP; m_context << eth::swapInstruction(itemSize + lvalueSize) << eth::Instruction::POP;
} }
} }
m_currentLValue->storeValue(*type, _assignment.getLocation()); m_currentLValue->storeValue(*type, _assignment.location());
m_currentLValue.reset(); m_currentLValue.reset();
return false; return false;
} }
@ -227,13 +227,13 @@ bool ExpressionCompiler::visit(UnaryOperation const& _unaryOperation)
// the operator should know how to convert itself and to which types it applies, so // the operator should know how to convert itself and to which types it applies, so
// put this code together with "Type::acceptsBinary/UnaryOperator" into a class that // put this code together with "Type::acceptsBinary/UnaryOperator" into a class that
// represents the operator // represents the operator
if (_unaryOperation.getType()->getCategory() == Type::Category::IntegerConstant) if (_unaryOperation.type()->category() == Type::Category::IntegerConstant)
{ {
m_context << _unaryOperation.getType()->literalValue(nullptr); m_context << _unaryOperation.type()->literalValue(nullptr);
return false; return false;
} }
_unaryOperation.getSubExpression().accept(*this); _unaryOperation.subExpression().accept(*this);
switch (_unaryOperation.getOperator()) switch (_unaryOperation.getOperator())
{ {
@ -248,17 +248,17 @@ bool ExpressionCompiler::visit(UnaryOperation const& _unaryOperation)
break; break;
case Token::Delete: // delete case Token::Delete: // delete
solAssert(!!m_currentLValue, "LValue not retrieved."); solAssert(!!m_currentLValue, "LValue not retrieved.");
m_currentLValue->setToZero(_unaryOperation.getLocation()); m_currentLValue->setToZero(_unaryOperation.location());
m_currentLValue.reset(); m_currentLValue.reset();
break; break;
case Token::Inc: // ++ (pre- or postfix) case Token::Inc: // ++ (pre- or postfix)
case Token::Dec: // -- (pre- or postfix) case Token::Dec: // -- (pre- or postfix)
solAssert(!!m_currentLValue, "LValue not retrieved."); solAssert(!!m_currentLValue, "LValue not retrieved.");
m_currentLValue->retrieveValue(_unaryOperation.getLocation()); m_currentLValue->retrieveValue(_unaryOperation.location());
if (!_unaryOperation.isPrefixOperation()) if (!_unaryOperation.isPrefixOperation())
{ {
// store value for later // store value for later
solAssert(_unaryOperation.getType()->getSizeOnStack() == 1, "Stack size != 1 not implemented."); solAssert(_unaryOperation.type()->sizeOnStack() == 1, "Stack size != 1 not implemented.");
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
if (m_currentLValue->sizeOnStack() > 0) if (m_currentLValue->sizeOnStack() > 0)
for (unsigned i = 1 + m_currentLValue->sizeOnStack(); i > 0; --i) for (unsigned i = 1 + m_currentLValue->sizeOnStack(); i > 0; --i)
@ -274,7 +274,7 @@ bool ExpressionCompiler::visit(UnaryOperation const& _unaryOperation)
for (unsigned i = m_currentLValue->sizeOnStack(); i > 0; --i) for (unsigned i = m_currentLValue->sizeOnStack(); i > 0; --i)
m_context << eth::swapInstruction(i); m_context << eth::swapInstruction(i);
m_currentLValue->storeValue( m_currentLValue->storeValue(
*_unaryOperation.getType(), _unaryOperation.getLocation(), *_unaryOperation.type(), _unaryOperation.location(),
!_unaryOperation.isPrefixOperation()); !_unaryOperation.isPrefixOperation());
m_currentLValue.reset(); m_currentLValue.reset();
break; break;
@ -294,39 +294,39 @@ bool ExpressionCompiler::visit(UnaryOperation const& _unaryOperation)
bool ExpressionCompiler::visit(BinaryOperation const& _binaryOperation) bool ExpressionCompiler::visit(BinaryOperation const& _binaryOperation)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _binaryOperation); CompilerContext::LocationSetter locationSetter(m_context, _binaryOperation);
Expression const& leftExpression = _binaryOperation.getLeftExpression(); Expression const& leftExpression = _binaryOperation.leftExpression();
Expression const& rightExpression = _binaryOperation.getRightExpression(); Expression const& rightExpression = _binaryOperation.rightExpression();
Type const& commonType = _binaryOperation.getCommonType(); Type const& commonType = _binaryOperation.commonType();
Token::Value const c_op = _binaryOperation.getOperator(); Token::Value const c_op = _binaryOperation.getOperator();
if (c_op == Token::And || c_op == Token::Or) // special case: short-circuiting if (c_op == Token::And || c_op == Token::Or) // special case: short-circuiting
appendAndOrOperatorCode(_binaryOperation); appendAndOrOperatorCode(_binaryOperation);
else if (commonType.getCategory() == Type::Category::IntegerConstant) else if (commonType.category() == Type::Category::IntegerConstant)
m_context << commonType.literalValue(nullptr); m_context << commonType.literalValue(nullptr);
else else
{ {
bool cleanupNeeded = commonType.getCategory() == Type::Category::Integer && bool cleanupNeeded = commonType.category() == Type::Category::Integer &&
(Token::isCompareOp(c_op) || c_op == Token::Div || c_op == Token::Mod); (Token::isCompareOp(c_op) || c_op == Token::Div || c_op == Token::Mod);
// for commutative operators, push the literal as late as possible to allow improved optimization // for commutative operators, push the literal as late as possible to allow improved optimization
auto isLiteral = [](Expression const& _e) auto isLiteral = [](Expression const& _e)
{ {
return dynamic_cast<Literal const*>(&_e) || _e.getType()->getCategory() == Type::Category::IntegerConstant; return dynamic_cast<Literal const*>(&_e) || _e.type()->category() == Type::Category::IntegerConstant;
}; };
bool swap = m_optimize && Token::isCommutativeOp(c_op) && isLiteral(rightExpression) && !isLiteral(leftExpression); bool swap = m_optimize && Token::isCommutativeOp(c_op) && isLiteral(rightExpression) && !isLiteral(leftExpression);
if (swap) if (swap)
{ {
leftExpression.accept(*this); leftExpression.accept(*this);
utils().convertType(*leftExpression.getType(), commonType, cleanupNeeded); utils().convertType(*leftExpression.type(), commonType, cleanupNeeded);
rightExpression.accept(*this); rightExpression.accept(*this);
utils().convertType(*rightExpression.getType(), commonType, cleanupNeeded); utils().convertType(*rightExpression.type(), commonType, cleanupNeeded);
} }
else else
{ {
rightExpression.accept(*this); rightExpression.accept(*this);
utils().convertType(*rightExpression.getType(), commonType, cleanupNeeded); utils().convertType(*rightExpression.type(), commonType, cleanupNeeded);
leftExpression.accept(*this); leftExpression.accept(*this);
utils().convertType(*leftExpression.getType(), commonType, cleanupNeeded); utils().convertType(*leftExpression.type(), commonType, cleanupNeeded);
} }
if (Token::isCompareOp(c_op)) if (Token::isCompareOp(c_op))
appendCompareOperatorCode(c_op, commonType); appendCompareOperatorCode(c_op, commonType);
@ -344,27 +344,27 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
using Location = FunctionType::Location; using Location = FunctionType::Location;
if (_functionCall.isTypeConversion()) if (_functionCall.isTypeConversion())
{ {
solAssert(_functionCall.getArguments().size() == 1, ""); solAssert(_functionCall.arguments().size() == 1, "");
solAssert(_functionCall.getNames().empty(), ""); solAssert(_functionCall.names().empty(), "");
Expression const& firstArgument = *_functionCall.getArguments().front(); Expression const& firstArgument = *_functionCall.arguments().front();
firstArgument.accept(*this); firstArgument.accept(*this);
utils().convertType(*firstArgument.getType(), *_functionCall.getType()); utils().convertType(*firstArgument.type(), *_functionCall.type());
return false; return false;
} }
FunctionTypePointer functionType; FunctionTypePointer functionType;
if (_functionCall.isStructConstructorCall()) if (_functionCall.isStructConstructorCall())
{ {
auto const& type = dynamic_cast<TypeType const&>(*_functionCall.getExpression().getType()); auto const& type = dynamic_cast<TypeType const&>(*_functionCall.expression().type());
auto const& structType = dynamic_cast<StructType const&>(*type.getActualType()); auto const& structType = dynamic_cast<StructType const&>(*type.actualType());
functionType = structType.constructorType(); functionType = structType.constructorType();
} }
else else
functionType = dynamic_pointer_cast<FunctionType const>(_functionCall.getExpression().getType()); functionType = dynamic_pointer_cast<FunctionType const>(_functionCall.expression().type());
TypePointers const& parameterTypes = functionType->getParameterTypes(); TypePointers const& parameterTypes = functionType->parameterTypes();
vector<ASTPointer<Expression const>> const& callArguments = _functionCall.getArguments(); vector<ASTPointer<Expression const>> const& callArguments = _functionCall.arguments();
vector<ASTPointer<ASTString>> const& callArgumentNames = _functionCall.getNames(); vector<ASTPointer<ASTString>> const& callArgumentNames = _functionCall.names();
if (!functionType->takesArbitraryParameters()) if (!functionType->takesArbitraryParameters())
solAssert(callArguments.size() == parameterTypes.size(), ""); solAssert(callArguments.size() == parameterTypes.size(), "");
@ -374,7 +374,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
arguments = callArguments; arguments = callArguments;
else else
// named arguments // named arguments
for (auto const& parameterName: functionType->getParameterNames()) for (auto const& parameterName: functionType->parameterNames())
{ {
bool found = false; bool found = false;
for (size_t j = 0; j < callArgumentNames.size() && !found; j++) for (size_t j = 0; j < callArgumentNames.size() && !found; j++)
@ -386,25 +386,25 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
if (_functionCall.isStructConstructorCall()) if (_functionCall.isStructConstructorCall())
{ {
TypeType const& type = dynamic_cast<TypeType const&>(*_functionCall.getExpression().getType()); TypeType const& type = dynamic_cast<TypeType const&>(*_functionCall.expression().type());
auto const& structType = dynamic_cast<StructType const&>(*type.getActualType()); auto const& structType = dynamic_cast<StructType const&>(*type.actualType());
m_context << u256(max(32u, structType.getCalldataEncodedSize(true))); m_context << u256(max(32u, structType.calldataEncodedSize(true)));
utils().allocateMemory(); utils().allocateMemory();
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
for (unsigned i = 0; i < arguments.size(); ++i) for (unsigned i = 0; i < arguments.size(); ++i)
{ {
arguments[i]->accept(*this); arguments[i]->accept(*this);
utils().convertType(*arguments[i]->getType(), *functionType->getParameterTypes()[i]); utils().convertType(*arguments[i]->type(), *functionType->parameterTypes()[i]);
utils().storeInMemoryDynamic(*functionType->getParameterTypes()[i]); utils().storeInMemoryDynamic(*functionType->parameterTypes()[i]);
} }
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
} }
else else
{ {
FunctionType const& function = *functionType; FunctionType const& function = *functionType;
switch (function.getLocation()) switch (function.location())
{ {
case Location::Internal: case Location::Internal:
{ {
@ -415,45 +415,45 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
for (unsigned i = 0; i < arguments.size(); ++i) for (unsigned i = 0; i < arguments.size(); ++i)
{ {
arguments[i]->accept(*this); arguments[i]->accept(*this);
utils().convertType(*arguments[i]->getType(), *function.getParameterTypes()[i]); utils().convertType(*arguments[i]->type(), *function.parameterTypes()[i]);
} }
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
m_context.appendJump(eth::AssemblyItem::JumpType::IntoFunction); m_context.appendJump(eth::AssemblyItem::JumpType::IntoFunction);
m_context << returnLabel; m_context << returnLabel;
unsigned returnParametersSize = CompilerUtils::getSizeOnStack(function.getReturnParameterTypes()); unsigned returnParametersSize = CompilerUtils::sizeOnStack(function.returnParameterTypes());
// callee adds return parameters, but removes arguments and return label // callee adds return parameters, but removes arguments and return label
m_context.adjustStackOffset(returnParametersSize - CompilerUtils::getSizeOnStack(function.getParameterTypes()) - 1); m_context.adjustStackOffset(returnParametersSize - CompilerUtils::sizeOnStack(function.parameterTypes()) - 1);
// @todo for now, the return value of a function is its first return value, so remove // @todo for now, the return value of a function is its first return value, so remove
// all others // all others
for (unsigned i = 1; i < function.getReturnParameterTypes().size(); ++i) for (unsigned i = 1; i < function.returnParameterTypes().size(); ++i)
utils().popStackElement(*function.getReturnParameterTypes()[i]); utils().popStackElement(*function.returnParameterTypes()[i]);
break; break;
} }
case Location::External: case Location::External:
case Location::CallCode: case Location::CallCode:
case Location::Bare: case Location::Bare:
case Location::BareCallCode: case Location::BareCallCode:
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
appendExternalFunctionCall(function, arguments); appendExternalFunctionCall(function, arguments);
break; break;
case Location::Creation: case Location::Creation:
{ {
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
solAssert(!function.gasSet(), "Gas limit set for contract creation."); solAssert(!function.gasSet(), "Gas limit set for contract creation.");
solAssert(function.getReturnParameterTypes().size() == 1, ""); solAssert(function.returnParameterTypes().size() == 1, "");
TypePointers argumentTypes; TypePointers argumentTypes;
for (auto const& arg: arguments) for (auto const& arg: arguments)
{ {
arg->accept(*this); arg->accept(*this);
argumentTypes.push_back(arg->getType()); argumentTypes.push_back(arg->type());
} }
ContractDefinition const& contract = dynamic_cast<ContractType const&>( ContractDefinition const& contract = dynamic_cast<ContractType const&>(
*function.getReturnParameterTypes().front()).getContractDefinition(); *function.returnParameterTypes().front()).contractDefinition();
// copy the contract's code into memory // copy the contract's code into memory
bytes const& bytecode = m_context.getCompiledContract(contract); bytes const& bytecode = m_context.compiledContract(contract);
utils().fetchFreeMemoryPointer(); utils().fetchFreeMemoryPointer();
m_context << u256(bytecode.size()) << eth::Instruction::DUP1; m_context << u256(bytecode.size()) << eth::Instruction::DUP1;
//@todo could be done by actually appending the Assembly, but then we probably need to compile //@todo could be done by actually appending the Assembly, but then we probably need to compile
@ -462,7 +462,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
m_context << eth::Instruction::DUP4 << eth::Instruction::CODECOPY; m_context << eth::Instruction::DUP4 << eth::Instruction::CODECOPY;
m_context << eth::Instruction::ADD; m_context << eth::Instruction::ADD;
utils().encodeToMemory(argumentTypes, function.getParameterTypes()); utils().encodeToMemory(argumentTypes, function.parameterTypes());
// now on stack: memory_end_ptr // now on stack: memory_end_ptr
// need: size, offset, endowment // need: size, offset, endowment
utils().toSizeAfterFreeMemoryPointer(); utils().toSizeAfterFreeMemoryPointer();
@ -478,10 +478,10 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
case Location::SetGas: case Location::SetGas:
{ {
// stack layout: contract_address function_id [gas] [value] // stack layout: contract_address function_id [gas] [value]
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
arguments.front()->accept(*this); arguments.front()->accept(*this);
utils().convertType(*arguments.front()->getType(), IntegerType(256), true); utils().convertType(*arguments.front()->type(), IntegerType(256), true);
// Note that function is not the original function, but the ".gas" function. // Note that function is not the original function, but the ".gas" function.
// Its values of gasSet and valueSet is equal to the original function's though. // Its values of gasSet and valueSet is equal to the original function's though.
unsigned stackDepth = (function.gasSet() ? 1 : 0) + (function.valueSet() ? 1 : 0); unsigned stackDepth = (function.gasSet() ? 1 : 0) + (function.valueSet() ? 1 : 0);
@ -493,7 +493,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
} }
case Location::SetValue: case Location::SetValue:
// stack layout: contract_address function_id [gas] [value] // stack layout: contract_address function_id [gas] [value]
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
// Note that function is not the original function, but the ".value" function. // Note that function is not the original function, but the ".value" function.
// Its values of gasSet and valueSet is equal to the original function's though. // Its values of gasSet and valueSet is equal to the original function's though.
if (function.valueSet()) if (function.valueSet())
@ -501,12 +501,12 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
arguments.front()->accept(*this); arguments.front()->accept(*this);
break; break;
case Location::Send: case Location::Send:
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
m_context << u256(0); // do not send gas (there still is the stipend) m_context << u256(0); // do not send gas (there still is the stipend)
arguments.front()->accept(*this); arguments.front()->accept(*this);
utils().convertType( utils().convertType(
*arguments.front()->getType(), *arguments.front()->type(),
*function.getParameterTypes().front(), true *function.parameterTypes().front(), true
); );
appendExternalFunctionCall( appendExternalFunctionCall(
FunctionType( FunctionType(
@ -525,7 +525,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
break; break;
case Location::Suicide: case Location::Suicide:
arguments.front()->accept(*this); arguments.front()->accept(*this);
utils().convertType(*arguments.front()->getType(), *function.getParameterTypes().front(), true); utils().convertType(*arguments.front()->type(), *function.parameterTypes().front(), true);
m_context << eth::Instruction::SUICIDE; m_context << eth::Instruction::SUICIDE;
break; break;
case Location::SHA3: case Location::SHA3:
@ -534,7 +534,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
for (auto const& arg: arguments) for (auto const& arg: arguments)
{ {
arg->accept(*this); arg->accept(*this);
argumentTypes.push_back(arg->getType()); argumentTypes.push_back(arg->type());
} }
utils().fetchFreeMemoryPointer(); utils().fetchFreeMemoryPointer();
utils().encodeToMemory(argumentTypes, TypePointers(), function.padArguments(), true); utils().encodeToMemory(argumentTypes, TypePointers(), function.padArguments(), true);
@ -548,17 +548,17 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
case Location::Log3: case Location::Log3:
case Location::Log4: case Location::Log4:
{ {
unsigned logNumber = int(function.getLocation()) - int(Location::Log0); unsigned logNumber = int(function.location()) - int(Location::Log0);
for (unsigned arg = logNumber; arg > 0; --arg) for (unsigned arg = logNumber; arg > 0; --arg)
{ {
arguments[arg]->accept(*this); arguments[arg]->accept(*this);
utils().convertType(*arguments[arg]->getType(), *function.getParameterTypes()[arg], true); utils().convertType(*arguments[arg]->type(), *function.parameterTypes()[arg], true);
} }
arguments.front()->accept(*this); arguments.front()->accept(*this);
utils().fetchFreeMemoryPointer(); utils().fetchFreeMemoryPointer();
utils().encodeToMemory( utils().encodeToMemory(
{arguments.front()->getType()}, {arguments.front()->type()},
{function.getParameterTypes().front()}, {function.parameterTypes().front()},
false, false,
true); true);
utils().toSizeAfterFreeMemoryPointer(); utils().toSizeAfterFreeMemoryPointer();
@ -567,24 +567,24 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
} }
case Location::Event: case Location::Event:
{ {
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
auto const& event = dynamic_cast<EventDefinition const&>(function.getDeclaration()); auto const& event = dynamic_cast<EventDefinition const&>(function.declaration());
unsigned numIndexed = 0; unsigned numIndexed = 0;
// All indexed arguments go to the stack // All indexed arguments go to the stack
for (unsigned arg = arguments.size(); arg > 0; --arg) for (unsigned arg = arguments.size(); arg > 0; --arg)
if (event.getParameters()[arg - 1]->isIndexed()) if (event.parameters()[arg - 1]->isIndexed())
{ {
++numIndexed; ++numIndexed;
arguments[arg - 1]->accept(*this); arguments[arg - 1]->accept(*this);
utils().convertType( utils().convertType(
*arguments[arg - 1]->getType(), *arguments[arg - 1]->type(),
*function.getParameterTypes()[arg - 1], *function.parameterTypes()[arg - 1],
true true
); );
} }
if (!event.isAnonymous()) if (!event.isAnonymous())
{ {
m_context << u256(h256::Arith(dev::sha3(function.externalSignature(event.getName())))); m_context << u256(h256::Arith(dev::sha3(function.externalSignature(event.name()))));
++numIndexed; ++numIndexed;
} }
solAssert(numIndexed <= 4, "Too many indexed arguments."); solAssert(numIndexed <= 4, "Too many indexed arguments.");
@ -593,11 +593,11 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
TypePointers nonIndexedArgTypes; TypePointers nonIndexedArgTypes;
TypePointers nonIndexedParamTypes; TypePointers nonIndexedParamTypes;
for (unsigned arg = 0; arg < arguments.size(); ++arg) for (unsigned arg = 0; arg < arguments.size(); ++arg)
if (!event.getParameters()[arg]->isIndexed()) if (!event.parameters()[arg]->isIndexed())
{ {
arguments[arg]->accept(*this); arguments[arg]->accept(*this);
nonIndexedArgTypes.push_back(arguments[arg]->getType()); nonIndexedArgTypes.push_back(arguments[arg]->type());
nonIndexedParamTypes.push_back(function.getParameterTypes()[arg]); nonIndexedParamTypes.push_back(function.parameterTypes()[arg]);
} }
utils().fetchFreeMemoryPointer(); utils().fetchFreeMemoryPointer();
utils().encodeToMemory(nonIndexedArgTypes, nonIndexedParamTypes); utils().encodeToMemory(nonIndexedArgTypes, nonIndexedParamTypes);
@ -609,7 +609,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
case Location::BlockHash: case Location::BlockHash:
{ {
arguments[0]->accept(*this); arguments[0]->accept(*this);
utils().convertType(*arguments[0]->getType(), *function.getParameterTypes()[0], true); utils().convertType(*arguments[0]->type(), *function.parameterTypes()[0], true);
m_context << eth::Instruction::BLOCKHASH; m_context << eth::Instruction::BLOCKHASH;
break; break;
} }
@ -617,12 +617,12 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
case Location::SHA256: case Location::SHA256:
case Location::RIPEMD160: case Location::RIPEMD160:
{ {
_functionCall.getExpression().accept(*this); _functionCall.expression().accept(*this);
static const map<Location, u256> contractAddresses{{Location::ECRecover, 1}, static const map<Location, u256> contractAddresses{{Location::ECRecover, 1},
{Location::SHA256, 2}, {Location::SHA256, 2},
{Location::RIPEMD160, 3}}; {Location::RIPEMD160, 3}};
m_context << contractAddresses.find(function.getLocation())->second; m_context << contractAddresses.find(function.location())->second;
for (unsigned i = function.getSizeOnStack(); i > 0; --i) for (unsigned i = function.sizeOnStack(); i > 0; --i)
m_context << eth::swapInstruction(i); m_context << eth::swapInstruction(i);
appendExternalFunctionCall(function, arguments); appendExternalFunctionCall(function, arguments);
break; break;
@ -643,19 +643,19 @@ bool ExpressionCompiler::visit(NewExpression const&)
void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess) void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _memberAccess); CompilerContext::LocationSetter locationSetter(m_context, _memberAccess);
ASTString const& member = _memberAccess.getMemberName(); ASTString const& member = _memberAccess.memberName();
switch (_memberAccess.getExpression().getType()->getCategory()) switch (_memberAccess.expression().type()->category())
{ {
case Type::Category::Contract: case Type::Category::Contract:
{ {
bool alsoSearchInteger = false; bool alsoSearchInteger = false;
ContractType const& type = dynamic_cast<ContractType const&>(*_memberAccess.getExpression().getType()); ContractType const& type = dynamic_cast<ContractType const&>(*_memberAccess.expression().type());
if (type.isSuper()) if (type.isSuper())
{ {
solAssert(!!_memberAccess.referencedDeclaration(), "Referenced declaration not resolved."); solAssert(!!_memberAccess.referencedDeclaration(), "Referenced declaration not resolved.");
m_context << m_context.getSuperFunctionEntryLabel( m_context << m_context.superFunctionEntryLabel(
dynamic_cast<FunctionDefinition const&>(*_memberAccess.referencedDeclaration()), dynamic_cast<FunctionDefinition const&>(*_memberAccess.referencedDeclaration()),
type.getContractDefinition() type.contractDefinition()
).pushTag(); ).pushTag();
} }
else else
@ -684,7 +684,7 @@ void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
if (member == "balance") if (member == "balance")
{ {
utils().convertType( utils().convertType(
*_memberAccess.getExpression().getType(), *_memberAccess.expression().type(),
IntegerType(0, IntegerType::Modifier::Address), IntegerType(0, IntegerType::Modifier::Address),
true true
); );
@ -692,7 +692,7 @@ void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
} }
else if ((set<string>{"send", "call", "callcode"}).count(member)) else if ((set<string>{"send", "call", "callcode"}).count(member))
utils().convertType( utils().convertType(
*_memberAccess.getExpression().getType(), *_memberAccess.expression().type(),
IntegerType(0, IntegerType::Modifier::Address), IntegerType(0, IntegerType::Modifier::Address),
true true
); );
@ -700,7 +700,7 @@ void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid member access to integer.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid member access to integer."));
break; break;
case Type::Category::Function: case Type::Category::Function:
solAssert(!!_memberAccess.getExpression().getType()->getMemberType(member), solAssert(!!_memberAccess.expression().type()->memberType(member),
"Invalid member access to function."); "Invalid member access to function.");
break; break;
case Type::Category::Magic: case Type::Category::Magic:
@ -735,12 +735,12 @@ void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
break; break;
case Type::Category::Struct: case Type::Category::Struct:
{ {
StructType const& type = dynamic_cast<StructType const&>(*_memberAccess.getExpression().getType()); StructType const& type = dynamic_cast<StructType const&>(*_memberAccess.expression().type());
switch (type.location()) switch (type.location())
{ {
case DataLocation::Storage: case DataLocation::Storage:
{ {
pair<u256, unsigned> const& offsets = type.getStorageOffsetsOfMember(member); pair<u256, unsigned> const& offsets = type.storageOffsetsOfMember(member);
m_context << offsets.first << eth::Instruction::ADD << u256(offsets.second); m_context << offsets.first << eth::Instruction::ADD << u256(offsets.second);
setLValueToStorageItem(_memberAccess); setLValueToStorageItem(_memberAccess);
break; break;
@ -748,7 +748,7 @@ void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
case DataLocation::Memory: case DataLocation::Memory:
{ {
m_context << type.memoryOffsetOfMember(member) << eth::Instruction::ADD; m_context << type.memoryOffsetOfMember(member) << eth::Instruction::ADD;
setLValue<MemoryItem>(_memberAccess, *_memberAccess.getType()); setLValue<MemoryItem>(_memberAccess, *_memberAccess.type());
break; break;
} }
default: default:
@ -758,36 +758,36 @@ void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
} }
case Type::Category::Enum: case Type::Category::Enum:
{ {
EnumType const& type = dynamic_cast<EnumType const&>(*_memberAccess.getExpression().getType()); EnumType const& type = dynamic_cast<EnumType const&>(*_memberAccess.expression().type());
m_context << type.getMemberValue(_memberAccess.getMemberName()); m_context << type.memberValue(_memberAccess.memberName());
break; break;
} }
case Type::Category::TypeType: case Type::Category::TypeType:
{ {
TypeType const& type = dynamic_cast<TypeType const&>(*_memberAccess.getExpression().getType()); TypeType const& type = dynamic_cast<TypeType const&>(*_memberAccess.expression().type());
solAssert( solAssert(
!type.getMembers().membersByName(_memberAccess.getMemberName()).empty(), !type.members().membersByName(_memberAccess.memberName()).empty(),
"Invalid member access to " + type.toString(false) "Invalid member access to " + type.toString(false)
); );
if (dynamic_cast<ContractType const*>(type.getActualType().get())) if (dynamic_cast<ContractType const*>(type.actualType().get()))
{ {
auto const* function = dynamic_cast<FunctionDefinition const*>(_memberAccess.referencedDeclaration()); auto const* function = dynamic_cast<FunctionDefinition const*>(_memberAccess.referencedDeclaration());
solAssert(!!function, "Function not found in member access"); solAssert(!!function, "Function not found in member access");
m_context << m_context.getFunctionEntryLabel(*function).pushTag(); m_context << m_context.functionEntryLabel(*function).pushTag();
} }
else if (auto enumType = dynamic_cast<EnumType const*>(type.getActualType().get())) else if (auto enumType = dynamic_cast<EnumType const*>(type.actualType().get()))
m_context << enumType->getMemberValue(_memberAccess.getMemberName()); m_context << enumType->memberValue(_memberAccess.memberName());
break; break;
} }
case Type::Category::Array: case Type::Category::Array:
{ {
solAssert(member == "length", "Illegal array member."); solAssert(member == "length", "Illegal array member.");
auto const& type = dynamic_cast<ArrayType const&>(*_memberAccess.getExpression().getType()); auto const& type = dynamic_cast<ArrayType const&>(*_memberAccess.expression().type());
if (!type.isDynamicallySized()) if (!type.isDynamicallySized())
{ {
utils().popStackElement(type); utils().popStackElement(type);
m_context << type.getLength(); m_context << type.length();
} }
else else
switch (type.location()) switch (type.location())
@ -812,22 +812,22 @@ void ExpressionCompiler::endVisit(MemberAccess const& _memberAccess)
bool ExpressionCompiler::visit(IndexAccess const& _indexAccess) bool ExpressionCompiler::visit(IndexAccess const& _indexAccess)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _indexAccess); CompilerContext::LocationSetter locationSetter(m_context, _indexAccess);
_indexAccess.getBaseExpression().accept(*this); _indexAccess.baseExpression().accept(*this);
Type const& baseType = *_indexAccess.getBaseExpression().getType(); Type const& baseType = *_indexAccess.baseExpression().type();
if (baseType.getCategory() == Type::Category::Mapping) if (baseType.category() == Type::Category::Mapping)
{ {
// stack: storage_base_ref // stack: storage_base_ref
TypePointer keyType = dynamic_cast<MappingType const&>(baseType).getKeyType(); TypePointer keyType = dynamic_cast<MappingType const&>(baseType).keyType();
solAssert(_indexAccess.getIndexExpression(), "Index expression expected."); solAssert(_indexAccess.indexExpression(), "Index expression expected.");
if (keyType->isDynamicallySized()) if (keyType->isDynamicallySized())
{ {
_indexAccess.getIndexExpression()->accept(*this); _indexAccess.indexExpression()->accept(*this);
utils().fetchFreeMemoryPointer(); utils().fetchFreeMemoryPointer();
// stack: base index mem // stack: base index mem
// note: the following operations must not allocate memory! // note: the following operations must not allocate memory!
utils().encodeToMemory( utils().encodeToMemory(
TypePointers{_indexAccess.getIndexExpression()->getType()}, TypePointers{_indexAccess.indexExpression()->type()},
TypePointers{keyType}, TypePointers{keyType},
false, false,
true true
@ -839,7 +839,7 @@ bool ExpressionCompiler::visit(IndexAccess const& _indexAccess)
else else
{ {
m_context << u256(0); // memory position m_context << u256(0); // memory position
appendExpressionCopyToMemory(*keyType, *_indexAccess.getIndexExpression()); appendExpressionCopyToMemory(*keyType, *_indexAccess.indexExpression());
m_context << eth::Instruction::SWAP1; m_context << eth::Instruction::SWAP1;
solAssert(CompilerUtils::freeMemoryPointer >= 0x40, ""); solAssert(CompilerUtils::freeMemoryPointer >= 0x40, "");
utils().storeInMemoryDynamic(IntegerType(256)); utils().storeInMemoryDynamic(IntegerType(256));
@ -849,12 +849,12 @@ bool ExpressionCompiler::visit(IndexAccess const& _indexAccess)
m_context << u256(0); m_context << u256(0);
setLValueToStorageItem(_indexAccess); setLValueToStorageItem(_indexAccess);
} }
else if (baseType.getCategory() == Type::Category::Array) else if (baseType.category() == Type::Category::Array)
{ {
ArrayType const& arrayType = dynamic_cast<ArrayType const&>(baseType); ArrayType const& arrayType = dynamic_cast<ArrayType const&>(baseType);
solAssert(_indexAccess.getIndexExpression(), "Index expression expected."); solAssert(_indexAccess.indexExpression(), "Index expression expected.");
_indexAccess.getIndexExpression()->accept(*this); _indexAccess.indexExpression()->accept(*this);
// stack layout: <base_ref> [<length>] <index> // stack layout: <base_ref> [<length>] <index>
ArrayUtils(m_context).accessIndex(arrayType); ArrayUtils(m_context).accessIndex(arrayType);
switch (arrayType.location()) switch (arrayType.location())
@ -869,14 +869,14 @@ bool ExpressionCompiler::visit(IndexAccess const& _indexAccess)
setLValueToStorageItem(_indexAccess); setLValueToStorageItem(_indexAccess);
break; break;
case DataLocation::Memory: case DataLocation::Memory:
setLValue<MemoryItem>(_indexAccess, *_indexAccess.getType(), !arrayType.isByteArray()); setLValue<MemoryItem>(_indexAccess, *_indexAccess.type(), !arrayType.isByteArray());
break; break;
case DataLocation::CallData: case DataLocation::CallData:
//@todo if we implement this, the value in calldata has to be added to the base offset //@todo if we implement this, the value in calldata has to be added to the base offset
solAssert(!arrayType.getBaseType()->isDynamicallySized(), "Nested arrays not yet implemented."); solAssert(!arrayType.baseType()->isDynamicallySized(), "Nested arrays not yet implemented.");
if (arrayType.getBaseType()->isValueType()) if (arrayType.baseType()->isValueType())
CompilerUtils(m_context).loadFromMemoryDynamic( CompilerUtils(m_context).loadFromMemoryDynamic(
*arrayType.getBaseType(), *arrayType.baseType(),
true, true,
!arrayType.isByteArray(), !arrayType.isByteArray(),
false false
@ -893,14 +893,14 @@ bool ExpressionCompiler::visit(IndexAccess const& _indexAccess)
void ExpressionCompiler::endVisit(Identifier const& _identifier) void ExpressionCompiler::endVisit(Identifier const& _identifier)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _identifier); CompilerContext::LocationSetter locationSetter(m_context, _identifier);
Declaration const* declaration = &_identifier.getReferencedDeclaration(); Declaration const* declaration = &_identifier.referencedDeclaration();
if (MagicVariableDeclaration const* magicVar = dynamic_cast<MagicVariableDeclaration const*>(declaration)) if (MagicVariableDeclaration const* magicVar = dynamic_cast<MagicVariableDeclaration const*>(declaration))
{ {
switch (magicVar->getType()->getCategory()) switch (magicVar->type()->category())
{ {
case Type::Category::Contract: case Type::Category::Contract:
// "this" or "super" // "this" or "super"
if (!dynamic_cast<ContractType const&>(*magicVar->getType()).isSuper()) if (!dynamic_cast<ContractType const&>(*magicVar->type()).isSuper())
m_context << eth::Instruction::ADDRESS; m_context << eth::Instruction::ADDRESS;
break; break;
case Type::Category::Integer: case Type::Category::Integer:
@ -912,13 +912,13 @@ void ExpressionCompiler::endVisit(Identifier const& _identifier)
} }
} }
else if (FunctionDefinition const* functionDef = dynamic_cast<FunctionDefinition const*>(declaration)) else if (FunctionDefinition const* functionDef = dynamic_cast<FunctionDefinition const*>(declaration))
m_context << m_context.getVirtualFunctionEntryLabel(*functionDef).pushTag(); m_context << m_context.virtualFunctionEntryLabel(*functionDef).pushTag();
else if (auto variable = dynamic_cast<VariableDeclaration const*>(declaration)) else if (auto variable = dynamic_cast<VariableDeclaration const*>(declaration))
{ {
if (!variable->isConstant()) if (!variable->isConstant())
setLValueFromDeclaration(*declaration, _identifier); setLValueFromDeclaration(*declaration, _identifier);
else else
variable->getValue()->accept(*this); variable->value()->accept(*this);
} }
else if (dynamic_cast<ContractDefinition const*>(declaration)) else if (dynamic_cast<ContractDefinition const*>(declaration))
{ {
@ -941,8 +941,8 @@ void ExpressionCompiler::endVisit(Identifier const& _identifier)
void ExpressionCompiler::endVisit(Literal const& _literal) void ExpressionCompiler::endVisit(Literal const& _literal)
{ {
CompilerContext::LocationSetter locationSetter(m_context, _literal); CompilerContext::LocationSetter locationSetter(m_context, _literal);
TypePointer type = _literal.getType(); TypePointer type = _literal.type();
switch (type->getCategory()) switch (type->category())
{ {
case Type::Category::IntegerConstant: case Type::Category::IntegerConstant:
case Type::Category::Bool: case Type::Category::Bool:
@ -960,13 +960,13 @@ void ExpressionCompiler::appendAndOrOperatorCode(BinaryOperation const& _binaryO
Token::Value const c_op = _binaryOperation.getOperator(); Token::Value const c_op = _binaryOperation.getOperator();
solAssert(c_op == Token::Or || c_op == Token::And, ""); solAssert(c_op == Token::Or || c_op == Token::And, "");
_binaryOperation.getLeftExpression().accept(*this); _binaryOperation.leftExpression().accept(*this);
m_context << eth::Instruction::DUP1; m_context << eth::Instruction::DUP1;
if (c_op == Token::And) if (c_op == Token::And)
m_context << eth::Instruction::ISZERO; m_context << eth::Instruction::ISZERO;
eth::AssemblyItem endLabel = m_context.appendConditionalJump(); eth::AssemblyItem endLabel = m_context.appendConditionalJump();
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
_binaryOperation.getRightExpression().accept(*this); _binaryOperation.rightExpression().accept(*this);
m_context << endLabel; m_context << endLabel;
} }
@ -1088,7 +1088,7 @@ void ExpressionCompiler::appendExternalFunctionCall(
) )
{ {
solAssert(_functionType.takesArbitraryParameters() || solAssert(_functionType.takesArbitraryParameters() ||
_arguments.size() == _functionType.getParameterTypes().size(), ""); _arguments.size() == _functionType.parameterTypes().size(), "");
// Assumed stack content here: // Assumed stack content here:
// <stack top> // <stack top>
@ -1104,21 +1104,21 @@ void ExpressionCompiler::appendExternalFunctionCall(
unsigned valueStackPos = m_context.currentToBaseStackOffset(1); unsigned valueStackPos = m_context.currentToBaseStackOffset(1);
using FunctionKind = FunctionType::Location; using FunctionKind = FunctionType::Location;
FunctionKind funKind = _functionType.getLocation(); FunctionKind funKind = _functionType.location();
bool returnSuccessCondition = funKind == FunctionKind::Bare || funKind == FunctionKind::BareCallCode; bool returnSuccessCondition = funKind == FunctionKind::Bare || funKind == FunctionKind::BareCallCode;
bool isCallCode = funKind == FunctionKind::BareCallCode || funKind == FunctionKind::CallCode; bool isCallCode = funKind == FunctionKind::BareCallCode || funKind == FunctionKind::CallCode;
//@todo only return the first return value for now //@todo only return the first return value for now
Type const* firstReturnType = Type const* firstReturnType =
_functionType.getReturnParameterTypes().empty() ? _functionType.returnParameterTypes().empty() ?
nullptr : nullptr :
_functionType.getReturnParameterTypes().front().get(); _functionType.returnParameterTypes().front().get();
unsigned retSize = 0; unsigned retSize = 0;
if (returnSuccessCondition) if (returnSuccessCondition)
retSize = 0; // return value actually is success condition retSize = 0; // return value actually is success condition
else if (firstReturnType) else if (firstReturnType)
{ {
retSize = firstReturnType->getCalldataEncodedSize(); retSize = firstReturnType->calldataEncodedSize();
solAssert(retSize > 0, "Unable to return dynamic type from external call."); solAssert(retSize > 0, "Unable to return dynamic type from external call.");
} }
@ -1127,7 +1127,7 @@ void ExpressionCompiler::appendExternalFunctionCall(
bool manualFunctionId = bool manualFunctionId =
(funKind == FunctionKind::Bare || funKind == FunctionKind::BareCallCode) && (funKind == FunctionKind::Bare || funKind == FunctionKind::BareCallCode) &&
!_arguments.empty() && !_arguments.empty() &&
_arguments.front()->getType()->mobileType()->getCalldataEncodedSize(false) == _arguments.front()->type()->mobileType()->calldataEncodedSize(false) ==
CompilerUtils::dataStartOffset; CompilerUtils::dataStartOffset;
if (manualFunctionId) if (manualFunctionId)
{ {
@ -1135,7 +1135,7 @@ void ExpressionCompiler::appendExternalFunctionCall(
// function identifier. // function identifier.
_arguments.front()->accept(*this); _arguments.front()->accept(*this);
utils().convertType( utils().convertType(
*_arguments.front()->getType(), *_arguments.front()->type(),
IntegerType(8 * CompilerUtils::dataStartOffset), IntegerType(8 * CompilerUtils::dataStartOffset),
true true
); );
@ -1147,14 +1147,14 @@ void ExpressionCompiler::appendExternalFunctionCall(
for (size_t i = manualFunctionId ? 1 : 0; i < _arguments.size(); ++i) for (size_t i = manualFunctionId ? 1 : 0; i < _arguments.size(); ++i)
{ {
_arguments[i]->accept(*this); _arguments[i]->accept(*this);
argumentTypes.push_back(_arguments[i]->getType()); argumentTypes.push_back(_arguments[i]->type());
} }
// Copy function identifier to memory. // Copy function identifier to memory.
utils().fetchFreeMemoryPointer(); utils().fetchFreeMemoryPointer();
if (!_functionType.isBareCall() || manualFunctionId) if (!_functionType.isBareCall() || manualFunctionId)
{ {
m_context << eth::dupInstruction(2 + gasValueSize + CompilerUtils::getSizeOnStack(argumentTypes)); m_context << eth::dupInstruction(2 + gasValueSize + CompilerUtils::sizeOnStack(argumentTypes));
utils().storeInMemoryDynamic(IntegerType(8 * CompilerUtils::dataStartOffset), false); utils().storeInMemoryDynamic(IntegerType(8 * CompilerUtils::dataStartOffset), false);
} }
// If the function takes arbitrary parameters, copy dynamic length data in place. // If the function takes arbitrary parameters, copy dynamic length data in place.
@ -1162,7 +1162,7 @@ void ExpressionCompiler::appendExternalFunctionCall(
// pointer on the stack). // pointer on the stack).
utils().encodeToMemory( utils().encodeToMemory(
argumentTypes, argumentTypes,
_functionType.getParameterTypes(), _functionType.parameterTypes(),
_functionType.padArguments(), _functionType.padArguments(),
_functionType.takesArbitraryParameters() _functionType.takesArbitraryParameters()
); );
@ -1252,7 +1252,7 @@ void ExpressionCompiler::appendExpressionCopyToMemory(Type const& _expectedType,
{ {
solAssert(_expectedType.isValueType(), "Not implemented for non-value types."); solAssert(_expectedType.isValueType(), "Not implemented for non-value types.");
_expression.accept(*this); _expression.accept(*this);
utils().convertType(*_expression.getType(), _expectedType, true); utils().convertType(*_expression.type(), _expectedType, true);
utils().storeInMemoryDynamic(_expectedType); utils().storeInMemoryDynamic(_expectedType);
} }
@ -1264,13 +1264,13 @@ void ExpressionCompiler::setLValueFromDeclaration(Declaration const& _declaratio
setLValue<StorageItem>(_expression, _declaration); setLValue<StorageItem>(_expression, _declaration);
else else
BOOST_THROW_EXCEPTION(InternalCompilerError() BOOST_THROW_EXCEPTION(InternalCompilerError()
<< errinfo_sourceLocation(_expression.getLocation()) << errinfo_sourceLocation(_expression.location())
<< errinfo_comment("Identifier type not supported or identifier not found.")); << errinfo_comment("Identifier type not supported or identifier not found."));
} }
void ExpressionCompiler::setLValueToStorageItem(Expression const& _expression) void ExpressionCompiler::setLValueToStorageItem(Expression const& _expression)
{ {
setLValue<StorageItem>(_expression, *_expression.getType()); setLValue<StorageItem>(_expression, *_expression.type());
} }
CompilerUtils ExpressionCompiler::utils() CompilerUtils ExpressionCompiler::utils()

View File

@ -130,7 +130,7 @@ void ExpressionCompiler::setLValue(Expression const& _expression, _Arguments con
if (_expression.lvalueRequested()) if (_expression.lvalueRequested())
m_currentLValue = move(lvalue); m_currentLValue = move(lvalue);
else else
lvalue->retrieveValue(_expression.getLocation(), true); lvalue->retrieveValue(_expression.location(), true);
} }
} }

View File

@ -61,7 +61,7 @@ GasEstimator::ASTGasConsumptionSelfAccumulated GasEstimator::structuralEstimatio
{ {
if (!finestNodes.count(&_node)) if (!finestNodes.count(&_node))
return true; return true;
gasCosts[&_node][0] = gasCosts[&_node][1] = particularCosts[_node.getLocation()]; gasCosts[&_node][0] = gasCosts[&_node][1] = particularCosts[_node.location()];
return true; return true;
}; };
auto onEdge = [&](ASTNode const& _parent, ASTNode const& _child) auto onEdge = [&](ASTNode const& _parent, ASTNode const& _child)
@ -156,7 +156,7 @@ GasEstimator::GasConsumption GasEstimator::functionalEstimation(
{ {
auto state = make_shared<KnownState>(); auto state = make_shared<KnownState>();
unsigned parametersSize = CompilerUtils::getSizeOnStack(_function.getParameters()); unsigned parametersSize = CompilerUtils::sizeOnStack(_function.parameters());
if (parametersSize > 16) if (parametersSize > 16)
return GasConsumption::infinite(); return GasConsumption::infinite();
@ -178,9 +178,9 @@ set<ASTNode const*> GasEstimator::finestNodesAtLocation(
set<ASTNode const*> nodes; set<ASTNode const*> nodes;
SimpleASTVisitor visitor(function<bool(ASTNode const&)>(), [&](ASTNode const& _n) SimpleASTVisitor visitor(function<bool(ASTNode const&)>(), [&](ASTNode const& _n)
{ {
if (!locations.count(_n.getLocation())) if (!locations.count(_n.location()))
{ {
locations[_n.getLocation()] = &_n; locations[_n.location()] = &_n;
nodes.insert(&_n); nodes.insert(&_n);
} }
}); });

View File

@ -66,7 +66,7 @@ void GlobalContext::setCurrentContract(ContractDefinition const& _contract)
m_currentContract = &_contract; m_currentContract = &_contract;
} }
vector<Declaration const*> GlobalContext::getDeclarations() const vector<Declaration const*> GlobalContext::declarations() const
{ {
vector<Declaration const*> declarations; vector<Declaration const*> declarations;
declarations.reserve(m_magicVariables.size()); declarations.reserve(m_magicVariables.size());
@ -75,7 +75,7 @@ vector<Declaration const*> GlobalContext::getDeclarations() const
return declarations; return declarations;
} }
MagicVariableDeclaration const* GlobalContext::getCurrentThis() const MagicVariableDeclaration const* GlobalContext::currentThis() const
{ {
if (!m_thisPointer[m_currentContract]) if (!m_thisPointer[m_currentContract])
m_thisPointer[m_currentContract] = make_shared<MagicVariableDeclaration>( m_thisPointer[m_currentContract] = make_shared<MagicVariableDeclaration>(
@ -84,7 +84,7 @@ MagicVariableDeclaration const* GlobalContext::getCurrentThis() const
} }
MagicVariableDeclaration const* GlobalContext::getCurrentSuper() const MagicVariableDeclaration const* GlobalContext::currentSuper() const
{ {
if (!m_superPointer[m_currentContract]) if (!m_superPointer[m_currentContract])
m_superPointer[m_currentContract] = make_shared<MagicVariableDeclaration>( m_superPointer[m_currentContract] = make_shared<MagicVariableDeclaration>(

View File

@ -47,11 +47,11 @@ class GlobalContext: private boost::noncopyable
public: public:
GlobalContext(); GlobalContext();
void setCurrentContract(ContractDefinition const& _contract); void setCurrentContract(ContractDefinition const& _contract);
MagicVariableDeclaration const* getCurrentThis() const; MagicVariableDeclaration const* currentThis() const;
MagicVariableDeclaration const* getCurrentSuper() const; MagicVariableDeclaration const* currentSuper() const;
/// @returns a vector of all implicit global declarations excluding "this". /// @returns a vector of all implicit global declarations excluding "this".
std::vector<Declaration const*> getDeclarations() const; std::vector<Declaration const*> declarations() const;
private: private:
std::vector<std::shared_ptr<MagicVariableDeclaration const>> m_magicVariables; std::vector<std::shared_ptr<MagicVariableDeclaration const>> m_magicVariables;

View File

@ -16,7 +16,7 @@ InterfaceHandler::InterfaceHandler()
m_lastTag = DocTagType::None; m_lastTag = DocTagType::None;
} }
string InterfaceHandler::getDocumentation( string InterfaceHandler::documentation(
ContractDefinition const& _contractDef, ContractDefinition const& _contractDef,
DocumentationType _type DocumentationType _type
) )
@ -28,16 +28,16 @@ string InterfaceHandler::getDocumentation(
case DocumentationType::NatspecDev: case DocumentationType::NatspecDev:
return devDocumentation(_contractDef); return devDocumentation(_contractDef);
case DocumentationType::ABIInterface: case DocumentationType::ABIInterface:
return getABIInterface(_contractDef); return ABIInterface(_contractDef);
case DocumentationType::ABISolidityInterface: case DocumentationType::ABISolidityInterface:
return getABISolidityInterface(_contractDef); return ABISolidityInterface(_contractDef);
} }
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation type")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation type"));
return ""; return "";
} }
string InterfaceHandler::getABIInterface(ContractDefinition const& _contractDef) string InterfaceHandler::ABIInterface(ContractDefinition const& _contractDef)
{ {
Json::Value abi(Json::arrayValue); Json::Value abi(Json::arrayValue);
@ -55,48 +55,48 @@ string InterfaceHandler::getABIInterface(ContractDefinition const& _contractDef)
return params; return params;
}; };
for (auto it: _contractDef.getInterfaceFunctions()) for (auto it: _contractDef.interfaceFunctions())
{ {
auto externalFunctionType = it.second->externalFunctionType(); auto externalFunctionType = it.second->externalFunctionType();
Json::Value method; Json::Value method;
method["type"] = "function"; method["type"] = "function";
method["name"] = it.second->getDeclaration().getName(); method["name"] = it.second->declaration().name();
method["constant"] = it.second->isConstant(); method["constant"] = it.second->isConstant();
method["inputs"] = populateParameters( method["inputs"] = populateParameters(
externalFunctionType->getParameterNames(), externalFunctionType->parameterNames(),
externalFunctionType->getParameterTypeNames() externalFunctionType->parameterTypeNames()
); );
method["outputs"] = populateParameters( method["outputs"] = populateParameters(
externalFunctionType->getReturnParameterNames(), externalFunctionType->returnParameterNames(),
externalFunctionType->getReturnParameterTypeNames() externalFunctionType->returnParameterTypeNames()
); );
abi.append(method); abi.append(method);
} }
if (_contractDef.getConstructor()) if (_contractDef.constructor())
{ {
Json::Value method; Json::Value method;
method["type"] = "constructor"; method["type"] = "constructor";
auto externalFunction = FunctionType(*_contractDef.getConstructor()).externalFunctionType(); auto externalFunction = FunctionType(*_contractDef.constructor()).externalFunctionType();
solAssert(!!externalFunction, ""); solAssert(!!externalFunction, "");
method["inputs"] = populateParameters( method["inputs"] = populateParameters(
externalFunction->getParameterNames(), externalFunction->parameterNames(),
externalFunction->getParameterTypeNames() externalFunction->parameterTypeNames()
); );
abi.append(method); abi.append(method);
} }
for (auto const& it: _contractDef.getInterfaceEvents()) for (auto const& it: _contractDef.interfaceEvents())
{ {
Json::Value event; Json::Value event;
event["type"] = "event"; event["type"] = "event";
event["name"] = it->getName(); event["name"] = it->name();
event["anonymous"] = it->isAnonymous(); event["anonymous"] = it->isAnonymous();
Json::Value params(Json::arrayValue); Json::Value params(Json::arrayValue);
for (auto const& p: it->getParameters()) for (auto const& p: it->parameters())
{ {
Json::Value input; Json::Value input;
input["name"] = p->getName(); input["name"] = p->name();
input["type"] = p->getType()->toString(true); input["type"] = p->type()->toString(true);
input["indexed"] = p->isIndexed(); input["indexed"] = p->isIndexed();
params.append(input); params.append(input);
} }
@ -106,9 +106,9 @@ string InterfaceHandler::getABIInterface(ContractDefinition const& _contractDef)
return Json::FastWriter().write(abi); return Json::FastWriter().write(abi);
} }
string InterfaceHandler::getABISolidityInterface(ContractDefinition const& _contractDef) string InterfaceHandler::ABISolidityInterface(ContractDefinition const& _contractDef)
{ {
string ret = "contract " + _contractDef.getName() + "{"; string ret = "contract " + _contractDef.name() + "{";
auto populateParameters = [](vector<string> const& _paramNames, vector<string> const& _paramTypes) auto populateParameters = [](vector<string> const& _paramNames, vector<string> const& _paramTypes)
{ {
@ -118,23 +118,23 @@ string InterfaceHandler::getABISolidityInterface(ContractDefinition const& _cont
r += (r.size() ? "," : "(") + _paramTypes[i] + " " + _paramNames[i]; r += (r.size() ? "," : "(") + _paramTypes[i] + " " + _paramNames[i];
return r.size() ? r + ")" : "()"; return r.size() ? r + ")" : "()";
}; };
if (_contractDef.getConstructor()) if (_contractDef.constructor())
{ {
auto externalFunction = FunctionType(*_contractDef.getConstructor()).externalFunctionType(); auto externalFunction = FunctionType(*_contractDef.constructor()).externalFunctionType();
solAssert(!!externalFunction, ""); solAssert(!!externalFunction, "");
ret += ret +=
"function " + "function " +
_contractDef.getName() + _contractDef.name() +
populateParameters(externalFunction->getParameterNames(), externalFunction->getParameterTypeNames()) + populateParameters(externalFunction->parameterNames(), externalFunction->parameterTypeNames()) +
";"; ";";
} }
for (auto const& it: _contractDef.getInterfaceFunctions()) for (auto const& it: _contractDef.interfaceFunctions())
{ {
ret += "function " + it.second->getDeclaration().getName() + ret += "function " + it.second->declaration().name() +
populateParameters(it.second->getParameterNames(), it.second->getParameterTypeNames()) + populateParameters(it.second->parameterNames(), it.second->parameterTypeNames()) +
(it.second->isConstant() ? "constant " : ""); (it.second->isConstant() ? "constant " : "");
if (it.second->getReturnParameterTypes().size()) if (it.second->returnParameterTypes().size())
ret += "returns" + populateParameters(it.second->getReturnParameterNames(), it.second->getReturnParameterTypeNames()); ret += "returns" + populateParameters(it.second->returnParameterNames(), it.second->returnParameterTypeNames());
else if (ret.back() == ' ') else if (ret.back() == ' ')
ret.pop_back(); ret.pop_back();
ret += ";"; ret += ";";
@ -148,10 +148,10 @@ string InterfaceHandler::userDocumentation(ContractDefinition const& _contractDe
Json::Value doc; Json::Value doc;
Json::Value methods(Json::objectValue); Json::Value methods(Json::objectValue);
for (auto const& it: _contractDef.getInterfaceFunctions()) for (auto const& it: _contractDef.interfaceFunctions())
{ {
Json::Value user; Json::Value user;
auto strPtr = it.second->getDocumentation(); auto strPtr = it.second->documentation();
if (strPtr) if (strPtr)
{ {
resetUser(); resetUser();
@ -175,7 +175,7 @@ string InterfaceHandler::devDocumentation(ContractDefinition const& _contractDef
Json::Value doc; Json::Value doc;
Json::Value methods(Json::objectValue); Json::Value methods(Json::objectValue);
auto contractDoc = _contractDef.getDocumentation(); auto contractDoc = _contractDef.documentation();
if (contractDoc) if (contractDoc)
{ {
m_contractAuthor.clear(); m_contractAuthor.clear();
@ -189,10 +189,10 @@ string InterfaceHandler::devDocumentation(ContractDefinition const& _contractDef
doc["title"] = m_title; doc["title"] = m_title;
} }
for (auto const& it: _contractDef.getInterfaceFunctions()) for (auto const& it: _contractDef.interfaceFunctions())
{ {
Json::Value method; Json::Value method;
auto strPtr = it.second->getDocumentation(); auto strPtr = it.second->documentation();
if (strPtr) if (strPtr)
{ {
resetDev(); resetDev();
@ -205,7 +205,7 @@ string InterfaceHandler::devDocumentation(ContractDefinition const& _contractDef
method["author"] = m_author; method["author"] = m_author;
Json::Value params(Json::objectValue); Json::Value params(Json::objectValue);
vector<string> paramNames = it.second->getParameterNames(); vector<string> paramNames = it.second->parameterNames();
for (auto const& pair: m_params) for (auto const& pair: m_params)
{ {
if (find(paramNames.begin(), paramNames.end(), pair.first) == paramNames.end()) if (find(paramNames.begin(), paramNames.end(), pair.first) == paramNames.end())

View File

@ -66,15 +66,15 @@ public:
/// @param _type The type of the documentation. Can be one of the /// @param _type The type of the documentation. Can be one of the
/// types provided by @c DocumentationType /// types provided by @c DocumentationType
/// @return A string with the json representation of provided type /// @return A string with the json representation of provided type
std::string getDocumentation( std::string documentation(
ContractDefinition const& _contractDef, ContractDefinition const& _contractDef,
DocumentationType _type DocumentationType _type
); );
/// Get the ABI Interface of the contract /// Get the ABI Interface of the contract
/// @param _contractDef The contract definition /// @param _contractDef The contract definition
/// @return A string with the json representation of the contract's ABI Interface /// @return A string with the json representation of the contract's ABI Interface
std::string getABIInterface(ContractDefinition const& _contractDef); std::string ABIInterface(ContractDefinition const& _contractDef);
std::string getABISolidityInterface(ContractDefinition const& _contractDef); std::string ABISolidityInterface(ContractDefinition const& _contractDef);
/// Get the User documentation of the contract /// Get the User documentation of the contract
/// @param _contractDef The contract definition /// @param _contractDef The contract definition
/// @return A string with the json representation of the contract's user documentation /// @return A string with the json representation of the contract's user documentation

View File

@ -32,9 +32,9 @@ using namespace solidity;
StackVariable::StackVariable(CompilerContext& _compilerContext, Declaration const& _declaration): StackVariable::StackVariable(CompilerContext& _compilerContext, Declaration const& _declaration):
LValue(_compilerContext, *_declaration.getType()), LValue(_compilerContext, *_declaration.type()),
m_baseStackOffset(m_context.getBaseStackOffsetOfVariable(_declaration)), m_baseStackOffset(m_context.baseStackOffsetOfVariable(_declaration)),
m_size(m_dataType.getSizeOnStack()) m_size(m_dataType.sizeOnStack())
{ {
} }
@ -98,12 +98,12 @@ void MemoryItem::storeValue(Type const& _sourceType, SourceLocation const&, bool
if (m_dataType.isValueType()) if (m_dataType.isValueType())
{ {
solAssert(_sourceType.isValueType(), ""); solAssert(_sourceType.isValueType(), "");
utils.moveIntoStack(_sourceType.getSizeOnStack()); utils.moveIntoStack(_sourceType.sizeOnStack());
utils.convertType(_sourceType, m_dataType, true); utils.convertType(_sourceType, m_dataType, true);
if (!_move) if (!_move)
{ {
utils.moveToStackTop(m_dataType.getSizeOnStack()); utils.moveToStackTop(m_dataType.sizeOnStack());
utils.copyToStackTop(2, m_dataType.getSizeOnStack()); utils.copyToStackTop(2, m_dataType.sizeOnStack());
} }
utils.storeInMemoryDynamic(m_dataType, m_padded); utils.storeInMemoryDynamic(m_dataType, m_padded);
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
@ -112,7 +112,7 @@ void MemoryItem::storeValue(Type const& _sourceType, SourceLocation const&, bool
{ {
solAssert(_sourceType == m_dataType, "Conversion not implemented for assignment to memory."); solAssert(_sourceType == m_dataType, "Conversion not implemented for assignment to memory.");
solAssert(m_dataType.getSizeOnStack() == 1, ""); solAssert(m_dataType.sizeOnStack() == 1, "");
if (!_move) if (!_move)
m_context << eth::Instruction::DUP2 << eth::Instruction::SWAP1; m_context << eth::Instruction::DUP2 << eth::Instruction::SWAP1;
// stack: [value] value lvalue // stack: [value] value lvalue
@ -132,9 +132,9 @@ void MemoryItem::setToZero(SourceLocation const&, bool _removeReference) const
} }
StorageItem::StorageItem(CompilerContext& _compilerContext, Declaration const& _declaration): StorageItem::StorageItem(CompilerContext& _compilerContext, Declaration const& _declaration):
StorageItem(_compilerContext, *_declaration.getType()) StorageItem(_compilerContext, *_declaration.type())
{ {
auto const& location = m_context.getStorageLocationOfVariable(_declaration); auto const& location = m_context.storageLocationOfVariable(_declaration);
m_context << location.first << u256(location.second); m_context << location.first << u256(location.second);
} }
@ -143,8 +143,8 @@ StorageItem::StorageItem(CompilerContext& _compilerContext, Type const& _type):
{ {
if (m_dataType.isValueType()) if (m_dataType.isValueType())
{ {
solAssert(m_dataType.getStorageSize() == m_dataType.getSizeOnStack(), ""); solAssert(m_dataType.storageSize() == m_dataType.sizeOnStack(), "");
solAssert(m_dataType.getStorageSize() == 1, "Invalid storage size."); solAssert(m_dataType.storageSize() == 1, "Invalid storage size.");
} }
} }
@ -153,7 +153,7 @@ void StorageItem::retrieveValue(SourceLocation const&, bool _remove) const
// stack: storage_key storage_offset // stack: storage_key storage_offset
if (!m_dataType.isValueType()) if (!m_dataType.isValueType())
{ {
solAssert(m_dataType.getSizeOnStack() == 1, "Invalid storage ref size."); solAssert(m_dataType.sizeOnStack() == 1, "Invalid storage ref size.");
if (_remove) if (_remove)
m_context << eth::Instruction::POP; // remove byte offset m_context << eth::Instruction::POP; // remove byte offset
else else
@ -162,22 +162,22 @@ void StorageItem::retrieveValue(SourceLocation const&, bool _remove) const
} }
if (!_remove) if (!_remove)
CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack()); CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack());
if (m_dataType.getStorageBytes() == 32) if (m_dataType.storageBytes() == 32)
m_context << eth::Instruction::POP << eth::Instruction::SLOAD; m_context << eth::Instruction::POP << eth::Instruction::SLOAD;
else else
{ {
m_context m_context
<< eth::Instruction::SWAP1 << eth::Instruction::SLOAD << eth::Instruction::SWAP1 << eth::Instruction::SWAP1 << eth::Instruction::SLOAD << eth::Instruction::SWAP1
<< u256(0x100) << eth::Instruction::EXP << eth::Instruction::SWAP1 << eth::Instruction::DIV; << u256(0x100) << eth::Instruction::EXP << eth::Instruction::SWAP1 << eth::Instruction::DIV;
if (m_dataType.getCategory() == Type::Category::FixedBytes) if (m_dataType.category() == Type::Category::FixedBytes)
m_context << (u256(0x1) << (256 - 8 * m_dataType.getStorageBytes())) << eth::Instruction::MUL; m_context << (u256(0x1) << (256 - 8 * m_dataType.storageBytes())) << eth::Instruction::MUL;
else if ( else if (
m_dataType.getCategory() == Type::Category::Integer && m_dataType.category() == Type::Category::Integer &&
dynamic_cast<IntegerType const&>(m_dataType).isSigned() dynamic_cast<IntegerType const&>(m_dataType).isSigned()
) )
m_context << u256(m_dataType.getStorageBytes() - 1) << eth::Instruction::SIGNEXTEND; m_context << u256(m_dataType.storageBytes() - 1) << eth::Instruction::SIGNEXTEND;
else else
m_context << ((u256(0x1) << (8 * m_dataType.getStorageBytes())) - 1) << eth::Instruction::AND; m_context << ((u256(0x1) << (8 * m_dataType.storageBytes())) - 1) << eth::Instruction::AND;
} }
} }
@ -187,9 +187,9 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
// stack: value storage_key storage_offset // stack: value storage_key storage_offset
if (m_dataType.isValueType()) if (m_dataType.isValueType())
{ {
solAssert(m_dataType.getStorageBytes() <= 32, "Invalid storage bytes size."); solAssert(m_dataType.storageBytes() <= 32, "Invalid storage bytes size.");
solAssert(m_dataType.getStorageBytes() > 0, "Invalid storage bytes size."); solAssert(m_dataType.storageBytes() > 0, "Invalid storage bytes size.");
if (m_dataType.getStorageBytes() == 32) if (m_dataType.storageBytes() == 32)
{ {
// offset should be zero // offset should be zero
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
@ -207,24 +207,24 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
// stack: value storege_ref multiplier old_full_value // stack: value storege_ref multiplier old_full_value
// clear bytes in old value // clear bytes in old value
m_context m_context
<< eth::Instruction::DUP2 << ((u256(1) << (8 * m_dataType.getStorageBytes())) - 1) << eth::Instruction::DUP2 << ((u256(1) << (8 * m_dataType.storageBytes())) - 1)
<< eth::Instruction::MUL; << eth::Instruction::MUL;
m_context << eth::Instruction::NOT << eth::Instruction::AND; m_context << eth::Instruction::NOT << eth::Instruction::AND;
// stack: value storage_ref multiplier cleared_value // stack: value storage_ref multiplier cleared_value
m_context m_context
<< eth::Instruction::SWAP1 << eth::Instruction::DUP4; << eth::Instruction::SWAP1 << eth::Instruction::DUP4;
// stack: value storage_ref cleared_value multiplier value // stack: value storage_ref cleared_value multiplier value
if (m_dataType.getCategory() == Type::Category::FixedBytes) if (m_dataType.category() == Type::Category::FixedBytes)
m_context m_context
<< (u256(0x1) << (256 - 8 * dynamic_cast<FixedBytesType const&>(m_dataType).numBytes())) << (u256(0x1) << (256 - 8 * dynamic_cast<FixedBytesType const&>(m_dataType).numBytes()))
<< eth::Instruction::SWAP1 << eth::Instruction::DIV; << eth::Instruction::SWAP1 << eth::Instruction::DIV;
else if ( else if (
m_dataType.getCategory() == Type::Category::Integer && m_dataType.category() == Type::Category::Integer &&
dynamic_cast<IntegerType const&>(m_dataType).isSigned() dynamic_cast<IntegerType const&>(m_dataType).isSigned()
) )
// remove the higher order bits // remove the higher order bits
m_context m_context
<< (u256(1) << (8 * (32 - m_dataType.getStorageBytes()))) << (u256(1) << (8 * (32 - m_dataType.storageBytes())))
<< eth::Instruction::SWAP1 << eth::Instruction::SWAP1
<< eth::Instruction::DUP2 << eth::Instruction::DUP2
<< eth::Instruction::MUL << eth::Instruction::MUL
@ -239,9 +239,9 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
else else
{ {
solAssert( solAssert(
_sourceType.getCategory() == m_dataType.getCategory(), _sourceType.category() == m_dataType.category(),
"Wrong type conversation for assignment."); "Wrong type conversation for assignment.");
if (m_dataType.getCategory() == Type::Category::Array) if (m_dataType.category() == Type::Category::Array)
{ {
m_context << eth::Instruction::POP; // remove byte offset m_context << eth::Instruction::POP; // remove byte offset
ArrayUtils(m_context).copyArrayToStorage( ArrayUtils(m_context).copyArrayToStorage(
@ -250,7 +250,7 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
if (_move) if (_move)
m_context << eth::Instruction::POP; m_context << eth::Instruction::POP;
} }
else if (m_dataType.getCategory() == Type::Category::Struct) else if (m_dataType.category() == Type::Category::Struct)
{ {
// stack layout: source_ref target_ref target_offset // stack layout: source_ref target_ref target_offset
// note that we have structs, so offset should be zero and are ignored // note that we have structs, so offset should be zero and are ignored
@ -262,17 +262,17 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
"Struct assignment with conversion." "Struct assignment with conversion."
); );
solAssert(sourceType.location() != DataLocation::CallData, "Structs in calldata not supported."); solAssert(sourceType.location() != DataLocation::CallData, "Structs in calldata not supported.");
for (auto const& member: structType.getMembers()) for (auto const& member: structType.members())
{ {
// assign each member that is not a mapping // assign each member that is not a mapping
TypePointer const& memberType = member.type; TypePointer const& memberType = member.type;
if (memberType->getCategory() == Type::Category::Mapping) if (memberType->category() == Type::Category::Mapping)
continue; continue;
TypePointer sourceMemberType = sourceType.getMemberType(member.name); TypePointer sourceMemberType = sourceType.memberType(member.name);
if (sourceType.location() == DataLocation::Storage) if (sourceType.location() == DataLocation::Storage)
{ {
// stack layout: source_ref target_ref // stack layout: source_ref target_ref
pair<u256, unsigned> const& offsets = sourceType.getStorageOffsetsOfMember(member.name); pair<u256, unsigned> const& offsets = sourceType.storageOffsetsOfMember(member.name);
m_context << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD; m_context << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD;
m_context << u256(offsets.second); m_context << u256(offsets.second);
// stack: source_ref target_ref source_member_ref source_member_off // stack: source_ref target_ref source_member_ref source_member_off
@ -283,21 +283,21 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
{ {
solAssert(sourceType.location() == DataLocation::Memory, ""); solAssert(sourceType.location() == DataLocation::Memory, "");
// stack layout: source_ref target_ref // stack layout: source_ref target_ref
TypePointer sourceMemberType = sourceType.getMemberType(member.name); TypePointer sourceMemberType = sourceType.memberType(member.name);
m_context << sourceType.memoryOffsetOfMember(member.name); m_context << sourceType.memoryOffsetOfMember(member.name);
m_context << eth::Instruction::DUP3 << eth::Instruction::ADD; m_context << eth::Instruction::DUP3 << eth::Instruction::ADD;
MemoryItem(m_context, *sourceMemberType).retrieveValue(_location, true); MemoryItem(m_context, *sourceMemberType).retrieveValue(_location, true);
// stack layout: source_ref target_ref source_value... // stack layout: source_ref target_ref source_value...
} }
unsigned stackSize = sourceMemberType->getSizeOnStack(); unsigned stackSize = sourceMemberType->sizeOnStack();
pair<u256, unsigned> const& offsets = structType.getStorageOffsetsOfMember(member.name); pair<u256, unsigned> const& offsets = structType.storageOffsetsOfMember(member.name);
m_context << eth::dupInstruction(1 + stackSize) << offsets.first << eth::Instruction::ADD; m_context << eth::dupInstruction(1 + stackSize) << offsets.first << eth::Instruction::ADD;
m_context << u256(offsets.second); m_context << u256(offsets.second);
// stack: source_ref target_ref target_off source_value... target_member_ref target_member_byte_off // stack: source_ref target_ref target_off source_value... target_member_ref target_member_byte_off
StorageItem(m_context, *memberType).storeValue(*sourceMemberType, _location, true); StorageItem(m_context, *memberType).storeValue(*sourceMemberType, _location, true);
} }
// stack layout: source_ref target_ref // stack layout: source_ref target_ref
solAssert(sourceType.getSizeOnStack() == 1, "Unexpected source size."); solAssert(sourceType.sizeOnStack() == 1, "Unexpected source size.");
if (_move) if (_move)
utils.popStackSlots(2); utils.popStackSlots(2);
else else
@ -313,25 +313,25 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
void StorageItem::setToZero(SourceLocation const&, bool _removeReference) const void StorageItem::setToZero(SourceLocation const&, bool _removeReference) const
{ {
if (m_dataType.getCategory() == Type::Category::Array) if (m_dataType.category() == Type::Category::Array)
{ {
if (!_removeReference) if (!_removeReference)
CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack()); CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack());
ArrayUtils(m_context).clearArray(dynamic_cast<ArrayType const&>(m_dataType)); ArrayUtils(m_context).clearArray(dynamic_cast<ArrayType const&>(m_dataType));
} }
else if (m_dataType.getCategory() == Type::Category::Struct) else if (m_dataType.category() == Type::Category::Struct)
{ {
// stack layout: storage_key storage_offset // stack layout: storage_key storage_offset
// @todo this can be improved: use StorageItem for non-value types, and just store 0 in // @todo this can be improved: use StorageItem for non-value types, and just store 0 in
// all slots that contain value types later. // all slots that contain value types later.
auto const& structType = dynamic_cast<StructType const&>(m_dataType); auto const& structType = dynamic_cast<StructType const&>(m_dataType);
for (auto const& member: structType.getMembers()) for (auto const& member: structType.members())
{ {
// zero each member that is not a mapping // zero each member that is not a mapping
TypePointer const& memberType = member.type; TypePointer const& memberType = member.type;
if (memberType->getCategory() == Type::Category::Mapping) if (memberType->category() == Type::Category::Mapping)
continue; continue;
pair<u256, unsigned> const& offsets = structType.getStorageOffsetsOfMember(member.name); pair<u256, unsigned> const& offsets = structType.storageOffsetsOfMember(member.name);
m_context m_context
<< offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD << offsets.first << eth::Instruction::DUP3 << eth::Instruction::ADD
<< u256(offsets.second); << u256(offsets.second);
@ -345,7 +345,7 @@ void StorageItem::setToZero(SourceLocation const&, bool _removeReference) const
solAssert(m_dataType.isValueType(), "Clearing of unsupported type requested: " + m_dataType.toString()); solAssert(m_dataType.isValueType(), "Clearing of unsupported type requested: " + m_dataType.toString());
if (!_removeReference) if (!_removeReference)
CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack()); CompilerUtils(m_context).copyToStackTop(sizeOnStack(), sizeOnStack());
if (m_dataType.getStorageBytes() == 32) if (m_dataType.storageBytes() == 32)
{ {
// offset should be zero // offset should be zero
m_context m_context
@ -361,7 +361,7 @@ void StorageItem::setToZero(SourceLocation const&, bool _removeReference) const
// stack: storege_ref multiplier old_full_value // stack: storege_ref multiplier old_full_value
// clear bytes in old value // clear bytes in old value
m_context m_context
<< eth::Instruction::SWAP1 << ((u256(1) << (8 * m_dataType.getStorageBytes())) - 1) << eth::Instruction::SWAP1 << ((u256(1) << (8 * m_dataType.storageBytes())) - 1)
<< eth::Instruction::MUL; << eth::Instruction::MUL;
m_context << eth::Instruction::NOT << eth::Instruction::AND; m_context << eth::Instruction::NOT << eth::Instruction::AND;
// stack: storage_ref cleared_value // stack: storage_ref cleared_value
@ -427,7 +427,7 @@ void StorageByteArrayElement::setToZero(SourceLocation const&, bool _removeRefer
} }
StorageArrayLength::StorageArrayLength(CompilerContext& _compilerContext, const ArrayType& _arrayType): StorageArrayLength::StorageArrayLength(CompilerContext& _compilerContext, const ArrayType& _arrayType):
LValue(_compilerContext, *_arrayType.getMemberType("length")), LValue(_compilerContext, *_arrayType.memberType("length")),
m_arrayType(_arrayType) m_arrayType(_arrayType)
{ {
solAssert(m_arrayType.isDynamicallySized(), ""); solAssert(m_arrayType.isDynamicallySized(), "");

View File

@ -91,7 +91,7 @@ public:
) const override; ) const override;
private: private:
/// Base stack offset (@see CompilerContext::getBaseStackOffsetOfVariable) of the local variable. /// Base stack offset (@see CompilerContext::baseStackOffsetOfVariable) of the local variable.
unsigned m_baseStackOffset; unsigned m_baseStackOffset;
/// Number of stack elements occupied by the value (not the reference). /// Number of stack elements occupied by the value (not the reference).
unsigned m_size; unsigned m_size;

View File

@ -47,58 +47,60 @@ void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
{ {
m_currentScope = &m_scopes[nullptr]; m_currentScope = &m_scopes[nullptr];
for (ASTPointer<InheritanceSpecifier> const& baseContract: _contract.getBaseContracts()) for (ASTPointer<InheritanceSpecifier> const& baseContract: _contract.baseContracts())
ReferencesResolver resolver(*baseContract, *this, &_contract, nullptr); ReferencesResolver resolver(*baseContract, *this, &_contract, nullptr);
m_currentScope = &m_scopes[&_contract]; m_currentScope = &m_scopes[&_contract];
linearizeBaseContracts(_contract); linearizeBaseContracts(_contract);
std::vector<ContractDefinition const*> properBases( std::vector<ContractDefinition const*> properBases(
++_contract.getLinearizedBaseContracts().begin(), ++_contract.linearizedBaseContracts().begin(),
_contract.getLinearizedBaseContracts().end() _contract.linearizedBaseContracts().end()
); );
for (ContractDefinition const* base: properBases) for (ContractDefinition const* base: properBases)
importInheritedScope(*base); importInheritedScope(*base);
for (ASTPointer<StructDefinition> const& structDef: _contract.getDefinedStructs()) for (ASTPointer<StructDefinition> const& structDef: _contract.definedStructs())
ReferencesResolver resolver(*structDef, *this, &_contract, nullptr); ReferencesResolver resolver(*structDef, *this, &_contract, nullptr);
for (ASTPointer<EnumDefinition> const& enumDef: _contract.getDefinedEnums()) for (ASTPointer<EnumDefinition> const& enumDef: _contract.definedEnums())
ReferencesResolver resolver(*enumDef, *this, &_contract, nullptr); ReferencesResolver resolver(*enumDef, *this, &_contract, nullptr);
for (ASTPointer<VariableDeclaration> const& variable: _contract.getStateVariables()) for (ASTPointer<VariableDeclaration> const& variable: _contract.stateVariables())
ReferencesResolver resolver(*variable, *this, &_contract, nullptr); ReferencesResolver resolver(*variable, *this, &_contract, nullptr);
for (ASTPointer<EventDefinition> const& event: _contract.getEvents()) for (ASTPointer<EventDefinition> const& event: _contract.events())
ReferencesResolver resolver(*event, *this, &_contract, nullptr); ReferencesResolver resolver(*event, *this, &_contract, nullptr);
// these can contain code, only resolve parameters for now // these can contain code, only resolve parameters for now
for (ASTPointer<ModifierDefinition> const& modifier: _contract.getFunctionModifiers()) for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers())
{ {
m_currentScope = &m_scopes[modifier.get()]; m_currentScope = &m_scopes[modifier.get()];
ReferencesResolver resolver(*modifier, *this, &_contract, nullptr); ReferencesResolver resolver(*modifier, *this, &_contract, nullptr);
} }
for (ASTPointer<FunctionDefinition> const& function: _contract.getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
{ {
m_currentScope = &m_scopes[function.get()]; m_currentScope = &m_scopes[function.get()];
ReferencesResolver referencesResolver(*function, *this, &_contract, ReferencesResolver referencesResolver(
function->getReturnParameterList().get()); *function, *this, &_contract,
function->returnParameterList().get()
);
} }
m_currentScope = &m_scopes[&_contract]; m_currentScope = &m_scopes[&_contract];
// now resolve references inside the code // now resolve references inside the code
for (ASTPointer<ModifierDefinition> const& modifier: _contract.getFunctionModifiers()) for (ASTPointer<ModifierDefinition> const& modifier: _contract.functionModifiers())
{ {
m_currentScope = &m_scopes[modifier.get()]; m_currentScope = &m_scopes[modifier.get()];
ReferencesResolver resolver(*modifier, *this, &_contract, nullptr, true); ReferencesResolver resolver(*modifier, *this, &_contract, nullptr, true);
} }
for (ASTPointer<FunctionDefinition> const& function: _contract.getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.definedFunctions())
{ {
m_currentScope = &m_scopes[function.get()]; m_currentScope = &m_scopes[function.get()];
ReferencesResolver referencesResolver( ReferencesResolver referencesResolver(
*function, *function,
*this, *this,
&_contract, &_contract,
function->getReturnParameterList().get(), function->returnParameterList().get(),
true true
); );
} }
@ -106,7 +108,7 @@ void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
void NameAndTypeResolver::checkTypeRequirements(ContractDefinition& _contract) void NameAndTypeResolver::checkTypeRequirements(ContractDefinition& _contract)
{ {
for (ASTPointer<StructDefinition> const& structDef: _contract.getDefinedStructs()) for (ASTPointer<StructDefinition> const& structDef: _contract.definedStructs())
structDef->checkValidityOfMembers(); structDef->checkValidityOfMembers();
_contract.checkTypeRequirements(); _contract.checkTypeRequirements();
} }
@ -114,7 +116,7 @@ void NameAndTypeResolver::checkTypeRequirements(ContractDefinition& _contract)
void NameAndTypeResolver::updateDeclaration(Declaration const& _declaration) void NameAndTypeResolver::updateDeclaration(Declaration const& _declaration)
{ {
m_scopes[nullptr].registerDeclaration(_declaration, false, true); m_scopes[nullptr].registerDeclaration(_declaration, false, true);
solAssert(_declaration.getScope() == nullptr, "Updated declaration outside global scope."); solAssert(_declaration.scope() == nullptr, "Updated declaration outside global scope.");
} }
vector<Declaration const*> NameAndTypeResolver::resolveName(ASTString const& _name, Declaration const* _scope) const vector<Declaration const*> NameAndTypeResolver::resolveName(ASTString const& _name, Declaration const* _scope) const
@ -125,7 +127,7 @@ vector<Declaration const*> NameAndTypeResolver::resolveName(ASTString const& _na
return iterator->second.resolveName(_name, false); return iterator->second.resolveName(_name, false);
} }
vector<Declaration const*> NameAndTypeResolver::getNameFromCurrentScope(ASTString const& _name, bool _recursive) vector<Declaration const*> NameAndTypeResolver::nameFromCurrentScope(ASTString const& _name, bool _recursive)
{ {
return m_currentScope->resolveName(_name, _recursive); return m_currentScope->resolveName(_name, _recursive);
} }
@ -144,11 +146,11 @@ vector<Declaration const*> NameAndTypeResolver::cleanedDeclarations(
// the declaration is functionDefinition while declarations > 1 // the declaration is functionDefinition while declarations > 1
FunctionDefinition const& functionDefinition = dynamic_cast<FunctionDefinition const&>(**it); FunctionDefinition const& functionDefinition = dynamic_cast<FunctionDefinition const&>(**it);
FunctionType functionType(functionDefinition); FunctionType functionType(functionDefinition);
for (auto parameter: functionType.getParameterTypes() + functionType.getReturnParameterTypes()) for (auto parameter: functionType.parameterTypes() + functionType.returnParameterTypes())
if (!parameter) if (!parameter)
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
DeclarationError() << DeclarationError() <<
errinfo_sourceLocation(_identifier.getLocation()) << errinfo_sourceLocation(_identifier.location()) <<
errinfo_comment("Function type can not be used in this context") errinfo_comment("Function type can not be used in this context")
); );
if (uniqueFunctions.end() == find_if( if (uniqueFunctions.end() == find_if(
@ -169,10 +171,10 @@ void NameAndTypeResolver::importInheritedScope(ContractDefinition const& _base)
{ {
auto iterator = m_scopes.find(&_base); auto iterator = m_scopes.find(&_base);
solAssert(iterator != end(m_scopes), ""); solAssert(iterator != end(m_scopes), "");
for (auto const& nameAndDeclaration: iterator->second.getDeclarations()) for (auto const& nameAndDeclaration: iterator->second.declarations())
for (auto const& declaration: nameAndDeclaration.second) for (auto const& declaration: nameAndDeclaration.second)
// Import if it was declared in the base, is not the constructor and is visible in derived classes // Import if it was declared in the base, is not the constructor and is visible in derived classes
if (declaration->getScope() == &_base && declaration->isVisibleInDerivedContracts()) if (declaration->scope() == &_base && declaration->isVisibleInDerivedContracts())
m_currentScope->registerDeclaration(*declaration); m_currentScope->registerDeclaration(*declaration);
} }
@ -181,16 +183,16 @@ void NameAndTypeResolver::linearizeBaseContracts(ContractDefinition& _contract)
// order in the lists is from derived to base // order in the lists is from derived to base
// list of lists to linearize, the last element is the list of direct bases // list of lists to linearize, the last element is the list of direct bases
list<list<ContractDefinition const*>> input(1, {}); list<list<ContractDefinition const*>> input(1, {});
for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: _contract.getBaseContracts()) for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: _contract.baseContracts())
{ {
ASTPointer<Identifier> baseName = baseSpecifier->getName(); ASTPointer<Identifier> baseName = baseSpecifier->name();
auto base = dynamic_cast<ContractDefinition const*>(&baseName->getReferencedDeclaration()); auto base = dynamic_cast<ContractDefinition const*>(&baseName->referencedDeclaration());
if (!base) if (!base)
BOOST_THROW_EXCEPTION(baseName->createTypeError("Contract expected.")); BOOST_THROW_EXCEPTION(baseName->createTypeError("Contract expected."));
// "push_front" has the effect that bases mentioned later can overwrite members of bases // "push_front" has the effect that bases mentioned later can overwrite members of bases
// mentioned earlier // mentioned earlier
input.back().push_front(base); input.back().push_front(base);
vector<ContractDefinition const*> const& basesBases = base->getLinearizedBaseContracts(); vector<ContractDefinition const*> const& basesBases = base->linearizedBaseContracts();
if (basesBases.empty()) if (basesBases.empty())
BOOST_THROW_EXCEPTION(baseName->createTypeError("Definition of base has to precede definition of derived contract")); BOOST_THROW_EXCEPTION(baseName->createTypeError("Definition of base has to precede definition of derived contract"));
input.push_front(list<ContractDefinition const*>(basesBases.begin(), basesBases.end())); input.push_front(list<ContractDefinition const*>(basesBases.begin(), basesBases.end()));
@ -330,7 +332,7 @@ void DeclarationRegistrationHelper::endVisit(VariableDeclarationStatement& _vari
// Register the local variables with the function // Register the local variables with the function
// This does not fit here perfectly, but it saves us another AST visit. // This does not fit here perfectly, but it saves us another AST visit.
solAssert(m_currentFunction, "Variable declaration without function."); solAssert(m_currentFunction, "Variable declaration without function.");
m_currentFunction->addLocalVariable(_variableDeclarationStatement.getDeclaration()); m_currentFunction->addLocalVariable(_variableDeclarationStatement.declaration());
} }
bool DeclarationRegistrationHelper::visit(VariableDeclaration& _declaration) bool DeclarationRegistrationHelper::visit(VariableDeclaration& _declaration)
@ -362,7 +364,7 @@ void DeclarationRegistrationHelper::enterNewSubScope(Declaration const& _declara
void DeclarationRegistrationHelper::closeCurrentScope() void DeclarationRegistrationHelper::closeCurrentScope()
{ {
solAssert(m_currentScope, "Closed non-existing scope."); solAssert(m_currentScope, "Closed non-existing scope.");
m_currentScope = m_scopes[m_currentScope].getEnclosingDeclaration(); m_currentScope = m_scopes[m_currentScope].enclosingDeclaration();
} }
void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaration, bool _opensScope) void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaration, bool _opensScope)
@ -374,15 +376,15 @@ void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaratio
Declaration const* conflictingDeclaration = m_scopes[m_currentScope].conflictingDeclaration(_declaration); Declaration const* conflictingDeclaration = m_scopes[m_currentScope].conflictingDeclaration(_declaration);
solAssert(conflictingDeclaration, ""); solAssert(conflictingDeclaration, "");
if (_declaration.getLocation().start < conflictingDeclaration->getLocation().start) if (_declaration.location().start < conflictingDeclaration->location().start)
{ {
firstDeclarationLocation = _declaration.getLocation(); firstDeclarationLocation = _declaration.location();
secondDeclarationLocation = conflictingDeclaration->getLocation(); secondDeclarationLocation = conflictingDeclaration->location();
} }
else else
{ {
firstDeclarationLocation = conflictingDeclaration->getLocation(); firstDeclarationLocation = conflictingDeclaration->location();
secondDeclarationLocation = _declaration.getLocation(); secondDeclarationLocation = _declaration.location();
} }
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
@ -421,9 +423,9 @@ void ReferencesResolver::endVisit(VariableDeclaration& _variable)
{ {
// endVisit because the internal type needs resolving if it is a user defined type // endVisit because the internal type needs resolving if it is a user defined type
// or mapping // or mapping
if (_variable.getTypeName()) if (_variable.typeName())
{ {
TypePointer type = _variable.getTypeName()->toType(); TypePointer type = _variable.typeName()->toType();
using Location = VariableDeclaration::Location; using Location = VariableDeclaration::Location;
Location loc = _variable.referenceLocation(); Location loc = _variable.referenceLocation();
// References are forced to calldata for external function parameters (not return) // References are forced to calldata for external function parameters (not return)
@ -441,7 +443,7 @@ void ReferencesResolver::endVisit(VariableDeclaration& _variable)
)); ));
type = ref->copyForLocation(DataLocation::CallData, true); type = ref->copyForLocation(DataLocation::CallData, true);
} }
else if (_variable.isCallableParameter() && _variable.getScope()->isPublic()) else if (_variable.isCallableParameter() && _variable.scope()->isPublic())
{ {
// force locations of public or external function (return) parameters to memory // force locations of public or external function (return) parameters to memory
if (loc == VariableDeclaration::Location::Storage) if (loc == VariableDeclaration::Location::Storage)
@ -471,8 +473,8 @@ void ReferencesResolver::endVisit(VariableDeclaration& _variable)
_variable.setType(type); _variable.setType(type);
if (!_variable.getType()) if (!_variable.type())
BOOST_THROW_EXCEPTION(_variable.getTypeName()->createTypeError("Invalid type name")); BOOST_THROW_EXCEPTION(_variable.typeName()->createTypeError("Invalid type name"));
} }
else if (!m_allowLazyTypes) else if (!m_allowLazyTypes)
BOOST_THROW_EXCEPTION(_variable.createTypeError("Explicit type needed.")); BOOST_THROW_EXCEPTION(_variable.createTypeError("Explicit type needed."));
@ -492,17 +494,17 @@ bool ReferencesResolver::visit(Mapping&)
bool ReferencesResolver::visit(UserDefinedTypeName& _typeName) bool ReferencesResolver::visit(UserDefinedTypeName& _typeName)
{ {
auto declarations = m_resolver.getNameFromCurrentScope(_typeName.getName()); auto declarations = m_resolver.nameFromCurrentScope(_typeName.name());
if (declarations.empty()) if (declarations.empty())
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
DeclarationError() << DeclarationError() <<
errinfo_sourceLocation(_typeName.getLocation()) << errinfo_sourceLocation(_typeName.location()) <<
errinfo_comment("Undeclared identifier.") errinfo_comment("Undeclared identifier.")
); );
else if (declarations.size() > 1) else if (declarations.size() > 1)
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
DeclarationError() << DeclarationError() <<
errinfo_sourceLocation(_typeName.getLocation()) << errinfo_sourceLocation(_typeName.location()) <<
errinfo_comment("Duplicate identifier.") errinfo_comment("Duplicate identifier.")
); );
else else
@ -512,11 +514,11 @@ bool ReferencesResolver::visit(UserDefinedTypeName& _typeName)
bool ReferencesResolver::visit(Identifier& _identifier) bool ReferencesResolver::visit(Identifier& _identifier)
{ {
auto declarations = m_resolver.getNameFromCurrentScope(_identifier.getName()); auto declarations = m_resolver.nameFromCurrentScope(_identifier.name());
if (declarations.empty()) if (declarations.empty())
BOOST_THROW_EXCEPTION( BOOST_THROW_EXCEPTION(
DeclarationError() << DeclarationError() <<
errinfo_sourceLocation(_identifier.getLocation()) << errinfo_sourceLocation(_identifier.location()) <<
errinfo_comment("Undeclared identifier.") errinfo_comment("Undeclared identifier.")
); );
else if (declarations.size() == 1) else if (declarations.size() == 1)

View File

@ -60,7 +60,7 @@ public:
/// Resolves a name in the "current" scope. Should only be called during the initial /// Resolves a name in the "current" scope. Should only be called during the initial
/// resolving phase. /// resolving phase.
std::vector<Declaration const*> getNameFromCurrentScope(ASTString const& _name, bool _recursive = true); std::vector<Declaration const*> nameFromCurrentScope(ASTString const& _name, bool _recursive = true);
/// returns the vector of declarations without repetitions /// returns the vector of declarations without repetitions
static std::vector<Declaration const*> cleanedDeclarations( static std::vector<Declaration const*> cleanedDeclarations(

View File

@ -41,15 +41,15 @@ class Parser::ASTNodeFactory
{ {
public: public:
ASTNodeFactory(Parser const& _parser): ASTNodeFactory(Parser const& _parser):
m_parser(_parser), m_location(_parser.getPosition(), -1, _parser.getSourceName()) {} m_parser(_parser), m_location(_parser.position(), -1, _parser.sourceName()) {}
ASTNodeFactory(Parser const& _parser, ASTPointer<ASTNode> const& _childNode): ASTNodeFactory(Parser const& _parser, ASTPointer<ASTNode> const& _childNode):
m_parser(_parser), m_location(_childNode->getLocation()) {} m_parser(_parser), m_location(_childNode->location()) {}
void markEndPosition() { m_location.end = m_parser.getEndPosition(); } void markEndPosition() { m_location.end = m_parser.endPosition(); }
void setLocation(SourceLocation const& _location) { m_location = _location; } void setLocation(SourceLocation const& _location) { m_location = _location; }
void setLocationEmpty() { m_location.end = m_location.start; } void setLocationEmpty() { m_location.end = m_location.start; }
/// Set the end position to the one of the given node. /// Set the end position to the one of the given node.
void setEndPositionFromNode(ASTPointer<ASTNode> const& _node) { m_location.end = _node->getLocation().end; } void setEndPositionFromNode(ASTPointer<ASTNode> const& _node) { m_location.end = _node->location().end; }
template <class NodeType, typename... Args> template <class NodeType, typename... Args>
ASTPointer<NodeType> createNode(Args&& ... _args) ASTPointer<NodeType> createNode(Args&& ... _args)
@ -69,9 +69,9 @@ ASTPointer<SourceUnit> Parser::parse(shared_ptr<Scanner> const& _scanner)
m_scanner = _scanner; m_scanner = _scanner;
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
vector<ASTPointer<ASTNode>> nodes; vector<ASTPointer<ASTNode>> nodes;
while (_scanner->getCurrentToken() != Token::EOS) while (_scanner->currentToken() != Token::EOS)
{ {
switch (m_scanner->getCurrentToken()) switch (m_scanner->currentToken())
{ {
case Token::Import: case Token::Import:
nodes.push_back(parseImportDirective()); nodes.push_back(parseImportDirective());
@ -86,26 +86,26 @@ ASTPointer<SourceUnit> Parser::parse(shared_ptr<Scanner> const& _scanner)
return nodeFactory.createNode<SourceUnit>(nodes); return nodeFactory.createNode<SourceUnit>(nodes);
} }
std::shared_ptr<const string> const& Parser::getSourceName() const std::shared_ptr<const string> const& Parser::sourceName() const
{ {
return m_scanner->getSourceName(); return m_scanner->sourceName();
} }
int Parser::getPosition() const int Parser::position() const
{ {
return m_scanner->getCurrentLocation().start; return m_scanner->currentLocation().start;
} }
int Parser::getEndPosition() const int Parser::endPosition() const
{ {
return m_scanner->getCurrentLocation().end; return m_scanner->currentLocation().end;
} }
ASTPointer<ImportDirective> Parser::parseImportDirective() ASTPointer<ImportDirective> Parser::parseImportDirective()
{ {
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
expectToken(Token::Import); expectToken(Token::Import);
if (m_scanner->getCurrentToken() != Token::StringLiteral) if (m_scanner->currentToken() != Token::StringLiteral)
BOOST_THROW_EXCEPTION(createParserError("Expected string literal (URL).")); BOOST_THROW_EXCEPTION(createParserError("Expected string literal (URL)."));
ASTPointer<ASTString> url = getLiteralAndAdvance(); ASTPointer<ASTString> url = getLiteralAndAdvance();
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
@ -117,8 +117,8 @@ ASTPointer<ContractDefinition> Parser::parseContractDefinition()
{ {
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
ASTPointer<ASTString> docString; ASTPointer<ASTString> docString;
if (m_scanner->getCurrentCommentLiteral() != "") if (m_scanner->currentCommentLiteral() != "")
docString = make_shared<ASTString>(m_scanner->getCurrentCommentLiteral()); docString = make_shared<ASTString>(m_scanner->currentCommentLiteral());
expectToken(Token::Contract); expectToken(Token::Contract);
ASTPointer<ASTString> name = expectIdentifierToken(); ASTPointer<ASTString> name = expectIdentifierToken();
vector<ASTPointer<InheritanceSpecifier>> baseContracts; vector<ASTPointer<InheritanceSpecifier>> baseContracts;
@ -128,27 +128,27 @@ ASTPointer<ContractDefinition> Parser::parseContractDefinition()
vector<ASTPointer<FunctionDefinition>> functions; vector<ASTPointer<FunctionDefinition>> functions;
vector<ASTPointer<ModifierDefinition>> modifiers; vector<ASTPointer<ModifierDefinition>> modifiers;
vector<ASTPointer<EventDefinition>> events; vector<ASTPointer<EventDefinition>> events;
if (m_scanner->getCurrentToken() == Token::Is) if (m_scanner->currentToken() == Token::Is)
do do
{ {
m_scanner->next(); m_scanner->next();
baseContracts.push_back(parseInheritanceSpecifier()); baseContracts.push_back(parseInheritanceSpecifier());
} }
while (m_scanner->getCurrentToken() == Token::Comma); while (m_scanner->currentToken() == Token::Comma);
expectToken(Token::LBrace); expectToken(Token::LBrace);
while (true) while (true)
{ {
Token::Value currentToken = m_scanner->getCurrentToken(); Token::Value currentTokenValue= m_scanner->currentToken();
if (currentToken == Token::RBrace) if (currentTokenValue== Token::RBrace)
break; break;
else if (currentToken == Token::Function) else if (currentTokenValue== Token::Function)
functions.push_back(parseFunctionDefinition(name.get())); functions.push_back(parseFunctionDefinition(name.get()));
else if (currentToken == Token::Struct) else if (currentTokenValue== Token::Struct)
structs.push_back(parseStructDefinition()); structs.push_back(parseStructDefinition());
else if (currentToken == Token::Enum) else if (currentTokenValue== Token::Enum)
enums.push_back(parseEnumDefinition()); enums.push_back(parseEnumDefinition());
else if (currentToken == Token::Identifier || currentToken == Token::Mapping || else if (currentTokenValue== Token::Identifier || currentTokenValue== Token::Mapping ||
Token::isElementaryTypeName(currentToken)) Token::isElementaryTypeName(currentTokenValue))
{ {
VarDeclParserOptions options; VarDeclParserOptions options;
options.isStateVariable = true; options.isStateVariable = true;
@ -156,9 +156,9 @@ ASTPointer<ContractDefinition> Parser::parseContractDefinition()
stateVariables.push_back(parseVariableDeclaration(options)); stateVariables.push_back(parseVariableDeclaration(options));
expectToken(Token::Semicolon); expectToken(Token::Semicolon);
} }
else if (currentToken == Token::Modifier) else if (currentTokenValue== Token::Modifier)
modifiers.push_back(parseModifierDefinition()); modifiers.push_back(parseModifierDefinition());
else if (currentToken == Token::Event) else if (currentTokenValue== Token::Event)
events.push_back(parseEventDefinition()); events.push_back(parseEventDefinition());
else else
BOOST_THROW_EXCEPTION(createParserError("Function, variable, struct or modifier declaration expected.")); BOOST_THROW_EXCEPTION(createParserError("Function, variable, struct or modifier declaration expected."));
@ -183,7 +183,7 @@ ASTPointer<InheritanceSpecifier> Parser::parseInheritanceSpecifier()
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
ASTPointer<Identifier> name(parseIdentifier()); ASTPointer<Identifier> name(parseIdentifier());
vector<ASTPointer<Expression>> arguments; vector<ASTPointer<Expression>> arguments;
if (m_scanner->getCurrentToken() == Token::LParen) if (m_scanner->currentToken() == Token::LParen)
{ {
m_scanner->next(); m_scanner->next();
arguments = parseFunctionCallListArguments(); arguments = parseFunctionCallListArguments();
@ -216,12 +216,12 @@ ASTPointer<FunctionDefinition> Parser::parseFunctionDefinition(ASTString const*
{ {
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
ASTPointer<ASTString> docstring; ASTPointer<ASTString> docstring;
if (m_scanner->getCurrentCommentLiteral() != "") if (m_scanner->currentCommentLiteral() != "")
docstring = make_shared<ASTString>(m_scanner->getCurrentCommentLiteral()); docstring = make_shared<ASTString>(m_scanner->currentCommentLiteral());
expectToken(Token::Function); expectToken(Token::Function);
ASTPointer<ASTString> name; ASTPointer<ASTString> name;
if (m_scanner->getCurrentToken() == Token::LParen) if (m_scanner->currentToken() == Token::LParen)
name = make_shared<ASTString>(); // anonymous function name = make_shared<ASTString>(); // anonymous function
else else
name = expectIdentifierToken(); name = expectIdentifierToken();
@ -233,7 +233,7 @@ ASTPointer<FunctionDefinition> Parser::parseFunctionDefinition(ASTString const*
vector<ASTPointer<ModifierInvocation>> modifiers; vector<ASTPointer<ModifierInvocation>> modifiers;
while (true) while (true)
{ {
Token::Value token = m_scanner->getCurrentToken(); Token::Value token = m_scanner->currentToken();
if (token == Token::Const) if (token == Token::Const)
{ {
isDeclaredConst = true; isDeclaredConst = true;
@ -251,7 +251,7 @@ ASTPointer<FunctionDefinition> Parser::parseFunctionDefinition(ASTString const*
break; break;
} }
ASTPointer<ParameterList> returnParameters; ASTPointer<ParameterList> returnParameters;
if (m_scanner->getCurrentToken() == Token::Returns) if (m_scanner->currentToken() == Token::Returns)
{ {
bool const permitEmptyParameterList = false; bool const permitEmptyParameterList = false;
m_scanner->next(); m_scanner->next();
@ -261,7 +261,7 @@ ASTPointer<FunctionDefinition> Parser::parseFunctionDefinition(ASTString const*
returnParameters = createEmptyParameterList(); returnParameters = createEmptyParameterList();
ASTPointer<Block> block = ASTPointer<Block>(); ASTPointer<Block> block = ASTPointer<Block>();
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
if (m_scanner->getCurrentToken() != Token::Semicolon) if (m_scanner->currentToken() != Token::Semicolon)
{ {
block = parseBlock(); block = parseBlock();
nodeFactory.setEndPositionFromNode(block); nodeFactory.setEndPositionFromNode(block);
@ -281,7 +281,7 @@ ASTPointer<StructDefinition> Parser::parseStructDefinition()
ASTPointer<ASTString> name = expectIdentifierToken(); ASTPointer<ASTString> name = expectIdentifierToken();
vector<ASTPointer<VariableDeclaration>> members; vector<ASTPointer<VariableDeclaration>> members;
expectToken(Token::LBrace); expectToken(Token::LBrace);
while (m_scanner->getCurrentToken() != Token::RBrace) while (m_scanner->currentToken() != Token::RBrace)
{ {
members.push_back(parseVariableDeclaration()); members.push_back(parseVariableDeclaration());
expectToken(Token::Semicolon); expectToken(Token::Semicolon);
@ -306,13 +306,13 @@ ASTPointer<EnumDefinition> Parser::parseEnumDefinition()
vector<ASTPointer<EnumValue>> members; vector<ASTPointer<EnumValue>> members;
expectToken(Token::LBrace); expectToken(Token::LBrace);
while (m_scanner->getCurrentToken() != Token::RBrace) while (m_scanner->currentToken() != Token::RBrace)
{ {
members.push_back(parseEnumValue()); members.push_back(parseEnumValue());
if (m_scanner->getCurrentToken() == Token::RBrace) if (m_scanner->currentToken() == Token::RBrace)
break; break;
expectToken(Token::Comma); expectToken(Token::Comma);
if (m_scanner->getCurrentToken() != Token::Identifier) if (m_scanner->currentToken() != Token::Identifier)
BOOST_THROW_EXCEPTION(createParserError("Expected Identifier after ','")); BOOST_THROW_EXCEPTION(createParserError("Expected Identifier after ','"));
} }
@ -345,7 +345,7 @@ ASTPointer<VariableDeclaration> Parser::parseVariableDeclaration(
while (true) while (true)
{ {
Token::Value token = m_scanner->getCurrentToken(); Token::Value token = m_scanner->currentToken();
if (_options.isStateVariable && Token::isVariableVisibilitySpecifier(token)) if (_options.isStateVariable && Token::isVariableVisibilitySpecifier(token))
{ {
if (visibility != Declaration::Visibility::Default) if (visibility != Declaration::Visibility::Default)
@ -377,7 +377,7 @@ ASTPointer<VariableDeclaration> Parser::parseVariableDeclaration(
} }
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
if (_options.allowEmptyName && m_scanner->getCurrentToken() != Token::Identifier) if (_options.allowEmptyName && m_scanner->currentToken() != Token::Identifier)
{ {
identifier = make_shared<ASTString>(""); identifier = make_shared<ASTString>("");
solAssert(type != nullptr, ""); solAssert(type != nullptr, "");
@ -388,7 +388,7 @@ ASTPointer<VariableDeclaration> Parser::parseVariableDeclaration(
ASTPointer<Expression> value; ASTPointer<Expression> value;
if (_options.allowInitialValue) if (_options.allowInitialValue)
{ {
if (m_scanner->getCurrentToken() == Token::Assign) if (m_scanner->currentToken() == Token::Assign)
{ {
m_scanner->next(); m_scanner->next();
value = parseExpression(); value = parseExpression();
@ -414,13 +414,13 @@ ASTPointer<ModifierDefinition> Parser::parseModifierDefinition()
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
ASTPointer<ASTString> docstring; ASTPointer<ASTString> docstring;
if (m_scanner->getCurrentCommentLiteral() != "") if (m_scanner->currentCommentLiteral() != "")
docstring = make_shared<ASTString>(m_scanner->getCurrentCommentLiteral()); docstring = make_shared<ASTString>(m_scanner->currentCommentLiteral());
expectToken(Token::Modifier); expectToken(Token::Modifier);
ASTPointer<ASTString> name(expectIdentifierToken()); ASTPointer<ASTString> name(expectIdentifierToken());
ASTPointer<ParameterList> parameters; ASTPointer<ParameterList> parameters;
if (m_scanner->getCurrentToken() == Token::LParen) if (m_scanner->currentToken() == Token::LParen)
{ {
VarDeclParserOptions options; VarDeclParserOptions options;
options.allowIndexed = true; options.allowIndexed = true;
@ -438,13 +438,13 @@ ASTPointer<EventDefinition> Parser::parseEventDefinition()
{ {
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
ASTPointer<ASTString> docstring; ASTPointer<ASTString> docstring;
if (m_scanner->getCurrentCommentLiteral() != "") if (m_scanner->currentCommentLiteral() != "")
docstring = make_shared<ASTString>(m_scanner->getCurrentCommentLiteral()); docstring = make_shared<ASTString>(m_scanner->currentCommentLiteral());
expectToken(Token::Event); expectToken(Token::Event);
ASTPointer<ASTString> name(expectIdentifierToken()); ASTPointer<ASTString> name(expectIdentifierToken());
ASTPointer<ParameterList> parameters; ASTPointer<ParameterList> parameters;
if (m_scanner->getCurrentToken() == Token::LParen) if (m_scanner->currentToken() == Token::LParen)
{ {
VarDeclParserOptions options; VarDeclParserOptions options;
options.allowIndexed = true; options.allowIndexed = true;
@ -453,7 +453,7 @@ ASTPointer<EventDefinition> Parser::parseEventDefinition()
else else
parameters = createEmptyParameterList(); parameters = createEmptyParameterList();
bool anonymous = false; bool anonymous = false;
if (m_scanner->getCurrentToken() == Token::Anonymous) if (m_scanner->currentToken() == Token::Anonymous)
{ {
anonymous = true; anonymous = true;
m_scanner->next(); m_scanner->next();
@ -468,7 +468,7 @@ ASTPointer<ModifierInvocation> Parser::parseModifierInvocation()
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
ASTPointer<Identifier> name(parseIdentifier()); ASTPointer<Identifier> name(parseIdentifier());
vector<ASTPointer<Expression>> arguments; vector<ASTPointer<Expression>> arguments;
if (m_scanner->getCurrentToken() == Token::LParen) if (m_scanner->currentToken() == Token::LParen)
{ {
m_scanner->next(); m_scanner->next();
arguments = parseFunctionCallListArguments(); arguments = parseFunctionCallListArguments();
@ -491,7 +491,7 @@ ASTPointer<TypeName> Parser::parseTypeName(bool _allowVar)
{ {
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
ASTPointer<TypeName> type; ASTPointer<TypeName> type;
Token::Value token = m_scanner->getCurrentToken(); Token::Value token = m_scanner->currentToken();
if (Token::isElementaryTypeName(token)) if (Token::isElementaryTypeName(token))
{ {
type = ASTNodeFactory(*this).createNode<ElementaryTypeName>(token); type = ASTNodeFactory(*this).createNode<ElementaryTypeName>(token);
@ -516,11 +516,11 @@ ASTPointer<TypeName> Parser::parseTypeName(bool _allowVar)
if (type) if (type)
// Parse "[...]" postfixes for arrays. // Parse "[...]" postfixes for arrays.
while (m_scanner->getCurrentToken() == Token::LBrack) while (m_scanner->currentToken() == Token::LBrack)
{ {
m_scanner->next(); m_scanner->next();
ASTPointer<Expression> length; ASTPointer<Expression> length;
if (m_scanner->getCurrentToken() != Token::RBrack) if (m_scanner->currentToken() != Token::RBrack)
length = parseExpression(); length = parseExpression();
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
expectToken(Token::RBrack); expectToken(Token::RBrack);
@ -534,10 +534,10 @@ ASTPointer<Mapping> Parser::parseMapping()
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
expectToken(Token::Mapping); expectToken(Token::Mapping);
expectToken(Token::LParen); expectToken(Token::LParen);
if (!Token::isElementaryTypeName(m_scanner->getCurrentToken())) if (!Token::isElementaryTypeName(m_scanner->currentToken()))
BOOST_THROW_EXCEPTION(createParserError("Expected elementary type name for mapping key type")); BOOST_THROW_EXCEPTION(createParserError("Expected elementary type name for mapping key type"));
ASTPointer<ElementaryTypeName> keyType; ASTPointer<ElementaryTypeName> keyType;
keyType = ASTNodeFactory(*this).createNode<ElementaryTypeName>(m_scanner->getCurrentToken()); keyType = ASTNodeFactory(*this).createNode<ElementaryTypeName>(m_scanner->currentToken());
m_scanner->next(); m_scanner->next();
expectToken(Token::Arrow); expectToken(Token::Arrow);
bool const allowVar = false; bool const allowVar = false;
@ -557,10 +557,10 @@ ASTPointer<ParameterList> Parser::parseParameterList(
VarDeclParserOptions options(_options); VarDeclParserOptions options(_options);
options.allowEmptyName = true; options.allowEmptyName = true;
expectToken(Token::LParen); expectToken(Token::LParen);
if (!_allowEmpty || m_scanner->getCurrentToken() != Token::RParen) if (!_allowEmpty || m_scanner->currentToken() != Token::RParen)
{ {
parameters.push_back(parseVariableDeclaration(options)); parameters.push_back(parseVariableDeclaration(options));
while (m_scanner->getCurrentToken() != Token::RParen) while (m_scanner->currentToken() != Token::RParen)
{ {
expectToken(Token::Comma); expectToken(Token::Comma);
parameters.push_back(parseVariableDeclaration(options)); parameters.push_back(parseVariableDeclaration(options));
@ -576,7 +576,7 @@ ASTPointer<Block> Parser::parseBlock()
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
expectToken(Token::LBrace); expectToken(Token::LBrace);
vector<ASTPointer<Statement>> statements; vector<ASTPointer<Statement>> statements;
while (m_scanner->getCurrentToken() != Token::RBrace) while (m_scanner->currentToken() != Token::RBrace)
statements.push_back(parseStatement()); statements.push_back(parseStatement());
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
expectToken(Token::RBrace); expectToken(Token::RBrace);
@ -586,7 +586,7 @@ ASTPointer<Block> Parser::parseBlock()
ASTPointer<Statement> Parser::parseStatement() ASTPointer<Statement> Parser::parseStatement()
{ {
ASTPointer<Statement> statement; ASTPointer<Statement> statement;
switch (m_scanner->getCurrentToken()) switch (m_scanner->currentToken())
{ {
case Token::If: case Token::If:
return parseIfStatement(); return parseIfStatement();
@ -618,7 +618,7 @@ ASTPointer<Statement> Parser::parseStatement()
break; break;
} }
case Token::Identifier: case Token::Identifier:
if (m_insideModifier && m_scanner->getCurrentLiteral() == "_") if (m_insideModifier && m_scanner->currentLiteral() == "_")
{ {
statement = ASTNodeFactory(*this).createNode<PlaceholderStatement>(); statement = ASTNodeFactory(*this).createNode<PlaceholderStatement>();
m_scanner->next(); m_scanner->next();
@ -641,7 +641,7 @@ ASTPointer<IfStatement> Parser::parseIfStatement()
expectToken(Token::RParen); expectToken(Token::RParen);
ASTPointer<Statement> trueBody = parseStatement(); ASTPointer<Statement> trueBody = parseStatement();
ASTPointer<Statement> falseBody; ASTPointer<Statement> falseBody;
if (m_scanner->getCurrentToken() == Token::Else) if (m_scanner->currentToken() == Token::Else)
{ {
m_scanner->next(); m_scanner->next();
falseBody = parseStatement(); falseBody = parseStatement();
@ -674,15 +674,15 @@ ASTPointer<ForStatement> Parser::parseForStatement()
expectToken(Token::LParen); expectToken(Token::LParen);
// LTODO: Maybe here have some predicate like peekExpression() instead of checking for semicolon and RParen? // LTODO: Maybe here have some predicate like peekExpression() instead of checking for semicolon and RParen?
if (m_scanner->getCurrentToken() != Token::Semicolon) if (m_scanner->currentToken() != Token::Semicolon)
initExpression = parseSimpleStatement(); initExpression = parseSimpleStatement();
expectToken(Token::Semicolon); expectToken(Token::Semicolon);
if (m_scanner->getCurrentToken() != Token::Semicolon) if (m_scanner->currentToken() != Token::Semicolon)
conditionExpression = parseExpression(); conditionExpression = parseExpression();
expectToken(Token::Semicolon); expectToken(Token::Semicolon);
if (m_scanner->getCurrentToken() != Token::RParen) if (m_scanner->currentToken() != Token::RParen)
loopExpression = parseExpressionStatement(); loopExpression = parseExpressionStatement();
expectToken(Token::RParen); expectToken(Token::RParen);
@ -713,29 +713,29 @@ ASTPointer<Statement> Parser::parseSimpleStatement()
// We parse '(Identifier|ElementaryTypeName) ( "[" Expression "]" )+' and then decide whether to hand this over // We parse '(Identifier|ElementaryTypeName) ( "[" Expression "]" )+' and then decide whether to hand this over
// to ExpressionStatement or create a VariableDeclarationStatement out of it. // to ExpressionStatement or create a VariableDeclarationStatement out of it.
ASTPointer<PrimaryExpression> primary; ASTPointer<PrimaryExpression> primary;
if (m_scanner->getCurrentToken() == Token::Identifier) if (m_scanner->currentToken() == Token::Identifier)
primary = parseIdentifier(); primary = parseIdentifier();
else else
{ {
primary = ASTNodeFactory(*this).createNode<ElementaryTypeNameExpression>(m_scanner->getCurrentToken()); primary = ASTNodeFactory(*this).createNode<ElementaryTypeNameExpression>(m_scanner->currentToken());
m_scanner->next(); m_scanner->next();
} }
vector<pair<ASTPointer<Expression>, SourceLocation>> indices; vector<pair<ASTPointer<Expression>, SourceLocation>> indices;
solAssert(m_scanner->getCurrentToken() == Token::LBrack, ""); solAssert(m_scanner->currentToken() == Token::LBrack, "");
SourceLocation indexLocation = primary->getLocation(); SourceLocation indexLocation = primary->location();
do do
{ {
expectToken(Token::LBrack); expectToken(Token::LBrack);
ASTPointer<Expression> index; ASTPointer<Expression> index;
if (m_scanner->getCurrentToken() != Token::RBrack) if (m_scanner->currentToken() != Token::RBrack)
index = parseExpression(); index = parseExpression();
indexLocation.end = getEndPosition(); indexLocation.end = endPosition();
indices.push_back(make_pair(index, indexLocation)); indices.push_back(make_pair(index, indexLocation));
expectToken(Token::RBrack); expectToken(Token::RBrack);
} }
while (m_scanner->getCurrentToken() == Token::LBrack); while (m_scanner->currentToken() == Token::LBrack);
if (m_scanner->getCurrentToken() == Token::Identifier || Token::isLocationSpecifier(m_scanner->getCurrentToken())) if (m_scanner->currentToken() == Token::Identifier || Token::isLocationSpecifier(m_scanner->currentToken()))
return parseVariableDeclarationStatement(typeNameIndexAccessStructure(primary, indices)); return parseVariableDeclarationStatement(typeNameIndexAccessStructure(primary, indices));
else else
return parseExpressionStatement(expressionFromIndexAccessStructure(primary, indices)); return parseExpressionStatement(expressionFromIndexAccessStructure(primary, indices));
@ -764,7 +764,7 @@ ASTPointer<Expression> Parser::parseExpression(
ASTPointer<Expression> const& _lookAheadIndexAccessStructure) ASTPointer<Expression> const& _lookAheadIndexAccessStructure)
{ {
ASTPointer<Expression> expression = parseBinaryExpression(4, _lookAheadIndexAccessStructure); ASTPointer<Expression> expression = parseBinaryExpression(4, _lookAheadIndexAccessStructure);
if (!Token::isAssignmentOp(m_scanner->getCurrentToken())) if (!Token::isAssignmentOp(m_scanner->currentToken()))
return expression; return expression;
Token::Value assignmentOperator = expectAssignmentOperator(); Token::Value assignmentOperator = expectAssignmentOperator();
ASTPointer<Expression> rightHandSide = parseExpression(); ASTPointer<Expression> rightHandSide = parseExpression();
@ -778,11 +778,11 @@ ASTPointer<Expression> Parser::parseBinaryExpression(int _minPrecedence,
{ {
ASTPointer<Expression> expression = parseUnaryExpression(_lookAheadIndexAccessStructure); ASTPointer<Expression> expression = parseUnaryExpression(_lookAheadIndexAccessStructure);
ASTNodeFactory nodeFactory(*this, expression); ASTNodeFactory nodeFactory(*this, expression);
int precedence = Token::precedence(m_scanner->getCurrentToken()); int precedence = Token::precedence(m_scanner->currentToken());
for (; precedence >= _minPrecedence; --precedence) for (; precedence >= _minPrecedence; --precedence)
while (Token::precedence(m_scanner->getCurrentToken()) == precedence) while (Token::precedence(m_scanner->currentToken()) == precedence)
{ {
Token::Value op = m_scanner->getCurrentToken(); Token::Value op = m_scanner->currentToken();
m_scanner->next(); m_scanner->next();
ASTPointer<Expression> right = parseBinaryExpression(precedence + 1); ASTPointer<Expression> right = parseBinaryExpression(precedence + 1);
nodeFactory.setEndPositionFromNode(right); nodeFactory.setEndPositionFromNode(right);
@ -796,7 +796,7 @@ ASTPointer<Expression> Parser::parseUnaryExpression(
{ {
ASTNodeFactory nodeFactory = _lookAheadIndexAccessStructure ? ASTNodeFactory nodeFactory = _lookAheadIndexAccessStructure ?
ASTNodeFactory(*this, _lookAheadIndexAccessStructure) : ASTNodeFactory(*this); ASTNodeFactory(*this, _lookAheadIndexAccessStructure) : ASTNodeFactory(*this);
Token::Value token = m_scanner->getCurrentToken(); Token::Value token = m_scanner->currentToken();
if (!_lookAheadIndexAccessStructure && (Token::isUnaryOp(token) || Token::isCountOp(token))) if (!_lookAheadIndexAccessStructure && (Token::isUnaryOp(token) || Token::isCountOp(token)))
{ {
// prefix expression // prefix expression
@ -809,7 +809,7 @@ ASTPointer<Expression> Parser::parseUnaryExpression(
{ {
// potential postfix expression // potential postfix expression
ASTPointer<Expression> subExpression = parseLeftHandSideExpression(_lookAheadIndexAccessStructure); ASTPointer<Expression> subExpression = parseLeftHandSideExpression(_lookAheadIndexAccessStructure);
token = m_scanner->getCurrentToken(); token = m_scanner->currentToken();
if (!Token::isCountOp(token)) if (!Token::isCountOp(token))
return subExpression; return subExpression;
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
@ -827,7 +827,7 @@ ASTPointer<Expression> Parser::parseLeftHandSideExpression(
ASTPointer<Expression> expression; ASTPointer<Expression> expression;
if (_lookAheadIndexAccessStructure) if (_lookAheadIndexAccessStructure)
expression = _lookAheadIndexAccessStructure; expression = _lookAheadIndexAccessStructure;
else if (m_scanner->getCurrentToken() == Token::New) else if (m_scanner->currentToken() == Token::New)
{ {
expectToken(Token::New); expectToken(Token::New);
ASTPointer<Identifier> contractName(parseIdentifier()); ASTPointer<Identifier> contractName(parseIdentifier());
@ -839,13 +839,13 @@ ASTPointer<Expression> Parser::parseLeftHandSideExpression(
while (true) while (true)
{ {
switch (m_scanner->getCurrentToken()) switch (m_scanner->currentToken())
{ {
case Token::LBrack: case Token::LBrack:
{ {
m_scanner->next(); m_scanner->next();
ASTPointer<Expression> index; ASTPointer<Expression> index;
if (m_scanner->getCurrentToken() != Token::RBrack) if (m_scanner->currentToken() != Token::RBrack)
index = parseExpression(); index = parseExpression();
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
expectToken(Token::RBrack); expectToken(Token::RBrack);
@ -879,7 +879,7 @@ ASTPointer<Expression> Parser::parseLeftHandSideExpression(
ASTPointer<Expression> Parser::parsePrimaryExpression() ASTPointer<Expression> Parser::parsePrimaryExpression()
{ {
ASTNodeFactory nodeFactory(*this); ASTNodeFactory nodeFactory(*this);
Token::Value token = m_scanner->getCurrentToken(); Token::Value token = m_scanner->currentToken();
ASTPointer<Expression> expression; ASTPointer<Expression> expression;
switch (token) switch (token)
{ {
@ -892,7 +892,7 @@ ASTPointer<Expression> Parser::parsePrimaryExpression()
{ {
ASTPointer<ASTString> literal = getLiteralAndAdvance(); ASTPointer<ASTString> literal = getLiteralAndAdvance();
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
Literal::SubDenomination subdenomination = static_cast<Literal::SubDenomination>(m_scanner->getCurrentToken()); Literal::SubDenomination subdenomination = static_cast<Literal::SubDenomination>(m_scanner->currentToken());
m_scanner->next(); m_scanner->next();
expression = nodeFactory.createNode<Literal>(token, literal, subdenomination); expression = nodeFactory.createNode<Literal>(token, literal, subdenomination);
break; break;
@ -901,7 +901,7 @@ ASTPointer<Expression> Parser::parsePrimaryExpression()
{ {
ASTPointer<ASTString> literal = getLiteralAndAdvance(); ASTPointer<ASTString> literal = getLiteralAndAdvance();
nodeFactory.markEndPosition(); nodeFactory.markEndPosition();
Literal::SubDenomination subdenomination = static_cast<Literal::SubDenomination>(m_scanner->getCurrentToken()); Literal::SubDenomination subdenomination = static_cast<Literal::SubDenomination>(m_scanner->currentToken());
m_scanner->next(); m_scanner->next();
expression = nodeFactory.createNode<Literal>(token, literal, subdenomination); expression = nodeFactory.createNode<Literal>(token, literal, subdenomination);
break; break;
@ -939,10 +939,10 @@ ASTPointer<Expression> Parser::parsePrimaryExpression()
vector<ASTPointer<Expression>> Parser::parseFunctionCallListArguments() vector<ASTPointer<Expression>> Parser::parseFunctionCallListArguments()
{ {
vector<ASTPointer<Expression>> arguments; vector<ASTPointer<Expression>> arguments;
if (m_scanner->getCurrentToken() != Token::RParen) if (m_scanner->currentToken() != Token::RParen)
{ {
arguments.push_back(parseExpression()); arguments.push_back(parseExpression());
while (m_scanner->getCurrentToken() != Token::RParen) while (m_scanner->currentToken() != Token::RParen)
{ {
expectToken(Token::Comma); expectToken(Token::Comma);
arguments.push_back(parseExpression()); arguments.push_back(parseExpression());
@ -954,18 +954,18 @@ vector<ASTPointer<Expression>> Parser::parseFunctionCallListArguments()
pair<vector<ASTPointer<Expression>>, vector<ASTPointer<ASTString>>> Parser::parseFunctionCallArguments() pair<vector<ASTPointer<Expression>>, vector<ASTPointer<ASTString>>> Parser::parseFunctionCallArguments()
{ {
pair<vector<ASTPointer<Expression>>, vector<ASTPointer<ASTString>>> ret; pair<vector<ASTPointer<Expression>>, vector<ASTPointer<ASTString>>> ret;
Token::Value token = m_scanner->getCurrentToken(); Token::Value token = m_scanner->currentToken();
if (token == Token::LBrace) if (token == Token::LBrace)
{ {
// call({arg1 : 1, arg2 : 2 }) // call({arg1 : 1, arg2 : 2 })
expectToken(Token::LBrace); expectToken(Token::LBrace);
while (m_scanner->getCurrentToken() != Token::RBrace) while (m_scanner->currentToken() != Token::RBrace)
{ {
ret.second.push_back(expectIdentifierToken()); ret.second.push_back(expectIdentifierToken());
expectToken(Token::Colon); expectToken(Token::Colon);
ret.first.push_back(parseExpression()); ret.first.push_back(parseExpression());
if (m_scanner->getCurrentToken() == Token::Comma) if (m_scanner->currentToken() == Token::Comma)
expectToken(Token::Comma); expectToken(Token::Comma);
else else
break; break;
@ -986,7 +986,7 @@ Parser::LookAheadInfo Parser::peekStatementType() const
// a variable declaration. // a variable declaration.
// If we get an identifier followed by a "[", it can be both ("type[9] a;" or "arr[9] = 7;"). // If we get an identifier followed by a "[", it can be both ("type[9] a;" or "arr[9] = 7;").
// In all other cases, we have an expression statement. // In all other cases, we have an expression statement.
Token::Value token(m_scanner->getCurrentToken()); Token::Value token(m_scanner->currentToken());
bool mightBeTypeName = (Token::isElementaryTypeName(token) || token == Token::Identifier); bool mightBeTypeName = (Token::isElementaryTypeName(token) || token == Token::Identifier);
if (token == Token::Mapping || token == Token::Var) if (token == Token::Mapping || token == Token::Var)
@ -1008,9 +1008,9 @@ ASTPointer<TypeName> Parser::typeNameIndexAccessStructure(
ASTNodeFactory nodeFactory(*this, _primary); ASTNodeFactory nodeFactory(*this, _primary);
ASTPointer<TypeName> type; ASTPointer<TypeName> type;
if (auto identifier = dynamic_cast<Identifier const*>(_primary.get())) if (auto identifier = dynamic_cast<Identifier const*>(_primary.get()))
type = nodeFactory.createNode<UserDefinedTypeName>(make_shared<ASTString>(identifier->getName())); type = nodeFactory.createNode<UserDefinedTypeName>(make_shared<ASTString>(identifier->name()));
else if (auto typeName = dynamic_cast<ElementaryTypeNameExpression const*>(_primary.get())) else if (auto typeName = dynamic_cast<ElementaryTypeNameExpression const*>(_primary.get()))
type = nodeFactory.createNode<ElementaryTypeName>(typeName->getTypeToken()); type = nodeFactory.createNode<ElementaryTypeName>(typeName->typeToken());
else else
solAssert(false, "Invalid type name for array look-ahead."); solAssert(false, "Invalid type name for array look-ahead.");
for (auto const& lengthExpression: _indices) for (auto const& lengthExpression: _indices)
@ -1036,14 +1036,14 @@ ASTPointer<Expression> Parser::expressionFromIndexAccessStructure(
void Parser::expectToken(Token::Value _value) void Parser::expectToken(Token::Value _value)
{ {
if (m_scanner->getCurrentToken() != _value) if (m_scanner->currentToken() != _value)
BOOST_THROW_EXCEPTION(createParserError(string("Expected token ") + string(Token::getName(_value)))); BOOST_THROW_EXCEPTION(createParserError(string("Expected token ") + string(Token::name(_value))));
m_scanner->next(); m_scanner->next();
} }
Token::Value Parser::expectAssignmentOperator() Token::Value Parser::expectAssignmentOperator()
{ {
Token::Value op = m_scanner->getCurrentToken(); Token::Value op = m_scanner->currentToken();
if (!Token::isAssignmentOp(op)) if (!Token::isAssignmentOp(op))
BOOST_THROW_EXCEPTION(createParserError("Expected assignment operator")); BOOST_THROW_EXCEPTION(createParserError("Expected assignment operator"));
m_scanner->next(); m_scanner->next();
@ -1052,14 +1052,14 @@ Token::Value Parser::expectAssignmentOperator()
ASTPointer<ASTString> Parser::expectIdentifierToken() ASTPointer<ASTString> Parser::expectIdentifierToken()
{ {
if (m_scanner->getCurrentToken() != Token::Identifier) if (m_scanner->currentToken() != Token::Identifier)
BOOST_THROW_EXCEPTION(createParserError("Expected identifier")); BOOST_THROW_EXCEPTION(createParserError("Expected identifier"));
return getLiteralAndAdvance(); return getLiteralAndAdvance();
} }
ASTPointer<ASTString> Parser::getLiteralAndAdvance() ASTPointer<ASTString> Parser::getLiteralAndAdvance()
{ {
ASTPointer<ASTString> identifier = make_shared<ASTString>(m_scanner->getCurrentLiteral()); ASTPointer<ASTString> identifier = make_shared<ASTString>(m_scanner->currentLiteral());
m_scanner->next(); m_scanner->next();
return identifier; return identifier;
} }
@ -1073,7 +1073,7 @@ ASTPointer<ParameterList> Parser::createEmptyParameterList()
ParserError Parser::createParserError(string const& _description) const ParserError Parser::createParserError(string const& _description) const
{ {
return ParserError() << errinfo_sourceLocation(SourceLocation(getPosition(), getPosition(), getSourceName())) return ParserError() << errinfo_sourceLocation(SourceLocation(position(), position(), sourceName()))
<< errinfo_comment(_description); << errinfo_comment(_description);
} }

View File

@ -37,15 +37,15 @@ public:
Parser() {} Parser() {}
ASTPointer<SourceUnit> parse(std::shared_ptr<Scanner> const& _scanner); ASTPointer<SourceUnit> parse(std::shared_ptr<Scanner> const& _scanner);
std::shared_ptr<std::string const> const& getSourceName() const; std::shared_ptr<std::string const> const& sourceName() const;
private: private:
class ASTNodeFactory; class ASTNodeFactory;
/// Start position of the current token /// Start position of the current token
int getPosition() const; int position() const;
/// End position of the current token /// End position of the current token
int getEndPosition() const; int endPosition() const;
struct VarDeclParserOptions struct VarDeclParserOptions
{ {

View File

@ -202,20 +202,20 @@ Token::Value Scanner::selectToken(char _next, Token::Value _then, Token::Value _
bool Scanner::skipWhitespace() bool Scanner::skipWhitespace()
{ {
int const startPosition = getSourcePos(); int const startPosition = sourcePos();
while (isWhiteSpace(m_char)) while (isWhiteSpace(m_char))
advance(); advance();
// Return whether or not we skipped any characters. // Return whether or not we skipped any characters.
return getSourcePos() != startPosition; return sourcePos() != startPosition;
} }
bool Scanner::skipWhitespaceExceptLF() bool Scanner::skipWhitespaceExceptLF()
{ {
int const startPosition = getSourcePos(); int const startPosition = sourcePos();
while (isWhiteSpace(m_char) && !isLineTerminator(m_char)) while (isWhiteSpace(m_char) && !isLineTerminator(m_char))
advance(); advance();
// Return whether or not we skipped any characters. // Return whether or not we skipped any characters.
return getSourcePos() != startPosition; return sourcePos() != startPosition;
} }
Token::Value Scanner::skipSingleLineComment() Token::Value Scanner::skipSingleLineComment()
@ -326,7 +326,7 @@ Token::Value Scanner::scanMultiLineDocComment()
Token::Value Scanner::scanSlash() Token::Value Scanner::scanSlash()
{ {
int firstSlashPosition = getSourcePos(); int firstSlashPosition = sourcePos();
advance(); advance();
if (m_char == '/') if (m_char == '/')
{ {
@ -338,7 +338,7 @@ Token::Value Scanner::scanSlash()
Token::Value comment; Token::Value comment;
m_nextSkippedComment.location.start = firstSlashPosition; m_nextSkippedComment.location.start = firstSlashPosition;
comment = scanSingleLineDocComment(); comment = scanSingleLineDocComment();
m_nextSkippedComment.location.end = getSourcePos(); m_nextSkippedComment.location.end = sourcePos();
m_nextSkippedComment.token = comment; m_nextSkippedComment.token = comment;
return Token::Whitespace; return Token::Whitespace;
} }
@ -363,7 +363,7 @@ Token::Value Scanner::scanSlash()
Token::Value comment; Token::Value comment;
m_nextSkippedComment.location.start = firstSlashPosition; m_nextSkippedComment.location.start = firstSlashPosition;
comment = scanMultiLineDocComment(); comment = scanMultiLineDocComment();
m_nextSkippedComment.location.end = getSourcePos(); m_nextSkippedComment.location.end = sourcePos();
m_nextSkippedComment.token = comment; m_nextSkippedComment.token = comment;
} }
return Token::Whitespace; return Token::Whitespace;
@ -385,7 +385,7 @@ void Scanner::scanToken()
do do
{ {
// Remember the position of the next token // Remember the position of the next token
m_nextToken.location.start = getSourcePos(); m_nextToken.location.start = sourcePos();
switch (m_char) switch (m_char)
{ {
case '\n': // fall-through case '\n': // fall-through
@ -564,7 +564,7 @@ void Scanner::scanToken()
// whitespace. // whitespace.
} }
while (token == Token::Whitespace); while (token == Token::Whitespace);
m_nextToken.location.end = getSourcePos(); m_nextToken.location.end = sourcePos();
m_nextToken.token = token; m_nextToken.token = token;
} }
@ -719,20 +719,20 @@ char CharStream::advanceAndGet(size_t _chars)
{ {
if (isPastEndOfInput()) if (isPastEndOfInput())
return 0; return 0;
m_pos += _chars; m_position += _chars;
if (isPastEndOfInput()) if (isPastEndOfInput())
return 0; return 0;
return m_source[m_pos]; return m_source[m_position];
} }
char CharStream::rollback(size_t _amount) char CharStream::rollback(size_t _amount)
{ {
solAssert(m_pos >= _amount, ""); solAssert(m_position >= _amount, "");
m_pos -= _amount; m_position -= _amount;
return get(); return get();
} }
string CharStream::getLineAtPosition(int _position) const string CharStream::lineAtPosition(int _position) const
{ {
// if _position points to \n, it returns the line before the \n // if _position points to \n, it returns the line before the \n
using size_type = string::size_type; using size_type = string::size_type;

View File

@ -71,27 +71,27 @@ class ParserRecorder;
class CharStream class CharStream
{ {
public: public:
CharStream(): m_pos(0) {} CharStream(): m_position(0) {}
explicit CharStream(std::string const& _source): m_source(_source), m_pos(0) {} explicit CharStream(std::string const& _source): m_source(_source), m_position(0) {}
int getPos() const { return m_pos; } int position() const { return m_position; }
bool isPastEndOfInput(size_t _charsForward = 0) const { return (m_pos + _charsForward) >= m_source.size(); } bool isPastEndOfInput(size_t _charsForward = 0) const { return (m_position + _charsForward) >= m_source.size(); }
char get(size_t _charsForward = 0) const { return m_source[m_pos + _charsForward]; } char get(size_t _charsForward = 0) const { return m_source[m_position + _charsForward]; }
char advanceAndGet(size_t _chars=1); char advanceAndGet(size_t _chars=1);
char rollback(size_t _amount); char rollback(size_t _amount);
void reset() { m_pos = 0; } void reset() { m_position = 0; }
///@{ ///@{
///@name Error printing helper functions ///@name Error printing helper functions
/// Functions that help pretty-printing parse errors /// Functions that help pretty-printing parse errors
/// Do only use in error cases, they are quite expensive. /// Do only use in error cases, they are quite expensive.
std::string getLineAtPosition(int _position) const; std::string lineAtPosition(int _position) const;
std::tuple<int, int> translatePositionToLineColumn(int _position) const; std::tuple<int, int> translatePositionToLineColumn(int _position) const;
///@} ///@}
private: private:
std::string m_source; std::string m_source;
size_t m_pos; size_t m_position;
}; };
@ -115,20 +115,20 @@ public:
///@name Information about the current token ///@name Information about the current token
/// Returns the current token /// Returns the current token
Token::Value getCurrentToken() Token::Value currentToken()
{ {
return m_currentToken.token; return m_currentToken.token;
} }
SourceLocation getCurrentLocation() const { return m_currentToken.location; } SourceLocation currentLocation() const { return m_currentToken.location; }
std::string const& getCurrentLiteral() const { return m_currentToken.literal; } std::string const& currentLiteral() const { return m_currentToken.literal; }
///@} ///@}
///@{ ///@{
///@name Information about the current comment token ///@name Information about the current comment token
SourceLocation getCurrentCommentLocation() const { return m_skippedComment.location; } SourceLocation currentCommentLocation() const { return m_skippedComment.location; }
std::string const& getCurrentCommentLiteral() const { return m_skippedComment.literal; } std::string const& currentCommentLiteral() const { return m_skippedComment.literal; }
/// Called by the parser during FunctionDefinition parsing to clear the current comment /// Called by the parser during FunctionDefinition parsing to clear the current comment
void clearCurrentCommentLiteral() { m_skippedComment.literal.clear(); } void clearCurrentCommentLiteral() { m_skippedComment.literal.clear(); }
@ -143,13 +143,13 @@ public:
std::string const& peekLiteral() const { return m_nextToken.literal; } std::string const& peekLiteral() const { return m_nextToken.literal; }
///@} ///@}
std::shared_ptr<std::string const> const& getSourceName() const { return m_sourceName; } std::shared_ptr<std::string const> const& sourceName() const { return m_sourceName; }
///@{ ///@{
///@name Error printing helper functions ///@name Error printing helper functions
/// Functions that help pretty-printing parse errors /// Functions that help pretty-printing parse errors
/// Do only use in error cases, they are quite expensive. /// Do only use in error cases, they are quite expensive.
std::string getLineAtPosition(int _position) const { return m_source.getLineAtPosition(_position); } std::string lineAtPosition(int _position) const { return m_source.lineAtPosition(_position); }
std::tuple<int, int> translatePositionToLineColumn(int _position) const { return m_source.translatePositionToLineColumn(_position); } std::tuple<int, int> translatePositionToLineColumn(int _position) const { return m_source.translatePositionToLineColumn(_position); }
///@} ///@}
@ -204,7 +204,7 @@ private:
bool scanEscape(); bool scanEscape();
/// Return the current source position. /// Return the current source position.
int getSourcePos() { return m_source.getPos(); } int sourcePos() { return m_source.position(); }
bool isSourcePastEndOfInput() { return m_source.isPastEndOfInput(); } bool isSourcePastEndOfInput() { return m_source.isPastEndOfInput(); }
TokenDesc m_skippedComment; // desc for current skipped comment TokenDesc m_skippedComment; // desc for current skipped comment

View File

@ -46,7 +46,7 @@ void SourceReferenceFormatter::printSourceLocation(
tie(endLine, endColumn) = _scanner.translatePositionToLineColumn(_location.end); tie(endLine, endColumn) = _scanner.translatePositionToLineColumn(_location.end);
if (startLine == endLine) if (startLine == endLine)
{ {
string line = _scanner.getLineAtPosition(_location.start); string line = _scanner.lineAtPosition(_location.start);
_stream << line << endl; _stream << line << endl;
for_each( for_each(
line.cbegin(), line.cbegin(),
@ -62,7 +62,7 @@ void SourceReferenceFormatter::printSourceLocation(
} }
else else
_stream << _stream <<
_scanner.getLineAtPosition(_location.start) << _scanner.lineAtPosition(_location.start) <<
endl << endl <<
string(startColumn, ' ') << string(startColumn, ' ') <<
"^\n" << "^\n" <<
@ -90,12 +90,12 @@ void SourceReferenceFormatter::printExceptionInformation(
{ {
SourceLocation const* location = boost::get_error_info<errinfo_sourceLocation>(_exception); SourceLocation const* location = boost::get_error_info<errinfo_sourceLocation>(_exception);
auto secondarylocation = boost::get_error_info<errinfo_secondarySourceLocation>(_exception); auto secondarylocation = boost::get_error_info<errinfo_secondarySourceLocation>(_exception);
Scanner const* scanner = nullptr; Scanner const* scannerPtr = nullptr;
if (location) if (location)
{ {
scanner = &_compiler.getScanner(*location->sourceName); scannerPtr = &_compiler.scanner(*location->sourceName);
printSourceName(_stream, *location, *scanner); printSourceName(_stream, *location, *scannerPtr);
} }
_stream << _name; _stream << _name;
@ -104,19 +104,19 @@ void SourceReferenceFormatter::printExceptionInformation(
if (location) if (location)
{ {
scanner = &_compiler.getScanner(*location->sourceName); scannerPtr = &_compiler.scanner(*location->sourceName);
printSourceLocation(_stream, *location, *scanner); printSourceLocation(_stream, *location, *scannerPtr);
} }
if (secondarylocation && !secondarylocation->infos.empty()) if (secondarylocation && !secondarylocation->infos.empty())
{ {
for (auto info: secondarylocation->infos) for (auto info: secondarylocation->infos)
{ {
scanner = &_compiler.getScanner(*info.second.sourceName); scannerPtr = &_compiler.scanner(*info.second.sourceName);
_stream << info.first << " "; _stream << info.first << " ";
printSourceName(_stream, info.second, *scanner); printSourceName(_stream, info.second, *scannerPtr);
_stream << endl; _stream << endl;
printSourceLocation(_stream, info.second, *scanner); printSourceLocation(_stream, info.second, *scannerPtr);
} }
_stream << endl; _stream << endl;
} }

View File

@ -344,7 +344,7 @@ public:
// Returns a string corresponding to the C++ token name // Returns a string corresponding to the C++ token name
// (e.g. "LT" for the token LT). // (e.g. "LT" for the token LT).
static char const* getName(Value tok) static char const* name(Value tok)
{ {
solAssert(tok < NUM_TOKENS, ""); solAssert(tok < NUM_TOKENS, "");
return m_name[tok]; return m_name[tok];

File diff suppressed because it is too large Load Diff

View File

@ -56,9 +56,9 @@ public:
/// of the elements of @a _types. /// of the elements of @a _types.
void computeOffsets(TypePointers const& _types); void computeOffsets(TypePointers const& _types);
/// @returns the offset of the given member, might be null if the member is not part of storage. /// @returns the offset of the given member, might be null if the member is not part of storage.
std::pair<u256, unsigned> const* getOffset(size_t _index) const; std::pair<u256, unsigned> const* offset(size_t _index) const;
/// @returns the total number of slots occupied by all members. /// @returns the total number of slots occupied by all members.
u256 const& getStorageSize() const { return m_storageSize; } u256 const& storageSize() const { return m_storageSize; }
private: private:
u256 m_storageSize; u256 m_storageSize;
@ -90,7 +90,7 @@ public:
MemberList() {} MemberList() {}
explicit MemberList(MemberMap const& _members): m_memberTypes(_members) {} explicit MemberList(MemberMap const& _members): m_memberTypes(_members) {}
MemberList& operator=(MemberList&& _other); MemberList& operator=(MemberList&& _other);
TypePointer getMemberType(std::string const& _name) const TypePointer memberType(std::string const& _name) const
{ {
TypePointer type; TypePointer type;
for (auto const& it: m_memberTypes) for (auto const& it: m_memberTypes)
@ -111,9 +111,9 @@ public:
} }
/// @returns the offset of the given member in storage slots and bytes inside a slot or /// @returns the offset of the given member in storage slots and bytes inside a slot or
/// a nullptr if the member is not part of storage. /// a nullptr if the member is not part of storage.
std::pair<u256, unsigned> const* getMemberStorageOffset(std::string const& _name) const; std::pair<u256, unsigned> const* memberStorageOffset(std::string const& _name) const;
/// @returns the number of storage slots occupied by the members. /// @returns the number of storage slots occupied by the members.
u256 const& getStorageSize() const; u256 const& storageSize() const;
MemberMap::const_iterator begin() const { return m_memberTypes.begin(); } MemberMap::const_iterator begin() const { return m_memberTypes.begin(); }
MemberMap::const_iterator end() const { return m_memberTypes.end(); } MemberMap::const_iterator end() const { return m_memberTypes.end(); }
@ -154,7 +154,7 @@ public:
/// Calculates the /// Calculates the
virtual Category getCategory() const = 0; virtual Category category() const = 0;
virtual bool isImplicitlyConvertibleTo(Type const& _other) const { return *this == _other; } virtual bool isImplicitlyConvertibleTo(Type const& _other) const { return *this == _other; }
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const
{ {
@ -172,29 +172,29 @@ public:
return Token::isCompareOp(_operator) ? commonType(shared_from_this(), _other) : TypePointer(); return Token::isCompareOp(_operator) ? commonType(shared_from_this(), _other) : TypePointer();
} }
virtual bool operator==(Type const& _other) const { return getCategory() == _other.getCategory(); } virtual bool operator==(Type const& _other) const { return category() == _other.category(); }
virtual bool operator!=(Type const& _other) const { return !this->operator ==(_other); } virtual bool operator!=(Type const& _other) const { return !this->operator ==(_other); }
/// @returns number of bytes used by this type when encoded for CALL, or 0 if the encoding /// @returns number of bytes used by this type when encoded for CALL, or 0 if the encoding
/// is not a simple big-endian encoding or the type cannot be stored in calldata. /// is not a simple big-endian encoding or the type cannot be stored in calldata.
/// If @a _padded then it is assumed that each element is padded to a multiple of 32 bytes. /// If @a _padded then it is assumed that each element is padded to a multiple of 32 bytes.
virtual unsigned getCalldataEncodedSize(bool _padded) const { (void)_padded; return 0; } virtual unsigned calldataEncodedSize(bool _padded) const { (void)_padded; return 0; }
/// @returns the size of this data type in bytes when stored in memory. For memory-reference /// @returns the size of this data type in bytes when stored in memory. For memory-reference
/// types, this is the size of the memory pointer. /// types, this is the size of the memory pointer.
virtual unsigned memoryHeadSize() const { return getCalldataEncodedSize(); } virtual unsigned memoryHeadSize() const { return calldataEncodedSize(); }
/// Convenience version of @see getCalldataEncodedSize(bool) /// Convenience version of @see calldataEncodedSize(bool)
unsigned getCalldataEncodedSize() const { return getCalldataEncodedSize(true); } unsigned calldataEncodedSize() const { return calldataEncodedSize(true); }
/// @returns true if the type is dynamically encoded in calldata /// @returns true if the type is dynamically encoded in calldata
virtual bool isDynamicallySized() const { return false; } virtual bool isDynamicallySized() const { return false; }
/// @returns the number of storage slots required to hold this value in storage. /// @returns the number of storage slots required to hold this value in storage.
/// For dynamically "allocated" types, it returns the size of the statically allocated head, /// For dynamically "allocated" types, it returns the size of the statically allocated head,
virtual u256 getStorageSize() const { return 1; } virtual u256 storageSize() const { return 1; }
/// Multiple small types can be packed into a single storage slot. If such a packing is possible /// Multiple small types can be packed into a single storage slot. If such a packing is possible
/// this function @returns the size in bytes smaller than 32. Data is moved to the next slot if /// this function @returns the size in bytes smaller than 32. Data is moved to the next slot if
/// it does not fit. /// it does not fit.
/// In order to avoid computation at runtime of whether such moving is necessary, structs and /// In order to avoid computation at runtime of whether such moving is necessary, structs and
/// array data (not each element) always start a new slot. /// array data (not each element) always start a new slot.
virtual unsigned getStorageBytes() const { return 32; } virtual unsigned storageBytes() const { return 32; }
/// Returns true if the type can be stored in storage. /// Returns true if the type can be stored in storage.
virtual bool canBeStored() const { return true; } virtual bool canBeStored() const { return true; }
/// Returns false if the type cannot live outside the storage, i.e. if it includes some mapping. /// Returns false if the type cannot live outside the storage, i.e. if it includes some mapping.
@ -202,7 +202,7 @@ public:
/// Returns true if the type can be stored as a value (as opposed to a reference) on the stack, /// Returns true if the type can be stored as a value (as opposed to a reference) on the stack,
/// i.e. it behaves differently in lvalue context and in value context. /// i.e. it behaves differently in lvalue context and in value context.
virtual bool isValueType() const { return false; } virtual bool isValueType() const { return false; }
virtual unsigned getSizeOnStack() const { return 1; } virtual unsigned sizeOnStack() const { return 1; }
/// @returns the mobile (in contrast to static) type corresponding to the given type. /// @returns the mobile (in contrast to static) type corresponding to the given type.
/// This returns the corresponding integer type for IntegerConstantTypes and the pointer type /// This returns the corresponding integer type for IntegerConstantTypes and the pointer type
/// for storage reference types. /// for storage reference types.
@ -212,9 +212,9 @@ public:
virtual bool dataStoredIn(DataLocation) const { return false; } virtual bool dataStoredIn(DataLocation) const { return false; }
/// Returns the list of all members of this type. Default implementation: no members. /// Returns the list of all members of this type. Default implementation: no members.
virtual MemberList const& getMembers() const { return EmptyMemberList; } virtual MemberList const& members() const { return EmptyMemberList; }
/// Convenience method, returns the type of the given named member or an empty pointer if no such member exists. /// Convenience method, returns the type of the given named member or an empty pointer if no such member exists.
TypePointer getMemberType(std::string const& _name) const { return getMembers().getMemberType(_name); } TypePointer memberType(std::string const& _name) const { return members().memberType(_name); }
virtual std::string toString(bool _short) const = 0; virtual std::string toString(bool _short) const = 0;
std::string toString() const { return toString(false); } std::string toString() const { return toString(false); }
@ -245,7 +245,7 @@ public:
{ {
Unsigned, Signed, Address Unsigned, Signed, Address
}; };
virtual Category getCategory() const override { return Category::Integer; } virtual Category category() const override { return Category::Integer; }
explicit IntegerType(int _bits, Modifier _modifier = Modifier::Unsigned); explicit IntegerType(int _bits, Modifier _modifier = Modifier::Unsigned);
@ -256,17 +256,17 @@ public:
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual unsigned getCalldataEncodedSize(bool _padded = true) const override { return _padded ? 32 : m_bits / 8; } virtual unsigned calldataEncodedSize(bool _padded = true) const override { return _padded ? 32 : m_bits / 8; }
virtual unsigned getStorageBytes() const override { return m_bits / 8; } virtual unsigned storageBytes() const override { return m_bits / 8; }
virtual bool isValueType() const override { return true; } virtual bool isValueType() const override { return true; }
virtual MemberList const& getMembers() const override { return isAddress() ? AddressMemberList : EmptyMemberList; } virtual MemberList const& members() const override { return isAddress() ? AddressMemberList : EmptyMemberList; }
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
virtual TypePointer externalType() const override { return shared_from_this(); } virtual TypePointer externalType() const override { return shared_from_this(); }
int getNumBits() const { return m_bits; } int numBits() const { return m_bits; }
bool isAddress() const { return m_modifier == Modifier::Address; } bool isAddress() const { return m_modifier == Modifier::Address; }
bool isSigned() const { return m_modifier == Modifier::Signed; } bool isSigned() const { return m_modifier == Modifier::Signed; }
@ -284,7 +284,7 @@ private:
class IntegerConstantType: public Type class IntegerConstantType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::IntegerConstant; } virtual Category category() const override { return Category::IntegerConstant; }
/// @returns true if the literal is a valid integer. /// @returns true if the literal is a valid integer.
static bool isValidLiteral(Literal const& _literal); static bool isValidLiteral(Literal const& _literal);
@ -307,7 +307,7 @@ public:
virtual TypePointer mobileType() const override; virtual TypePointer mobileType() const override;
/// @returns the smallest integer type that can hold the value or an empty pointer if not possible. /// @returns the smallest integer type that can hold the value or an empty pointer if not possible.
std::shared_ptr<IntegerType const> getIntegerType() const; std::shared_ptr<IntegerType const> integerType() const;
private: private:
bigint m_value; bigint m_value;
@ -319,7 +319,7 @@ private:
class StringLiteralType: public Type class StringLiteralType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::StringLiteral; } virtual Category category() const override { return Category::StringLiteral; }
explicit StringLiteralType(Literal const& _literal); explicit StringLiteralType(Literal const& _literal);
@ -333,7 +333,7 @@ public:
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
virtual unsigned getSizeOnStack() const override { return 0; } virtual unsigned sizeOnStack() const override { return 0; }
virtual std::string toString(bool) const override { return "literal_string \"" + m_value + "\""; } virtual std::string toString(bool) const override { return "literal_string \"" + m_value + "\""; }
virtual TypePointer mobileType() const override; virtual TypePointer mobileType() const override;
@ -350,7 +350,7 @@ private:
class FixedBytesType: public Type class FixedBytesType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::FixedBytes; } virtual Category category() const override { return Category::FixedBytes; }
/// @returns the smallest bytes type for the given literal or an empty pointer /// @returns the smallest bytes type for the given literal or an empty pointer
/// if no type fits. /// if no type fits.
@ -364,8 +364,8 @@ public:
virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; virtual TypePointer unaryOperatorResult(Token::Value _operator) const override;
virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override; virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override;
virtual unsigned getCalldataEncodedSize(bool _padded) const override { return _padded && m_bytes > 0 ? 32 : m_bytes; } virtual unsigned calldataEncodedSize(bool _padded) const override { return _padded && m_bytes > 0 ? 32 : m_bytes; }
virtual unsigned getStorageBytes() const override { return m_bytes; } virtual unsigned storageBytes() const override { return m_bytes; }
virtual bool isValueType() const override { return true; } virtual bool isValueType() const override { return true; }
virtual std::string toString(bool) const override { return "bytes" + dev::toString(m_bytes); } virtual std::string toString(bool) const override { return "bytes" + dev::toString(m_bytes); }
@ -384,13 +384,13 @@ class BoolType: public Type
{ {
public: public:
BoolType() {} BoolType() {}
virtual Category getCategory() const override { return Category::Bool; } virtual Category category() const override { return Category::Bool; }
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; virtual TypePointer unaryOperatorResult(Token::Value _operator) const override;
virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override; virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override;
virtual unsigned getCalldataEncodedSize(bool _padded) const override{ return _padded ? 32 : 1; } virtual unsigned calldataEncodedSize(bool _padded) const override{ return _padded ? 32 : 1; }
virtual unsigned getStorageBytes() const override { return 1; } virtual unsigned storageBytes() const override { return 1; }
virtual bool isValueType() const override { return true; } virtual bool isValueType() const override { return true; }
virtual std::string toString(bool) const override { return "bool"; } virtual std::string toString(bool) const override { return "bool"; }
@ -457,7 +457,7 @@ protected:
class ArrayType: public ReferenceType class ArrayType: public ReferenceType
{ {
public: public:
virtual Category getCategory() const override { return Category::Array; } virtual Category category() const override { return Category::Array; }
/// Constructor for a byte array ("bytes") and string. /// Constructor for a byte array ("bytes") and string.
explicit ArrayType(DataLocation _location, bool _isString = false): explicit ArrayType(DataLocation _location, bool _isString = false):
@ -483,13 +483,13 @@ public:
virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual bool operator==(const Type& _other) const override; virtual bool operator==(const Type& _other) const override;
virtual unsigned getCalldataEncodedSize(bool _padded) const override; virtual unsigned calldataEncodedSize(bool _padded) const override;
virtual bool isDynamicallySized() const override { return m_hasDynamicLength; } virtual bool isDynamicallySized() const override { return m_hasDynamicLength; }
virtual u256 getStorageSize() const override; virtual u256 storageSize() const override;
virtual bool canLiveOutsideStorage() const override { return m_baseType->canLiveOutsideStorage(); } virtual bool canLiveOutsideStorage() const override { return m_baseType->canLiveOutsideStorage(); }
virtual unsigned getSizeOnStack() const override; virtual unsigned sizeOnStack() const override;
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
virtual MemberList const& getMembers() const override virtual MemberList const& members() const override
{ {
return isString() ? EmptyMemberList : s_arrayTypeMemberList; return isString() ? EmptyMemberList : s_arrayTypeMemberList;
} }
@ -499,8 +499,8 @@ public:
bool isByteArray() const { return m_arrayKind != ArrayKind::Ordinary; } bool isByteArray() const { return m_arrayKind != ArrayKind::Ordinary; }
/// @returns true if this is a string /// @returns true if this is a string
bool isString() const { return m_arrayKind == ArrayKind::String; } bool isString() const { return m_arrayKind == ArrayKind::String; }
TypePointer const& getBaseType() const { solAssert(!!m_baseType, ""); return m_baseType;} TypePointer const& baseType() const { solAssert(!!m_baseType, ""); return m_baseType;}
u256 const& getLength() const { return m_length; } u256 const& length() const { return m_length; }
TypePointer copyForLocation(DataLocation _location, bool _isPointer) const override; TypePointer copyForLocation(DataLocation _location, bool _isPointer) const override;
@ -522,7 +522,7 @@ private:
class ContractType: public Type class ContractType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::Contract; } virtual Category category() const override { return Category::Contract; }
explicit ContractType(ContractDefinition const& _contract, bool _super = false): explicit ContractType(ContractDefinition const& _contract, bool _super = false):
m_contract(_contract), m_super(_super) {} m_contract(_contract), m_super(_super) {}
/// Contracts can be implicitly converted to super classes and to addresses. /// Contracts can be implicitly converted to super classes and to addresses.
@ -531,42 +531,42 @@ public:
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; virtual TypePointer unaryOperatorResult(Token::Value _operator) const override;
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual unsigned getCalldataEncodedSize(bool _padded ) const override virtual unsigned calldataEncodedSize(bool _padded ) const override
{ {
return externalType()->getCalldataEncodedSize(_padded); return externalType()->calldataEncodedSize(_padded);
} }
virtual unsigned getStorageBytes() const override { return 20; } virtual unsigned storageBytes() const override { return 20; }
virtual bool canLiveOutsideStorage() const override { return true; } virtual bool canLiveOutsideStorage() const override { return true; }
virtual bool isValueType() const override { return true; } virtual bool isValueType() const override { return true; }
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
virtual MemberList const& getMembers() const override; virtual MemberList const& members() const override;
virtual TypePointer externalType() const override virtual TypePointer externalType() const override
{ {
return std::make_shared<IntegerType>(160, IntegerType::Modifier::Address); return std::make_shared<IntegerType>(160, IntegerType::Modifier::Address);
} }
bool isSuper() const { return m_super; } bool isSuper() const { return m_super; }
ContractDefinition const& getContractDefinition() const { return m_contract; } ContractDefinition const& contractDefinition() const { return m_contract; }
/// Returns the function type of the constructor. Note that the location part of the function type /// Returns the function type of the constructor. Note that the location part of the function type
/// is not used, as this type cannot be the type of a variable or expression. /// is not used, as this type cannot be the type of a variable or expression.
FunctionTypePointer const& getConstructorType() const; FunctionTypePointer const& constructorType() const;
/// @returns the identifier of the function with the given name or Invalid256 if such a name does /// @returns the identifier of the function with the given name or Invalid256 if such a name does
/// not exist. /// not exist.
u256 getFunctionIdentifier(std::string const& _functionName) const; u256 functionIdentifier(std::string const& _functionName) const;
/// @returns a list of all state variables (including inherited) of the contract and their /// @returns a list of all state variables (including inherited) of the contract and their
/// offsets in storage. /// offsets in storage.
std::vector<std::tuple<VariableDeclaration const*, u256, unsigned>> getStateVariables() const; std::vector<std::tuple<VariableDeclaration const*, u256, unsigned>> stateVariables() const;
private: private:
ContractDefinition const& m_contract; ContractDefinition const& m_contract;
/// If true, it is the "super" type of the current contract, i.e. it contains only inherited /// If true, it is the "super" type of the current contract, i.e. it contains only inherited
/// members. /// members.
bool m_super; bool m_super;
/// Type of the constructor, @see getConstructorType. Lazily initialized. /// Type of the constructor, @see constructorType. Lazily initialized.
mutable FunctionTypePointer m_constructorType; mutable FunctionTypePointer m_constructorType;
/// List of member types, will be lazy-initialized because of recursive references. /// List of member types, will be lazy-initialized because of recursive references.
mutable std::unique_ptr<MemberList> m_members; mutable std::unique_ptr<MemberList> m_members;
@ -578,18 +578,18 @@ private:
class StructType: public ReferenceType class StructType: public ReferenceType
{ {
public: public:
virtual Category getCategory() const override { return Category::Struct; } virtual Category category() const override { return Category::Struct; }
explicit StructType(StructDefinition const& _struct, DataLocation _location = DataLocation::Storage): explicit StructType(StructDefinition const& _struct, DataLocation _location = DataLocation::Storage):
ReferenceType(_location), m_struct(_struct) {} ReferenceType(_location), m_struct(_struct) {}
virtual bool isImplicitlyConvertibleTo(const Type& _convertTo) const override; virtual bool isImplicitlyConvertibleTo(const Type& _convertTo) const override;
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual unsigned getCalldataEncodedSize(bool _padded) const override; virtual unsigned calldataEncodedSize(bool _padded) const override;
u256 memorySize() const; u256 memorySize() const;
virtual u256 getStorageSize() const override; virtual u256 storageSize() const override;
virtual bool canLiveOutsideStorage() const override { return true; } virtual bool canLiveOutsideStorage() const override { return true; }
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
virtual MemberList const& getMembers() const override; virtual MemberList const& members() const override;
TypePointer copyForLocation(DataLocation _location, bool _isPointer) const override; TypePointer copyForLocation(DataLocation _location, bool _isPointer) const override;
@ -597,7 +597,7 @@ public:
/// and a memory struct of this type. /// and a memory struct of this type.
FunctionTypePointer constructorType() const; FunctionTypePointer constructorType() const;
std::pair<u256, unsigned> const& getStorageOffsetsOfMember(std::string const& _name) const; std::pair<u256, unsigned> const& storageOffsetsOfMember(std::string const& _name) const;
u256 memoryOffsetOfMember(std::string const& _name) const; u256 memoryOffsetOfMember(std::string const& _name) const;
StructDefinition const& structDefinition() const { return m_struct; } StructDefinition const& structDefinition() const { return m_struct; }
@ -617,15 +617,15 @@ private:
class EnumType: public Type class EnumType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::Enum; } virtual Category category() const override { return Category::Enum; }
explicit EnumType(EnumDefinition const& _enum): m_enum(_enum) {} explicit EnumType(EnumDefinition const& _enum): m_enum(_enum) {}
virtual TypePointer unaryOperatorResult(Token::Value _operator) const override; virtual TypePointer unaryOperatorResult(Token::Value _operator) const override;
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual unsigned getCalldataEncodedSize(bool _padded) const override virtual unsigned calldataEncodedSize(bool _padded) const override
{ {
return externalType()->getCalldataEncodedSize(_padded); return externalType()->calldataEncodedSize(_padded);
} }
virtual unsigned getStorageBytes() const override; virtual unsigned storageBytes() const override;
virtual bool canLiveOutsideStorage() const override { return true; } virtual bool canLiveOutsideStorage() const override { return true; }
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
virtual bool isValueType() const override { return true; } virtual bool isValueType() const override { return true; }
@ -633,12 +633,12 @@ public:
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual TypePointer externalType() const override virtual TypePointer externalType() const override
{ {
return std::make_shared<IntegerType>(8 * int(getStorageBytes())); return std::make_shared<IntegerType>(8 * int(storageBytes()));
} }
EnumDefinition const& getEnumDefinition() const { return m_enum; } EnumDefinition const& enumDefinition() const { return m_enum; }
/// @returns the value that the string has in the Enum /// @returns the value that the string has in the Enum
unsigned int getMemberValue(ASTString const& _member) const; unsigned int memberValue(ASTString const& _member) const;
private: private:
EnumDefinition const& m_enum; EnumDefinition const& m_enum;
@ -681,7 +681,7 @@ public:
BlockHash ///< BLOCKHASH BlockHash ///< BLOCKHASH
}; };
virtual Category getCategory() const override { return Category::Function; } virtual Category category() const override { return Category::Function; }
/// @returns TypePointer of a new FunctionType object. All input/return parameters are an /// @returns TypePointer of a new FunctionType object. All input/return parameters are an
/// appropriate external types of input/return parameters of current function. /// appropriate external types of input/return parameters of current function.
@ -733,20 +733,20 @@ public:
m_declaration(_declaration) m_declaration(_declaration)
{} {}
TypePointers const& getParameterTypes() const { return m_parameterTypes; } TypePointers const& parameterTypes() const { return m_parameterTypes; }
std::vector<std::string> const& getParameterNames() const { return m_parameterNames; } std::vector<std::string> const& parameterNames() const { return m_parameterNames; }
std::vector<std::string> const getParameterTypeNames() const; std::vector<std::string> const parameterTypeNames() const;
TypePointers const& getReturnParameterTypes() const { return m_returnParameterTypes; } TypePointers const& returnParameterTypes() const { return m_returnParameterTypes; }
std::vector<std::string> const& getReturnParameterNames() const { return m_returnParameterNames; } std::vector<std::string> const& returnParameterNames() const { return m_returnParameterNames; }
std::vector<std::string> const getReturnParameterTypeNames() const; std::vector<std::string> const returnParameterTypeNames() const;
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual u256 getStorageSize() const override; virtual u256 storageSize() const override;
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
virtual unsigned getSizeOnStack() const override; virtual unsigned sizeOnStack() const override;
virtual MemberList const& getMembers() const override; virtual MemberList const& members() const override;
/// @returns true if this function can take the given argument types (possibly /// @returns true if this function can take the given argument types (possibly
/// after implicit conversion). /// after implicit conversion).
@ -756,14 +756,14 @@ public:
/// @returns true if the ABI is used for this call (only meaningful for external calls) /// @returns true if the ABI is used for this call (only meaningful for external calls)
bool isBareCall() const; bool isBareCall() const;
Location const& getLocation() const { return m_location; } Location const& location() const { return m_location; }
/// @returns the external signature of this function type given the function name /// @returns the external signature of this function type given the function name
/// If @a _name is not provided (empty string) then the @c m_declaration member of the /// If @a _name is not provided (empty string) then the @c m_declaration member of the
/// function type is used /// function type is used
std::string externalSignature(std::string const& _name = "") const; std::string externalSignature(std::string const& _name = "") const;
/// @returns the external identifier of this function (the hash of the signature). /// @returns the external identifier of this function (the hash of the signature).
u256 externalIdentifier() const; u256 externalIdentifier() const;
Declaration const& getDeclaration() const Declaration const& declaration() const
{ {
solAssert(m_declaration, "Requested declaration from a FunctionType that has none"); solAssert(m_declaration, "Requested declaration from a FunctionType that has none");
return *m_declaration; return *m_declaration;
@ -772,7 +772,7 @@ public:
bool isConstant() const { return m_isConstant; } bool isConstant() const { return m_isConstant; }
/// @return A shared pointer of an ASTString. /// @return A shared pointer of an ASTString.
/// Can contain a nullptr in which case indicates absence of documentation /// Can contain a nullptr in which case indicates absence of documentation
ASTPointer<ASTString> getDocumentation() const; ASTPointer<ASTString> documentation() const;
/// true iff arguments are to be padded to multiples of 32 bytes for external calls /// true iff arguments are to be padded to multiples of 32 bytes for external calls
bool padArguments() const { return !(m_location == Location::SHA3 || m_location == Location::SHA256 || m_location == Location::RIPEMD160); } bool padArguments() const { return !(m_location == Location::SHA3 || m_location == Location::SHA256 || m_location == Location::RIPEMD160); }
@ -814,7 +814,7 @@ private:
class MappingType: public Type class MappingType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::Mapping; } virtual Category category() const override { return Category::Mapping; }
MappingType(TypePointer const& _keyType, TypePointer const& _valueType): MappingType(TypePointer const& _keyType, TypePointer const& _valueType):
m_keyType(_keyType), m_valueType(_valueType) {} m_keyType(_keyType), m_valueType(_valueType) {}
@ -822,8 +822,8 @@ public:
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
TypePointer const& getKeyType() const { return m_keyType; } TypePointer const& keyType() const { return m_keyType; }
TypePointer const& getValueType() const { return m_valueType; } TypePointer const& valueType() const { return m_valueType; }
private: private:
TypePointer m_keyType; TypePointer m_keyType;
@ -837,15 +837,15 @@ private:
class VoidType: public Type class VoidType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::Void; } virtual Category category() const override { return Category::Void; }
VoidType() {} VoidType() {}
virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); } virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); }
virtual std::string toString(bool) const override { return "void"; } virtual std::string toString(bool) const override { return "void"; }
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual u256 getStorageSize() const override; virtual u256 storageSize() const override;
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
virtual unsigned getSizeOnStack() const override { return 0; } virtual unsigned sizeOnStack() const override { return 0; }
}; };
/** /**
@ -855,19 +855,19 @@ public:
class TypeType: public Type class TypeType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::TypeType; } virtual Category category() const override { return Category::TypeType; }
explicit TypeType(TypePointer const& _actualType, ContractDefinition const* _currentContract = nullptr): explicit TypeType(TypePointer const& _actualType, ContractDefinition const* _currentContract = nullptr):
m_actualType(_actualType), m_currentContract(_currentContract) {} m_actualType(_actualType), m_currentContract(_currentContract) {}
TypePointer const& getActualType() const { return m_actualType; } TypePointer const& actualType() const { return m_actualType; }
virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); } virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); }
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual u256 getStorageSize() const override; virtual u256 storageSize() const override;
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
virtual unsigned getSizeOnStack() const override { return 0; } virtual unsigned sizeOnStack() const override { return 0; }
virtual std::string toString(bool _short) const override { return "type(" + m_actualType->toString(_short) + ")"; } virtual std::string toString(bool _short) const override { return "type(" + m_actualType->toString(_short) + ")"; }
virtual MemberList const& getMembers() const override; virtual MemberList const& members() const override;
private: private:
TypePointer m_actualType; TypePointer m_actualType;
@ -884,14 +884,14 @@ private:
class ModifierType: public Type class ModifierType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::Modifier; } virtual Category category() const override { return Category::Modifier; }
explicit ModifierType(ModifierDefinition const& _modifier); explicit ModifierType(ModifierDefinition const& _modifier);
virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); } virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); }
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual u256 getStorageSize() const override; virtual u256 storageSize() const override;
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
virtual unsigned getSizeOnStack() const override { return 0; } virtual unsigned sizeOnStack() const override { return 0; }
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;
@ -908,7 +908,7 @@ class MagicType: public Type
{ {
public: public:
enum class Kind { Block, Message, Transaction }; enum class Kind { Block, Message, Transaction };
virtual Category getCategory() const override { return Category::Magic; } virtual Category category() const override { return Category::Magic; }
explicit MagicType(Kind _kind); explicit MagicType(Kind _kind);
@ -920,8 +920,8 @@ public:
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual bool canLiveOutsideStorage() const override { return true; } virtual bool canLiveOutsideStorage() const override { return true; }
virtual unsigned getSizeOnStack() const override { return 0; } virtual unsigned sizeOnStack() const override { return 0; }
virtual MemberList const& getMembers() const override { return m_members; } virtual MemberList const& members() const override { return m_members; }
virtual std::string toString(bool _short) const override; virtual std::string toString(bool _short) const override;

View File

@ -123,31 +123,31 @@ void CommandLineInterface::handleBinary(string const& _contract)
if (m_args.count(g_argBinaryStr)) if (m_args.count(g_argBinaryStr))
{ {
if (m_args.count("output-dir")) if (m_args.count("output-dir"))
createFile(_contract + ".bin", toHex(m_compiler->getBytecode(_contract))); createFile(_contract + ".bin", toHex(m_compiler->bytecode(_contract)));
else else
{ {
cout << "Binary: " << endl; cout << "Binary: " << endl;
cout << toHex(m_compiler->getBytecode(_contract)) << endl; cout << toHex(m_compiler->bytecode(_contract)) << endl;
} }
} }
if (m_args.count(g_argCloneBinaryStr)) if (m_args.count(g_argCloneBinaryStr))
{ {
if (m_args.count("output-dir")) if (m_args.count("output-dir"))
createFile(_contract + ".clone_bin", toHex(m_compiler->getCloneBytecode(_contract))); createFile(_contract + ".clone_bin", toHex(m_compiler->cloneBytecode(_contract)));
else else
{ {
cout << "Clone Binary: " << endl; cout << "Clone Binary: " << endl;
cout << toHex(m_compiler->getCloneBytecode(_contract)) << endl; cout << toHex(m_compiler->cloneBytecode(_contract)) << endl;
} }
} }
if (m_args.count(g_argRuntimeBinaryStr)) if (m_args.count(g_argRuntimeBinaryStr))
{ {
if (m_args.count("output-dir")) if (m_args.count("output-dir"))
createFile(_contract + ".bin", toHex(m_compiler->getRuntimeBytecode(_contract))); createFile(_contract + ".bin", toHex(m_compiler->runtimeBytecode(_contract)));
else else
{ {
cout << "Binary of the runtime part: " << endl; cout << "Binary of the runtime part: " << endl;
cout << toHex(m_compiler->getRuntimeBytecode(_contract)) << endl; cout << toHex(m_compiler->runtimeBytecode(_contract)) << endl;
} }
} }
} }
@ -155,11 +155,11 @@ void CommandLineInterface::handleBinary(string const& _contract)
void CommandLineInterface::handleOpcode(string const& _contract) void CommandLineInterface::handleOpcode(string const& _contract)
{ {
if (m_args.count("output-dir")) if (m_args.count("output-dir"))
createFile(_contract + ".opcode", eth::disassemble(m_compiler->getBytecode(_contract))); createFile(_contract + ".opcode", eth::disassemble(m_compiler->bytecode(_contract)));
else else
{ {
cout << "Opcodes: " << endl; cout << "Opcodes: " << endl;
cout << eth::disassemble(m_compiler->getBytecode(_contract)); cout << eth::disassemble(m_compiler->bytecode(_contract));
cout << endl; cout << endl;
} }
@ -179,7 +179,7 @@ void CommandLineInterface::handleSignatureHashes(string const& _contract)
return; return;
string out; string out;
for (auto const& it: m_compiler->getContractDefinition(_contract).getInterfaceFunctions()) for (auto const& it: m_compiler->contractDefinition(_contract).interfaceFunctions())
out += toHex(it.first.ref()) + ": " + it.second->externalSignature() + "\n"; out += toHex(it.first.ref()) + ": " + it.second->externalSignature() + "\n";
if (m_args.count("output-dir")) if (m_args.count("output-dir"))
@ -223,11 +223,11 @@ void CommandLineInterface::handleMeta(DocumentationType _type, string const& _co
if (m_args.count(argName)) if (m_args.count(argName))
{ {
if (m_args.count("output-dir")) if (m_args.count("output-dir"))
createFile(_contract + suffix, m_compiler->getMetadata(_contract, _type)); createFile(_contract + suffix, m_compiler->metadata(_contract, _type));
else else
{ {
cout << title << endl; cout << title << endl;
cout << m_compiler->getMetadata(_contract, _type) << endl; cout << m_compiler->metadata(_contract, _type) << endl;
} }
} }
@ -236,46 +236,46 @@ void CommandLineInterface::handleMeta(DocumentationType _type, string const& _co
void CommandLineInterface::handleGasEstimation(string const& _contract) void CommandLineInterface::handleGasEstimation(string const& _contract)
{ {
using Gas = GasEstimator::GasConsumption; using Gas = GasEstimator::GasConsumption;
if (!m_compiler->getAssemblyItems(_contract) && !m_compiler->getRuntimeAssemblyItems(_contract)) if (!m_compiler->assemblyItems(_contract) && !m_compiler->runtimeAssemblyItems(_contract))
return; return;
cout << "Gas estimation:" << endl; cout << "Gas estimation:" << endl;
if (eth::AssemblyItems const* items = m_compiler->getAssemblyItems(_contract)) if (eth::AssemblyItems const* items = m_compiler->assemblyItems(_contract))
{ {
Gas gas = GasEstimator::functionalEstimation(*items); Gas gas = GasEstimator::functionalEstimation(*items);
u256 bytecodeSize(m_compiler->getRuntimeBytecode(_contract).size()); u256 bytecodeSize(m_compiler->runtimeBytecode(_contract).size());
cout << "construction:" << endl; cout << "construction:" << endl;
cout << " " << gas << " + " << (bytecodeSize * eth::c_createDataGas) << " = "; cout << " " << gas << " + " << (bytecodeSize * eth::c_createDataGas) << " = ";
gas += bytecodeSize * eth::c_createDataGas; gas += bytecodeSize * eth::c_createDataGas;
cout << gas << endl; cout << gas << endl;
} }
if (eth::AssemblyItems const* items = m_compiler->getRuntimeAssemblyItems(_contract)) if (eth::AssemblyItems const* items = m_compiler->runtimeAssemblyItems(_contract))
{ {
ContractDefinition const& contract = m_compiler->getContractDefinition(_contract); ContractDefinition const& contract = m_compiler->contractDefinition(_contract);
cout << "external:" << endl; cout << "external:" << endl;
for (auto it: contract.getInterfaceFunctions()) for (auto it: contract.interfaceFunctions())
{ {
string sig = it.second->externalSignature(); string sig = it.second->externalSignature();
GasEstimator::GasConsumption gas = GasEstimator::functionalEstimation(*items, sig); GasEstimator::GasConsumption gas = GasEstimator::functionalEstimation(*items, sig);
cout << " " << sig << ":\t" << gas << endl; cout << " " << sig << ":\t" << gas << endl;
} }
if (contract.getFallbackFunction()) if (contract.fallbackFunction())
{ {
GasEstimator::GasConsumption gas = GasEstimator::functionalEstimation(*items, "INVALID"); GasEstimator::GasConsumption gas = GasEstimator::functionalEstimation(*items, "INVALID");
cout << " fallback:\t" << gas << endl; cout << " fallback:\t" << gas << endl;
} }
cout << "internal:" << endl; cout << "internal:" << endl;
for (auto const& it: contract.getDefinedFunctions()) for (auto const& it: contract.definedFunctions())
{ {
if (it->isPartOfExternalInterface() || it->isConstructor()) if (it->isPartOfExternalInterface() || it->isConstructor())
continue; continue;
size_t entry = m_compiler->getFunctionEntryPoint(_contract, *it); size_t entry = m_compiler->functionEntryPoint(_contract, *it);
GasEstimator::GasConsumption gas = GasEstimator::GasConsumption::infinite(); GasEstimator::GasConsumption gas = GasEstimator::GasConsumption::infinite();
if (entry > 0) if (entry > 0)
gas = GasEstimator::functionalEstimation(*items, entry, *it); gas = GasEstimator::functionalEstimation(*items, entry, *it);
FunctionType type(*it); FunctionType type(*it);
cout << " " << it->getName() << "("; cout << " " << it->name() << "(";
auto end = type.getParameterTypes().end(); auto end = type.parameterTypes().end();
for (auto it = type.getParameterTypes().begin(); it != end; ++it) for (auto it = type.parameterTypes().begin(); it != end; ++it)
cout << (*it)->toString() << (it + 1 == end ? "" : ","); cout << (*it)->toString() << (it + 1 == end ? "" : ",");
cout << "):\t" << gas << endl; cout << "):\t" << gas << endl;
} }
@ -488,7 +488,7 @@ void CommandLineInterface::handleCombinedJSON()
set<string> requests; set<string> requests;
boost::split(requests, m_args["combined-json"].as<string>(), boost::is_any_of(",")); boost::split(requests, m_args["combined-json"].as<string>(), boost::is_any_of(","));
vector<string> contracts = m_compiler->getContractNames(); vector<string> contracts = m_compiler->contractNames();
if (!contracts.empty()) if (!contracts.empty())
output["contracts"] = Json::Value(Json::objectValue); output["contracts"] = Json::Value(Json::objectValue);
@ -496,24 +496,24 @@ void CommandLineInterface::handleCombinedJSON()
{ {
Json::Value contractData(Json::objectValue); Json::Value contractData(Json::objectValue);
if (requests.count("interface")) if (requests.count("interface"))
contractData["interface"] = m_compiler->getSolidityInterface(contractName); contractData["interface"] = m_compiler->solidityInterface(contractName);
if (requests.count("abi")) if (requests.count("abi"))
contractData["abi"] = m_compiler->getInterface(contractName); contractData["abi"] = m_compiler->interface(contractName);
if (requests.count("bin")) if (requests.count("bin"))
contractData["bin"] = toHex(m_compiler->getBytecode(contractName)); contractData["bin"] = toHex(m_compiler->bytecode(contractName));
if (requests.count("clone-bin")) if (requests.count("clone-bin"))
contractData["clone-bin"] = toHex(m_compiler->getCloneBytecode(contractName)); contractData["clone-bin"] = toHex(m_compiler->cloneBytecode(contractName));
if (requests.count("opcodes")) if (requests.count("opcodes"))
contractData["opcodes"] = eth::disassemble(m_compiler->getBytecode(contractName)); contractData["opcodes"] = eth::disassemble(m_compiler->bytecode(contractName));
if (requests.count("asm")) if (requests.count("asm"))
{ {
ostringstream unused; ostringstream unused;
contractData["asm"] = m_compiler->streamAssembly(unused, contractName, m_sourceCodes, true); contractData["asm"] = m_compiler->streamAssembly(unused, contractName, m_sourceCodes, true);
} }
if (requests.count("devdoc")) if (requests.count("devdoc"))
contractData["devdoc"] = m_compiler->getMetadata(contractName, DocumentationType::NatspecDev); contractData["devdoc"] = m_compiler->metadata(contractName, DocumentationType::NatspecDev);
if (requests.count("userdoc")) if (requests.count("userdoc"))
contractData["userdoc"] = m_compiler->getMetadata(contractName, DocumentationType::NatspecUser); contractData["userdoc"] = m_compiler->metadata(contractName, DocumentationType::NatspecUser);
output["contracts"][contractName] = contractData; output["contracts"][contractName] = contractData;
} }
@ -522,7 +522,7 @@ void CommandLineInterface::handleCombinedJSON()
output["sources"] = Json::Value(Json::objectValue); output["sources"] = Json::Value(Json::objectValue);
for (auto const& sourceCode: m_sourceCodes) for (auto const& sourceCode: m_sourceCodes)
{ {
ASTJsonConverter converter(m_compiler->getAST(sourceCode.first)); ASTJsonConverter converter(m_compiler->AST(sourceCode.first));
output["sources"][sourceCode.first] = Json::Value(Json::objectValue); output["sources"][sourceCode.first] = Json::Value(Json::objectValue);
output["sources"][sourceCode.first]["AST"] = converter.json(); output["sources"][sourceCode.first]["AST"] = converter.json();
} }
@ -546,11 +546,11 @@ void CommandLineInterface::handleAst(string const& _argStr)
{ {
vector<ASTNode const*> asts; vector<ASTNode const*> asts;
for (auto const& sourceCode: m_sourceCodes) for (auto const& sourceCode: m_sourceCodes)
asts.push_back(&m_compiler->getAST(sourceCode.first)); asts.push_back(&m_compiler->AST(sourceCode.first));
map<ASTNode const*, eth::GasMeter::GasConsumption> gasCosts; map<ASTNode const*, eth::GasMeter::GasConsumption> gasCosts;
if (m_compiler->getRuntimeAssemblyItems()) if (m_compiler->runtimeAssemblyItems())
gasCosts = GasEstimator::breakToStatementLevel( gasCosts = GasEstimator::breakToStatementLevel(
GasEstimator::structuralEstimation(*m_compiler->getRuntimeAssemblyItems(), asts), GasEstimator::structuralEstimation(*m_compiler->runtimeAssemblyItems(), asts),
asts asts
); );
@ -562,12 +562,12 @@ void CommandLineInterface::handleAst(string const& _argStr)
string postfix = ""; string postfix = "";
if (_argStr == g_argAstStr) if (_argStr == g_argAstStr)
{ {
ASTPrinter printer(m_compiler->getAST(sourceCode.first), sourceCode.second); ASTPrinter printer(m_compiler->AST(sourceCode.first), sourceCode.second);
printer.print(data); printer.print(data);
} }
else else
{ {
ASTJsonConverter converter(m_compiler->getAST(sourceCode.first)); ASTJsonConverter converter(m_compiler->AST(sourceCode.first));
converter.print(data); converter.print(data);
postfix += "_json"; postfix += "_json";
} }
@ -584,7 +584,7 @@ void CommandLineInterface::handleAst(string const& _argStr)
if (_argStr == g_argAstStr) if (_argStr == g_argAstStr)
{ {
ASTPrinter printer( ASTPrinter printer(
m_compiler->getAST(sourceCode.first), m_compiler->AST(sourceCode.first),
sourceCode.second, sourceCode.second,
gasCosts gasCosts
); );
@ -592,7 +592,7 @@ void CommandLineInterface::handleAst(string const& _argStr)
} }
else else
{ {
ASTJsonConverter converter(m_compiler->getAST(sourceCode.first)); ASTJsonConverter converter(m_compiler->AST(sourceCode.first));
converter.print(cout); converter.print(cout);
} }
} }
@ -608,7 +608,7 @@ void CommandLineInterface::actOnInput()
handleAst(g_argAstStr); handleAst(g_argAstStr);
handleAst(g_argAstJson); handleAst(g_argAstJson);
vector<string> contracts = m_compiler->getContractNames(); vector<string> contracts = m_compiler->contractNames();
for (string const& contract: contracts) for (string const& contract: contracts)
{ {
if (needsHumanTargetedStdout(m_args)) if (needsHumanTargetedStdout(m_args))

View File

@ -54,7 +54,7 @@ string formatError(Exception const& _exception, string const& _name, CompilerSta
Json::Value functionHashes(ContractDefinition const& _contract) Json::Value functionHashes(ContractDefinition const& _contract)
{ {
Json::Value functionHashes(Json::objectValue); Json::Value functionHashes(Json::objectValue);
for (auto const& it: _contract.getInterfaceFunctions()) for (auto const& it: _contract.interfaceFunctions())
functionHashes[it.second->externalSignature()] = toHex(it.first.ref()); functionHashes[it.second->externalSignature()] = toHex(it.first.ref());
return functionHashes; return functionHashes;
} }
@ -71,42 +71,42 @@ Json::Value estimateGas(CompilerStack const& _compiler, string const& _contract)
{ {
Json::Value gasEstimates(Json::objectValue); Json::Value gasEstimates(Json::objectValue);
using Gas = GasEstimator::GasConsumption; using Gas = GasEstimator::GasConsumption;
if (!_compiler.getAssemblyItems(_contract) && !_compiler.getRuntimeAssemblyItems(_contract)) if (!_compiler.assemblyItems(_contract) && !_compiler.runtimeAssemblyItems(_contract))
return gasEstimates; return gasEstimates;
if (eth::AssemblyItems const* items = _compiler.getAssemblyItems(_contract)) if (eth::AssemblyItems const* items = _compiler.assemblyItems(_contract))
{ {
Gas gas = GasEstimator::functionalEstimation(*items); Gas gas = GasEstimator::functionalEstimation(*items);
u256 bytecodeSize(_compiler.getRuntimeBytecode(_contract).size()); u256 bytecodeSize(_compiler.runtimeBytecode(_contract).size());
Json::Value creationGas(Json::arrayValue); Json::Value creationGas(Json::arrayValue);
creationGas[0] = gasToJson(gas); creationGas[0] = gasToJson(gas);
creationGas[1] = gasToJson(bytecodeSize * eth::c_createDataGas); creationGas[1] = gasToJson(bytecodeSize * eth::c_createDataGas);
gasEstimates["creation"] = creationGas; gasEstimates["creation"] = creationGas;
} }
if (eth::AssemblyItems const* items = _compiler.getRuntimeAssemblyItems(_contract)) if (eth::AssemblyItems const* items = _compiler.runtimeAssemblyItems(_contract))
{ {
ContractDefinition const& contract = _compiler.getContractDefinition(_contract); ContractDefinition const& contract = _compiler.contractDefinition(_contract);
Json::Value externalFunctions(Json::objectValue); Json::Value externalFunctions(Json::objectValue);
for (auto it: contract.getInterfaceFunctions()) for (auto it: contract.interfaceFunctions())
{ {
string sig = it.second->externalSignature(); string sig = it.second->externalSignature();
externalFunctions[sig] = gasToJson(GasEstimator::functionalEstimation(*items, sig)); externalFunctions[sig] = gasToJson(GasEstimator::functionalEstimation(*items, sig));
} }
if (contract.getFallbackFunction()) if (contract.fallbackFunction())
externalFunctions[""] = gasToJson(GasEstimator::functionalEstimation(*items, "INVALID")); externalFunctions[""] = gasToJson(GasEstimator::functionalEstimation(*items, "INVALID"));
gasEstimates["external"] = externalFunctions; gasEstimates["external"] = externalFunctions;
Json::Value internalFunctions(Json::objectValue); Json::Value internalFunctions(Json::objectValue);
for (auto const& it: contract.getDefinedFunctions()) for (auto const& it: contract.definedFunctions())
{ {
if (it->isPartOfExternalInterface() || it->isConstructor()) if (it->isPartOfExternalInterface() || it->isConstructor())
continue; continue;
size_t entry = _compiler.getFunctionEntryPoint(_contract, *it); size_t entry = _compiler.functionEntryPoint(_contract, *it);
GasEstimator::GasConsumption gas = GasEstimator::GasConsumption::infinite(); GasEstimator::GasConsumption gas = GasEstimator::GasConsumption::infinite();
if (entry > 0) if (entry > 0)
gas = GasEstimator::functionalEstimation(*items, entry, *it); gas = GasEstimator::functionalEstimation(*items, entry, *it);
FunctionType type(*it); FunctionType type(*it);
string sig = it->getName() + "("; string sig = it->name() + "(";
auto end = type.getParameterTypes().end(); auto end = type.parameterTypes().end();
for (auto it = type.getParameterTypes().begin(); it != end; ++it) for (auto it = type.parameterTypes().begin(); it != end; ++it)
sig += (*it)->toString() + (it + 1 == end ? "" : ","); sig += (*it)->toString() + (it + 1 == end ? "" : ",");
sig += ")"; sig += ")";
internalFunctions[sig] = gasToJson(gas); internalFunctions[sig] = gasToJson(gas);
@ -163,14 +163,14 @@ string compile(string _input, bool _optimize)
} }
output["contracts"] = Json::Value(Json::objectValue); output["contracts"] = Json::Value(Json::objectValue);
for (string const& contractName: compiler.getContractNames()) for (string const& contractName: compiler.contractNames())
{ {
Json::Value contractData(Json::objectValue); Json::Value contractData(Json::objectValue);
contractData["solidity_interface"] = compiler.getSolidityInterface(contractName); contractData["solidity_interface"] = compiler.solidityInterface(contractName);
contractData["interface"] = compiler.getInterface(contractName); contractData["interface"] = compiler.interface(contractName);
contractData["bytecode"] = toHex(compiler.getBytecode(contractName)); contractData["bytecode"] = toHex(compiler.bytecode(contractName));
contractData["opcodes"] = eth::disassemble(compiler.getBytecode(contractName)); contractData["opcodes"] = eth::disassemble(compiler.bytecode(contractName));
contractData["functionHashes"] = functionHashes(compiler.getContractDefinition(contractName)); contractData["functionHashes"] = functionHashes(compiler.contractDefinition(contractName));
contractData["gasEstimates"] = estimateGas(compiler, contractName); contractData["gasEstimates"] = estimateGas(compiler, contractName);
ostringstream unused; ostringstream unused;
contractData["assembly"] = compiler.streamAssembly(unused, contractName, sources, true); contractData["assembly"] = compiler.streamAssembly(unused, contractName, sources, true);
@ -179,7 +179,7 @@ string compile(string _input, bool _optimize)
output["sources"] = Json::Value(Json::objectValue); output["sources"] = Json::Value(Json::objectValue);
output["sources"][""] = Json::Value(Json::objectValue); output["sources"][""] = Json::Value(Json::objectValue);
output["sources"][""]["AST"] = ASTJsonConverter(compiler.getAST("")).json(); output["sources"][""]["AST"] = ASTJsonConverter(compiler.AST("")).json();
return Json::FastWriter().write(output); return Json::FastWriter().write(output);
} }

View File

@ -233,7 +233,7 @@ protected:
m_compiler.reset(false, m_addStandardSources); m_compiler.reset(false, m_addStandardSources);
m_compiler.addSource("", registrarCode); m_compiler.addSource("", registrarCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed");
s_compiledRegistrar.reset(new bytes(m_compiler.getBytecode("GlobalRegistrar"))); s_compiledRegistrar.reset(new bytes(m_compiler.bytecode("GlobalRegistrar")));
} }
sendMessage(*s_compiledRegistrar, true); sendMessage(*s_compiledRegistrar, true);
BOOST_REQUIRE(!m_output.empty()); BOOST_REQUIRE(!m_output.empty());

View File

@ -125,7 +125,7 @@ protected:
m_compiler.reset(false, m_addStandardSources); m_compiler.reset(false, m_addStandardSources);
m_compiler.addSource("", registrarCode); m_compiler.addSource("", registrarCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed");
s_compiledRegistrar.reset(new bytes(m_compiler.getBytecode("FixedFeeRegistrar"))); s_compiledRegistrar.reset(new bytes(m_compiler.bytecode("FixedFeeRegistrar")));
} }
sendMessage(*s_compiledRegistrar, true); sendMessage(*s_compiledRegistrar, true);
BOOST_REQUIRE(!m_output.empty()); BOOST_REQUIRE(!m_output.empty());

View File

@ -440,7 +440,7 @@ protected:
m_compiler.reset(false, m_addStandardSources); m_compiler.reset(false, m_addStandardSources);
m_compiler.addSource("", walletCode); m_compiler.addSource("", walletCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed");
s_compiledWallet.reset(new bytes(m_compiler.getBytecode("Wallet"))); s_compiledWallet.reset(new bytes(m_compiler.bytecode("Wallet")));
} }
bytes args = encodeArgs(u256(0x60), _required, _dailyLimit, u256(_owners.size()), _owners); bytes args = encodeArgs(u256(0x60), _required, _dailyLimit, u256(_owners.size()), _owners);
sendMessage(*s_compiledWallet + args, true, _value); sendMessage(*s_compiledWallet + args, true, _value);

View File

@ -52,23 +52,23 @@ eth::AssemblyItems compileContract(const string& _sourceCode)
BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared<Scanner>(CharStream(_sourceCode)))); BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared<Scanner>(CharStream(_sourceCode))));
NameAndTypeResolver resolver({}); NameAndTypeResolver resolver({});
resolver.registerDeclarations(*sourceUnit); resolver.registerDeclarations(*sourceUnit);
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract)); BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract));
} }
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
BOOST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract)); BOOST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract));
} }
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
Compiler compiler; Compiler compiler;
compiler.compileContract(*contract, map<ContractDefinition const*, bytes const*>{}); compiler.compileContract(*contract, map<ContractDefinition const*, bytes const*>{});
return compiler.getRuntimeAssemblyItems(); return compiler.runtimeAssemblyItems();
} }
BOOST_FAIL("No contract found in source."); BOOST_FAIL("No contract found in source.");
return AssemblyItems(); return AssemblyItems();

View File

@ -48,8 +48,8 @@ public:
m_compiler.setSource(_sourceCode); m_compiler.setSource(_sourceCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed"); ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(), "Compiling contract failed");
AssemblyItems const* items = m_compiler.getRuntimeAssemblyItems(""); AssemblyItems const* items = m_compiler.runtimeAssemblyItems("");
ASTNode const& sourceUnit = m_compiler.getAST(); ASTNode const& sourceUnit = m_compiler.AST();
BOOST_REQUIRE(items != nullptr); BOOST_REQUIRE(items != nullptr);
m_gasCosts = GasEstimator::breakToStatementLevel( m_gasCosts = GasEstimator::breakToStatementLevel(
GasEstimator::structuralEstimation(*items, vector<ASTNode const*>({&sourceUnit})), GasEstimator::structuralEstimation(*items, vector<ASTNode const*>({&sourceUnit})),
@ -61,9 +61,9 @@ public:
{ {
compileAndRun(_sourceCode); compileAndRun(_sourceCode);
auto state = make_shared<KnownState>(); auto state = make_shared<KnownState>();
PathGasMeter meter(*m_compiler.getAssemblyItems()); PathGasMeter meter(*m_compiler.assemblyItems());
GasMeter::GasConsumption gas = meter.estimateMax(0, state); GasMeter::GasConsumption gas = meter.estimateMax(0, state);
u256 bytecodeSize(m_compiler.getRuntimeBytecode().size()); u256 bytecodeSize(m_compiler.runtimeBytecode().size());
gas += bytecodeSize * c_createDataGas; gas += bytecodeSize * c_createDataGas;
BOOST_REQUIRE(!gas.isInfinite); BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK(gas.value == m_gasUsed); BOOST_CHECK(gas.value == m_gasUsed);
@ -82,7 +82,7 @@ public:
} }
GasMeter::GasConsumption gas = GasEstimator::functionalEstimation( GasMeter::GasConsumption gas = GasEstimator::functionalEstimation(
*m_compiler.getRuntimeAssemblyItems(), *m_compiler.runtimeAssemblyItems(),
_sig _sig
); );
BOOST_REQUIRE(!gas.isInfinite); BOOST_REQUIRE(!gas.isInfinite);
@ -115,11 +115,11 @@ BOOST_AUTO_TEST_CASE(non_overlapping_filtered_costs)
{ {
auto second = first; auto second = first;
for (++second; second != m_gasCosts.cend(); ++second) for (++second; second != m_gasCosts.cend(); ++second)
if (first->first->getLocation().intersects(second->first->getLocation())) if (first->first->location().intersects(second->first->location()))
{ {
BOOST_CHECK_MESSAGE(false, "Source locations should not overlap!"); BOOST_CHECK_MESSAGE(false, "Source locations should not overlap!");
SourceReferenceFormatter::printSourceLocation(cout, first->first->getLocation(), m_compiler.getScanner()); SourceReferenceFormatter::printSourceLocation(cout, first->first->location(), m_compiler.scanner());
SourceReferenceFormatter::printSourceLocation(cout, second->first->getLocation(), m_compiler.getScanner()); SourceReferenceFormatter::printSourceLocation(cout, second->first->location(), m_compiler.scanner());
} }
} }
} }

View File

@ -40,7 +40,7 @@ public:
void checkInterface(std::string const& _code, std::string const& _expectedInterfaceString) void checkInterface(std::string const& _code, std::string const& _expectedInterfaceString)
{ {
ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing contract failed"); ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing contract failed");
std::string generatedInterfaceString = m_compilerStack.getMetadata("", DocumentationType::ABIInterface); std::string generatedInterfaceString = m_compilerStack.metadata("", DocumentationType::ABIInterface);
Json::Value generatedInterface; Json::Value generatedInterface;
m_reader.parse(generatedInterfaceString, generatedInterface); m_reader.parse(generatedInterfaceString, generatedInterface);
Json::Value expectedInterface; Json::Value expectedInterface;

View File

@ -108,18 +108,18 @@ bytes compileFirstExpression(const string& _sourceCode, vector<vector<string>> _
resolver.registerDeclarations(*sourceUnit); resolver.registerDeclarations(*sourceUnit);
vector<ContractDefinition const*> inheritanceHierarchy; vector<ContractDefinition const*> inheritanceHierarchy;
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
ETH_TEST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract), "Resolving names failed"); ETH_TEST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract), "Resolving names failed");
inheritanceHierarchy = vector<ContractDefinition const*>(1, contract); inheritanceHierarchy = vector<ContractDefinition const*>(1, contract);
} }
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
ETH_TEST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract), "Checking type Requirements failed"); ETH_TEST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract), "Checking type Requirements failed");
} }
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
FirstExpressionExtractor extractor(*contract); FirstExpressionExtractor extractor(*contract);
@ -137,8 +137,8 @@ bytes compileFirstExpression(const string& _sourceCode, vector<vector<string>> _
ExpressionCompiler(context).compile(*extractor.getExpression()); ExpressionCompiler(context).compile(*extractor.getExpression());
for (vector<string> const& function: _functions) for (vector<string> const& function: _functions)
context << context.getFunctionEntryLabel(dynamic_cast<FunctionDefinition const&>(resolveDeclaration(function, resolver))); context << context.functionEntryLabel(dynamic_cast<FunctionDefinition const&>(resolveDeclaration(function, resolver)));
bytes instructions = context.getAssembledBytecode(); bytes instructions = context.assembledBytecode();
// debug // debug
// cout << eth::disassemble(instructions) << endl; // cout << eth::disassemble(instructions) << endl;
return instructions; return instructions;

View File

@ -43,14 +43,14 @@ public:
{ {
m_code = _code; m_code = _code;
ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing failed");
m_interface = m_compilerStack.getMetadata("", DocumentationType::ABISolidityInterface); m_interface = m_compilerStack.metadata("", DocumentationType::ABISolidityInterface);
ETH_TEST_REQUIRE_NO_THROW(m_reCompiler.parse(m_interface), "Interface parsing failed"); ETH_TEST_REQUIRE_NO_THROW(m_reCompiler.parse(m_interface), "Interface parsing failed");
return m_reCompiler.getContractDefinition(_contractName); return m_reCompiler.contractDefinition(_contractName);
} }
string getSourcePart(ASTNode const& _node) const string getSourcePart(ASTNode const& _node) const
{ {
SourceLocation location = _node.getLocation(); SourceLocation location = _node.location();
BOOST_REQUIRE(!location.isEmpty()); BOOST_REQUIRE(!location.isEmpty());
return m_interface.substr(location.start, location.end - location.start); return m_interface.substr(location.start, location.end - location.start);
} }
@ -76,8 +76,8 @@ BOOST_AUTO_TEST_CASE(single_function)
"contract test {\n" "contract test {\n"
" function f(uint a) returns(uint d) { return a * 7; }\n" " function f(uint a) returns(uint d) { return a * 7; }\n"
"}\n"); "}\n");
BOOST_REQUIRE_EQUAL(1, contract.getDefinedFunctions().size()); BOOST_REQUIRE_EQUAL(1, contract.definedFunctions().size());
BOOST_CHECK_EQUAL(getSourcePart(*contract.getDefinedFunctions().front()), BOOST_CHECK_EQUAL(getSourcePart(*contract.definedFunctions().front()),
"function f(uint256 a)returns(uint256 d);"); "function f(uint256 a)returns(uint256 d);");
} }
@ -85,8 +85,8 @@ BOOST_AUTO_TEST_CASE(single_constant_function)
{ {
ContractDefinition const& contract = checkInterface( ContractDefinition const& contract = checkInterface(
"contract test { function f(uint a) constant returns(bytes1 x) { 1==2; } }"); "contract test { function f(uint a) constant returns(bytes1 x) { 1==2; } }");
BOOST_REQUIRE_EQUAL(1, contract.getDefinedFunctions().size()); BOOST_REQUIRE_EQUAL(1, contract.definedFunctions().size());
BOOST_CHECK_EQUAL(getSourcePart(*contract.getDefinedFunctions().front()), BOOST_CHECK_EQUAL(getSourcePart(*contract.definedFunctions().front()),
"function f(uint256 a)constant returns(bytes1 x);"); "function f(uint256 a)constant returns(bytes1 x);");
} }
@ -99,9 +99,9 @@ BOOST_AUTO_TEST_CASE(multiple_functions)
ContractDefinition const& contract = checkInterface(sourceCode); ContractDefinition const& contract = checkInterface(sourceCode);
set<string> expectation({"function f(uint256 a)returns(uint256 d);", set<string> expectation({"function f(uint256 a)returns(uint256 d);",
"function g(uint256 b)returns(uint256 e);"}); "function g(uint256 b)returns(uint256 e);"});
BOOST_REQUIRE_EQUAL(2, contract.getDefinedFunctions().size()); BOOST_REQUIRE_EQUAL(2, contract.definedFunctions().size());
BOOST_CHECK(expectation == set<string>({getSourcePart(*contract.getDefinedFunctions().at(0)), BOOST_CHECK(expectation == set<string>({getSourcePart(*contract.definedFunctions().at(0)),
getSourcePart(*contract.getDefinedFunctions().at(1))})); getSourcePart(*contract.definedFunctions().at(1))}));
} }
BOOST_AUTO_TEST_CASE(exclude_fallback_function) BOOST_AUTO_TEST_CASE(exclude_fallback_function)
@ -120,7 +120,7 @@ BOOST_AUTO_TEST_CASE(events)
"}\n"; "}\n";
ContractDefinition const& contract = checkInterface(sourceCode); ContractDefinition const& contract = checkInterface(sourceCode);
// events should not appear in the Solidity Interface // events should not appear in the Solidity Interface
BOOST_REQUIRE_EQUAL(0, contract.getEvents().size()); BOOST_REQUIRE_EQUAL(0, contract.events().size());
} }
BOOST_AUTO_TEST_CASE(inheritance) BOOST_AUTO_TEST_CASE(inheritance)
@ -137,9 +137,9 @@ BOOST_AUTO_TEST_CASE(inheritance)
ContractDefinition const& contract = checkInterface(sourceCode); ContractDefinition const& contract = checkInterface(sourceCode);
set<string> expectedFunctions({"function baseFunction(uint256 p)returns(uint256 i);", set<string> expectedFunctions({"function baseFunction(uint256 p)returns(uint256 i);",
"function derivedFunction(bytes32 p)returns(bytes32 i);"}); "function derivedFunction(bytes32 p)returns(bytes32 i);"});
BOOST_REQUIRE_EQUAL(2, contract.getDefinedFunctions().size()); BOOST_REQUIRE_EQUAL(2, contract.definedFunctions().size());
BOOST_CHECK(expectedFunctions == set<string>({getSourcePart(*contract.getDefinedFunctions().at(0)), BOOST_CHECK(expectedFunctions == set<string>({getSourcePart(*contract.definedFunctions().at(0)),
getSourcePart(*contract.getDefinedFunctions().at(1))})); getSourcePart(*contract.definedFunctions().at(1))}));
} }
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()

View File

@ -51,19 +51,19 @@ ASTPointer<SourceUnit> parseTextAndResolveNames(std::string const& _source)
resolver.registerDeclarations(*sourceUnit); resolver.registerDeclarations(*sourceUnit);
std::shared_ptr<GlobalContext> globalContext = make_shared<GlobalContext>(); std::shared_ptr<GlobalContext> globalContext = make_shared<GlobalContext>();
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
globalContext->setCurrentContract(*contract); globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*globalContext->getCurrentThis()); resolver.updateDeclaration(*globalContext->currentThis());
resolver.updateDeclaration(*globalContext->getCurrentSuper()); resolver.updateDeclaration(*globalContext->currentSuper());
resolver.resolveNamesAndTypes(*contract); resolver.resolveNamesAndTypes(*contract);
} }
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
globalContext->setCurrentContract(*contract); globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*globalContext->getCurrentThis()); resolver.updateDeclaration(*globalContext->currentThis());
resolver.checkTypeRequirements(*contract); resolver.checkTypeRequirements(*contract);
} }
@ -75,7 +75,7 @@ static ContractDefinition const* retrieveContract(ASTPointer<SourceUnit> _source
{ {
ContractDefinition* contract; ContractDefinition* contract;
unsigned counter = 0; unsigned counter = 0;
for (ASTPointer<ASTNode> const& node: _source->getNodes()) for (ASTPointer<ASTNode> const& node: _source->nodes())
if ((contract = dynamic_cast<ContractDefinition*>(node.get())) && counter == index) if ((contract = dynamic_cast<ContractDefinition*>(node.get())) && counter == index)
return contract; return contract;
@ -86,7 +86,7 @@ static FunctionTypePointer const& retrieveFunctionBySignature(ContractDefinition
std::string const& _signature) std::string const& _signature)
{ {
FixedHash<4> hash(dev::sha3(_signature)); FixedHash<4> hash(dev::sha3(_signature));
return _contract->getInterfaceFunctions()[hash]; return _contract->interfaceFunctions()[hash];
} }
} }
@ -377,11 +377,11 @@ BOOST_AUTO_TEST_CASE(function_no_implementation)
" function functionName(bytes32 input) returns (bytes32 out);\n" " function functionName(bytes32 input) returns (bytes32 out);\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->getNodes(); std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->nodes();
ContractDefinition* contract = dynamic_cast<ContractDefinition*>(nodes[0].get()); ContractDefinition* contract = dynamic_cast<ContractDefinition*>(nodes[0].get());
BOOST_CHECK(contract); BOOST_CHECK(contract);
BOOST_CHECK(!contract->isFullyImplemented()); BOOST_CHECK(!contract->isFullyImplemented());
BOOST_CHECK(!contract->getDefinedFunctions()[0]->isFullyImplemented()); BOOST_CHECK(!contract->definedFunctions()[0]->isFullyImplemented());
} }
BOOST_AUTO_TEST_CASE(abstract_contract) BOOST_AUTO_TEST_CASE(abstract_contract)
@ -392,15 +392,15 @@ BOOST_AUTO_TEST_CASE(abstract_contract)
contract derived is base { function foo() {} } contract derived is base { function foo() {} }
)"; )";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->getNodes(); std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->nodes();
ContractDefinition* base = dynamic_cast<ContractDefinition*>(nodes[0].get()); ContractDefinition* base = dynamic_cast<ContractDefinition*>(nodes[0].get());
ContractDefinition* derived = dynamic_cast<ContractDefinition*>(nodes[1].get()); ContractDefinition* derived = dynamic_cast<ContractDefinition*>(nodes[1].get());
BOOST_CHECK(base); BOOST_CHECK(base);
BOOST_CHECK(!base->isFullyImplemented()); BOOST_CHECK(!base->isFullyImplemented());
BOOST_CHECK(!base->getDefinedFunctions()[0]->isFullyImplemented()); BOOST_CHECK(!base->definedFunctions()[0]->isFullyImplemented());
BOOST_CHECK(derived); BOOST_CHECK(derived);
BOOST_CHECK(derived->isFullyImplemented()); BOOST_CHECK(derived->isFullyImplemented());
BOOST_CHECK(derived->getDefinedFunctions()[0]->isFullyImplemented()); BOOST_CHECK(derived->definedFunctions()[0]->isFullyImplemented());
} }
BOOST_AUTO_TEST_CASE(abstract_contract_with_overload) BOOST_AUTO_TEST_CASE(abstract_contract_with_overload)
@ -411,7 +411,7 @@ BOOST_AUTO_TEST_CASE(abstract_contract_with_overload)
contract derived is base { function foo(uint) {} } contract derived is base { function foo(uint) {} }
)"; )";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->getNodes(); std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->nodes();
ContractDefinition* base = dynamic_cast<ContractDefinition*>(nodes[0].get()); ContractDefinition* base = dynamic_cast<ContractDefinition*>(nodes[0].get());
ContractDefinition* derived = dynamic_cast<ContractDefinition*>(nodes[1].get()); ContractDefinition* derived = dynamic_cast<ContractDefinition*>(nodes[1].get());
BOOST_REQUIRE(base); BOOST_REQUIRE(base);
@ -459,7 +459,7 @@ BOOST_AUTO_TEST_CASE(abstract_contract_constructor_args_not_provided)
} }
)"; )";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name resolving failed");
std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->getNodes(); std::vector<ASTPointer<ASTNode>> nodes = sourceUnit->nodes();
BOOST_CHECK_EQUAL(nodes.size(), 3); BOOST_CHECK_EQUAL(nodes.size(), 3);
ContractDefinition* derived = dynamic_cast<ContractDefinition*>(nodes[2].get()); ContractDefinition* derived = dynamic_cast<ContractDefinition*>(nodes[2].get());
BOOST_CHECK(derived); BOOST_CHECK(derived);
@ -486,10 +486,10 @@ BOOST_AUTO_TEST_CASE(function_canonical_signature)
" }\n" " }\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
BOOST_CHECK_EQUAL("foo(uint256,uint64,bool)", functions[0]->externalSignature()); BOOST_CHECK_EQUAL("foo(uint256,uint64,bool)", functions[0]->externalSignature());
} }
} }
@ -503,10 +503,10 @@ BOOST_AUTO_TEST_CASE(function_canonical_signature_type_aliases)
" }\n" " }\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
if (functions.empty()) if (functions.empty())
continue; continue;
BOOST_CHECK_EQUAL("boo(uint256,bytes32,address)", functions[0]->externalSignature()); BOOST_CHECK_EQUAL("boo(uint256,bytes32,address)", functions[0]->externalSignature());
@ -526,10 +526,10 @@ BOOST_AUTO_TEST_CASE(function_external_types)
} }
})"; })";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
if (functions.empty()) if (functions.empty())
continue; continue;
BOOST_CHECK_EQUAL("boo(uint256,bool,bytes8,bool[2],uint256[],address,address[])", functions[0]->externalSignature()); BOOST_CHECK_EQUAL("boo(uint256,bool,bytes8,bool[2],uint256[],address,address[])", functions[0]->externalSignature());
@ -548,10 +548,10 @@ BOOST_AUTO_TEST_CASE(enum_external_type)
} }
})"; })";
ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed"); ETH_TEST_REQUIRE_NO_THROW(sourceUnit = parseTextAndResolveNames(text), "Parsing and name Resolving failed");
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{ {
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
if (functions.empty()) if (functions.empty())
continue; continue;
BOOST_CHECK_EQUAL("boo(uint8)", functions[0]->externalSignature()); BOOST_CHECK_EQUAL("boo(uint8)", functions[0]->externalSignature());
@ -880,24 +880,24 @@ BOOST_AUTO_TEST_CASE(state_variable_accessors)
BOOST_REQUIRE((contract = retrieveContract(source, 0)) != nullptr); BOOST_REQUIRE((contract = retrieveContract(source, 0)) != nullptr);
FunctionTypePointer function = retrieveFunctionBySignature(contract, "foo()"); FunctionTypePointer function = retrieveFunctionBySignature(contract, "foo()");
BOOST_REQUIRE(function && function->hasDeclaration()); BOOST_REQUIRE(function && function->hasDeclaration());
auto returnParams = function->getReturnParameterTypeNames(); auto returnParams = function->returnParameterTypeNames();
BOOST_CHECK_EQUAL(returnParams.at(0), "uint256"); BOOST_CHECK_EQUAL(returnParams.at(0), "uint256");
BOOST_CHECK(function->isConstant()); BOOST_CHECK(function->isConstant());
function = retrieveFunctionBySignature(contract, "map(uint256)"); function = retrieveFunctionBySignature(contract, "map(uint256)");
BOOST_REQUIRE(function && function->hasDeclaration()); BOOST_REQUIRE(function && function->hasDeclaration());
auto params = function->getParameterTypeNames(); auto params = function->parameterTypeNames();
BOOST_CHECK_EQUAL(params.at(0), "uint256"); BOOST_CHECK_EQUAL(params.at(0), "uint256");
returnParams = function->getReturnParameterTypeNames(); returnParams = function->returnParameterTypeNames();
BOOST_CHECK_EQUAL(returnParams.at(0), "bytes4"); BOOST_CHECK_EQUAL(returnParams.at(0), "bytes4");
BOOST_CHECK(function->isConstant()); BOOST_CHECK(function->isConstant());
function = retrieveFunctionBySignature(contract, "multiple_map(uint256,uint256)"); function = retrieveFunctionBySignature(contract, "multiple_map(uint256,uint256)");
BOOST_REQUIRE(function && function->hasDeclaration()); BOOST_REQUIRE(function && function->hasDeclaration());
params = function->getParameterTypeNames(); params = function->parameterTypeNames();
BOOST_CHECK_EQUAL(params.at(0), "uint256"); BOOST_CHECK_EQUAL(params.at(0), "uint256");
BOOST_CHECK_EQUAL(params.at(1), "uint256"); BOOST_CHECK_EQUAL(params.at(1), "uint256");
returnParams = function->getReturnParameterTypeNames(); returnParams = function->returnParameterTypeNames();
BOOST_CHECK_EQUAL(returnParams.at(0), "bytes4"); BOOST_CHECK_EQUAL(returnParams.at(0), "bytes4");
BOOST_CHECK(function->isConstant()); BOOST_CHECK(function->isConstant());
} }

View File

@ -49,9 +49,9 @@ public:
ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), "Parsing failed");
if (_userDocumentation) if (_userDocumentation)
generatedDocumentationString = m_compilerStack.getMetadata("", DocumentationType::NatspecUser); generatedDocumentationString = m_compilerStack.metadata("", DocumentationType::NatspecUser);
else else
generatedDocumentationString = m_compilerStack.getMetadata("", DocumentationType::NatspecDev); generatedDocumentationString = m_compilerStack.metadata("", DocumentationType::NatspecDev);
Json::Value generatedDocumentation; Json::Value generatedDocumentation;
m_reader.parse(generatedDocumentationString, generatedDocumentation); m_reader.parse(generatedDocumentationString, generatedDocumentation);
Json::Value expectedDocumentation; Json::Value expectedDocumentation;

View File

@ -43,7 +43,7 @@ ASTPointer<ContractDefinition> parseText(std::string const& _source)
{ {
Parser parser; Parser parser;
ASTPointer<SourceUnit> sourceUnit = parser.parse(std::make_shared<Scanner>(CharStream(_source))); ASTPointer<SourceUnit> sourceUnit = parser.parse(std::make_shared<Scanner>(CharStream(_source)));
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ASTPointer<ContractDefinition> contract = dynamic_pointer_cast<ContractDefinition>(node)) if (ASTPointer<ContractDefinition> contract = dynamic_pointer_cast<ContractDefinition>(node))
return contract; return contract;
BOOST_FAIL("No contract found in source."); BOOST_FAIL("No contract found in source.");
@ -53,7 +53,7 @@ ASTPointer<ContractDefinition> parseText(std::string const& _source)
static void checkFunctionNatspec(ASTPointer<FunctionDefinition> _function, static void checkFunctionNatspec(ASTPointer<FunctionDefinition> _function,
std::string const& _expectedDoc) std::string const& _expectedDoc)
{ {
auto doc = _function->getDocumentation(); auto doc = _function->documentation();
BOOST_CHECK_MESSAGE(doc != nullptr, "Function does not have Natspec Doc as expected"); BOOST_CHECK_MESSAGE(doc != nullptr, "Function does not have Natspec Doc as expected");
BOOST_CHECK_EQUAL(*doc, _expectedDoc); BOOST_CHECK_EQUAL(*doc, _expectedDoc);
} }
@ -169,7 +169,7 @@ BOOST_AUTO_TEST_CASE(function_natspec_documentation)
" function functionName(bytes32 input) returns (bytes32 out) {}\n" " function functionName(bytes32 input) returns (bytes32 out) {}\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed");
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "This is a test function"); checkFunctionNatspec(function, "This is a test function");
} }
@ -184,9 +184,9 @@ BOOST_AUTO_TEST_CASE(function_normal_comments)
" function functionName(bytes32 input) returns (bytes32 out) {}\n" " function functionName(bytes32 input) returns (bytes32 out) {}\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed");
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, BOOST_CHECK_MESSAGE(function->documentation() == nullptr,
"Should not have gotten a Natspecc comment for this function"); "Should not have gotten a Natspecc comment for this function");
} }
@ -206,7 +206,7 @@ BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation)
" function functionName4(bytes32 input) returns (bytes32 out) {}\n" " function functionName4(bytes32 input) returns (bytes32 out) {}\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed");
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "This is test function 1"); checkFunctionNatspec(function, "This is test function 1");
@ -215,7 +215,7 @@ BOOST_AUTO_TEST_CASE(multiple_functions_natspec_documentation)
checkFunctionNatspec(function, "This is test function 2"); checkFunctionNatspec(function, "This is test function 2");
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(2), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(2), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(function->getDocumentation() == nullptr, BOOST_CHECK_MESSAGE(function->documentation() == nullptr,
"Should not have gotten natspec comment for functionName3()"); "Should not have gotten natspec comment for functionName3()");
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(3), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(3), "Failed to retrieve function");
@ -233,7 +233,7 @@ BOOST_AUTO_TEST_CASE(multiline_function_documentation)
" function functionName1(bytes32 input) returns (bytes32 out) {}\n" " function functionName1(bytes32 input) returns (bytes32 out) {}\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed");
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "This is a test function\n" checkFunctionNatspec(function, "This is a test function\n"
@ -258,7 +258,7 @@ BOOST_AUTO_TEST_CASE(natspec_comment_in_function_body)
" function fun(bytes32 input) returns (bytes32 out) {}\n" " function fun(bytes32 input) returns (bytes32 out) {}\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed");
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
checkFunctionNatspec(function, "fun1 description"); checkFunctionNatspec(function, "fun1 description");
@ -284,10 +284,10 @@ BOOST_AUTO_TEST_CASE(natspec_docstring_between_keyword_and_signature)
" }\n" " }\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed");
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(!function->getDocumentation(), BOOST_CHECK_MESSAGE(!function->documentation(),
"Shouldn't get natspec docstring for this function"); "Shouldn't get natspec docstring for this function");
} }
@ -307,10 +307,10 @@ BOOST_AUTO_TEST_CASE(natspec_docstring_after_signature)
" }\n" " }\n"
"}\n"; "}\n";
ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed"); ETH_TEST_REQUIRE_NO_THROW(contract = parseText(text), "Parsing failed");
auto functions = contract->getDefinedFunctions(); auto functions = contract->definedFunctions();
ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function"); ETH_TEST_REQUIRE_NO_THROW(function = functions.at(0), "Failed to retrieve function");
BOOST_CHECK_MESSAGE(!function->getDocumentation(), BOOST_CHECK_MESSAGE(!function->documentation(),
"Shouldn't get natspec docstring for this function"); "Shouldn't get natspec docstring for this function");
} }

View File

@ -35,49 +35,49 @@ BOOST_AUTO_TEST_SUITE(SolidityScanner)
BOOST_AUTO_TEST_CASE(test_empty) BOOST_AUTO_TEST_CASE(test_empty)
{ {
Scanner scanner(CharStream("")); Scanner scanner(CharStream(""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
} }
BOOST_AUTO_TEST_CASE(smoke_test) BOOST_AUTO_TEST_CASE(smoke_test)
{ {
Scanner scanner(CharStream("function break;765 \t \"string1\",'string2'\nidentifier1")); Scanner scanner(CharStream("function break;765 \t \"string1\",'string2'\nidentifier1"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Function); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Break); BOOST_CHECK_EQUAL(scanner.next(), Token::Break);
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number); BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "765"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "765");
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string1"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "string1");
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma); BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string2"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "string2");
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "identifier1"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "identifier1");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
} }
BOOST_AUTO_TEST_CASE(string_escapes) BOOST_AUTO_TEST_CASE(string_escapes)
{ {
Scanner scanner(CharStream(" { \"a\\x61\"")); Scanner scanner(CharStream(" { \"a\\x61\""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBrace); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "aa"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "aa");
} }
BOOST_AUTO_TEST_CASE(string_escapes_with_zero) BOOST_AUTO_TEST_CASE(string_escapes_with_zero)
{ {
Scanner scanner(CharStream(" { \"a\\x61\\x00abc\"")); Scanner scanner(CharStream(" { \"a\\x61\\x00abc\""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBrace); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral); BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), std::string("aa\0abc", 6)); BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("aa\0abc", 6));
} }
BOOST_AUTO_TEST_CASE(string_escape_illegal) BOOST_AUTO_TEST_CASE(string_escape_illegal)
{ {
Scanner scanner(CharStream(" bla \"\\x6rf\" (illegalescape)")); Scanner scanner(CharStream(" bla \"\\x6rf\" (illegalescape)"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal); BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), ""); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "");
// TODO recovery from illegal tokens should be improved // TODO recovery from illegal tokens should be improved
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal); BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
@ -88,11 +88,11 @@ BOOST_AUTO_TEST_CASE(string_escape_illegal)
BOOST_AUTO_TEST_CASE(hex_numbers) BOOST_AUTO_TEST_CASE(hex_numbers)
{ {
Scanner scanner(CharStream("var x = 0x765432536763762734623472346;")); Scanner scanner(CharStream("var x = 0x765432536763762734623472346;"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Var); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Var);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Assign); BOOST_CHECK_EQUAL(scanner.next(), Token::Assign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number); BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "0x765432536763762734623472346"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "0x765432536763762734623472346");
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
} }
@ -100,23 +100,23 @@ BOOST_AUTO_TEST_CASE(hex_numbers)
BOOST_AUTO_TEST_CASE(negative_numbers) BOOST_AUTO_TEST_CASE(negative_numbers)
{ {
Scanner scanner(CharStream("var x = -.2 + -0x78 + -7.3 + 8.9;")); Scanner scanner(CharStream("var x = -.2 + -0x78 + -7.3 + 8.9;"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Var); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Var);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Assign); BOOST_CHECK_EQUAL(scanner.next(), Token::Assign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number); BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), ".2"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), ".2");
BOOST_CHECK_EQUAL(scanner.next(), Token::Add); BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number); BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "0x78"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "0x78");
BOOST_CHECK_EQUAL(scanner.next(), Token::Add); BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number); BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "7.3"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "7.3");
BOOST_CHECK_EQUAL(scanner.next(), Token::Add); BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number); BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "8.9"); BOOST_CHECK_EQUAL(scanner.currentLiteral(), "8.9");
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
} }
@ -124,22 +124,22 @@ BOOST_AUTO_TEST_CASE(negative_numbers)
BOOST_AUTO_TEST_CASE(locations) BOOST_AUTO_TEST_CASE(locations)
{ {
Scanner scanner(CharStream("function_identifier has ; -0x743/*comment*/\n ident //comment")); Scanner scanner(CharStream("function_identifier has ; -0x743/*comment*/\n ident //comment"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 0); BOOST_CHECK_EQUAL(scanner.currentLocation().start, 0);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 19); BOOST_CHECK_EQUAL(scanner.currentLocation().end, 19);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 20); BOOST_CHECK_EQUAL(scanner.currentLocation().start, 20);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 23); BOOST_CHECK_EQUAL(scanner.currentLocation().end, 23);
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon); BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 24); BOOST_CHECK_EQUAL(scanner.currentLocation().start, 24);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 25); BOOST_CHECK_EQUAL(scanner.currentLocation().end, 25);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub); BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number); BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 27); BOOST_CHECK_EQUAL(scanner.currentLocation().start, 27);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 32); BOOST_CHECK_EQUAL(scanner.currentLocation().end, 32);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 45); BOOST_CHECK_EQUAL(scanner.currentLocation().start, 45);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 50); BOOST_CHECK_EQUAL(scanner.currentLocation().end, 50);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
} }
@ -147,7 +147,7 @@ BOOST_AUTO_TEST_CASE(ambiguities)
{ {
// test scanning of some operators which need look-ahead // test scanning of some operators which need look-ahead
Scanner scanner(CharStream("<=""<""+ +=a++ =>""<<")); Scanner scanner(CharStream("<=""<""+ +=a++ =>""<<"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LessThanOrEqual); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LessThanOrEqual);
BOOST_CHECK_EQUAL(scanner.next(), Token::LessThan); BOOST_CHECK_EQUAL(scanner.next(), Token::LessThan);
BOOST_CHECK_EQUAL(scanner.next(), Token::Add); BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssignAdd); BOOST_CHECK_EQUAL(scanner.next(), Token::AssignAdd);
@ -160,25 +160,25 @@ BOOST_AUTO_TEST_CASE(ambiguities)
BOOST_AUTO_TEST_CASE(documentation_comments_parsed_begin) BOOST_AUTO_TEST_CASE(documentation_comments_parsed_begin)
{ {
Scanner scanner(CharStream("/// Send $(value / 1000) chocolates to the user")); Scanner scanner(CharStream("/// Send $(value / 1000) chocolates to the user"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
} }
BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed_begin) BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed_begin)
{ {
Scanner scanner(CharStream("/** Send $(value / 1000) chocolates to the user*/")); Scanner scanner(CharStream("/** Send $(value / 1000) chocolates to the user*/"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
} }
BOOST_AUTO_TEST_CASE(documentation_comments_parsed) BOOST_AUTO_TEST_CASE(documentation_comments_parsed)
{ {
Scanner scanner(CharStream("some other tokens /// Send $(value / 1000) chocolates to the user")); Scanner scanner(CharStream("some other tokens /// Send $(value / 1000) chocolates to the user"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
} }
BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed) BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed)
@ -186,11 +186,11 @@ BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed)
Scanner scanner(CharStream("some other tokens /**\n" Scanner scanner(CharStream("some other tokens /**\n"
"* Send $(value / 1000) chocolates to the user\n" "* Send $(value / 1000) chocolates to the user\n"
"*/")); "*/"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
} }
BOOST_AUTO_TEST_CASE(multiline_documentation_no_stars) BOOST_AUTO_TEST_CASE(multiline_documentation_no_stars)
@ -198,11 +198,11 @@ BOOST_AUTO_TEST_CASE(multiline_documentation_no_stars)
Scanner scanner(CharStream("some other tokens /**\n" Scanner scanner(CharStream("some other tokens /**\n"
" Send $(value / 1000) chocolates to the user\n" " Send $(value / 1000) chocolates to the user\n"
"*/")); "*/"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
} }
BOOST_AUTO_TEST_CASE(multiline_documentation_whitespace_hell) BOOST_AUTO_TEST_CASE(multiline_documentation_whitespace_hell)
@ -210,39 +210,39 @@ BOOST_AUTO_TEST_CASE(multiline_documentation_whitespace_hell)
Scanner scanner(CharStream("some other tokens /** \t \r \n" Scanner scanner(CharStream("some other tokens /** \t \r \n"
"\t \r * Send $(value / 1000) chocolates to the user\n" "\t \r * Send $(value / 1000) chocolates to the user\n"
"*/")); "*/"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS); BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "Send $(value / 1000) chocolates to the user"); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
} }
BOOST_AUTO_TEST_CASE(comment_before_eos) BOOST_AUTO_TEST_CASE(comment_before_eos)
{ {
Scanner scanner(CharStream("//")); Scanner scanner(CharStream("//"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
} }
BOOST_AUTO_TEST_CASE(documentation_comment_before_eos) BOOST_AUTO_TEST_CASE(documentation_comment_before_eos)
{ {
Scanner scanner(CharStream("///")); Scanner scanner(CharStream("///"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
} }
BOOST_AUTO_TEST_CASE(empty_multiline_comment) BOOST_AUTO_TEST_CASE(empty_multiline_comment)
{ {
Scanner scanner(CharStream("/**/")); Scanner scanner(CharStream("/**/"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
} }
BOOST_AUTO_TEST_CASE(empty_multiline_documentation_comment_before_eos) BOOST_AUTO_TEST_CASE(empty_multiline_documentation_comment_before_eos)
{ {
Scanner scanner(CharStream("/***/")); Scanner scanner(CharStream("/***/"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), ""); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
} }
BOOST_AUTO_TEST_CASE(comments_mixed_in_sequence) BOOST_AUTO_TEST_CASE(comments_mixed_in_sequence)
@ -250,15 +250,15 @@ BOOST_AUTO_TEST_CASE(comments_mixed_in_sequence)
Scanner scanner(CharStream("hello_world ///documentation comment \n" Scanner scanner(CharStream("hello_world ///documentation comment \n"
"//simple comment \n" "//simple comment \n"
"<<")); "<<"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::Identifier); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::SHL); BOOST_CHECK_EQUAL(scanner.next(), Token::SHL);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "documentation comment "); BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "documentation comment ");
} }
BOOST_AUTO_TEST_CASE(ether_subdenominations) BOOST_AUTO_TEST_CASE(ether_subdenominations)
{ {
Scanner scanner(CharStream("wei szabo finney ether")); Scanner scanner(CharStream("wei szabo finney ether"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::SubWei); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::SubWei);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubSzabo); BOOST_CHECK_EQUAL(scanner.next(), Token::SubSzabo);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubFinney); BOOST_CHECK_EQUAL(scanner.next(), Token::SubFinney);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubEther); BOOST_CHECK_EQUAL(scanner.next(), Token::SubEther);
@ -267,7 +267,7 @@ BOOST_AUTO_TEST_CASE(ether_subdenominations)
BOOST_AUTO_TEST_CASE(time_subdenominations) BOOST_AUTO_TEST_CASE(time_subdenominations)
{ {
Scanner scanner(CharStream("seconds minutes hours days weeks years")); Scanner scanner(CharStream("seconds minutes hours days weeks years"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::SubSecond); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::SubSecond);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubMinute); BOOST_CHECK_EQUAL(scanner.next(), Token::SubMinute);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubHour); BOOST_CHECK_EQUAL(scanner.next(), Token::SubHour);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubDay); BOOST_CHECK_EQUAL(scanner.next(), Token::SubDay);
@ -278,7 +278,7 @@ BOOST_AUTO_TEST_CASE(time_subdenominations)
BOOST_AUTO_TEST_CASE(time_after) BOOST_AUTO_TEST_CASE(time_after)
{ {
Scanner scanner(CharStream("after 1")); Scanner scanner(CharStream("after 1"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::After); BOOST_CHECK_EQUAL(scanner.currentToken(), Token::After);
} }
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()

View File

@ -41,13 +41,13 @@ BOOST_AUTO_TEST_CASE(storage_layout_simple)
{string("second"), Type::fromElementaryTypeName("uint120")}, {string("second"), Type::fromElementaryTypeName("uint120")},
{string("wraps"), Type::fromElementaryTypeName("uint16")} {string("wraps"), Type::fromElementaryTypeName("uint16")}
})); }));
BOOST_REQUIRE_EQUAL(u256(2), members.getStorageSize()); BOOST_REQUIRE_EQUAL(u256(2), members.storageSize());
BOOST_REQUIRE(members.getMemberStorageOffset("first") != nullptr); BOOST_REQUIRE(members.memberStorageOffset("first") != nullptr);
BOOST_REQUIRE(members.getMemberStorageOffset("second") != nullptr); BOOST_REQUIRE(members.memberStorageOffset("second") != nullptr);
BOOST_REQUIRE(members.getMemberStorageOffset("wraps") != nullptr); BOOST_REQUIRE(members.memberStorageOffset("wraps") != nullptr);
BOOST_CHECK(*members.getMemberStorageOffset("first") == make_pair(u256(0), unsigned(0))); BOOST_CHECK(*members.memberStorageOffset("first") == make_pair(u256(0), unsigned(0)));
BOOST_CHECK(*members.getMemberStorageOffset("second") == make_pair(u256(0), unsigned(16))); BOOST_CHECK(*members.memberStorageOffset("second") == make_pair(u256(0), unsigned(16)));
BOOST_CHECK(*members.getMemberStorageOffset("wraps") == make_pair(u256(1), unsigned(0))); BOOST_CHECK(*members.memberStorageOffset("wraps") == make_pair(u256(1), unsigned(0)));
} }
BOOST_AUTO_TEST_CASE(storage_layout_mapping) BOOST_AUTO_TEST_CASE(storage_layout_mapping)
@ -64,26 +64,26 @@ BOOST_AUTO_TEST_CASE(storage_layout_mapping)
Type::fromElementaryTypeName("uint8") Type::fromElementaryTypeName("uint8")
)}, )},
})); }));
BOOST_REQUIRE_EQUAL(u256(4), members.getStorageSize()); BOOST_REQUIRE_EQUAL(u256(4), members.storageSize());
BOOST_REQUIRE(members.getMemberStorageOffset("first") != nullptr); BOOST_REQUIRE(members.memberStorageOffset("first") != nullptr);
BOOST_REQUIRE(members.getMemberStorageOffset("second") != nullptr); BOOST_REQUIRE(members.memberStorageOffset("second") != nullptr);
BOOST_REQUIRE(members.getMemberStorageOffset("third") != nullptr); BOOST_REQUIRE(members.memberStorageOffset("third") != nullptr);
BOOST_REQUIRE(members.getMemberStorageOffset("final") != nullptr); BOOST_REQUIRE(members.memberStorageOffset("final") != nullptr);
BOOST_CHECK(*members.getMemberStorageOffset("first") == make_pair(u256(0), unsigned(0))); BOOST_CHECK(*members.memberStorageOffset("first") == make_pair(u256(0), unsigned(0)));
BOOST_CHECK(*members.getMemberStorageOffset("second") == make_pair(u256(1), unsigned(0))); BOOST_CHECK(*members.memberStorageOffset("second") == make_pair(u256(1), unsigned(0)));
BOOST_CHECK(*members.getMemberStorageOffset("third") == make_pair(u256(2), unsigned(0))); BOOST_CHECK(*members.memberStorageOffset("third") == make_pair(u256(2), unsigned(0)));
BOOST_CHECK(*members.getMemberStorageOffset("final") == make_pair(u256(3), unsigned(0))); BOOST_CHECK(*members.memberStorageOffset("final") == make_pair(u256(3), unsigned(0)));
} }
BOOST_AUTO_TEST_CASE(storage_layout_arrays) BOOST_AUTO_TEST_CASE(storage_layout_arrays)
{ {
BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(1), 32).getStorageSize() == 1); BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(1), 32).storageSize() == 1);
BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(1), 33).getStorageSize() == 2); BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(1), 33).storageSize() == 2);
BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(2), 31).getStorageSize() == 2); BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(2), 31).storageSize() == 2);
BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(7), 8).getStorageSize() == 2); BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(7), 8).storageSize() == 2);
BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(7), 9).getStorageSize() == 3); BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(7), 9).storageSize() == 3);
BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(31), 9).getStorageSize() == 9); BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(31), 9).storageSize() == 9);
BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(32), 9).getStorageSize() == 9); BOOST_CHECK(ArrayType(DataLocation::Storage, make_shared<FixedBytesType>(32), 9).storageSize() == 9);
} }
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()

View File

@ -59,7 +59,7 @@ public:
m_compiler.reset(false, m_addStandardSources); m_compiler.reset(false, m_addStandardSources);
m_compiler.addSource("", _sourceCode); m_compiler.addSource("", _sourceCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed"); ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize, m_optimizeRuns), "Compiling contract failed");
bytes code = m_compiler.getBytecode(_contractName); bytes code = m_compiler.bytecode(_contractName);
sendMessage(code + _arguments, true, _value); sendMessage(code + _arguments, true, _value);
return m_output; return m_output;
} }