-
Notifications
You must be signed in to change notification settings - Fork 6.1k
/
Copy pathTypeInference.cpp
1244 lines (1096 loc) · 43 KB
/
TypeInference.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
#include <libsolidity/experimental/analysis/TypeInference.h>
#include <libsolidity/experimental/analysis/TypeClassRegistration.h>
#include <libsolidity/experimental/analysis/TypeRegistration.h>
#include <libsolidity/experimental/analysis/Analysis.h>
#include <libsolidity/experimental/ast/TypeSystemHelper.h>
#include <libsolutil/Numeric.h>
#include <libsolutil/StringUtils.h>
#include <liblangutil/Exceptions.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/AST.h>
#include <boost/algorithm/string.hpp>
#include <range/v3/view/transform.hpp>
using namespace solidity;
using namespace solidity::frontend;
using namespace solidity::frontend::experimental;
using namespace solidity::langutil;
TypeInference::TypeInference(Analysis& _analysis):
m_analysis(_analysis),
m_errorReporter(_analysis.errorReporter()),
m_typeSystem(_analysis.typeSystem()),
m_env(&m_typeSystem.env()),
m_voidType(m_typeSystem.type(PrimitiveType::Void, {})),
m_wordType(m_typeSystem.type(PrimitiveType::Word, {})),
m_integerType(m_typeSystem.type(PrimitiveType::Integer, {})),
m_unitType(m_typeSystem.type(PrimitiveType::Unit, {})),
m_boolType(m_typeSystem.type(PrimitiveType::Bool, {}))
{
TypeSystemHelpers helper{m_typeSystem};
auto declareBuiltinClass = [&](std::string _name, BuiltinClass _class) -> TypeClass {
auto result = m_typeSystem.declareTypeClass(_name, nullptr);
if (auto error = std::get_if<std::string>(&result))
solAssert(!error, *error);
TypeClass declaredClass = std::get<TypeClass>(result);
// TODO: validation?
solAssert(annotation().builtinClassesByName.emplace(_name, _class).second);
return annotation().builtinClasses.emplace(_class, declaredClass).first->second;
};
auto registeredTypeClass = [&](BuiltinClass _builtinClass) -> TypeClass {
return annotation().builtinClasses.at(_builtinClass);
};
auto defineConversion = [&](BuiltinClass _builtinClass, PrimitiveType _fromType, std::string _functionName) {
annotation().typeClassFunctions[registeredTypeClass(_builtinClass)] = {{
std::move(_functionName),
helper.functionType(
m_typeSystem.type(_fromType, {}),
m_typeSystem.typeClassInfo(registeredTypeClass(_builtinClass)).typeVariable
),
}};
};
auto defineBinaryMonoidalOperator = [&](BuiltinClass _builtinClass, Token _token, std::string _functionName) {
Type typeVar = m_typeSystem.typeClassInfo(registeredTypeClass(_builtinClass)).typeVariable;
annotation().operators.emplace(_token, std::make_tuple(registeredTypeClass(_builtinClass), _functionName));
annotation().typeClassFunctions[registeredTypeClass(_builtinClass)] = {{
std::move(_functionName),
helper.functionType(
helper.tupleType({typeVar, typeVar}),
typeVar
)
}};
};
auto defineBinaryCompareOperator = [&](BuiltinClass _builtinClass, Token _token, std::string _functionName) {
Type typeVar = m_typeSystem.typeClassInfo(registeredTypeClass(_builtinClass)).typeVariable;
annotation().operators.emplace(_token, std::make_tuple(registeredTypeClass(_builtinClass), _functionName));
annotation().typeClassFunctions[registeredTypeClass(_builtinClass)] = {{
std::move(_functionName),
helper.functionType(
helper.tupleType({typeVar, typeVar}),
m_typeSystem.type(PrimitiveType::Bool, {})
)
}};
};
declareBuiltinClass("integer", BuiltinClass::Integer);
declareBuiltinClass("*", BuiltinClass::Mul);
declareBuiltinClass("+", BuiltinClass::Add);
declareBuiltinClass("==", BuiltinClass::Equal);
declareBuiltinClass("<", BuiltinClass::Less);
declareBuiltinClass("<=", BuiltinClass::LessOrEqual);
declareBuiltinClass(">", BuiltinClass::Greater);
declareBuiltinClass(">=", BuiltinClass::GreaterOrEqual);
defineConversion(BuiltinClass::Integer, PrimitiveType::Integer, "fromInteger");
defineBinaryMonoidalOperator(BuiltinClass::Mul, Token::Mul, "mul");
defineBinaryMonoidalOperator(BuiltinClass::Add, Token::Add, "add");
defineBinaryCompareOperator(BuiltinClass::Equal, Token::Equal, "eq");
defineBinaryCompareOperator(BuiltinClass::Less, Token::LessThan, "lt");
defineBinaryCompareOperator(BuiltinClass::LessOrEqual, Token::LessThanOrEqual, "leq");
defineBinaryCompareOperator(BuiltinClass::Greater, Token::GreaterThan, "gt");
defineBinaryCompareOperator(BuiltinClass::GreaterOrEqual, Token::GreaterThanOrEqual, "geq");
}
bool TypeInference::analyze(SourceUnit const& _sourceUnit)
{
_sourceUnit.accept(*this);
return !m_errorReporter.hasErrors();
}
bool TypeInference::visit(ForAllQuantifier const& _quantifier)
{
solAssert(m_expressionContext == ExpressionContext::Term);
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
_quantifier.typeVariableDeclarations().accept(*this);
}
_quantifier.quantifiedDeclaration().accept(*this);
return false;
}
bool TypeInference::visit(FunctionDefinition const& _functionDefinition)
{
solAssert(m_expressionContext == ExpressionContext::Term);
auto& functionAnnotation = annotation(_functionDefinition);
if (functionAnnotation.type)
return false;
ScopedSaveAndRestore signatureRestore(m_currentFunctionType, std::nullopt);
Type argumentsType = m_typeSystem.freshTypeVariable({});
Type returnType = m_typeSystem.freshTypeVariable({});
Type functionType = TypeSystemHelpers{m_typeSystem}.functionType(argumentsType, returnType);
m_currentFunctionType = functionType;
functionAnnotation.type = functionType;
_functionDefinition.parameterList().accept(*this);
unify(argumentsType, type(_functionDefinition.parameterList()), _functionDefinition.parameterList().location());
if (_functionDefinition.experimentalReturnExpression())
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
_functionDefinition.experimentalReturnExpression()->accept(*this);
unify(
returnType,
type(*_functionDefinition.experimentalReturnExpression()),
_functionDefinition.experimentalReturnExpression()->location()
);
}
else
unify(returnType, m_unitType, _functionDefinition.location());
if (_functionDefinition.isImplemented())
_functionDefinition.body().accept(*this);
return false;
}
void TypeInference::endVisit(FunctionDefinition const& _functionDefinition)
{
solAssert(m_expressionContext == ExpressionContext::Term);
m_env->fixTypeVars(TypeEnvironmentHelpers{*m_env}.typeVars(type(_functionDefinition)));
}
void TypeInference::endVisit(Return const& _return)
{
solAssert(m_currentFunctionType);
Type functionReturnType = std::get<1>(TypeSystemHelpers{m_typeSystem}.destFunctionType(*m_currentFunctionType));
if (_return.expression())
unify(functionReturnType, type(*_return.expression()), _return.location());
else
unify(functionReturnType, m_unitType, _return.location());
}
void TypeInference::endVisit(ParameterList const& _parameterList)
{
auto& listAnnotation = annotation(_parameterList);
solAssert(!listAnnotation.type);
listAnnotation.type = TypeSystemHelpers{m_typeSystem}.tupleType(
_parameterList.parameters() | ranges::views::transform([&](auto _arg) { return type(*_arg); }) | ranges::to<std::vector<Type>>
);
}
bool TypeInference::visit(TypeClassDefinition const& _typeClassDefinition)
{
solAssert(m_expressionContext == ExpressionContext::Term);
auto& typeClassDefinitionAnnotation = annotation(_typeClassDefinition);
if (typeClassDefinitionAnnotation.type)
return false;
typeClassDefinitionAnnotation.type = type(&_typeClassDefinition, {});
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
_typeClassDefinition.typeVariable().accept(*this);
}
std::map<std::string, Type> functionTypes;
solAssert(m_analysis.annotation<TypeClassRegistration>(_typeClassDefinition).typeClass.has_value());
TypeClass typeClass = m_analysis.annotation<TypeClassRegistration>(_typeClassDefinition).typeClass.value();
Type typeVar = m_typeSystem.typeClassVariable(typeClass);
unify(type(_typeClassDefinition.typeVariable()), typeVar, _typeClassDefinition.location());
auto& typeMembersAnnotation = annotation().members[typeConstructor(&_typeClassDefinition)];
for (auto subNode: _typeClassDefinition.subNodes())
{
subNode->accept(*this);
auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(subNode.get());
solAssert(functionDefinition);
auto functionType = type(*functionDefinition);
if (!functionTypes.emplace(functionDefinition->name(), functionType).second)
m_errorReporter.fatalTypeError(3195_error, functionDefinition->location(), "Function in type class declared multiple times.");
auto typeVars = TypeEnvironmentHelpers{*m_env}.typeVars(functionType);
if (typeVars.size() != 1)
m_errorReporter.fatalTypeError(8379_error, functionDefinition->location(), "Function in type class may only depend on the type class variable.");
unify(typeVars.front(), typeVar, functionDefinition->location());
typeMembersAnnotation[functionDefinition->name()] = TypeMember{functionType};
}
annotation().typeClassFunctions[typeClass] = std::move(functionTypes);
for (auto [functionName, functionType]: functionTypes)
{
TypeEnvironmentHelpers helper{*m_env};
auto typeVars = helper.typeVars(functionType);
if (typeVars.empty())
m_errorReporter.typeError(1723_error, _typeClassDefinition.location(), "Function " + functionName + " does not depend on class variable.");
if (typeVars.size() > 2)
m_errorReporter.typeError(6387_error, _typeClassDefinition.location(), "Function " + functionName + " depends on multiple type variables.");
if (!m_env->typeEquals(typeVars.front(), typeVar))
m_errorReporter.typeError(1807_error, _typeClassDefinition.location(), "Function " + functionName + " depends on invalid type variable.");
}
for (auto instantiation: m_analysis.annotation<TypeRegistration>(_typeClassDefinition).instantiations | ranges::views::values)
// TODO: recursion-safety? Order of instantiation?
instantiation->accept(*this);
return false;
}
bool TypeInference::visit(InlineAssembly const& _inlineAssembly)
{
// External references have already been resolved in a prior stage and stored in the annotation.
// We run the resolve step again regardless.
yul::ExternalIdentifierAccess::Resolver identifierAccess = [&](
yul::Identifier const& _identifier,
yul::IdentifierContext _context,
bool
) -> bool
{
if (_context == yul::IdentifierContext::NonExternal)
{
// TODO: do we need this?
// Hack until we can disallow any shadowing: If we found an internal reference,
// clear the external references, so that codegen does not use it.
_inlineAssembly.annotation().externalReferences.erase(& _identifier);
return false;
}
InlineAssemblyAnnotation::ExternalIdentifierInfo* identifierInfo = util::valueOrNullptr(_inlineAssembly.annotation().externalReferences, &_identifier);
if (!identifierInfo)
return false;
Declaration const* declaration = identifierInfo->declaration;
solAssert(!!declaration, "");
solAssert(identifierInfo->suffix == "", "");
unify(type(*declaration), m_wordType, originLocationOf(_identifier));
identifierInfo->valueSize = 1;
return true;
};
solAssert(!_inlineAssembly.annotation().analysisInfo, "");
_inlineAssembly.annotation().analysisInfo = std::make_shared<yul::AsmAnalysisInfo>();
yul::AsmAnalyzer analyzer(
*_inlineAssembly.annotation().analysisInfo,
m_errorReporter,
_inlineAssembly.dialect(),
identifierAccess
);
if (!analyzer.analyze(_inlineAssembly.operations()))
solAssert(m_errorReporter.hasErrors());
return false;
}
bool TypeInference::visit(BinaryOperation const& _binaryOperation)
{
auto& operationAnnotation = annotation(_binaryOperation);
solAssert(!operationAnnotation.type);
TypeSystemHelpers helper{m_typeSystem};
switch (m_expressionContext)
{
case ExpressionContext::Term:
if (auto* operatorInfo = util::valueOrNullptr(annotation().operators, _binaryOperation.getOperator()))
{
auto [typeClass, functionName] = *operatorInfo;
// TODO: error robustness?
Type functionType = m_env->fresh(annotation().typeClassFunctions.at(typeClass).at(functionName));
_binaryOperation.leftExpression().accept(*this);
_binaryOperation.rightExpression().accept(*this);
Type argTuple = helper.tupleType({type(_binaryOperation.leftExpression()), type(_binaryOperation.rightExpression())});
Type resultType = m_typeSystem.freshTypeVariable({});
Type genericFunctionType = helper.functionType(argTuple, resultType);
unify(functionType, genericFunctionType, _binaryOperation.location());
operationAnnotation.type = resultType;
}
else if (_binaryOperation.getOperator() == Token::Colon)
{
_binaryOperation.leftExpression().accept(*this);
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
_binaryOperation.rightExpression().accept(*this);
}
Type leftType = type(_binaryOperation.leftExpression());
unify(leftType, type(_binaryOperation.rightExpression()), _binaryOperation.location());
operationAnnotation.type = leftType;
}
else
{
m_errorReporter.typeError(4504_error, _binaryOperation.location(), "Binary operation in term context not yet supported.");
operationAnnotation.type = m_typeSystem.freshTypeVariable({});
}
return false;
case ExpressionContext::Type:
if (_binaryOperation.getOperator() == Token::Colon)
{
_binaryOperation.leftExpression().accept(*this);
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Sort};
_binaryOperation.rightExpression().accept(*this);
}
Type leftType = type(_binaryOperation.leftExpression());
unify(leftType, type(_binaryOperation.rightExpression()), _binaryOperation.location());
operationAnnotation.type = leftType;
}
else if (_binaryOperation.getOperator() == Token::RightArrow)
{
_binaryOperation.leftExpression().accept(*this);
_binaryOperation.rightExpression().accept(*this);
operationAnnotation.type = helper.functionType(type(_binaryOperation.leftExpression()), type(_binaryOperation.rightExpression()));
}
else if (_binaryOperation.getOperator() == Token::BitOr)
{
_binaryOperation.leftExpression().accept(*this);
_binaryOperation.rightExpression().accept(*this);
operationAnnotation.type = helper.sumType({type(_binaryOperation.leftExpression()), type(_binaryOperation.rightExpression())});
}
else
{
m_errorReporter.typeError(1439_error, _binaryOperation.location(), "Invalid binary operations in type context.");
operationAnnotation.type = m_typeSystem.freshTypeVariable({});
}
return false;
case ExpressionContext::Sort:
m_errorReporter.typeError(1017_error, _binaryOperation.location(), "Invalid binary operation in sort context.");
operationAnnotation.type = m_typeSystem.freshTypeVariable({});
return false;
}
return false;
}
void TypeInference::endVisit(VariableDeclarationStatement const& _variableDeclarationStatement)
{
solAssert(m_expressionContext == ExpressionContext::Term);
if (_variableDeclarationStatement.declarations().size () != 1)
{
m_errorReporter.typeError(2655_error, _variableDeclarationStatement.location(), "Multi variable declaration not supported.");
return;
}
Type variableType = type(*_variableDeclarationStatement.declarations().front());
if (_variableDeclarationStatement.initialValue())
unify(variableType, type(*_variableDeclarationStatement.initialValue()), _variableDeclarationStatement.location());
}
bool TypeInference::visit(VariableDeclaration const& _variableDeclaration)
{
solAssert(!_variableDeclaration.value());
auto& variableAnnotation = annotation(_variableDeclaration);
solAssert(!variableAnnotation.type);
switch (m_expressionContext)
{
case ExpressionContext::Term:
if (_variableDeclaration.typeExpression())
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
_variableDeclaration.typeExpression()->accept(*this);
variableAnnotation.type = type(*_variableDeclaration.typeExpression());
return false;
}
variableAnnotation.type = m_typeSystem.freshTypeVariable({});
return false;
case ExpressionContext::Type:
variableAnnotation.type = m_typeSystem.freshTypeVariable({});
if (_variableDeclaration.typeExpression())
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Sort};
_variableDeclaration.typeExpression()->accept(*this);
unify(*variableAnnotation.type, type(*_variableDeclaration.typeExpression()), _variableDeclaration.typeExpression()->location());
}
return false;
case ExpressionContext::Sort:
m_errorReporter.typeError(2399_error, _variableDeclaration.location(), "Variable declaration in sort context.");
variableAnnotation.type = m_typeSystem.freshTypeVariable({});
return false;
}
util::unreachable();
}
void TypeInference::endVisit(IfStatement const& _ifStatement)
{
auto& ifAnnotation = annotation(_ifStatement);
solAssert(!ifAnnotation.type);
if (m_expressionContext != ExpressionContext::Term)
{
m_errorReporter.typeError(2015_error, _ifStatement.location(), "If statement outside term context.");
ifAnnotation.type = m_typeSystem.freshTypeVariable({});
return;
}
unify(type(_ifStatement.condition()), m_boolType, _ifStatement.condition().location());
ifAnnotation.type = m_unitType;
}
void TypeInference::endVisit(Assignment const& _assignment)
{
auto& assignmentAnnotation = annotation(_assignment);
solAssert(!assignmentAnnotation.type);
if (m_expressionContext != ExpressionContext::Term)
{
m_errorReporter.typeError(4337_error, _assignment.location(), "Assignment outside term context.");
assignmentAnnotation.type = m_typeSystem.freshTypeVariable({});
return;
}
Type leftType = type(_assignment.leftHandSide());
unify(leftType, type(_assignment.rightHandSide()), _assignment.location());
assignmentAnnotation.type = leftType;
}
experimental::Type TypeInference::handleIdentifierByReferencedDeclaration(langutil::SourceLocation _location, Declaration const& _declaration)
{
switch (m_expressionContext)
{
case ExpressionContext::Term:
{
if (
!dynamic_cast<FunctionDefinition const*>(&_declaration) &&
!dynamic_cast<VariableDeclaration const*>(&_declaration) &&
!dynamic_cast<TypeClassDefinition const*>(&_declaration) &&
!dynamic_cast<TypeDefinition const*>(&_declaration)
)
{
SecondarySourceLocation ssl;
ssl.append("Referenced node.", _declaration.location());
m_errorReporter.fatalTypeError(3101_error, _location, ssl, "Attempt to type identifier referring to unexpected node.");
}
auto& declarationAnnotation = annotation(_declaration);
if (!declarationAnnotation.type)
_declaration.accept(*this);
solAssert(declarationAnnotation.type);
if (dynamic_cast<VariableDeclaration const*>(&_declaration))
return *declarationAnnotation.type;
else if (dynamic_cast<FunctionDefinition const*>(&_declaration))
return polymorphicInstance(*declarationAnnotation.type);
else if (dynamic_cast<TypeClassDefinition const*>(&_declaration))
{
solAssert(TypeEnvironmentHelpers{*m_env}.typeVars(*declarationAnnotation.type).empty());
return *declarationAnnotation.type;
}
else if (dynamic_cast<TypeDefinition const*>(&_declaration))
{
// TODO: can we avoid this?
Type type = *declarationAnnotation.type;
if (TypeSystemHelpers{m_typeSystem}.isTypeFunctionType(type))
type = std::get<1>(TypeSystemHelpers{m_typeSystem}.destTypeFunctionType(type));
return polymorphicInstance(type);
}
else
solAssert(false);
break;
}
case ExpressionContext::Type:
{
if (
!dynamic_cast<VariableDeclaration const*>(&_declaration) &&
!dynamic_cast<TypeDefinition const*>(&_declaration)
)
{
SecondarySourceLocation ssl;
ssl.append("Referenced node.", _declaration.location());
m_errorReporter.fatalTypeError(2217_error, _location, ssl, "Attempt to type identifier referring to unexpected node.");
}
// TODO: Assert that this is a type class variable declaration?
auto& declarationAnnotation = annotation(_declaration);
if (!declarationAnnotation.type)
_declaration.accept(*this);
solAssert(declarationAnnotation.type);
if (dynamic_cast<VariableDeclaration const*>(&_declaration))
return *declarationAnnotation.type;
else if (dynamic_cast<TypeDefinition const*>(&_declaration))
return polymorphicInstance(*declarationAnnotation.type);
else
solAssert(false);
break;
}
case ExpressionContext::Sort:
{
if (auto const* typeClassDefinition = dynamic_cast<TypeClassDefinition const*>(&_declaration))
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Term};
typeClassDefinition->accept(*this);
solAssert(m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.has_value());
TypeClass typeClass = m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.value();
return m_typeSystem.freshTypeVariable(Sort{{typeClass}});
}
else
{
m_errorReporter.typeError(2599_error, _location, "Expected type class.");
return m_typeSystem.freshTypeVariable({});
}
break;
}
}
util::unreachable();
}
bool TypeInference::visit(Identifier const& _identifier)
{
auto& identifierAnnotation = annotation(_identifier);
solAssert(!identifierAnnotation.type);
if (auto const* referencedDeclaration = _identifier.annotation().referencedDeclaration)
{
identifierAnnotation.type = handleIdentifierByReferencedDeclaration(_identifier.location(), *referencedDeclaration);
return false;
}
switch (m_expressionContext)
{
case ExpressionContext::Term:
// TODO: error handling
solAssert(false);
break;
case ExpressionContext::Type:
m_errorReporter.typeError(5934_error, _identifier.location(), "Undeclared type variable.");
// Assign it a fresh variable anyway just so that we can continue analysis.
identifierAnnotation.type = m_typeSystem.freshTypeVariable({});
break;
case ExpressionContext::Sort:
// TODO: error handling
solAssert(false);
break;
}
return false;
}
void TypeInference::endVisit(TupleExpression const& _tupleExpression)
{
auto& expressionAnnotation = annotation(_tupleExpression);
solAssert(!expressionAnnotation.type);
TypeSystemHelpers helper{m_typeSystem};
auto componentTypes = _tupleExpression.components() | ranges::views::transform([&](auto _expr) -> Type {
auto& componentAnnotation = annotation(*_expr);
solAssert(componentAnnotation.type);
return *componentAnnotation.type;
}) | ranges::to<std::vector<Type>>;
switch (m_expressionContext)
{
case ExpressionContext::Term:
case ExpressionContext::Type:
expressionAnnotation.type = helper.tupleType(componentTypes);
break;
case ExpressionContext::Sort:
{
Type type = m_typeSystem.freshTypeVariable({});
for (auto componentType: componentTypes)
unify(type, componentType, _tupleExpression.location());
expressionAnnotation.type = type;
break;
}
}
}
bool TypeInference::visit(IdentifierPath const& _identifierPath)
{
auto& identifierAnnotation = annotation(_identifierPath);
solAssert(!identifierAnnotation.type);
if (auto const* referencedDeclaration = _identifierPath.annotation().referencedDeclaration)
{
identifierAnnotation.type = handleIdentifierByReferencedDeclaration(_identifierPath.location(), *referencedDeclaration);
return false;
}
// TODO: error handling
solAssert(false);
}
bool TypeInference::visit(TypeClassInstantiation const& _typeClassInstantiation)
{
ScopedSaveAndRestore activeInstantiations{m_activeInstantiations, m_activeInstantiations + std::set<TypeClassInstantiation const*>{&_typeClassInstantiation}};
// Note: recursion is resolved due to special handling during unification.
auto& instantiationAnnotation = annotation(_typeClassInstantiation);
if (instantiationAnnotation.type)
return false;
instantiationAnnotation.type = m_voidType;
TypeClass typeClass = std::visit(util::GenericVisitor{
[&](ASTPointer<IdentifierPath> _typeClassName) -> TypeClass {
auto const* typeClassDefinition = dynamic_cast<TypeClassDefinition const*>(_typeClassName->annotation().referencedDeclaration);
solAssert(typeClassDefinition);
// visiting the type class will re-visit this instantiation
typeClassDefinition->accept(*this);
// TODO: more error handling? Should be covered by the visit above.
solAssert(m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.has_value());
return m_analysis.annotation<TypeClassRegistration>(*typeClassDefinition).typeClass.value();
},
[&](Token _token) -> TypeClass {
std::optional<BuiltinClass> builtinClass = builtinClassFromToken(_token);
solAssert(builtinClass.has_value());
solAssert(annotation().builtinClasses.count(*builtinClass) != 0);
return annotation().builtinClasses.at(*builtinClass);
}
}, _typeClassInstantiation.typeClass().name());
// TODO: _typeClassInstantiation.typeConstructor().accept(*this); ?
auto typeConstructor = m_analysis.annotation<TypeRegistration>(_typeClassInstantiation.typeConstructor()).typeConstructor;
solAssert(typeConstructor);
std::vector<Type> arguments;
Arity arity{
{},
typeClass
};
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
if (_typeClassInstantiation.argumentSorts())
{
_typeClassInstantiation.argumentSorts()->accept(*this);
auto& argumentSortAnnotation = annotation(*_typeClassInstantiation.argumentSorts());
solAssert(argumentSortAnnotation.type);
arguments = TypeSystemHelpers{m_typeSystem}.destTupleType(*argumentSortAnnotation.type);
arity.argumentSorts = arguments | ranges::views::transform([&](Type _type) {
return m_env->sort(_type);
}) | ranges::to<std::vector<Sort>>;
}
}
m_env->fixTypeVars(arguments);
Type instanceType{TypeConstant{*typeConstructor, arguments}};
std::map<std::string, Type> functionTypes;
for (auto subNode: _typeClassInstantiation.subNodes())
{
auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(subNode.get());
solAssert(functionDefinition);
subNode->accept(*this);
if (!functionTypes.emplace(functionDefinition->name(), type(*functionDefinition)).second)
m_errorReporter.typeError(3654_error, subNode->location(), "Duplicate definition of function " + functionDefinition->name() + " during type class instantiation.");
}
if (auto error = m_typeSystem.instantiateClass(instanceType, arity))
m_errorReporter.typeError(5094_error, _typeClassInstantiation.location(), *error);
auto const& classFunctions = annotation().typeClassFunctions.at(typeClass);
solAssert(std::holds_alternative<TypeVariable>(m_typeSystem.typeClassVariable(typeClass)));
TypeVariable classVar = std::get<TypeVariable>(m_typeSystem.typeClassVariable(typeClass));
for (auto [name, classFunctionType]: classFunctions)
{
if (!functionTypes.count(name))
{
m_errorReporter.typeError(6948_error, _typeClassInstantiation.location(), "Missing function: " + name);
continue;
}
Type instantiatedClassFunctionType = TypeEnvironmentHelpers{*m_env}.substitute(classFunctionType, classVar, instanceType);
Type instanceFunctionType = functionTypes.at(name);
functionTypes.erase(name);
if (!m_env->typeEquals(instanceFunctionType, instantiatedClassFunctionType))
m_errorReporter.typeError(
7428_error,
_typeClassInstantiation.location(),
fmt::format(
"Instantiation function '{}' does not match the declaration in the type class ({} != {}).",
name,
TypeEnvironmentHelpers{*m_env}.typeToString(instanceFunctionType),
TypeEnvironmentHelpers{*m_env}.typeToString(instantiatedClassFunctionType)
)
);
}
if (!functionTypes.empty())
m_errorReporter.typeError(4873_error, _typeClassInstantiation.location(), "Additional functions in class instantiation.");
return false;
}
bool TypeInference::visit(MemberAccess const& _memberAccess)
{
if (m_expressionContext != ExpressionContext::Term)
{
m_errorReporter.typeError(5195_error, _memberAccess.location(), "Member access outside term context.");
annotation(_memberAccess).type = m_typeSystem.freshTypeVariable({});
return false;
}
return true;
}
experimental::Type TypeInference::memberType(Type _type, std::string _memberName, langutil::SourceLocation _location)
{
Type resolvedType = m_env->resolve(_type);
TypeSystemHelpers helper{m_typeSystem};
if (helper.isTypeConstant(resolvedType))
{
auto constructor = std::get<0>(helper.destTypeConstant(resolvedType));
if (auto* typeMember = util::valueOrNullptr(annotation().members.at(constructor), _memberName))
return polymorphicInstance(typeMember->type);
else
{
m_errorReporter.typeError(5755_error, _location, fmt::format("Member {} not found in type {}.", _memberName, TypeEnvironmentHelpers{*m_env}.typeToString(_type)));
return m_typeSystem.freshTypeVariable({});
}
}
else
{
m_errorReporter.typeError(5104_error, _location, "Unsupported member access expression.");
return m_typeSystem.freshTypeVariable({});
}
}
void TypeInference::endVisit(MemberAccess const& _memberAccess)
{
auto& memberAccessAnnotation = annotation(_memberAccess);
solAssert(!memberAccessAnnotation.type);
Type expressionType = type(_memberAccess.expression());
memberAccessAnnotation.type = memberType(expressionType, _memberAccess.memberName(), _memberAccess.location());
}
bool TypeInference::visit(TypeDefinition const& _typeDefinition)
{
bool isBuiltIn = dynamic_cast<Builtin const*>(_typeDefinition.typeExpression());
TypeSystemHelpers helper{m_typeSystem};
auto& typeDefinitionAnnotation = annotation(_typeDefinition);
if (typeDefinitionAnnotation.type)
return false;
if (_typeDefinition.arguments())
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
_typeDefinition.arguments()->accept(*this);
}
std::vector<Type> arguments;
if (_typeDefinition.arguments())
for (ASTPointer<VariableDeclaration> argumentDeclaration: _typeDefinition.arguments()->parameters())
{
solAssert(argumentDeclaration);
Type typeVar = type(*argumentDeclaration);
solAssert(std::holds_alternative<TypeVariable>(typeVar));
arguments.emplace_back(typeVar);
}
m_env->fixTypeVars(arguments);
Type definedType = type(&_typeDefinition, arguments);
if (arguments.empty())
typeDefinitionAnnotation.type = definedType;
else
typeDefinitionAnnotation.type = helper.typeFunctionType(helper.tupleType(arguments), definedType);
std::optional<Type> underlyingType;
if (isBuiltIn)
// TODO: This special case should eventually become user-definable.
underlyingType = m_wordType;
else if (_typeDefinition.typeExpression())
{
ScopedSaveAndRestore expressionContext{m_expressionContext, ExpressionContext::Type};
_typeDefinition.typeExpression()->accept(*this);
underlyingType = annotation(*_typeDefinition.typeExpression()).type;
}
TypeConstructor constructor = typeConstructor(&_typeDefinition);
auto [members, newlyInserted] = annotation().members.emplace(constructor, std::map<std::string, TypeMember>{});
solAssert(newlyInserted, fmt::format("Members of type '{}' are already defined.", m_typeSystem.constructorInfo(constructor).name));
if (underlyingType)
{
// Undeclared type variables are not allowed in type definitions and we fixed all the declared ones.
solAssert(!TypeEnvironmentHelpers{*m_env}.hasGenericTypeVars(*underlyingType));
members->second.emplace("abs", TypeMember{helper.functionType(*underlyingType, definedType)});
members->second.emplace("rep", TypeMember{helper.functionType(definedType, *underlyingType)});
annotation().underlyingTypes[constructor] = *underlyingType;
}
if (helper.isPrimitiveType(definedType, PrimitiveType::Pair))
{
solAssert(isBuiltIn);
solAssert(arguments.size() == 2);
members->second.emplace("first", TypeMember{helper.functionType(definedType, arguments[0])});
members->second.emplace("second", TypeMember{helper.functionType(definedType, arguments[1])});
}
return false;
}
bool TypeInference::visit(FunctionCall const&) { return true; }
void TypeInference::endVisit(FunctionCall const& _functionCall)
{
auto& functionCallAnnotation = annotation(_functionCall);
solAssert(!functionCallAnnotation.type);
Type functionType = type(_functionCall.expression());
TypeSystemHelpers helper{m_typeSystem};
std::vector<Type> argTypes;
for (auto arg: _functionCall.arguments())
{
switch (m_expressionContext)
{
case ExpressionContext::Term:
case ExpressionContext::Type:
argTypes.emplace_back(type(*arg));
break;
case ExpressionContext::Sort:
m_errorReporter.typeError(9173_error, _functionCall.location(), "Function call in sort context.");
functionCallAnnotation.type = m_typeSystem.freshTypeVariable({});
break;
}
}
switch (m_expressionContext)
{
case ExpressionContext::Term:
{
Type argTuple = helper.tupleType(argTypes);
Type resultType = m_typeSystem.freshTypeVariable({});
Type genericFunctionType = helper.functionType(argTuple, resultType);
unify(functionType, genericFunctionType, _functionCall.location());
functionCallAnnotation.type = resultType;
break;
}
case ExpressionContext::Type:
{
Type argTuple = helper.tupleType(argTypes);
Type resultType = m_typeSystem.freshTypeVariable({});
Type genericFunctionType = helper.typeFunctionType(argTuple, resultType);
unify(functionType, genericFunctionType, _functionCall.location());
functionCallAnnotation.type = resultType;
break;
}
case ExpressionContext::Sort:
solAssert(false);
}
}
// TODO: clean up rational parsing
namespace
{
std::optional<rational> parseRational(std::string const& _value)
{
rational value;
try
{
auto radixPoint = find(_value.begin(), _value.end(), '.');
if (radixPoint != _value.end())
{
if (
!all_of(radixPoint + 1, _value.end(), util::isDigit) ||
!all_of(_value.begin(), radixPoint, util::isDigit)
)
return std::nullopt;
// 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(std::string(fractionalBegin, _value.end()));
denominator /= boost::multiprecision::pow(
bigint(10),
static_cast<unsigned>(distance(radixPoint + 1, _value.end()))
);
numerator = bigint(std::string(_value.begin(), radixPoint));
value = numerator + denominator;
}
else
value = bigint(_value);
return value;
}
catch (...)
{
return std::nullopt;
}
}
/// 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);
}
std::optional<rational> rationalValue(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.
std::optional<rational> mantissa = parseRational(std::string(valueString.begin(), expPoint));
if (!mantissa)
return std::nullopt;
value = *mantissa;
// 0E... is always zero.
if (value == 0)
return std::nullopt;
bigint exp = bigint(std::string(expPoint + 1, valueString.end()));
if (exp > std::numeric_limits<int32_t>::max() || exp < std::numeric_limits<int32_t>::min())
return std::nullopt;
uint32_t expAbs = bigint(abs(exp)).convert_to<uint32_t>();
if (exp < 0)
{
if (!fitsPrecisionBase10(abs(value.denominator()), expAbs))
return std::nullopt;
value /= boost::multiprecision::pow(
bigint(10),
expAbs