[Yul] Support conditionals

This commit is contained in:
Leonardo Alt 2020-02-13 15:42:16 -04:00
parent c635377450
commit 3800391a1a
7 changed files with 77 additions and 0 deletions

View File

@ -180,6 +180,24 @@ void IRGeneratorForStatements::endVisit(VariableDeclarationStatement const& _var
declare(m_context.addLocalVariable(*decl));
}
bool IRGeneratorForStatements::visit(Conditional const& _conditional)
{
_conditional.condition().accept(*this);
string condition = expressionAsType(_conditional.condition(), *TypeProvider::boolean());
declare(_conditional);
m_code << "switch " << condition << "\n" "case 0 {\n";
_conditional.falseExpression().accept(*this);
assign(_conditional, _conditional.falseExpression());
m_code << "}\n" "default {\n";
_conditional.trueExpression().accept(*this);
assign(_conditional, _conditional.trueExpression());
m_code << "}\n";
return false;
}
bool IRGeneratorForStatements::visit(Assignment const& _assignment)
{
_assignment.rightHandSide().accept(*this);

View File

@ -48,6 +48,7 @@ public:
void initializeStateVar(VariableDeclaration const& _varDecl);
void endVisit(VariableDeclarationStatement const& _variableDeclaration) override;
bool visit(Conditional const& _conditional) override;
bool visit(Assignment const& _assignment) override;
bool visit(TupleExpression const& _tuple) override;
bool visit(IfStatement const& _ifStatement) override;

View File

@ -0,0 +1,10 @@
contract A {
function f() public pure returns (uint) {
uint x = 3 < 0 ? 2 > 1 ? 2 : 1 : 7 > 2 ? 7 : 6;
return x;
}
}
// ====
// compileViaYul: also
// ----
// f() -> 7

View File

@ -0,0 +1,11 @@
contract A {
function f() public pure returns (uint) {
uint x = true ? 1 : 0;
uint y = false ? 0 : 1;
return x + y;
}
}
// ====
// compileViaYul: also
// ----
// f() -> 2

View File

@ -0,0 +1,11 @@
contract A {
function f(bool cond) public pure returns (uint, uint) {
(uint a, uint b) = cond ? (1, 2) : (3, 4);
return (a, b);
}
}
// ====
// compileViaYul: also
// ----
// f(bool): true -> 1, 2
// f(bool): false -> 3, 4

View File

@ -0,0 +1,13 @@
contract A {
function f() public pure returns (uint, uint, uint, uint) {
uint y1 = 1;
uint y2 = 1;
uint x = 3 < 0 ? y1 = 3 : 6;
uint z = 3 < 10 ? y2 = 5 : 6;
return (x, y1, y2, z);
}
}
// ====
// compileViaYul: also
// ----
// f() -> 6, 1, 5, 5

View File

@ -0,0 +1,13 @@
contract A {
function f() public pure returns (uint, uint, uint, uint) {
uint x = 3;
uint y = 1;
uint z = (x > y) ? x : y;
uint w = x < y ? x : y;
return (x, y, z, w);
}
}
// ====
// compileViaYul: also
// ----
// f() -> 3, 1, 3, 1