-
Notifications
You must be signed in to change notification settings - Fork 6.1k
/
Copy pathConstantEvaluator.cpp
444 lines (396 loc) · 12.7 KB
/
ConstantEvaluator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <[email protected]>
* @date 2015
* Evaluator for types of constant expressions.
*/
#include <libsolidity/analysis/ConstantEvaluator.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/ast/TypeProvider.h>
#include <liblangutil/ErrorReporter.h>
#include <libsolutil/Keccak256.h>
#include <libsolutil/StringUtils.h>
#include <libsolutil/FixedHash.h>
#include <limits>
using namespace solidity;
using namespace solidity::frontend;
using namespace solidity::langutil;
using TypedRational = ConstantEvaluator::TypedRational;
namespace
{
/// Check whether (_base ** _exp) fits into 4096 bits.
bool fitsPrecisionExp(bigint const& _base, bigint const& _exp)
{
if (_base == 0)
return true;
solAssert(_base > 0, "");
std::size_t const bitsMax = 4096;
std::size_t mostSignificantBaseBit = static_cast<std::size_t>(boost::multiprecision::msb(_base));
if (mostSignificantBaseBit == 0) // _base == 1
return true;
if (mostSignificantBaseBit > bitsMax) // _base >= 2 ^ 4096
return false;
bigint bitsNeeded = _exp * (mostSignificantBaseBit + 1);
return bitsNeeded <= bitsMax;
}
/// Checks whether _mantissa * (2 ** _expBase10) fits into 4096 bits.
bool fitsPrecisionBase2(bigint const& _mantissa, uint32_t _expBase2)
{
return fitsPrecisionBaseX(_mantissa, 1.0, _expBase2);
}
}
std::optional<rational> ConstantEvaluator::evaluateBinaryOperator(Token _operator, rational const& _left, rational const& _right)
{
bool fractional = _left.denominator() != 1 || _right.denominator() != 1;
switch (_operator)
{
//bit operations will only be enabled for integers and fixed types that resemble integers
case Token::BitOr:
if (fractional)
return std::nullopt;
else
return _left.numerator() | _right.numerator();
case Token::BitXor:
if (fractional)
return std::nullopt;
else
return _left.numerator() ^ _right.numerator();
case Token::BitAnd:
if (fractional)
return std::nullopt;
else
return _left.numerator() & _right.numerator();
case Token::Add: return _left + _right;
case Token::Sub: return _left - _right;
case Token::Mul: return _left * _right;
case Token::Div:
if (_right == rational(0))
return std::nullopt;
else
return _left / _right;
case Token::Mod:
if (_right == rational(0))
return std::nullopt;
else if (fractional)
{
rational tempValue = _left / _right;
return _left - (tempValue.numerator() / tempValue.denominator()) * _right;
}
else
return _left.numerator() % _right.numerator();
break;
case Token::Exp:
{
if (_right.denominator() != 1)
return std::nullopt;
bigint const& exp = _right.numerator();
// x ** 0 = 1
// for 0, 1 and -1 the size of the exponent doesn't have to be restricted
if (exp == 0)
return 1;
else if (_left == 0 || _left == 1)
return _left;
else if (_left == -1)
{
bigint isOdd = abs(exp) & bigint(1);
return 1 - 2 * isOdd.convert_to<int>();
}
else
{
if (abs(exp) > std::numeric_limits<uint32_t>::max())
return std::nullopt; // This will need too much memory to represent.
uint32_t absExp = bigint(abs(exp)).convert_to<uint32_t>();
if (!fitsPrecisionExp(abs(_left.numerator()), absExp) || !fitsPrecisionExp(abs(_left.denominator()), absExp))
return std::nullopt;
static auto const optimizedPow = [](bigint const& _base, uint32_t _exponent) -> bigint {
if (_base == 1)
return 1;
else if (_base == -1)
return 1 - 2 * static_cast<int>(_exponent & 1);
else
return boost::multiprecision::pow(_base, _exponent);
};
bigint numerator = optimizedPow(_left.numerator(), absExp);
bigint denominator = optimizedPow(_left.denominator(), absExp);
if (exp >= 0)
return makeRational(numerator, denominator);
else
// invert
return makeRational(denominator, numerator);
}
break;
}
case Token::SHL:
{
if (fractional)
return std::nullopt;
else if (_right < 0)
return std::nullopt;
else if (_right > std::numeric_limits<uint32_t>::max())
return std::nullopt;
if (_left.numerator() == 0)
return 0;
else
{
uint32_t exponent = _right.numerator().convert_to<uint32_t>();
if (!fitsPrecisionBase2(abs(_left.numerator()), exponent))
return std::nullopt;
return _left.numerator() * boost::multiprecision::pow(bigint(2), exponent);
}
break;
}
// NOTE: we're using >> (SAR) to denote right shifting. The type of the LValue
// determines the resulting type and the type of shift (SAR or SHR).
case Token::SAR:
{
if (fractional)
return std::nullopt;
else if (_right < 0)
return std::nullopt;
else if (_right > std::numeric_limits<uint32_t>::max())
return std::nullopt;
if (_left.numerator() == 0)
return 0;
else
{
uint32_t exponent = _right.numerator().convert_to<uint32_t>();
if (exponent > boost::multiprecision::msb(boost::multiprecision::abs(_left.numerator())))
return _left.numerator() < 0 ? -1 : 0;
else
{
if (_left.numerator() < 0)
// Add 1 to the negative value before dividing to get a result that is strictly too large,
// then subtract 1 afterwards to round towards negative infinity.
// This is the same algorithm as used in ExpressionCompiler::appendShiftOperatorCode(...).
// To see this note that for negative x, xor(x,all_ones) = (-x-1) and
// therefore xor(div(xor(x,all_ones), exp(2, shift_amount)), all_ones) is
// -(-x - 1) / 2^shift_amount - 1, which is the same as
// (x + 1) / 2^shift_amount - 1.
return rational((_left.numerator() + 1) / boost::multiprecision::pow(bigint(2), exponent) - bigint(1), 1);
else
return rational(_left.numerator() / boost::multiprecision::pow(bigint(2), exponent), 1);
}
}
break;
}
default:
return std::nullopt;
}
}
std::optional<rational> ConstantEvaluator::evaluateUnaryOperator(Token _operator, rational const& _input)
{
switch (_operator)
{
case Token::BitNot:
if (_input.denominator() != 1)
return std::nullopt;
else
return ~_input.numerator();
case Token::Sub:
return -_input;
default:
return std::nullopt;
}
}
namespace
{
std::optional<TypedRational> convertType(rational const& _value, Type const& _type)
{
if (_type.category() == Type::Category::RationalNumber)
return TypedRational{TypeProvider::rationalNumber(_value), _value};
else if (auto const* integerType = dynamic_cast<IntegerType const*>(&_type))
{
if (_value > integerType->maxValue() || _value < integerType->minValue())
return std::nullopt;
else
return TypedRational{&_type, _value.numerator() / _value.denominator()};
}
else
return std::nullopt;
}
std::optional<TypedRational> convertType(std::optional<TypedRational> const& _value, Type const& _type)
{
return _value ? convertType(_value->value, _type) : std::nullopt;
}
std::optional<TypedRational> constantToTypedValue(Type const& _type)
{
if (_type.category() == Type::Category::RationalNumber)
return TypedRational{&_type, dynamic_cast<RationalNumberType const&>(_type).value()};
else
return std::nullopt;
}
}
std::optional<TypedRational> ConstantEvaluator::evaluate(
langutil::ErrorReporter& _errorReporter,
Expression const& _expr
)
{
return ConstantEvaluator{_errorReporter}.evaluate(_expr);
}
std::optional<TypedRational> ConstantEvaluator::tryEvaluate(Expression const& _expr)
{
ErrorList errorList;
ErrorReporter errorReporter(errorList);
try
{
return ConstantEvaluator{errorReporter}.evaluate(_expr);
}
catch (FatalError const&)
{
return std::nullopt;
}
}
std::optional<TypedRational> ConstantEvaluator::evaluate(ASTNode const& _node)
{
if (!m_values.count(&_node))
{
if (auto const* varDecl = dynamic_cast<VariableDeclaration const*>(&_node))
{
solAssert(varDecl->isConstant(), "");
// In some circumstances, we do not yet have a type for the variable.
if (!varDecl->value() || !varDecl->type())
m_values[&_node] = std::nullopt;
else
{
m_depth++;
if (m_depth > 32)
m_errorReporter.fatalTypeError(
5210_error,
varDecl->location(),
"Cyclic constant definition (or maximum recursion depth exhausted)."
);
m_values[&_node] = convertType(evaluate(*varDecl->value()), *varDecl->type());
m_depth--;
}
}
else if (auto const* expression = dynamic_cast<Expression const*>(&_node))
{
expression->accept(*this);
if (!m_values.count(&_node))
m_values[&_node] = std::nullopt;
}
}
return m_values.at(&_node);
}
void ConstantEvaluator::endVisit(UnaryOperation const& _operation)
{
std::optional<TypedRational> value = evaluate(_operation.subExpression());
if (!value)
return;
Type const* resultType = value->type->unaryOperatorResult(_operation.getOperator());
if (!resultType)
return;
value = convertType(value, *resultType);
if (!value)
return;
if (std::optional<rational> result = evaluateUnaryOperator(_operation.getOperator(), value->value))
{
std::optional<TypedRational> convertedValue = convertType(*result, *resultType);
if (!convertedValue)
m_errorReporter.fatalTypeError(
3667_error,
_operation.location(),
"Arithmetic error when computing constant value."
);
m_values[&_operation] = convertedValue;
}
}
void ConstantEvaluator::endVisit(BinaryOperation const& _operation)
{
std::optional<TypedRational> left = evaluate(_operation.leftExpression());
std::optional<TypedRational> right = evaluate(_operation.rightExpression());
if (!left || !right)
return;
// If this is implemented in the future: Comparison operators have a "binaryOperatorResult"
// that is non-bool, but the result has to be bool.
if (TokenTraits::isCompareOp(_operation.getOperator()))
return;
Type const* resultType = left->type->binaryOperatorResult(_operation.getOperator(), right->type);
if (!resultType)
{
m_errorReporter.fatalTypeError(
6020_error,
_operation.location(),
"Operator " +
std::string(TokenTraits::toString(_operation.getOperator())) +
" not compatible with types " +
left->type->toString() +
" and " +
right->type->toString()
);
return;
}
left = convertType(left, *resultType);
right = convertType(right, *resultType);
if (!left || !right)
return;
if (std::optional<rational> value = evaluateBinaryOperator(_operation.getOperator(), left->value, right->value))
{
std::optional<TypedRational> convertedValue = convertType(*value, *resultType);
if (!convertedValue)
m_errorReporter.fatalTypeError(
2643_error,
_operation.location(),
"Arithmetic error when computing constant value."
);
m_values[&_operation] = convertedValue;
}
}
void ConstantEvaluator::endVisit(Literal const& _literal)
{
if (Type const* literalType = TypeProvider::forLiteral(_literal))
m_values[&_literal] = constantToTypedValue(*literalType);
}
void ConstantEvaluator::endVisit(Identifier const& _identifier)
{
VariableDeclaration const* variableDeclaration = dynamic_cast<VariableDeclaration const*>(_identifier.annotation().referencedDeclaration);
if (variableDeclaration && variableDeclaration->isConstant())
m_values[&_identifier] = evaluate(*variableDeclaration);
}
void ConstantEvaluator::endVisit(TupleExpression const& _tuple)
{
if (!_tuple.isInlineArray() && _tuple.components().size() == 1)
m_values[&_tuple] = evaluate(*_tuple.components().front());
}
void ConstantEvaluator::endVisit(FunctionCall const& _functionCall)
{
using util::keccak256;
using util::h256;
auto const* builtinFunction = dynamic_cast<MagicVariableDeclaration const*>(ASTNode::referencedDeclaration(_functionCall.expression()));
if (!builtinFunction)
return;
auto const* functionType = builtinFunction->functionType(true);
solAssert(functionType);
switch (functionType->kind())
{
case FunctionType::Kind::ERC7201:
{
solAssert(_functionCall.arguments().size() == 1);
auto const* argument = dynamic_cast<Literal const*>(_functionCall.arguments()[0].get());
solAssert(argument);
ASTString argStringLiteral = argument->valueWithoutUnderscores();
auto value =
u256(keccak256(h256(u256(keccak256(argStringLiteral)) - 1))) &
u256(~0xff)
;
solAssert(functionType->returnParameterTypes().size() == 1);
m_values[&_functionCall] = TypedRational{functionType->returnParameterTypes()[0], rational{value}};
break;
}
default:
break;
}
}