Merge pull request #8321 from ethereum/removeStackFromAsmAnalysis

Remove stack counting from Asm Analysis.
This commit is contained in:
chriseth 2020-02-17 14:32:17 +01:00 committed by GitHub
commit 2d1c4b770f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 194 additions and 298 deletions

View File

@ -45,14 +45,14 @@ using namespace solidity::langutil;
bool AsmAnalyzer::analyze(Block const& _block) bool AsmAnalyzer::analyze(Block const& _block)
{ {
bool success = false; m_success = true;
try try
{ {
if (!(ScopeFiller(m_info, m_errorReporter))(_block)) if (!(ScopeFiller(m_info, m_errorReporter))(_block))
return false; return false;
success = (*this)(_block); (*this)(_block);
if (!success) if (!m_success)
yulAssert(m_errorReporter.hasErrors(), "No success but no error."); yulAssert(m_errorReporter.hasErrors(), "No success but no error.");
} }
catch (FatalError const&) catch (FatalError const&)
@ -60,7 +60,7 @@ bool AsmAnalyzer::analyze(Block const& _block)
// This FatalError con occur if the errorReporter has too many errors. // This FatalError con occur if the errorReporter has too many errors.
yulAssert(!m_errorReporter.errors().empty(), "Fatal error detected, but no error is reported."); yulAssert(!m_errorReporter.errors().empty(), "Fatal error detected, but no error is reported.");
} }
return success && !m_errorReporter.hasErrors(); return m_success && !m_errorReporter.hasErrors();
} }
AsmAnalysisInfo AsmAnalyzer::analyzeStrictAssertCorrect(Dialect const& _dialect, Object const& _object) AsmAnalysisInfo AsmAnalyzer::analyzeStrictAssertCorrect(Dialect const& _dialect, Object const& _object)
@ -79,127 +79,112 @@ AsmAnalysisInfo AsmAnalyzer::analyzeStrictAssertCorrect(Dialect const& _dialect,
return analysisInfo; return analysisInfo;
} }
bool AsmAnalyzer::operator()(Literal const& _literal) vector<YulString> AsmAnalyzer::operator()(Literal const& _literal)
{ {
expectValidType(_literal.type, _literal.location); expectValidType(_literal.type, _literal.location);
++m_stackHeight;
if (_literal.kind == LiteralKind::String && _literal.value.str().size() > 32) if (_literal.kind == LiteralKind::String && _literal.value.str().size() > 32)
{ typeError(
m_errorReporter.typeError(
_literal.location, _literal.location,
"String literal too long (" + to_string(_literal.value.str().size()) + " > 32)" "String literal too long (" + to_string(_literal.value.str().size()) + " > 32)"
); );
return false;
}
else if (_literal.kind == LiteralKind::Number && bigint(_literal.value.str()) > u256(-1)) else if (_literal.kind == LiteralKind::Number && bigint(_literal.value.str()) > u256(-1))
{ typeError(_literal.location, "Number literal too large (> 256 bits)");
m_errorReporter.typeError(
_literal.location,
"Number literal too large (> 256 bits)"
);
return false;
}
else if (_literal.kind == LiteralKind::Boolean) else if (_literal.kind == LiteralKind::Boolean)
yulAssert(_literal.value == "true"_yulstring || _literal.value == "false"_yulstring, ""); yulAssert(_literal.value == "true"_yulstring || _literal.value == "false"_yulstring, "");
return true;
return {_literal.type};
} }
bool AsmAnalyzer::operator()(Identifier const& _identifier) vector<YulString> AsmAnalyzer::operator()(Identifier const& _identifier)
{ {
yulAssert(!_identifier.name.empty(), ""); yulAssert(!_identifier.name.empty(), "");
size_t numErrorsBefore = m_errorReporter.errors().size(); size_t numErrorsBefore = m_errorReporter.errors().size();
bool success = true; YulString type = m_dialect.defaultType;
if (m_currentScope->lookup(_identifier.name, GenericVisitor{ if (m_currentScope->lookup(_identifier.name, GenericVisitor{
[&](Scope::Variable const& _var) [&](Scope::Variable const& _var)
{ {
if (!m_activeVariables.count(&_var)) if (!m_activeVariables.count(&_var))
{ declarationError(
m_errorReporter.declarationError(
_identifier.location, _identifier.location,
"Variable " + _identifier.name.str() + " used before it was declared." "Variable " + _identifier.name.str() + " used before it was declared."
); );
success = false; type = _var.type;
}
++m_stackHeight;
}, },
[&](Scope::Function const&) [&](Scope::Function const&)
{ {
m_errorReporter.typeError( typeError(
_identifier.location, _identifier.location,
"Function " + _identifier.name.str() + " used without being called." "Function " + _identifier.name.str() + " used without being called."
); );
success = false;
} }
})) }))
{ {
} }
else else
{ {
size_t stackSize(-1); bool found = false;
if (m_resolver) if (m_resolver)
{ {
bool insideFunction = m_currentScope->insideFunction(); bool insideFunction = m_currentScope->insideFunction();
stackSize = m_resolver(_identifier, yul::IdentifierContext::RValue, insideFunction); size_t stackSize = m_resolver(_identifier, yul::IdentifierContext::RValue, insideFunction);
if (stackSize != size_t(-1))
{
found = true;
yulAssert(stackSize == 1, "Invalid stack size of external reference.");
} }
if (stackSize == size_t(-1)) }
if (!found)
{ {
// Only add an error message if the callback did not do it. // Only add an error message if the callback did not do it.
if (numErrorsBefore == m_errorReporter.errors().size()) if (numErrorsBefore == m_errorReporter.errors().size())
m_errorReporter.declarationError(_identifier.location, "Identifier not found."); declarationError(_identifier.location, "Identifier not found.");
success = false; m_success = false;
} }
m_stackHeight += stackSize == size_t(-1) ? 1 : stackSize;
} }
return success;
return {type};
} }
bool AsmAnalyzer::operator()(ExpressionStatement const& _statement) void AsmAnalyzer::operator()(ExpressionStatement const& _statement)
{ {
int initialStackHeight = m_stackHeight; vector<YulString> types = std::visit(*this, _statement.expression);
bool success = std::visit(*this, _statement.expression); if (m_success && !types.empty())
if (success && m_stackHeight != initialStackHeight) typeError(_statement.location,
{
string msg =
"Top-level expressions are not supposed to return values (this expression returns " + "Top-level expressions are not supposed to return values (this expression returns " +
to_string(m_stackHeight - initialStackHeight) + to_string(types.size()) +
" value" + " value" +
(m_stackHeight - initialStackHeight == 1 ? "" : "s") + (types.size() == 1 ? "" : "s") +
"). Use ``pop()`` or assign them."; "). Use ``pop()`` or assign them."
m_errorReporter.error(Error::Type::TypeError, _statement.location, msg); );
success = false;
}
return success;
} }
bool AsmAnalyzer::operator()(Assignment const& _assignment) void AsmAnalyzer::operator()(Assignment const& _assignment)
{ {
yulAssert(_assignment.value, ""); yulAssert(_assignment.value, "");
int const expectedItems = _assignment.variableNames.size(); size_t const numVariables = _assignment.variableNames.size();
yulAssert(expectedItems >= 1, ""); yulAssert(numVariables >= 1, "");
int const stackHeight = m_stackHeight;
bool success = std::visit(*this, *_assignment.value); vector<YulString> types = std::visit(*this, *_assignment.value);
if ((m_stackHeight - stackHeight) != expectedItems)
{ if (types.size() != numVariables)
m_errorReporter.declarationError( declarationError(
_assignment.location, _assignment.location,
"Variable count does not match number of values (" + "Variable count does not match number of values (" +
to_string(expectedItems) + to_string(numVariables) +
" vs. " + " vs. " +
to_string(m_stackHeight - stackHeight) + to_string(types.size()) +
")" ")"
); );
return false;
} for (size_t i = 0; i < numVariables; ++i)
for (auto const& variableName: _assignment.variableNames) checkAssignment(_assignment.variableNames[i]);
if (!checkAssignment(variableName, 1))
success = false;
return success;
} }
bool AsmAnalyzer::operator()(VariableDeclaration const& _varDecl) void AsmAnalyzer::operator()(VariableDeclaration const& _varDecl)
{ {
bool success = true; size_t const numVariables = _varDecl.variables.size();
int const numVariables = _varDecl.variables.size();
if (m_resolver) if (m_resolver)
for (auto const& variable: _varDecl.variables) for (auto const& variable: _varDecl.variables)
// Call the resolver for variable declarations to allow it to raise errors on shadowing. // Call the resolver for variable declarations to allow it to raise errors on shadowing.
@ -210,35 +195,27 @@ bool AsmAnalyzer::operator()(VariableDeclaration const& _varDecl)
); );
if (_varDecl.value) if (_varDecl.value)
{ {
int const stackHeight = m_stackHeight; vector<YulString> types = std::visit(*this, *_varDecl.value);
success = std::visit(*this, *_varDecl.value); if (types.size() != numVariables)
int numValues = m_stackHeight - stackHeight; declarationError(_varDecl.location,
if (numValues != numVariables)
{
m_errorReporter.declarationError(_varDecl.location,
"Variable count mismatch: " + "Variable count mismatch: " +
to_string(numVariables) + to_string(numVariables) +
" variables and " + " variables and " +
to_string(numValues) + to_string(types.size()) +
" values." " values."
); );
// Adjust stack height to avoid misleading additional errors.
m_stackHeight += numVariables - numValues;
return false;
} }
}
else
m_stackHeight += numVariables;
for (auto const& variable: _varDecl.variables) for (TypedName const& variable: _varDecl.variables)
{ {
expectValidType(variable.type, variable.location); expectValidType(variable.type, variable.location);
m_activeVariables.insert(&std::get<Scope::Variable>(m_currentScope->identifiers.at(variable.name))); m_activeVariables.insert(&std::get<Scope::Variable>(
m_currentScope->identifiers.at(variable.name))
);
} }
return success;
} }
bool AsmAnalyzer::operator()(FunctionDefinition const& _funDef) void AsmAnalyzer::operator()(FunctionDefinition const& _funDef)
{ {
yulAssert(!_funDef.name.empty(), ""); yulAssert(!_funDef.name.empty(), "");
Block const* virtualBlock = m_info.virtualBlocks.at(&_funDef).get(); Block const* virtualBlock = m_info.virtualBlocks.at(&_funDef).get();
@ -250,112 +227,95 @@ bool AsmAnalyzer::operator()(FunctionDefinition const& _funDef)
m_activeVariables.insert(&std::get<Scope::Variable>(varScope.identifiers.at(var.name))); m_activeVariables.insert(&std::get<Scope::Variable>(varScope.identifiers.at(var.name)));
} }
int const stackHeight = m_stackHeight; (*this)(_funDef.body);
m_stackHeight = _funDef.parameters.size() + _funDef.returnVariables.size();
bool success = (*this)(_funDef.body);
m_stackHeight = stackHeight;
return success;
} }
bool AsmAnalyzer::operator()(FunctionCall const& _funCall) vector<YulString> AsmAnalyzer::operator()(FunctionCall const& _funCall)
{ {
yulAssert(!_funCall.functionName.name.empty(), ""); yulAssert(!_funCall.functionName.name.empty(), "");
bool success = true; vector<YulString> const* parameterTypes = nullptr;
size_t parameters = 0; vector<YulString> const* returnTypes = nullptr;
size_t returns = 0;
bool needsLiteralArguments = false; bool needsLiteralArguments = false;
if (BuiltinFunction const* f = m_dialect.builtin(_funCall.functionName.name)) if (BuiltinFunction const* f = m_dialect.builtin(_funCall.functionName.name))
{ {
// TODO: compare types, too parameterTypes = &f->parameters;
parameters = f->parameters.size(); returnTypes = &f->returns;
returns = f->returns.size();
if (f->literalArguments) if (f->literalArguments)
needsLiteralArguments = true; needsLiteralArguments = true;
} }
else if (!m_currentScope->lookup(_funCall.functionName.name, GenericVisitor{ else if (!m_currentScope->lookup(_funCall.functionName.name, GenericVisitor{
[&](Scope::Variable const&) [&](Scope::Variable const&)
{ {
m_errorReporter.typeError( typeError(
_funCall.functionName.location, _funCall.functionName.location,
"Attempt to call variable instead of function." "Attempt to call variable instead of function."
); );
success = false;
}, },
[&](Scope::Function const& _fun) [&](Scope::Function const& _fun)
{ {
/// TODO: compare types too parameterTypes = &_fun.arguments;
parameters = _fun.arguments.size(); returnTypes = &_fun.returns;
returns = _fun.returns.size();
} }
})) }))
{ {
if (!warnOnInstructions(_funCall.functionName.name.str(), _funCall.functionName.location)) if (!warnOnInstructions(_funCall.functionName.name.str(), _funCall.functionName.location))
m_errorReporter.declarationError(_funCall.functionName.location, "Function not found."); declarationError(_funCall.functionName.location, "Function not found.");
success = false; m_success = false;
} }
if (success) if (parameterTypes && _funCall.arguments.size() != parameterTypes->size())
if (_funCall.arguments.size() != parameters) typeError(
{
m_errorReporter.typeError(
_funCall.functionName.location, _funCall.functionName.location,
"Function expects " + "Function expects " +
to_string(parameters) + to_string(parameterTypes->size()) +
" arguments but got " + " arguments but got " +
to_string(_funCall.arguments.size()) + "." to_string(_funCall.arguments.size()) + "."
); );
success = false;
}
vector<YulString> argTypes;
for (auto const& arg: _funCall.arguments | boost::adaptors::reversed) for (auto const& arg: _funCall.arguments | boost::adaptors::reversed)
{ {
if (!expectExpression(arg)) argTypes.emplace_back(expectExpression(arg));
success = false;
else if (needsLiteralArguments) if (needsLiteralArguments)
{ {
if (!holds_alternative<Literal>(arg)) if (!holds_alternative<Literal>(arg))
m_errorReporter.typeError( typeError(
_funCall.functionName.location, _funCall.functionName.location,
"Function expects direct literals as arguments." "Function expects direct literals as arguments."
); );
else if (!m_dataNames.count(std::get<Literal>(arg).value)) else if (!m_dataNames.count(std::get<Literal>(arg).value))
m_errorReporter.typeError( typeError(
_funCall.functionName.location, _funCall.functionName.location,
"Unknown data object \"" + std::get<Literal>(arg).value.str() + "\"." "Unknown data object \"" + std::get<Literal>(arg).value.str() + "\"."
); );
} }
} }
// Use argument size instead of parameter count to avoid misleading errors.
m_stackHeight += int(returns) - int(_funCall.arguments.size()); if (m_success)
return success; {
yulAssert(parameterTypes && parameterTypes->size() == argTypes.size(), "");
yulAssert(returnTypes, "");
return *returnTypes;
}
else if (returnTypes)
return vector<YulString>(returnTypes->size(), m_dialect.defaultType);
else
return {};
} }
bool AsmAnalyzer::operator()(If const& _if) void AsmAnalyzer::operator()(If const& _if)
{ {
bool success = true; expectExpression(*_if.condition);
int const initialHeight = m_stackHeight; (*this)(_if.body);
if (!expectExpression(*_if.condition))
success = false;
m_stackHeight = initialHeight;
if (!(*this)(_if.body))
success = false;
return success;
} }
bool AsmAnalyzer::operator()(Switch const& _switch) void AsmAnalyzer::operator()(Switch const& _switch)
{ {
yulAssert(_switch.expression, ""); yulAssert(_switch.expression, "");
bool success = true; expectExpression(*_switch.expression);
int const initialHeight = m_stackHeight;
if (!expectExpression(*_switch.expression))
success = false;
YulString caseType; YulString caseType;
bool mismatchingTypes = false; bool mismatchingTypes = false;
@ -370,7 +330,6 @@ bool AsmAnalyzer::operator()(Switch const& _switch)
break; break;
} }
} }
if (mismatchingTypes) if (mismatchingTypes)
m_errorReporter.typeError( m_errorReporter.typeError(
_switch.location, _switch.location,
@ -382,191 +341,103 @@ bool AsmAnalyzer::operator()(Switch const& _switch)
{ {
if (_case.value) if (_case.value)
{ {
int const initialStackHeight = m_stackHeight; // We cannot use "expectExpression" here because *_case.value is not an
bool isCaseValueValid = true; // Expression and would be converted to an Expression otherwise.
// We cannot use "expectExpression" here because *_case.value is not a (*this)(*_case.value);
// Statement and would be converted to a Statement otherwise.
if (!(*this)(*_case.value))
{
isCaseValueValid = false;
success = false;
}
expectDeposit(1, initialStackHeight, _case.value->location);
m_stackHeight--;
// If the case value is not valid, we should not insert it into cases.
yulAssert(isCaseValueValid || m_errorReporter.hasErrors(), "Invalid case value.");
/// Note: the parser ensures there is only one default case /// Note: the parser ensures there is only one default case
if (isCaseValueValid && !cases.insert(valueOfLiteral(*_case.value)).second) if (m_success && !cases.insert(valueOfLiteral(*_case.value)).second)
{ declarationError(_case.location, "Duplicate case defined.");
m_errorReporter.declarationError(
_case.location,
"Duplicate case defined."
);
success = false;
}
} }
if (!(*this)(_case.body)) (*this)(_case.body);
success = false;
} }
m_stackHeight = initialHeight;
return success;
} }
bool AsmAnalyzer::operator()(ForLoop const& _for) void AsmAnalyzer::operator()(ForLoop const& _for)
{ {
yulAssert(_for.condition, ""); yulAssert(_for.condition, "");
Scope* outerScope = m_currentScope; Scope* outerScope = m_currentScope;
int const initialHeight = m_stackHeight; (*this)(_for.pre);
bool success = true;
if (!(*this)(_for.pre))
success = false;
// The block was closed already, but we re-open it again and stuff the // The block was closed already, but we re-open it again and stuff the
// condition, the body and the post part inside. // condition, the body and the post part inside.
m_stackHeight += scope(&_for.pre).numberOfVariables();
m_currentScope = &scope(&_for.pre); m_currentScope = &scope(&_for.pre);
if (!expectExpression(*_for.condition)) expectExpression(*_for.condition);
success = false;
m_stackHeight--;
// backup outer for-loop & create new state // backup outer for-loop & create new state
auto outerForLoop = m_currentForLoop; auto outerForLoop = m_currentForLoop;
m_currentForLoop = &_for; m_currentForLoop = &_for;
if (!(*this)(_for.body)) (*this)(_for.body);
success = false; (*this)(_for.post);
if (!(*this)(_for.post))
success = false;
m_stackHeight = initialHeight;
m_currentScope = outerScope; m_currentScope = outerScope;
m_currentForLoop = outerForLoop; m_currentForLoop = outerForLoop;
return success;
} }
bool AsmAnalyzer::operator()(Block const& _block) void AsmAnalyzer::operator()(Block const& _block)
{ {
bool success = true;
auto previousScope = m_currentScope; auto previousScope = m_currentScope;
m_currentScope = &scope(&_block); m_currentScope = &scope(&_block);
int const initialStackHeight = m_stackHeight;
for (auto const& s: _block.statements) for (auto const& s: _block.statements)
if (!std::visit(*this, s)) std::visit(*this, s);
success = false;
m_stackHeight -= scope(&_block).numberOfVariables();
int const stackDiff = m_stackHeight - initialStackHeight;
if (success && stackDiff != 0)
{
m_errorReporter.declarationError(
_block.location,
"Unbalanced stack at the end of a block: " +
(
stackDiff > 0 ?
to_string(stackDiff) + string(" surplus item(s).") :
to_string(-stackDiff) + string(" missing item(s).")
)
);
success = false;
}
m_currentScope = previousScope; m_currentScope = previousScope;
return success;
} }
bool AsmAnalyzer::expectExpression(Expression const& _expr) YulString AsmAnalyzer::expectExpression(Expression const& _expr)
{ {
bool success = true; vector<YulString> types = std::visit(*this, _expr);
int const initialHeight = m_stackHeight; if (types.size() != 1)
if (!std::visit(*this, _expr)) typeError(
success = false; locationOf(_expr),
if (success && !expectDeposit(1, initialHeight, locationOf(_expr))) "Expected expression to evaluate to one value, but got " +
success = false; to_string(types.size()) +
return success; " values instead."
}
bool AsmAnalyzer::expectDeposit(int _deposit, int _oldHeight, SourceLocation const& _location)
{
if (m_stackHeight - _oldHeight != _deposit)
{
m_errorReporter.typeError(
_location,
"Expected expression to return one item to the stack, but did return " +
to_string(m_stackHeight - _oldHeight) +
" items."
); );
return false; return types.empty() ? m_dialect.defaultType : types.front();
}
return true;
} }
bool AsmAnalyzer::checkAssignment(Identifier const& _variable, size_t _valueSize) void AsmAnalyzer::checkAssignment(Identifier const& _variable)
{ {
yulAssert(!_variable.name.empty(), ""); yulAssert(!_variable.name.empty(), "");
bool success = true;
size_t numErrorsBefore = m_errorReporter.errors().size(); size_t numErrorsBefore = m_errorReporter.errors().size();
size_t variableSize(-1); bool found = false;
if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name)) if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name))
{ {
// Check that it is a variable // Check that it is a variable
if (!holds_alternative<Scope::Variable>(*var)) if (!holds_alternative<Scope::Variable>(*var))
{ typeError(_variable.location, "Assignment requires variable.");
m_errorReporter.typeError(_variable.location, "Assignment requires variable.");
success = false;
}
else if (!m_activeVariables.count(&std::get<Scope::Variable>(*var))) else if (!m_activeVariables.count(&std::get<Scope::Variable>(*var)))
{ declarationError(
m_errorReporter.declarationError(
_variable.location, _variable.location,
"Variable " + _variable.name.str() + " used before it was declared." "Variable " + _variable.name.str() + " used before it was declared."
); );
success = false; found = true;
}
variableSize = 1;
} }
else if (m_resolver) else if (m_resolver)
{ {
bool insideFunction = m_currentScope->insideFunction(); bool insideFunction = m_currentScope->insideFunction();
variableSize = m_resolver(_variable, yul::IdentifierContext::LValue, insideFunction); size_t variableSize = m_resolver(_variable, yul::IdentifierContext::LValue, insideFunction);
} if (variableSize != size_t(-1))
if (variableSize == size_t(-1))
{ {
found = true;
yulAssert(variableSize == 1, "Invalid stack size of external reference.");
}
}
if (!found)
{
m_success = false;
// Only add message if the callback did not. // Only add message if the callback did not.
if (numErrorsBefore == m_errorReporter.errors().size()) if (numErrorsBefore == m_errorReporter.errors().size())
m_errorReporter.declarationError(_variable.location, "Variable not found or variable not lvalue."); declarationError(_variable.location, "Variable not found or variable not lvalue.");
success = false;
} }
if (_valueSize == size_t(-1))
_valueSize = variableSize == size_t(-1) ? 1 : variableSize;
m_stackHeight -= _valueSize;
if (_valueSize != variableSize && variableSize != size_t(-1))
{
m_errorReporter.typeError(
_variable.location,
"Variable size (" +
to_string(variableSize) +
") and value size (" +
to_string(_valueSize) +
") do not match."
);
success = false;
}
return success;
} }
Scope& AsmAnalyzer::scope(Block const* _block) Scope& AsmAnalyzer::scope(Block const* _block)
@ -603,7 +474,7 @@ bool AsmAnalyzer::warnOnInstructions(evmasm::Instruction _instr, SourceLocation
yulAssert(m_evmVersion.hasBitwiseShifting() == m_evmVersion.hasCreate2(), ""); yulAssert(m_evmVersion.hasBitwiseShifting() == m_evmVersion.hasCreate2(), "");
auto errorForVM = [=](string const& vmKindMessage) { auto errorForVM = [=](string const& vmKindMessage) {
m_errorReporter.typeError( typeError(
_location, _location,
"The \"" + "The \"" +
boost::to_lower_copy(instructionInfo(_instr).name) boost::to_lower_copy(instructionInfo(_instr).name)
@ -664,9 +535,23 @@ bool AsmAnalyzer::warnOnInstructions(evmasm::Instruction _instr, SourceLocation
"incorrect stack access. Because of that they are disallowed in strict assembly. " "incorrect stack access. Because of that they are disallowed in strict assembly. "
"Use functions, \"switch\", \"if\" or \"for\" statements instead." "Use functions, \"switch\", \"if\" or \"for\" statements instead."
); );
m_success = false;
} }
else else
return false; return false;
return true; return true;
} }
void AsmAnalyzer::typeError(SourceLocation const& _location, string const& _description)
{
m_errorReporter.typeError(_location, _description);
m_success = false;
}
void AsmAnalyzer::declarationError(SourceLocation const& _location, string const& _description)
{
m_errorReporter.declarationError(_location, _description);
m_success = false;
}

View File

@ -77,36 +77,40 @@ public:
/// Asserts on failure. /// Asserts on failure.
static AsmAnalysisInfo analyzeStrictAssertCorrect(Dialect const& _dialect, Object const& _object); static AsmAnalysisInfo analyzeStrictAssertCorrect(Dialect const& _dialect, Object const& _object);
bool operator()(Literal const& _literal); std::vector<YulString> operator()(Literal const& _literal);
bool operator()(Identifier const&); std::vector<YulString> operator()(Identifier const&);
bool operator()(ExpressionStatement const&); void operator()(ExpressionStatement const&);
bool operator()(Assignment const& _assignment); void operator()(Assignment const& _assignment);
bool operator()(VariableDeclaration const& _variableDeclaration); void operator()(VariableDeclaration const& _variableDeclaration);
bool operator()(FunctionDefinition const& _functionDefinition); void operator()(FunctionDefinition const& _functionDefinition);
bool operator()(FunctionCall const& _functionCall); std::vector<YulString> operator()(FunctionCall const& _functionCall);
bool operator()(If const& _if); void operator()(If const& _if);
bool operator()(Switch const& _switch); void operator()(Switch const& _switch);
bool operator()(ForLoop const& _forLoop); void operator()(ForLoop const& _forLoop);
bool operator()(Break const&) { return true; } void operator()(Break const&) { }
bool operator()(Continue const&) { return true; } void operator()(Continue const&) { }
bool operator()(Leave const&) { return true; } void operator()(Leave const&) { }
bool operator()(Block const& _block); void operator()(Block const& _block);
private: private:
/// Visits the statement and expects it to deposit one item onto the stack. /// Visits the expression, expects that it evaluates to exactly one value and
bool expectExpression(Expression const& _expr); /// returns the type. Reports errors on errors and returns the default type.
YulString expectExpression(Expression const& _expr);
bool expectDeposit(int _deposit, int _oldHeight, langutil::SourceLocation const& _location); bool expectDeposit(int _deposit, int _oldHeight, langutil::SourceLocation const& _location);
/// Verifies that a variable to be assigned to exists and has the same size /// Verifies that a variable to be assigned to exists and can be assigned to.
/// as the value, @a _valueSize, unless that is equal to -1. void checkAssignment(Identifier const& _variable);
bool checkAssignment(Identifier const& _assignment, size_t _valueSize = size_t(-1));
Scope& scope(Block const* _block); Scope& scope(Block const* _block);
void expectValidType(YulString _type, langutil::SourceLocation const& _location); void expectValidType(YulString _type, langutil::SourceLocation const& _location);
bool warnOnInstructions(evmasm::Instruction _instr, langutil::SourceLocation const& _location); bool warnOnInstructions(evmasm::Instruction _instr, langutil::SourceLocation const& _location);
bool warnOnInstructions(std::string const& _instrIdentifier, langutil::SourceLocation const& _location); bool warnOnInstructions(std::string const& _instrIdentifier, langutil::SourceLocation const& _location);
int m_stackHeight = 0; void typeError(langutil::SourceLocation const& _location, std::string const& _description);
void declarationError(langutil::SourceLocation const& _location, std::string const& _description);
/// Success-flag, can be set to false at any time.
bool m_success = true;
yul::ExternalIdentifierAccess::Resolver m_resolver; yul::ExternalIdentifierAccess::Resolver m_resolver;
Scope* m_currentScope = nullptr; Scope* m_currentScope = nullptr;
/// Variables that are active at the current point in assembly (as opposed to /// Variables that are active at the current point in assembly (as opposed to

View File

@ -287,7 +287,7 @@ BOOST_AUTO_TEST_CASE(if_statement_invalid)
{ {
CHECK_PARSE_ERROR("{ if mload {} }", ParserError, "Expected '(' but got '{'"); CHECK_PARSE_ERROR("{ if mload {} }", ParserError, "Expected '(' but got '{'");
BOOST_CHECK("{ if calldatasize() {}"); BOOST_CHECK("{ if calldatasize() {}");
CHECK_PARSE_ERROR("{ if mstore(1, 1) {} }", TypeError, "Expected expression to return one item to the stack, but did return 0 items"); CHECK_PARSE_ERROR("{ if mstore(1, 1) {} }", TypeError, "Expected expression to evaluate to one value, but got 0 values instead.");
CHECK_PARSE_ERROR("{ if 32 let x := 3 }", ParserError, "Expected '{' but got reserved keyword 'let'"); CHECK_PARSE_ERROR("{ if 32 let x := 3 }", ParserError, "Expected '{' but got reserved keyword 'let'");
} }
@ -316,7 +316,7 @@ BOOST_AUTO_TEST_CASE(switch_invalid_expression)
{ {
CHECK_PARSE_ERROR("{ switch {} default {} }", ParserError, "Literal or identifier expected."); CHECK_PARSE_ERROR("{ switch {} default {} }", ParserError, "Literal or identifier expected.");
CHECK_PARSE_ERROR("{ switch mload default {} }", ParserError, "Expected '(' but got reserved keyword 'default'"); CHECK_PARSE_ERROR("{ switch mload default {} }", ParserError, "Expected '(' but got reserved keyword 'default'");
CHECK_PARSE_ERROR("{ switch mstore(1, 1) default {} }", TypeError, "Expected expression to return one item to the stack, but did return 0 items"); CHECK_PARSE_ERROR("{ switch mstore(1, 1) default {} }", TypeError, "Expected expression to evaluate to one value, but got 0 values instead.");
} }
BOOST_AUTO_TEST_CASE(switch_default_before_case) BOOST_AUTO_TEST_CASE(switch_default_before_case)
@ -352,7 +352,7 @@ BOOST_AUTO_TEST_CASE(for_invalid_expression)
CHECK_PARSE_ERROR("{ for {} 1 1 {} }", ParserError, "Expected '{' but got 'Number'"); CHECK_PARSE_ERROR("{ for {} 1 1 {} }", ParserError, "Expected '{' but got 'Number'");
CHECK_PARSE_ERROR("{ for {} 1 {} 1 }", ParserError, "Expected '{' but got 'Number'"); CHECK_PARSE_ERROR("{ for {} 1 {} 1 }", ParserError, "Expected '{' but got 'Number'");
CHECK_PARSE_ERROR("{ for {} mload {} {} }", ParserError, "Expected '(' but got '{'"); CHECK_PARSE_ERROR("{ for {} mload {} {} }", ParserError, "Expected '(' but got '{'");
CHECK_PARSE_ERROR("{ for {} mstore(1, 1) {} {} }", TypeError, "Expected expression to return one item to the stack, but did return 0 items"); CHECK_PARSE_ERROR("{ for {} mstore(1, 1) {} {} }", TypeError, "Expected expression to evaluate to one value, but got 0 values instead.");
} }
BOOST_AUTO_TEST_CASE(for_visibility) BOOST_AUTO_TEST_CASE(for_visibility)
@ -732,9 +732,9 @@ BOOST_AUTO_TEST_CASE(shift_constantinople_warning)
{ {
if (solidity::test::CommonOptions::get().evmVersion().hasBitwiseShifting()) if (solidity::test::CommonOptions::get().evmVersion().hasBitwiseShifting())
return; return;
CHECK_PARSE_WARNING("{ pop(shl(10, 32)) }", TypeError, "The \"shl\" instruction is only available for Constantinople-compatible VMs"); CHECK_PARSE_WARNING("{ shl(10, 32) }", TypeError, "The \"shl\" instruction is only available for Constantinople-compatible VMs");
CHECK_PARSE_WARNING("{ pop(shr(10, 32)) }", TypeError, "The \"shr\" instruction is only available for Constantinople-compatible VMs"); CHECK_PARSE_WARNING("{ shr(10, 32) }", TypeError, "The \"shr\" instruction is only available for Constantinople-compatible VMs");
CHECK_PARSE_WARNING("{ pop(sar(10, 32)) }", TypeError, "The \"sar\" instruction is only available for Constantinople-compatible VMs"); CHECK_PARSE_WARNING("{ sar(10, 32) }", TypeError, "The \"sar\" instruction is only available for Constantinople-compatible VMs");
} }
BOOST_AUTO_TEST_CASE(jump_error) BOOST_AUTO_TEST_CASE(jump_error)

View File

@ -387,7 +387,10 @@ BOOST_AUTO_TEST_CASE(returndatasize_as_variable)
{Error::Type::Warning, "Variable is shadowed in inline assembly by an instruction of the same name"} {Error::Type::Warning, "Variable is shadowed in inline assembly by an instruction of the same name"}
}); });
if (!solidity::test::CommonOptions::get().evmVersion().supportsReturndata()) if (!solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
{
expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("\"returndatasize\" instruction is only available for Byzantium-compatible VMs"))); expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("\"returndatasize\" instruction is only available for Byzantium-compatible VMs")));
expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("Expected expression to evaluate to one value, but got 0 values instead.")));
}
CHECK_ALLOW_MULTI(text, expectations); CHECK_ALLOW_MULTI(text, expectations);
} }
@ -402,7 +405,10 @@ BOOST_AUTO_TEST_CASE(create2_as_variable)
{Error::Type::Warning, "Variable is shadowed in inline assembly by an instruction of the same name"} {Error::Type::Warning, "Variable is shadowed in inline assembly by an instruction of the same name"}
}); });
if (!solidity::test::CommonOptions::get().evmVersion().hasCreate2()) if (!solidity::test::CommonOptions::get().evmVersion().hasCreate2())
{
expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("\"create2\" instruction is only available for Constantinople-compatible VMs"))); expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("\"create2\" instruction is only available for Constantinople-compatible VMs")));
expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("Expected expression to evaluate to one value, but got 0 values instead.")));
}
CHECK_ALLOW_MULTI(text, expectations); CHECK_ALLOW_MULTI(text, expectations);
} }
@ -417,7 +423,10 @@ BOOST_AUTO_TEST_CASE(extcodehash_as_variable)
{Error::Type::Warning, "Variable is shadowed in inline assembly by an instruction of the same name"} {Error::Type::Warning, "Variable is shadowed in inline assembly by an instruction of the same name"}
}); });
if (!solidity::test::CommonOptions::get().evmVersion().hasExtCodeHash()) if (!solidity::test::CommonOptions::get().evmVersion().hasExtCodeHash())
{
expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("\"extcodehash\" instruction is only available for Constantinople-compatible VMs"))); expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("\"extcodehash\" instruction is only available for Constantinople-compatible VMs")));
expectations.emplace_back(make_pair(Error::Type::TypeError, std::string("Expected expression to evaluate to one value, but got 0 values instead.")));
}
CHECK_ALLOW_MULTI(text, expectations); CHECK_ALLOW_MULTI(text, expectations);
} }

View File

@ -121,9 +121,7 @@ BOOST_AUTO_TEST_CASE(assembly_staticcall)
} }
} }
)"; )";
if (!solidity::test::CommonOptions::get().evmVersion().hasStaticCall()) if (solidity::test::CommonOptions::get().evmVersion().hasStaticCall())
CHECK_ERROR(text, TypeError, "\"staticcall\" instruction is only available for Byzantium-compatible");
else
CHECK_SUCCESS_NO_WARNINGS(text); CHECK_SUCCESS_NO_WARNINGS(text);
} }