<commit_before>/*
    This file is part of cpp-ethereum.

    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <<EMAIL>>
 * @date 2014
 * Solidity abstract syntax tree.
 */

#include <algorithm>
#include <boost/range/adaptor/reversed.hpp>
#include <libsolidity/Utils.h>
#include <libsolidity/AST.h>
#include <libsolidity/ASTVisitor.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/AST_accept.h>

#include <libdevcore/SHA3.h>

using namespace std;

namespace dev
{
namespace solidity
{

TypeError ASTNode::createTypeError(string const& _description) const
{
	return TypeError() << errinfo_sourceLocation(getLocation()) << errinfo_comment(_description);
}

TypePointer ContractDefinition::getType(ContractDefinition const* _currentContract) const
{
	return make_shared<TypeType>(make_shared<ContractType>(*this), _currentContract);
}

void ContractDefinition::checkTypeRequirements()
{
	for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: getBaseContracts())
		baseSpecifier->checkTypeRequirements();

	checkDuplicateFunctions();
	checkIllegalOverrides();
	checkAbstractFunctions();
	checkAbstractConstructors();

	FunctionDefinition const* constructor = getConstructor();
	if (constructor && !constructor->getReturnParameters().empty())
		BOOST_THROW_EXCEPTION(constructor->getReturnParameterList()->createTypeError(
									"Non-empty \"returns\" directive for constructor."));

	FunctionDefinition const* fallbackFunction = nullptr;
	for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
	{
		if (function->getName().empty())
		{
			if (fallbackFunction)
				BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_comment("Only one fallback function is allowed."));
			else
			{
				fallbackFunction = function.get();
				if (!fallbackFunction->getParameters().empty())
					BOOST_THROW_EXCEPTION(fallbackFunction->getParameterList().createTypeError("Fallback function cannot take parameters."));
			}
		}
		if (!function->isFullyImplemented())
			setFullyImplemented(false);
	}
	for (ASTPointer<ModifierDefinition> const& modifier: getFunctionModifiers())
		modifier->checkTypeRequirements();

	for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
		function->checkTypeRequirements();

	for (ASTPointer<VariableDeclaration> const& variable: m_stateVariables)
		variable->checkTypeRequirements();

	checkExternalTypeClashes();
	// check for hash collisions in function signatures
	set<FixedHash<4>> hashes;
	for (auto const& it: getInterfaceFunctionList())
	{
		FixedHash<4> const& hash = it.first;
		if (hashes.count(hash))
			BOOST_THROW_EXCEPTION(createTypeError(
				string("Function signature hash collision for ") + it.second->externalSignature()
			));
		hashes.insert(hash);
	}
}

map<FixedHash<4>, FunctionTypePointer> ContractDefinition::getInterfaceFunctions() const
{
	auto exportedFunctionList = getInterfaceFunctionList();

	map<FixedHash<4>, FunctionTypePointer> exportedFunctions;
	for (auto const& it: exportedFunctionList)
		exportedFunctions.insert(it);

	solAssert(exportedFunctionList.size() == exportedFunctions.size(),
			  "Hash collision at Function Definition Hash calculation");

	return exportedFunctions;
}

FunctionDefinition const* ContractDefinition::getConstructor() const
{
	for (ASTPointer<FunctionDefinition> const& f: m_definedFunctions)
		if (f->isConstructor())
			return f.get();
	return nullptr;
}

FunctionDefinition const* ContractDefinition::getFallbackFunction() const
{
	for (ContractDefinition const* contract: getLinearizedBaseContracts())
		for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
			if (f->getName().empty())
				return f.get();
	return nullptr;
}

void ContractDefinition::checkDuplicateFunctions() const
{
	/// Checks that two functions with the same name defined in this contract have different
	/// argument types and that there is at most one constructor.
	map<string, vector<FunctionDefinition const*>> functions;
	for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
		functions[function->getName()].push_back(function.get());

	if (functions[getName()].size() > 1)
	{
		SecondarySourceLocation ssl;
		auto it = functions[getName()].begin();
		++it;
		for (; it != functions[getName()].end(); ++it)
			ssl.append("Another declaration is here:", (*it)->getLocation());

		BOOST_THROW_EXCEPTION(
			DeclarationError() <<
			errinfo_sourceLocation(functions[getName()].front()->getLocation()) <<
			errinfo_comment("More than one constructor defined.") <<
			errinfo_secondarySourceLocation(ssl)
		);
	}
	for (auto const& it: functions)
	{
		vector<FunctionDefinition const*> const& overloads = it.second;
		for (size_t i = 0; i < overloads.size(); ++i)
			for (size_t j = i + 1; j < overloads.size(); ++j)
				if (FunctionType(*overloads[i]).hasEqualArgumentTypes(FunctionType(*overloads[j])))
					BOOST_THROW_EXCEPTION(
						DeclarationError() <<
						errinfo_sourceLocation(overloads[j]->getLocation()) <<
						errinfo_comment("Function with same name and arguments defined twice.") <<
						errinfo_secondarySourceLocation(SecondarySourceLocation().append(
							"Other declaration is here:", overloads[i]->getLocation()))
					);
	}
}

void ContractDefinition::checkAbstractFunctions()
{
	map<string, bool> functions;

	// Search from base to derived
	for (ContractDefinition const* contract: boost::adaptors::reverse(getLinearizedBaseContracts()))
		for (ASTPointer<FunctionDefinition> const& function: contract->getDefinedFunctions())
		{
			string const& name = function->getName();
			if (!function->isFullyImplemented() && functions.count(name) && functions[name])
				BOOST_THROW_EXCEPTION(function->createTypeError("Redeclaring an already implemented function as abstract"));
			functions[name] = function->isFullyImplemented();
		}

	for (auto const& it: functions)
		if (!it.second)
		{
			setFullyImplemented(false);
			break;
		}
}

void ContractDefinition::checkAbstractConstructors()
{
	set<ContractDefinition const*> argumentsNeeded;
	// check that we get arguments for all base constructors that need it.
	// If not mark the contract as abstract (not fully implemented)

	vector<ContractDefinition const*> const& bases = getLinearizedBaseContracts();
	for (ContractDefinition const* contract: bases)
		if (FunctionDefinition const* constructor = contract->getConstructor())
			if (contract != this && !constructor->getParameters().empty())
				argumentsNeeded.insert(contract);

	for (ContractDefinition const* contract: bases)
	{
		if (FunctionDefinition const* constructor = contract->getConstructor())
			for (auto const& modifier: constructor->getModifiers())
			{
				auto baseContract = dynamic_cast<ContractDefinition const*>(
					&modifier->getName()->getReferencedDeclaration()
				);
				if (baseContract)
					argumentsNeeded.erase(baseContract);
			}


		for (ASTPointer<InheritanceSpecifier> const& base: contract->getBaseContracts())
		{
			auto baseContract = dynamic_cast<ContractDefinition const*>(
				&base->getName()->getReferencedDeclaration()
			);
			solAssert(baseContract, "");
			if (!base->getArguments().empty())
				argumentsNeeded.erase(baseContract);
		}
	}
	if (!argumentsNeeded.empty())
		setFullyImplemented(false);
}

void ContractDefinition::checkIllegalOverrides() const
{
	// TODO unify this at a later point. for this we need to put the constness and the access specifier
	// into the types
	map<string, vector<FunctionDefinition const*>> functions;
	map<string, ModifierDefinition const*> modifiers;

	// We search from derived to base, so the stored item causes the error.
	for (ContractDefinition const* contract: getLinearizedBaseContracts())
	{
		for (ASTPointer<FunctionDefinition> const& function: contract->getDefinedFunctions())
		{
			if (function->isConstructor())
				continue; // constructors can neither be overridden nor override anything
			string const& name = function->getName();
			if (modifiers.count(name))
				BOOST_THROW_EXCEPTION(modifiers[name]->createTypeError("Override changes function to modifier."));
			FunctionType functionType(*function);
			// function should not change the return type
			for (FunctionDefinition const* overriding: functions[name])
			{
				FunctionType overridingType(*overriding);
				if (!overridingType.hasEqualArgumentTypes(functionType))
					continue;
				if (
					overriding->getVisibility() != function->getVisibility() ||
					overriding->isDeclaredConst() != function->isDeclaredConst() ||
					overridingType != functionType
				)
					BOOST_THROW_EXCEPTION(overriding->createTypeError("Override changes extended function signature."));
			}
			functions[name].push_back(function.get());
		}
		for (ASTPointer<ModifierDefinition> const& modifier: contract->getFunctionModifiers())
		{
			string const& name = modifier->getName();
			ModifierDefinition const*& override = modifiers[name];
			if (!override)
				override = modifier.get();
			else if (ModifierType(*override) != ModifierType(*modifier))
				BOOST_THROW_EXCEPTION(override->createTypeError("Override changes modifier signature."));
			if (!functions[name].empty())
				BOOST_THROW_EXCEPTION(override->createTypeError("Override changes modifier to function."));
		}
	}
}

void ContractDefinition::checkExternalTypeClashes() const
{
	map<string, vector<pair<Declaration const*, shared_ptr<FunctionType>>>> externalDeclarations;
	for (ContractDefinition const* contract: getLinearizedBaseContracts())
	{
		for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
			if (f->isPartOfExternalInterface())
			{
				auto functionType = make_shared<FunctionType>(*f);
				externalDeclarations[functionType->externalSignature(f->getName())].push_back(
					make_pair(f.get(), functionType)
				);
			}
		for (ASTPointer<VariableDeclaration> const& v: contract->getStateVariables())
			if (v->isPartOfExternalInterface())
			{
				auto functionType = make_shared<FunctionType>(*v);
				externalDeclarations[functionType->externalSignature(v->getName())].push_back(
					make_pair(v.get(), functionType)
				);
			}
	}
	for (auto const& it: externalDeclarations)
		for (size_t i = 0; i < it.second.size(); ++i)
			for (size_t j = i + 1; j < it.second.size(); ++j)
				if (!it.second[i].second->hasEqualArgumentTypes(*it.second[j].second))
					BOOST_THROW_EXCEPTION(it.second[j].first->createTypeError(
						"Function overload clash during conversion to external types for arguments."
					));
}

vector<ASTPointer<EventDefinition>> const& ContractDefinition::getInterfaceEvents() const
{
	if (!m_interfaceEvents)
	{
		set<string> eventsSeen;
		m_interfaceEvents.reset(new vector<ASTPointer<EventDefinition>>());
		for (ContractDefinition const* contract: getLinearizedBaseContracts())
			for (ASTPointer<EventDefinition> const& e: contract->getEvents())
				if (eventsSeen.count(e->getName()) == 0)
				{
					eventsSeen.insert(e->getName());
					m_interfaceEvents->push_back(e);
				}
	}
	return *m_interfaceEvents;
}

vector<pair<FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::getInterfaceFunctionList() const
{
	if (!m_interfaceFunctionList)
	{
		set<string> functionsSeen;
		set<string> signaturesSeen;
		m_interfaceFunctionList.reset(new vector<pair<FixedHash<4>, FunctionTypePointer>>());
		for (ContractDefinition const* contract: getLinearizedBaseContracts())
		{
			for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
			{
				string functionSignature = f->externalSignature();
				if (f->isPartOfExternalInterface() && signaturesSeen.count(functionSignature) == 0)
				{
					functionsSeen.insert(f->getName());
					signaturesSeen.insert(functionSignature);
					FixedHash<4> hash(dev::sha3(functionSignature));
					m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*f, false)));
				}
			}

			for (ASTPointer<VariableDeclaration> const& v: contract->getStateVariables())
				if (functionsSeen.count(v->getName()) == 0 && v->isPartOfExternalInterface())
				{
					FunctionType ftype(*v);
					solAssert(v->getType().get(), "");
					functionsSeen.insert(v->getName());
					FixedHash<4> hash(dev::sha3(ftype.externalSignature(v->getName())));
					m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*v)));
				}
		}
	}
	return *m_interfaceFunctionList;
}

vector<Declaration const*> const& ContractDefinition::getInheritableMembers() const
{
	if (!m_inheritableMembers)
	{
		set<string> memberSeen;
		m_inheritableMembers.reset(new vector<Declaration const*>());
		auto addInheritableMember = [&](Declaration const* _decl)
		{
			if (memberSeen.count(_decl->getName()) == 0 && _decl->isVisibleInDerivedContracts())
			{
				memberSeen.insert(_decl->getName());
				m_inheritableMembers->push_back(_decl);
			}
		};

		for (ASTPointer<FunctionDefinition> const& f: getDefinedFunctions())
			addInheritableMember(f.get());

		for (ASTPointer<VariableDeclaration> const& v: getStateVariables())
			addInheritableMember(v.get());

		for (ASTPointer<StructDefinition> const& s: getDefinedStructs())
			addInheritableMember(s.get());
	}
	return *m_inheritableMembers;
}

TypePointer EnumValue::getType(ContractDefinition const*) const
{
	EnumDefinition const* parentDef = dynamic_cast<EnumDefinition const*>(getScope());
	solAssert(parentDef, "Enclosing Scope of EnumValue was not set");
	return make_shared<EnumType>(*parentDef);
}

void InheritanceSpecifier::checkTypeRequirements()
{
	m_baseName->checkTypeRequirements(nullptr);
	for (ASTPointer<Expression> const& argument: m_arguments)
		argument->checkTypeRequirements(nullptr);

	ContractDefinition const* base = dynamic_cast<ContractDefinition const*>(&m_baseName->getReferencedDeclaration());
	solAssert(base, "Base contract not available.");
	TypePointers parameterTypes = ContractType(*base).getConstructorType()->getParameterTypes();
	if (!m_arguments.empty() && parameterTypes.size() != m_arguments.size())
		BOOST_THROW_EXCEPTION(createTypeError("Wrong argument count for constructor call."));
	for (size_t i = 0; i < m_arguments.size(); ++i)
		if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i]))
			BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError(
				"Invalid type for argument in constructor call. "
				"Invalid implicit conversion from " +
				m_arguments[i]->getType()->toString() +
				" to " +
				parameterTypes[i]->toString() +
				" requested."
			));
}

TypePointer StructDefinition::getType(ContractDefinition const*) const
{
	return make_shared<TypeType>(make_shared<StructType>(*this));
}

void StructDefinition::checkMemberTypes() const
{
	for (ASTPointer<VariableDeclaration> const& member: getMembers())
		if (!member->getType()->canBeStored())
			BOOST_THROW_EXCEPTION(member->createTypeError("Type cannot be used in struct."));
}

void StructDefinition::checkRecursion() const
{
	set<StructDefinition const*> definitionsSeen;
	vector<StructDefinition const*> queue = {this};
	while (!queue.empty())
	{
		StructDefinition const* def = queue.back();
		queue.pop_back();
		if (definitionsSeen.count(def))
			BOOST_THROW_EXCEPTION(ParserError() << errinfo_sourceLocation(def->getLocation())
												<< errinfo_comment("Recursive struct definition."));
		definitionsSeen.insert(def);
		for (ASTPointer<VariableDeclaration> const& member: def->getMembers())
			if (member->getType()->getCategory() == Type::Category::Struct)
			{
				UserDefinedTypeName const& typeName = dynamic_cast<UserDefinedTypeName const&>(*member->getTypeName());
				queue.push_back(&dynamic_cast<StructDefinition const&>(*typeName.getReferencedDeclaration()));
			}
	}
}

TypePointer EnumDefinition::getType(ContractDefinition const*) const
{
	return make_shared<TypeType>(make_shared<EnumType>(*this));
}

TypePointer FunctionDefinition::getType(ContractDefinition const*) const
{
	return make_shared<FunctionType>(*this);
}

void FunctionDefinition::checkTypeRequirements()
{
	for (ASTPointer<VariableDeclaration> const& var: getParameters() + getReturnParameters())
	{
		if (!var->getType()->canLiveOutsideStorage())
			BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage."));
		if (getVisibility() >= Visibility::Public && !(var->getType()->externalType()))
			BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed for public and external functions."));
	}
	for (ASTPointer<ModifierInvocation> const& modifier: m_functionModifiers)<commit_msg>Fix and test for not really recursive structs.<commit_after>/*
    This file is part of cpp-ethereum.

    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <<EMAIL>>
 * @date 2014
 * Solidity abstract syntax tree.
 */

#include <algorithm>
#include <functional>
#include <boost/range/adaptor/reversed.hpp>
#include <libsolidity/Utils.h>
#include <libsolidity/AST.h>
#include <libsolidity/ASTVisitor.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/AST_accept.h>

#include <libdevcore/SHA3.h>

using namespace std;

namespace dev
{
namespace solidity
{

TypeError ASTNode::createTypeError(string const& _description) const
{
	return TypeError() << errinfo_sourceLocation(getLocation()) << errinfo_comment(_description);
}

TypePointer ContractDefinition::getType(ContractDefinition const* _currentContract) const
{
	return make_shared<TypeType>(make_shared<ContractType>(*this), _currentContract);
}

void ContractDefinition::checkTypeRequirements()
{
	for (ASTPointer<InheritanceSpecifier> const& baseSpecifier: getBaseContracts())
		baseSpecifier->checkTypeRequirements();

	checkDuplicateFunctions();
	checkIllegalOverrides();
	checkAbstractFunctions();
	checkAbstractConstructors();

	FunctionDefinition const* constructor = getConstructor();
	if (constructor && !constructor->getReturnParameters().empty())
		BOOST_THROW_EXCEPTION(constructor->getReturnParameterList()->createTypeError(
									"Non-empty \"returns\" directive for constructor."));

	FunctionDefinition const* fallbackFunction = nullptr;
	for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
	{
		if (function->getName().empty())
		{
			if (fallbackFunction)
				BOOST_THROW_EXCEPTION(DeclarationError() << errinfo_comment("Only one fallback function is allowed."));
			else
			{
				fallbackFunction = function.get();
				if (!fallbackFunction->getParameters().empty())
					BOOST_THROW_EXCEPTION(fallbackFunction->getParameterList().createTypeError("Fallback function cannot take parameters."));
			}
		}
		if (!function->isFullyImplemented())
			setFullyImplemented(false);
	}
	for (ASTPointer<ModifierDefinition> const& modifier: getFunctionModifiers())
		modifier->checkTypeRequirements();

	for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
		function->checkTypeRequirements();

	for (ASTPointer<VariableDeclaration> const& variable: m_stateVariables)
		variable->checkTypeRequirements();

	checkExternalTypeClashes();
	// check for hash collisions in function signatures
	set<FixedHash<4>> hashes;
	for (auto const& it: getInterfaceFunctionList())
	{
		FixedHash<4> const& hash = it.first;
		if (hashes.count(hash))
			BOOST_THROW_EXCEPTION(createTypeError(
				string("Function signature hash collision for ") + it.second->externalSignature()
			));
		hashes.insert(hash);
	}
}

map<FixedHash<4>, FunctionTypePointer> ContractDefinition::getInterfaceFunctions() const
{
	auto exportedFunctionList = getInterfaceFunctionList();

	map<FixedHash<4>, FunctionTypePointer> exportedFunctions;
	for (auto const& it: exportedFunctionList)
		exportedFunctions.insert(it);

	solAssert(exportedFunctionList.size() == exportedFunctions.size(),
			  "Hash collision at Function Definition Hash calculation");

	return exportedFunctions;
}

FunctionDefinition const* ContractDefinition::getConstructor() const
{
	for (ASTPointer<FunctionDefinition> const& f: m_definedFunctions)
		if (f->isConstructor())
			return f.get();
	return nullptr;
}

FunctionDefinition const* ContractDefinition::getFallbackFunction() const
{
	for (ContractDefinition const* contract: getLinearizedBaseContracts())
		for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
			if (f->getName().empty())
				return f.get();
	return nullptr;
}

void ContractDefinition::checkDuplicateFunctions() const
{
	/// Checks that two functions with the same name defined in this contract have different
	/// argument types and that there is at most one constructor.
	map<string, vector<FunctionDefinition const*>> functions;
	for (ASTPointer<FunctionDefinition> const& function: getDefinedFunctions())
		functions[function->getName()].push_back(function.get());

	if (functions[getName()].size() > 1)
	{
		SecondarySourceLocation ssl;
		auto it = functions[getName()].begin();
		++it;
		for (; it != functions[getName()].end(); ++it)
			ssl.append("Another declaration is here:", (*it)->getLocation());

		BOOST_THROW_EXCEPTION(
			DeclarationError() <<
			errinfo_sourceLocation(functions[getName()].front()->getLocation()) <<
			errinfo_comment("More than one constructor defined.") <<
			errinfo_secondarySourceLocation(ssl)
		);
	}
	for (auto const& it: functions)
	{
		vector<FunctionDefinition const*> const& overloads = it.second;
		for (size_t i = 0; i < overloads.size(); ++i)
			for (size_t j = i + 1; j < overloads.size(); ++j)
				if (FunctionType(*overloads[i]).hasEqualArgumentTypes(FunctionType(*overloads[j])))
					BOOST_THROW_EXCEPTION(
						DeclarationError() <<
						errinfo_sourceLocation(overloads[j]->getLocation()) <<
						errinfo_comment("Function with same name and arguments defined twice.") <<
						errinfo_secondarySourceLocation(SecondarySourceLocation().append(
							"Other declaration is here:", overloads[i]->getLocation()))
					);
	}
}

void ContractDefinition::checkAbstractFunctions()
{
	map<string, bool> functions;

	// Search from base to derived
	for (ContractDefinition const* contract: boost::adaptors::reverse(getLinearizedBaseContracts()))
		for (ASTPointer<FunctionDefinition> const& function: contract->getDefinedFunctions())
		{
			string const& name = function->getName();
			if (!function->isFullyImplemented() && functions.count(name) && functions[name])
				BOOST_THROW_EXCEPTION(function->createTypeError("Redeclaring an already implemented function as abstract"));
			functions[name] = function->isFullyImplemented();
		}

	for (auto const& it: functions)
		if (!it.second)
		{
			setFullyImplemented(false);
			break;
		}
}

void ContractDefinition::checkAbstractConstructors()
{
	set<ContractDefinition const*> argumentsNeeded;
	// check that we get arguments for all base constructors that need it.
	// If not mark the contract as abstract (not fully implemented)

	vector<ContractDefinition const*> const& bases = getLinearizedBaseContracts();
	for (ContractDefinition const* contract: bases)
		if (FunctionDefinition const* constructor = contract->getConstructor())
			if (contract != this && !constructor->getParameters().empty())
				argumentsNeeded.insert(contract);

	for (ContractDefinition const* contract: bases)
	{
		if (FunctionDefinition const* constructor = contract->getConstructor())
			for (auto const& modifier: constructor->getModifiers())
			{
				auto baseContract = dynamic_cast<ContractDefinition const*>(
					&modifier->getName()->getReferencedDeclaration()
				);
				if (baseContract)
					argumentsNeeded.erase(baseContract);
			}


		for (ASTPointer<InheritanceSpecifier> const& base: contract->getBaseContracts())
		{
			auto baseContract = dynamic_cast<ContractDefinition const*>(
				&base->getName()->getReferencedDeclaration()
			);
			solAssert(baseContract, "");
			if (!base->getArguments().empty())
				argumentsNeeded.erase(baseContract);
		}
	}
	if (!argumentsNeeded.empty())
		setFullyImplemented(false);
}

void ContractDefinition::checkIllegalOverrides() const
{
	// TODO unify this at a later point. for this we need to put the constness and the access specifier
	// into the types
	map<string, vector<FunctionDefinition const*>> functions;
	map<string, ModifierDefinition const*> modifiers;

	// We search from derived to base, so the stored item causes the error.
	for (ContractDefinition const* contract: getLinearizedBaseContracts())
	{
		for (ASTPointer<FunctionDefinition> const& function: contract->getDefinedFunctions())
		{
			if (function->isConstructor())
				continue; // constructors can neither be overridden nor override anything
			string const& name = function->getName();
			if (modifiers.count(name))
				BOOST_THROW_EXCEPTION(modifiers[name]->createTypeError("Override changes function to modifier."));
			FunctionType functionType(*function);
			// function should not change the return type
			for (FunctionDefinition const* overriding: functions[name])
			{
				FunctionType overridingType(*overriding);
				if (!overridingType.hasEqualArgumentTypes(functionType))
					continue;
				if (
					overriding->getVisibility() != function->getVisibility() ||
					overriding->isDeclaredConst() != function->isDeclaredConst() ||
					overridingType != functionType
				)
					BOOST_THROW_EXCEPTION(overriding->createTypeError("Override changes extended function signature."));
			}
			functions[name].push_back(function.get());
		}
		for (ASTPointer<ModifierDefinition> const& modifier: contract->getFunctionModifiers())
		{
			string const& name = modifier->getName();
			ModifierDefinition const*& override = modifiers[name];
			if (!override)
				override = modifier.get();
			else if (ModifierType(*override) != ModifierType(*modifier))
				BOOST_THROW_EXCEPTION(override->createTypeError("Override changes modifier signature."));
			if (!functions[name].empty())
				BOOST_THROW_EXCEPTION(override->createTypeError("Override changes modifier to function."));
		}
	}
}

void ContractDefinition::checkExternalTypeClashes() const
{
	map<string, vector<pair<Declaration const*, shared_ptr<FunctionType>>>> externalDeclarations;
	for (ContractDefinition const* contract: getLinearizedBaseContracts())
	{
		for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
			if (f->isPartOfExternalInterface())
			{
				auto functionType = make_shared<FunctionType>(*f);
				externalDeclarations[functionType->externalSignature(f->getName())].push_back(
					make_pair(f.get(), functionType)
				);
			}
		for (ASTPointer<VariableDeclaration> const& v: contract->getStateVariables())
			if (v->isPartOfExternalInterface())
			{
				auto functionType = make_shared<FunctionType>(*v);
				externalDeclarations[functionType->externalSignature(v->getName())].push_back(
					make_pair(v.get(), functionType)
				);
			}
	}
	for (auto const& it: externalDeclarations)
		for (size_t i = 0; i < it.second.size(); ++i)
			for (size_t j = i + 1; j < it.second.size(); ++j)
				if (!it.second[i].second->hasEqualArgumentTypes(*it.second[j].second))
					BOOST_THROW_EXCEPTION(it.second[j].first->createTypeError(
						"Function overload clash during conversion to external types for arguments."
					));
}

vector<ASTPointer<EventDefinition>> const& ContractDefinition::getInterfaceEvents() const
{
	if (!m_interfaceEvents)
	{
		set<string> eventsSeen;
		m_interfaceEvents.reset(new vector<ASTPointer<EventDefinition>>());
		for (ContractDefinition const* contract: getLinearizedBaseContracts())
			for (ASTPointer<EventDefinition> const& e: contract->getEvents())
				if (eventsSeen.count(e->getName()) == 0)
				{
					eventsSeen.insert(e->getName());
					m_interfaceEvents->push_back(e);
				}
	}
	return *m_interfaceEvents;
}

vector<pair<FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::getInterfaceFunctionList() const
{
	if (!m_interfaceFunctionList)
	{
		set<string> functionsSeen;
		set<string> signaturesSeen;
		m_interfaceFunctionList.reset(new vector<pair<FixedHash<4>, FunctionTypePointer>>());
		for (ContractDefinition const* contract: getLinearizedBaseContracts())
		{
			for (ASTPointer<FunctionDefinition> const& f: contract->getDefinedFunctions())
			{
				string functionSignature = f->externalSignature();
				if (f->isPartOfExternalInterface() && signaturesSeen.count(functionSignature) == 0)
				{
					functionsSeen.insert(f->getName());
					signaturesSeen.insert(functionSignature);
					FixedHash<4> hash(dev::sha3(functionSignature));
					m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*f, false)));
				}
			}

			for (ASTPointer<VariableDeclaration> const& v: contract->getStateVariables())
				if (functionsSeen.count(v->getName()) == 0 && v->isPartOfExternalInterface())
				{
					FunctionType ftype(*v);
					solAssert(v->getType().get(), "");
					functionsSeen.insert(v->getName());
					FixedHash<4> hash(dev::sha3(ftype.externalSignature(v->getName())));
					m_interfaceFunctionList->push_back(make_pair(hash, make_shared<FunctionType>(*v)));
				}
		}
	}
	return *m_interfaceFunctionList;
}

vector<Declaration const*> const& ContractDefinition::getInheritableMembers() const
{
	if (!m_inheritableMembers)
	{
		set<string> memberSeen;
		m_inheritableMembers.reset(new vector<Declaration const*>());
		auto addInheritableMember = [&](Declaration const* _decl)
		{
			if (memberSeen.count(_decl->getName()) == 0 && _decl->isVisibleInDerivedContracts())
			{
				memberSeen.insert(_decl->getName());
				m_inheritableMembers->push_back(_decl);
			}
		};

		for (ASTPointer<FunctionDefinition> const& f: getDefinedFunctions())
			addInheritableMember(f.get());

		for (ASTPointer<VariableDeclaration> const& v: getStateVariables())
			addInheritableMember(v.get());

		for (ASTPointer<StructDefinition> const& s: getDefinedStructs())
			addInheritableMember(s.get());
	}
	return *m_inheritableMembers;
}

TypePointer EnumValue::getType(ContractDefinition const*) const
{
	EnumDefinition const* parentDef = dynamic_cast<EnumDefinition const*>(getScope());
	solAssert(parentDef, "Enclosing Scope of EnumValue was not set");
	return make_shared<EnumType>(*parentDef);
}

void InheritanceSpecifier::checkTypeRequirements()
{
	m_baseName->checkTypeRequirements(nullptr);
	for (ASTPointer<Expression> const& argument: m_arguments)
		argument->checkTypeRequirements(nullptr);

	ContractDefinition const* base = dynamic_cast<ContractDefinition const*>(&m_baseName->getReferencedDeclaration());
	solAssert(base, "Base contract not available.");
	TypePointers parameterTypes = ContractType(*base).getConstructorType()->getParameterTypes();
	if (!m_arguments.empty() && parameterTypes.size() != m_arguments.size())
		BOOST_THROW_EXCEPTION(createTypeError("Wrong argument count for constructor call."));
	for (size_t i = 0; i < m_arguments.size(); ++i)
		if (!m_arguments[i]->getType()->isImplicitlyConvertibleTo(*parameterTypes[i]))
			BOOST_THROW_EXCEPTION(m_arguments[i]->createTypeError(
				"Invalid type for argument in constructor call. "
				"Invalid implicit conversion from " +
				m_arguments[i]->getType()->toString() +
				" to " +
				parameterTypes[i]->toString() +
				" requested."
			));
}

TypePointer StructDefinition::getType(ContractDefinition const*) const
{
	return make_shared<TypeType>(make_shared<StructType>(*this));
}

void StructDefinition::checkMemberTypes() const
{
	for (ASTPointer<VariableDeclaration> const& member: getMembers())
		if (!member->getType()->canBeStored())
			BOOST_THROW_EXCEPTION(member->createTypeError("Type cannot be used in struct."));
}

void StructDefinition::checkRecursion() const
{
	using StructPointer = StructDefinition const*;
	using StructPointersSet = set<StructPointer>;
	function<void(StructPointer,StructPointersSet const&)> check = [&](StructPointer _struct, StructPointersSet const& _parents)
	{
		if (_parents.count(_struct))
			BOOST_THROW_EXCEPTION(
				ParserError() <<
				errinfo_sourceLocation(_struct->getLocation()) <<
				errinfo_comment("Recursive struct definition.")
			);
		set<StructDefinition const*> parents = _parents;
		parents.insert(_struct);
		for (ASTPointer<VariableDeclaration> const& member: _struct->getMembers())
			if (member->getType()->getCategory() == Type::Category::Struct)
			{
				auto const& typeName = dynamic_cast<UserDefinedTypeName const&>(*member->getTypeName());
				check(
					&dynamic_cast<StructDefinition const&>(*typeName.getReferencedDeclaration()),
					parents
				);
			}
	};
	check(this, {});
}

TypePointer EnumDefinition::getType(ContractDefinition const*) const
{
	return make_shared<TypeType>(make_shared<EnumType>(*this));
}

TypePointer FunctionDefinition::getType(ContractDefinition const*) const
{
	return make_shared<FunctionType>(*this);
}

void FunctionDefinition::checkTypeRequirements()
{
	for (ASTPointer<VariableDeclaration> const& var: getParameters() + getReturnParameters())
	{
		if (!var->getType()->canLiveOutsideStorage())
			BOOST_THROW_EXCEPTION(var->createTypeError("Type is required to live outside storage."));
		if (getVisibility() >= Visibility::Public && !(var->getType()->externalType()))
			BOOST_THROW_EXCEPTION(var->createTypeError("Internal type is not allowed for public and external functions."));
	}
	for (ASTPointer<ModifierInvocation> const& modifier: m_functionModifiers)
{'fraction_non_alphanumeric': 0.126287010645105, 'fraction_numerical': 0.0015124192891629341, 'mean_word_length': 5.753682969946965, 'pattern_counts': {'":': 0, '<': 247, '<?xml version=': 0, '>': 401, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1602602', 'n_tokens_mistral': 10902, 'n_tokens_neox': 9674, 'n_words': 2195}