diff options
-rw-r--r-- | AST.cpp | 40 | ||||
-rw-r--r-- | AST.h | 26 | ||||
-rw-r--r-- | Compiler.cpp | 2 | ||||
-rw-r--r-- | CompilerContext.h | 4 | ||||
-rw-r--r-- | ExpressionCompiler.cpp | 177 | ||||
-rw-r--r-- | ExpressionCompiler.h | 77 | ||||
-rw-r--r-- | NameAndTypeResolver.cpp | 5 | ||||
-rw-r--r-- | Types.cpp | 6 | ||||
-rw-r--r-- | Types.h | 15 |
9 files changed, 245 insertions, 107 deletions
@@ -278,6 +278,15 @@ vector<FunctionDefinition const*> ContractDefinition::getInterfaceFunctions() co 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() { for (shared_ptr<Statement> const& statement: m_statements) @@ -315,7 +324,7 @@ void Return::checkTypeRequirements() void VariableDefinition::checkTypeRequirements() { // 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 // rules inherited from JavaScript. if (m_value) @@ -329,13 +338,14 @@ void VariableDefinition::checkTypeRequirements() 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() { m_leftHandSide->checkTypeRequirements(); - if (!m_leftHandSide->isLvalue()) - BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue.")); + m_leftHandSide->requireLValue(); m_rightHandSide->expectType(*m_leftHandSide->getType()); m_type = m_leftHandSide->getType(); if (m_assigmentOperator != Token::ASSIGN) @@ -359,13 +369,19 @@ void Expression::expectType(Type const& _expectedType) + _expectedType.toString() + ".")); } +void Expression::requireLValue() +{ + if (!isLvalue()) + BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue.")); + m_lvalueRequested = true; +} + void UnaryOperation::checkTypeRequirements() { // INC, DEC, ADD, SUB, NOT, BIT_NOT, DELETE m_subExpression->checkTypeRequirements(); if (m_operator == Token::Value::INC || m_operator == Token::Value::DEC || m_operator == Token::Value::DELETE) - if (!m_subExpression->isLvalue()) - BOOST_THROW_EXCEPTION(createTypeError("Expression has to be an lvalue.")); + m_subExpression->requireLValue(); m_type = m_subExpression->getType(); if (!m_type->acceptsUnaryOperator(m_operator)) BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type.")); @@ -416,6 +432,8 @@ void FunctionCall::checkTypeRequirements() } else { + m_expression->requireLValue(); + //@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 // function parameters @@ -448,8 +466,15 @@ void MemberAccess::checkTypeRequirements() void IndexAccess::checkTypeRequirements() { - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Index access not yet implemented.")); - // m_type = ; + m_base->checkTypeRequirements(); + 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() @@ -481,6 +506,7 @@ void Identifier::checkTypeRequirements() // Calling a function (e.g. function(12), otherContract.function(34)) does not do a type // conversion. m_type = make_shared<FunctionType>(*functionDef); + m_isLvalue = true; return; } ContractDefinition* contractDef = dynamic_cast<ContractDefinition*>(m_referencedDeclaration); @@ -186,6 +186,8 @@ public: void addLocalVariable(VariableDeclaration const& _localVariable) { m_localVariables.push_back(&_localVariable); } 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: bool m_isPublic; 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 /// 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()); } 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; } @@ -270,7 +272,7 @@ public: UserDefinedTypeName(Location const& _location, ASTPointer<ASTString> const& _name): TypeName(_location), m_name(_name) {} 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; } void setReferencedStruct(StructDefinition& _referencedStruct) { m_referencedStruct = &_referencedStruct; } @@ -292,7 +294,10 @@ public: ASTPointer<TypeName> const& _valueType): TypeName(_location), m_keyType(_keyType), m_valueType(_valueType) {} 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: ASTPointer<ElementaryTypeName> m_keyType; @@ -481,7 +486,7 @@ private: class Expression: public ASTNode { 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; std::shared_ptr<Type const> const& getType() const { return m_type; } @@ -490,6 +495,12 @@ public: /// Helper function, infer the type via @ref checkTypeRequirements and then check that it /// is implicitly convertible to @a _expectedType. If not, throw exception. 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: //! Inferred type of the expression, only filled after a call to checkTypeRequirements(). @@ -497,6 +508,8 @@ protected: //! Whether or not this expression is an lvalue, i.e. something that can be assigned to. //! This is set during calls to @a checkTypeRequirements() 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. @@ -543,6 +556,7 @@ public: Token::Value getOperator() const { return m_operator; } bool isPrefixOperation() const { return m_isPrefix; } + Expression& getSubExpression() const { return *m_subExpression; } private: Token::Value m_operator; @@ -635,6 +649,8 @@ public: virtual void accept(ASTVisitor& _visitor) override; virtual void checkTypeRequirements() override; + Expression& getBaseExpression() const { return *m_base; } + Expression& getIndexExpression() const { return *m_index; } private: ASTPointer<Expression> m_base; ASTPointer<Expression> m_index; diff --git a/Compiler.cpp b/Compiler.cpp index da28ba8a..eed88678 100644 --- a/Compiler.cpp +++ b/Compiler.cpp @@ -225,7 +225,7 @@ bool Compiler::visit(IfStatement& _ifStatement) eth::AssemblyItem trueTag = m_context.appendConditionalJump(); if (_ifStatement.getFalseStatement()) _ifStatement.getFalseStatement()->accept(*this); - eth::AssemblyItem endTag = m_context.appendJump(); + eth::AssemblyItem endTag = m_context.appendJumpToNew(); m_context << trueTag; _ifStatement.getTrueStatement().accept(*this); m_context << endTag; diff --git a/CompilerContext.h b/CompilerContext.h index 562c2932..e624222d 100644 --- a/CompilerContext.h +++ b/CompilerContext.h @@ -65,7 +65,9 @@ public: /// Appends a JUMPI instruction to @a _tag CompilerContext& appendConditionalJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJumpI(_tag); return *this; } /// 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 CompilerContext& appendJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJump(_tag); return *this; } /// Appends pushing of a new tag and @returns the new tag. diff --git a/ExpressionCompiler.cpp b/ExpressionCompiler.cpp index 05bbb091..d80b42b3 100644 --- a/ExpressionCompiler.cpp +++ b/ExpressionCompiler.cpp @@ -22,6 +22,7 @@ #include <utility> #include <numeric> +#include <libdevcore/Common.h> #include <libsolidity/AST.h> #include <libsolidity/ExpressionCompiler.h> #include <libsolidity/CompilerContext.h> @@ -50,14 +51,19 @@ bool ExpressionCompiler::visit(Assignment& _assignment) appendTypeConversion(*_assignment.getRightHandSide().getType(), *_assignment.getType()); m_currentLValue.reset(); _assignment.getLeftHandSide().accept(*this); + if (asserts(m_currentLValue.isValid())) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("LValue not retrieved.")); Token::Value op = _assignment.getAssignmentOperator(); 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()); - else - m_context << eth::Instruction::POP; + } + m_currentLValue.storeValue(_assignment); - storeInLValue(_assignment); return false; } @@ -76,23 +82,37 @@ void ExpressionCompiler::endVisit(UnaryOperation& _unaryOperation) m_context << eth::Instruction::NOT; break; case Token::DELETE: // delete - { - // a -> a xor a (= 0). // @todo semantics change for complex types - m_context << eth::Instruction::DUP1 << eth::Instruction::XOR; - storeInLValue(_unaryOperation); + if (asserts(m_currentLValue.isValid())) + 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); break; - } case Token::INC: // ++ (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()) - 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); if (_unaryOperation.getOperator() == Token::INC) m_context << eth::Instruction::ADD; else 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()); break; case Token::ADD: // + // unary add, so basically no-op @@ -151,12 +171,6 @@ bool ExpressionCompiler::visit(FunctionCall& _functionCall) { // Calling convention: Caller pushes return address and arguments // 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(); eth::AssemblyItem returnLabel = m_context.pushNewTag(); @@ -168,8 +182,12 @@ bool ExpressionCompiler::visit(FunctionCall& _functionCall) arguments[i]->accept(*this); appendTypeConversion(*arguments[i]->getType(), *function.getParameters()[i]->getType()); } + m_currentLValue.reset(); + _functionCall.getExpression().accept(*this); + if (asserts(m_currentLValue.isInCode())) + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Code reference expected.")); - m_context.appendJumpTo(functionTag); + m_context.appendJump(); m_context << returnLabel; // callee adds return parameters, but removes arguments and return label @@ -185,30 +203,33 @@ bool ExpressionCompiler::visit(FunctionCall& _functionCall) void ExpressionCompiler::endVisit(MemberAccess&) { - + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Member access not yet implemented.")); } -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) { - Declaration const* declaration = _identifier.getReferencedDeclaration(); - if (m_context.isLocalVariable(declaration)) - 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); + m_currentLValue.fromDeclaration(_identifier, *_identifier.getReferencedDeclaration()); + m_currentLValue.retrieveValueIfLValueNotRequested(_identifier); } void ExpressionCompiler::endVisit(Literal& _literal) @@ -371,66 +392,104 @@ void ExpressionCompiler::appendHighBitsCleanup(IntegerType const& _typeOnStack) 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: - // not stored on the stack + case CODE: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Tried to retrieve value of a function.")); 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 BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation()) << errinfo_comment("Stack too deep.")); - m_context << eth::dupInstruction(stackPos + 1); + *m_context << eth::dupInstruction(stackPos + 1); break; } - case LValueLocation::STORAGE: - m_context << m_currentLValue.location << eth::Instruction::SLOAD; + case STORAGE: + if (!_remove) + *m_context << eth::Instruction::DUP1; + *m_context << eth::Instruction::SLOAD; break; - case LValueLocation::MEMORY: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type not yet implemented.")); + case MEMORY: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Location type not yet implemented.")); break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unsupported location type.")); + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Unsupported location type.")); 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) BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation()) << errinfo_comment("Stack too deep.")); else if (stackPos > 0) - m_context << eth::swapInstruction(stackPos) << eth::Instruction::POP; + *m_context << eth::swapInstruction(stackPos) << eth::Instruction::POP; if (!_move) - retrieveLValueValue(_expression); + retrieveValue(_expression); break; } - case LValueLocation::STORAGE: + case LValue::STORAGE: if (!_move) - m_context << eth::Instruction::DUP1; - m_context << m_currentLValue.location << eth::Instruction::SSTORE; + *m_context << eth::Instruction::DUP2 << eth::Instruction::SWAP1; + *m_context << eth::Instruction::SSTORE; break; - case LValueLocation::CODE: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type does not support assignment.")); + case LValue::CODE: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Location type does not support assignment.")); break; - case LValueLocation::MEMORY: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Location type not yet implemented.")); + case LValue::MEMORY: + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Location type not yet implemented.")); break; default: - BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unsupported location type.")); + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_sourceLocation(_expression.getLocation()) + << errinfo_comment("Unsupported location type.")); 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.")); +} + } } diff --git a/ExpressionCompiler.h b/ExpressionCompiler.h index bd5a9f86..f52da29e 100644 --- a/ExpressionCompiler.h +++ b/ExpressionCompiler.h @@ -20,6 +20,7 @@ * Solidity AST to EVM bytecode compiler for expressions. */ +#include <boost/noncopyable.hpp> #include <libdevcore/Common.h> #include <libsolidity/ASTVisitor.h> @@ -49,14 +50,15 @@ public: static void appendTypeConversion(CompilerContext& _context, Type const& _typeOnStack, Type const& _targetType); private: - ExpressionCompiler(CompilerContext& _compilerContext): m_context(_compilerContext) {} + ExpressionCompiler(CompilerContext& _compilerContext): + m_context(_compilerContext), m_currentLValue(m_context) {} virtual bool visit(Assignment& _assignment) override; virtual void endVisit(UnaryOperation& _unaryOperation) override; virtual bool visit(BinaryOperation& _binaryOperation) override; virtual bool visit(FunctionCall& _functionCall) 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(Literal& _literal) override; @@ -79,37 +81,58 @@ private: //// Appends code that cleans higher-order bits for integer types. 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 }; - - LValueLocation() { reset(); } - LValueLocation(LocationType _type, u256 const& _location): locationType(_type), location(_location) {} - void reset() { locationType = INVALID; location = 0; } - bool isValid() const { return locationType != INVALID; } - bool isInCode() const { return locationType == CODE; } - bool isInOnStack() const { return locationType == STACK; } - bool isInMemory() const { return locationType == MEMORY; } - bool isInStorage() const { return locationType == STORAGE; } - - LocationType locationType; - /// Depending on the type, this is the id of a tag (code), the base offset of a stack - /// variable (@see CompilerContext::getBaseStackOffsetOfVariable) or the offset in - /// storage or memory. - u256 location; + public: + enum LValueType { NONE, CODE, STACK, MEMORY, STORAGE }; + + explicit LValue(CompilerContext& _compilerContext): m_context(&_compilerContext) { reset(); } + LValue(CompilerContext& _compilerContext, LValueType _type, unsigned _baseStackOffset = 0): + m_context(&_compilerContext), m_type(_type), m_baseStackOffset(_baseStackOffset) {} + + /// Set type according to the declaration and retrieve the reference. + /// @a _expression is the current expression, used for error reporting. + void fromDeclaration(Expression const& _expression, Declaration const& _declaration); + void reset() { m_type = NONE; m_baseStackOffset = 0; } + + bool isValid() const { return m_type != NONE; } + bool isInCode() const { return m_type == CODE; } + bool isInOnStack() const { return m_type == STACK; } + 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; + LValue m_currentLValue; }; diff --git a/NameAndTypeResolver.cpp b/NameAndTypeResolver.cpp index 0578e599..4a15fe79 100644 --- a/NameAndTypeResolver.cpp +++ b/NameAndTypeResolver.cpp @@ -52,7 +52,7 @@ void NameAndTypeResolver::resolveNamesAndTypes(ContractDefinition& _contract) for (ASTPointer<FunctionDefinition> const& function: _contract.getDefinedFunctions()) { m_currentScope = &m_scopes[function.get()]; - function->getBody().checkTypeRequirements(); + function->checkTypeRequirements(); } m_currentScope = &m_scopes[nullptr]; } @@ -186,9 +186,8 @@ bool ReferencesResolver::visit(Return& _return) return true; } -bool ReferencesResolver::visit(Mapping&) +bool ReferencesResolver::visit(Mapping& _mapping) { - // @todo return true; } @@ -63,9 +63,11 @@ shared_ptr<Type> Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeN 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) @@ -35,7 +35,7 @@ namespace dev namespace solidity { -// @todo realMxN, string<N>, mapping +// @todo realMxN, string<N> /** * 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. /// For dynamically "allocated" types, it returns the size of the statically allocated head, 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 u256 literalValue(Literal const&) const @@ -182,6 +184,8 @@ public: virtual bool operator==(Type const& _other) const override; virtual u256 getStorageSize() const; + //@todo it can, if its members can + virtual bool canLiveOutsideStorage() const { return false; } virtual std::string toString() const override { return "struct{...}"; } private: @@ -202,6 +206,7 @@ public: virtual bool operator==(Type const& _other) const override; virtual std::string toString() const override { return "function(...)returns(...)"; } 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: FunctionDefinition const& m_function; @@ -214,11 +219,15 @@ class MappingType: public Type { public: 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 std::string toString() const override { return "mapping(...=>...)"; } + 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: std::shared_ptr<Type const> m_keyType; std::shared_ptr<Type const> m_valueType; @@ -236,6 +245,7 @@ public: 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 bool canLiveOutsideStorage() const { return false; } }; /** @@ -252,6 +262,7 @@ public: 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 bool canLiveOutsideStorage() const { return false; } virtual std::string toString() const override { return "type(" + m_actualType->toString() + ")"; } private: |