Type inference draft.

This commit is contained in:
Daniel Kirchner
2023-09-05 11:50:14 +02:00
committed by Nikola Matic
parent 6ec4d3dd98
commit 45f00dda3b
52 changed files with 5240 additions and 265 deletions
@@ -0,0 +1,74 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/experimental/codegen/Common.h>
#include <libsolidity/experimental/ast/TypeSystem.h>
#include <libsolidity/experimental/ast/TypeSystemHelper.h>
#include <libsolutil/CommonIO.h>
#include <libyul/AsmPrinter.h>
using namespace std;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::util;
using namespace solidity::yul;
namespace solidity::frontend::experimental
{
string IRNames::function(TypeEnvironment const& _env, FunctionDefinition const& _function, Type _type)
{
if (_function.isConstructor())
return constructor(*_function.annotation().contract);
return "fun_" + _function.name() + "_" + to_string(_function.id()) + "$" + TypeEnvironmentHelpers{_env}.canonicalTypeName(_type) + "$";
}
string IRNames::function(VariableDeclaration const& _varDecl)
{
return "getter_fun_" + _varDecl.name() + "_" + to_string(_varDecl.id());
}
string IRNames::creationObject(ContractDefinition const& _contract)
{
return _contract.name() + "_" + toString(_contract.id());
}
string IRNames::deployedObject(ContractDefinition const& _contract)
{
return _contract.name() + "_" + toString(_contract.id()) + "_deployed";
}
string IRNames::constructor(ContractDefinition const& _contract)
{
return "constructor_" + _contract.name() + "_" + to_string(_contract.id());
}
string IRNames::localVariable(VariableDeclaration const& _declaration)
{
return "var_" + _declaration.name() + '_' + std::to_string(_declaration.id());
}
string IRNames::localVariable(Expression const& _expression)
{
return "expr_" + to_string(_expression.id());
}
}
+41
View File
@@ -0,0 +1,41 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libsolidity/ast/AST.h>
#include <libsolidity/experimental/ast/TypeSystem.h>
#include <algorithm>
#include <string>
namespace solidity::frontend::experimental
{
struct IRNames
{
static std::string function(TypeEnvironment const& _env, FunctionDefinition const& _function, Type _type);
static std::string function(VariableDeclaration const& _varDecl);
static std::string creationObject(ContractDefinition const& _contract);
static std::string deployedObject(ContractDefinition const& _contract);
static std::string constructor(ContractDefinition const& _contract);
static std::string localVariable(VariableDeclaration const& _declaration);
static std::string localVariable(Expression const& _expression);
};
}
@@ -0,0 +1,55 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libsolidity/ast/ASTForward.h>
#include <libsolidity/experimental/analysis/Analysis.h>
#include <libsolidity/experimental/ast/TypeSystem.h>
#include <list>
#include <set>
namespace solidity::frontend::experimental
{
class Analysis;
struct IRGenerationContext
{
Analysis const& analysis;
TypeEnvironment const* env = nullptr;
void enqueueFunctionDefinition(FunctionDefinition const* _functionDefinition, Type _type)
{
QueuedFunction queue{_functionDefinition, env->resolve(_type)};
for (auto type: generatedFunctions[_functionDefinition])
if (env->typeEquals(type, _type))
return;
functionQueue.emplace_back(queue);
}
struct QueuedFunction
{
FunctionDefinition const* function = nullptr;
Type type = std::monostate{};
};
std::list<QueuedFunction> functionQueue;
std::map<FunctionDefinition const*, std::vector<Type>> generatedFunctions;
};
}
@@ -0,0 +1,161 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/experimental/codegen/IRGenerator.h>
#include <libsolidity/experimental/codegen/IRGenerationContext.h>
#include <libsolidity/experimental/codegen/IRGeneratorForStatements.h>
#include <libsolidity/experimental/codegen/Common.h>
#include <libsolidity/experimental/analysis/Analysis.h>
#include <libsolidity/experimental/analysis/TypeInference.h>
#include <libsolidity/experimental/ast/TypeSystemHelper.h>
#include <libyul/YulStack.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AST.h>
#include <libyul/optimiser/ASTCopier.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolutil/Whiskers.h>
#include <range/v3/view/drop_last.hpp>
#include <variant>
using namespace std;
using namespace solidity;
using namespace solidity::frontend::experimental;
using namespace solidity::langutil;
using namespace solidity::util;
IRGenerator::IRGenerator(
EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
frontend::RevertStrings, std::map<std::string, unsigned int>,
DebugInfoSelection const&,
CharStreamProvider const*,
Analysis const& _analysis
)
:
m_evmVersion(_evmVersion),
m_eofVersion(_eofVersion),
// m_debugInfoSelection(_debugInfoSelection),
// m_soliditySourceProvider(_soliditySourceProvider),
m_env(_analysis.typeSystem().env().clone()),
m_context{_analysis, &m_env, {}, {}}
{
}
string IRGenerator::run(
ContractDefinition const& _contract,
bytes const& /*_cborMetadata*/,
map<ContractDefinition const*, string_view const> const& /*_otherYulSources*/
)
{
Whiskers t(R"(
object "<CreationObject>" {
code {
codecopy(0, dataoffset("<DeployedObject>"), datasize("<DeployedObject>"))
return(0, datasize("<DeployedObject>"))
}
object "<DeployedObject>" {
code {
<code>
}
}
}
)");
t("CreationObject", IRNames::creationObject(_contract));
t("DeployedObject", IRNames::deployedObject(_contract));
t("code", generate(_contract));
return t.render();
}
string IRGenerator::generate(ContractDefinition const& _contract)
{
std::stringstream code;
code << "{\n";
if (_contract.fallbackFunction())
{
auto type = m_context.analysis.annotation<TypeInference>(*_contract.fallbackFunction()).type;
solAssert(type);
type = m_context.env->resolve(*type);
code << IRNames::function(*m_context.env, *_contract.fallbackFunction(), *type) << "()\n";
m_context.enqueueFunctionDefinition(_contract.fallbackFunction(), *type);
}
code << "revert(0,0)\n";
code << "}\n";
while (!m_context.functionQueue.empty())
{
auto queueEntry = m_context.functionQueue.front();
m_context.functionQueue.pop_front();
auto& generatedTypes = m_context.generatedFunctions.insert(std::make_pair(queueEntry.function, vector<Type>{})).first->second;
if (!util::contains_if(generatedTypes, [&](auto const& _generatedType) { return m_context.env->typeEquals(_generatedType, queueEntry.type); }))
{
generatedTypes.emplace_back(queueEntry.type);
code << generate(*queueEntry.function, queueEntry.type);
}
}
return code.str();
}
string IRGenerator::generate(FunctionDefinition const& _function, Type _type)
{
TypeEnvironment newEnv = m_context.env->clone();
ScopedSaveAndRestore envRestore{m_context.env, &newEnv};
auto type = m_context.analysis.annotation<TypeInference>(_function).type;
solAssert(type);
for (auto err: newEnv.unify(*type, _type))
{
TypeEnvironmentHelpers helper{newEnv};
solAssert(false, helper.typeToString(*type) + " <-> " + helper.typeToString(_type));
}
std::stringstream code;
code << "function " << IRNames::function(newEnv, _function, _type) << "(";
if (_function.parameters().size() > 1)
for (auto const& arg: _function.parameters() | ranges::views::drop_last(1))
code << IRNames::localVariable(*arg) << ", ";
if (!_function.parameters().empty())
code << IRNames::localVariable(*_function.parameters().back());
code << ")";
if (_function.experimentalReturnExpression())
{
auto returnType = m_context.analysis.annotation<TypeInference>(*_function.experimentalReturnExpression()).type;
solAssert(returnType);
if (!m_env.typeEquals(*returnType, m_context.analysis.typeSystem().type(PrimitiveType::Unit, {})))
{
// TODO: destructure tuples.
code << " -> " << IRNames::localVariable(*_function.experimentalReturnExpression()) << " ";
}
}
code << "{\n";
for (auto _statement: _function.body().statements())
{
IRGeneratorForStatements statementGenerator{m_context};
code << statementGenerator.generate(*_statement);
}
code << "}\n";
return code.str();
}
@@ -0,0 +1,72 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libsolidity/experimental/codegen/IRGenerationContext.h>
#include <libsolidity/interface/DebugSettings.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <libsolidity/ast/ASTForward.h>
#include <libsolidity/ast/CallGraph.h>
#include <libsolidity/experimental/ast/TypeSystem.h>
#include <liblangutil/CharStreamProvider.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/EVMVersion.h>
#include <json/json.h>
#include <string>
namespace solidity::frontend::experimental
{
class Analysis;
class IRGenerator
{
public:
IRGenerator(
langutil::EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
RevertStrings /*_revertStrings*/,
std::map<std::string, unsigned> /*_sourceIndices*/,
langutil::DebugInfoSelection const& /*_debugInfoSelection*/,
langutil::CharStreamProvider const* /*_soliditySourceProvider*/,
Analysis const& _analysis
);
std::string run(
ContractDefinition const& _contract,
bytes const& _cborMetadata,
std::map<ContractDefinition const*, std::string_view const> const& _otherYulSources
);
std::string generate(ContractDefinition const& _contract);
std::string generate(FunctionDefinition const& _function, Type _type);
private:
langutil::EVMVersion const m_evmVersion;
std::optional<uint8_t> const m_eofVersion;
OptimiserSettings const m_optimiserSettings;
// langutil::DebugInfoSelection m_debugInfoSelection = {};
// langutil::CharStreamProvider const* m_soliditySourceProvider = nullptr;
TypeEnvironment m_env;
IRGenerationContext m_context;
};
}
@@ -0,0 +1,388 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/experimental/codegen/IRGeneratorForStatements.h>
#include <libsolidity/experimental/analysis/Analysis.h>
#include <libsolidity/experimental/analysis/TypeInference.h>
#include <libsolidity/experimental/analysis/TypeRegistration.h>
#include <libsolidity/experimental/ast/TypeSystemHelper.h>
#include <libyul/YulStack.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AST.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libsolidity/experimental/codegen/Common.h>
#include <range/v3/view/drop_last.hpp>
using namespace std;
using namespace solidity;
using namespace solidity::util;
using namespace solidity::frontend;
using namespace solidity::frontend::experimental;
using namespace std::string_literals;
std::string IRGeneratorForStatements::generate(ASTNode const& _node)
{
_node.accept(*this);
return m_code.str();
}
namespace {
struct CopyTranslate: public yul::ASTCopier
{
CopyTranslate(
IRGenerationContext const& _context,
yul::Dialect const& _dialect,
map<yul::Identifier const*, InlineAssemblyAnnotation::ExternalIdentifierInfo> _references
): m_context(_context), m_dialect(_dialect), m_references(std::move(_references)) {}
using ASTCopier::operator();
yul::Expression operator()(yul::Identifier const& _identifier) override
{
// The operator() function is only called in lvalue context. In rvalue context,
// only translate(yul::Identifier) is called.
if (m_references.count(&_identifier))
return translateReference(_identifier);
else
return ASTCopier::operator()(_identifier);
}
yul::YulString translateIdentifier(yul::YulString _name) override
{
if (m_dialect.builtin(_name))
return _name;
else
return yul::YulString{"usr$" + _name.str()};
}
yul::Identifier translate(yul::Identifier const& _identifier) override
{
if (!m_references.count(&_identifier))
return ASTCopier::translate(_identifier);
yul::Expression translated = translateReference(_identifier);
solAssert(holds_alternative<yul::Identifier>(translated));
return get<yul::Identifier>(std::move(translated));
}
private:
/// Translates a reference to a local variable, potentially including
/// a suffix. Might return a literal, which causes this to be invalid in
/// lvalue-context.
yul::Expression translateReference(yul::Identifier const& _identifier)
{
auto const& reference = m_references.at(&_identifier);
auto const varDecl = dynamic_cast<VariableDeclaration const*>(reference.declaration);
solAssert(varDecl, "External reference in inline assembly to something that is not a variable declaration.");
auto type = m_context.analysis.annotation<TypeInference>(*varDecl).type;
solAssert(type);
solAssert(m_context.env->typeEquals(*type, m_context.analysis.typeSystem().type(PrimitiveType::Word, {})));
string value = IRNames::localVariable(*varDecl);
return yul::Identifier{_identifier.debugData, yul::YulString{value}};
}
IRGenerationContext const& m_context;
yul::Dialect const& m_dialect;
map<yul::Identifier const*, InlineAssemblyAnnotation::ExternalIdentifierInfo> m_references;
};
}
bool IRGeneratorForStatements::visit(TupleExpression const& _tupleExpression)
{
std::vector<string> components;
for (auto const& component: _tupleExpression.components())
{
solUnimplementedAssert(component);
component->accept(*this);
components.emplace_back(IRNames::localVariable(*component));
}
solUnimplementedAssert(false, "No support for tuples.");
return false;
}
bool IRGeneratorForStatements::visit(InlineAssembly const& _assembly)
{
CopyTranslate bodyCopier{m_context, _assembly.dialect(), _assembly.annotation().externalReferences};
yul::Statement modified = bodyCopier(_assembly.operations());
solAssert(holds_alternative<yul::Block>(modified));
m_code << yul::AsmPrinter()(std::get<yul::Block>(modified)) << "\n";
return false;
}
bool IRGeneratorForStatements::visit(VariableDeclarationStatement const& _variableDeclarationStatement)
{
if (_variableDeclarationStatement.initialValue())
_variableDeclarationStatement.initialValue()->accept(*this);
solAssert(_variableDeclarationStatement.declarations().size() == 1, "multi variable declarations not supported");
VariableDeclaration const* variableDeclaration = _variableDeclarationStatement.declarations().front().get();
solAssert(variableDeclaration);
// TODO: check the type of the variable; register local variable; initialize
m_code << "let " << IRNames::localVariable(*variableDeclaration);
if (_variableDeclarationStatement.initialValue())
m_code << " := " << IRNames::localVariable(*_variableDeclarationStatement.initialValue());
m_code << "\n";
return false;
}
bool IRGeneratorForStatements::visit(ExpressionStatement const&)
{
return true;
}
bool IRGeneratorForStatements::visit(Identifier const& _identifier)
{
if (auto const* var = dynamic_cast<VariableDeclaration const*>(_identifier.annotation().referencedDeclaration))
{
m_code << "let " << IRNames::localVariable(_identifier) << " := " << IRNames::localVariable(*var) << "\n";
}
else if (auto const* function = dynamic_cast<FunctionDefinition const*>(_identifier.annotation().referencedDeclaration))
solAssert(m_expressionDeclaration.emplace(&_identifier, function).second);
else if (auto const* typeClass = dynamic_cast<TypeClassDefinition const*>(_identifier.annotation().referencedDeclaration))
solAssert(m_expressionDeclaration.emplace(&_identifier, typeClass).second);
else if (auto const* typeDefinition = dynamic_cast<TypeDefinition const*>(_identifier.annotation().referencedDeclaration))
solAssert(m_expressionDeclaration.emplace(&_identifier, typeDefinition).second);
else
solAssert(false, "Unsupported Identifier");
return false;
}
void IRGeneratorForStatements::endVisit(Return const& _return)
{
if (Expression const* value = _return.expression())
{
solAssert(_return.annotation().function, "Invalid return.");
solAssert(_return.annotation().function->experimentalReturnExpression(), "Invalid return.");
m_code << IRNames::localVariable(*_return.annotation().function->experimentalReturnExpression()) << " := " << IRNames::localVariable(*value) << "\n";
}
m_code << "leave\n";
}
experimental::Type IRGeneratorForStatements::type(ASTNode const& _node) const
{
auto type = m_context.analysis.annotation<TypeInference>(_node).type;
solAssert(type);
return *type;
}
void IRGeneratorForStatements::endVisit(BinaryOperation const& _binaryOperation)
{
TypeSystemHelpers helper{m_context.analysis.typeSystem()};
Type leftType = type(_binaryOperation.leftExpression());
Type rightType = type(_binaryOperation.rightExpression());
Type resultType = type(_binaryOperation);
Type functionType = helper.functionType(helper.tupleType({leftType, rightType}), resultType);
auto [typeClass, memberName] = m_context.analysis.annotation<TypeInference>().operators.at(_binaryOperation.getOperator());
auto const& functionDefinition = resolveTypeClassFunction(typeClass, memberName, functionType);
// TODO: deduplicate with FunctionCall
// TODO: get around resolveRecursive by passing the environment further down?
functionType = m_context.env->resolveRecursive(functionType);
m_context.enqueueFunctionDefinition(&functionDefinition, functionType);
// TODO: account for return stack size
m_code << "let " << IRNames::localVariable(_binaryOperation) << " := " << IRNames::function(*m_context.env, functionDefinition, functionType) << "("
<< IRNames::localVariable(_binaryOperation.leftExpression()) << ", " << IRNames::localVariable(_binaryOperation.rightExpression()) << ")\n";
}
namespace
{
TypeRegistration::TypeClassInstantiations const& typeClassInstantiations(IRGenerationContext const& _context, TypeClass _class)
{
auto const* typeClassDeclaration = _context.analysis.typeSystem().typeClassDeclaration(_class);
if (typeClassDeclaration)
return _context.analysis.annotation<TypeRegistration>(*typeClassDeclaration).instantiations;
// TODO: better mechanism than fetching by name.
auto& instantiations = _context.analysis.annotation<TypeRegistration>().builtinClassInstantiations;
auto& builtinClassesByName = _context.analysis.annotation<TypeInference>().builtinClassesByName;
return instantiations.at(builtinClassesByName.at(_context.analysis.typeSystem().typeClassName(_class)));
}
}
FunctionDefinition const& IRGeneratorForStatements::resolveTypeClassFunction(TypeClass _class, string _name, Type _type)
{
TypeSystemHelpers helper{m_context.analysis.typeSystem()};
TypeEnvironment env = m_context.env->clone();
Type genericFunctionType = env.fresh(m_context.analysis.annotation<TypeInference>().typeClassFunctions.at(_class).at(_name));
auto typeVars = TypeEnvironmentHelpers{env}.typeVars(genericFunctionType);
solAssert(typeVars.size() == 1);
solAssert(env.unify(genericFunctionType, _type).empty());
auto typeClassInstantiation = get<0>(helper.destTypeConstant(env.resolve(typeVars.front())));
auto const& instantiations = typeClassInstantiations(m_context, _class);
TypeClassInstantiation const* instantiation = instantiations.at(typeClassInstantiation);
FunctionDefinition const* functionDefinition = nullptr;
for (auto const& node: instantiation->subNodes())
{
auto const* def = dynamic_cast<FunctionDefinition const*>(node.get());
solAssert(def);
if (def->name() == _name)
{
functionDefinition = def;
break;
}
}
solAssert(functionDefinition);
return *functionDefinition;
}
void IRGeneratorForStatements::endVisit(MemberAccess const& _memberAccess)
{
TypeSystemHelpers helper{m_context.analysis.typeSystem()};
// TODO: avoid resolve?
auto expressionType = m_context.env->resolve(type(_memberAccess.expression()));
auto constructor = std::get<0>(helper.destTypeConstant(expressionType));
auto memberAccessType = type(_memberAccess);
// TODO: better mechanism
if (constructor == m_context.analysis.typeSystem().constructor(PrimitiveType::Bool))
{
if (_memberAccess.memberName() == "abs")
solAssert(m_expressionDeclaration.emplace(&_memberAccess, Builtins::ToBool).second);
else if (_memberAccess.memberName() == "rep")
solAssert(m_expressionDeclaration.emplace(&_memberAccess, Builtins::FromBool).second);
return;
}
auto const* declaration = m_context.analysis.typeSystem().constructorInfo(constructor).typeDeclaration;
solAssert(declaration);
if (auto const* typeClassDefinition = dynamic_cast<TypeClassDefinition const*>(declaration))
{
optional<TypeClass> typeClass = m_context.analysis.annotation<TypeInference>(*typeClassDefinition).typeClass;
solAssert(typeClass);
solAssert(m_expressionDeclaration.emplace(
&_memberAccess,
&resolveTypeClassFunction(*typeClass, _memberAccess.memberName(), memberAccessType)
).second);
}
else if (dynamic_cast<TypeDefinition const*>(declaration))
{
if (_memberAccess.memberName() == "abs" || _memberAccess.memberName() == "rep")
solAssert(m_expressionDeclaration.emplace(&_memberAccess, Builtins::Identity).second);
else
solAssert(false);
}
else
solAssert(false);
}
bool IRGeneratorForStatements::visit(ElementaryTypeNameExpression const&)
{
// TODO: is this always a no-op?
return false;
}
void IRGeneratorForStatements::endVisit(FunctionCall const& _functionCall)
{
Type functionType = type(_functionCall.expression());
auto declaration = m_expressionDeclaration.at(&_functionCall.expression());
if (auto builtin = get_if<Builtins>(&declaration))
{
switch(*builtin)
{
case Builtins::FromBool:
case Builtins::Identity:
solAssert(_functionCall.arguments().size() == 1);
m_code << "let " << IRNames::localVariable(_functionCall) << " := " << IRNames::localVariable(*_functionCall.arguments().front()) << "\n";
return;
case Builtins::ToBool:
solAssert(_functionCall.arguments().size() == 1);
m_code << "let " << IRNames::localVariable(_functionCall) << " := iszero(iszero(" << IRNames::localVariable(*_functionCall.arguments().front()) << "))\n";
return;
}
solAssert(false);
}
FunctionDefinition const* functionDefinition = dynamic_cast<FunctionDefinition const*>(get<Declaration const*>(declaration));
solAssert(functionDefinition);
// TODO: get around resolveRecursive by passing the environment further down?
functionType = m_context.env->resolveRecursive(functionType);
m_context.enqueueFunctionDefinition(functionDefinition, functionType);
// TODO: account for return stack size
m_code << "let " << IRNames::localVariable(_functionCall) << " := " << IRNames::function(*m_context.env, *functionDefinition, functionType) << "(";
auto const& arguments = _functionCall.arguments();
if (arguments.size() > 1)
for (auto arg: arguments | ranges::views::drop_last(1))
m_code << IRNames::localVariable(*arg) << ", ";
if (!arguments.empty())
m_code << IRNames::localVariable(*arguments.back());
m_code << ")\n";
}
bool IRGeneratorForStatements::visit(FunctionCall const&)
{
return true;
}
bool IRGeneratorForStatements::visit(Block const& _block)
{
m_code << "{\n";
solAssert(!_block.unchecked());
for (auto const& statement: _block.statements())
statement->accept(*this);
m_code << "}\n";
return false;
}
bool IRGeneratorForStatements::visit(IfStatement const& _ifStatement)
{
_ifStatement.condition().accept(*this);
if (_ifStatement.falseStatement())
{
m_code << "switch " << IRNames::localVariable(_ifStatement.condition()) << " {\n";
m_code << "case 0 {\n";
_ifStatement.falseStatement()->accept(*this);
m_code << "}\n";
m_code << "default {\n";
_ifStatement.trueStatement().accept(*this);
m_code << "}\n";
}
else
{
m_code << "if " << IRNames::localVariable(_ifStatement.condition()) << " {\n";
_ifStatement.trueStatement().accept(*this);
m_code << "}\n";
}
return false;
}
bool IRGeneratorForStatements::visit(Assignment const& _assignment)
{
_assignment.rightHandSide().accept(*this);
auto const* lhs = dynamic_cast<Identifier const*>(&_assignment.leftHandSide());
solAssert(lhs, "Can only assign to identifiers.");
auto const* lhsVar = dynamic_cast<VariableDeclaration const*>(lhs->annotation().referencedDeclaration);
solAssert(lhsVar, "Can only assign to identifiers referring to variables.");
m_code << IRNames::localVariable(*lhsVar) << " := " << IRNames::localVariable(_assignment.rightHandSide()) << "\n";
m_code << "let " << IRNames::localVariable(_assignment) << " := " << IRNames::localVariable(*lhsVar) << "\n";
return false;
}
bool IRGeneratorForStatements::visitNode(ASTNode const&)
{
solAssert(false, "Unsupported AST node during statement code generation.");
}
@@ -0,0 +1,71 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libsolidity/experimental/codegen/IRGenerationContext.h>
#include <libsolidity/ast/ASTVisitor.h>
#include <functional>
#include <sstream>
namespace solidity::frontend::experimental
{
class Analysis;
class IRGeneratorForStatements: public ASTConstVisitor
{
public:
IRGeneratorForStatements(IRGenerationContext& _context): m_context(_context) {}
std::string generate(ASTNode const& _node);
private:
bool visit(ExpressionStatement const& _expressionStatement) override;
bool visit(Block const& _block) override;
bool visit(IfStatement const& _ifStatement) override;
bool visit(Assignment const& _assignment) override;
bool visit(Identifier const& _identifier) override;
bool visit(FunctionCall const& _functionCall) override;
void endVisit(FunctionCall const& _functionCall) override;
bool visit(ElementaryTypeNameExpression const& _elementaryTypeNameExpression) override;
bool visit(MemberAccess const&) override { return true; }
bool visit(TupleExpression const&) override;
void endVisit(MemberAccess const& _memberAccess) override;
bool visit(InlineAssembly const& _inlineAssembly) override;
bool visit(BinaryOperation const&) override { return true; }
void endVisit(BinaryOperation const& _binaryOperation) override;
bool visit(VariableDeclarationStatement const& _variableDeclarationStatement) override;
bool visit(Return const&) override { return true; }
void endVisit(Return const& _return) override;
/// Default visit will reject all AST nodes that are not explicitly supported.
bool visitNode(ASTNode const& _node) override;
IRGenerationContext& m_context;
std::stringstream m_code;
enum class Builtins
{
Identity,
FromBool,
ToBool
};
std::map<Expression const*, std::variant<Declaration const*, Builtins>> m_expressionDeclaration;
Type type(ASTNode const& _node) const;
FunctionDefinition const& resolveTypeClassFunction(TypeClass _class, std::string _name, Type _type);
};
}
@@ -0,0 +1,135 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/experimental/codegen/Common.h>
#include <libsolidity/experimental/codegen/IRGenerationContext.h>
#include <libsolidity/experimental/codegen/IRVariable.h>
#include <libsolidity/experimental/analysis/Analysis.h>
#include <libsolidity/experimental/analysis/TypeInference.h>
#include <libsolidity/ast/AST.h>
#include <libsolutil/StringUtils.h>
using namespace std;
using namespace solidity;
using namespace solidity::frontend::experimental;
using namespace solidity::util;
template<typename Node>
Type getType(IRGenerationContext const& _context, Node const& _node)
{
auto& annotation = _context.analysis.annotation<TypeInference>(_node);
solAssert(annotation.type);
return _context.env->resolve(*annotation.type);
}
namespace
{
size_t getTypeStackSlots(IRGenerationContext const& _context, Type _type)
{
}
}
IRVariable::IRVariable(IRGenerationContext const& _context, std::string _baseName, Type _type):
m_baseName(std::move(_baseName)), m_type(_type)
{
}
IRVariable::IRVariable(IRGenerationContext const& _context, VariableDeclaration const& _declaration):
IRVariable(_context, IRNames::localVariable(_declaration), getType(_context, _declaration))
{
}
IRVariable::IRVariable(IRGenerationContext const& _context, Expression const& _expression):
IRVariable(_context, IRNames::localVariable(_expression), getType(_context, _expression))
{
}
IRVariable IRVariable::part(string const& _name) const
{
for (auto const& [itemName, itemType]: m_type.stackItems())
if (itemName == _name)
{
solAssert(itemName.empty() || itemType, "");
return IRVariable{suffixedName(itemName), itemType ? *itemType : m_type};
}
solAssert(false, "Invalid stack item name: " + _name);
}
bool IRVariable::hasPart(std::string const& _name) const
{
for (auto const& [itemName, itemType]: m_type.stackItems())
if (itemName == _name)
{
solAssert(itemName.empty() || itemType, "");
return true;
}
return false;
}
vector<string> IRVariable::stackSlots() const
{
vector<string> result;
for (auto const& [itemName, itemType]: m_type.stackItems())
if (itemType)
{
solAssert(!itemName.empty(), "");
solAssert(m_type != *itemType, "");
result += IRVariable{suffixedName(itemName), *itemType}.stackSlots();
}
else
{
solAssert(itemName.empty(), "");
result.emplace_back(m_baseName);
}
return result;
}
string IRVariable::commaSeparatedList() const
{
return joinHumanReadable(stackSlots());
}
string IRVariable::commaSeparatedListPrefixed() const
{
return joinHumanReadablePrefixed(stackSlots());
}
string IRVariable::name() const
{
solAssert(m_type.sizeOnStack() == 1, "");
auto const& [itemName, type] = m_type.stackItems().front();
solAssert(!type, "Expected null type for name " + itemName);
return suffixedName(itemName);
}
IRVariable IRVariable::tupleComponent(size_t _i) const
{
solAssert(
m_type.category() == Type::Category::Tuple,
"Requested tuple component of non-tuple IR variable."
);
return part(IRNames::tupleComponent(_i));
}
string IRVariable::suffixedName(string const& _suffix) const
{
if (_suffix.empty())
return m_baseName;
else
return m_baseName + '_' + _suffix;
}
@@ -0,0 +1,85 @@
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libsolidity/experimental/ast/TypeSystem.h>
#include <optional>
#include <string>
#include <vector>
namespace solidity::frontend
{
class VariableDeclaration;
class Expression;
}
namespace solidity::frontend::experimental
{
class IRGenerationContext;
class IRVariable
{
public:
/// IR variable with explicit base name @a _baseName and type @a _type.
IRVariable(IRGenerationContext const& _analysis, std::string _baseName, Type _type);
/// IR variable referring to the declaration @a _decl.
IRVariable(IRGenerationContext const& _analysis, VariableDeclaration const& _decl);
/// IR variable referring to the expression @a _expr.
IRVariable(IRGenerationContext const& _analysis, Expression const& _expression);
/// @returns the name of the variable, if it occupies a single stack slot (otherwise throws).
std::string name() const;
/// @returns a comma-separated list of the stack slots of the variable.
std::string commaSeparatedList() const;
/// @returns a comma-separated list of the stack slots of the variable that is
/// prefixed with a comma, unless it is empty.
std::string commaSeparatedListPrefixed() const;
/// @returns an IRVariable referring to the tuple component @a _i of a tuple variable.
IRVariable tupleComponent(std::size_t _i) const;
/// @returns the type of the variable.
Type const& type() const { return m_type; }
/// @returns an IRVariable referring to the stack component @a _slot of the variable.
/// @a _slot must be among the stack slots in ``m_type.stackItems()``.
/// The returned IRVariable is itself typed with the type of the stack slot as defined
/// in ``m_type.stackItems()`` and may again occupy multiple stack slots.
IRVariable part(std::string const& _slot) const;
/// @returns true if variable contains @a _name component
/// @a _name name of the component that is being checked
bool hasPart(std::string const& _name) const;
/// @returns a vector containing the names of the stack slots of the variable.
std::vector<std::string> stackSlots() const;
private:
/// @returns a name consisting of the base name appended with an underscore and @æ _suffix,
/// unless @a _suffix is empty, in which case the base name itself is returned.
std::string suffixedName(std::string const& _suffix) const;
std::string m_baseName;
Type m_type;
};
}