-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathTypes.cpp
4032 lines (3588 loc) · 113 KB
/
Types.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 2014
* Solidity data types
*/
#include <libsolidity/ast/Types.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/ast/TypeProvider.h>
#include <libsolidity/analysis/ConstantEvaluator.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/FunctionSelector.h>
#include <libsolutil/Keccak256.h>
#include <libsolutil/UTF8.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/tail.hpp>
#include <range/v3/view/transform.hpp>
#include <limits>
#include <unordered_set>
#include <utility>
using namespace std;
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::frontend;
namespace
{
/// Checks whether _mantissa * (10 ** _expBase10) fits into 4096 bits.
bool fitsPrecisionBase10(bigint const& _mantissa, uint32_t _expBase10)
{
double const log2Of10AwayFromZero = 3.3219280948873624;
return fitsPrecisionBaseX(_mantissa, log2Of10AwayFromZero, _expBase10);
}
/// Checks whether _value fits into IntegerType _type.
BoolResult fitsIntegerType(bigint const& _value, IntegerType const& _type)
{
if (_value < 0 && !_type.isSigned())
return BoolResult::err("Cannot implicitly convert signed literal to unsigned type.");
if (_type.minValue() > _value || _value > _type.maxValue())
return BoolResult::err("Literal is too large to fit in " + _type.toString(false) + ".");
return true;
}
/// Checks whether _value fits into _bits bits when having 1 bit as the sign bit
/// if _signed is true.
bool fitsIntoBits(bigint const& _value, unsigned _bits, bool _signed)
{
return fitsIntegerType(
_value,
*TypeProvider::integer(
_bits,
_signed ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned
)
);
}
util::Result<TypePointers> transformParametersToExternal(TypePointers const& _parameters, bool _inLibrary)
{
TypePointers transformed;
for (auto const& type: _parameters)
{
if (!type)
return util::Result<TypePointers>::err("Type information not present.");
else if (Type const* ext = type->interfaceType(_inLibrary).get())
transformed.push_back(ext);
else
return util::Result<TypePointers>::err("Parameter should have external type.");
}
return transformed;
}
}
MemberList::Member::Member(Declaration const* _declaration, Type const* _type):
Member(_declaration, _type, _declaration->name())
{}
MemberList::Member::Member(Declaration const* _declaration, Type const* _type, string _name):
name(move(_name)),
type(_type),
declaration(_declaration)
{
}
void Type::clearCache() const
{
m_members.clear();
m_stackItems.reset();
m_stackSize.reset();
}
void StorageOffsets::computeOffsets(TypePointers const& _types)
{
bigint slotOffset = 0;
unsigned byteOffset = 0;
map<size_t, pair<u256, unsigned>> offsets;
for (size_t i = 0; i < _types.size(); ++i)
{
Type const* type = _types[i];
if (!type->canBeStored())
continue;
if (byteOffset + type->storageBytes() > 32)
{
// would overflow, go to next slot
++slotOffset;
byteOffset = 0;
}
solAssert(slotOffset < bigint(1) << 256 ,"Object too large for storage.");
offsets[i] = make_pair(u256(slotOffset), byteOffset);
solAssert(type->storageSize() >= 1, "Invalid storage size.");
if (type->storageSize() == 1 && byteOffset + type->storageBytes() <= 32)
byteOffset += type->storageBytes();
else
{
slotOffset += type->storageSize();
byteOffset = 0;
}
}
if (byteOffset > 0)
++slotOffset;
solAssert(slotOffset < bigint(1) << 256, "Object too large for storage.");
m_storageSize = u256(slotOffset);
swap(m_offsets, offsets);
}
pair<u256, unsigned> const* StorageOffsets::offset(size_t _index) const
{
if (m_offsets.count(_index))
return &m_offsets.at(_index);
else
return nullptr;
}
void MemberList::combine(MemberList const & _other)
{
m_memberTypes += _other.m_memberTypes;
}
pair<u256, unsigned> const* MemberList::memberStorageOffset(string const& _name) const
{
StorageOffsets const& offsets = storageOffsets();
for (auto&& [index, member]: m_memberTypes | ranges::views::enumerate)
if (member.name == _name)
return offsets.offset(index);
return nullptr;
}
u256 const& MemberList::storageSize() const
{
return storageOffsets().storageSize();
}
StorageOffsets const& MemberList::storageOffsets() const {
return m_storageOffsets.init([&]{
TypePointers memberTypes;
memberTypes.reserve(m_memberTypes.size());
for (auto const& member: m_memberTypes)
memberTypes.push_back(member.type);
StorageOffsets storageOffsets;
storageOffsets.computeOffsets(memberTypes);
return storageOffsets;
});
}
/// Helper functions for type identifier
namespace
{
string parenthesizeIdentifier(string const& _internal)
{
return "(" + _internal + ")";
}
template <class Range>
string identifierList(Range const&& _list)
{
return parenthesizeIdentifier(boost::algorithm::join(_list, ","));
}
string richIdentifier(Type const* _type)
{
return _type ? _type->richIdentifier() : "";
}
string identifierList(vector<Type const*> const& _list)
{
return identifierList(_list | ranges::views::transform(richIdentifier));
}
string identifierList(Type const* _type)
{
return parenthesizeIdentifier(richIdentifier(_type));
}
string identifierList(Type const* _type1, Type const* _type2)
{
TypePointers list;
list.push_back(_type1);
list.push_back(_type2);
return identifierList(list);
}
string parenthesizeUserIdentifier(string const& _internal)
{
return parenthesizeIdentifier(_internal);
}
}
string Type::escapeIdentifier(string const& _identifier)
{
string ret = _identifier;
// FIXME: should be _$$$_
boost::algorithm::replace_all(ret, "$", "$$$");
boost::algorithm::replace_all(ret, ",", "_$_");
boost::algorithm::replace_all(ret, "(", "$_");
boost::algorithm::replace_all(ret, ")", "_$");
return ret;
}
string Type::identifier() const
{
string ret = escapeIdentifier(richIdentifier());
solAssert(ret.find_first_of("0123456789") != 0, "Identifier cannot start with a number.");
solAssert(
ret.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMONPQRSTUVWXYZ_$") == string::npos,
"Identifier contains invalid characters."
);
return ret;
}
Type const* Type::commonType(Type const* _a, Type const* _b)
{
if (!_a || !_b)
return nullptr;
else if (_a->mobileType() && _b->isImplicitlyConvertibleTo(*_a->mobileType()))
return _a->mobileType();
else if (_b->mobileType() && _a->isImplicitlyConvertibleTo(*_b->mobileType()))
return _b->mobileType();
else
return nullptr;
}
MemberList const& Type::members(ASTNode const* _currentScope) const
{
if (!m_members[_currentScope])
{
solAssert(
_currentScope == nullptr ||
dynamic_cast<SourceUnit const*>(_currentScope) ||
dynamic_cast<ContractDefinition const*>(_currentScope),
"");
MemberList::MemberMap members = nativeMembers(_currentScope);
if (_currentScope)
members += boundFunctions(*this, *_currentScope);
m_members[_currentScope] = make_unique<MemberList>(move(members));
}
return *m_members[_currentScope];
}
Type const* Type::fullEncodingType(bool _inLibraryCall, bool _encoderV2, bool) const
{
Type const* encodingType = mobileType();
if (encodingType)
encodingType = encodingType->interfaceType(_inLibraryCall);
if (encodingType)
encodingType = encodingType->encodingType();
// Structs are fine in the following circumstances:
// - ABIv2 or,
// - storage struct for a library
if (_inLibraryCall && encodingType && encodingType->dataStoredIn(DataLocation::Storage))
return encodingType;
Type const* baseType = encodingType;
while (auto const* arrayType = dynamic_cast<ArrayType const*>(baseType))
{
baseType = arrayType->baseType();
auto const* baseArrayType = dynamic_cast<ArrayType const*>(baseType);
if (!_encoderV2 && baseArrayType && baseArrayType->isDynamicallySized())
return nullptr;
}
if (!_encoderV2 && dynamic_cast<StructType const*>(baseType))
return nullptr;
return encodingType;
}
MemberList::MemberMap Type::boundFunctions(Type const& _type, ASTNode const& _scope)
{
vector<UsingForDirective const*> usingForDirectives;
if (auto const* sourceUnit = dynamic_cast<SourceUnit const*>(&_scope))
usingForDirectives += ASTNode::filteredNodes<UsingForDirective>(sourceUnit->nodes());
else if (auto const* contract = dynamic_cast<ContractDefinition const*>(&_scope))
usingForDirectives +=
contract->usingForDirectives() +
ASTNode::filteredNodes<UsingForDirective>(contract->sourceUnit().nodes());
else
solAssert(false, "");
// Normalise data location of type.
DataLocation typeLocation = DataLocation::Storage;
if (auto refType = dynamic_cast<ReferenceType const*>(&_type))
typeLocation = refType->location();
set<Declaration const*> seenFunctions;
MemberList::MemberMap members;
for (UsingForDirective const* ufd: usingForDirectives)
{
// Convert both types to pointers for comparison to see if the `using for`
// directive applies.
// Further down, we check more detailed for each function if `_type` is
// convertible to the function parameter type.
if (ufd->typeName() &&
*TypeProvider::withLocationIfReference(typeLocation, &_type, true) !=
*TypeProvider::withLocationIfReference(
typeLocation,
ufd->typeName()->annotation().type,
true
)
)
continue;
auto const& library = dynamic_cast<ContractDefinition const&>(
*ufd->libraryName().annotation().referencedDeclaration
);
for (FunctionDefinition const* function: library.definedFunctions())
{
if (!function->isOrdinary() || !function->isVisibleAsLibraryMember() || seenFunctions.count(function))
continue;
seenFunctions.insert(function);
if (function->parameters().empty())
continue;
FunctionTypePointer fun =
dynamic_cast<FunctionType const&>(*function->typeViaContractName()).asBoundFunction();
if (_type.isImplicitlyConvertibleTo(*fun->selfType()))
members.emplace_back(function, fun);
}
}
return members;
}
AddressType::AddressType(StateMutability _stateMutability):
m_stateMutability(_stateMutability)
{
solAssert(m_stateMutability == StateMutability::Payable || m_stateMutability == StateMutability::NonPayable, "");
}
string AddressType::richIdentifier() const
{
if (m_stateMutability == StateMutability::Payable)
return "t_address_payable";
else
return "t_address";
}
BoolResult AddressType::isImplicitlyConvertibleTo(Type const& _other) const
{
if (_other.category() != category())
return false;
AddressType const& other = dynamic_cast<AddressType const&>(_other);
return other.m_stateMutability <= m_stateMutability;
}
BoolResult AddressType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
if ((_convertTo.category() == category()) || isImplicitlyConvertibleTo(_convertTo))
return true;
else if (auto const* contractType = dynamic_cast<ContractType const*>(&_convertTo))
return (m_stateMutability >= StateMutability::Payable) || !contractType->isPayable();
else if (m_stateMutability == StateMutability::NonPayable)
{
if (auto integerType = dynamic_cast<IntegerType const*>(&_convertTo))
return (!integerType->isSigned() && integerType->numBits() == 160);
else if (auto fixedBytesType = dynamic_cast<FixedBytesType const*>(&_convertTo))
return (fixedBytesType->numBytes() == 20);
}
return false;
}
string AddressType::toString(bool) const
{
if (m_stateMutability == StateMutability::Payable)
return "address payable";
else
return "address";
}
string AddressType::canonicalName() const
{
return "address";
}
u256 AddressType::literalValue(Literal const* _literal) const
{
solAssert(_literal, "");
solAssert(_literal->value().substr(0, 2) == "0x", "");
return u256(_literal->valueWithoutUnderscores());
}
TypeResult AddressType::unaryOperatorResult(Token _operator) const
{
return _operator == Token::Delete ? TypeProvider::emptyTuple() : nullptr;
}
TypeResult AddressType::binaryOperatorResult(Token _operator, Type const* _other) const
{
if (!TokenTraits::isCompareOp(_operator))
return TypeResult::err("Arithmetic operations on addresses are not supported. Convert to integer first before using them.");
return Type::commonType(this, _other);
}
bool AddressType::operator==(Type const& _other) const
{
if (_other.category() != category())
return false;
AddressType const& other = dynamic_cast<AddressType const&>(_other);
return other.m_stateMutability == m_stateMutability;
}
MemberList::MemberMap AddressType::nativeMembers(ASTNode const*) const
{
MemberList::MemberMap members = {
{"balance", TypeProvider::uint256()},
{"code", TypeProvider::array(DataLocation::Memory)},
{"codehash", TypeProvider::fixedBytes(32)},
{"call", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareCall, false, StateMutability::Payable)},
{"callcode", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareCallCode, false, StateMutability::Payable)},
{"delegatecall", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareDelegateCall, false, StateMutability::NonPayable)},
{"staticcall", TypeProvider::function(strings{"bytes memory"}, strings{"bool", "bytes memory"}, FunctionType::Kind::BareStaticCall, false, StateMutability::View)}
};
if (m_stateMutability == StateMutability::Payable)
{
members.emplace_back(MemberList::Member{"send", TypeProvider::function(strings{"uint"}, strings{"bool"}, FunctionType::Kind::Send, false, StateMutability::NonPayable)});
members.emplace_back(MemberList::Member{"transfer", TypeProvider::function(strings{"uint"}, strings(), FunctionType::Kind::Transfer, false, StateMutability::NonPayable)});
}
return members;
}
namespace
{
bool isValidShiftAndAmountType(Token _operator, Type const& _shiftAmountType)
{
// Disable >>> here.
if (_operator == Token::SHR)
return false;
else if (IntegerType const* otherInt = dynamic_cast<decltype(otherInt)>(&_shiftAmountType))
return !otherInt->isSigned();
else if (RationalNumberType const* otherRat = dynamic_cast<decltype(otherRat)>(&_shiftAmountType))
return !otherRat->isFractional() && otherRat->integerType() && !otherRat->integerType()->isSigned();
else
return false;
}
}
IntegerType::IntegerType(unsigned _bits, IntegerType::Modifier _modifier):
m_bits(_bits), m_modifier(_modifier)
{
solAssert(
m_bits > 0 && m_bits <= 256 && m_bits % 8 == 0,
"Invalid bit number for integer type: " + util::toString(m_bits)
);
}
string IntegerType::richIdentifier() const
{
return "t_" + string(isSigned() ? "" : "u") + "int" + to_string(numBits());
}
BoolResult IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const
{
if (_convertTo.category() == category())
{
IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo);
// disallowing unsigned to signed conversion of different bits
if (isSigned() != convertTo.isSigned())
return false;
else if (convertTo.m_bits < m_bits)
return false;
else
return true;
}
else if (_convertTo.category() == Category::FixedPoint)
{
FixedPointType const& convertTo = dynamic_cast<FixedPointType const&>(_convertTo);
return maxValue() <= convertTo.maxIntegerValue() && minValue() >= convertTo.minIntegerValue();
}
else
return false;
}
BoolResult IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
if (isImplicitlyConvertibleTo(_convertTo))
return true;
else if (auto integerType = dynamic_cast<IntegerType const*>(&_convertTo))
return (numBits() == integerType->numBits()) || (isSigned() == integerType->isSigned());
else if (auto addressType = dynamic_cast<AddressType const*>(&_convertTo))
return
(addressType->stateMutability() != StateMutability::Payable) &&
!isSigned() &&
(numBits() == 160);
else if (auto fixedBytesType = dynamic_cast<FixedBytesType const*>(&_convertTo))
return (!isSigned() && (numBits() == fixedBytesType->numBytes() * 8));
else if (dynamic_cast<EnumType const*>(&_convertTo))
return true;
else if (auto fixedPointType = dynamic_cast<FixedPointType const*>(&_convertTo))
return (isSigned() == fixedPointType->isSigned()) && (numBits() == fixedPointType->numBits());
return false;
}
TypeResult IntegerType::unaryOperatorResult(Token _operator) const
{
// "delete" is ok for all integer types
if (_operator == Token::Delete)
return TypeResult{TypeProvider::emptyTuple()};
// unary negation only on signed types
else if (_operator == Token::Sub)
return isSigned() ? TypeResult{this} : TypeResult::err("Unary negation is only allowed for signed integers.");
else if (_operator == Token::Inc || _operator == Token::Dec || _operator == Token::BitNot)
return TypeResult{this};
else
return TypeResult::err("");
}
bool IntegerType::operator==(Type const& _other) const
{
if (_other.category() != category())
return false;
IntegerType const& other = dynamic_cast<IntegerType const&>(_other);
return other.m_bits == m_bits && other.m_modifier == m_modifier;
}
string IntegerType::toString(bool) const
{
string prefix = isSigned() ? "int" : "uint";
return prefix + util::toString(m_bits);
}
u256 IntegerType::min() const
{
if (isSigned())
return s2u(s256(minValue()));
else
return u256(minValue());
}
u256 IntegerType::max() const
{
if (isSigned())
return s2u(s256(maxValue()));
else
return u256(maxValue());
}
bigint IntegerType::minValue() const
{
if (isSigned())
return -(bigint(1) << (m_bits - 1));
else
return bigint(0);
}
bigint IntegerType::maxValue() const
{
if (isSigned())
return (bigint(1) << (m_bits - 1)) - 1;
else
return (bigint(1) << m_bits) - 1;
}
TypeResult IntegerType::binaryOperatorResult(Token _operator, Type const* _other) const
{
if (
_other->category() != Category::RationalNumber &&
_other->category() != Category::FixedPoint &&
_other->category() != category()
)
return nullptr;
if (TokenTraits::isShiftOp(_operator))
{
// Shifts are not symmetric with respect to the type
if (isValidShiftAndAmountType(_operator, *_other))
return this;
else
return nullptr;
}
else if (Token::Exp == _operator)
{
if (auto otherIntType = dynamic_cast<IntegerType const*>(_other))
{
if (otherIntType->isSigned())
return TypeResult::err("Exponentiation power is not allowed to be a signed integer type.");
}
else if (dynamic_cast<FixedPointType const*>(_other))
return nullptr;
else if (auto rationalNumberType = dynamic_cast<RationalNumberType const*>(_other))
{
if (rationalNumberType->isFractional())
return TypeResult::err("Exponent is fractional.");
if (!rationalNumberType->integerType())
return TypeResult::err("Exponent too large.");
if (rationalNumberType->isNegative())
return TypeResult::err("Exponentiation power is not allowed to be a negative integer literal.");
}
return this;
}
auto commonType = Type::commonType(this, _other); //might be an integer or fixed point
if (!commonType)
return nullptr;
// All integer types can be compared
if (TokenTraits::isCompareOp(_operator))
return commonType;
if (TokenTraits::isBooleanOp(_operator))
return nullptr;
return commonType;
}
FixedPointType::FixedPointType(unsigned _totalBits, unsigned _fractionalDigits, FixedPointType::Modifier _modifier):
m_totalBits(_totalBits), m_fractionalDigits(_fractionalDigits), m_modifier(_modifier)
{
solAssert(
8 <= m_totalBits && m_totalBits <= 256 && m_totalBits % 8 == 0 && m_fractionalDigits <= 80,
"Invalid bit number(s) for fixed type: " +
util::toString(_totalBits) + "x" + util::toString(_fractionalDigits)
);
}
string FixedPointType::richIdentifier() const
{
return "t_" + string(isSigned() ? "" : "u") + "fixed" + to_string(m_totalBits) + "x" + to_string(m_fractionalDigits);
}
BoolResult FixedPointType::isImplicitlyConvertibleTo(Type const& _convertTo) const
{
if (_convertTo.category() == category())
{
FixedPointType const& convertTo = dynamic_cast<FixedPointType const&>(_convertTo);
if (convertTo.fractionalDigits() < m_fractionalDigits)
return BoolResult::err("Too many fractional digits.");
if (convertTo.numBits() < m_totalBits)
return false;
else
return convertTo.maxIntegerValue() >= maxIntegerValue() && convertTo.minIntegerValue() <= minIntegerValue();
}
return false;
}
BoolResult FixedPointType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
return _convertTo.category() == category() || _convertTo.category() == Category::Integer;
}
TypeResult FixedPointType::unaryOperatorResult(Token _operator) const
{
switch (_operator)
{
case Token::Delete:
// "delete" is ok for all fixed types
return TypeResult{TypeProvider::emptyTuple()};
case Token::Add:
case Token::Sub:
case Token::Inc:
case Token::Dec:
// for fixed, we allow +, -, ++ and --
return this;
default:
return nullptr;
}
}
bool FixedPointType::operator==(Type const& _other) const
{
if (_other.category() != category())
return false;
FixedPointType const& other = dynamic_cast<FixedPointType const&>(_other);
return other.m_totalBits == m_totalBits && other.m_fractionalDigits == m_fractionalDigits && other.m_modifier == m_modifier;
}
string FixedPointType::toString(bool) const
{
string prefix = isSigned() ? "fixed" : "ufixed";
return prefix + util::toString(m_totalBits) + "x" + util::toString(m_fractionalDigits);
}
bigint FixedPointType::maxIntegerValue() const
{
bigint maxValue = (bigint(1) << (m_totalBits - (isSigned() ? 1 : 0))) - 1;
return maxValue / boost::multiprecision::pow(bigint(10), m_fractionalDigits);
}
bigint FixedPointType::minIntegerValue() const
{
if (isSigned())
{
bigint minValue = -(bigint(1) << (m_totalBits - (isSigned() ? 1 : 0)));
return minValue / boost::multiprecision::pow(bigint(10), m_fractionalDigits);
}
else
return bigint(0);
}
TypeResult FixedPointType::binaryOperatorResult(Token _operator, Type const* _other) const
{
auto commonType = Type::commonType(this, _other);
if (!commonType)
return nullptr;
// All fixed types can be compared
if (TokenTraits::isCompareOp(_operator))
return commonType;
if (TokenTraits::isBitOp(_operator) || TokenTraits::isBooleanOp(_operator) || _operator == Token::Exp)
return nullptr;
return commonType;
}
IntegerType const* FixedPointType::asIntegerType() const
{
return TypeProvider::integer(numBits(), isSigned() ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned);
}
tuple<bool, rational> RationalNumberType::parseRational(string const& _value)
{
rational value;
try
{
auto radixPoint = find(_value.begin(), _value.end(), '.');
if (radixPoint != _value.end())
{
if (
!all_of(radixPoint + 1, _value.end(), ::isdigit) ||
!all_of(_value.begin(), radixPoint, ::isdigit)
)
return make_tuple(false, rational(0));
// Only decimal notation allowed here, leading zeros would switch to octal.
auto fractionalBegin = find_if_not(
radixPoint + 1,
_value.end(),
[](char const& a) { return a == '0'; }
);
rational numerator;
rational denominator(1);
denominator = bigint(string(fractionalBegin, _value.end()));
denominator /= boost::multiprecision::pow(
bigint(10),
static_cast<unsigned>(distance(radixPoint + 1, _value.end()))
);
numerator = bigint(string(_value.begin(), radixPoint));
value = numerator + denominator;
}
else
value = bigint(_value);
return make_tuple(true, value);
}
catch (...)
{
return make_tuple(false, rational(0));
}
}
tuple<bool, rational> RationalNumberType::isValidLiteral(Literal const& _literal)
{
rational value;
try
{
ASTString valueString = _literal.valueWithoutUnderscores();
auto expPoint = find(valueString.begin(), valueString.end(), 'e');
if (expPoint == valueString.end())
expPoint = find(valueString.begin(), valueString.end(), 'E');
if (boost::starts_with(valueString, "0x"))
{
// process as hex
value = bigint(valueString);
}
else if (expPoint != valueString.end())
{
// Parse mantissa and exponent. Checks numeric limit.
tuple<bool, rational> mantissa = parseRational(string(valueString.begin(), expPoint));
if (!get<0>(mantissa))
return make_tuple(false, rational(0));
value = get<1>(mantissa);
// 0E... is always zero.
if (value == 0)
return make_tuple(true, rational(0));
bigint exp = bigint(string(expPoint + 1, valueString.end()));
if (exp > numeric_limits<int32_t>::max() || exp < numeric_limits<int32_t>::min())
return make_tuple(false, rational(0));
uint32_t expAbs = bigint(abs(exp)).convert_to<uint32_t>();
if (exp < 0)
{
if (!fitsPrecisionBase10(abs(value.denominator()), expAbs))
return make_tuple(false, rational(0));
value /= boost::multiprecision::pow(
bigint(10),
expAbs
);
}
else if (exp > 0)
{
if (!fitsPrecisionBase10(abs(value.numerator()), expAbs))
return make_tuple(false, rational(0));
value *= boost::multiprecision::pow(
bigint(10),
expAbs
);
}
}
else
{
// parse as rational number
tuple<bool, rational> tmp = parseRational(valueString);
if (!get<0>(tmp))
return tmp;
value = get<1>(tmp);
}
}
catch (...)
{
return make_tuple(false, rational(0));
}
switch (_literal.subDenomination())
{
case Literal::SubDenomination::None:
case Literal::SubDenomination::Wei:
case Literal::SubDenomination::Second:
break;
case Literal::SubDenomination::Gwei:
value *= bigint("1000000000");
break;
case Literal::SubDenomination::Ether:
value *= bigint("1000000000000000000");
break;
case Literal::SubDenomination::Minute:
value *= bigint("60");
break;
case Literal::SubDenomination::Hour:
value *= bigint("3600");
break;
case Literal::SubDenomination::Day:
value *= bigint("86400");
break;
case Literal::SubDenomination::Week:
value *= bigint("604800");
break;
case Literal::SubDenomination::Year:
value *= bigint("31536000");
break;
}
return make_tuple(true, value);
}
BoolResult RationalNumberType::isImplicitlyConvertibleTo(Type const& _convertTo) const
{
switch (_convertTo.category())
{
case Category::Integer:
{
if (isFractional())
return false;
IntegerType const& targetType = dynamic_cast<IntegerType const&>(_convertTo);
return fitsIntegerType(m_value.numerator(), targetType);
}
case Category::FixedPoint:
{
FixedPointType const& targetType = dynamic_cast<FixedPointType const&>(_convertTo);
// Store a negative number into an unsigned.
if (isNegative() && !targetType.isSigned())
return false;
if (!isFractional())
return (targetType.minIntegerValue() <= m_value) && (m_value <= targetType.maxIntegerValue());
rational value = m_value * pow(bigint(10), targetType.fractionalDigits());
// Need explicit conversion since truncation will occur.
if (value.denominator() != 1)
return false;
return fitsIntoBits(value.numerator(), targetType.numBits(), targetType.isSigned());
}
case Category::FixedBytes:
return (m_value == rational(0)) || (m_compatibleBytesType && *m_compatibleBytesType == _convertTo);
default:
return false;
}
}
BoolResult RationalNumberType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
if (isImplicitlyConvertibleTo(_convertTo))
return true;
auto category = _convertTo.category();
if (category == Category::FixedBytes)
return false;
else if (auto addressType = dynamic_cast<AddressType const*>(&_convertTo))
return (m_value == 0) ||
((addressType->stateMutability() != StateMutability::Payable) &&
!isNegative() &&
!isFractional() &&
integerType() &&
(integerType()->numBits() <= 160));
else if (category == Category::Integer)
return false;
else if (auto enumType = dynamic_cast<EnumType const*>(&_convertTo))
if (isNegative() || isFractional() || m_value >= enumType->numberOfMembers())
return false;
Type const* mobType = mobileType();
return (mobType && mobType->isExplicitlyConvertibleTo(_convertTo));
}
TypeResult RationalNumberType::unaryOperatorResult(Token _operator) const
{
if (optional<rational> value = ConstantEvaluator::evaluateUnaryOperator(_operator, m_value))
return TypeResult{TypeProvider::rationalNumber(*value)};
else
return nullptr;
}
TypeResult RationalNumberType::binaryOperatorResult(Token _operator, Type const* _other) const
{
if (_other->category() == Category::Integer || _other->category() == Category::FixedPoint)
{
if (isFractional())
return TypeResult::err("Fractional literals not supported.");
else if (!integerType())
return TypeResult::err("Literal too large.");
// Shift and exp are not symmetric, so it does not make sense to swap
// the types as below. As an exception, we always use uint here.
if (TokenTraits::isShiftOp(_operator))
{
if (!isValidShiftAndAmountType(_operator, *_other))
return nullptr;
return isNegative() ? TypeProvider::int256() : TypeProvider::uint256();