Browse Source

Merge pull request #515 from chriseth/sol_structs

Mappings and structs for Solidity
cl-refactor
chriseth 10 years ago
parent
commit
6fa0cbf85d
  1. 53
      libsolidity/AST.cpp
  2. 31
      libsolidity/AST.h
  3. 2
      libsolidity/Compiler.cpp
  4. 4
      libsolidity/CompilerContext.h
  5. 190
      libsolidity/ExpressionCompiler.cpp
  6. 77
      libsolidity/ExpressionCompiler.h
  7. 34
      libsolidity/NameAndTypeResolver.cpp
  8. 11
      libsolidity/NameAndTypeResolver.h
  9. 61
      libsolidity/Types.cpp
  10. 27
      libsolidity/Types.h
  11. 2
      test/solidityCompiler.cpp
  12. 204
      test/solidityEndToEndTest.cpp
  13. 38
      test/solidityNameAndTypeResolution.cpp

53
libsolidity/AST.cpp

@ -278,6 +278,15 @@ vector<FunctionDefinition const*> ContractDefinition::getInterfaceFunctions() co
return exportedFunctions; return exportedFunctions;
} }
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."));
m_body->checkTypeRequirements();
}
void Block::checkTypeRequirements() void Block::checkTypeRequirements()
{ {
for (shared_ptr<Statement> const& statement: m_statements) for (shared_ptr<Statement> const& statement: m_statements)
@ -315,7 +324,7 @@ void Return::checkTypeRequirements()
void VariableDefinition::checkTypeRequirements() void VariableDefinition::checkTypeRequirements()
{ {
// Variables can be declared without type (with "var"), in which case the first assignment // Variables can be declared without type (with "var"), in which case the first assignment
// setsthe type. // sets the type.
// Note that assignments before the first declaration are legal because of the special scoping // Note that assignments before the first declaration are legal because of the special scoping
// rules inherited from JavaScript. // rules inherited from JavaScript.
if (m_value) if (m_value)
@ -329,13 +338,14 @@ void VariableDefinition::checkTypeRequirements()
m_variable->setType(m_value->getType()); m_variable->setType(m_value->getType());
} }
} }
if (m_variable->getType() && !m_variable->getType()->canLiveOutsideStorage())
BOOST_THROW_EXCEPTION(m_variable->createTypeError("Type is required to live outside storage."));
} }
void Assignment::checkTypeRequirements() void Assignment::checkTypeRequirements()
{ {
m_leftHandSide->checkTypeRequirements(); m_leftHandSide->checkTypeRequirements();
if (!m_leftHandSide->isLvalue()) m_leftHandSide->requireLValue();
BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue."));
m_rightHandSide->expectType(*m_leftHandSide->getType()); m_rightHandSide->expectType(*m_leftHandSide->getType());
m_type = m_leftHandSide->getType(); m_type = m_leftHandSide->getType();
if (m_assigmentOperator != Token::ASSIGN) if (m_assigmentOperator != Token::ASSIGN)
@ -359,13 +369,19 @@ void Expression::expectType(Type const& _expectedType)
+ _expectedType.toString() + ".")); + _expectedType.toString() + "."));
} }
void Expression::requireLValue()
{
if (!isLvalue())
BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue."));
m_lvalueRequested = true;
}
void UnaryOperation::checkTypeRequirements() void UnaryOperation::checkTypeRequirements()
{ {
// INC, DEC, ADD, SUB, NOT, BIT_NOT, DELETE // INC, DEC, ADD, SUB, NOT, BIT_NOT, DELETE
m_subExpression->checkTypeRequirements(); m_subExpression->checkTypeRequirements();
if (m_operator == Token::Value::INC || m_operator == Token::Value::DEC || m_operator == Token::Value::DELETE) if (m_operator == Token::Value::INC || m_operator == Token::Value::DEC || m_operator == Token::Value::DELETE)
if (!m_subExpression->isLvalue()) m_subExpression->requireLValue();
BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue."));
m_type = m_subExpression->getType(); m_type = m_subExpression->getType();
if (!m_type->acceptsUnaryOperator(m_operator)) if (!m_type->acceptsUnaryOperator(m_operator))
BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type.")); BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type."));
@ -416,6 +432,8 @@ void FunctionCall::checkTypeRequirements()
} }
else else
{ {
m_expression->requireLValue();
//@todo would be nice to create a struct type from the arguments //@todo would be nice to create a struct type from the arguments
// and then ask if that is implicitly convertible to the struct represented by the // and then ask if that is implicitly convertible to the struct represented by the
// function parameters // function parameters
@ -442,14 +460,30 @@ bool FunctionCall::isTypeConversion() const
void MemberAccess::checkTypeRequirements() void MemberAccess::checkTypeRequirements()
{ {
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member access not yet implemented.")); m_expression->checkTypeRequirements();
// m_type = ; m_expression->requireLValue();
if (m_expression->getType()->getCategory() != Type::Category::STRUCT)
BOOST_THROW_EXCEPTION(createTypeError("Member access to a non-struct (is " +
m_expression->getType()->toString() + ")"));
StructType const& type = dynamic_cast<StructType const&>(*m_expression->getType());
unsigned memberIndex = type.memberNameToIndex(*m_memberName);
if (memberIndex >= type.getMemberCount())
BOOST_THROW_EXCEPTION(createTypeError("Member \"" + *m_memberName + "\" not found in " + type.toString()));
m_type = type.getMemberByIndex(memberIndex).getType();
m_isLvalue = true;
} }
void IndexAccess::checkTypeRequirements() void IndexAccess::checkTypeRequirements()
{ {
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Index access not yet implemented.")); m_base->checkTypeRequirements();
// m_type = ; m_base->requireLValue();
if (m_base->getType()->getCategory() != Type::Category::MAPPING)
BOOST_THROW_EXCEPTION(m_base->createTypeError("Indexed expression has to be a mapping (is " +
m_base->getType()->toString() + ")"));
MappingType const& type = dynamic_cast<MappingType const&>(*m_base->getType());
m_index->expectType(*type.getKeyType());
m_type = type.getValueType();
m_isLvalue = true;
} }
void Identifier::checkTypeRequirements() void Identifier::checkTypeRequirements()
@ -481,6 +515,7 @@ void Identifier::checkTypeRequirements()
// Calling a function (e.g. function(12), otherContract.function(34)) does not do a type // Calling a function (e.g. function(12), otherContract.function(34)) does not do a type
// conversion. // conversion.
m_type = make_shared<FunctionType>(*functionDef); m_type = make_shared<FunctionType>(*functionDef);
m_isLvalue = true;
return; return;
} }
ContractDefinition* contractDef = dynamic_cast<ContractDefinition*>(m_referencedDeclaration); ContractDefinition* contractDef = dynamic_cast<ContractDefinition*>(m_referencedDeclaration);

31
libsolidity/AST.h

@ -146,7 +146,7 @@ private:
/** /**
* Parameter list, used as function parameter list and return list. * Parameter list, used as function parameter list and return list.
* None of the parameters is allowed to contain mappings (not even recursively * None of the parameters is allowed to contain mappings (not even recursively
* inside structs), but (@todo) this is not yet enforced. * inside structs).
*/ */
class ParameterList: public ASTNode class ParameterList: public ASTNode
{ {
@ -186,6 +186,8 @@ public:
void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); } void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); }
std::vector<VariableDeclaration const*> const& getLocalVariables() const { return m_localVariables; } std::vector<VariableDeclaration const*> const& getLocalVariables() const { return m_localVariables; }
/// Checks that all parameters have allowed types and calls checkTypeRequirements on the body.
void checkTypeRequirements();
private: private:
bool m_isPublic; bool m_isPublic;
ASTPointer<ParameterList> m_parameters; ASTPointer<ParameterList> m_parameters;
@ -236,7 +238,7 @@ public:
/// Retrieve the element of the type hierarchy this node refers to. Can return an empty shared /// Retrieve the element of the type hierarchy this node refers to. Can return an empty shared
/// pointer until the types have been resolved using the @ref NameAndTypeResolver. /// pointer until the types have been resolved using the @ref NameAndTypeResolver.
virtual std::shared_ptr<Type> toType() = 0; virtual std::shared_ptr<Type> toType() const = 0;
}; };
/** /**
@ -252,7 +254,7 @@ public:
if (asserts(Token::isElementaryTypeName(_type))) BOOST_THROW_EXCEPTION(InternalCompilerError()); if (asserts(Token::isElementaryTypeName(_type))) BOOST_THROW_EXCEPTION(InternalCompilerError());
} }
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual std::shared_ptr<Type> toType() override { return Type::fromElementaryTypeName(m_type); } virtual std::shared_ptr<Type> toType() const override { return Type::fromElementaryTypeName(m_type); }
Token::Value getTypeName() const { return m_type; } Token::Value getTypeName() const { return m_type; }
@ -270,7 +272,7 @@ public:
UserDefinedTypeName(Location const& _location, ASTPointer<ASTString> const& _name): UserDefinedTypeName(Location const& _location, ASTPointer<ASTString> const& _name):
TypeName(_location), m_name(_name) {} TypeName(_location), m_name(_name) {}
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual std::shared_ptr<Type> toType() override { return Type::fromUserDefinedTypeName(*this); } virtual std::shared_ptr<Type> toType() const override { return Type::fromUserDefinedTypeName(*this); }
ASTString const& getName() const { return *m_name; } ASTString const& getName() const { return *m_name; }
void setReferencedStruct(StructDefinition& _referencedStruct) { m_referencedStruct = &_referencedStruct; } void setReferencedStruct(StructDefinition& _referencedStruct) { m_referencedStruct = &_referencedStruct; }
@ -292,7 +294,10 @@ public:
ASTPointer<TypeName> const& _valueType): ASTPointer<TypeName> const& _valueType):
TypeName(_location), m_keyType(_keyType), m_valueType(_valueType) {} TypeName(_location), m_keyType(_keyType), m_valueType(_valueType) {}
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual std::shared_ptr<Type> toType() override { return Type::fromMapping(*this); } virtual std::shared_ptr<Type> toType() const override { return Type::fromMapping(*this); }
ElementaryTypeName const& getKeyType() const { return *m_keyType; }
TypeName const& getValueType() const { return *m_valueType; }
private: private:
ASTPointer<ElementaryTypeName> m_keyType; ASTPointer<ElementaryTypeName> m_keyType;
@ -363,7 +368,6 @@ private:
/** /**
* Statement in which a break statement is legal. * Statement in which a break statement is legal.
* @todo actually check this requirement.
*/ */
class BreakableStatement: public Statement class BreakableStatement: public Statement
{ {
@ -481,7 +485,7 @@ private:
class Expression: public ASTNode class Expression: public ASTNode
{ {
public: public:
Expression(Location const& _location): ASTNode(_location), m_isLvalue(false) {} Expression(Location const& _location): ASTNode(_location), m_isLvalue(false), m_lvalueRequested(false) {}
virtual void checkTypeRequirements() = 0; virtual void checkTypeRequirements() = 0;
std::shared_ptr<Type const> const& getType() const { return m_type; } std::shared_ptr<Type const> const& getType() const { return m_type; }
@ -490,6 +494,12 @@ public:
/// Helper function, infer the type via @ref checkTypeRequirements and then check that it /// Helper function, infer the type via @ref checkTypeRequirements and then check that it
/// is implicitly convertible to @a _expectedType. If not, throw exception. /// is implicitly convertible to @a _expectedType. If not, throw exception.
void expectType(Type const& _expectedType); void expectType(Type const& _expectedType);
/// Checks that this expression is an lvalue and also registers that an address and
/// not a value is generated during compilation. Can be called after checkTypeRequirements()
/// by an enclosing expression.
void requireLValue();
/// Returns true if @a requireLValue was previously called on this expression.
bool lvalueRequested() const { return m_lvalueRequested; }
protected: protected:
//! Inferred type of the expression, only filled after a call to checkTypeRequirements(). //! Inferred type of the expression, only filled after a call to checkTypeRequirements().
@ -497,6 +507,8 @@ protected:
//! Whether or not this expression is an lvalue, i.e. something that can be assigned to. //! Whether or not this expression is an lvalue, i.e. something that can be assigned to.
//! This is set during calls to @a checkTypeRequirements() //! This is set during calls to @a checkTypeRequirements()
bool m_isLvalue; bool m_isLvalue;
//! Whether the outer expression requested the address (true) or the value (false) of this expression.
bool m_lvalueRequested;
}; };
/// Assignment, can also be a compound assignment. /// Assignment, can also be a compound assignment.
@ -543,6 +555,7 @@ public:
Token::Value getOperator() const { return m_operator; } Token::Value getOperator() const { return m_operator; }
bool isPrefixOperation() const { return m_isPrefix; } bool isPrefixOperation() const { return m_isPrefix; }
Expression& getSubExpression() const { return *m_subExpression; }
private: private:
Token::Value m_operator; Token::Value m_operator;
@ -615,6 +628,7 @@ public:
ASTPointer<ASTString> const& _memberName): ASTPointer<ASTString> const& _memberName):
Expression(_location), m_expression(_expression), m_memberName(_memberName) {} Expression(_location), m_expression(_expression), m_memberName(_memberName) {}
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
Expression& getExpression() const { return *m_expression; }
ASTString const& getMemberName() const { return *m_memberName; } ASTString const& getMemberName() const { return *m_memberName; }
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
@ -635,6 +649,9 @@ public:
virtual void accept(ASTVisitor& _visitor) override; virtual void accept(ASTVisitor& _visitor) override;
virtual void checkTypeRequirements() override; virtual void checkTypeRequirements() override;
Expression& getBaseExpression() const { return *m_base; }
Expression& getIndexExpression() const { return *m_index; }
private: private:
ASTPointer<Expression> m_base; ASTPointer<Expression> m_base;
ASTPointer<Expression> m_index; ASTPointer<Expression> m_index;

2
libsolidity/Compiler.cpp

@ -225,7 +225,7 @@ bool Compiler::visit(IfStatement& _ifStatement)
eth::AssemblyItem trueTag = m_context.appendConditionalJump(); eth::AssemblyItem trueTag = m_context.appendConditionalJump();
if (_ifStatement.getFalseStatement()) if (_ifStatement.getFalseStatement())
_ifStatement.getFalseStatement()->accept(*this); _ifStatement.getFalseStatement()->accept(*this);
eth::AssemblyItem endTag = m_context.appendJump(); eth::AssemblyItem endTag = m_context.appendJumpToNew();
m_context << trueTag; m_context << trueTag;
_ifStatement.getTrueStatement().accept(*this); _ifStatement.getTrueStatement().accept(*this);
m_context << endTag; m_context << endTag;

4
libsolidity/CompilerContext.h

@ -65,7 +65,9 @@ public:
/// Appends a JUMPI instruction to @a _tag /// Appends a JUMPI instruction to @a _tag
CompilerContext& appendConditionalJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJumpI(_tag); return *this; } CompilerContext& appendConditionalJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJumpI(_tag); return *this; }
/// Appends a JUMP to a new tag and @returns the tag /// Appends a JUMP to a new tag and @returns the tag
eth::AssemblyItem appendJump() { return m_asm.appendJump().tag(); } eth::AssemblyItem appendJumpToNew() { return m_asm.appendJump().tag(); }
/// Appends a JUMP to a tag already on the stack
CompilerContext& appendJump() { return *this << eth::Instruction::JUMP; }
/// Appends a JUMP to a specific tag /// Appends a JUMP to a specific tag
CompilerContext& appendJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJump(_tag); return *this; } CompilerContext& appendJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJump(_tag); return *this; }
/// Appends pushing of a new tag and @returns the new tag. /// Appends pushing of a new tag and @returns the new tag.

190
libsolidity/ExpressionCompiler.cpp

@ -22,6 +22,7 @@
#include <utility> #include <utility>
#include <numeric> #include <numeric>
#include <libdevcore/Common.h>
#include <libsolidity/AST.h> #include <libsolidity/AST.h>
#include <libsolidity/ExpressionCompiler.h> #include <libsolidity/ExpressionCompiler.h>
#include <libsolidity/CompilerContext.h> #include <libsolidity/CompilerContext.h>
@ -48,16 +49,21 @@ bool ExpressionCompiler::visit(Assignment& _assignment)
{ {
_assignment.getRightHandSide().accept(*this); _assignment.getRightHandSide().accept(*this);
appendTypeConversion(*_assignment.getRightHandSide().getType(), *_assignment.getType()); appendTypeConversion(*_assignment.getRightHandSide().getType(), *_assignment.getType());
m_currentLValue.reset();
_assignment.getLeftHandSide().accept(*this); _assignment.getLeftHandSide().accept(*this);
if (asserts(m_currentLValue.isValid()))
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("LValue not retrieved."));
Token::Value op = _assignment.getAssignmentOperator(); Token::Value op = _assignment.getAssignmentOperator();
if (op != Token::ASSIGN) // compound assignment if (op != Token::ASSIGN) // compound assignment
{
if (m_currentLValue.storesReferenceOnStack())
m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2;
m_currentLValue.retrieveValue(_assignment, true);
appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), *_assignment.getType()); appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), *_assignment.getType());
else }
m_context << eth::Instruction::POP; m_currentLValue.storeValue(_assignment);
m_currentLValue.reset();
storeInLValue(_assignment);
return false; return false;
} }
@ -76,23 +82,39 @@ void ExpressionCompiler::endVisit(UnaryOperation& _unaryOperation)
m_context << eth::Instruction::NOT; m_context << eth::Instruction::NOT;
break; break;
case Token::DELETE: // delete case Token::DELETE: // delete
{
// a -> a xor a (= 0).
// @todo semantics change for complex types // @todo semantics change for complex types
m_context << eth::Instruction::DUP1 << eth::Instruction::XOR; if (asserts(m_currentLValue.isValid()))
storeInLValue(_unaryOperation); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("LValue not retrieved."));
m_context << u256(0);
if (m_currentLValue.storesReferenceOnStack())
m_context << eth::Instruction::SWAP1;
m_currentLValue.storeValue(_unaryOperation);
m_currentLValue.reset();
break; break;
}
case Token::INC: // ++ (pre- or postfix) case Token::INC: // ++ (pre- or postfix)
case Token::DEC: // -- (pre- or postfix) case Token::DEC: // -- (pre- or postfix)
if (asserts(m_currentLValue.isValid()))
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("LValue not retrieved."));
m_currentLValue.retrieveValue(_unaryOperation);
if (!_unaryOperation.isPrefixOperation()) if (!_unaryOperation.isPrefixOperation())
m_context << eth::Instruction::DUP1; {
if (m_currentLValue.storesReferenceOnStack())
m_context << eth::Instruction::SWAP1 << eth::Instruction::DUP2;
else
m_context << eth::Instruction::DUP1;
}
m_context << u256(1); m_context << u256(1);
if (_unaryOperation.getOperator() == Token::INC) if (_unaryOperation.getOperator() == Token::INC)
m_context << eth::Instruction::ADD; m_context << eth::Instruction::ADD;
else else
m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB; // @todo avoid the swap m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB; // @todo avoid the swap
storeInLValue(_unaryOperation, !_unaryOperation.isPrefixOperation()); // Stack for prefix: [ref] (*ref)+-1
// Stack for postfix: *ref [ref] (*ref)+-1
if (m_currentLValue.storesReferenceOnStack())
m_context << eth::Instruction::SWAP1;
m_currentLValue.storeValue(_unaryOperation, !_unaryOperation.isPrefixOperation());
m_currentLValue.reset();
break; break;
case Token::ADD: // + case Token::ADD: // +
// unary add, so basically no-op // unary add, so basically no-op
@ -151,12 +173,6 @@ bool ExpressionCompiler::visit(FunctionCall& _functionCall)
{ {
// Calling convention: Caller pushes return address and arguments // Calling convention: Caller pushes return address and arguments
// Callee removes them and pushes return values // Callee removes them and pushes return values
m_currentLValue.reset();
_functionCall.getExpression().accept(*this);
if (asserts(m_currentLValue.isInCode()))
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Code reference expected."));
eth::AssemblyItem functionTag(eth::PushTag, m_currentLValue.location);
FunctionDefinition const& function = dynamic_cast<FunctionType const&>(*_functionCall.getExpression().getType()).getFunction(); FunctionDefinition const& function = dynamic_cast<FunctionType const&>(*_functionCall.getExpression().getType()).getFunction();
eth::AssemblyItem returnLabel = m_context.pushNewTag(); eth::AssemblyItem returnLabel = m_context.pushNewTag();
@ -168,8 +184,12 @@ bool ExpressionCompiler::visit(FunctionCall& _functionCall)
arguments[i]->accept(*this); arguments[i]->accept(*this);
appendTypeConversion(*arguments[i]->getType(), *function.getParameters()[i]->getType()); appendTypeConversion(*arguments[i]->getType(), *function.getParameters()[i]->getType());
} }
_functionCall.getExpression().accept(*this);
if (asserts(m_currentLValue.isInCode()))
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Code reference expected."));
m_currentLValue.reset();
m_context.appendJumpTo(functionTag); m_context.appendJump();
m_context << returnLabel; m_context << returnLabel;
// callee adds return parameters, but removes arguments and return label // callee adds return parameters, but removes arguments and return label
@ -183,32 +203,42 @@ bool ExpressionCompiler::visit(FunctionCall& _functionCall)
return false; return false;
} }
void ExpressionCompiler::endVisit(MemberAccess&) void ExpressionCompiler::endVisit(MemberAccess& _memberAccess)
{ {
if (asserts(m_currentLValue.isInStorage()))
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member access to a non-storage value."));
StructType const& type = dynamic_cast<StructType const&>(*_memberAccess.getExpression().getType());
unsigned memberIndex = type.memberNameToIndex(_memberAccess.getMemberName());
if (asserts(memberIndex <= type.getMemberCount()))
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member not found in struct during compilation."));
m_context << type.getStorageOffsetOfMember(memberIndex) << eth::Instruction::ADD;
m_currentLValue.retrieveValueIfLValueNotRequested(_memberAccess);
} }
void ExpressionCompiler::endVisit(IndexAccess&) bool ExpressionCompiler::visit(IndexAccess& _indexAccess)
{ {
m_currentLValue.reset();
_indexAccess.getBaseExpression().accept(*this);
if (asserts(m_currentLValue.isInStorage()))
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Index access to a non-storage value."));
_indexAccess.getIndexExpression().accept(*this);
appendTypeConversion(*_indexAccess.getIndexExpression().getType(),
*dynamic_cast<MappingType const&>(*_indexAccess.getBaseExpression().getType()).getKeyType(),
true);
// @todo move this once we actually use memory
m_context << u256(32) << eth::Instruction::MSTORE << u256(0) << eth::Instruction::MSTORE;
m_context << u256(64) << u256(0) << eth::Instruction::SHA3;
m_currentLValue = LValue(m_context, LValue::STORAGE);
m_currentLValue.retrieveValueIfLValueNotRequested(_indexAccess);
return false;
} }
void ExpressionCompiler::endVisit(Identifier& _identifier) void ExpressionCompiler::endVisit(Identifier& _identifier)
{ {
Declaration const* declaration = _identifier.getReferencedDeclaration(); m_currentLValue.fromDeclaration(_identifier, *_identifier.getReferencedDeclaration());
if (m_context.isLocalVariable(declaration)) m_currentLValue.retrieveValueIfLValueNotRequested(_identifier);
m_currentLValue = LValueLocation(LValueLocation::STACK,
m_context.getBaseStackOffsetOfVariable(*declaration));
else if (m_context.isStateVariable(declaration))
m_currentLValue = LValueLocation(LValueLocation::STORAGE,
m_context.getStorageLocationOfVariable(*declaration));
else if (m_context.isFunctionDefinition(declaration))
m_currentLValue = LValueLocation(LValueLocation::CODE,
m_context.getFunctionEntryLabel(dynamic_cast<FunctionDefinition const&>(*declaration)).data());
else
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Identifier type not supported or identifier not found."));
retrieveLValueValue(_identifier);
} }
void ExpressionCompiler::endVisit(Literal& _literal) void ExpressionCompiler::endVisit(Literal& _literal)
@ -371,66 +401,104 @@ void ExpressionCompiler::appendHighBitsCleanup(IntegerType const& _typeOnStack)
m_context << ((u256(1) << _typeOnStack.getNumBits()) - 1) << eth::Instruction::AND; m_context << ((u256(1) << _typeOnStack.getNumBits()) - 1) << eth::Instruction::AND;
} }
void ExpressionCompiler::retrieveLValueValue(Expression const& _expression) void ExpressionCompiler::LValue::retrieveValue(Expression const& _expression, bool _remove) const
{ {
switch (m_currentLValue.locationType) switch (m_type)
{ {
case LValueLocation::CODE: case CODE:
// not stored on the stack BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Tried to retrieve value of a function."));
break; break;
case LValueLocation::STACK: case STACK:
{ {
unsigned stackPos = m_context.baseToCurrentStackOffset(unsigned(m_currentLValue.location)); unsigned stackPos = m_context->baseToCurrentStackOffset(unsigned(m_baseStackOffset));
if (stackPos >= 15) //@todo correct this by fetching earlier or moving to memory if (stackPos >= 15) //@todo correct this by fetching earlier or moving to memory
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation()) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Stack too deep.")); << errinfo_comment("Stack too deep."));
m_context << eth::dupInstruction(stackPos + 1); *m_context << eth::dupInstruction(stackPos + 1);
break; break;
} }
case LValueLocation::STORAGE: case STORAGE:
m_context << m_currentLValue.location << eth::Instruction::SLOAD; if (!_remove)
*m_context << eth::Instruction::DUP1;
*m_context << eth::Instruction::SLOAD;
break; break;
case LValueLocation::MEMORY: case MEMORY:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type not yet implemented.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Location type not yet implemented."));
break; break;
default: default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unsupported location type.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Unsupported location type."));
break; break;
} }
} }
void ExpressionCompiler::storeInLValue(Expression const& _expression, bool _move) void ExpressionCompiler::LValue::storeValue(Expression const& _expression, bool _move) const
{ {
switch (m_currentLValue.locationType) switch (m_type)
{ {
case LValueLocation::STACK: case STACK:
{ {
unsigned stackPos = m_context.baseToCurrentStackOffset(unsigned(m_currentLValue.location)); unsigned stackPos = m_context->baseToCurrentStackOffset(unsigned(m_baseStackOffset));
if (stackPos > 16) if (stackPos > 16)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation()) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Stack too deep.")); << errinfo_comment("Stack too deep."));
else if (stackPos > 0) else if (stackPos > 0)
m_context << eth::swapInstruction(stackPos) << eth::Instruction::POP; *m_context << eth::swapInstruction(stackPos) << eth::Instruction::POP;
if (!_move) if (!_move)
retrieveLValueValue(_expression); retrieveValue(_expression);
break; break;
} }
case LValueLocation::STORAGE: case LValue::STORAGE:
if (!_move) if (!_move)
m_context << eth::Instruction::DUP1; *m_context << eth::Instruction::DUP2 << eth::Instruction::SWAP1;
m_context << m_currentLValue.location << eth::Instruction::SSTORE; *m_context << eth::Instruction::SSTORE;
break; break;
case LValueLocation::CODE: case LValue::CODE:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type does not support assignment.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Location type does not support assignment."));
break; break;
case LValueLocation::MEMORY: case LValue::MEMORY:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type not yet implemented.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Location type not yet implemented."));
break; break;
default: default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unsupported location type.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Unsupported location type."));
break; break;
} }
} }
void ExpressionCompiler::LValue::retrieveValueIfLValueNotRequested(const Expression& _expression)
{
if (!_expression.lvalueRequested())
{
retrieveValue(_expression, true);
reset();
}
}
void ExpressionCompiler::LValue::fromDeclaration( Expression const& _expression, Declaration const& _declaration)
{
if (m_context->isLocalVariable(&_declaration))
{
m_type = STACK;
m_baseStackOffset = m_context->getBaseStackOffsetOfVariable(_declaration);
}
else if (m_context->isStateVariable(&_declaration))
{
m_type = STORAGE;
*m_context << m_context->getStorageLocationOfVariable(_declaration);
}
else if (m_context->isFunctionDefinition(&_declaration))
{
m_type = CODE;
*m_context << m_context->getFunctionEntryLabel(dynamic_cast<FunctionDefinition const&>(_declaration)).pushTag();
}
else
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Identifier type not supported or identifier not found."));
}
} }
} }

77
libsolidity/ExpressionCompiler.h

@ -20,6 +20,7 @@
* Solidity AST to EVM bytecode compiler for expressions. * Solidity AST to EVM bytecode compiler for expressions.
*/ */
#include <boost/noncopyable.hpp>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libsolidity/ASTVisitor.h> #include <libsolidity/ASTVisitor.h>
@ -49,14 +50,15 @@ public:
static void appendTypeConversion(CompilerContext& _context, Type const& _typeOnStack, Type const& _targetType); static void appendTypeConversion(CompilerContext& _context, Type const& _typeOnStack, Type const& _targetType);
private: private:
ExpressionCompiler(CompilerContext& _compilerContext): m_context(_compilerContext) {} ExpressionCompiler(CompilerContext& _compilerContext):
m_context(_compilerContext), m_currentLValue(m_context) {}
virtual bool visit(Assignment& _assignment) override; virtual bool visit(Assignment& _assignment) override;
virtual void endVisit(UnaryOperation& _unaryOperation) override; virtual void endVisit(UnaryOperation& _unaryOperation) override;
virtual bool visit(BinaryOperation& _binaryOperation) override; virtual bool visit(BinaryOperation& _binaryOperation) override;
virtual bool visit(FunctionCall& _functionCall) override; virtual bool visit(FunctionCall& _functionCall) override;
virtual void endVisit(MemberAccess& _memberAccess) override; virtual void endVisit(MemberAccess& _memberAccess) override;
virtual void endVisit(IndexAccess& _indexAccess) override; virtual bool visit(IndexAccess& _indexAccess) override;
virtual void endVisit(Identifier& _identifier) override; virtual void endVisit(Identifier& _identifier) override;
virtual void endVisit(Literal& _literal) override; virtual void endVisit(Literal& _literal) override;
@ -79,37 +81,58 @@ private:
//// Appends code that cleans higher-order bits for integer types. //// Appends code that cleans higher-order bits for integer types.
void appendHighBitsCleanup(IntegerType const& _typeOnStack); void appendHighBitsCleanup(IntegerType const& _typeOnStack);
/// Copies the value of the current lvalue to the top of the stack.
void retrieveLValueValue(Expression const& _expression);
/// Stores the value on top of the stack in the current lvalue. Removes it from the stack if
/// @a _move is true.
void storeInLValue(Expression const& _expression, bool _move = false);
/** /**
* Location of an lvalue, either in code (for a function) on the stack, in the storage or memory. * Helper class to store and retrieve lvalues to and from various locations.
* All types except STACK store a reference in a slot on the stack, STACK just stores the
* base stack offset of the variable in @a m_baseStackOffset.
*/ */
struct LValueLocation class LValue
{ {
enum LocationType { INVALID, CODE, STACK, MEMORY, STORAGE }; public:
enum LValueType { NONE, CODE, STACK, MEMORY, STORAGE };
LValueLocation() { reset(); }
LValueLocation(LocationType _type, u256 const& _location): locationType(_type), location(_location) {} explicit LValue(CompilerContext& _compilerContext): m_context(&_compilerContext) { reset(); }
void reset() { locationType = INVALID; location = 0; } LValue(CompilerContext& _compilerContext, LValueType _type, unsigned _baseStackOffset = 0):
bool isValid() const { return locationType != INVALID; } m_context(&_compilerContext), m_type(_type), m_baseStackOffset(_baseStackOffset) {}
bool isInCode() const { return locationType == CODE; }
bool isInOnStack() const { return locationType == STACK; } /// Set type according to the declaration and retrieve the reference.
bool isInMemory() const { return locationType == MEMORY; } /// @a _expression is the current expression, used for error reporting.
bool isInStorage() const { return locationType == STORAGE; } void fromDeclaration(Expression const& _expression, Declaration const& _declaration);
void reset() { m_type = NONE; m_baseStackOffset = 0; }
LocationType locationType;
/// Depending on the type, this is the id of a tag (code), the base offset of a stack bool isValid() const { return m_type != NONE; }
/// variable (@see CompilerContext::getBaseStackOffsetOfVariable) or the offset in bool isInCode() const { return m_type == CODE; }
/// storage or memory. bool isInOnStack() const { return m_type == STACK; }
u256 location; bool isInMemory() const { return m_type == MEMORY; }
bool isInStorage() const { return m_type == STORAGE; }
/// @returns true if this lvalue reference type occupies a slot on the stack.
bool storesReferenceOnStack() const { return m_type == STORAGE || m_type == MEMORY || m_type == CODE; }
/// Copies the value of the current lvalue to the top of the stack and, if @a _remove is true,
/// also removes the reference from the stack (note that is does not reset the type to @a NONE).
/// @a _expression is the current expression, used for error reporting.
void retrieveValue(Expression const& _expression, bool _remove = false) const;
/// Stores a value (from the stack directly beneath the reference, which is assumed to
/// be on the top of the stack, if any) in the lvalue and removes the reference.
/// Also removes the stored value from the stack if @a _move is
/// true. @a _expression is the current expression, used for error reporting.
void storeValue(Expression const& _expression, bool _move = false) const;
/// Convenience function to convert the stored reference to a value and reset type to NONE if
/// the reference was not requested by @a _expression.
void retrieveValueIfLValueNotRequested(Expression const& _expression);
private:
CompilerContext* m_context;
LValueType m_type;
/// If m_type is STACK, this is base stack offset (@see
/// CompilerContext::getBaseStackOffsetOfVariable) of a local variable.
unsigned m_baseStackOffset;
}; };
LValueLocation m_currentLValue;
CompilerContext& m_context; CompilerContext& m_context;
LValue m_currentLValue;
}; };

34
libsolidity/NameAndTypeResolver.cpp

@ -37,7 +37,10 @@ void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
reset(); reset();
DeclarationRegistrationHelper registrar(m_scopes, _contract); DeclarationRegistrationHelper registrar(m_scopes, _contract);
m_currentScope = &m_scopes[&_contract]; m_currentScope = &m_scopes[&_contract];
//@todo structs for (ASTPointer<StructDefinition> const& structDef: _contract.getDefinedStructs())
ReferencesResolver resolver(*structDef, *this, nullptr);
for (ASTPointer<StructDefinition> const& structDef: _contract.getDefinedStructs())
checkForRecursion(*structDef);
for (ASTPointer<VariableDeclaration> const& variable: _contract.getStateVariables()) for (ASTPointer<VariableDeclaration> const& variable: _contract.getStateVariables())
ReferencesResolver resolver(*variable, *this, nullptr); ReferencesResolver resolver(*variable, *this, nullptr);
for (ASTPointer<FunctionDefinition> const& function: _contract.getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.getDefinedFunctions())
@ -52,7 +55,7 @@ void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract)
for (ASTPointer<FunctionDefinition> const& function: _contract.getDefinedFunctions()) for (ASTPointer<FunctionDefinition> const& function: _contract.getDefinedFunctions())
{ {
m_currentScope = &m_scopes[function.get()]; m_currentScope = &m_scopes[function.get()];
function->getBody().checkTypeRequirements(); function->checkTypeRequirements();
} }
m_currentScope = &m_scopes[nullptr]; m_currentScope = &m_scopes[nullptr];
} }
@ -70,6 +73,24 @@ Declaration* NameAndTypeResolver::getNameFromCurrentScope(ASTString const& _name
return m_currentScope->resolveName(_name, _recursive); return m_currentScope->resolveName(_name, _recursive);
} }
void NameAndTypeResolver::checkForRecursion(StructDefinition const& _struct)
{
set<StructDefinition const*> definitionsSeen;
vector<StructDefinition const*> queue = {&_struct};
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)
queue.push_back(dynamic_cast<UserDefinedTypeName&>(*member->getTypeName()).getReferencedStruct());
}
}
void NameAndTypeResolver::reset() void NameAndTypeResolver::reset()
{ {
m_scopes.clear(); m_scopes.clear();
@ -163,8 +184,8 @@ void DeclarationRegistrationHelper::registerDeclaration(Declaration& _declaratio
} }
ReferencesResolver::ReferencesResolver(ASTNode& _root, NameAndTypeResolver& _resolver, ReferencesResolver::ReferencesResolver(ASTNode& _root, NameAndTypeResolver& _resolver,
ParameterList* _returnParameters): ParameterList* _returnParameters, bool _allowLazyTypes):
m_resolver(_resolver), m_returnParameters(_returnParameters) m_resolver(_resolver), m_returnParameters(_returnParameters), m_allowLazyTypes(_allowLazyTypes)
{ {
_root.accept(*this); _root.accept(*this);
} }
@ -175,6 +196,8 @@ void ReferencesResolver::endVisit(VariableDeclaration& _variable)
// or mapping // or mapping
if (_variable.getTypeName()) if (_variable.getTypeName())
_variable.setType(_variable.getTypeName()->toType()); _variable.setType(_variable.getTypeName()->toType());
else if (!m_allowLazyTypes)
BOOST_THROW_EXCEPTION(_variable.createTypeError("Explicit type needed."));
// otherwise we have a "var"-declaration whose type is resolved by the first assignment // otherwise we have a "var"-declaration whose type is resolved by the first assignment
} }
@ -186,9 +209,8 @@ bool ReferencesResolver::visit(Return& _return)
return true; return true;
} }
bool ReferencesResolver::visit(Mapping&) bool ReferencesResolver::visit(Mapping& _mapping)
{ {
// @todo
return true; return true;
} }

11
libsolidity/NameAndTypeResolver.h

@ -55,10 +55,13 @@ public:
Declaration* getNameFromCurrentScope(ASTString const& _name, bool _recursive = true); Declaration* getNameFromCurrentScope(ASTString const& _name, bool _recursive = true);
private: private:
/// Throws if @a _struct contains a recursive loop. Note that recursion via mappings is fine.
void checkForRecursion(StructDefinition const& _struct);
void reset(); void reset();
/// Maps nodes declaring a scope to scopes, i.e. ContractDefinition, FunctionDeclaration and /// Maps nodes declaring a scope to scopes, i.e. ContractDefinition and FunctionDeclaration,
/// StructDefinition (@todo not yet implemented), where nullptr denotes the global scope. /// where nullptr denotes the global scope. Note that structs are not scope since they do
/// not contain code.
std::map<ASTNode const*, Scope> m_scopes; std::map<ASTNode const*, Scope> m_scopes;
Scope* m_currentScope; Scope* m_currentScope;
@ -99,7 +102,8 @@ private:
class ReferencesResolver: private ASTVisitor class ReferencesResolver: private ASTVisitor
{ {
public: public:
ReferencesResolver(ASTNode& _root, NameAndTypeResolver& _resolver, ParameterList* _returnParameters); ReferencesResolver(ASTNode& _root, NameAndTypeResolver& _resolver,
ParameterList* _returnParameters, bool _allowLazyTypes = true);
private: private:
virtual void endVisit(VariableDeclaration& _variable) override; virtual void endVisit(VariableDeclaration& _variable) override;
@ -110,6 +114,7 @@ private:
NameAndTypeResolver& m_resolver; NameAndTypeResolver& m_resolver;
ParameterList* m_returnParameters; ParameterList* m_returnParameters;
bool m_allowLazyTypes;
}; };
} }

61
libsolidity/Types.cpp

@ -63,9 +63,11 @@ shared_ptr<Type> Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeN
return make_shared<StructType>(*_typeName.getReferencedStruct()); return make_shared<StructType>(*_typeName.getReferencedStruct());
} }
shared_ptr<Type> Type::fromMapping(Mapping const&) shared_ptr<Type> Type::fromMapping(Mapping const& _typeName)
{ {
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Mapping types not yet implemented.")); shared_ptr<Type const> keyType = _typeName.getKeyType().toType();
shared_ptr<Type const> valueType = _typeName.getValueType().toType();
return make_shared<MappingType>(keyType, valueType);
} }
shared_ptr<Type> Type::forLiteral(Literal const& _literal) shared_ptr<Type> Type::forLiteral(Literal const& _literal)
@ -78,7 +80,7 @@ shared_ptr<Type> Type::forLiteral(Literal const& _literal)
case Token::NUMBER: case Token::NUMBER:
return IntegerType::smallestTypeForLiteral(_literal.getValue()); return IntegerType::smallestTypeForLiteral(_literal.getValue());
case Token::STRING_LITERAL: case Token::STRING_LITERAL:
return shared_ptr<Type>(); // @todo return shared_ptr<Type>(); // @todo add string literals
default: default:
return shared_ptr<Type>(); return shared_ptr<Type>();
} }
@ -229,6 +231,48 @@ u256 StructType::getStorageSize() const
return max<u256>(1, size); return max<u256>(1, size);
} }
bool StructType::canLiveOutsideStorage() const
{
for (unsigned i = 0; i < getMemberCount(); ++i)
if (!getMemberByIndex(i).getType()->canLiveOutsideStorage())
return false;
return true;
}
string StructType::toString() const
{
return string("struct ") + m_struct.getName();
}
unsigned StructType::getMemberCount() const
{
return m_struct.getMembers().size();
}
unsigned StructType::memberNameToIndex(string const& _name) const
{
vector<ASTPointer<VariableDeclaration>> const& members = m_struct.getMembers();
for (unsigned index = 0; index < members.size(); ++index)
if (members[index]->getName() == _name)
return index;
return unsigned(-1);
}
VariableDeclaration const& StructType::getMemberByIndex(unsigned _index) const
{
return *m_struct.getMembers()[_index];
}
u256 StructType::getStorageOffsetOfMember(unsigned _index) const
{
//@todo cache member offset?
u256 offset;
vector<ASTPointer<VariableDeclaration>> const& members = m_struct.getMembers();
for (unsigned index = 0; index < _index; ++index)
offset += getMemberByIndex(index).getType()->getStorageSize();
return offset;
}
bool FunctionType::operator==(Type const& _other) const bool FunctionType::operator==(Type const& _other) const
{ {
if (_other.getCategory() != getCategory()) if (_other.getCategory() != getCategory())
@ -237,6 +281,12 @@ bool FunctionType::operator==(Type const& _other) const
return other.m_function == m_function; return other.m_function == m_function;
} }
string FunctionType::toString() const
{
//@todo nice string for function types
return "function(...)returns(...)";
}
bool MappingType::operator==(Type const& _other) const bool MappingType::operator==(Type const& _other) const
{ {
if (_other.getCategory() != getCategory()) if (_other.getCategory() != getCategory())
@ -245,6 +295,11 @@ bool MappingType::operator==(Type const& _other) const
return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType; return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType;
} }
string MappingType::toString() const
{
return "mapping(" + getKeyType()->toString() + " => " + getValueType()->toString() + ")";
}
bool TypeType::operator==(Type const& _other) const bool TypeType::operator==(Type const& _other) const
{ {
if (_other.getCategory() != getCategory()) if (_other.getCategory() != getCategory())

27
libsolidity/Types.h

@ -35,7 +35,7 @@ namespace dev
namespace solidity namespace solidity
{ {
// @todo realMxN, string<N>, mapping // @todo realMxN, string<N>
/** /**
* Abstract base class that forms the root of the type hierarchy. * Abstract base class that forms the root of the type hierarchy.
@ -78,6 +78,8 @@ public:
/// @returns number of bytes required to hold this value in storage. /// @returns number of bytes required to hold this value in storage.
/// For dynamically "allocated" types, it returns the size of the statically allocated head, /// For dynamically "allocated" types, it returns the size of the statically allocated head,
virtual u256 getStorageSize() const { return 1; } virtual u256 getStorageSize() const { return 1; }
/// Returns false if the type cannot live outside the storage, i.e. if it includes some mapping.
virtual bool canLiveOutsideStorage() const { return true; }
virtual std::string toString() const = 0; virtual std::string toString() const = 0;
virtual u256 literalValue(Literal const&) const virtual u256 literalValue(Literal const&) const
@ -182,7 +184,14 @@ public:
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual u256 getStorageSize() const; virtual u256 getStorageSize() const;
virtual std::string toString() const override { return "struct{...}"; } virtual bool canLiveOutsideStorage() const;
virtual std::string toString() const override;
unsigned getMemberCount() const;
/// Returns the index of the member with name @a _name or unsigned(-1) if it does not exist.
unsigned memberNameToIndex(std::string const& _name) const;
VariableDeclaration const& getMemberByIndex(unsigned _index) const;
u256 getStorageOffsetOfMember(unsigned _index) const;
private: private:
StructDefinition const& m_struct; StructDefinition const& m_struct;
@ -200,8 +209,9 @@ public:
FunctionDefinition const& getFunction() const { return m_function; } FunctionDefinition const& getFunction() const { return m_function; }
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual std::string toString() const override { return "function(...)returns(...)"; } virtual std::string toString() const override;
virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable function type requested.")); } virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable function type requested.")); }
virtual bool canLiveOutsideStorage() const { return false; }
private: private:
FunctionDefinition const& m_function; FunctionDefinition const& m_function;
@ -214,10 +224,15 @@ class MappingType: public Type
{ {
public: public:
virtual Category getCategory() const override { return Category::MAPPING; } virtual Category getCategory() const override { return Category::MAPPING; }
MappingType() {} MappingType(std::shared_ptr<Type const> _keyType, std::shared_ptr<Type const> _valueType):
m_keyType(_keyType), m_valueType(_valueType) {}
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual std::string toString() const override { return "mapping(...=>...)"; } virtual std::string toString() const override;
virtual bool canLiveOutsideStorage() const { return false; }
std::shared_ptr<Type const> getKeyType() const { return m_keyType; }
std::shared_ptr<Type const> getValueType() const { return m_valueType; }
private: private:
std::shared_ptr<Type const> m_keyType; std::shared_ptr<Type const> m_keyType;
@ -236,6 +251,7 @@ public:
virtual std::string toString() const override { return "void"; } virtual std::string toString() const override { return "void"; }
virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable void type requested.")); } virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable void type requested.")); }
virtual bool canLiveOutsideStorage() const { return false; }
}; };
/** /**
@ -252,6 +268,7 @@ public:
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); } virtual u256 getStorageSize() const { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); }
virtual bool canLiveOutsideStorage() const { return false; }
virtual std::string toString() const override { return "type(" + m_actualType->toString() + ")"; } virtual std::string toString() const override { return "type(" + m_actualType->toString() + ")"; }
private: private:

2
test/solidityCompiler.cpp

@ -128,8 +128,6 @@ BOOST_AUTO_TEST_CASE(different_argument_numbers)
byte(Instruction::JUMP), byte(Instruction::JUMP),
byte(Instruction::JUMPDEST), byte(Instruction::JUMPDEST),
// stack here: ret e h f(1,2,3) // stack here: ret e h f(1,2,3)
byte(Instruction::DUP2),
byte(Instruction::POP),
byte(Instruction::SWAP1), byte(Instruction::SWAP1),
// stack here: ret e f(1,2,3) h // stack here: ret e f(1,2,3) h
byte(Instruction::POP), byte(Instruction::POP),

204
test/solidityEndToEndTest.cpp

@ -32,6 +32,9 @@ using namespace std;
namespace dev namespace dev
{ {
/// Provider another overload for toBigEndian to encode arguments and return values.
inline bytes toBigEndian(bool _value) { return bytes({byte(_value)}); }
namespace solidity namespace solidity
{ {
namespace test namespace test
@ -137,6 +140,7 @@ private:
m_output = executive.out().toVector(); m_output = executive.out().toVector();
} }
protected:
Address m_contractAddress; Address m_contractAddress;
eth::State m_state; eth::State m_state;
u256 const m_gasPrice = 100 * eth::szabo; u256 const m_gasPrice = 100 * eth::szabo;
@ -496,6 +500,206 @@ BOOST_AUTO_TEST_CASE(state_smoke_test)
BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0x3))); BOOST_CHECK(callContractFunction(0, bytes(1, 0x00)) == toBigEndian(u256(0x3)));
} }
BOOST_AUTO_TEST_CASE(simple_mapping)
{
char const* sourceCode = "contract test {\n"
" mapping(uint8 => uint8) table;\n"
" function get(uint8 k) returns (uint8 v) {\n"
" return table[k];\n"
" }\n"
" function set(uint8 k, uint8 v) {\n"
" table[k] = v;\n"
" }\n"
"}";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction(0, bytes({0x00})) == bytes({0x00}));
BOOST_CHECK(callContractFunction(0, bytes({0x01})) == bytes({0x00}));
BOOST_CHECK(callContractFunction(0, bytes({0xa7})) == bytes({0x00}));
callContractFunction(1, bytes({0x01, 0xa1}));
BOOST_CHECK(callContractFunction(0, bytes({0x00})) == bytes({0x00}));
BOOST_CHECK(callContractFunction(0, bytes({0x01})) == bytes({0xa1}));
BOOST_CHECK(callContractFunction(0, bytes({0xa7})) == bytes({0x00}));
callContractFunction(1, bytes({0x00, 0xef}));
BOOST_CHECK(callContractFunction(0, bytes({0x00})) == bytes({0xef}));
BOOST_CHECK(callContractFunction(0, bytes({0x01})) == bytes({0xa1}));
BOOST_CHECK(callContractFunction(0, bytes({0xa7})) == bytes({0x00}));
callContractFunction(1, bytes({0x01, 0x05}));
BOOST_CHECK(callContractFunction(0, bytes({0x00})) == bytes({0xef}));
BOOST_CHECK(callContractFunction(0, bytes({0x01})) == bytes({0x05}));
BOOST_CHECK(callContractFunction(0, bytes({0xa7})) == bytes({0x00}));
}
BOOST_AUTO_TEST_CASE(mapping_state)
{
char const* sourceCode = "contract Ballot {\n"
" mapping(address => bool) canVote;\n"
" mapping(address => uint) voteCount;\n"
" mapping(address => bool) voted;\n"
" function getVoteCount(address addr) returns (uint retVoteCount) {\n"
" return voteCount[addr];\n"
" }\n"
" function grantVoteRight(address addr) {\n"
" canVote[addr] = true;\n"
" }\n"
" function vote(address voter, address vote) returns (bool success) {\n"
" if (!canVote[voter] || voted[voter]) return false;\n"
" voted[voter] = true;\n"
" voteCount[vote] = voteCount[vote] + 1;\n"
" return true;\n"
" }\n"
"}\n";
compileAndRun(sourceCode);
class Ballot
{
public:
u256 getVoteCount(u160 _address) { return m_voteCount[_address]; }
void grantVoteRight(u160 _address) { m_canVote[_address] = true; }
bool vote(u160 _voter, u160 _vote)
{
if (!m_canVote[_voter] || m_voted[_voter]) return false;
m_voted[_voter] = true;
m_voteCount[_vote]++;
return true;
}
private:
map<u160, bool> m_canVote;
map<u160, u256> m_voteCount;
map<u160, bool> m_voted;
} ballot;
auto getVoteCount = bind(&Ballot::getVoteCount, &ballot, _1);
auto grantVoteRight = bind(&Ballot::grantVoteRight, &ballot, _1);
auto vote = bind(&Ballot::vote, &ballot, _1, _2);
testSolidityAgainstCpp(0, getVoteCount, u160(0));
testSolidityAgainstCpp(0, getVoteCount, u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(2));
// voting without vote right shourd be rejected
testSolidityAgainstCpp(2, vote, u160(0), u160(2));
testSolidityAgainstCpp(0, getVoteCount, u160(0));
testSolidityAgainstCpp(0, getVoteCount, u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(2));
// grant vote rights
testSolidityAgainstCpp(1, grantVoteRight, u160(0));
testSolidityAgainstCpp(1, grantVoteRight, u160(1));
// vote, should increase 2's vote count
testSolidityAgainstCpp(2, vote, u160(0), u160(2));
testSolidityAgainstCpp(0, getVoteCount, u160(0));
testSolidityAgainstCpp(0, getVoteCount, u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(2));
// vote again, should be rejected
testSolidityAgainstCpp(2, vote, u160(0), u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(0));
testSolidityAgainstCpp(0, getVoteCount, u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(2));
// vote without right to vote
testSolidityAgainstCpp(2, vote, u160(2), u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(0));
testSolidityAgainstCpp(0, getVoteCount, u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(2));
// grant vote right and now vote again
testSolidityAgainstCpp(1, grantVoteRight, u160(2));
testSolidityAgainstCpp(2, vote, u160(2), u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(0));
testSolidityAgainstCpp(0, getVoteCount, u160(1));
testSolidityAgainstCpp(0, getVoteCount, u160(2));
}
BOOST_AUTO_TEST_CASE(mapping_state_inc_dec)
{
char const* sourceCode = "contract test {\n"
" uint value;\n"
" mapping(uint => uint) table;\n"
" function f(uint x) returns (uint y) {\n"
" value = x;\n"
" if (x > 0) table[++value] = 8;\n"
" if (x > 1) value--;\n"
" if (x > 2) table[value]++;\n"
" return --table[value++];\n"
" }\n"
"}\n";
compileAndRun(sourceCode);
u256 value = 0;
map<u256, u256> table;
auto f = [&](u256 const& _x) -> u256
{
value = _x;
if (_x > 0)
table[++value] = 8;
if (_x > 1)
value --;
if (_x > 2)
table[value]++;
return --table[value++];
};
testSolidityAgainstCppOnRange(0, f, 0, 5);
}
BOOST_AUTO_TEST_CASE(multi_level_mapping)
{
char const* sourceCode = "contract test {\n"
" mapping(uint => mapping(uint => uint)) table;\n"
" function f(uint x, uint y, uint z) returns (uint w) {\n"
" if (z == 0) return table[x][y];\n"
" else return table[x][y] = z;\n"
" }\n"
"}\n";
compileAndRun(sourceCode);
map<u256, map<u256, u256>> table;
auto f = [&](u256 const& _x, u256 const& _y, u256 const& _z) -> u256
{
if (_z == 0) return table[_x][_y];
else return table[_x][_y] = _z;
};
testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(0));
testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(0));
testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(9));
testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(0));
testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(0));
testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(7));
testSolidityAgainstCpp(0, f, u256(4), u256(5), u256(0));
testSolidityAgainstCpp(0, f, u256(5), u256(4), u256(0));
}
BOOST_AUTO_TEST_CASE(structs)
{
char const* sourceCode = "contract test {\n"
" struct s1 {\n"
" uint8 x;\n"
" bool y;\n"
" }\n"
" struct s2 {\n"
" uint32 z;\n"
" s1 s1data;\n"
" mapping(uint8 => s2) recursive;\n"
" }\n"
" s2 data;\n"
" function check() returns (bool ok) {\n"
" return data.z == 1 && data.s1data.x == 2 && \n"
" data.s1data.y == true && \n"
" data.recursive[3].recursive[4].z == 5 && \n"
" data.recursive[4].recursive[3].z == 6 && \n"
" data.recursive[0].s1data.y == false && \n"
" data.recursive[4].z == 9;\n"
" }\n"
" function set() {\n"
" data.z = 1;\n"
" data.s1data.x = 2;\n"
" data.s1data.y = true;\n"
" data.recursive[3].recursive[4].z = 5;\n"
" data.recursive[4].recursive[3].z = 6;\n"
" data.recursive[0].s1data.y = false;\n"
" data.recursive[4].z = 9;\n"
" }\n"
"}\n";
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction(0) == bytes({0x00}));
BOOST_CHECK(callContractFunction(1) == bytes());
BOOST_CHECK(callContractFunction(0) == bytes({0x01}));
}
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
} }

38
test/solidityNameAndTypeResolution.cpp

@ -121,6 +121,44 @@ BOOST_AUTO_TEST_CASE(reference_to_later_declaration)
BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text));
} }
BOOST_AUTO_TEST_CASE(struct_definition_directly_recursive)
{
char const* text = "contract test {\n"
" struct MyStructName {\n"
" address addr;\n"
" MyStructName x;\n"
" }\n"
"}\n";
BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError);
}
BOOST_AUTO_TEST_CASE(struct_definition_indirectly_recursive)
{
char const* text = "contract test {\n"
" struct MyStructName1 {\n"
" address addr;\n"
" uint256 count;\n"
" MyStructName2 x;\n"
" }\n"
" struct MyStructName2 {\n"
" MyStructName1 x;\n"
" }\n"
"}\n";
BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError);
}
BOOST_AUTO_TEST_CASE(struct_definition_recursion_via_mapping)
{
char const* text = "contract test {\n"
" struct MyStructName1 {\n"
" address addr;\n"
" uint256 count;\n"
" mapping(uint => MyStructName1) x;\n"
" }\n"
"}\n";
BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text));
}
BOOST_AUTO_TEST_CASE(type_inference_smoke_test) BOOST_AUTO_TEST_CASE(type_inference_smoke_test)
{ {
char const* text = "contract test {\n" char const* text = "contract test {\n"

Loading…
Cancel
Save