Merge branch 'sol_integerConstants' of https://github.com/chriseth/cpp-ethereum into chriseth-sol_integerConstants

This commit is contained in:
Gav Wood 2015-01-09 14:57:59 +01:00
commit 875ec9d471
6 changed files with 323 additions and 164 deletions

40
AST.cpp
View File

@ -173,7 +173,15 @@ void VariableDefinition::checkTypeRequirements()
{ {
// no type declared and no previous assignment, infer the type // no type declared and no previous assignment, infer the type
m_value->checkTypeRequirements(); m_value->checkTypeRequirements();
m_variable->setType(m_value->getType()); TypePointer type = m_value->getType();
if (type->getCategory() == Type::Category::INTEGER_CONSTANT)
{
auto intType = dynamic_pointer_cast<IntegerConstantType const>(type)->getIntegerType();
if (!intType)
BOOST_THROW_EXCEPTION(m_value->createTypeError("Invalid integer constant " + type->toString()));
type = intType;
}
m_variable->setType(type);
} }
} }
} }
@ -192,16 +200,22 @@ void Assignment::checkTypeRequirements()
{ {
// compound assignment // compound assignment
m_rightHandSide->checkTypeRequirements(); m_rightHandSide->checkTypeRequirements();
TypePointer resultType = Type::binaryOperatorResult(Token::AssignmentToBinaryOp(m_assigmentOperator), TypePointer resultType = m_type->binaryOperatorResult(Token::AssignmentToBinaryOp(m_assigmentOperator),
m_type, m_rightHandSide->getType()); m_rightHandSide->getType());
if (!resultType || *resultType != *m_type) if (!resultType || *resultType != *m_type)
BOOST_THROW_EXCEPTION(createTypeError("Operator not compatible with type.")); BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_assigmentOperator)) +
" not compatible with types " +
m_type->toString() + " and " +
m_rightHandSide->getType()->toString()));
} }
} }
void ExpressionStatement::checkTypeRequirements() void ExpressionStatement::checkTypeRequirements()
{ {
m_expression->checkTypeRequirements(); m_expression->checkTypeRequirements();
if (m_expression->getType()->getCategory() == Type::Category::INTEGER_CONSTANT)
if (!dynamic_pointer_cast<IntegerConstantType const>(m_expression->getType())->getIntegerType())
BOOST_THROW_EXCEPTION(m_expression->createTypeError("Invalid integer constant."));
} }
void Expression::expectType(Type const& _expectedType) void Expression::expectType(Type const& _expectedType)
@ -227,8 +241,8 @@ void UnaryOperation::checkTypeRequirements()
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)
m_subExpression->requireLValue(); m_subExpression->requireLValue();
m_type = m_subExpression->getType(); m_type = m_subExpression->getType()->unaryOperatorResult(m_operator);
if (!m_type->acceptsUnaryOperator(m_operator)) if (!m_type)
BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type.")); BOOST_THROW_EXCEPTION(createTypeError("Unary operator not compatible with type."));
} }
@ -236,7 +250,7 @@ void BinaryOperation::checkTypeRequirements()
{ {
m_left->checkTypeRequirements(); m_left->checkTypeRequirements();
m_right->checkTypeRequirements(); m_right->checkTypeRequirements();
m_commonType = Type::binaryOperatorResult(m_operator, m_left->getType(), m_right->getType()); m_commonType = m_left->getType()->binaryOperatorResult(m_operator, m_right->getType());
if (!m_commonType) if (!m_commonType)
BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_operator)) + BOOST_THROW_EXCEPTION(createTypeError("Operator " + string(Token::toString(m_operator)) +
" not compatible with types " + " not compatible with types " +
@ -300,7 +314,7 @@ void NewExpression::checkTypeRequirements()
m_contract = dynamic_cast<ContractDefinition const*>(m_contractName->getReferencedDeclaration()); m_contract = dynamic_cast<ContractDefinition const*>(m_contractName->getReferencedDeclaration());
if (!m_contract) if (!m_contract)
BOOST_THROW_EXCEPTION(createTypeError("Identifier is not a contract.")); BOOST_THROW_EXCEPTION(createTypeError("Identifier is not a contract."));
shared_ptr<ContractType const> type = make_shared<ContractType const>(*m_contract); shared_ptr<ContractType const> type = make_shared<ContractType>(*m_contract);
m_type = type; m_type = type;
TypePointers const& parameterTypes = type->getConstructorType()->getParameterTypes(); TypePointers const& parameterTypes = type->getConstructorType()->getParameterTypes();
if (parameterTypes.size() != m_arguments.size()) if (parameterTypes.size() != m_arguments.size())
@ -351,7 +365,7 @@ void Identifier::checkTypeRequirements()
if (structDef) if (structDef)
{ {
// note that we do not have a struct type here // note that we do not have a struct type here
m_type = make_shared<TypeType const>(make_shared<StructType const>(*structDef)); m_type = make_shared<TypeType>(make_shared<StructType>(*structDef));
return; return;
} }
FunctionDefinition const* functionDef = dynamic_cast<FunctionDefinition const*>(m_referencedDeclaration); FunctionDefinition const* functionDef = dynamic_cast<FunctionDefinition const*>(m_referencedDeclaration);
@ -360,13 +374,13 @@ void Identifier::checkTypeRequirements()
// a function reference is not a TypeType, because calling a TypeType converts to the type. // a function reference is not a TypeType, because calling a TypeType converts to the type.
// 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 const>(*functionDef); m_type = make_shared<FunctionType>(*functionDef);
return; return;
} }
ContractDefinition const* contractDef = dynamic_cast<ContractDefinition const*>(m_referencedDeclaration); ContractDefinition const* contractDef = dynamic_cast<ContractDefinition const*>(m_referencedDeclaration);
if (contractDef) if (contractDef)
{ {
m_type = make_shared<TypeType const>(make_shared<ContractType>(*contractDef)); m_type = make_shared<TypeType>(make_shared<ContractType>(*contractDef));
return; return;
} }
MagicVariableDeclaration const* magicVariable = dynamic_cast<MagicVariableDeclaration const*>(m_referencedDeclaration); MagicVariableDeclaration const* magicVariable = dynamic_cast<MagicVariableDeclaration const*>(m_referencedDeclaration);
@ -380,14 +394,14 @@ void Identifier::checkTypeRequirements()
void ElementaryTypeNameExpression::checkTypeRequirements() void ElementaryTypeNameExpression::checkTypeRequirements()
{ {
m_type = make_shared<TypeType const>(Type::fromElementaryTypeName(m_typeToken)); m_type = make_shared<TypeType>(Type::fromElementaryTypeName(m_typeToken));
} }
void Literal::checkTypeRequirements() void Literal::checkTypeRequirements()
{ {
m_type = Type::forLiteral(*this); m_type = Type::forLiteral(*this);
if (!m_type) if (!m_type)
BOOST_THROW_EXCEPTION(createTypeError("Literal value too large.")); BOOST_THROW_EXCEPTION(createTypeError("Invalid literal value."));
} }
} }

View File

@ -71,12 +71,20 @@ bool ExpressionCompiler::visit(Assignment const& _assignment)
return false; return false;
} }
void ExpressionCompiler::endVisit(UnaryOperation const& _unaryOperation) bool ExpressionCompiler::visit(UnaryOperation const& _unaryOperation)
{ {
//@todo type checking and creating code for an operator should be in the same place: //@todo type checking and creating code for an operator should be in the same place:
// the operator should know how to convert itself and to which types it applies, so // the operator should know how to convert itself and to which types it applies, so
// put this code together with "Type::acceptsBinary/UnaryOperator" into a class that // put this code together with "Type::acceptsBinary/UnaryOperator" into a class that
// represents the operator // represents the operator
if (_unaryOperation.getType()->getCategory() == Type::Category::INTEGER_CONSTANT)
{
m_context << _unaryOperation.getType()->literalValue(nullptr);
return false;
}
_unaryOperation.getSubExpression().accept(*this);
switch (_unaryOperation.getOperator()) switch (_unaryOperation.getOperator())
{ {
case Token::NOT: // ! case Token::NOT: // !
@ -128,6 +136,7 @@ void ExpressionCompiler::endVisit(UnaryOperation const& _unaryOperation)
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid unary operator: " + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid unary operator: " +
string(Token::toString(_unaryOperation.getOperator())))); string(Token::toString(_unaryOperation.getOperator()))));
} }
return false;
} }
bool ExpressionCompiler::visit(BinaryOperation const& _binaryOperation) bool ExpressionCompiler::visit(BinaryOperation const& _binaryOperation)
@ -139,17 +148,19 @@ bool ExpressionCompiler::visit(BinaryOperation const& _binaryOperation)
if (op == Token::AND || op == Token::OR) // special case: short-circuiting if (op == Token::AND || op == Token::OR) // special case: short-circuiting
appendAndOrOperatorCode(_binaryOperation); appendAndOrOperatorCode(_binaryOperation);
else if (commonType.getCategory() == Type::Category::INTEGER_CONSTANT)
m_context << commonType.literalValue(nullptr);
else else
{ {
bool cleanupNeeded = false; bool cleanupNeeded = commonType.getCategory() == Type::Category::INTEGER &&
if (commonType.getCategory() == Type::Category::INTEGER) (Token::isCompareOp(op) || op == Token::DIV || op == Token::MOD);
if (Token::isCompareOp(op) || op == Token::DIV || op == Token::MOD)
cleanupNeeded = true;
// for commutative operators, push the literal as late as possible to allow improved optimization // for commutative operators, push the literal as late as possible to allow improved optimization
//@todo this has to be extended for literal expressions auto isLiteral = [](Expression const& _e)
bool swap = (m_optimize && Token::isCommutativeOp(op) && dynamic_cast<Literal const*>(&rightExpression) {
&& !dynamic_cast<Literal const*>(&leftExpression)); return dynamic_cast<Literal const*>(&_e) || _e.getType()->getCategory() == Type::Category::INTEGER_CONSTANT;
};
bool swap = m_optimize && Token::isCommutativeOp(op) && isLiteral(rightExpression) && !isLiteral(leftExpression);
if (swap) if (swap)
{ {
leftExpression.accept(*this); leftExpression.accept(*this);
@ -478,10 +489,10 @@ void ExpressionCompiler::endVisit(Literal const& _literal)
{ {
switch (_literal.getType()->getCategory()) switch (_literal.getType()->getCategory())
{ {
case Type::Category::INTEGER: case Type::Category::INTEGER_CONSTANT:
case Type::Category::BOOL: case Type::Category::BOOL:
case Type::Category::STRING: case Type::Category::STRING:
m_context << _literal.getType()->literalValue(_literal); m_context << _literal.getType()->literalValue(&_literal);
break; break;
default: default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Only integer, boolean and string literals implemented for now.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Only integer, boolean and string literals implemented for now."));
@ -617,9 +628,16 @@ void ExpressionCompiler::appendTypeConversion(Type const& _typeOnStack, Type con
if (_typeOnStack == _targetType && !_cleanupNeeded) if (_typeOnStack == _targetType && !_cleanupNeeded)
return; return;
if (_typeOnStack.getCategory() == Type::Category::INTEGER) Type::Category stackTypeCategory = _typeOnStack.getCategory();
Type::Category targetTypeCategory = _targetType.getCategory();
if (stackTypeCategory == Type::Category::INTEGER)
{
solAssert(targetTypeCategory == Type::Category::INTEGER || targetTypeCategory == Type::Category::CONTRACT, "");
appendHighBitsCleanup(dynamic_cast<IntegerType const&>(_typeOnStack)); appendHighBitsCleanup(dynamic_cast<IntegerType const&>(_typeOnStack));
else if (_typeOnStack.getCategory() == Type::Category::STRING) }
else if (stackTypeCategory == Type::Category::INTEGER_CONSTANT)
solAssert(targetTypeCategory == Type::Category::INTEGER || targetTypeCategory == Type::Category::CONTRACT, "");
else if (stackTypeCategory == Type::Category::STRING)
{ {
// nothing to do, strings are high-order-bit-aligned // nothing to do, strings are high-order-bit-aligned
//@todo clear lower-order bytes if we allow explicit conversion to shorter strings //@todo clear lower-order bytes if we allow explicit conversion to shorter strings

View File

@ -58,7 +58,7 @@ private:
m_optimize(_optimize), m_context(_compilerContext), m_currentLValue(m_context) {} m_optimize(_optimize), m_context(_compilerContext), m_currentLValue(m_context) {}
virtual bool visit(Assignment const& _assignment) override; virtual bool visit(Assignment const& _assignment) override;
virtual void endVisit(UnaryOperation const& _unaryOperation) override; virtual bool visit(UnaryOperation const& _unaryOperation) override;
virtual bool visit(BinaryOperation const& _binaryOperation) override; virtual bool visit(BinaryOperation const& _binaryOperation) override;
virtual bool visit(FunctionCall const& _functionCall) override; virtual bool visit(FunctionCall const& _functionCall) override;
virtual bool visit(NewExpression const& _newExpression) override; virtual bool visit(NewExpression const& _newExpression) override;

View File

@ -455,7 +455,7 @@ void Scanner::scanToken()
token = Token::ADD; token = Token::ADD;
break; break;
case '-': case '-':
// - -- -= Number // - -- -=
advance(); advance();
if (m_char == '-') if (m_char == '-')
{ {
@ -464,8 +464,6 @@ void Scanner::scanToken()
} }
else if (m_char == '=') else if (m_char == '=')
token = selectToken(Token::ASSIGN_SUB); token = selectToken(Token::ASSIGN_SUB);
else if (m_char == '.' || isDecimalDigit(m_char))
token = scanNumber('-');
else else
token = Token::SUB; token = Token::SUB;
break; break;
@ -650,8 +648,7 @@ Token::Value Scanner::scanNumber(char _charSeen)
} }
else else
{ {
if (_charSeen == '-') solAssert(_charSeen == 0, "");
addLiteralChar('-');
// if the first character is '0' we must check for octals and hex // if the first character is '0' we must check for octals and hex
if (m_char == '0') if (m_char == '0')
{ {

264
Types.cpp
View File

@ -44,17 +44,17 @@ shared_ptr<Type const> Type::fromElementaryTypeName(Token::Value _typeToken)
if (bytes == 0) if (bytes == 0)
bytes = 32; bytes = 32;
int modifier = offset / 33; int modifier = offset / 33;
return make_shared<IntegerType const>(bytes * 8, return make_shared<IntegerType>(bytes * 8,
modifier == 0 ? IntegerType::Modifier::SIGNED : modifier == 0 ? IntegerType::Modifier::SIGNED :
modifier == 1 ? IntegerType::Modifier::UNSIGNED : modifier == 1 ? IntegerType::Modifier::UNSIGNED :
IntegerType::Modifier::HASH); IntegerType::Modifier::HASH);
} }
else if (_typeToken == Token::ADDRESS) else if (_typeToken == Token::ADDRESS)
return make_shared<IntegerType const>(0, IntegerType::Modifier::ADDRESS); return make_shared<IntegerType>(0, IntegerType::Modifier::ADDRESS);
else if (_typeToken == Token::BOOL) else if (_typeToken == Token::BOOL)
return make_shared<BoolType const>(); return make_shared<BoolType>();
else if (Token::STRING0 <= _typeToken && _typeToken <= Token::STRING32) else if (Token::STRING0 <= _typeToken && _typeToken <= Token::STRING32)
return make_shared<StaticStringType const>(int(_typeToken) - int(Token::STRING0)); return make_shared<StaticStringType>(int(_typeToken) - int(Token::STRING0));
else else
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unable to convert elementary typename " + BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unable to convert elementary typename " +
std::string(Token::toString(_typeToken)) + " to type.")); std::string(Token::toString(_typeToken)) + " to type."));
@ -64,11 +64,11 @@ shared_ptr<Type const> Type::fromUserDefinedTypeName(UserDefinedTypeName const&
{ {
Declaration const* declaration = _typeName.getReferencedDeclaration(); Declaration const* declaration = _typeName.getReferencedDeclaration();
if (StructDefinition const* structDef = dynamic_cast<StructDefinition const*>(declaration)) if (StructDefinition const* structDef = dynamic_cast<StructDefinition const*>(declaration))
return make_shared<StructType const>(*structDef); return make_shared<StructType>(*structDef);
else if (FunctionDefinition const* function = dynamic_cast<FunctionDefinition const*>(declaration)) else if (FunctionDefinition const* function = dynamic_cast<FunctionDefinition const*>(declaration))
return make_shared<FunctionType const>(*function); return make_shared<FunctionType>(*function);
else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration)) else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration))
return make_shared<ContractType const>(*contract); return make_shared<ContractType>(*contract);
return shared_ptr<Type const>(); return shared_ptr<Type const>();
} }
@ -80,7 +80,7 @@ shared_ptr<Type const> Type::fromMapping(Mapping const& _typeName)
shared_ptr<Type const> valueType = _typeName.getValueType().toType(); shared_ptr<Type const> valueType = _typeName.getValueType().toType();
if (!valueType) if (!valueType)
BOOST_THROW_EXCEPTION(_typeName.getValueType().createTypeError("Invalid type name")); BOOST_THROW_EXCEPTION(_typeName.getValueType().createTypeError("Invalid type name"));
return make_shared<MappingType const>(keyType, valueType); return make_shared<MappingType>(keyType, valueType);
} }
shared_ptr<Type const> Type::forLiteral(Literal const& _literal) shared_ptr<Type const> Type::forLiteral(Literal const& _literal)
@ -89,14 +89,14 @@ shared_ptr<Type const> Type::forLiteral(Literal const& _literal)
{ {
case Token::TRUE_LITERAL: case Token::TRUE_LITERAL:
case Token::FALSE_LITERAL: case Token::FALSE_LITERAL:
return make_shared<BoolType const>(); return make_shared<BoolType>();
case Token::NUMBER: case Token::NUMBER:
return IntegerType::smallestTypeForLiteral(_literal.getValue()); return IntegerConstantType::fromLiteral(_literal.getValue());
case Token::STRING_LITERAL: case Token::STRING_LITERAL:
//@todo put larger strings into dynamic strings //@todo put larger strings into dynamic strings
return StaticStringType::smallestTypeForLiteral(_literal.getValue()); return StaticStringType::smallestTypeForLiteral(_literal.getValue());
default: default:
return shared_ptr<Type const>(); return shared_ptr<Type>();
} }
} }
@ -112,19 +112,6 @@ TypePointer Type::commonType(TypePointer const& _a, TypePointer const& _b)
const MemberList Type::EmptyMemberList = MemberList(); const MemberList Type::EmptyMemberList = MemberList();
shared_ptr<IntegerType const> IntegerType::smallestTypeForLiteral(string const& _literal)
{
bigint value(_literal);
bool isSigned = value < 0 || (!_literal.empty() && _literal.front() == '-');
if (isSigned)
// convert to positive number of same bit requirements
value = ((-value) - 1) << 1;
unsigned bytes = max(bytesRequired(value), 1u);
if (bytes > 32)
return shared_ptr<IntegerType const>();
return make_shared<IntegerType const>(bytes * 8, isSigned ? Modifier::SIGNED : Modifier::UNSIGNED);
}
IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier): IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier):
m_bits(_bits), m_modifier(_modifier) m_bits(_bits), m_modifier(_modifier)
{ {
@ -156,18 +143,26 @@ bool IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const
return _convertTo.getCategory() == getCategory() || _convertTo.getCategory() == Category::CONTRACT; return _convertTo.getCategory() == getCategory() || _convertTo.getCategory() == Category::CONTRACT;
} }
bool IntegerType::acceptsUnaryOperator(Token::Value _operator) const TypePointer IntegerType::unaryOperatorResult(Token::Value _operator) const
{ {
// "delete" is ok for all integer types
if (_operator == Token::DELETE) if (_operator == Token::DELETE)
return true; return shared_from_this();
if (isAddress()) // no further unary operators for addresses
return false; else if (isAddress())
if (_operator == Token::BIT_NOT) return TypePointer();
return true; // "~" is ok for all other types
if (isHash()) else if (_operator == Token::BIT_NOT)
return false; return shared_from_this();
return _operator == Token::ADD || _operator == Token::SUB || // nothing else for hashes
_operator == Token::INC || _operator == Token::DEC; else if (isHash())
return TypePointer();
// for non-hash integers, we allow +, -, ++ and --
else if (_operator == Token::ADD || _operator == Token::SUB ||
_operator == Token::INC || _operator == Token::DEC)
return shared_from_this();
else
return TypePointer();
} }
bool IntegerType::operator==(Type const& _other) const bool IntegerType::operator==(Type const& _other) const
@ -186,17 +181,11 @@ string IntegerType::toString() const
return prefix + dev::toString(m_bits); return prefix + dev::toString(m_bits);
} }
u256 IntegerType::literalValue(Literal const& _literal) const TypePointer IntegerType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const
{ {
bigint value(_literal.getValue()); if (_other->getCategory() != Category::INTEGER_CONSTANT && _other->getCategory() != getCategory())
return u256(value);
}
TypePointer IntegerType::binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _this, TypePointer const& _other) const
{
if (getCategory() != _other->getCategory())
return TypePointer(); return TypePointer();
auto commonType = dynamic_pointer_cast<IntegerType const>(Type::commonType(_this, _other)); auto commonType = dynamic_pointer_cast<IntegerType const>(Type::commonType(shared_from_this(), _other));
if (!commonType) if (!commonType)
return TypePointer(); return TypePointer();
@ -216,18 +205,153 @@ TypePointer IntegerType::binaryOperatorResultImpl(Token::Value _operator, TypePo
const MemberList IntegerType::AddressMemberList = const MemberList IntegerType::AddressMemberList =
MemberList({{"balance", MemberList({{"balance",
make_shared<IntegerType const>(256)}, make_shared<IntegerType >(256)},
{"callstring32", {"callstring32",
make_shared<FunctionType const>(TypePointers({make_shared<StaticStringType const>(32)}), make_shared<FunctionType>(TypePointers({make_shared<StaticStringType>(32)}),
TypePointers(), FunctionType::Location::BARE)}, TypePointers(), FunctionType::Location::BARE)},
{"callstring32string32", {"callstring32string32",
make_shared<FunctionType const>(TypePointers({make_shared<StaticStringType const>(32), make_shared<FunctionType>(TypePointers({make_shared<StaticStringType>(32),
make_shared<StaticStringType const>(32)}), make_shared<StaticStringType>(32)}),
TypePointers(), FunctionType::Location::BARE)}, TypePointers(), FunctionType::Location::BARE)},
{"send", {"send",
make_shared<FunctionType const>(TypePointers({make_shared<IntegerType const>(256)}), make_shared<FunctionType>(TypePointers({make_shared<IntegerType>(256)}),
TypePointers(), FunctionType::Location::SEND)}}); TypePointers(), FunctionType::Location::SEND)}});
shared_ptr<IntegerConstantType const> IntegerConstantType::fromLiteral(string const& _literal)
{
return make_shared<IntegerConstantType>(bigint(_literal));
}
bool IntegerConstantType::isImplicitlyConvertibleTo(Type const& _convertTo) const
{
TypePointer integerType = getIntegerType();
return integerType && integerType->isImplicitlyConvertibleTo(_convertTo);
}
bool IntegerConstantType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
TypePointer integerType = getIntegerType();
return integerType && integerType->isExplicitlyConvertibleTo(_convertTo);
}
TypePointer IntegerConstantType::unaryOperatorResult(Token::Value _operator) const
{
bigint value;
switch (_operator)
{
case Token::BIT_NOT:
value = ~m_value;
break;
case Token::ADD:
value = m_value;
break;
case Token::SUB:
value = -m_value;
break;
default:
return TypePointer();
}
return make_shared<IntegerConstantType>(value);
}
TypePointer IntegerConstantType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const
{
if (_other->getCategory() == Category::INTEGER)
{
shared_ptr<IntegerType const> integerType = getIntegerType();
if (!integerType)
return TypePointer();
return integerType->binaryOperatorResult(_operator, _other);
}
else if (_other->getCategory() != getCategory())
return TypePointer();
IntegerConstantType const& other = dynamic_cast<IntegerConstantType const&>(*_other);
if (Token::isCompareOp(_operator))
{
shared_ptr<IntegerType const> thisIntegerType = getIntegerType();
shared_ptr<IntegerType const> otherIntegerType = other.getIntegerType();
if (!thisIntegerType || !otherIntegerType)
return TypePointer();
return thisIntegerType->binaryOperatorResult(_operator, otherIntegerType);
}
else
{
bigint value;
switch (_operator)
{
case Token::BIT_OR:
value = m_value | other.m_value;
break;
case Token::BIT_XOR:
value = m_value ^ other.m_value;
break;
case Token::BIT_AND:
value = m_value & other.m_value;
break;
case Token::ADD:
value = m_value + other.m_value;
break;
case Token::SUB:
value = m_value - other.m_value;
break;
case Token::MUL:
value = m_value * other.m_value;
break;
case Token::DIV:
if (other.m_value == 0)
return TypePointer();
value = m_value / other.m_value;
break;
case Token::MOD:
if (other.m_value == 0)
return TypePointer();
value = m_value % other.m_value;
break;
default:
return TypePointer();
}
return make_shared<IntegerConstantType>(value);
}
}
bool IntegerConstantType::operator==(Type const& _other) const
{
if (_other.getCategory() != getCategory())
return false;
return m_value == dynamic_cast<IntegerConstantType const&>(_other).m_value;
}
string IntegerConstantType::toString() const
{
return "int_const " + m_value.str();
}
u256 IntegerConstantType::literalValue(Literal const*) const
{
// we ignore the literal and hope that the type was correctly determined
solAssert(m_value <= u256(-1), "Integer constant too large.");
solAssert(m_value >= -(bigint(1) << 255), "Integer constant too small.");
if (m_value >= 0)
return u256(m_value);
else
return s2u(s256(m_value));
}
shared_ptr<IntegerType const> IntegerConstantType::getIntegerType() const
{
bigint value = m_value;
bool negative = (value < 0);
if (negative) // convert to positive number of same bit requirements
value = ((-value) - 1) << 1;
if (value > u256(-1))
return shared_ptr<IntegerType const>();
else
return make_shared<IntegerType>(max(bytesRequired(value), 1u) * 8,
negative ? IntegerType::Modifier::SIGNED
: IntegerType::Modifier::UNSIGNED);
}
shared_ptr<StaticStringType> StaticStringType::smallestTypeForLiteral(string const& _literal) shared_ptr<StaticStringType> StaticStringType::smallestTypeForLiteral(string const& _literal)
{ {
if (_literal.length() <= 32) if (_literal.length() <= 32)
@ -257,12 +381,13 @@ bool StaticStringType::operator==(Type const& _other) const
return other.m_bytes == m_bytes; return other.m_bytes == m_bytes;
} }
u256 StaticStringType::literalValue(const Literal& _literal) const u256 StaticStringType::literalValue(const Literal* _literal) const
{ {
solAssert(_literal, "");
u256 value = 0; u256 value = 0;
for (char c: _literal.getValue()) for (char c: _literal->getValue())
value = (value << 8) | byte(c); value = (value << 8) | byte(c);
return value << ((32 - _literal.getValue().length()) * 8); return value << ((32 - _literal->getValue().length()) * 8);
} }
bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const
@ -278,22 +403,23 @@ bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const
return isImplicitlyConvertibleTo(_convertTo); return isImplicitlyConvertibleTo(_convertTo);
} }
u256 BoolType::literalValue(Literal const& _literal) const u256 BoolType::literalValue(Literal const* _literal) const
{ {
if (_literal.getToken() == Token::TRUE_LITERAL) solAssert(_literal, "");
if (_literal->getToken() == Token::TRUE_LITERAL)
return u256(1); return u256(1);
else if (_literal.getToken() == Token::FALSE_LITERAL) else if (_literal->getToken() == Token::FALSE_LITERAL)
return u256(0); return u256(0);
else else
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal."));
} }
TypePointer BoolType::binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _this, TypePointer const& _other) const TypePointer BoolType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const
{ {
if (getCategory() != _other->getCategory()) if (getCategory() != _other->getCategory())
return TypePointer(); return TypePointer();
if (Token::isCompareOp(_operator) || _operator == Token::AND || _operator == Token::OR) if (Token::isCompareOp(_operator) || _operator == Token::AND || _operator == Token::OR)
return _this; return _other;
else else
return TypePointer(); return TypePointer();
} }
@ -347,9 +473,9 @@ shared_ptr<FunctionType const> const& ContractType::getConstructorType() const
{ {
FunctionDefinition const* constructor = m_contract.getConstructor(); FunctionDefinition const* constructor = m_contract.getConstructor();
if (constructor) if (constructor)
m_constructorType = make_shared<FunctionType const>(*constructor); m_constructorType = make_shared<FunctionType>(*constructor);
else else
m_constructorType = make_shared<FunctionType const>(TypePointers(), TypePointers()); m_constructorType = make_shared<FunctionType>(TypePointers(), TypePointers());
} }
return m_constructorType; return m_constructorType;
} }
@ -521,21 +647,21 @@ MagicType::MagicType(MagicType::Kind _kind):
switch (m_kind) switch (m_kind)
{ {
case Kind::BLOCK: case Kind::BLOCK:
m_members = MemberList({{"coinbase", make_shared<IntegerType const>(0, IntegerType::Modifier::ADDRESS)}, m_members = MemberList({{"coinbase", make_shared<IntegerType>(0, IntegerType::Modifier::ADDRESS)},
{"timestamp", make_shared<IntegerType const>(256)}, {"timestamp", make_shared<IntegerType >(256)},
{"prevhash", make_shared<IntegerType const>(256, IntegerType::Modifier::HASH)}, {"prevhash", make_shared<IntegerType>(256, IntegerType::Modifier::HASH)},
{"difficulty", make_shared<IntegerType const>(256)}, {"difficulty", make_shared<IntegerType>(256)},
{"number", make_shared<IntegerType const>(256)}, {"number", make_shared<IntegerType>(256)},
{"gaslimit", make_shared<IntegerType const>(256)}}); {"gaslimit", make_shared<IntegerType>(256)}});
break; break;
case Kind::MSG: case Kind::MSG:
m_members = MemberList({{"sender", make_shared<IntegerType const>(0, IntegerType::Modifier::ADDRESS)}, m_members = MemberList({{"sender", make_shared<IntegerType>(0, IntegerType::Modifier::ADDRESS)},
{"gas", make_shared<IntegerType const>(256)}, {"gas", make_shared<IntegerType>(256)},
{"value", make_shared<IntegerType const>(256)}}); {"value", make_shared<IntegerType>(256)}});
break; break;
case Kind::TX: case Kind::TX:
m_members = MemberList({{"origin", make_shared<IntegerType const>(0, IntegerType::Modifier::ADDRESS)}, m_members = MemberList({{"origin", make_shared<IntegerType>(0, IntegerType::Modifier::ADDRESS)},
{"gasprice", make_shared<IntegerType const>(256)}}); {"gasprice", make_shared<IntegerType>(256)}});
break; break;
default: default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic."));

126
Types.h
View File

@ -70,12 +70,12 @@ private:
/** /**
* Abstract base class that forms the root of the type hierarchy. * Abstract base class that forms the root of the type hierarchy.
*/ */
class Type: private boost::noncopyable class Type: private boost::noncopyable, public std::enable_shared_from_this<Type>
{ {
public: public:
enum class Category enum class Category
{ {
INTEGER, BOOL, REAL, STRING, CONTRACT, STRUCT, FUNCTION, MAPPING, VOID, TYPE, MAGIC INTEGER, INTEGER_CONSTANT, BOOL, REAL, STRING, CONTRACT, STRUCT, FUNCTION, MAPPING, VOID, TYPE, MAGIC
}; };
///@{ ///@{
@ -92,12 +92,6 @@ public:
static TypePointer forLiteral(Literal const& _literal); static TypePointer forLiteral(Literal const& _literal);
/// @returns a pointer to _a or _b if the other is implicitly convertible to it or nullptr otherwise /// @returns a pointer to _a or _b if the other is implicitly convertible to it or nullptr otherwise
static TypePointer commonType(TypePointer const& _a, TypePointer const& _b); static TypePointer commonType(TypePointer const& _a, TypePointer const& _b);
/// @returns the resulting type of applying the given operator or an empty pointer if this is not possible.
/// The default implementation allows comparison operators if a common type exists
static TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _a, TypePointer const& _b)
{
return _a->binaryOperatorResultImpl(_operator, _a, _b);
}
virtual Category getCategory() const = 0; virtual Category getCategory() const = 0;
virtual bool isImplicitlyConvertibleTo(Type const& _other) const { return *this == _other; } virtual bool isImplicitlyConvertibleTo(Type const& _other) const { return *this == _other; }
@ -105,7 +99,17 @@ public:
{ {
return isImplicitlyConvertibleTo(_convertTo); return isImplicitlyConvertibleTo(_convertTo);
} }
virtual bool acceptsUnaryOperator(Token::Value) const { return false; } /// @returns the resulting type of applying the given unary operator or an empty pointer if
/// this is not possible.
/// The default implementation does not allow any unary operator.
virtual TypePointer unaryOperatorResult(Token::Value) const { return TypePointer(); }
/// @returns the resulting type of applying the given binary operator or an empty pointer if
/// this is not possible.
/// The default implementation allows comparison operators if a common type exists
virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const
{
return Token::isCompareOp(_operator) ? commonType(shared_from_this(), _other) : TypePointer();
}
virtual bool operator==(Type const& _other) const { return getCategory() == _other.getCategory(); } virtual bool operator==(Type const& _other) const { return getCategory() == _other.getCategory(); }
virtual bool operator!=(Type const& _other) const { return !this->operator ==(_other); } virtual bool operator!=(Type const& _other) const { return !this->operator ==(_other); }
@ -131,18 +135,13 @@ public:
TypePointer getMemberType(std::string const& _name) const { return getMembers().getMemberType(_name); } TypePointer getMemberType(std::string const& _name) const { return getMembers().getMemberType(_name); }
virtual std::string toString() const = 0; virtual std::string toString() const = 0;
virtual u256 literalValue(Literal const&) const virtual u256 literalValue(Literal const*) const
{ {
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Literal value requested " BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Literal value requested "
"for type without literals.")); "for type without literals."));
} }
protected: protected:
virtual TypePointer binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _a, TypePointer const& _b) const
{
return Token::isCompareOp(_operator) ? commonType(_a, _b) : TypePointer();
}
/// Convenience object used when returning an empty member list. /// Convenience object used when returning an empty member list.
static const MemberList EmptyMemberList; static const MemberList EmptyMemberList;
}; };
@ -159,15 +158,12 @@ public:
}; };
virtual Category getCategory() const override { return Category::INTEGER; } virtual Category getCategory() const override { return Category::INTEGER; }
/// @returns the smallest integer type for the given literal or an empty pointer
/// if no type fits.
static std::shared_ptr<IntegerType const> smallestTypeForLiteral(std::string const& _literal);
explicit IntegerType(int _bits, Modifier _modifier = Modifier::UNSIGNED); explicit IntegerType(int _bits, Modifier _modifier = Modifier::UNSIGNED);
virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual bool acceptsUnaryOperator(Token::Value _operator) const override; virtual TypePointer unaryOperatorResult(Token::Value _operator) const override;
virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override;
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
@ -177,22 +173,52 @@ public:
virtual MemberList const& getMembers() const { return isAddress() ? AddressMemberList : EmptyMemberList; } virtual MemberList const& getMembers() const { return isAddress() ? AddressMemberList : EmptyMemberList; }
virtual std::string toString() const override; virtual std::string toString() const override;
virtual u256 literalValue(Literal const& _literal) const override;
int getNumBits() const { return m_bits; } int getNumBits() const { return m_bits; }
bool isHash() const { return m_modifier == Modifier::HASH || m_modifier == Modifier::ADDRESS; } bool isHash() const { return m_modifier == Modifier::HASH || m_modifier == Modifier::ADDRESS; }
bool isAddress() const { return m_modifier == Modifier::ADDRESS; } bool isAddress() const { return m_modifier == Modifier::ADDRESS; }
int isSigned() const { return m_modifier == Modifier::SIGNED; } int isSigned() const { return m_modifier == Modifier::SIGNED; }
protected:
virtual TypePointer binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _this, TypePointer const& _other) const override;
private: private:
int m_bits; int m_bits;
Modifier m_modifier; Modifier m_modifier;
static const MemberList AddressMemberList; static const MemberList AddressMemberList;
}; };
/**
* Integer constants either literals or computed. Example expressions: 2, 2+10, ~10.
* There is one distinct type per value.
*/
class IntegerConstantType: public Type
{
public:
virtual Category getCategory() const override { return Category::INTEGER_CONSTANT; }
static std::shared_ptr<IntegerConstantType const> fromLiteral(std::string const& _literal);
explicit IntegerConstantType(bigint _value): m_value(_value) {}
virtual bool isImplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual TypePointer unaryOperatorResult(Token::Value _operator) const override;
virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override;
virtual bool operator==(Type const& _other) const override;
virtual bool canBeStored() const override { return false; }
virtual bool canLiveOutsideStorage() const override { return false; }
virtual unsigned getSizeOnStack() const override { return 1; }
virtual std::string toString() const override;
virtual u256 literalValue(Literal const* _literal) const override;
/// @returns the smallest integer type that can hold the value or an empty pointer if not possible.
std::shared_ptr<IntegerType const> getIntegerType() const;
private:
bigint m_value;
};
/** /**
* String type with fixed length, up to 32 bytes. * String type with fixed length, up to 32 bytes.
*/ */
@ -214,7 +240,7 @@ public:
virtual bool isValueType() const override { return true; } virtual bool isValueType() const override { return true; }
virtual std::string toString() const override { return "string" + dev::toString(m_bytes); } virtual std::string toString() const override { return "string" + dev::toString(m_bytes); }
virtual u256 literalValue(Literal const& _literal) const override; virtual u256 literalValue(Literal const* _literal) const override;
int getNumBytes() const { return m_bytes; } int getNumBytes() const { return m_bytes; }
@ -231,19 +257,17 @@ public:
BoolType() {} BoolType() {}
virtual Category getCategory() const { return Category::BOOL; } virtual Category getCategory() const { return Category::BOOL; }
virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override; virtual bool isExplicitlyConvertibleTo(Type const& _convertTo) const override;
virtual bool acceptsUnaryOperator(Token::Value _operator) const override virtual TypePointer unaryOperatorResult(Token::Value _operator) const override
{ {
return _operator == Token::NOT || _operator == Token::DELETE; return (_operator == Token::NOT || _operator == Token::DELETE) ? shared_from_this() : TypePointer();
} }
virtual TypePointer binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const override;
virtual unsigned getCalldataEncodedSize() const { return 1; } virtual unsigned getCalldataEncodedSize() const { return 1; }
virtual bool isValueType() const override { return true; } virtual bool isValueType() const override { return true; }
virtual std::string toString() const override { return "bool"; } virtual std::string toString() const override { return "bool"; }
virtual u256 literalValue(Literal const& _literal) const override; virtual u256 literalValue(Literal const* _literal) const override;
protected:
virtual TypePointer binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _this, TypePointer const& _other) const override;
}; };
/** /**
@ -285,9 +309,9 @@ class StructType: public Type
public: public:
virtual Category getCategory() const override { return Category::STRUCT; } virtual Category getCategory() const override { return Category::STRUCT; }
StructType(StructDefinition const& _struct): m_struct(_struct) {} StructType(StructDefinition const& _struct): m_struct(_struct) {}
virtual bool acceptsUnaryOperator(Token::Value _operator) const override virtual TypePointer unaryOperatorResult(Token::Value _operator) const override
{ {
return _operator == Token::DELETE; return _operator == Token::DELETE ? shared_from_this() : TypePointer();
} }
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
@ -378,20 +402,12 @@ public:
virtual Category getCategory() const override { return Category::VOID; } virtual Category getCategory() const override { return Category::VOID; }
VoidType() {} VoidType() {}
virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); }
virtual std::string toString() const override { return "void"; } virtual std::string toString() const override { return "void"; }
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual u256 getStorageSize() const override { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable void type requested.")); } virtual u256 getStorageSize() const override { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable void type requested.")); }
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
virtual unsigned getSizeOnStack() const override { return 0; } virtual unsigned getSizeOnStack() const override { return 0; }
protected:
virtual TypePointer binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _this, TypePointer const& _other) const override
{
(void)_operator;
(void)_this;
(void)_other;
return TypePointer();
}
}; };
/** /**
@ -403,24 +419,15 @@ class TypeType: public Type
public: public:
virtual Category getCategory() const override { return Category::TYPE; } virtual Category getCategory() const override { return Category::TYPE; }
TypeType(TypePointer const& _actualType): m_actualType(_actualType) {} TypeType(TypePointer const& _actualType): m_actualType(_actualType) {}
TypePointer const& getActualType() const { return m_actualType; } TypePointer const& getActualType() const { return m_actualType; }
virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override { return TypePointer(); }
virtual bool operator==(Type const& _other) const override; virtual bool operator==(Type const& _other) const override;
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual u256 getStorageSize() const override { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); } virtual u256 getStorageSize() const override { BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); }
virtual bool canLiveOutsideStorage() const override { return false; } virtual bool canLiveOutsideStorage() const override { return false; }
virtual std::string toString() const override { return "type(" + m_actualType->toString() + ")"; } virtual std::string toString() const override { return "type(" + m_actualType->toString() + ")"; }
protected:
virtual TypePointer binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _this, TypePointer const& _other) const override
{
(void)_operator;
(void)_this;
(void)_other;
return TypePointer();
}
private: private:
TypePointer m_actualType; TypePointer m_actualType;
}; };
@ -437,6 +444,12 @@ public:
virtual Category getCategory() const override { return Category::MAGIC; } virtual Category getCategory() const override { return Category::MAGIC; }
MagicType(Kind _kind); MagicType(Kind _kind);
virtual TypePointer binaryOperatorResult(Token::Value, TypePointer const&) const override
{
return TypePointer();
}
virtual bool operator==(Type const& _other) const; virtual bool operator==(Type const& _other) const;
virtual bool canBeStored() const override { return false; } virtual bool canBeStored() const override { return false; }
virtual bool canLiveOutsideStorage() const override { return true; } virtual bool canLiveOutsideStorage() const override { return true; }
@ -445,15 +458,6 @@ public:
virtual std::string toString() const override; virtual std::string toString() const override;
protected:
virtual TypePointer binaryOperatorResultImpl(Token::Value _operator, TypePointer const& _this, TypePointer const& _other) const override
{
(void)_operator;
(void)_this;
(void)_other;
return TypePointer();
}
private: private:
Kind m_kind; Kind m_kind;