-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Expand file tree
/
Copy pathDeclarationTypeChecker.cpp
More file actions
635 lines (564 loc) · 19.5 KB
/
DeclarationTypeChecker.cpp
File metadata and controls
635 lines (564 loc) · 19.5 KB
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
/*
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
#include <libsolidity/analysis/DeclarationTypeChecker.h>
#include <libsolidity/analysis/ConstantEvaluator.h>
#include <libsolidity/ast/TypeProvider.h>
#include <liblangutil/ErrorReporter.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/Visitor.h>
#include <range/v3/view/transform.hpp>
using namespace solidity::langutil;
using namespace solidity::frontend;
bool DeclarationTypeChecker::visit(ElementaryTypeName const& _typeName)
{
if (_typeName.annotation().type)
return false;
_typeName.annotation().type = TypeProvider::fromElementaryTypeName(_typeName.typeName());
if (_typeName.stateMutability().has_value())
{
// for non-address types this was already caught by the parser
solAssert(_typeName.annotation().type->category() == Type::Category::Address, "");
switch (*_typeName.stateMutability())
{
case StateMutability::Payable:
_typeName.annotation().type = TypeProvider::payableAddress();
break;
case StateMutability::NonPayable:
_typeName.annotation().type = TypeProvider::address();
break;
default:
m_errorReporter.typeError(
2311_error,
_typeName.location(),
"Address types can only be payable or non-payable."
);
break;
}
}
return true;
}
bool DeclarationTypeChecker::visit(EnumDefinition const& _enum)
{
if (_enum.members().size() > 256)
m_errorReporter.declarationError(
1611_error,
_enum.location(),
"Enum with more than 256 members is not allowed."
);
return false;
}
bool DeclarationTypeChecker::visit(StructDefinition const& _struct)
{
if (_struct.annotation().recursive.has_value())
{
if (!m_currentStructsSeen.empty() && *_struct.annotation().recursive)
m_recursiveStructSeen = true;
return false;
}
if (m_currentStructsSeen.count(&_struct))
{
_struct.annotation().recursive = true;
m_recursiveStructSeen = true;
return false;
}
bool previousRecursiveStructSeen = m_recursiveStructSeen;
bool hasRecursiveChild = false;
m_currentStructsSeen.insert(&_struct);
for (auto const& member: _struct.members())
{
m_recursiveStructSeen = false;
member->accept(*this);
solAssert(member->annotation().type, "");
if (m_recursiveStructSeen)
hasRecursiveChild = true;
}
if (!_struct.annotation().recursive.has_value())
_struct.annotation().recursive = hasRecursiveChild;
m_recursiveStructSeen = previousRecursiveStructSeen || *_struct.annotation().recursive;
m_currentStructsSeen.erase(&_struct);
if (m_currentStructsSeen.empty())
m_recursiveStructSeen = false;
// Check direct recursion, fatal error if detected.
auto visitor = [&](StructDefinition const& _struct, auto& _cycleDetector, size_t _depth)
{
if (_depth >= 256)
m_errorReporter.fatalDeclarationError(
5651_error,
_struct.location(),
"Struct definition exhausts cyclic dependency validator."
);
for (ASTPointer<VariableDeclaration> const& member: _struct.members())
{
Type const* memberType = member->annotation().type;
if (auto arrayType = dynamic_cast<ArrayType const*>(memberType))
memberType = arrayType->finalBaseType(true);
if (auto structType = dynamic_cast<StructType const*>(memberType))
if (_cycleDetector.run(structType->structDefinition()))
return;
}
};
if (util::CycleDetector<StructDefinition>(visitor).run(_struct))
m_errorReporter.fatalTypeError(2046_error, _struct.location(), "Recursive struct definition.");
return false;
}
void DeclarationTypeChecker::endVisit(UserDefinedValueTypeDefinition const& _userDefined)
{
TypeName const* typeName = _userDefined.underlyingType();
solAssert(typeName, "");
if (!dynamic_cast<ElementaryTypeName const*>(typeName))
m_errorReporter.fatalTypeError(
8657_error,
typeName->location(),
"The underlying type for a user defined value type has to be an elementary value type."
);
Type const* type = typeName->annotation().type;
solAssert(type, "");
solAssert(!dynamic_cast<UserDefinedValueType const*>(type), "");
if (!type->isValueType())
m_errorReporter.typeError(
8129_error,
_userDefined.location(),
"The underlying type of the user defined value type \"" +
_userDefined.name() +
"\" is not a value type."
);
}
void DeclarationTypeChecker::endVisit(UserDefinedTypeName const& _typeName)
{
if (_typeName.annotation().type)
return;
Declaration const* declaration = _typeName.pathNode().annotation().referencedDeclaration;
solAssert(declaration, "");
if (StructDefinition const* structDef = dynamic_cast<StructDefinition const*>(declaration))
{
if (!m_insideFunctionType && !m_currentStructsSeen.empty())
structDef->accept(*this);
_typeName.annotation().type = TypeProvider::structType(*structDef, DataLocation::Storage);
}
else if (EnumDefinition const* enumDef = dynamic_cast<EnumDefinition const*>(declaration))
_typeName.annotation().type = TypeProvider::enumType(*enumDef);
else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration))
_typeName.annotation().type = TypeProvider::contract(*contract);
else if (auto userDefinedValueType = dynamic_cast<UserDefinedValueTypeDefinition const*>(declaration))
_typeName.annotation().type = TypeProvider::userDefinedValueType(*userDefinedValueType);
else
{
_typeName.annotation().type = TypeProvider::emptyTuple();
m_errorReporter.fatalTypeError(
5172_error,
_typeName.location(),
"Name has to refer to a user-defined type."
);
}
}
void DeclarationTypeChecker::endVisit(IdentifierPath const& _path)
{
Declaration const* declaration = _path.annotation().referencedDeclaration;
solAssert(declaration, "");
if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration))
if (contract->isLibrary())
m_errorReporter.typeError(1130_error, _path.location(), "Invalid use of a library name.");
}
bool DeclarationTypeChecker::visit(FunctionTypeName const& _typeName)
{
if (_typeName.annotation().type)
return false;
bool previousInsideFunctionType = m_insideFunctionType;
m_insideFunctionType = true;
_typeName.parameterTypeList()->accept(*this);
_typeName.returnParameterTypeList()->accept(*this);
m_insideFunctionType = previousInsideFunctionType;
switch (_typeName.visibility())
{
case Visibility::Internal:
case Visibility::External:
break;
default:
m_errorReporter.fatalTypeError(
6012_error,
_typeName.location(),
"Invalid visibility, can only be \"external\" or \"internal\"."
);
return false;
}
if (_typeName.isPayable() && _typeName.visibility() != Visibility::External)
{
m_errorReporter.fatalTypeError(
7415_error,
_typeName.location(),
"Only external function types can be payable."
);
return false;
}
_typeName.annotation().type = TypeProvider::function(_typeName);
return false;
}
void DeclarationTypeChecker::endVisit(Mapping const& _mapping)
{
if (_mapping.annotation().type)
return;
if (auto const* typeName = dynamic_cast<UserDefinedTypeName const*>(&_mapping.keyType()))
switch (typeName->annotation().type->category())
{
case Type::Category::Enum:
case Type::Category::Contract:
case Type::Category::UserDefinedValueType:
break;
default:
m_errorReporter.fatalTypeError(
7804_error,
typeName->location(),
"Only elementary types, user defined value types, contract types or enums are allowed as mapping keys."
);
break;
}
else
solAssert(dynamic_cast<ElementaryTypeName const*>(&_mapping.keyType()), "");
Type const* keyType = _mapping.keyType().annotation().type;
ASTString keyName = _mapping.keyName();
Type const* valueType = _mapping.valueType().annotation().type;
ASTString valueName = _mapping.valueName();
// Convert key type to memory.
keyType = TypeProvider::withLocationIfReference(DataLocation::Memory, keyType);
// Convert value type to storage reference.
valueType = TypeProvider::withLocationIfReference(DataLocation::Storage, valueType);
_mapping.annotation().type = TypeProvider::mapping(keyType, keyName, valueType, valueName);
// Check if parameter names are conflicting.
if (!keyName.empty())
{
auto childMappingType = dynamic_cast<MappingType const*>(valueType);
ASTString currentValueName = valueName;
bool loop = true;
while (loop)
{
bool isError = false;
// Value type is a mapping.
if (childMappingType)
{
// Compare top mapping's key name with child mapping's key name.
ASTString childKeyName = childMappingType->keyName();
if (keyName == childKeyName)
isError = true;
auto valueType = childMappingType->valueType();
currentValueName = childMappingType->valueName();
childMappingType = dynamic_cast<MappingType const*>(valueType);
}
else
{
// Compare top mapping's key name with the value name.
if (keyName == currentValueName)
isError = true;
loop = false; // We arrived at the end of mapping recursion.
}
// Report error.
if (isError)
{
m_errorReporter.declarationError(
1809_error,
_mapping.location(),
"Conflicting parameter name \"" + keyName + "\" in mapping."
);
}
}
}
}
void DeclarationTypeChecker::endVisit(ArrayTypeName const& _typeName)
{
if (_typeName.annotation().type)
return;
Type const* baseType = _typeName.baseType().annotation().type;
if (!baseType)
{
solAssert(m_errorReporter.hasErrors(), "");
return;
}
if (Expression const* length = _typeName.length())
{
std::optional<rational> lengthValue;
if (length->annotation().type && length->annotation().type->category() == Type::Category::RationalNumber)
lengthValue = dynamic_cast<RationalNumberType const&>(*length->annotation().type).value();
else if (ConstantEvaluator::TypedValue value = ConstantEvaluator::evaluate(m_errorReporter, *length);
std::holds_alternative<rational>(value.value)
)
lengthValue = std::get<rational>(value.value);
if (!lengthValue)
m_errorReporter.typeError(
5462_error,
length->location(),
"Invalid array length, expected integer literal or constant expression."
);
else if (*lengthValue == 0)
m_errorReporter.typeError(1406_error, length->location(), "Array with zero length specified.");
else if (lengthValue->denominator() != 1)
m_errorReporter.typeError(3208_error, length->location(), "Array with fractional length specified.");
else if (*lengthValue < 0)
m_errorReporter.typeError(3658_error, length->location(), "Array with negative length specified.");
else if (lengthValue > TypeProvider::uint256()->max())
m_errorReporter.typeError(
1847_error,
length->location(),
"Array length too large, maximum is 2**256 - 1."
);
_typeName.annotation().type = TypeProvider::array(
DataLocation::Storage,
baseType,
lengthValue ? u256(lengthValue->numerator()) : u256(0)
);
}
else
_typeName.annotation().type = TypeProvider::array(DataLocation::Storage, baseType);
}
void DeclarationTypeChecker::endVisit(VariableDeclaration const& _variable)
{
if (_variable.annotation().type)
return;
if (_variable.isFileLevelVariable() && !_variable.isConstant())
m_errorReporter.declarationError(
8342_error,
_variable.location(),
"Only constant variables are allowed at file level."
);
if (_variable.isConstant() && (!_variable.isStateVariable() && !_variable.isFileLevelVariable()))
m_errorReporter.declarationError(
1788_error,
_variable.location(),
"The \"constant\" keyword can only be used for state variables or variables at file level."
);
if (_variable.immutable() && !_variable.isStateVariable())
m_errorReporter.declarationError(
8297_error,
_variable.location(),
"The \"immutable\" keyword can only be used for state variables."
);
using Location = VariableDeclaration::Location;
Location varLoc = _variable.referenceLocation();
DataLocation typeLoc = DataLocation::Memory;
if (varLoc == VariableDeclaration::Location::Transient && !m_evmVersion.supportsTransientStorage())
m_errorReporter.declarationError(
7985_error,
_variable.location(),
"Transient storage is not supported by EVM versions older than cancun."
);
std::set<Location> allowedDataLocations = _variable.allowedDataLocations();
if (!allowedDataLocations.count(varLoc))
{
auto locationToString = [](VariableDeclaration::Location _location) -> std::string
{
switch (_location)
{
case Location::Memory: return "\"memory\"";
case Location::Storage: return "\"storage\"";
case Location::Transient: return "\"transient\"";
case Location::CallData: return "\"calldata\"";
case Location::Constant: return "\"constant\"";
case Location::Unspecified: return "none";
}
return {};
};
std::string errorString;
if (!_variable.hasReferenceOrMappingType())
errorString = "Data location can only be specified for array, struct or mapping types";
else
{
errorString = "Data location must be " +
util::joinHumanReadable(
allowedDataLocations | ranges::views::transform(locationToString),
", ",
" or "
);
if (_variable.isConstructorParameter())
errorString += " for constructor parameter";
else if (_variable.isCallableOrCatchParameter())
errorString +=
" for " +
std::string(_variable.isReturnParameter() ? "return " : "") +
"parameter in" +
std::string(_variable.isExternalCallableParameter() ? " external" : "") +
" function";
else
errorString += " for variable";
}
errorString += ", but " + locationToString(varLoc) + " was given.";
m_errorReporter.typeError(6651_error, _variable.location(), errorString);
solAssert(!allowedDataLocations.empty(), "");
varLoc = *allowedDataLocations.begin();
}
// Find correct data location.
if (_variable.isEventOrErrorParameter())
{
solAssert(varLoc == Location::Unspecified, "");
typeLoc = DataLocation::Memory;
}
else if (_variable.isFileLevelVariable())
{
solAssert(varLoc == Location::Unspecified, "");
typeLoc = DataLocation::Memory;
}
else if (_variable.isStateVariable())
{
switch (varLoc)
{
case Location::Unspecified:
typeLoc = (_variable.isConstant() || _variable.immutable()) ? DataLocation::Memory : DataLocation::Storage;
break;
case Location::Transient:
if (_variable.isConstant() || _variable.immutable())
m_errorReporter.declarationError(
2197_error,
_variable.location(),
"Transient cannot be used as data location for constant or immutable variables."
);
if (_variable.value())
m_errorReporter.declarationError(
9825_error,
_variable.location(),
"Initialization of transient storage state variables is not supported."
);
typeLoc = DataLocation::Transient;
break;
default:
solAssert(false);
break;
}
}
else if (
dynamic_cast<StructDefinition const*>(_variable.scope()) ||
dynamic_cast<EnumDefinition const*>(_variable.scope())
)
// The actual location will later be changed depending on how the type is used.
typeLoc = DataLocation::Storage;
else
switch (varLoc)
{
case Location::Memory:
typeLoc = DataLocation::Memory;
break;
case Location::Storage:
typeLoc = DataLocation::Storage;
break;
case Location::CallData:
typeLoc = DataLocation::CallData;
break;
case Location::Transient:
solUnimplemented("Transient data location cannot be used in this kind of variable or parameter declaration.");
break;
case Location::Constant:
typeLoc = DataLocation::Constant;
break;
case Location::Unspecified:
solAssert(!_variable.hasReferenceOrMappingType(), "Data location not properly set.");
}
Type const* type = _variable.typeName().annotation().type;
if (auto ref = dynamic_cast<ReferenceType const*>(type))
{
bool isPointer = !_variable.isStateVariable();
type = TypeProvider::withLocation(ref, typeLoc, isPointer);
}
if (_variable.isConstant() && !type->isValueType())
{
bool allowed = false;
bool isByteArrayOrString = false;
if (auto arrayType = dynamic_cast<ArrayType const*>(type))
{
isByteArrayOrString = arrayType->isByteArrayOrString();
if (isByteArrayOrString)
allowed = true;
else
allowed = !arrayType->containsNestedMapping();
}
else if (auto structType = dynamic_cast<StructType const*>(type))
{
bool membersResolved = true;
for (auto const& member: structType->structDefinition().members())
if (!member->annotation().type)
{
membersResolved = false;
break;
}
allowed = !membersResolved || !structType->containsNestedMapping();
}
else if (dynamic_cast<MappingType const*>(type))
allowed = false;
if (!allowed)
m_errorReporter.fatalTypeError(9259_error, _variable.location(), "Constants of this type are not supported. Only value types, arrays, structs, and byte/string types without mappings are allowed.");
if (!isByteArrayOrString)
{
if (auto ref = dynamic_cast<ReferenceType const*>(type))
type = TypeProvider::withLocation(ref, DataLocation::Constant, false);
}
}
if (!type->isValueType())
solUnimplementedAssert(typeLoc != DataLocation::Transient, "Transient data location is only supported for value types.");
_variable.annotation().type = type;
}
bool DeclarationTypeChecker::visit(UsingForDirective const& _usingFor)
{
if (_usingFor.usesBraces())
{
for (ASTPointer<IdentifierPath> const& function: _usingFor.functionsOrLibrary())
if (auto functionDefinition = dynamic_cast<FunctionDefinition const*>(function->annotation().referencedDeclaration))
{
if (!functionDefinition->isFree() && !(
dynamic_cast<ContractDefinition const*>(functionDefinition->scope()) &&
dynamic_cast<ContractDefinition const*>(functionDefinition->scope())->isLibrary()
))
m_errorReporter.typeError(
4167_error,
function->location(),
"Only file-level functions and library functions can be attached to a type in a \"using\" statement"
);
}
else
m_errorReporter.fatalTypeError(8187_error, function->location(), "Expected function name." );
}
else
{
ContractDefinition const* library = dynamic_cast<ContractDefinition const*>(
_usingFor.functionsOrLibrary().front()->annotation().referencedDeclaration
);
if (!library || !library->isLibrary())
m_errorReporter.fatalTypeError(
4357_error,
_usingFor.functionsOrLibrary().front()->location(),
"Library name expected. If you want to attach a function, use '{...}'."
);
}
// We do not visit _usingFor.functions() because it will lead to an error since
// library names cannot be mentioned stand-alone.
if (_usingFor.typeName())
_usingFor.typeName()->accept(*this);
return false;
}
bool DeclarationTypeChecker::visit(InheritanceSpecifier const& _inheritanceSpecifier)
{
auto const* contract = dynamic_cast<ContractDefinition const*>(_inheritanceSpecifier.name().annotation().referencedDeclaration);
solAssert(contract, "");
if (contract->isLibrary())
{
m_errorReporter.typeError(
2571_error,
_inheritanceSpecifier.name().location(),
"Libraries cannot be inherited from."
);
return false;
}
return true;
}
bool DeclarationTypeChecker::check(ASTNode const& _node)
{
auto watcher = m_errorReporter.errorWatcher();
_node.accept(*this);
return watcher.ok();
}