From dcd410efd490f90b49bc6768d94104d226154167 Mon Sep 17 00:00:00 2001 From: Chloe Stefantsova Date: Mon, 20 Jan 2025 01:58:43 -0800 Subject: [PATCH] [analyzer][cfe] Remove TypeStructure variable from shared classes Part of https://github.com/dart-lang/sdk/issues/54902 Change-Id: Ia70f2afd321e9b4a4762b6ed860611dee1399d87 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404622 Reviewed-by: Paul Berry Commit-Queue: Chloe Stefantsova --- .../lib/src/flow_analysis/flow_analysis.dart | 2 +- .../type_inference/shared_inference_log.dart | 70 +-- .../type_inference/type_analysis_result.dart | 110 ++-- .../lib/src/type_inference/type_analyzer.dart | 520 +++++++-------- .../type_analyzer_operations.dart | 594 +++++++----------- .../src/type_inference/type_constraint.dart | 194 ++---- .../lib/src/types/shared_type.dart | 240 +++---- .../flow_analysis/flow_analysis_mini_ast.dart | 43 +- .../flow_analysis/flow_analysis_test.dart | 408 ++++++------ pkg/_fe_analyzer_shared/test/mini_ast.dart | 556 ++++++++-------- .../test/mini_type_constraint_gatherer.dart | 25 +- pkg/_fe_analyzer_shared/test/mini_types.dart | 36 +- pkg/analyzer/lib/dart/element/type.dart | 5 +- pkg/analyzer/lib/src/dart/ast/ast.dart | 37 +- .../lib/src/dart/element/element.dart | 6 +- .../src/dart/element/generic_inferrer.dart | 6 +- pkg/analyzer/lib/src/dart/element/type.dart | 25 +- .../element/type_constraint_gatherer.dart | 85 +-- .../lib/src/dart/element/type_schema.dart | 3 +- .../assignment_expression_resolver.dart | 5 +- .../resolver/binary_expression_resolver.dart | 4 +- .../dart/resolver/flow_analysis_visitor.dart | 147 ++--- .../dart/resolver/invocation_inferrer.dart | 6 +- .../dart/resolver/list_pattern_resolver.dart | 2 +- .../resolver/record_literal_resolver.dart | 2 +- .../dart/resolver/shared_type_analyzer.dart | 33 +- .../src/error/bool_expression_verifier.dart | 6 +- .../generated/error_detection_helpers.dart | 19 +- .../lib/src/generated/error_verifier.dart | 2 +- .../lib/src/generated/inference_log.dart | 11 +- pkg/analyzer/lib/src/generated/resolver.dart | 126 ++-- .../type_constraint_generation_test.dart | 7 +- .../lib/src/kernel/internal_ast.dart | 2 +- .../src/type_inference/inference_visitor.dart | 211 +++---- .../inference_visitor_base.dart | 32 +- .../type_inference/shared_type_analyzer.dart | 24 +- .../type_constraint_gatherer.dart | 38 +- .../type_inference/type_inference_engine.dart | 126 ++-- .../lib/src/type_inference/type_inferrer.dart | 9 +- .../lib/src/type_inference/type_schema.dart | 3 +- .../type_schema_environment.dart | 34 +- .../type_constraint_generation_test.dart | 14 +- .../type_constraint_gatherer_nnbd_test.dart | 8 +- .../type_constraint_gatherer_test.dart | 8 +- pkg/kernel/lib/ast.dart | 20 +- pkg/kernel/lib/src/ast/types.dart | 32 +- 46 files changed, 1658 insertions(+), 2238 deletions(-) diff --git a/pkg/_fe_analyzer_shared/lib/src/flow_analysis/flow_analysis.dart b/pkg/_fe_analyzer_shared/lib/src/flow_analysis/flow_analysis.dart index 4e2645383628..7f00e8a66447 100644 --- a/pkg/_fe_analyzer_shared/lib/src/flow_analysis/flow_analysis.dart +++ b/pkg/_fe_analyzer_shared/lib/src/flow_analysis/flow_analysis.dart @@ -5336,7 +5336,7 @@ class _FlowAnalysisImpl extends State { /// This class defines methods that the analyzer or CFE can use to instrument /// their type inference logic. The implementations are found in /// [SharedInferenceLogWriterImpl]. -abstract interface class SharedInferenceLogWriter< - TypeStructure extends SharedTypeStructure, - Type extends SharedTypeStructure, - TypeParameterStructure extends SharedTypeParameterStructure< - TypeStructure>> { +abstract interface class SharedInferenceLogWriter { /// If [inProgress] is `true`, verifies that generic type inference is in /// progress; otherwise, verifies that generic type inference is not in /// progress. @@ -150,18 +146,18 @@ abstract interface class SharedInferenceLogWriter< /// Called when generic type inference starts collecting constraints by /// attempting to match one type schema against another. - void enterConstraintGeneration( - ConstraintGenerationSource source, Type p, Type q); + void enterConstraintGeneration(ConstraintGenerationSource source, + covariant SharedType p, covariant SharedType q); /// Called when type inference begins inferring a collection element. void enterElement(Object node); /// Called when type inference begins inferring an expression. - void enterExpression(Object node, Type contextType); + void enterExpression(Object node, covariant SharedType contextType); /// Called when type inference begins inferring an AST node associated with /// extension override syntax. - void enterExtensionOverride(Object node, Type contextType); + void enterExtensionOverride(Object node, covariant SharedType contextType); /// Called when type inference has discovered that a construct that uses /// method invocation syntax (e.g. `x.f()`) is actually an invocation of a @@ -172,7 +168,7 @@ abstract interface class SharedInferenceLogWriter< /// Called when generic type inference begins. void enterGenericInference( - List typeFormals, Type template); + List typeFormals, covariant SharedType template); /// Called when type inference begins inferring the left hand side of an /// assignment. @@ -202,7 +198,9 @@ abstract interface class SharedInferenceLogWriter< /// Called when generic type inference ends. void exitGenericInference( - {bool aborted = false, bool failed = false, List? finalTypes}); + {bool aborted = false, + bool failed = false, + covariant List? finalTypes}); /// Called when type inference has finished inferring the left hand side of an /// assignment. @@ -236,26 +234,23 @@ abstract interface class SharedInferenceLogWriter< /// Records a constraint that was generated during the process of matching one /// type schema to another. - void recordGeneratedConstraint( - TypeParameterStructure parameter, - MergedTypeConstraint - constraint); + void recordGeneratedConstraint(SharedTypeParameter parameter, + MergedTypeConstraint constraint); /// Records that type inference has resolved a method name. void recordLookupResult( {required Object expression, - required Type type, + required SharedType type, required Object? target, required String methodName}); /// Records the preliminary types chosen during either a downwards or a /// horizontal inference step. - void recordPreliminaryTypes(List types); + void recordPreliminaryTypes(List types); /// Called when type inference is inferring an expression, and assigns the /// expression a static type. - void recordStaticType(Object expression, Type type); + void recordStaticType(Object expression, SharedType type); } /// Implementation of the interface log writer. @@ -267,13 +262,8 @@ abstract interface class SharedInferenceLogWriter< /// from classes derived from [SharedInferenceLogWriterImpl], but these methods /// are not exposed in [SharedInferenceLogWriter] so that they won't be called /// accidentally on their own. -abstract class SharedInferenceLogWriterImpl< - TypeStructure extends SharedTypeStructure, - Type extends SharedTypeStructure, - TypeParameterStructure extends SharedTypeParameterStructure< - TypeStructure>> - implements - SharedInferenceLogWriter { +abstract class SharedInferenceLogWriterImpl + implements SharedInferenceLogWriter { /// A stack of [State] objects representing the calls that have been made to /// `enter...` methods without any matched `exit...` method. /// @@ -403,7 +393,7 @@ abstract class SharedInferenceLogWriterImpl< @override void enterConstraintGeneration( - ConstraintGenerationSource source, Type p, Type q) { + ConstraintGenerationSource source, SharedType p, SharedType q) { checkCall( method: 'enterConstraintGeneration', arguments: [source, p, q], @@ -425,7 +415,7 @@ abstract class SharedInferenceLogWriterImpl< } @override - void enterExpression(Object node, Type contextType) { + void enterExpression(Object node, SharedType contextType) { pushState(new ExpressionState( writer: this, message: 'INFER EXPRESSION ${describe(node)} IN CONTEXT $contextType', @@ -433,7 +423,7 @@ abstract class SharedInferenceLogWriterImpl< } @override - void enterExtensionOverride(Object node, Type contextType) { + void enterExtensionOverride(Object node, SharedType contextType) { pushState(new State( kind: StateKind.extensionOverride, writer: this, @@ -452,13 +442,12 @@ abstract class SharedInferenceLogWriterImpl< @override void enterGenericInference( - List typeFormals, Type template) { + List typeFormals, SharedType template) { if (state.kind == StateKind.genericInference) { fail('Tried to start generic inference when already in progress'); } String typeFormalNames = [ - for (TypeParameterStructure typeFormal in typeFormals) - typeFormal.displayName + for (SharedTypeParameter typeFormal in typeFormals) typeFormal.displayName ].join(', '); pushState(new GenericInferenceState( writer: this, @@ -548,7 +537,9 @@ abstract class SharedInferenceLogWriterImpl< @override void exitGenericInference( - {bool aborted = false, bool failed = false, List? finalTypes}) { + {bool aborted = false, + bool failed = false, + List? finalTypes}) { if ((aborted ? 1 : 0) + (failed ? 1 : 0) + (finalTypes != null ? 1 : 0) != 1) { fail('Must specify exactly one of aborted=true, failed=true, ' @@ -677,11 +668,8 @@ abstract class SharedInferenceLogWriterImpl< } @override - void recordGeneratedConstraint( - TypeParameterStructure parameter, - MergedTypeConstraint - constraint) { + void recordGeneratedConstraint(SharedTypeParameter parameter, + MergedTypeConstraint constraint) { checkCall( method: 'recordGeneratedConstraint', arguments: [parameter, constraint], @@ -694,7 +682,7 @@ abstract class SharedInferenceLogWriterImpl< @override void recordLookupResult( {required Object expression, - required Type type, + required SharedType type, required Object? target, required String methodName}) { checkCall( @@ -713,7 +701,7 @@ abstract class SharedInferenceLogWriterImpl< } @override - void recordPreliminaryTypes(List types) { + void recordPreliminaryTypes(List types) { checkCall( method: 'recordPreliminaryTypes', arguments: [types], @@ -727,7 +715,7 @@ abstract class SharedInferenceLogWriterImpl< } @override - void recordStaticType(Object expression, Type type) { + void recordStaticType(Object expression, SharedType type) { checkCall( method: 'recordStaticType', arguments: [expression, type], diff --git a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analysis_result.dart b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analysis_result.dart index d6f3592acddd..1b4c62c7a2e8 100644 --- a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analysis_result.dart +++ b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analysis_result.dart @@ -7,9 +7,7 @@ import 'type_analyzer.dart'; /// Result for analyzing an assigned variable pattern in /// [TypeAnalyzer.analyzeAssignedVariablePattern]. -class AssignedVariablePatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class AssignedVariablePatternResult extends PatternResult { /// Error for when a variable was assigned multiple times within a pattern. final Error? duplicateAssignmentPatternVariableError; @@ -25,11 +23,9 @@ class AssignedVariablePatternResult< /// Result for analyzing a constant pattern in /// [TypeAnalyzer.analyzeConstantPattern]. -class ConstantPatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class ConstantPatternResult extends PatternResult { /// The static type of the constant expression. - final SharedTypeView expressionType; + final SharedTypeView expressionType; /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -47,11 +43,9 @@ class ConstantPatternResult< /// Result for analyzing a declared variable pattern in /// [TypeAnalyzer.analyzeDeclaredVariablePattern]. -class DeclaredVariablePatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class DeclaredVariablePatternResult extends PatternResult { /// The static type of the variable. - final SharedTypeView staticType; + final SharedTypeView staticType; /// Error for when the matched value type is not assignable to the static /// type in an irrefutable context. @@ -68,10 +62,9 @@ class DeclaredVariablePatternResult< /// This class keeps track of the type of the expression. Derived classes expose /// other results of type analysis that are specific to certain expression /// types. -class ExpressionTypeAnalysisResult< - TypeStructure extends SharedTypeStructure> { +class ExpressionTypeAnalysisResult { /// The static type of the expression. - final SharedTypeView type; + final SharedTypeView type; ExpressionTypeAnalysisResult({required this.type}); } @@ -79,16 +72,15 @@ class ExpressionTypeAnalysisResult< /// Result for analyzing an if-case statement or element in /// [TypeAnalyzer.analyzeIfCaseStatement] and /// [TypeAnalyzer.analyzeIfCaseElement]. -class IfCaseStatementResult< - TypeStructure extends SharedTypeStructure, Error> { +class IfCaseStatementResult { /// The static type of the matched expression. - final SharedTypeView matchedExpressionType; + final SharedTypeView matchedExpressionType; /// Error for when the guard has a non-bool type. final Error? nonBooleanGuardError; /// The type of the guard expression, if present. - final SharedTypeView? guardType; + final SharedTypeView? guardType; IfCaseStatementResult( {required this.matchedExpressionType, @@ -97,9 +89,7 @@ class IfCaseStatementResult< } /// Container for the result of running type analysis on an integer literal. -class IntTypeAnalysisResult< - TypeStructure extends SharedTypeStructure> - extends ExpressionTypeAnalysisResult { +class IntTypeAnalysisResult extends ExpressionTypeAnalysisResult { /// Whether the integer literal was converted to a double. final bool convertedToDouble; @@ -107,11 +97,9 @@ class IntTypeAnalysisResult< } /// Result for analyzing a list pattern in [TypeAnalyzer.analyzeListPattern]. -class ListPatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class ListPatternResult extends PatternResult { /// The required type of the list pattern. - final SharedTypeView requiredType; + final SharedTypeView requiredType; /// Errors for when multiple rest patterns occurred within the list pattern. /// @@ -133,9 +121,7 @@ class ListPatternResult< /// Result for analyzing a logical or pattern in /// [TypeAnalyzer.analyzeLogicalOrPattern]. -class LogicalOrPatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class LogicalOrPatternResult extends PatternResult { /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -145,10 +131,9 @@ class LogicalOrPatternResult< } /// Result for analyzing a map pattern in [TypeAnalyzer.analyzeMapPattern]. -class MapPatternResult, - Error> extends PatternResult { +class MapPatternResult extends PatternResult { /// The required type of the map pattern. - final SharedTypeView requiredType; + final SharedTypeView requiredType; /// Error for when the matched value type is not assignable to the required /// type in an irrefutable context. @@ -258,9 +243,7 @@ class MatchContext, - Error> extends PatternResult { +class NullCheckOrAssertPatternResult extends PatternResult { /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -275,11 +258,9 @@ class NullCheckOrAssertPatternResult< /// Result for analyzing an object pattern in /// [TypeAnalyzer.analyzeObjectPattern]. -class ObjectPatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class ObjectPatternResult extends PatternResult { /// The required type of the object pattern. - final SharedTypeView requiredType; + final SharedTypeView requiredType; /// Errors for when the same property name was used multiple times in the /// object pattern. @@ -301,11 +282,9 @@ class ObjectPatternResult< } /// Container for the result of running type analysis on a pattern assignment. -class PatternAssignmentAnalysisResult< - TypeStructure extends SharedTypeStructure> - extends ExpressionTypeAnalysisResult { +class PatternAssignmentAnalysisResult extends ExpressionTypeAnalysisResult { /// The type schema of the pattern on the left hand size of the assignment. - final SharedTypeSchemaView patternSchema; + final SharedTypeSchemaView patternSchema; PatternAssignmentAnalysisResult({ required this.patternSchema, @@ -315,13 +294,12 @@ class PatternAssignmentAnalysisResult< /// Result for analyzing a pattern-for-in statement or element in /// [TypeAnalyzer.analyzePatternForIn]. -class PatternForInResult< - TypeStructure extends SharedTypeStructure, Error> { +class PatternForInResult { /// The static type of the elements of the for in expression. - final SharedTypeView elementType; + final SharedTypeView elementType; /// The static type of the collection of elements of the for in expression. - final SharedTypeView expressionType; + final SharedTypeView expressionType; /// Error for when the expression is not an iterable. final Error? patternForInExpressionIsNotIterableError; @@ -333,22 +311,21 @@ class PatternForInResult< } /// Result for analyzing a pattern in [TypeAnalyzer]. -class PatternResult> { +class PatternResult { /// The matched value type that was used to type check the pattern. - final SharedTypeView matchedValueType; + final SharedTypeView matchedValueType; PatternResult({required this.matchedValueType}); } /// Container for the result of running type analysis on a pattern variable /// declaration. -class PatternVariableDeclarationAnalysisResult< - TypeStructure extends SharedTypeStructure> { +class PatternVariableDeclarationAnalysisResult { /// The type schema of the pattern on the left hand size of the declaration. - final SharedTypeSchemaView patternSchema; + final SharedTypeSchemaView patternSchema; /// The type of the initializer expression. - final SharedTypeView initializerType; + final SharedTypeView initializerType; PatternVariableDeclarationAnalysisResult({ required this.patternSchema, @@ -358,11 +335,9 @@ class PatternVariableDeclarationAnalysisResult< /// Result for analyzing a record pattern in /// [TypeAnalyzer.analyzeRecordPattern]. -class RecordPatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class RecordPatternResult extends PatternResult { /// The required type of the record pattern. - final SharedTypeView requiredType; + final SharedTypeView requiredType; /// Errors for when the same property name was used multiple times in the /// record pattern. @@ -385,11 +360,9 @@ class RecordPatternResult< /// Result for analyzing a relational pattern in /// [TypeAnalyzer.analyzeRelationalPattern]. -class RelationalPatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class RelationalPatternResult extends PatternResult { /// The static type of the operand. - final SharedTypeView operandType; + final SharedTypeView operandType; /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -411,9 +384,7 @@ class RelationalPatternResult< /// Result for analyzing a switch expression in /// [TypeAnalyzer.analyzeSwitchExpression]. -class SwitchExpressionResult< - TypeStructure extends SharedTypeStructure, - Error> extends ExpressionTypeAnalysisResult { +class SwitchExpressionResult extends ExpressionTypeAnalysisResult { /// Errors for non-bool guards. /// /// The key is the case index of the erroneous guard. @@ -426,7 +397,7 @@ class SwitchExpressionResult< /// The key is the case index of the guard. /// /// This is `null` if no such guards where present. - final Map>? guardTypes; + final Map? guardTypes; SwitchExpressionResult( {required super.type, @@ -435,8 +406,7 @@ class SwitchExpressionResult< } /// Container for the result of running type analysis on an integer literal. -class SwitchStatementTypeAnalysisResult< - TypeStructure extends SharedTypeStructure, Error> { +class SwitchStatementTypeAnalysisResult { /// Whether the switch statement had a `default` clause. final bool hasDefault; @@ -455,7 +425,7 @@ class SwitchStatementTypeAnalysisResult< final bool requiresExhaustivenessValidation; /// The static type of the scrutinee expression. - final SharedTypeView scrutineeType; + final SharedTypeView scrutineeType; /// Errors for the cases that don't complete normally. /// @@ -474,7 +444,7 @@ class SwitchStatementTypeAnalysisResult< /// The keys of the maps are case and head indices of the guard. /// /// This is `null` if no such guards where present. - final Map>>? guardTypes; + final Map>? guardTypes; SwitchStatementTypeAnalysisResult({ required this.hasDefault, @@ -502,9 +472,7 @@ enum UnnecessaryWildcardKind { /// Result for analyzing a wildcard pattern /// [TypeAnalyzer.analyzeWildcardPattern]. -class WildcardPatternResult< - TypeStructure extends SharedTypeStructure, - Error> extends PatternResult { +class WildcardPatternResult extends PatternResult { /// Error for when the matched value type is not assignable to the wildcard /// type in an irrefutable context. final Error? patternTypeMismatchInIrrefutableContextError; diff --git a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer.dart b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer.dart index 89fa45fdbdf8..992fa7565db0 100644 --- a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer.dart +++ b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer.dart @@ -131,11 +131,10 @@ enum RelationalOperatorKind { } /// Information about a relational operator. -class RelationalOperatorResolution< - TypeStructure extends SharedTypeStructure> { +class RelationalOperatorResolution { final RelationalOperatorKind kind; - final SharedTypeView parameterType; - final SharedTypeView returnType; + final SharedTypeView parameterType; + final SharedTypeView returnType; RelationalOperatorResolution({ required this.kind, @@ -263,31 +262,24 @@ class SwitchStatementMemberInfo, Node extends Object, Statement extends Node, Expression extends Node, Variable extends Object, Pattern extends Node, Error, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, TypeDeclarationType extends Object, TypeDeclaration extends Object> - implements - TypeAnalysisNullShortingInterface> { - TypeAnalyzerErrors, Pattern, Error> get errors; + implements TypeAnalysisNullShortingInterface { + TypeAnalyzerErrors get errors; @override - FlowAnalysis> get flow; + FlowAnalysis get flow; @override - TypeAnalyzerOperations get operations; + TypeAnalyzerOperations + get operations; /// Options affecting the behavior of [TypeAnalyzer]. TypeAnalyzerOptions get options; @@ -305,14 +297,11 @@ mixin TypeAnalyzer< /// [analyzeDeclaredVariablePattern] should be used instead. /// /// Stack effect: none. - AssignedVariablePatternResult - analyzeAssignedVariablePattern( - MatchContext, - Variable> - context, - Pattern node, - Variable variable) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + AssignedVariablePatternResult analyzeAssignedVariablePattern( + MatchContext context, + Pattern node, + Variable variable) { + SharedTypeView matchedValueType = flow.getMatchedValueType(); Error? duplicateAssignmentPatternVariableError; Map? assignedVariables = context.assignedVariables; if (assignedVariables != null) { @@ -329,15 +318,14 @@ mixin TypeAnalyzer< } } - SharedTypeView variableDeclaredType = - operations.variableType(variable); + SharedTypeView variableDeclaredType = operations.variableType(variable); Node? irrefutableContext = context.irrefutableContext; assert(irrefutableContext != null, 'Assigned variables must only appear in irrefutable pattern contexts'); Error? patternTypeMismatchInIrrefutableContextError; if (irrefutableContext != null && - matchedValueType is! SharedDynamicTypeStructure && - matchedValueType is! SharedInvalidTypeStructure && + matchedValueType is! SharedDynamicType && + matchedValueType is! SharedInvalidType && !operations.isSubtypeOf(matchedValueType, variableDeclaredType)) { patternTypeMismatchInIrrefutableContextError = errors.patternTypeMismatchInIrrefutableContext( @@ -359,7 +347,7 @@ mixin TypeAnalyzer< /// Computes the type schema for a variable pattern appearing in an assignment /// context. [variable] is the variable being referenced. - SharedTypeSchemaView analyzeAssignedVariablePatternSchema( + SharedTypeSchemaView analyzeAssignedVariablePatternSchema( Variable variable) => operations.typeToSchema( flow.promotedType(variable) ?? operations.variableType(variable)); @@ -370,21 +358,20 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern innerPattern). - PatternResult analyzeCastPattern({ - required MatchContext, Variable> + PatternResult analyzeCastPattern({ + required MatchContext context, required Pattern pattern, required Pattern innerPattern, - required SharedTypeView requiredType, + required SharedTypeView requiredType, }) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); flow.promoteForPattern( matchedType: matchedValueType, knownType: requiredType, matchFailsIfWrongType: false); if (operations.isSubtypeOf(matchedValueType, requiredType) && - requiredType is! SharedInvalidTypeStructure) { + requiredType is! SharedInvalidType) { errors.matchedTypeIsSubtypeOfRequired( pattern: pattern, matchedType: matchedValueType, @@ -407,8 +394,7 @@ mixin TypeAnalyzer< /// Computes the type schema for a cast pattern. /// /// Stack effect: none. - SharedTypeSchemaView analyzeCastPatternSchema() => - operations.unknownType; + SharedTypeSchemaView analyzeCastPatternSchema() => operations.unknownType; /// Analyzes a constant pattern. [node] is the pattern itself, and /// [expression] is the constant expression. Depending on the client's @@ -420,13 +406,11 @@ mixin TypeAnalyzer< /// and information about reported errors. /// /// Stack effect: pushes (Expression). - ConstantPatternResult analyzeConstantPattern( - MatchContext, - Variable> - context, + ConstantPatternResult analyzeConstantPattern( + MatchContext context, Node node, Expression expression) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () Node? irrefutableContext = context.irrefutableContext; Error? refutablePatternInIrrefutableContextError; @@ -435,7 +419,7 @@ mixin TypeAnalyzer< errors.refutablePatternInIrrefutableContext( pattern: node, context: irrefutableContext); } - SharedTypeView expressionType = analyzeExpression( + SharedTypeView expressionType = analyzeExpression( expression, operations.typeToSchema(matchedValueType)); flow.constantPattern_end(expression, expressionType, patternsEnabled: options.patternsEnabled, @@ -470,7 +454,7 @@ mixin TypeAnalyzer< /// Computes the type schema for a constant pattern. /// /// Stack effect: none. - SharedTypeSchemaView analyzeConstantPatternSchema() { + SharedTypeSchemaView analyzeConstantPatternSchema() { // Constant patterns are only allowed in refutable contexts, and refutable // contexts don't propagate a type schema into the scrutinee. So this // code path is only reachable if the user's code contains errors. @@ -491,24 +475,21 @@ mixin TypeAnalyzer< /// variable (possibly inferred) and information about reported errors. /// /// Stack effect: none. - DeclaredVariablePatternResult - analyzeDeclaredVariablePattern( - MatchContext, - Variable> - context, + DeclaredVariablePatternResult analyzeDeclaredVariablePattern( + MatchContext context, Pattern node, Variable variable, String variableName, - SharedTypeView? declaredType, + SharedTypeView? declaredType, ) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); - SharedTypeView staticType = + SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView staticType = declaredType ?? variableTypeFromInitializerType(matchedValueType); Node? irrefutableContext = context.irrefutableContext; Error? patternTypeMismatchInIrrefutableContextError; if (irrefutableContext != null && - matchedValueType is! SharedDynamicTypeStructure && - matchedValueType is! SharedInvalidTypeStructure && + matchedValueType is! SharedDynamicType && + matchedValueType is! SharedInvalidType && !operations.isSubtypeOf(matchedValueType, staticType)) { patternTypeMismatchInIrrefutableContextError = errors.patternTypeMismatchInIrrefutableContext( @@ -522,8 +503,7 @@ mixin TypeAnalyzer< // The promotion may have made the matched type even more specific than // either `matchedType` or `staticType`, so fetch it again and use that // in the call to `declaredVariablePattern` below. - SharedTypeView promotedValueType = - flow.getMatchedValueType(); + SharedTypeView promotedValueType = flow.getMatchedValueType(); bool isImplicitlyTyped = declaredType == null; // TODO(paulberry): are we handling _isFinal correctly? int promotionKey = context.patternVariablePromotionKeys[variableName] = @@ -548,8 +528,8 @@ mixin TypeAnalyzer< /// declared type (if present). /// /// Stack effect: none. - SharedTypeSchemaView analyzeDeclaredVariablePatternSchema( - SharedTypeView? declaredType) { + SharedTypeSchemaView analyzeDeclaredVariablePatternSchema( + SharedTypeView? declaredType) { return declaredType == null ? operations.unknownType : operations.typeToSchema(declaredType); @@ -567,22 +547,20 @@ mixin TypeAnalyzer< /// [node] will be allowed to continue into the containing expression. /// /// Stack effect: pushes (Expression). - SharedTypeView analyzeExpression( - Expression node, SharedTypeSchemaView schema, + SharedTypeView analyzeExpression(Expression node, SharedTypeSchemaView schema, {bool continueNullShorting = false}) { int? nullShortingTargetDepth; if (!continueNullShorting) nullShortingTargetDepth = nullShortingDepth; // Stack: () - if (schema is SharedDynamicTypeSchemaView) { + if (schema is SharedDynamicTypeSchemaView) { schema = operations.unknownType; } - ExpressionTypeAnalysisResult result = - dispatchExpression(node, schema); + ExpressionTypeAnalysisResult result = dispatchExpression(node, schema); // Stack: (Expression) if (operations.isNever(result.type)) { flow.handleExit(); } - SharedTypeView type = result.type; + SharedTypeView type = result.type; if (nullShortingTargetDepth != null && nullShortingDepth > nullShortingTargetDepth) { type = finishNullShorting(nullShortingTargetDepth, type); @@ -610,7 +588,7 @@ mixin TypeAnalyzer< /// `else` clause, the representation for `ifFalse` will be pushed by /// [handleNoCollectionElement]. If there is no guard, the representation /// for `guard` will be pushed by [handleNoGuard]. - IfCaseStatementResult analyzeIfCaseElement({ + IfCaseStatementResult analyzeIfCaseElement({ required Node node, required Expression expression, required Pattern pattern, @@ -622,7 +600,7 @@ mixin TypeAnalyzer< }) { // Stack: () flow.ifCaseStatement_begin(); - SharedTypeView initializerType = + SharedTypeView initializerType = analyzeExpression(expression, operations.unknownType); flow.ifCaseStatement_afterExpression(expression, initializerType); // Stack: (Expression) @@ -630,8 +608,7 @@ mixin TypeAnalyzer< Map patternVariablePromotionKeys = {}; // TODO(paulberry): rework handling of isFinal dispatchPattern( - new MatchContext, - Variable>( + new MatchContext( isFinal: false, componentVariables: componentVariables, patternVariablePromotionKeys: patternVariablePromotionKeys, @@ -643,7 +620,7 @@ mixin TypeAnalyzer< variables, componentVariables, patternVariablePromotionKeys, location: JoinedPatternVariableLocation.singlePattern); Error? nonBooleanGuardError; - SharedTypeView? guardType; + SharedTypeView? guardType; if (guard != null) { guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); @@ -675,7 +652,7 @@ mixin TypeAnalyzer< /// representation for `ifFalse` will be pushed by [handleNoStatement]. If /// there is no guard, the representation for `guard` will be pushed by /// [handleNoGuard]. - IfCaseStatementResult analyzeIfCaseStatement( + IfCaseStatementResult analyzeIfCaseStatement( Statement node, Expression expression, Pattern pattern, @@ -686,7 +663,7 @@ mixin TypeAnalyzer< ) { // Stack: () flow.ifCaseStatement_begin(); - SharedTypeView initializerType = + SharedTypeView initializerType = analyzeExpression(expression, operations.unknownType); flow.ifCaseStatement_afterExpression(expression, initializerType); // Stack: (Expression) @@ -694,8 +671,7 @@ mixin TypeAnalyzer< Map patternVariablePromotionKeys = {}; // TODO(paulberry): rework handling of isFinal dispatchPattern( - new MatchContext, - Variable>( + new MatchContext( isFinal: false, componentVariables: componentVariables, patternVariablePromotionKeys: patternVariablePromotionKeys, @@ -713,7 +689,7 @@ mixin TypeAnalyzer< handle_ifCaseStatement_afterPattern(node: node); // Stack: (Expression, Pattern) Error? nonBooleanGuardError; - SharedTypeView? guardType; + SharedTypeView? guardType; if (guard != null) { guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); @@ -781,15 +757,14 @@ mixin TypeAnalyzer< /// Analyzes an integer literal, given the type schema [schema]. /// /// Stack effect: none. - IntTypeAnalysisResult analyzeIntLiteral( - SharedTypeSchemaView schema) { + IntTypeAnalysisResult analyzeIntLiteral(SharedTypeSchemaView schema) { bool convertToDouble = !operations.isTypeSchemaSatisfied( type: operations.intType, typeSchema: schema) && operations.isTypeSchemaSatisfied( type: operations.doubleType, typeSchema: schema); - SharedTypeView type = + SharedTypeView type = convertToDouble ? operations.doubleType : operations.intType; - return new IntTypeAnalysisResult( + return new IntTypeAnalysisResult( type: type, convertedToDouble: convertToDouble); } @@ -803,31 +778,29 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * Pattern) where n = elements.length. - ListPatternResult analyzeListPattern( - MatchContext, - Variable> - context, + ListPatternResult analyzeListPattern( + MatchContext context, Pattern node, - {SharedTypeView? elementType, + {SharedTypeView? elementType, required List elements}) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); - SharedTypeView valueType; + SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView valueType; if (elementType != null) { valueType = elementType; } else { - SharedTypeView? listElementType = + SharedTypeView? listElementType = operations.matchListType(matchedValueType); if (listElementType != null) { valueType = listElementType; - } else if (matchedValueType is SharedDynamicTypeStructure) { + } else if (matchedValueType is SharedDynamicType) { valueType = operations.dynamicType; - } else if (matchedValueType is SharedInvalidTypeStructure) { + } else if (matchedValueType is SharedInvalidType) { valueType = operations.errorType; } else { valueType = operations.objectQuestionType; } } - SharedTypeView requiredType = operations.listType(valueType); + SharedTypeView requiredType = operations.listType(valueType); flow.promoteForPattern( matchedType: matchedValueType, knownType: requiredType, @@ -849,7 +822,7 @@ mixin TypeAnalyzer< previousRestPattern = element; Pattern? subPattern = getRestPatternElementPattern(element); if (subPattern != null) { - SharedTypeView subPatternMatchedType = requiredType; + SharedTypeView subPatternMatchedType = requiredType; flow.pushSubpattern(subPatternMatchedType); dispatchPattern( context.withUnnecessaryWildcardKind(null), subPattern); @@ -887,8 +860,8 @@ mixin TypeAnalyzer< /// subpatterns. /// /// Stack effect: none. - SharedTypeSchemaView analyzeListPatternSchema({ - required SharedTypeView? elementType, + SharedTypeSchemaView analyzeListPatternSchema({ + required SharedTypeView? elementType, required List elements, }) { if (elementType != null) { @@ -899,13 +872,13 @@ mixin TypeAnalyzer< return operations.listTypeSchema(operations.unknownType); } - SharedTypeSchemaView? currentGLB; + SharedTypeSchemaView? currentGLB; for (Node element in elements) { - SharedTypeSchemaView? typeToAdd; + SharedTypeSchemaView? typeToAdd; if (isRestPatternElement(element)) { Pattern? subPattern = getRestPatternElementPattern(element); if (subPattern != null) { - SharedTypeSchemaView subPatternType = + SharedTypeSchemaView subPatternType = dispatchPatternSchema(subPattern); typeToAdd = operations.matchIterableTypeSchema(subPatternType); } @@ -930,14 +903,12 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern left, Pattern right) - PatternResult analyzeLogicalAndPattern( - MatchContext, - Variable> - context, + PatternResult analyzeLogicalAndPattern( + MatchContext context, Pattern node, Node lhs, Node rhs) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () dispatchPattern( context.withUnnecessaryWildcardKind( @@ -960,8 +931,7 @@ mixin TypeAnalyzer< /// the left and right sides of the `&&` operator. /// /// Stack effect: none. - SharedTypeSchemaView analyzeLogicalAndPatternSchema( - Node lhs, Node rhs) { + SharedTypeSchemaView analyzeLogicalAndPatternSchema(Node lhs, Node rhs) { return operations.typeSchemaGlb( dispatchPatternSchema(lhs), dispatchPatternSchema(rhs)); } @@ -974,14 +944,12 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern left, Pattern right) - LogicalOrPatternResult analyzeLogicalOrPattern( - MatchContext, - Variable> - context, + LogicalOrPatternResult analyzeLogicalOrPattern( + MatchContext context, Pattern node, Node lhs, Node rhs) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); Node? irrefutableContext = context.irrefutableContext; Error? refutablePatternInIrrefutableContextError; if (irrefutableContext != null) { @@ -1053,8 +1021,7 @@ mixin TypeAnalyzer< /// the left and right sides of the `|` or `&` operator. /// /// Stack effect: none. - SharedTypeSchemaView analyzeLogicalOrPatternSchema( - Node lhs, Node rhs) { + SharedTypeSchemaView analyzeLogicalOrPatternSchema(Node lhs, Node rhs) { // Logical-or patterns are only allowed in refutable contexts, and // refutable contexts don't propagate a type schema into the scrutinee. // So this code path is only reachable if the user's code contains errors. @@ -1072,21 +1039,19 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * MapPatternElement) where n = elements.length. - MapPatternResult analyzeMapPattern( - MatchContext, - Variable> - context, + MapPatternResult analyzeMapPattern( + MatchContext context, Pattern node, { required ({ - SharedTypeView keyType, - SharedTypeView valueType + SharedTypeView keyType, + SharedTypeView valueType })? typeArguments, required List elements, }) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); - SharedTypeView keyType; - SharedTypeView valueType; - SharedTypeSchemaView keySchema; + SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView keyType; + SharedTypeView valueType; + SharedTypeSchemaView keySchema; if (typeArguments != null) { keyType = typeArguments.keyType; valueType = typeArguments.valueType; @@ -1097,11 +1062,11 @@ mixin TypeAnalyzer< keyType = typeArguments.keyType; valueType = typeArguments.valueType; keySchema = operations.typeToSchema(keyType); - } else if (matchedValueType is SharedDynamicTypeStructure) { + } else if (matchedValueType is SharedDynamicType) { keyType = operations.dynamicType; valueType = operations.dynamicType; keySchema = operations.unknownType; - } else if (matchedValueType is SharedInvalidTypeStructure) { + } else if (matchedValueType is SharedInvalidType) { keyType = operations.errorType; valueType = operations.errorType; keySchema = operations.unknownType; @@ -1111,7 +1076,7 @@ mixin TypeAnalyzer< keySchema = operations.unknownType; } } - SharedTypeView requiredType = operations.mapType( + SharedTypeView requiredType = operations.mapType( keyType: keyType, valueType: valueType, ); @@ -1134,8 +1099,7 @@ mixin TypeAnalyzer< Node element = elements[i]; MapPatternEntry? entry = getMapPatternEntry(element); if (entry != null) { - SharedTypeView keyType = - analyzeExpression(entry.key, keySchema); + SharedTypeView keyType = analyzeExpression(entry.key, keySchema); flow.pushSubpattern(valueType); dispatchPattern( context.withUnnecessaryWildcardKind(null), @@ -1188,10 +1152,10 @@ mixin TypeAnalyzer< /// subpatterns. /// /// Stack effect: none. - SharedTypeSchemaView analyzeMapPatternSchema({ + SharedTypeSchemaView analyzeMapPatternSchema({ required ({ - SharedTypeView keyType, - SharedTypeView valueType + SharedTypeView keyType, + SharedTypeView valueType })? typeArguments, required List elements, }) { @@ -1202,11 +1166,11 @@ mixin TypeAnalyzer< )); } - SharedTypeSchemaView? valueType; + SharedTypeSchemaView? valueType; for (Node element in elements) { MapPatternEntry? entry = getMapPatternEntry(element); if (entry != null) { - SharedTypeSchemaView entryValueType = + SharedTypeSchemaView entryValueType = dispatchPatternSchema(entry.value); if (valueType == null) { valueType = entryValueType; @@ -1231,15 +1195,12 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern innerPattern). - NullCheckOrAssertPatternResult - analyzeNullCheckOrAssertPattern( - MatchContext, - Variable> - context, - Pattern node, - Pattern innerPattern, - {required bool isAssert}) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + NullCheckOrAssertPatternResult analyzeNullCheckOrAssertPattern( + MatchContext context, + Pattern node, + Pattern innerPattern, + {required bool isAssert}) { + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () Error? refutablePatternInIrrefutableContextError; Error? matchedTypeIsStrictlyNonNullableError; @@ -1279,7 +1240,7 @@ mixin TypeAnalyzer< /// a null-check or a null-assert pattern. /// /// Stack effect: none. - SharedTypeSchemaView analyzeNullCheckOrAssertPatternSchema( + SharedTypeSchemaView analyzeNullCheckOrAssertPatternSchema( Pattern innerPattern, {required bool isAssert}) { if (isAssert) { @@ -1303,19 +1264,16 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * Pattern) where n = fields.length. - ObjectPatternResult analyzeObjectPattern( - MatchContext, - Variable> - context, + ObjectPatternResult analyzeObjectPattern( + MatchContext context, Pattern node, { required List> fields, }) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); Map? duplicateRecordPatternFieldErrors = _reportDuplicateRecordPatternFields(node, fields); - SharedTypeView requiredType = - downwardInferObjectPatternRequiredType( + SharedTypeView requiredType = downwardInferObjectPatternRequiredType( matchedType: matchedValueType, pattern: node, ); @@ -1324,9 +1282,9 @@ mixin TypeAnalyzer< // If the required type is `dynamic` or `Never`, then every getter is // treated as having the same type. - (Object?, SharedTypeView)? overridePropertyGetType; - if (requiredType is SharedDynamicTypeStructure || - requiredType is SharedInvalidTypeStructure || + (Object?, SharedTypeView)? overridePropertyGetType; + if (requiredType is SharedDynamicType || + requiredType is SharedInvalidType || operations.isNever(requiredType)) { overridePropertyGetType = (null, requiredType); } @@ -1346,23 +1304,20 @@ mixin TypeAnalyzer< // Stack: () for (RecordPatternField field in fields) { - var ( - Object? propertyMember, - SharedTypeView unpromotedPropertyType - ) = overridePropertyGetType ?? - resolveObjectPatternPropertyGet( - objectPattern: node, - receiverType: requiredType, - field: field, - ); + var (Object? propertyMember, SharedTypeView unpromotedPropertyType) = + overridePropertyGetType ?? + resolveObjectPatternPropertyGet( + objectPattern: node, + receiverType: requiredType, + field: field, + ); // Note: an object pattern field must always have a property name, but in // error recovery circumstances, one may be absent; when this happens, use // the empty string as a the property name to prevent a crash. String propertyName = field.name ?? ''; - SharedTypeView promotedPropertyType = - flow.pushPropertySubpattern( - propertyName, propertyMember, unpromotedPropertyType) ?? - unpromotedPropertyType; + SharedTypeView promotedPropertyType = flow.pushPropertySubpattern( + propertyName, propertyMember, unpromotedPropertyType) ?? + unpromotedPropertyType; if (operations.isNever(promotedPropertyType)) { flow.handleExit(); } @@ -1386,8 +1341,7 @@ mixin TypeAnalyzer< /// specified with the object name, and with the type arguments applied. /// /// Stack effect: none. - SharedTypeSchemaView analyzeObjectPatternSchema( - SharedTypeView type) { + SharedTypeSchemaView analyzeObjectPatternSchema(SharedTypeView type) { return operations.typeToSchema(type); } @@ -1397,20 +1351,17 @@ mixin TypeAnalyzer< /// the pattern, and [rhs] for the right hand side. /// /// Stack effect: pushes (Expression, Pattern). - PatternAssignmentAnalysisResult analyzePatternAssignment( + PatternAssignmentAnalysisResult analyzePatternAssignment( Expression node, Pattern pattern, Expression rhs) { // Stack: () - SharedTypeSchemaView patternSchema = - dispatchPatternSchema(pattern); - SharedTypeView rhsType = - analyzeExpression(rhs, patternSchema); + SharedTypeSchemaView patternSchema = dispatchPatternSchema(pattern); + SharedTypeView rhsType = analyzeExpression(rhs, patternSchema); // Stack: (Expression) flow.patternAssignment_afterRhs(rhs, rhsType); Map> componentVariables = {}; Map patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext, - Variable>( + new MatchContext( isFinal: false, irrefutableContext: node, assignedVariables: {}, @@ -1426,7 +1377,7 @@ mixin TypeAnalyzer< } flow.patternAssignment_end(); // Stack: (Expression, Pattern) - return new PatternAssignmentAnalysisResult( + return new PatternAssignmentAnalysisResult( patternSchema: patternSchema, type: rhsType, ); @@ -1446,7 +1397,7 @@ mixin TypeAnalyzer< /// /// Note, however, that the caller is responsible for reporting an error if /// the static type of [expression] is potentially nullable. - PatternForInResult analyzePatternForIn({ + PatternForInResult analyzePatternForIn({ required Node node, required bool hasAwait, required Pattern pattern, @@ -1454,23 +1405,22 @@ mixin TypeAnalyzer< required void Function() dispatchBody, }) { // Stack: () - SharedTypeSchemaView patternTypeSchema = - dispatchPatternSchema(pattern); - SharedTypeSchemaView expressionTypeSchema = hasAwait + SharedTypeSchemaView patternTypeSchema = dispatchPatternSchema(pattern); + SharedTypeSchemaView expressionTypeSchema = hasAwait ? operations.streamTypeSchema(patternTypeSchema) : operations.iterableTypeSchema(patternTypeSchema); - SharedTypeView expressionType = + SharedTypeView expressionType = analyzeExpression(expression, expressionTypeSchema); // Stack: (Expression) Error? patternForInExpressionIsNotIterableError; - SharedTypeView? elementType = hasAwait + SharedTypeView? elementType = hasAwait ? operations.matchStreamType(expressionType) : operations.matchIterableType(expressionType); if (elementType == null) { - if (expressionType is SharedDynamicTypeStructure) { + if (expressionType is SharedDynamicType) { elementType = operations.dynamicType; - } else if (expressionType is SharedInvalidTypeStructure) { + } else if (expressionType is SharedInvalidType) { elementType = operations.errorType; } else { patternForInExpressionIsNotIterableError = @@ -1487,8 +1437,7 @@ mixin TypeAnalyzer< Map> componentVariables = {}; Map patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext, - Variable>( + new MatchContext( isFinal: false, irrefutableContext: node, componentVariables: componentVariables, @@ -1521,14 +1470,12 @@ mixin TypeAnalyzer< /// type of the initializer and the type schema of the [pattern]. /// /// Stack effect: pushes (Expression, Pattern). - PatternVariableDeclarationAnalysisResult - analyzePatternVariableDeclaration( - Node node, Pattern pattern, Expression initializer, - {required bool isFinal}) { + PatternVariableDeclarationAnalysisResult analyzePatternVariableDeclaration( + Node node, Pattern pattern, Expression initializer, + {required bool isFinal}) { // Stack: () - SharedTypeSchemaView patternSchema = - dispatchPatternSchema(pattern); - SharedTypeView initializerType = + SharedTypeSchemaView patternSchema = dispatchPatternSchema(pattern); + SharedTypeView initializerType = analyzeExpression(initializer, patternSchema); // Stack: (Expression) flow.patternVariableDeclaration_afterInitializer( @@ -1536,8 +1483,7 @@ mixin TypeAnalyzer< Map> componentVariables = {}; Map patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext, - Variable>( + new MatchContext( isFinal: isFinal, irrefutableContext: node, componentVariables: componentVariables, @@ -1563,29 +1509,26 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * Pattern) where n = fields.length. - RecordPatternResult analyzeRecordPattern( - MatchContext, - Variable> - context, + RecordPatternResult analyzeRecordPattern( + MatchContext context, Pattern node, { required List> fields, }) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); - List> demonstratedPositionalTypes = []; - List<(String, SharedTypeView)> demonstratedNamedTypes = []; + SharedTypeView matchedValueType = flow.getMatchedValueType(); + List demonstratedPositionalTypes = []; + List<(String, SharedTypeView)> demonstratedNamedTypes = []; Map? duplicateRecordPatternFieldErrors = _reportDuplicateRecordPatternFields(node, fields); - void dispatchField(int i, SharedTypeView matchedType) { + void dispatchField(int i, SharedTypeView matchedType) { RecordPatternField field = fields[i]; flow.pushSubpattern(matchedType); dispatchPattern( context.withUnnecessaryWildcardKind(null), field.pattern, ); - SharedTypeView demonstratedType = - flow.getMatchedValueType(); + SharedTypeView demonstratedType = flow.getMatchedValueType(); String? name = field.name; if (name == null) { demonstratedPositionalTypes.add(demonstratedType); @@ -1596,7 +1539,7 @@ mixin TypeAnalyzer< flow.popSubpattern(); } - void dispatchFields(SharedTypeView matchedType) { + void dispatchFields(SharedTypeView matchedType) { for (int i = 0; i < fields.length; i++) { dispatchField(i, matchedType); } @@ -1604,7 +1547,7 @@ mixin TypeAnalyzer< // Build the required type. int requiredTypePositionalCount = 0; - List<(String, SharedTypeView)> requiredTypeNamedTypes = []; + List<(String, SharedTypeView)> requiredTypeNamedTypes = []; for (int i = 0; i < fields.length; i++) { RecordPatternField field = fields[i]; String? name = field.name; @@ -1617,7 +1560,7 @@ mixin TypeAnalyzer< ); } } - SharedTypeView requiredType = operations.recordType( + SharedTypeView requiredType = operations.recordType( positional: new List.filled( requiredTypePositionalCount, operations.objectQuestionType, @@ -1628,8 +1571,8 @@ mixin TypeAnalyzer< matchedType: matchedValueType, knownType: requiredType); // Stack: () - if (matchedValueType is SharedRecordTypeView) { - List>? fieldTypes = + if (matchedValueType is SharedRecordTypeView) { + List? fieldTypes = _matchRecordTypeShape(fields, matchedValueType); if (fieldTypes != null) { assert(fieldTypes.length == fields.length); @@ -1639,9 +1582,9 @@ mixin TypeAnalyzer< } else { dispatchFields(operations.objectQuestionType); } - } else if (matchedValueType is SharedDynamicTypeStructure) { + } else if (matchedValueType is SharedDynamicType) { dispatchFields(operations.dynamicType); - } else if (matchedValueType is SharedInvalidTypeStructure) { + } else if (matchedValueType is SharedInvalidType) { dispatchFields(operations.errorType); } else { dispatchFields(operations.objectQuestionType); @@ -1661,7 +1604,7 @@ mixin TypeAnalyzer< ); } - SharedTypeView demonstratedType = operations.recordType( + SharedTypeView demonstratedType = operations.recordType( positional: demonstratedPositionalTypes, named: demonstratedNamedTypes); flow.promoteForPattern( matchedType: matchedValueType, @@ -1678,14 +1621,13 @@ mixin TypeAnalyzer< /// Computes the type schema for a record pattern. /// /// Stack effect: none. - SharedTypeSchemaView analyzeRecordPatternSchema({ + SharedTypeSchemaView analyzeRecordPatternSchema({ required List> fields, }) { - List> positional = []; - List<(String, SharedTypeSchemaView)> named = []; + List positional = []; + List<(String, SharedTypeSchemaView)> named = []; for (RecordPatternField field in fields) { - SharedTypeSchemaView fieldType = - dispatchPatternSchema(field.pattern); + SharedTypeSchemaView fieldType = dispatchPatternSchema(field.pattern); String? name = field.name; if (name != null) { named.add((name, fieldType)); @@ -1709,13 +1651,11 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Expression). - RelationalPatternResult analyzeRelationalPattern( - MatchContext, - Variable> - context, + RelationalPatternResult analyzeRelationalPattern( + MatchContext context, Pattern node, Expression operand) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () Error? refutablePatternInIrrefutableContextError; Node? irrefutableContext = context.irrefutableContext; @@ -1724,9 +1664,9 @@ mixin TypeAnalyzer< errors.refutablePatternInIrrefutableContext( pattern: node, context: irrefutableContext); } - RelationalOperatorResolution? operator = + RelationalOperatorResolution? operator = resolveRelationalPatternOperator(node, matchedValueType); - SharedTypeView? parameterType = operator?.parameterType; + SharedTypeView? parameterType = operator?.parameterType; bool isEquality = switch (operator?.kind) { RelationalOperatorKind.equals => true, RelationalOperatorKind.notEquals => true, @@ -1735,7 +1675,7 @@ mixin TypeAnalyzer< if (isEquality && parameterType != null) { parameterType = operations.makeNullable(parameterType); } - SharedTypeView operandType = analyzeExpression( + SharedTypeView operandType = analyzeExpression( operand, parameterType == null ? operations.unknownType @@ -1782,7 +1722,7 @@ mixin TypeAnalyzer< /// Computes the type schema for a relational pattern. /// /// Stack effect: none. - SharedTypeSchemaView analyzeRelationalPatternSchema() { + SharedTypeSchemaView analyzeRelationalPatternSchema() { // Relational patterns are only allowed in refutable contexts, and refutable // contexts don't propagate a type schema into the scrutinee. So this // code path is only reachable if the user's code contains errors. @@ -1797,11 +1737,8 @@ mixin TypeAnalyzer< /// /// Stack effect: pushes (Expression, n * ExpressionCase), where n is the /// number of cases. - SwitchExpressionResult analyzeSwitchExpression( - Expression node, - Expression scrutinee, - int numCases, - SharedTypeSchemaView schema) { + SwitchExpressionResult analyzeSwitchExpression(Expression node, + Expression scrutinee, int numCases, SharedTypeSchemaView schema) { // Stack: () // The static type of a switch expression `E` of the form `switch (e0) { p1 @@ -1809,7 +1746,7 @@ mixin TypeAnalyzer< // follows: // // - The scrutinee (`e0`) is first analyzed with context type `_`. - SharedTypeView expressionType = + SharedTypeView expressionType = analyzeExpression(scrutinee, operations.unknownType); // Stack: (Expression) handleSwitchScrutinee(expressionType); @@ -1817,8 +1754,8 @@ mixin TypeAnalyzer< // - If the switch expression has no cases, its static type is `Never`. Map? nonBooleanGuardErrors; - Map>? guardTypes; - SharedTypeView staticType; + Map? guardTypes; + SharedTypeView staticType; if (numCases == 0) { staticType = operations.neverType; } else { @@ -1827,8 +1764,8 @@ mixin TypeAnalyzer< // - Let `T` be the least upper bound of the static types of all the case // expressions. // - Let `S` be the greatest closure of `K`. - SharedTypeView? t; - SharedTypeView s = operations.greatestClosure(schema); + SharedTypeView? t; + SharedTypeView s = operations.greatestClosure(schema); bool allCasesSatisfyContext = true; for (int i = 0; i < numCases; i++) { // Stack: (Expression, i * ExpressionCase) @@ -1843,8 +1780,8 @@ mixin TypeAnalyzer< Map> componentVariables = {}; Map patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext, Variable>( + new MatchContext( isFinal: false, switchScrutinee: scrutinee, componentVariables: componentVariables, @@ -1862,7 +1799,7 @@ mixin TypeAnalyzer< guard = memberInfo.head.guard; bool hasGuard = guard != null; if (hasGuard) { - SharedTypeView guardType = analyzeExpression( + SharedTypeView guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); Error? nonBooleanGuardError = _checkGuardType(guard, guardType); (guardTypes ??= {})[i] = guardType; @@ -1881,8 +1818,7 @@ mixin TypeAnalyzer< flow.switchStatement_endAlternative(guard, {}); flow.switchStatement_endAlternatives(null, hasLabels: false); // Stack: (Expression, i * ExpressionCase, CaseHead) - SharedTypeView ti = - analyzeExpression(memberInfo.expression, schema); + SharedTypeView ti = analyzeExpression(memberInfo.expression, schema); if (allCasesSatisfyContext && !operations.isSubtypeOf(ti, s)) { allCasesSatisfyContext = false; } @@ -1925,11 +1861,10 @@ mixin TypeAnalyzer< /// /// Stack effect: pushes (Expression, n * StatementCase), where n is the /// number of cases after merging together cases that share a body. - SwitchStatementTypeAnalysisResult - analyzeSwitchStatement( - Statement node, Expression scrutinee, final int numCases) { + SwitchStatementTypeAnalysisResult analyzeSwitchStatement( + Statement node, Expression scrutinee, final int numCases) { // Stack: () - SharedTypeView scrutineeType = + SharedTypeView scrutineeType = analyzeExpression(scrutinee, operations.unknownType); // Stack: (Expression) handleSwitchScrutinee(scrutineeType); @@ -1938,7 +1873,7 @@ mixin TypeAnalyzer< bool lastCaseTerminates = true; Map? switchCaseCompletesNormallyErrors; Map>? nonBooleanGuardErrors; - Map>>? guardTypes; + Map>? guardTypes; for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { // Stack: (Expression, numExecutionPaths * StatementCase) flow.switchStatement_beginAlternatives(); @@ -1960,8 +1895,8 @@ mixin TypeAnalyzer< Map> componentVariables = {}; Map patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext, Variable>( + new MatchContext( isFinal: false, switchScrutinee: scrutinee, componentVariables: componentVariables, @@ -1979,7 +1914,7 @@ mixin TypeAnalyzer< // numHeads * CaseHead, Pattern), guard = head.guard; if (guard != null) { - SharedTypeView guardType = analyzeExpression( + SharedTypeView guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); Error? nonBooleanGuardError = _checkGuardType(guard, guardType); ((guardTypes ??= {})[caseIndex] ??= {})[headIndex] = guardType; @@ -2071,11 +2006,10 @@ mixin TypeAnalyzer< /// Stack effect: none. /// /// Returns the inferred type of the variable. - SharedTypeView analyzeUninitializedVariableDeclaration( - Node node, Variable variable, SharedTypeView? declaredType, + SharedTypeView analyzeUninitializedVariableDeclaration( + Node node, Variable variable, SharedTypeView? declaredType, {required bool isFinal}) { - SharedTypeView inferredType = - declaredType ?? operations.dynamicType; + SharedTypeView inferredType = declaredType ?? operations.dynamicType; setVariableType(variable, inferredType); flow.declare(variable, inferredType, initialized: false); return inferredType; @@ -2088,14 +2022,13 @@ mixin TypeAnalyzer< /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: none. - WildcardPatternResult analyzeWildcardPattern({ - required MatchContext, Variable> + WildcardPatternResult analyzeWildcardPattern({ + required MatchContext context, required Pattern node, - required SharedTypeView? declaredType, + required SharedTypeView? declaredType, }) { - SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); Node? irrefutableContext = context.irrefutableContext; Error? patternTypeMismatchInIrrefutableContextError; if (irrefutableContext != null && declaredType != null) { @@ -2136,8 +2069,8 @@ mixin TypeAnalyzer< /// explicitly declared type (if present). /// /// Stack effect: none. - SharedTypeSchemaView analyzeWildcardPatternSchema({ - required SharedTypeView? declaredType, + SharedTypeSchemaView analyzeWildcardPatternSchema({ + required SharedTypeView? declaredType, }) { return declaredType == null ? operations.unknownType @@ -2161,8 +2094,8 @@ mixin TypeAnalyzer< /// [analyzeSwitchExpression]. /// /// Stack effect: pushes (Expression). - ExpressionTypeAnalysisResult dispatchExpression( - Expression node, SharedTypeSchemaView schema); + ExpressionTypeAnalysisResult dispatchExpression( + Expression node, SharedTypeSchemaView schema); /// Calls the appropriate `analyze` method according to the form of [pattern]. /// @@ -2171,17 +2104,15 @@ mixin TypeAnalyzer< /// and the information accumulated while matching previous patterns. /// /// Stack effect: pushes (Pattern). - PatternResult dispatchPattern( - MatchContext, - Variable> - context, + PatternResult dispatchPattern( + MatchContext context, Node pattern); /// Calls the appropriate `analyze...Schema` method according to the form of /// [pattern]. /// /// Stack effect: none. - SharedTypeSchemaView dispatchPatternSchema(Node pattern); + SharedTypeSchemaView dispatchPatternSchema(Node pattern); /// Calls the appropriate `analyze` method according to the form of /// [statement], and then adjusts the stack as needed to combine any @@ -2194,8 +2125,8 @@ mixin TypeAnalyzer< void dispatchStatement(Statement statement); /// Infers the type for the [pattern], should be a subtype of [matchedType]. - SharedTypeView downwardInferObjectPatternRequiredType({ - required SharedTypeView matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required Pattern pattern, }); @@ -2212,7 +2143,7 @@ mixin TypeAnalyzer< required JoinedPatternVariableLocation location, required JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView type, + required SharedTypeView type, }); /// If the [element] is a map pattern entry, returns it. @@ -2308,8 +2239,8 @@ mixin TypeAnalyzer< /// Called after visiting an entry element in a map pattern. /// /// Stack effect: pushes (MapPatternElement). - void handleMapPatternEntry(Pattern container, Node entryElement, - SharedTypeView keyType); + void handleMapPatternEntry( + Pattern container, Node entryElement, SharedTypeView keyType); /// Called after visiting a rest element in a map pattern. /// @@ -2373,15 +2304,14 @@ mixin TypeAnalyzer< /// eliminate this method. /// /// Stack effect: none. - void handleSwitchScrutinee(SharedTypeView type); + void handleSwitchScrutinee(SharedTypeView type); /// Queries whether the switch statement or expression represented by [node] /// was exhaustive. [expressionType] is the static type of the scrutinee. /// /// Will only be called if the switch statement or expression lacks a /// `default` clause, and patterns support is disabled. - bool isLegacySwitchExhaustive( - Node node, SharedTypeView expressionType); + bool isLegacySwitchExhaustive(Node node, SharedTypeView expressionType); /// Returns whether [node] is a rest element in a list or map pattern. bool isRestPatternElement(Node node); @@ -2392,9 +2322,9 @@ mixin TypeAnalyzer< /// Returns the type of the property in [receiverType] that corresponds to /// the name of the [field]. If the property cannot be resolved, the client /// should report an error, and return `dynamic` for recovery. - (Object?, SharedTypeView) resolveObjectPatternPropertyGet({ + (Object?, SharedTypeView) resolveObjectPatternPropertyGet({ required Pattern objectPattern, - required SharedTypeView receiverType, + required SharedTypeView receiverType, required RecordPatternField field, }); @@ -2404,18 +2334,17 @@ mixin TypeAnalyzer< /// If no operator is found, `null` should be returned. (This could happen /// either because the code is invalid, or because [matchedValueType] is /// `dynamic`). - RelationalOperatorResolution? resolveRelationalPatternOperator( - Pattern node, SharedTypeView matchedValueType); + RelationalOperatorResolution? resolveRelationalPatternOperator( + Pattern node, SharedTypeView matchedValueType); /// Records that type inference has assigned a [type] to a [variable]. This /// is called once per variable, regardless of whether the variable's type is /// explicit or inferred. - void setVariableType(Variable variable, SharedTypeView type); + void setVariableType(Variable variable, SharedTypeView type); /// Computes the type that should be inferred for an implicitly typed variable /// whose initializer expression has static type [type]. - SharedTypeView variableTypeFromInitializerType( - SharedTypeView type); + SharedTypeView variableTypeFromInitializerType(SharedTypeView type); /// Common functionality shared by [analyzeIfStatement] and /// [analyzeIfCaseStatement]. @@ -2461,8 +2390,7 @@ mixin TypeAnalyzer< // Stack: (CollectionElement ifTrue, CollectionElement ifFalse) } - Error? _checkGuardType( - Expression expression, SharedTypeView type) { + Error? _checkGuardType(Expression expression, SharedTypeView type) { // TODO(paulberry): harmonize this with analyzer's checkForNonBoolExpression // TODO(paulberry): spec says the type must be `bool` or `dynamic`. This // logic permits `T extends bool`, `T promoted to bool`, or `Never`. What @@ -2492,15 +2420,14 @@ mixin TypeAnalyzer< Variable? variable = variables[variableName]; List components = componentVariables[variableName] ?? []; bool isFirst = true; - SharedTypeView? typeIfConsistent; + SharedTypeView? typeIfConsistent; bool? isFinalIfConsistent; bool isIdenticalToComponent = false; for (Variable component in components) { if (identical(variable, component)) { isIdenticalToComponent = true; } - SharedTypeView componentType = - operations.variableType(component); + SharedTypeView componentType = operations.variableType(component); bool isComponentFinal = operations.isVariableFinal(component); if (isFirst) { typeIfConsistent = componentType; @@ -2546,22 +2473,21 @@ mixin TypeAnalyzer< /// If the shape described by [fields] is the same as the shape of the /// [matchedType], returns matched types for each field in [fields]. /// Otherwise returns `null`. - List>? _matchRecordTypeShape( + List? _matchRecordTypeShape( List> fields, - SharedRecordTypeView matchedType, + SharedRecordTypeView matchedType, ) { - Map> matchedTypeNamed = {}; - for (var SharedNamedTypeView(:name, :type) - in matchedType.namedTypes) { + Map matchedTypeNamed = {}; + for (var SharedNamedTypeView(:name, :type) in matchedType.namedTypes) { matchedTypeNamed[name] = type; } - List> result = []; + List result = []; int namedCount = 0; - Iterator> positionalIterator = + Iterator positionalIterator = matchedType.positionalTypes.iterator; for (RecordPatternField field in fields) { - SharedTypeView? fieldType; + SharedTypeView? fieldType; String? name = field.name; if (name != null) { fieldType = matchedTypeNamed[name]; @@ -2613,10 +2539,10 @@ mixin TypeAnalyzer< return errorResults; } - bool _structurallyEqualAfterNormTypes(SharedTypeView type1, - SharedTypeView type2) { - SharedTypeView norm1 = operations.normalize(type1); - SharedTypeView norm2 = operations.normalize(type2); + bool _structurallyEqualAfterNormTypes( + SharedTypeView type1, SharedTypeView type2) { + SharedTypeView norm1 = operations.normalize(type1); + SharedTypeView norm2 = operations.normalize(type2); return norm1.unwrapTypeView().isStructurallyEqualTo(norm2.unwrapTypeView()); } } diff --git a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer_operations.dart b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer_operations.dart index d75cfe59b712..41420016e362 100644 --- a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer_operations.dart +++ b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_analyzer_operations.dart @@ -20,41 +20,35 @@ import 'type_constraint.dart'; /// implementing [TypeAnalyzerOperations] needs to implement only /// `futureTypeInternal` to receive the implementations of both `futureType` and /// `futureTypeSchema` by mixing in [TypeAnalyzerOperationsMixin]. -abstract interface class TypeAnalyzerOperations< - TypeStructure extends SharedTypeStructure, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - implements FlowAnalysisOperations> { +abstract interface class TypeAnalyzerOperations + implements FlowAnalysisOperations { /// Returns the type `double`. - SharedTypeView get doubleType; + SharedTypeView get doubleType; /// Returns the type `dynamic`. - SharedTypeView get dynamicType; + SharedTypeView get dynamicType; /// Returns the type used by the client in the case of errors. - SharedTypeView get errorType; + SharedTypeView get errorType; /// Returns the type `int`. - SharedTypeView get intType; + SharedTypeView get intType; /// Returns the type `Never`. - SharedTypeView get neverType; + SharedTypeView get neverType; /// Returns the type `Null`. - SharedTypeView get nullType; + SharedTypeView get nullType; /// Returns the type `Object?`. - SharedTypeView get objectQuestionType; + SharedTypeView get objectQuestionType; /// Returns the type `Object`. - SharedTypeView get objectType; + SharedTypeView get objectType; /// Returns the unknown type schema (`_`) used in type inference. - SharedTypeSchemaView get unknownType; + SharedTypeSchemaView get unknownType; /// Returns the type `Future` with omitted nullability and type argument /// [argumentType]. @@ -63,8 +57,7 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [futureTypeInternal] to /// receive a concrete implementation of [futureType] instead of implementing /// [futureType] directly. - SharedTypeView futureType( - SharedTypeView argumentType); + SharedTypeView futureType(SharedTypeView argumentType); /// [futureTypeInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of [futureType] @@ -89,7 +82,7 @@ abstract interface class TypeAnalyzerOperations< /// [futureTypeInternal] instead of the tool-specific ways of constructing a /// future type, for the sake of uniformity, and to simplify the abstraction /// step too. - TypeStructure futureTypeInternal(TypeStructure typeStructure); + SharedType futureTypeInternal(covariant SharedType typeStructure); /// Returns the type schema `Future` with omitted nullability and type /// argument [argumentTypeSchema]. @@ -98,8 +91,8 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [futureTypeInternal] to /// receive a concrete implementation of [futureTypeSchema] instead of /// implementing [futureTypeSchema] directly. - SharedTypeSchemaView futureTypeSchema( - SharedTypeSchemaView argumentTypeSchema); + SharedTypeSchemaView futureTypeSchema( + SharedTypeSchemaView argumentTypeSchema); /// If [type] was introduced by a class, mixin, enum, or extension type, /// returns a [TypeDeclarationKind] indicating what kind of thing it was @@ -108,10 +101,10 @@ abstract interface class TypeAnalyzerOperations< /// Examples of types derived from a class declarations are `A`, `A?`, `A*`, /// `B`, where `A` and `B` are the names of class declarations or /// extension type declarations, `T` and `S` are types. - TypeDeclarationKind? getTypeDeclarationKind( - SharedTypeView type); + TypeDeclarationKind? getTypeDeclarationKind(SharedTypeView type); - TypeDeclarationKind? getTypeDeclarationKindInternal(TypeStructure type); + TypeDeclarationKind? getTypeDeclarationKindInternal( + covariant SharedType type); /// Returns variance for of the type parameter at index [parameterIndex] in /// [typeDeclaration]. @@ -128,15 +121,14 @@ abstract interface class TypeAnalyzerOperations< /// and `B` are class declarations or extension type declarations, `T` and /// `S` are type schemas. TypeDeclarationKind? getTypeSchemaDeclarationKind( - SharedTypeSchemaView typeSchema); + SharedTypeSchemaView typeSchema); /// Computes the greatest lower bound of [type1] and [type2]. /// /// The concrete classes implementing [TypeAnalyzerOperations] should mix in /// [TypeAnalyzerOperationsMixin] and implement [glbInternal] to receive a /// concrete implementation of [glb] instead of implementing [glb] directly. - SharedTypeView glb( - SharedTypeView type1, SharedTypeView type2); + SharedTypeView glb(SharedTypeView type1, SharedTypeView type2); /// [glbInternal] should be implemented by concrete classes implementing /// [TypeAnalyzerOperations]. The implementations of [glb] and [typeSchemaGlb] @@ -158,100 +150,95 @@ abstract interface class TypeAnalyzerOperations< /// concrete members it can be beneficial to use [glbInternal] instead of the /// tool-specific ways of constructing a future type, for the sake of /// uniformity, and to simplify the abstraction step too. - TypeStructure glbInternal(TypeStructure type1, TypeStructure type2); + SharedType glbInternal( + covariant SharedType type1, covariant SharedType type2); /// Returns the greatest closure of [schema] with respect to the unknown type /// (`_`). - SharedTypeView greatestClosure( - SharedTypeSchemaView schema); + SharedTypeView greatestClosure(SharedTypeSchemaView schema); /// Computes the greatest closure of a type. /// /// Computing the greatest closure of a type is described here: /// https://github.com/dart-lang/language/blob/main/resources/type-system/inference.md#type-variable-elimination-least-and-greatest-closure-of-a-type - TypeStructure greatestClosureOfTypeInternal( - TypeStructure type, - List> - typeParametersToEliminate); + SharedType greatestClosureOfTypeInternal(covariant SharedType type, + List typeParametersToEliminate); /// Queries whether [type] is an "always-exhaustive" type (as defined in the /// patterns spec). Exhaustive types are types for which the switch statement /// is required to be exhaustive when patterns support is enabled. - bool isAlwaysExhaustiveType(SharedTypeView type); + bool isAlwaysExhaustiveType(SharedTypeView type); /// Returns `true` if [fromType] is assignable to [toType]. - bool isAssignableTo(SharedTypeView fromType, - SharedTypeView toType); + bool isAssignableTo(SharedTypeView fromType, SharedTypeView toType); /// Returns `true` if [type] is `Function` from `dart:core`. The method /// returns `false` for `Function?` and `Function*`. - bool isDartCoreFunctionInternal(TypeStructure type); + bool isDartCoreFunctionInternal(covariant SharedType type); /// Returns `true` if [type] is `Record` from `dart:core`. The method /// returns `false` for `Record?` and `Record*`. - bool isDartCoreRecordInternal(TypeStructure type); + bool isDartCoreRecordInternal(covariant SharedType type); /// Returns `true` if [type] is `E`, `E?`, or /// `E*` for some extension type declaration E, some /// non-negative n, and some types T1, ..., Tn. - bool isExtensionTypeInternal(TypeStructure type); + bool isExtensionTypeInternal(covariant SharedType type); /// Returns `true` if [type] is `A`, `A?`, or /// `A*` for some class, mixin, or enum A, some non-negative n, /// and some types T1, ..., Tn. The method returns `false` if [type] is an /// extension type, a type alias, `Null`, `Never`, or `FutureOr` for any /// type `X`. - bool isInterfaceTypeInternal(TypeStructure type); + bool isInterfaceTypeInternal(covariant SharedType type); @override - bool isNever(SharedTypeView type); + bool isNever(SharedTypeView type); /// Returns `true` if `Null` is not a subtype of all types matching [type]. /// /// The predicate of [isNonNullableInternal] could be computed directly with /// a subtype query, but the implementations can do that more efficiently. - bool isNonNullableInternal(TypeStructure type); + bool isNonNullableInternal(covariant SharedType type); /// Returns `true` if `Null` is a subtype of all types matching [type]. /// /// The predicate of [isNullableInternal] could be computed directly with a /// subtype query, but the implementations can do that more efficiently. - bool isNullableInternal(TypeStructure type); + bool isNullableInternal(covariant SharedType type); /// Returns `true` if [type] is `Object` from `dart:core`. The method returns /// `false` for `Object?` and `Object*`. - bool isObject(SharedTypeView type); + bool isObject(SharedTypeView type); /// The concrete classes implementing [TypeAnalyzerOperations] should /// implement [isSubtypeOfInternal] in order to receive the implementations of /// [typeIsSubtypeOfTypeSchema], [typeSchemaIsSubtypeOfType], and /// [typeSchemaIsSubtypeOfTypeSchema] by mixing in /// [TypeAnalyzerOperationsMixin]. - bool isSubtypeOfInternal(TypeStructure left, TypeStructure right); + bool isSubtypeOfInternal( + covariant SharedType left, covariant SharedType right); @override - bool isTypeParameterType(SharedTypeView type); + bool isTypeParameterType(SharedTypeView type); /// Returns `true` if the type [type] satisfies the type schema [typeSchema]. bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView typeSchema, - required SharedTypeView type}); + {required SharedTypeSchemaView typeSchema, required SharedTypeView type}); /// Returns whether [node] is final. bool isVariableFinal(Variable node); /// Returns the type schema `Iterable`, with type argument. - SharedTypeSchemaView iterableTypeSchema( - SharedTypeSchemaView elementTypeSchema); + SharedTypeSchemaView iterableTypeSchema( + SharedTypeSchemaView elementTypeSchema); /// Computes the least closure of a type. /// /// Computing the greatest closure of a type is described here: /// https://github.com/dart-lang/language/blob/main/resources/type-system/inference.md#type-variable-elimination-least-and-greatest-closure-of-a-type - TypeStructure leastClosureOfTypeInternal( - TypeStructure type, - List> - typeParametersToEliminate); + SharedType leastClosureOfTypeInternal(covariant SharedType type, + List typeParametersToEliminate); /// Returns the type `List`, with type argument [elementType]. /// @@ -259,8 +246,7 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [listTypeInternal] to receive /// a concrete implementation of [listType] instead of implementing [listType] /// directly. - SharedTypeView listType( - SharedTypeView elementType); + SharedTypeView listType(SharedTypeView elementType); /// [listTypeInternal] should be implemented by concrete classes implementing /// [TypeAnalyzerOperations]. The implementations of [listType] and @@ -284,7 +270,7 @@ abstract interface class TypeAnalyzerOperations< /// [listTypeInternal] instead of the tool-specific ways of constructing a /// future type, for the sake of uniformity, and to simplify the abstraction /// step too. - TypeStructure listTypeInternal(TypeStructure elementType); + SharedType listTypeInternal(covariant SharedType elementType); /// Returns the type schema `List`, with type argument [elementTypeSchema]. /// @@ -292,16 +278,14 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [listTypeInternal] to receive /// a concrete implementation of [listTypeSchema] instead of implementing /// [listTypeSchema] directly. - SharedTypeSchemaView listTypeSchema( - SharedTypeSchemaView elementTypeSchema); + SharedTypeSchemaView listTypeSchema(SharedTypeSchemaView elementTypeSchema); /// Computes the least upper bound of [type1] and [type2]. /// /// The concrete classes implementing [TypeAnalyzerOperations] should mix in /// [TypeAnalyzerOperationsMixin] and implement [lubInternal] to receive a /// concrete implementation of [lub] instead of implementing [lub] directly. - SharedTypeView lub( - SharedTypeView type1, SharedTypeView type2); + SharedTypeView lub(SharedTypeView type1, SharedTypeView type2); /// [lubInternal] should be implemented by concrete classes implementing /// [TypeAnalyzerOperations]. The implementations of [lub] and [typeSchemaLub] @@ -323,7 +307,8 @@ abstract interface class TypeAnalyzerOperations< /// concrete members it can be beneficial to use [lubInternal] instead of the /// tool-specific ways of constructing a future type, for the sake of /// uniformity, and to simplify the abstraction step too. - TypeStructure lubInternal(TypeStructure type1, TypeStructure type2); + SharedType lubInternal( + covariant SharedType type1, covariant SharedType type2); /// [makeNullableInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of @@ -348,7 +333,7 @@ abstract interface class TypeAnalyzerOperations< /// [makeNullableInternal] instead of the tool-specific ways of constructing a /// future type, for the sake of uniformity, and to simplify the abstraction /// step too. - TypeStructure makeNullableInternal(TypeStructure type); + SharedType makeNullableInternal(covariant SharedType type); /// Computes the nullable form of [typeSchema]. /// @@ -356,8 +341,7 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [makeNullableInternal] to /// receive a concrete implementation of [makeTypeSchemaNullable] instead of /// implementing [makeTypeSchemaNullable] directly. - SharedTypeSchemaView makeTypeSchemaNullable( - SharedTypeSchemaView typeSchema); + SharedTypeSchemaView makeTypeSchemaNullable(SharedTypeSchemaView typeSchema); /// Returns the type `Map`, with type arguments. /// @@ -365,9 +349,9 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [mapTypeInternal] to receive a /// concrete implementation of [mapType] instead of implementing [mapType] /// directly. - SharedTypeView mapType({ - required SharedTypeView keyType, - required SharedTypeView valueType, + SharedTypeView mapType({ + required SharedTypeView keyType, + required SharedTypeView valueType, }); /// [mapTypeInternal] should be implemented by concrete classes implementing @@ -393,9 +377,9 @@ abstract interface class TypeAnalyzerOperations< /// [mapTypeInternal] instead of the tool-specific ways of constructing a /// future type, for the sake of uniformity, and to simplify the abstraction /// step too. - TypeStructure mapTypeInternal({ - required TypeStructure keyType, - required TypeStructure valueType, + SharedType mapTypeInternal({ + required covariant SharedType keyType, + required covariant SharedType valueType, }); /// Returns the type schema `Map`, with type arguments [keyTypeSchema] and @@ -405,9 +389,9 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [mapTypeInternal] to receive a /// concrete implementation of [makeTypeSchemaNullable] instead of /// implementing [makeTypeSchemaNullable] directly. - SharedTypeSchemaView mapTypeSchema({ - required SharedTypeSchemaView keyTypeSchema, - required SharedTypeSchemaView valueTypeSchema, + SharedTypeSchemaView mapTypeSchema({ + required SharedTypeSchemaView keyTypeSchema, + required SharedTypeSchemaView valueTypeSchema, }); /// If [type] takes the form `FutureOr`, `FutureOr?`, or `FutureOr*` @@ -417,8 +401,7 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [matchFutureOrInternal] to /// receive a concrete implementation of [matchFutureOr] instead of /// implementing [matchFutureOr] directly. - SharedTypeView? matchFutureOr( - SharedTypeView type); + SharedTypeView? matchFutureOr(SharedTypeView type); /// [matchFutureOrInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of @@ -443,7 +426,7 @@ abstract interface class TypeAnalyzerOperations< /// [matchFutureOrInternal] instead of the tool-specific ways of constructing /// a future type, for the sake of uniformity, and to simplify the abstraction /// step too. - TypeStructure? matchFutureOrInternal(TypeStructure type); + SharedType? matchFutureOrInternal(covariant SharedType type); /// If [type] is a parameter type that is of a kind used in type inference, /// returns the corresponding parameter. @@ -454,7 +437,8 @@ abstract interface class TypeAnalyzerOperations< /// by `foo`. /// /// X foo(bool c, X x1, X x2) => c ? x1 : x2; - TypeParameterStructure? matchInferableParameterInternal(TypeStructure type); + SharedTypeParameter? matchInferableParameterInternal( + covariant SharedType type); /// If [type] is a subtype of the type `Iterable?` for some `T`, returns /// the type `T`. Otherwise returns `null`. @@ -463,8 +447,7 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [matchIterableTypeInternal] to /// receive a concrete implementation of [matchIterableType] instead of /// implementing [matchIterableType] directly. - SharedTypeView? matchIterableType( - SharedTypeView type); + SharedTypeView? matchIterableType(SharedTypeView type); /// [matchIterableTypeInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of @@ -489,7 +472,7 @@ abstract interface class TypeAnalyzerOperations< /// [matchIterableTypeInternal] instead of the tool-specific ways of /// constructing a future type, for the sake of uniformity, and to simplify /// the abstraction step too. - TypeStructure? matchIterableTypeInternal(TypeStructure type); + SharedType? matchIterableTypeInternal(covariant SharedType type); /// If [typeSchema] is the type schema `Iterable?` (or a subtype thereof), /// for some `T`, returns the type `T`. Otherwise returns `null`. @@ -498,25 +481,21 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [matchIterableTypeInternal] to /// receive a concrete implementation of [matchIterableTypeSchema] instead of /// implementing [matchIterableTypeSchema] directly. - SharedTypeSchemaView? matchIterableTypeSchema( - SharedTypeSchemaView typeSchema); + SharedTypeSchemaView? matchIterableTypeSchema( + SharedTypeSchemaView typeSchema); /// If [type] is a subtype of the type `List?` for some `T`, returns the /// type `T`. Otherwise returns `null`. - SharedTypeView? matchListType( - SharedTypeView type); + SharedTypeView? matchListType(SharedTypeView type); /// If [type] is a subtype of the type `Map?` for some `K` and `V`, /// returns these `K` and `V`. Otherwise returns `null`. - ({ - SharedTypeView keyType, - SharedTypeView valueType - })? matchMapType(SharedTypeView type); + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type); /// If [type] is a subtype of the type `Stream?` for some `T`, returns /// the type `T`. Otherwise returns `null`. - SharedTypeView? matchStreamType( - SharedTypeView type); + SharedTypeView? matchStreamType(SharedTypeView type); /// If [type] was introduced by a class, mixin, enum, or extension type, /// returns an object of [TypeDeclarationMatchResult] describing the @@ -524,8 +503,8 @@ abstract interface class TypeAnalyzerOperations< /// /// If [type] isn't introduced by a class, mixin, enum, or extension type, /// returns null. - TypeDeclarationMatchResult? matchTypeDeclarationTypeInternal(TypeStructure type); + TypeDeclarationMatchResult? + matchTypeDeclarationTypeInternal(covariant SharedType type); /// If [type] is a parameter type with empty nullability suffix, returns its /// bound, whether it is its type parameter bound or its promoted bound. @@ -546,7 +525,7 @@ abstract interface class TypeAnalyzerOperations< /// return f(x); /// } /// } - TypeStructure? matchTypeParameterBoundInternal(TypeStructure type); + SharedType? matchTypeParameterBoundInternal(covariant SharedType type); /// If [typeSchema] takes the form `FutureOr`, `FutureOr?`, or /// `FutureOr*` for some `T`, returns the type schema `T`. Otherwise @@ -556,17 +535,16 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [matchFutureOrInternal] to /// receive a concrete implementation of [matchTypeSchemaFutureOr] instead of /// implementing [matchTypeSchemaFutureOr] directly. - SharedTypeSchemaView? matchTypeSchemaFutureOr( - SharedTypeSchemaView typeSchema); + SharedTypeSchemaView? matchTypeSchemaFutureOr( + SharedTypeSchemaView typeSchema); /// Computes `NORM` of [type]. /// https://github.com/dart-lang/language /// See `resources/type-system/normalization.md` - SharedTypeView normalize(SharedTypeView type); + SharedTypeView normalize(SharedTypeView type); @override - SharedTypeView promoteToNonNull( - SharedTypeView type); + SharedTypeView promoteToNonNull(SharedTypeView type); /// Builds the client specific record type. /// @@ -574,9 +552,9 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [recordTypeInternal] to /// receive a concrete implementation of [recordType] instead of implementing /// [recordType] directly. - SharedTypeView recordType( - {required List> positional, - required List<(String, SharedTypeView)> named}); + SharedTypeView recordType( + {required List positional, + required List<(String, SharedTypeView)> named}); /// [recordTypeInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of [recordType] @@ -601,9 +579,9 @@ abstract interface class TypeAnalyzerOperations< /// [recordTypeInternal] instead of the tool-specific ways of constructing a /// future type, for the sake of uniformity, and to simplify the abstraction /// step too. - TypeStructure recordTypeInternal( - {required List positional, - required List<(String, TypeStructure)> named}); + SharedType recordTypeInternal( + {required List positional, + required List<(String, SharedType)> named}); /// Builds the client specific record type schema. /// @@ -611,17 +589,15 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [recordTypeInternal] to /// receive a concrete implementation of [recordTypeSchema] instead of /// implementing [recordTypeSchema] directly. - SharedTypeSchemaView recordTypeSchema( - {required List> positional, - required List<(String, SharedTypeSchemaView)> named}); + SharedTypeSchemaView recordTypeSchema( + {required List positional, + required List<(String, SharedTypeSchemaView)> named}); /// Returns the type schema `Stream`, with type argument [elementTypeSchema]. - SharedTypeSchemaView streamTypeSchema( - SharedTypeSchemaView elementTypeSchema); + SharedTypeSchemaView streamTypeSchema(SharedTypeSchemaView elementTypeSchema); @override - SharedTypeView? tryPromoteToType( - SharedTypeView to, SharedTypeView from); + SharedTypeView? tryPromoteToType(SharedTypeView to, SharedTypeView from); /// Returns `true` if [leftType] is a subtype of the greatest closure of /// [rightSchema]. @@ -636,8 +612,8 @@ abstract interface class TypeAnalyzerOperations< /// implement [isSubtypeOfInternal] and mix in [TypeAnalyzerOperationsMixin] /// to receive an implementation of [typeIsSubtypeOfTypeSchema] instead of /// implementing it directly. - bool typeIsSubtypeOfTypeSchema(SharedTypeView leftType, - SharedTypeSchemaView rightSchema); + bool typeIsSubtypeOfTypeSchema( + SharedTypeView leftType, SharedTypeSchemaView rightSchema); /// Computes the greatest lower bound of [typeSchema1] and [typeSchema2]. /// @@ -645,9 +621,8 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [glbInternal] to receive a /// concrete implementation of [typeSchemaGlb] instead of implementing /// [typeSchemaGlb] directly. - SharedTypeSchemaView typeSchemaGlb( - SharedTypeSchemaView typeSchema1, - SharedTypeSchemaView typeSchema2); + SharedTypeSchemaView typeSchemaGlb( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2); /// Returns `true` if the least closure of [leftSchema] is a subtype of /// [rightType]. @@ -662,8 +637,8 @@ abstract interface class TypeAnalyzerOperations< /// implement [isSubtypeOfInternal] and mix in [TypeAnalyzerOperationsMixin] /// to receive an implementation of [typeSchemaIsSubtypeOfType] instead of /// implementing it directly. - bool typeSchemaIsSubtypeOfType(SharedTypeSchemaView leftSchema, - SharedTypeView rightType); + bool typeSchemaIsSubtypeOfType( + SharedTypeSchemaView leftSchema, SharedTypeView rightType); /// Returns `true` if least closure of [leftSchema] is a subtype of /// the greatest closure of [rightSchema]. @@ -679,8 +654,7 @@ abstract interface class TypeAnalyzerOperations< /// to receive an implementation of [typeSchemaIsSubtypeOfTypeSchema] instead /// of implementing it directly. bool typeSchemaIsSubtypeOfTypeSchema( - SharedTypeSchemaView leftSchema, - SharedTypeSchemaView rightSchema); + SharedTypeSchemaView leftSchema, SharedTypeSchemaView rightSchema); /// Computes the least upper bound of [typeSchema1] and [typeSchema2]. /// @@ -688,141 +662,114 @@ abstract interface class TypeAnalyzerOperations< /// [TypeAnalyzerOperationsMixin] and implement [lubInternal] to receive a /// concrete implementation of [typeSchemaLub] instead of implementing /// [typeSchemaLub] directly. - SharedTypeSchemaView typeSchemaLub( - SharedTypeSchemaView typeSchema1, - SharedTypeSchemaView typeSchema2); + SharedTypeSchemaView typeSchemaLub( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2); /// Converts a type into a corresponding type schema. - SharedTypeSchemaView typeToSchema( - SharedTypeView type); + SharedTypeSchemaView typeToSchema(SharedTypeView type); /// Returns [type] suffixed with the [suffix]. - TypeStructure withNullabilitySuffixInternal( - TypeStructure type, NullabilitySuffix suffix); - - TypeConstraintGenerator< - TypeStructure, - SharedNamedFunctionParameterStructure, - Variable, - TypeParameterStructure, - TypeDeclarationType, - TypeDeclaration, + SharedType withNullabilitySuffixInternal( + covariant SharedType type, NullabilitySuffix suffix); + + TypeConstraintGenerator createTypeConstraintGenerator( - {required TypeConstraintGenerationDataForTesting? + {required TypeConstraintGenerationDataForTesting? typeConstraintGenerationDataForTesting, - required List typeParametersToInfer, - required TypeAnalyzerOperations + required List typeParametersToInfer, + required TypeAnalyzerOperations typeAnalyzerOperations, required bool inferenceUsingBoundsIsEnabled}); - MergedTypeConstraint + MergedTypeConstraint mergeInConstraintsFromBound( - {required TypeParameterStructure typeParameterToInfer, - required List typeParametersToInfer, - required TypeStructure lower, + {required SharedTypeParameter typeParameterToInfer, + required List typeParametersToInfer, + required SharedType lower, required Map< - TypeParameterStructure, - MergedTypeConstraint> + SharedTypeParameter, + MergedTypeConstraint> inferencePhaseConstraints, - required TypeConstraintGenerationDataForTesting? + required TypeConstraintGenerationDataForTesting? dataForTesting, required bool inferenceUsingBoundsIsEnabled}); } -mixin TypeAnalyzerOperationsMixin< - TypeStructure extends SharedTypeStructure, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> +mixin TypeAnalyzerOperationsMixin implements - TypeAnalyzerOperations { + TypeAnalyzerOperations { @override - SharedTypeView futureType( - SharedTypeView argumentType) { + SharedTypeView futureType(SharedTypeView argumentType) { return new SharedTypeView( futureTypeInternal(argumentType.unwrapTypeView())); } @override - SharedTypeSchemaView futureTypeSchema( - SharedTypeSchemaView argumentTypeSchema) { + SharedTypeSchemaView futureTypeSchema( + SharedTypeSchemaView argumentTypeSchema) { return new SharedTypeSchemaView( futureTypeInternal(argumentTypeSchema.unwrapTypeSchemaView())); } @override - TypeDeclarationKind? getTypeDeclarationKind( - SharedTypeView type) { + TypeDeclarationKind? getTypeDeclarationKind(SharedTypeView type) { return getTypeDeclarationKindInternal(type.unwrapTypeView()); } @override TypeDeclarationKind? getTypeSchemaDeclarationKind( - SharedTypeSchemaView typeSchema) { + SharedTypeSchemaView typeSchema) { return getTypeDeclarationKindInternal(typeSchema.unwrapTypeSchemaView()); } @override - SharedTypeView glb(SharedTypeView type1, - SharedTypeView type2) { + SharedTypeView glb(SharedTypeView type1, SharedTypeView type2) { return new SharedTypeView( glbInternal(type1.unwrapTypeView(), type2.unwrapTypeView())); } @override - bool isSubtypeOf(SharedTypeView leftType, - SharedTypeView rightType) { + bool isSubtypeOf(SharedTypeView leftType, SharedTypeView rightType) { return isSubtypeOfInternal( leftType.unwrapTypeView(), rightType.unwrapTypeView()); } @override - SharedTypeView listType( - SharedTypeView elementType) { + SharedTypeView listType(SharedTypeView elementType) { return new SharedTypeView(listTypeInternal(elementType.unwrapTypeView())); } @override - SharedTypeSchemaView listTypeSchema( - SharedTypeSchemaView elementTypeSchema) { + SharedTypeSchemaView listTypeSchema(SharedTypeSchemaView elementTypeSchema) { return new SharedTypeSchemaView( listTypeInternal(elementTypeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView lub(SharedTypeView type1, - SharedTypeView type2) { + SharedTypeView lub(SharedTypeView type1, SharedTypeView type2) { return new SharedTypeView( lubInternal(type1.unwrapTypeView(), type2.unwrapTypeView())); } @override - SharedTypeView makeNullable( - SharedTypeView type) { + SharedTypeView makeNullable(SharedTypeView type) { return new SharedTypeView(makeNullableInternal(type.unwrapTypeView())); } @override - SharedTypeSchemaView makeTypeSchemaNullable( - SharedTypeSchemaView typeSchema) { + SharedTypeSchemaView makeTypeSchemaNullable(SharedTypeSchemaView typeSchema) { return new SharedTypeSchemaView( makeNullableInternal(typeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView mapType({ - required SharedTypeView keyType, - required SharedTypeView valueType, + SharedTypeView mapType({ + required SharedTypeView keyType, + required SharedTypeView valueType, }) { return new SharedTypeView(mapTypeInternal( keyType: keyType.unwrapTypeView(), @@ -830,119 +777,111 @@ mixin TypeAnalyzerOperationsMixin< } @override - SharedTypeSchemaView mapTypeSchema( - {required SharedTypeSchemaView keyTypeSchema, - required SharedTypeSchemaView valueTypeSchema}) { + SharedTypeSchemaView mapTypeSchema( + {required SharedTypeSchemaView keyTypeSchema, + required SharedTypeSchemaView valueTypeSchema}) { return new SharedTypeSchemaView(mapTypeInternal( keyType: keyTypeSchema.unwrapTypeSchemaView(), valueType: valueTypeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView? matchFutureOr( - SharedTypeView type) { + SharedTypeView? matchFutureOr(SharedTypeView type) { return matchFutureOrInternal(type.unwrapTypeView())?.wrapSharedTypeView(); } @override - SharedTypeView? matchIterableType( - SharedTypeView type) { + SharedTypeView? matchIterableType(SharedTypeView type) { return matchIterableTypeInternal(type.unwrapTypeView()) ?.wrapSharedTypeView(); } @override - SharedTypeSchemaView? matchIterableTypeSchema( - SharedTypeSchemaView typeSchema) { + SharedTypeSchemaView? matchIterableTypeSchema( + SharedTypeSchemaView typeSchema) { return matchIterableTypeInternal(typeSchema.unwrapTypeSchemaView()) ?.wrapSharedTypeSchemaView(); } @override - SharedTypeSchemaView? matchTypeSchemaFutureOr( - SharedTypeSchemaView typeSchema) { + SharedTypeSchemaView? matchTypeSchemaFutureOr( + SharedTypeSchemaView typeSchema) { return matchFutureOrInternal(typeSchema.unwrapTypeSchemaView()) ?.wrapSharedTypeSchemaView(); } @override - SharedTypeView recordType( - {required List> positional, - required List<(String, SharedTypeView)> named}) { + SharedTypeView recordType( + {required List positional, + required List<(String, SharedTypeView)> named}) { return new SharedTypeView(recordTypeInternal( - positional: positional.cast(), - named: named.cast<(String, TypeStructure)>())); + positional: positional.cast(), + named: named.cast<(String, SharedType)>())); } @override - SharedTypeSchemaView recordTypeSchema( - {required List> positional, - required List<(String, SharedTypeSchemaView)> named}) { + SharedTypeSchemaView recordTypeSchema( + {required List positional, + required List<(String, SharedTypeSchemaView)> named}) { return new SharedTypeSchemaView(recordTypeInternal( - positional: positional.cast(), - named: named.cast<(String, TypeStructure)>())); + positional: positional.cast(), + named: named.cast<(String, SharedType)>())); } @override - bool typeIsSubtypeOfTypeSchema(SharedTypeView leftType, - SharedTypeSchemaView rightSchema) { + bool typeIsSubtypeOfTypeSchema( + SharedTypeView leftType, SharedTypeSchemaView rightSchema) { return isSubtypeOfInternal( leftType.unwrapTypeView(), rightSchema.unwrapTypeSchemaView()); } @override - SharedTypeSchemaView typeSchemaGlb( - SharedTypeSchemaView typeSchema1, - SharedTypeSchemaView typeSchema2) { + SharedTypeSchemaView typeSchemaGlb( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2) { return new SharedTypeSchemaView(glbInternal( typeSchema1.unwrapTypeSchemaView(), typeSchema2.unwrapTypeSchemaView())); } @override - bool typeSchemaIsSubtypeOfType(SharedTypeSchemaView leftSchema, - SharedTypeView rightType) { + bool typeSchemaIsSubtypeOfType( + SharedTypeSchemaView leftSchema, SharedTypeView rightType) { return isSubtypeOfInternal( leftSchema.unwrapTypeSchemaView(), rightType.unwrapTypeView()); } @override bool typeSchemaIsSubtypeOfTypeSchema( - SharedTypeSchemaView leftSchema, - SharedTypeSchemaView rightSchema) { + SharedTypeSchemaView leftSchema, SharedTypeSchemaView rightSchema) { return isSubtypeOfInternal( leftSchema.unwrapTypeSchemaView(), rightSchema.unwrapTypeSchemaView()); } @override - SharedTypeSchemaView typeSchemaLub( - SharedTypeSchemaView typeSchema1, - SharedTypeSchemaView typeSchema2) { + SharedTypeSchemaView typeSchemaLub( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2) { return new SharedTypeSchemaView(lubInternal( typeSchema1.unwrapTypeSchemaView(), typeSchema2.unwrapTypeSchemaView())); } @override - SharedTypeSchemaView typeToSchema( - SharedTypeView type) { + SharedTypeSchemaView typeToSchema(SharedTypeView type) { return new SharedTypeSchemaView(type.unwrapTypeView()); } @override - MergedTypeConstraint + MergedTypeConstraint mergeInConstraintsFromBound( - {required TypeParameterStructure typeParameterToInfer, - required List typeParametersToInfer, - required TypeStructure lower, + {required SharedTypeParameter typeParameterToInfer, + required List typeParametersToInfer, + required SharedType lower, required Map< - TypeParameterStructure, - MergedTypeConstraint> + SharedTypeParameter, + MergedTypeConstraint> inferencePhaseConstraints, - required TypeConstraintGenerationDataForTesting? + required TypeConstraintGenerationDataForTesting? dataForTesting, required bool inferenceUsingBoundsIsEnabled}) { // The type parameter's bound may refer to itself (or other type @@ -967,17 +906,11 @@ mixin TypeAnalyzerOperationsMixin< // constraints (i.e. `X <: B` in this example), then they are added to // the set of constraints just before choosing the final type. - TypeStructure typeParameterToInferBound = typeParameterToInfer.boundShared!; + SharedType typeParameterToInferBound = typeParameterToInfer.boundShared!; // TODO(cstefantsova): Pass [dataForTesting] when // [InferenceDataForTesting] is merged with [TypeInferenceResultForTesting]. - TypeConstraintGenerator< - TypeStructure, - SharedNamedFunctionParameterStructure, - Variable, - TypeParameterStructure, - TypeDeclarationType, - TypeDeclaration, + TypeConstraintGenerator typeConstraintGatherer = createTypeConstraintGenerator( typeConstraintGenerationDataForTesting: null, @@ -988,19 +921,13 @@ mixin TypeAnalyzerOperationsMixin< lower, typeParameterToInferBound, leftSchema: true, astNodeForTesting: null); Map< - TypeParameterStructure, - MergedTypeConstraint< - TypeStructure, - TypeParameterStructure, - Variable, - TypeDeclarationType, + SharedTypeParameter, + MergedTypeConstraint> constraintsPerTypeVariable = typeConstraintGatherer.computeConstraints(); - for (TypeParameterStructure typeParameter - in constraintsPerTypeVariable.keys) { - MergedTypeConstraint constraint = - constraintsPerTypeVariable[typeParameter]!; + for (SharedTypeParameter typeParameter in constraintsPerTypeVariable.keys) { + MergedTypeConstraint + constraint = constraintsPerTypeVariable[typeParameter]!; constraint.origin = new TypeConstraintFromExtendsClause( typeParameterName: typeParameterToInfer.displayName, boundType: new SharedTypeView(typeParameterToInferBound), @@ -1022,11 +949,7 @@ mixin TypeAnalyzerOperationsMixin< /// Abstract interface of a type constraint generator. abstract class TypeConstraintGenerator< - TypeStructure extends SharedTypeStructure, - FunctionParameterStructure extends SharedNamedFunctionParameterStructure< - TypeStructure>, Variable extends Object, - TypeParameterStructure extends SharedTypeParameterStructure, TypeDeclarationType extends Object, TypeDeclaration extends Object, AstNode extends Object> { @@ -1052,20 +975,20 @@ abstract class TypeConstraintGenerator< bool get enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr; /// Abstract type operations to be used in the matching methods. - TypeAnalyzerOperations get typeAnalyzerOperations; + TypeAnalyzerOperations + get typeAnalyzerOperations; /// Type parameters being constrained by [TypeConstraintGenerator]. - Iterable get typeParametersToConstrain; + Iterable get typeParametersToConstrain; /// Add constraint: [lower] <: [typeParameter] <: TOP. void addLowerConstraintForParameter( - TypeParameterStructure typeParameter, TypeStructure lower, + covariant SharedTypeParameter typeParameter, covariant SharedType lower, {required AstNode? astNodeForTesting}); /// Add constraint: BOTTOM <: [typeParameter] <: [upper]. void addUpperConstraintForParameter( - TypeParameterStructure typeParameter, TypeStructure upper, + covariant SharedTypeParameter typeParameter, covariant SharedType upper, {required AstNode? astNodeForTesting}); /// Iterates over all of the type constraints generated since @@ -1076,14 +999,14 @@ abstract class TypeConstraintGenerator< /// algorithm, in the step for generic function types. See /// https://github.com/dart-lang/language/blob/main/resources/type-system/inference.md#subtype-constraint-generation. void eliminateTypeParametersInGeneratedConstraints( - List typeParametersToEliminate, + List typeParametersToEliminate, TypeConstraintGeneratorState eliminationStartState, {required AstNode? astNodeForTesting}); /// Returns the type arguments of the supertype of [type] that is an /// instantiation of [typeDeclaration]. If none of the supertypes of [type] /// are instantiations of [typeDeclaration], returns null. - List? getTypeArgumentsAsInstanceOf( + List? getTypeArgumentsAsInstanceOf( TypeDeclarationType type, TypeDeclaration typeDeclaration); /// Creates fresh type parameters, instantiates the non-generic parts of [p] @@ -1095,16 +1018,11 @@ abstract class TypeConstraintGenerator< /// algorithm, in the step for the generic function types. See /// https://github.com/dart-lang/language/blob/main/resources/type-system/inference.md#subtype-constraint-generation. ( - TypeStructure, - TypeStructure, { - List typeParametersToEliminate + SharedType, + SharedType, { + List typeParametersToEliminate }) instantiateFunctionTypesAndProvideFreshTypeParameters( - SharedFunctionTypeStructure - p, - SharedFunctionTypeStructure - q, + covariant SharedFunctionType p, covariant SharedFunctionType q, {required bool leftSchema}); /// Matches [p] against [q]. @@ -1119,12 +1037,9 @@ abstract class TypeConstraintGenerator< /// be simply a type. If [leftSchema] is `true`, [p] may contain `_`; if it /// is `false`, [q] may contain `_`. bool performSubtypeConstraintGenerationForFunctionTypes( - TypeStructure p, TypeStructure q, + SharedType p, SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { - if (p is SharedFunctionTypeStructure && - q is SharedFunctionTypeStructure) { + if (p is SharedFunctionType && q is SharedFunctionType) { if (p.typeParametersShared.isEmpty && q.typeParametersShared.isEmpty) { return _handleNonGenericFunctionTypes(p, q, leftSchema: leftSchema, astNodeForTesting: astNodeForTesting); @@ -1150,7 +1065,7 @@ abstract class TypeConstraintGenerator< /// be simply a type. If [leftSchema] is `true`, [p] may contain `_`; if it is /// `false`, [q] may contain `_`. bool performSubtypeConstraintGenerationForLeftFutureOr( - TypeStructure p, TypeStructure q, + SharedType p, SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { // If `P` is `FutureOr` the match holds under constraint set `C1 + C2`: NullabilitySuffix pNullability = p.nullabilitySuffix; @@ -1160,7 +1075,7 @@ abstract class TypeConstraintGenerator< // If `Future` is a subtype match for `Q` under constraint set `C1`. // And if `P0` is a subtype match for `Q` under constraint set `C2`. - TypeStructure futureP0 = typeAnalyzerOperations.futureTypeInternal(p0); + SharedType futureP0 = typeAnalyzerOperations.futureTypeInternal(p0); if (performSubtypeConstraintGenerationInternal(futureP0, q, leftSchema: leftSchema, astNodeForTesting: astNodeForTesting) && performSubtypeConstraintGenerationInternal(p0, q, @@ -1187,12 +1102,12 @@ abstract class TypeConstraintGenerator< /// be simply a type. If [leftSchema] is `true`, [p] may contain `_`; if it is /// `false`, [q] may contain `_`. bool performSubtypeConstraintGenerationForLeftNullableType( - TypeStructure p, TypeStructure q, + SharedType p, SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { // If `P` is `P0?` the match holds under constraint set `C1 + C2`: NullabilitySuffix pNullability = p.nullabilitySuffix; if (pNullability == NullabilitySuffix.question) { - TypeStructure p0 = typeAnalyzerOperations.withNullabilitySuffixInternal( + SharedType p0 = typeAnalyzerOperations.withNullabilitySuffixInternal( p, NullabilitySuffix.none); final TypeConstraintGeneratorState state = currentState; @@ -1219,10 +1134,9 @@ abstract class TypeConstraintGenerator< /// the constraint state is unchanged (or rolled back), and `false` is /// returned. bool performSubtypeConstraintGenerationForRecordTypes( - TypeStructure p, TypeStructure q, + SharedType p, SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { - if (p is! SharedRecordTypeStructure || - q is! SharedRecordTypeStructure) { + if (p is! SharedRecordType || q is! SharedRecordType) { return false; } @@ -1280,17 +1194,17 @@ abstract class TypeConstraintGenerator< /// be simply a type. If [leftSchema] is `true`, [p] may contain `_`; if it is /// `false`, [q] may contain `_`. bool performSubtypeConstraintGenerationForRightFutureOr( - TypeStructure p, TypeStructure q, + SharedType p, SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { // If `Q` is `FutureOr` the match holds under constraint set `C`: - if (typeAnalyzerOperations.matchFutureOrInternal(q) case TypeStructure q0? + if (typeAnalyzerOperations.matchFutureOrInternal(q) case SharedType q0? when enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr || q.nullabilitySuffix == NullabilitySuffix.none) { final TypeConstraintGeneratorState state = currentState; // If `P` is `FutureOr` and `P0` is a subtype match for `Q0` under // constraint set `C`. - if (typeAnalyzerOperations.matchFutureOrInternal(p) case TypeStructure p0? + if (typeAnalyzerOperations.matchFutureOrInternal(p) case SharedType p0? when enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr || p.nullabilitySuffix == NullabilitySuffix.none) { if (performSubtypeConstraintGenerationInternal(p0, q0, @@ -1338,12 +1252,12 @@ abstract class TypeConstraintGenerator< /// be simply a type. If [leftSchema] is `true`, [p] may contain `_`; if it is /// `false`, [q] may contain `_`. bool performSubtypeConstraintGenerationForRightNullableType( - TypeStructure p, TypeStructure q, + SharedType p, SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { // If `Q` is `Q0?` the match holds under constraint set `C`: NullabilitySuffix qNullability = q.nullabilitySuffix; if (qNullability == NullabilitySuffix.question) { - TypeStructure q0 = typeAnalyzerOperations.withNullabilitySuffixInternal( + SharedType q0 = typeAnalyzerOperations.withNullabilitySuffixInternal( q, NullabilitySuffix.none); final TypeConstraintGeneratorState state = currentState; @@ -1351,7 +1265,7 @@ abstract class TypeConstraintGenerator< // constraint set `C`. NullabilitySuffix pNullability = p.nullabilitySuffix; if (pNullability == NullabilitySuffix.question) { - TypeStructure p0 = typeAnalyzerOperations.withNullabilitySuffixInternal( + SharedType p0 = typeAnalyzerOperations.withNullabilitySuffixInternal( p, NullabilitySuffix.none); if (performSubtypeConstraintGenerationInternal(p0, q0, leftSchema: leftSchema, astNodeForTesting: astNodeForTesting)) { @@ -1361,7 +1275,7 @@ abstract class TypeConstraintGenerator< // Or if `P` is `dynamic` or `void` and `Object` is a subtype match // for `Q0` under constraint set `C`. - if (p is SharedDynamicTypeStructure || p is SharedVoidTypeStructure) { + if (p is SharedDynamicType || p is SharedVoidType) { if (performSubtypeConstraintGenerationInternal( typeAnalyzerOperations.objectType.unwrapTypeView(), q0, leftSchema: leftSchema, astNodeForTesting: astNodeForTesting)) { @@ -1411,7 +1325,7 @@ abstract class TypeConstraintGenerator< /// be simply a type. If [leftSchema] is `true`, [p] may contain `_`; if it is /// `false`, [q] may contain `_`. bool? performSubtypeConstraintGenerationForTypeDeclarationTypes( - TypeStructure p, TypeStructure q, + SharedType p, SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { switch (( typeAnalyzerOperations.matchTypeDeclarationTypeInternal(p), @@ -1425,12 +1339,12 @@ abstract class TypeConstraintGenerator< TypeDeclarationMatchResult( typeDeclarationKind: TypeDeclarationKind pTypeDeclarationKind, typeDeclaration: TypeDeclaration pDeclarationObject, - typeArguments: List pTypeArguments + typeArguments: List pTypeArguments ), TypeDeclarationMatchResult( typeDeclarationKind: TypeDeclarationKind qTypeDeclarationKind, typeDeclaration: TypeDeclaration qDeclarationObject, - typeArguments: List qTypeArguments + typeArguments: List qTypeArguments ) ) when pTypeDeclarationKind == qTypeDeclarationKind && @@ -1476,15 +1390,15 @@ abstract class TypeConstraintGenerator< /// implementation of both [performSubtypeConstraintGenerationLeftSchema] and /// [performSubtypeConstraintGenerationRightSchema] from the mixin. bool performSubtypeConstraintGenerationInternal( - TypeStructure p, TypeStructure q, + covariant SharedType p, covariant SharedType q, {required bool leftSchema, required AstNode? astNodeForTesting}) { // If `P` is `_` then the match holds with no constraints. - if (p is SharedUnknownTypeStructure) { + if (p is SharedUnknownType) { return true; } // If `Q` is `_` then the match holds with no constraints. - if (q is SharedUnknownTypeStructure) { + if (q is SharedUnknownType) { return true; } @@ -1553,8 +1467,8 @@ abstract class TypeConstraintGenerator< // If `Q` is `dynamic`, `Object?`, or `void` then the match holds under // no constraints. - if (q is SharedDynamicTypeStructure || - q is SharedVoidTypeStructure || + if (q is SharedDynamicType || + q is SharedVoidType || q == typeAnalyzerOperations.objectQuestionType.unwrapTypeView()) { return true; } @@ -1572,7 +1486,7 @@ abstract class TypeConstraintGenerator< // If `P` is `Null`, then the match holds under no constraints: // Only if `Q` is nullable. - if (p is SharedNullTypeStructure) { + if (p is SharedNullType) { return typeAnalyzerOperations.isNullableInternal(q); } @@ -1598,7 +1512,7 @@ abstract class TypeConstraintGenerator< // If `Q` is `Function` then the match holds under no constraints: // If `P` is a function type. if (typeAnalyzerOperations.isDartCoreFunctionInternal(q)) { - if (p is SharedFunctionTypeStructure) { + if (p is SharedFunctionType) { return true; } } @@ -1612,7 +1526,7 @@ abstract class TypeConstraintGenerator< // constraints: // If `P` is a record type or `Record`. if (typeAnalyzerOperations.isDartCoreRecordInternal(q)) { - if (p is SharedRecordTypeStructure) { + if (p is SharedRecordType) { return true; } } @@ -1639,7 +1553,7 @@ abstract class TypeConstraintGenerator< /// The algorithm for subtype constraint generation is described in /// https://github.com/dart-lang/language/blob/main/resources/type-system/inference.md#subtype-constraint-generation bool performSubtypeConstraintGenerationLeftSchema( - SharedTypeSchemaView p, SharedTypeView q, + SharedTypeSchemaView p, SharedTypeView q, {required AstNode? astNodeForTesting}); /// Matches type [p] against type schema [q] as a subtype against supertype, @@ -1656,7 +1570,7 @@ abstract class TypeConstraintGenerator< /// The algorithm for subtype constraint generation is described in /// https://github.com/dart-lang/language/blob/main/resources/type-system/inference.md#subtype-constraint-generation bool performSubtypeConstraintGenerationRightSchema( - SharedTypeView p, SharedTypeSchemaView q, + SharedTypeView p, SharedTypeSchemaView q, {required AstNode? astNodeForTesting}); /// Restores the constraint generator to [state]. @@ -1669,15 +1583,8 @@ abstract class TypeConstraintGenerator< /// /// See the documentation on /// [performSubtypeConstraintGenerationForFunctionTypes] for details. - bool _handleGenericFunctionTypes( - SharedFunctionTypeStructure - p, - SharedFunctionTypeStructure - q, - {required bool leftSchema, - required AstNode? astNodeForTesting}) { + bool _handleGenericFunctionTypes(SharedFunctionType p, SharedFunctionType q, + {required bool leftSchema, required AstNode? astNodeForTesting}) { assert( p.typeParametersShared.isNotEmpty || q.typeParametersShared.isNotEmpty); // A generic function type F0 is a @@ -1749,14 +1656,8 @@ abstract class TypeConstraintGenerator< /// See the documentation on /// [performSubtypeConstraintGenerationForFunctionTypes] for details. bool _handleNonGenericFunctionTypes( - SharedFunctionTypeStructure - p, - SharedFunctionTypeStructure - q, - {required bool leftSchema, - required AstNode? astNodeForTesting}) { + SharedFunctionType p, SharedFunctionType q, + {required bool leftSchema, required AstNode? astNodeForTesting}) { assert(p.typeParametersShared.isEmpty && q.typeParametersShared.isEmpty); // A function type (M0,..., Mn, [M{n+1}, ..., Mm]) -> R0 is a subtype // match for a function type (N0,..., Nk, [N{k+1}, ..., Nr]) -> R1 with @@ -1886,8 +1787,8 @@ abstract class TypeConstraintGenerator< /// If returns `false`, the constraints are unchanged. bool _interfaceTypeArguments( TypeDeclaration declaration, - List pTypeArguments, - List qTypeArguments, + List pTypeArguments, + List qTypeArguments, bool leftSchema, {required AstNode? astNodeForTesting}) { assert(pTypeArguments.length == qTypeArguments.length); @@ -1897,8 +1798,8 @@ abstract class TypeConstraintGenerator< for (int i = 0; i < pTypeArguments.length; i++) { Variance variance = typeAnalyzerOperations.getTypeParameterVariance(declaration, i); - TypeStructure M = pTypeArguments[i]; - TypeStructure N = qTypeArguments[i]; + SharedType M = pTypeArguments[i]; + SharedType N = qTypeArguments[i]; if ((variance == Variance.covariant || variance == Variance.invariant) && !performSubtypeConstraintGenerationInternal(M, N, leftSchema: leftSchema, astNodeForTesting: astNodeForTesting)) { @@ -1924,7 +1825,7 @@ abstract class TypeConstraintGenerator< /// the relation possible are recorded, and `true` is returned. Otherwise, /// the constraint state is unchanged (or rolled back using [restoreState]), /// and `false` is returned. - bool _interfaceTypes(TypeStructure p, TypeStructure q, bool leftSchema, + bool _interfaceTypes(SharedType p, SharedType q, bool leftSchema, {required AstNode? astNodeForTesting}) { if (p.nullabilitySuffix != NullabilitySuffix.none) { return false; @@ -1950,11 +1851,11 @@ abstract class TypeConstraintGenerator< ), TypeDeclarationMatchResult( typeDeclaration: TypeDeclaration qTypeDeclaration, - typeArguments: List qTypeArguments + typeArguments: List qTypeArguments ) )) { if (getTypeArgumentsAsInstanceOf(pTypeDeclarationType, qTypeDeclaration) - case List typeArguments) { + case List typeArguments) { return _interfaceTypeArguments( qTypeDeclaration, typeArguments, qTypeArguments, leftSchema, astNodeForTesting: astNodeForTesting); @@ -1965,36 +1866,21 @@ abstract class TypeConstraintGenerator< } /// Returns the set of type constraints that was gathered. - Map< - TypeParameterStructure, - MergedTypeConstraint> computeConstraints(); + Map> + computeConstraints(); } mixin TypeConstraintGeneratorMixin< - TypeStructure extends SharedTypeStructure, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - FunctionParameterStructure extends SharedNamedFunctionParameterStructure< - TypeStructure>, Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, TypeDeclarationType extends Object, TypeDeclaration extends Object, AstNode extends Object> - on TypeConstraintGenerator< - TypeStructure, - FunctionParameterStructure, - Variable, - TypeParameterStructure, - TypeDeclarationType, - TypeDeclaration, + on TypeConstraintGenerator { @override bool performSubtypeConstraintGenerationLeftSchema( - SharedTypeSchemaView p, SharedTypeView q, + SharedTypeSchemaView p, SharedTypeView q, {required AstNode? astNodeForTesting}) { return performSubtypeConstraintGenerationInternal( p.unwrapTypeSchemaView(), q.unwrapTypeView(), @@ -2003,7 +1889,7 @@ mixin TypeConstraintGeneratorMixin< @override bool performSubtypeConstraintGenerationRightSchema( - SharedTypeView p, SharedTypeSchemaView q, + SharedTypeView p, SharedTypeSchemaView q, {required AstNode? astNodeForTesting}) { return performSubtypeConstraintGenerationInternal( p.unwrapTypeView(), q.unwrapTypeSchemaView(), @@ -2035,11 +1921,12 @@ enum TypeDeclarationKind { /// its components that can be used for the further analysis of the type in the /// algorithms related to type inference. class TypeDeclarationMatchResult { + TypeDeclaration extends Object> { /// The kind of type declaration the matched type is of. final TypeDeclarationKind typeDeclarationKind; - /// A more specific subtype of [Type] describing the matched type. + /// A more specific subtype of [SharedType] describing the + /// matched type. /// /// This is client-specific is needed to avoid unnecessary downcasts. final TypeDeclarationType typeDeclarationType; @@ -2051,10 +1938,11 @@ class TypeDeclarationMatchResult typeArguments; + final List typeArguments; TypeDeclarationMatchResult( {required this.typeDeclarationKind, diff --git a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_constraint.dart b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_constraint.dart index 7a8a79dc3bca..23c6e06f496a 100644 --- a/pkg/_fe_analyzer_shared/lib/src/type_inference/type_constraint.dart +++ b/pkg/_fe_analyzer_shared/lib/src/type_inference/type_constraint.dart @@ -9,15 +9,12 @@ import 'type_analyzer_operations.dart'; /// /// We require that `typeParameter <: constraint` if `isUpper` is true, and /// `constraint <: typeParameter` otherwise. -class GeneratedTypeConstraint< - TypeStructure extends SharedTypeStructure, - TypeParameterStructure extends SharedTypeParameterStructure, - Variable extends Object> { +class GeneratedTypeConstraint { /// The type parameter that is constrained by [constraint]. - final TypeParameterStructure typeParameter; + final SharedTypeParameterView typeParameter; /// The type schema constraining the type parameter. - final SharedTypeSchemaView constraint; + final SharedTypeSchemaView constraint; /// True if `typeParameter <: constraint`, and false otherwise. /// @@ -38,12 +35,8 @@ class GeneratedTypeConstraint< } /// A constraint on a type parameter that we're inferring. -class MergedTypeConstraint< - TypeStructure extends SharedTypeStructure, - TypeParameterStructure extends SharedTypeParameterStructure, - Variable extends Object, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> { +class MergedTypeConstraint { /// The lower bound of the type being constrained. This bound must be a /// subtype of the type being constrained. In other words, lowerBound <: T. /// @@ -63,7 +56,7 @@ class MergedTypeConstraint< /// In the example above `num` is chosen as the greatest upper bound between /// `int` and `double`, so the resulting constraint is equal or stronger than /// either of the two. - SharedTypeSchemaView lower; + SharedTypeSchemaView lower; /// The upper bound of the type being constrained. The type being constrained /// must be a subtype of this bound. In other words, T <: upperBound. @@ -87,21 +80,20 @@ class MergedTypeConstraint< /// /// Here the [lower] will be `String` and the upper bound will be `num`, /// which cannot be satisfied, so this is ill typed. - SharedTypeSchemaView upper; + SharedTypeSchemaView upper; /// Where this constraint comes from, used for error messages. - TypeConstraintOrigin origin; + TypeConstraintOrigin origin; MergedTypeConstraint( {required this.lower, required this.upper, required this.origin}); MergedTypeConstraint.fromExtends( {required String typeParameterName, - required SharedTypeView boundType, - required SharedTypeView extendsType, - required TypeAnalyzerOperations + required SharedTypeView boundType, + required SharedTypeView extendsType, + required TypeAnalyzerOperations typeAnalyzerOperations}) : this( origin: new TypeConstraintFromExtendsClause( @@ -112,33 +104,27 @@ class MergedTypeConstraint< upper: typeAnalyzerOperations.typeToSchema(extendsType), lower: typeAnalyzerOperations.unknownType); - MergedTypeConstraint clone() { + MergedTypeConstraint clone() { return new MergedTypeConstraint(lower: lower, upper: upper, origin: origin); } bool isEmpty( - TypeAnalyzerOperations + TypeAnalyzerOperations typeAnalyzerOperations) { - return lower is SharedUnknownTypeStructure && - upper is SharedUnknownTypeStructure; + return lower is SharedUnknownType && upper is SharedUnknownType; } bool isSatisfiedBy( - SharedTypeView type, - TypeAnalyzerOperations + SharedTypeView type, + TypeAnalyzerOperations typeAnalyzerOperations) { return typeAnalyzerOperations.typeIsSubtypeOfTypeSchema(type, upper) && typeAnalyzerOperations.typeSchemaIsSubtypeOfType(lower, type); } void mergeIn( - GeneratedTypeConstraint - generatedTypeConstraint, - TypeAnalyzerOperations + GeneratedTypeConstraint generatedTypeConstraint, + TypeAnalyzerOperations typeAnalyzerOperations) { if (generatedTypeConstraint.isUpper) { mergeInTypeSchemaUpper( @@ -150,17 +136,15 @@ class MergedTypeConstraint< } void mergeInTypeSchemaLower( - SharedTypeSchemaView constraint, - TypeAnalyzerOperations + SharedTypeSchemaView constraint, + TypeAnalyzerOperations typeAnalyzerOperations) { lower = typeAnalyzerOperations.typeSchemaLub(lower, constraint); } void mergeInTypeSchemaUpper( - SharedTypeSchemaView constraint, - TypeAnalyzerOperations + SharedTypeSchemaView constraint, + TypeAnalyzerOperations typeAnalyzerOperations) { upper = typeAnalyzerOperations.typeSchemaGlb(upper, constraint); } @@ -171,18 +155,12 @@ class MergedTypeConstraint< } } -class TypeConstraintFromArgument< - TypeStructure extends SharedTypeStructure, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin { - final SharedTypeView argumentType; - final SharedTypeView parameterType; +class TypeConstraintFromArgument + extends TypeConstraintOrigin { + final SharedTypeView argumentType; + final SharedTypeView parameterType; final String parameterName; final String? genericClassName; final bool isGenericClassInDartCore; @@ -196,8 +174,7 @@ class TypeConstraintFromArgument< @override List formatError( - TypeAnalyzerOperations + TypeAnalyzerOperations typeAnalyzerOperations) { // TODO(cstefantsova): we should highlight the span. That would be more // useful. However in summary code it doesn't look like the AST node with @@ -222,16 +199,10 @@ class TypeConstraintFromArgument< } } -class TypeConstraintFromExtendsClause< - TypeStructure extends SharedTypeStructure, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin { +class TypeConstraintFromExtendsClause + extends TypeConstraintOrigin { /// Name of the type parameter with the extends clause. final String typeParameterName; @@ -239,13 +210,13 @@ class TypeConstraintFromExtendsClause< /// this clause only when it is not `null`. /// /// For example `Iterable` for `>`. - final SharedTypeView boundType; + final SharedTypeView boundType; /// [boundType] in which type parameters are substituted with inferred /// type arguments. /// /// For example `Iterable` if `T` inferred to `int`. - final SharedTypeView extendsType; + final SharedTypeView extendsType; TypeConstraintFromExtendsClause( {required this.typeParameterName, @@ -254,8 +225,7 @@ class TypeConstraintFromExtendsClause< @override List formatError( - TypeAnalyzerOperations + TypeAnalyzerOperations typeAnalyzerOperations) { String boundStr = boundType.getDisplayString(); String extendsStr = extendsType.getDisplayString(); @@ -266,28 +236,19 @@ class TypeConstraintFromExtendsClause< } } -class TypeConstraintFromFunctionContext< - TypeStructure extends SharedTypeStructure, - Type extends SharedTypeStructure, - TypeSchema extends SharedTypeStructure, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin { - final Type contextType; - final Type functionType; +class TypeConstraintFromFunctionContext + extends TypeConstraintOrigin { + final SharedType contextType; + final SharedType functionType; TypeConstraintFromFunctionContext( {required this.functionType, required this.contextType}); @override List formatError( - TypeAnalyzerOperations + TypeAnalyzerOperations typeAnalyzerOperations) { return [ "Function type", @@ -297,28 +258,19 @@ class TypeConstraintFromFunctionContext< } } -class TypeConstraintFromReturnType< - TypeStructure extends SharedTypeStructure, - Type extends SharedTypeStructure, - TypeSchema extends SharedTypeStructure, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin { - final Type contextType; - final Type declaredType; +class TypeConstraintFromReturnType + extends TypeConstraintOrigin { + final SharedType contextType; + final SharedType declaredType; TypeConstraintFromReturnType( {required this.declaredType, required this.contextType}); @override List formatError( - TypeAnalyzerOperations + TypeAnalyzerOperations typeAnalyzerOperations) { return [ "Return type", @@ -331,36 +283,24 @@ class TypeConstraintFromReturnType< /// The origin of a type constraint, for the purposes of producing a human /// readable error message during type inference as well as determining whether /// the constraint was used to fix the type parameter or not. -abstract class TypeConstraintOrigin< - TypeStructure extends SharedTypeStructure, - Variable extends Object, - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> { +abstract class TypeConstraintOrigin { const TypeConstraintOrigin(); List formatError( - TypeAnalyzerOperations + TypeAnalyzerOperations typeAnalyzerOperations); } -class UnknownTypeConstraintOrigin< - TypeStructure extends SharedTypeStructure, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin { +class UnknownTypeConstraintOrigin + extends TypeConstraintOrigin { const UnknownTypeConstraintOrigin(); @override List formatError( - TypeAnalyzerOperations + TypeAnalyzerOperations typeAnalyzerOperations) { return []; } @@ -369,18 +309,12 @@ class UnknownTypeConstraintOrigin< /// Data structure maintaining intermediate type inference results, such as /// type constraints, for testing purposes. Under normal execution, no /// instance of this class should be created. -class TypeConstraintGenerationDataForTesting< - TypeStructure extends SharedTypeStructure, - TypeParameterStructure extends SharedTypeParameterStructure, - Variable extends Object, +class TypeConstraintGenerationDataForTesting { /// Map from nodes requiring type inference to the generated type constraints /// for the node. - final Map< - AstNode, - List< - GeneratedTypeConstraint>> generatedTypeConstraints = {}; + final Map>> + generatedTypeConstraints = {}; /// Merges [other] into the receiver, combining the constraints. /// @@ -389,9 +323,7 @@ class TypeConstraintGenerationDataForTesting< /// because the changes made to the reused structures will be visible to /// [other]. void mergeIn( - TypeConstraintGenerationDataForTesting - other) { + TypeConstraintGenerationDataForTesting other) { for (AstNode node in other.generatedTypeConstraints.keys) { List? constraints = generatedTypeConstraints[node]; diff --git a/pkg/_fe_analyzer_shared/lib/src/types/shared_type.dart b/pkg/_fe_analyzer_shared/lib/src/types/shared_type.dart index 5ed4fb1cba54..a4f096c07ebc 100644 --- a/pkg/_fe_analyzer_shared/lib/src/types/shared_type.dart +++ b/pkg/_fe_analyzer_shared/lib/src/types/shared_type.dart @@ -6,33 +6,27 @@ import '../type_inference/nullability_suffix.dart'; /// Common interface for data structures used by the implementations to /// represent the type `dynamic`. -abstract interface class SharedDynamicTypeStructure< - TypeStructure extends SharedTypeStructure> - implements SharedTypeStructure {} +abstract interface class SharedDynamicType implements SharedType {} /// Common interface for data structures used by the implementations to /// represent function types. -abstract interface class SharedFunctionTypeStructure< - TypeStructure extends SharedTypeStructure, - TypeParameterStructure extends SharedTypeParameterStructure, - FunctionParameterStructure extends SharedNamedFunctionParameterStructure< - TypeStructure>> implements SharedTypeStructure { +abstract interface class SharedFunctionType implements SharedType { /// All the positional parameter types, starting with the required ones, and /// followed by the optional ones. - List get positionalParameterTypesShared; + List get positionalParameterTypesShared; /// The number of elements of [positionalParameterTypesShared] that are /// required parameters. int get requiredPositionalParameterCount; /// The return type. - TypeStructure get returnTypeShared; + SharedType get returnTypeShared; /// All the named parameters, sorted by name. - List get sortedNamedParametersShared; + List get sortedNamedParametersShared; /// The type parameters of the function type. - List get typeParametersShared; + List get typeParametersShared; } /// Common interface for data structures used by the implementations to @@ -40,14 +34,11 @@ abstract interface class SharedFunctionTypeStructure< /// /// The implementations may choose to suppress further errors that arise from /// the use of this type. -abstract interface class SharedInvalidTypeStructure< - TypeStructure extends SharedTypeStructure> - implements SharedTypeStructure {} +abstract interface class SharedInvalidType implements SharedType {} /// Common interface for data structures used by the implementations to /// represent a named parameter of a function type. -abstract interface class SharedNamedFunctionParameterStructure< - TypeStructure extends SharedTypeStructure> { +abstract interface class SharedNamedFunctionParameter { /// Whether this named parameter is required. bool get isRequired; @@ -55,40 +46,35 @@ abstract interface class SharedNamedFunctionParameterStructure< String get nameShared; /// The type of the parameter. - TypeStructure get typeShared; + SharedType get typeShared; } /// Common interface for data structures used by the implementations to /// represent a name/type pair. -abstract interface class SharedNamedTypeStructure< - TypeStructure extends SharedTypeStructure> { +abstract interface class SharedNamedType { String get nameShared; - TypeStructure get typeShared; + + SharedType get typeShared; } /// Common interface for data structures used by implementations to represent /// the type `Null`. -abstract interface class SharedNullTypeStructure< - TypeStructure extends SharedTypeStructure> - implements SharedTypeStructure {} +abstract interface class SharedNullType implements SharedType {} /// Common interface for data structures used by the implementations to /// represent a record type. -abstract interface class SharedRecordTypeStructure< - TypeStructure extends SharedTypeStructure> - implements SharedTypeStructure { - List get positionalTypesShared; +abstract interface class SharedRecordType implements SharedType { + List get positionalTypesShared; /// All the named fields, sorted by name. - List> get sortedNamedTypesShared; + List get sortedNamedTypesShared; } /// Common interface for data structures used by the implementations to /// represent a generic type parameter. -abstract interface class SharedTypeParameterStructure< - TypeStructure extends SharedTypeStructure> { +abstract interface class SharedTypeParameter { /// The bound of the type parameter. - TypeStructure? get boundShared; + SharedType? get boundShared; /// The name of the type parameter, for display to the user. String get displayName; @@ -96,20 +82,19 @@ abstract interface class SharedTypeParameterStructure< /// Common interface for data structures used by the implementations to /// represent a type. -abstract interface class SharedTypeStructure< - TypeStructure extends SharedTypeStructure> { +abstract interface class SharedType { /// If this type ends in a suffix (`?` or `*`), the suffix it ends with; /// otherwise [NullabilitySuffix.none]. NullabilitySuffix get nullabilitySuffix; - /// Return the presentation of this type as it should appear when presented to - /// users in contexts such as error messages. + /// Return the presentation of this type as it should appear when presented + /// to users in contexts such as error messages. /// /// Clients should not depend on the content of the returned value as it will /// be changed if doing so would improve the UX. String getDisplayString(); - bool isStructurallyEqualTo(SharedTypeStructure other); + bool isStructurallyEqualTo(covariant SharedType other); } /// Common interface for data structures used by the implementations to @@ -117,170 +102,143 @@ abstract interface class SharedTypeStructure< /// /// Note below that there is no `SharedUnknownTypeView`, only /// [SharedUnknownTypeSchemaView], since we want to restrict -/// [SharedUnknownTypeStructure] from appearing in type views. -abstract interface class SharedUnknownTypeStructure< - TypeStructure extends SharedTypeStructure> - implements SharedTypeStructure {} +/// [SharedUnknownType] from appearing in type views. +abstract interface class SharedUnknownType implements SharedType {} /// Common interface for data structures used by the implementations to /// represent the type `void`. -abstract interface class SharedVoidTypeStructure< - TypeStructure extends SharedTypeStructure> - implements SharedTypeStructure {} - -extension type SharedDynamicTypeSchemaView< - TypeStructure extends SharedTypeStructure>( - SharedDynamicTypeStructure _typeStructure) - implements SharedTypeSchemaView {} - -extension type SharedDynamicTypeView< - TypeStructure extends SharedTypeStructure>( - SharedDynamicTypeStructure _typeStructure) - implements SharedTypeView {} - -extension type SharedInvalidTypeSchemaView< - TypeStructure extends SharedTypeStructure>( - SharedInvalidTypeStructure _typeStructure) - implements SharedTypeSchemaView {} - -extension type SharedInvalidTypeView< - TypeStructure extends SharedTypeStructure>( - SharedInvalidTypeStructure _typeStructure) - implements SharedTypeView {} - -extension type SharedNamedTypeSchemaView< - TypeStructure extends SharedTypeStructure>( - SharedNamedTypeStructure _typeStructure) implements Object {} - -extension type SharedNamedTypeView< - TypeStructure extends SharedTypeStructure>( - SharedNamedTypeStructure _namedTypeStructure) +abstract interface class SharedVoidType implements SharedType {} + +extension type SharedDynamicTypeSchemaView(SharedDynamicType _typeStructure) + implements SharedTypeSchemaView {} + +extension type SharedDynamicTypeView(SharedDynamicType _typeStructure) + implements SharedTypeView {} + +extension type SharedInvalidTypeSchemaView(SharedInvalidType _typeStructure) + implements SharedTypeSchemaView {} + +extension type SharedInvalidTypeView(SharedInvalidType _typeStructure) + implements SharedTypeView {} + +extension type SharedNamedTypeSchemaView(SharedNamedType _typeStructure) + implements Object {} + +extension type SharedNamedTypeView(SharedNamedType _namedTypeStructure) implements Object { String get name => _namedTypeStructure.nameShared; - SharedTypeView get type => - new SharedTypeView(_namedTypeStructure.typeShared); + SharedTypeView get type => new SharedTypeView(_namedTypeStructure.typeShared); } -extension type SharedRecordTypeSchemaView< - TypeStructure extends SharedTypeStructure>( - SharedRecordTypeStructure _typeStructure) - implements SharedTypeSchemaView { - List> get namedTypes { +extension type SharedRecordTypeSchemaView(SharedRecordType _typeStructure) + implements SharedTypeSchemaView { + List get namedTypes { return _typeStructure.sortedNamedTypesShared - as List>; + as List; } - List> get positionalTypes { - return _typeStructure.positionalTypesShared - as List>; + List get positionalTypes { + return _typeStructure.positionalTypesShared as List; } } -extension type SharedRecordTypeView< - TypeStructure extends SharedTypeStructure>( - SharedRecordTypeStructure _typeStructure) - implements SharedTypeView { - List> get namedTypes { - return _typeStructure.sortedNamedTypesShared - as List>; +extension type SharedRecordTypeView(SharedRecordType _typeStructure) + implements SharedTypeView { + List get namedTypes { + return _typeStructure.sortedNamedTypesShared as List; } - List> get positionalTypes { - return _typeStructure.positionalTypesShared - as List>; + List get positionalTypes { + return _typeStructure.positionalTypesShared as List; } } -extension type SharedTypeSchemaView< - TypeStructure extends SharedTypeStructure>._( - SharedTypeStructure _typeStructure) implements Object { - SharedTypeSchemaView(TypeStructure typeStructure) : this._(typeStructure); - +extension type SharedTypeSchemaView(SharedType _typeStructure) + implements Object { NullabilitySuffix get nullabilitySuffix => _typeStructure.nullabilitySuffix; String getDisplayString() => _typeStructure.getDisplayString(); - TypeStructure unwrapTypeSchemaView() => _typeStructure as TypeStructure; -} + bool isStructurallyEqualTo(SharedTypeSchemaView other) => + _typeStructure.isStructurallyEqualTo(other.unwrapTypeSchemaView()); -extension type SharedTypeView< - TypeStructure extends SharedTypeStructure>._( - SharedTypeStructure _typeStructure) implements Object { - SharedTypeView(TypeStructure typeStructure) : this._(typeStructure); + TypeStructure unwrapTypeSchemaView() => + _typeStructure as TypeStructure; +} +extension type SharedTypeView(SharedType _typeStructure) implements Object { NullabilitySuffix get nullabilitySuffix => _typeStructure.nullabilitySuffix; String getDisplayString() => _typeStructure.getDisplayString(); - TypeStructure unwrapTypeView() => _typeStructure as TypeStructure; + bool isStructurallyEqualTo(SharedTypeView other) => + _typeStructure.isStructurallyEqualTo(other.unwrapTypeView()); + + TypeStructure unwrapTypeView() => + _typeStructure as TypeStructure; +} + +extension type SharedTypeParameterView(SharedTypeParameter _typeParameter) + implements Object { + TypeParameter unwrapTypeParameterViewAsTypeParameterStructure< + TypeParameter extends SharedTypeParameter>() => + _typeParameter as TypeParameter; } /// Note that there is no `SharedUnknownTypeView`, only /// [SharedUnknownTypeSchemaView], since we want to restrict -/// [SharedUnknownTypeStructure] from appearing in type views and allow it to -/// appear only in type schema views. -extension type SharedUnknownTypeSchemaView< - TypeStructure extends SharedTypeStructure>( - SharedUnknownTypeStructure _typeStructure) - implements SharedTypeSchemaView {} - -extension type SharedVoidTypeSchemaView< - TypeStructure extends SharedTypeStructure>( - SharedVoidTypeStructure _typeStructure) - implements SharedTypeSchemaView {} - -extension type SharedVoidTypeView< - TypeStructure extends SharedTypeStructure>( - SharedVoidTypeStructure _typeStructure) - implements SharedTypeView {} +/// [SharedUnknownType] from appearing in type views and +/// allow it to appear only in type schema views. +extension type SharedUnknownTypeSchemaView(SharedUnknownType _typeStructure) + implements SharedTypeSchemaView {} + +extension type SharedVoidTypeSchemaView(SharedVoidType _typeStructure) + implements SharedTypeSchemaView {} + +extension type SharedVoidTypeView(SharedVoidType _typeStructure) + implements SharedTypeView {} /// Extension methods of [SharedTypeStructureExtension] are intended to avoid -/// explicit null-testing on types before wrapping them into [SharedTypeView] or -/// [SharedTypeSchemaView]. +/// explicit null-testing on types before wrapping them into [SharedTypeView] +/// or [SharedTypeSchemaView]. /// /// Consider the following code: /// DartType? type = e.foo(); /// return type == null ? null : SharedTypeView(type); /// /// In the example above we want to wrap the result of the evaluation of -/// `e.foo()` in `SharedTypeView` if it's not null. For that we need to store it -/// into a variable to enable promotion in the ternary operator that will +/// `e.foo()` in `SharedTypeView` if it's not null. For that we need to store +/// it into a variable to enable promotion in the ternary operator that will /// perform the wrapping. /// /// This code can be rewritten in a more concise way using /// [SharedTypeStructureExtension] as follows: /// return e.foo()?.wrapSharedTypeView(); -extension SharedTypeStructureExtension< - TypeStructure extends SharedTypeStructure> on TypeStructure { - SharedTypeSchemaView wrapSharedTypeSchemaView() { +extension SharedTypeStructureExtension on SharedType { + SharedTypeSchemaView wrapSharedTypeSchemaView() { return new SharedTypeSchemaView(this); } - SharedTypeView wrapSharedTypeView() { + SharedTypeView wrapSharedTypeView() { return new SharedTypeView(this); } } -extension SharedTypeStructureMapEntryExtension< - TypeStructure extends SharedTypeStructure> on ({ - TypeStructure keyType, - TypeStructure valueType +extension SharedTypeStructureMapEntryExtension on ({ + SharedType keyType, + SharedType valueType }) { - ({ - SharedTypeView keyType, - SharedTypeView valueType - }) wrapSharedTypeMapEntryView() { + ({SharedTypeView keyType, SharedTypeView valueType}) + wrapSharedTypeMapEntryView() { return ( keyType: new SharedTypeView(this.keyType), valueType: new SharedTypeView(this.valueType) ); } - ({ - SharedTypeSchemaView keyType, - SharedTypeSchemaView valueType - }) wrapSharedTypeSchemaMapEntryView() { + ({SharedTypeSchemaView keyType, SharedTypeSchemaView valueType}) + wrapSharedTypeSchemaMapEntryView() { return ( keyType: new SharedTypeSchemaView(this.keyType), valueType: new SharedTypeSchemaView(this.valueType) diff --git a/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_mini_ast.dart b/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_mini_ast.dart index 638cbba3ee92..a4ca8748f7d1 100644 --- a/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_mini_ast.dart +++ b/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_mini_ast.dart @@ -18,10 +18,8 @@ import '../mini_types.dart'; Expression getSsaNodes(void Function(SsaNodeHarness) callback) => new _GetSsaNodes(callback, location: computeLocation()); -Expression implicitThis_whyNotPromoted( - String staticType, - void Function(Map, NonPromotionReason>) - callback) => +Expression implicitThis_whyNotPromoted(String staticType, + void Function(Map) callback) => new _WhyNotPromoted_ImplicitThis(Type(staticType), callback, location: computeLocation()); @@ -29,15 +27,15 @@ Expression implicitThis_whyNotPromoted( /// the [FlowAnalysisOperations] needed by flow analysis, as well as other /// methods needed for testing. class FlowAnalysisTestHarness extends Harness - with FlowModelHelper> { + with FlowModelHelper { @override final PromotionKeyStore promotionKeyStore = PromotionKeyStore(); @override - final SharedTypeView boolType = SharedTypeView(Type('bool')); + final SharedTypeView boolType = SharedTypeView(Type('bool')); @override - FlowAnalysisOperations> get typeOperations => + FlowAnalysisOperations get typeOperations => typeAnalyzer.operations; @override @@ -50,21 +48,20 @@ class FlowAnalysisTestHarness extends Harness /// Helper class allowing tests to examine the values of variables' SSA nodes. class SsaNodeHarness { - final FlowAnalysis> - _flow; + final FlowAnalysis _flow; SsaNodeHarness(this._flow); /// Gets the SSA node associated with [variable] at the current point in /// control flow, or `null` if the variable has been write captured. - SsaNode>? operator [](Var variable) => + SsaNode? operator [](Var variable) => _flow.ssaNodeForTesting(variable); } class _GetExpressionInfo extends Expression { final Expression target; - final void Function(ExpressionInfo>?) callback; + final void Function(ExpressionInfo?) callback; _GetExpressionInfo(this.target, this.callback, {required super.location}); @@ -74,13 +71,12 @@ class _GetExpressionInfo extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var type = h.typeAnalyzer.analyzeExpression(target, h.operations.unknownType); h.flow.forwardExpression(this, target); callback(h.flow.expressionInfoForTesting(this)); - return new ExpressionTypeAnalysisResult(type: type); + return new ExpressionTypeAnalysisResult(type: type); } } @@ -93,8 +89,7 @@ class _GetSsaNodes extends Expression { void preVisit(PreVisitor visitor) {} @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { callback(SsaNodeHarness(h.flow)); h.irBuilder.atom('null', Kind.expression, location: location); return ExpressionTypeAnalysisResult( @@ -105,7 +100,7 @@ class _GetSsaNodes extends Expression { class _WhyNotPromoted extends Expression { final Expression target; - final void Function(Map, NonPromotionReason>) callback; + final void Function(Map) callback; _WhyNotPromoted(this.target, this.callback, {required super.location}); @@ -118,20 +113,19 @@ class _WhyNotPromoted extends Expression { String toString() => '$target (whyNotPromoted)'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var type = h.typeAnalyzer.analyzeExpression(target, h.operations.unknownType); h.flow.forwardExpression(this, target); callback(h.flow.whyNotPromoted(this)()); - return new ExpressionTypeAnalysisResult(type: type); + return new ExpressionTypeAnalysisResult(type: type); } } class _WhyNotPromoted_ImplicitThis extends Expression { final Type staticType; - final void Function(Map, NonPromotionReason>) callback; + final void Function(Map) callback; _WhyNotPromoted_ImplicitThis(this.staticType, this.callback, {required super.location}); @@ -143,8 +137,7 @@ class _WhyNotPromoted_ImplicitThis extends Expression { String toString() => 'implicit this (whyNotPromoted)'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { callback(h.flow.whyNotPromotedImplicitThis(SharedTypeView(staticType))()); h.irBuilder.atom('noop', Kind.expression, location: location); return ExpressionTypeAnalysisResult( @@ -159,7 +152,7 @@ extension ExpressionExtensionForFlowAnalysisTesting on ProtoExpression { /// analysis information associated with it, `null` will be passed to /// [callback]. Expression getExpressionInfo( - void Function(ExpressionInfo>?) callback) { + void Function(ExpressionInfo?) callback) { var location = computeLocation(); return new _GetExpressionInfo(asExpression(location: location), callback, location: location); @@ -170,7 +163,7 @@ extension ExpressionExtensionForFlowAnalysisTesting on ProtoExpression { /// non-promotion info associated with it. If the expression has no /// non-promotion info, an empty map will be passed to [callback]. Expression whyNotPromoted( - void Function(Map, NonPromotionReason>) callback) { + void Function(Map) callback) { var location = computeLocation(); return new _WhyNotPromoted(asExpression(location: location), callback, location: location); diff --git a/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_test.dart b/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_test.dart index ce7436cb70c3..3ecae7e27c13 100644 --- a/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_test.dart +++ b/pkg/_fe_analyzer_shared/test/flow_analysis/flow_analysis_test.dart @@ -37,7 +37,7 @@ main() { group('API', () { test('asExpression_end promotes variables', () { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -213,7 +213,7 @@ main() { test('equalityOp(x != null) promotes true branch', () { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -277,7 +277,7 @@ main() { test('equalityOp(x == null) promotes false branch', () { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -340,7 +340,7 @@ main() { test('equalityOp(null != x) promotes true branch', () { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -368,7 +368,7 @@ main() { test('equalityOp(null == x) promotes false branch', () { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -480,7 +480,7 @@ main() { test('doStatement_bodyBegin() un-promotes', () { var x = Var('x'); - late SsaNode> ssaBeforeLoop; + late SsaNode ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -635,12 +635,11 @@ main() { test('finish checks proper nesting', () { var e = expr('Null'); var s = if_(e, []); - var flow = - FlowAnalysis>( - h.typeOperations, AssignedVariables(), - respectImplicitlyTypedVarInitializers: true, - fieldPromotionEnabled: true, - inferenceUpdate4Enabled: true); + var flow = FlowAnalysis( + h.typeOperations, AssignedVariables(), + respectImplicitlyTypedVarInitializers: true, + fieldPromotionEnabled: true, + inferenceUpdate4Enabled: true); flow.ifStatement_conditionBegin(); flow.ifStatement_thenBegin(e, s); expect(() => flow.finish(), _asserts); @@ -648,7 +647,7 @@ main() { test('for_conditionBegin() un-promotes', () { var x = Var('x'); - late SsaNode> ssaBeforeLoop; + late SsaNode ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -782,8 +781,8 @@ main() { test('for_end() with break updates Ssa of modified vars', () { var x = Var('x'); var y = Var('y'); - late SsaNode> xSsaInsideLoop; - late SsaNode> ySsaInsideLoop; + late SsaNode xSsaInsideLoop; + late SsaNode ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -810,8 +809,8 @@ main() { 'tested', () { var x = Var('x'); var y = Var('y'); - late SsaNode> xSsaInsideLoop; - late SsaNode> ySsaInsideLoop; + late SsaNode xSsaInsideLoop; + late SsaNode ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -836,7 +835,7 @@ main() { test('forEach_bodyBegin() un-promotes', () { var x = Var('x'); - late SsaNode> ssaBeforeLoop; + late SsaNode ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -989,7 +988,7 @@ main() { test('functionExpression_begin() cancels promotions of written vars', () { var x = Var('x'); var y = Var('y'); - late SsaNode> ssaBeforeFunction; + late SsaNode ssaBeforeFunction; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -1401,7 +1400,7 @@ main() { var x = Var('x'); var y = Var('y'); var z = Var('z'); - late SsaNode> xSsaNodeBeforeIf; + late SsaNode xSsaNodeBeforeIf; h.run([ declare(w, type: 'Object', initializer: expr('Object')), declare(x, type: 'bool', initializer: expr('bool')), @@ -1429,7 +1428,7 @@ main() { 'ifStatement_end() ignores non-matching SSA info from "then" path if ' 'unreachable', () { var x = Var('x'); - late SsaNode> xSsaNodeBeforeIf; + late SsaNode xSsaNodeBeforeIf; h.run([ declare(x, type: 'Object', initializer: expr('Object')), getSsaNodes((nodes) { @@ -1449,7 +1448,7 @@ main() { 'ifStatement_end() ignores non-matching SSA info from "else" path if ' 'unreachable', () { var x = Var('x'); - late SsaNode> xSsaNodeBeforeIf; + late SsaNode xSsaNodeBeforeIf; h.run([ declare(x, type: 'Object', initializer: expr('Object')), getSsaNodes((nodes) { @@ -1565,7 +1564,7 @@ main() { .get(h, key)! .promotedTypes! .single - .unwrapTypeView() + .unwrapTypeView() .type, 'int'); }), @@ -1655,7 +1654,7 @@ main() { String? expectedPromotedTypeThen, String? expectedPromotedTypeElse, {bool inverted = false}) { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.run([ declare(x, type: declaredType, initializer: expr(declaredType)), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -1959,7 +1958,7 @@ main() { test('nonNullAssert_end(x) promotes', () { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -1981,7 +1980,7 @@ main() { test('nullAwareAccess temporarily promotes', () { var x = Var('x'); - late SsaNode> ssaBeforePromotion; + late SsaNode ssaBeforePromotion; h.addMember('int', 'f', 'Null Function(Object?)'); h.run([ declare(x, type: 'int?', initializer: expr('int?')), @@ -2338,7 +2337,7 @@ main() { test('switchStatement_beginCase(true) un-promotes', () { var x = Var('x'); - late SsaNode> ssaBeforeSwitch; + late SsaNode ssaBeforeSwitch; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -2502,7 +2501,7 @@ main() { test('tryCatchStatement_bodyEnd() un-promotes variables assigned in body', () { var x = Var('x'); - late SsaNode> ssaAfterTry; + late SsaNode ssaAfterTry; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -2633,8 +2632,8 @@ main() { 'tryFinallyStatement_finallyBegin() un-promotes variables assigned in ' 'body', () { var x = Var('x'); - late SsaNode> ssaAtStartOfTry; - late SsaNode> ssaAfterTry; + late SsaNode ssaAtStartOfTry; + late SsaNode ssaAfterTry; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -2703,8 +2702,8 @@ main() { 'variables assigned in finally', () { var x = Var('x'); var y = Var('y'); - late SsaNode> xSsaAtEndOfFinally; - late SsaNode> ySsaAtEndOfFinally; + late SsaNode xSsaAtEndOfFinally; + late SsaNode ySsaAtEndOfFinally; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -2742,10 +2741,10 @@ main() { 'is sound to do so', () { var x = Var('x'); var y = Var('y'); - late SsaNode> xSsaAtEndOfTry; - late SsaNode> ySsaAtEndOfTry; - late SsaNode> xSsaAtEndOfFinally; - late SsaNode> ySsaAtEndOfFinally; + late SsaNode xSsaAtEndOfTry; + late SsaNode ySsaAtEndOfTry; + late SsaNode xSsaAtEndOfFinally; + late SsaNode ySsaAtEndOfFinally; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3205,7 +3204,7 @@ main() { test('whileStatement_conditionBegin() un-promotes', () { var x = Var('x'); - late SsaNode> ssaBeforeLoop; + late SsaNode ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -3284,8 +3283,8 @@ main() { test('whileStatement_end() with break updates Ssa of modified vars', () { var x = Var('x'); var y = Var('y'); - late SsaNode> xSsaInsideLoop; - late SsaNode> ySsaInsideLoop; + late SsaNode xSsaInsideLoop; + late SsaNode ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3312,8 +3311,8 @@ main() { 'types were tested', () { var x = Var('x'); var y = Var('y'); - late SsaNode> xSsaInsideLoop; - late SsaNode> ySsaInsideLoop; + late SsaNode xSsaInsideLoop; + late SsaNode ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3339,8 +3338,8 @@ main() { test('write() de-promotes and updates Ssa of a promoted variable', () { var x = Var('x'); var y = Var('y'); - late SsaNode> ssaBeforeWrite; - late ExpressionInfo> writtenValueInfo; + late SsaNode ssaBeforeWrite; + late ExpressionInfo writtenValueInfo; h.run([ declare(x, type: 'Object', initializer: expr('Object')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3362,8 +3361,8 @@ main() { test('write() updates Ssa', () { var x = Var('x'); var y = Var('y'); - late SsaNode> ssaBeforeWrite; - late ExpressionInfo> writtenValueInfo; + late SsaNode ssaBeforeWrite; + late ExpressionInfo writtenValueInfo; h.run([ declare(x, type: 'Object', initializer: expr('Object')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3394,8 +3393,8 @@ main() { var x = Var('x'); var y = Var('y'); - late SsaNode> xSsaBeforeWrite; - late SsaNode> ySsa; + late SsaNode xSsaBeforeWrite; + late SsaNode ySsa; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3414,7 +3413,7 @@ main() { test('write() does not store expressionInfo for trivial expressions', () { var x = Var('x'); var y = Var('y'); - late SsaNode> ssaBeforeWrite; + late SsaNode ssaBeforeWrite; h.run([ declare(x, type: 'Object', initializer: expr('Object')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3436,7 +3435,7 @@ main() { test('write() permits expression to be null', () { var x = Var('x'); - late SsaNode> ssaBeforeWrite; + late SsaNode ssaBeforeWrite; h.run([ declare(x, type: 'Object', initializer: expr('Object')), getSsaNodes((nodes) => ssaBeforeWrite = nodes[x]!), @@ -3656,15 +3655,15 @@ main() { }); group('setUnreachable', () { - var unreachable = FlowModel>( - Reachability.initial.setUnreachable()); - var reachable = FlowModel>(Reachability.initial); + var unreachable = + FlowModel(Reachability.initial.setUnreachable()); + var reachable = FlowModel(Reachability.initial); test('unchanged', () { expect(unreachable.setUnreachable(), same(unreachable)); }); test('changed', () { - void _check(FlowModel> initial) { + void _check(FlowModel initial) { var s = initial.setUnreachable(); expect(s, isNot(same(initial))); expect(s.reachable.overallReachable, false); @@ -3676,33 +3675,33 @@ main() { }); test('split', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1.split(); expect(s2.reachable.parent, same(s1.reachable)); }); test('unsplit', () { - var s1 = FlowModel>(Reachability.initial.split()); + var s1 = FlowModel(Reachability.initial.split()); var s2 = s1.unsplit(); expect(s2.reachable, same(Reachability.initial)); }); group('unsplitTo', () { test('no change', () { - var s1 = FlowModel>(Reachability.initial.split()); + var s1 = FlowModel(Reachability.initial.split()); var result = s1.unsplitTo(s1.reachable.parent!); expect(result, same(s1)); }); test('unsplit once, reachable', () { - var s1 = FlowModel>(Reachability.initial.split()); + var s1 = FlowModel(Reachability.initial.split()); var s2 = s1.split(); var result = s2.unsplitTo(s1.reachable.parent!); expect(result.reachable, same(s1.reachable)); }); test('unsplit once, unreachable', () { - var s1 = FlowModel>(Reachability.initial.split()); + var s1 = FlowModel(Reachability.initial.split()); var s2 = s1.split().setUnreachable(); var result = s2.unsplitTo(s1.reachable.parent!); expect(result.reachable.locallyReachable, false); @@ -3710,7 +3709,7 @@ main() { }); test('unsplit twice, reachable', () { - var s1 = FlowModel>(Reachability.initial.split()); + var s1 = FlowModel(Reachability.initial.split()); var s2 = s1.split(); var s3 = s2.split(); var result = s3.unsplitTo(s1.reachable.parent!); @@ -3718,7 +3717,7 @@ main() { }); test('unsplit twice, top unreachable', () { - var s1 = FlowModel>(Reachability.initial.split()); + var s1 = FlowModel(Reachability.initial.split()); var s2 = s1.split(); var s3 = s2.split().setUnreachable(); var result = s3.unsplitTo(s1.reachable.parent!); @@ -3727,7 +3726,7 @@ main() { }); test('unsplit twice, previous unreachable', () { - var s1 = FlowModel>(Reachability.initial.split()); + var s1 = FlowModel(Reachability.initial.split()); var s2 = s1.split().setUnreachable(); var s3 = s2.split(); var result = s3.unsplitTo(s1.reachable.parent!); @@ -3738,25 +3737,25 @@ main() { group('tryPromoteForTypeCheck', () { test('unpromoted -> unchanged (same)', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intVar, 'int').ifTrue; expect(s2, same(s1)); }); test('unpromoted -> unchanged (supertype)', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intVar, 'Object').ifTrue; expect(s2, same(s1)); }); test('unpromoted -> unchanged (unrelated)', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intVar, 'String').ifTrue; expect(s2, same(s1)); }); test('unpromoted -> subtype', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intQVar, 'int').ifTrue; expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { @@ -3766,7 +3765,7 @@ main() { }); test('promoted -> unchanged (same)', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'int').ifTrue; @@ -3774,7 +3773,7 @@ main() { }); test('promoted -> unchanged (supertype)', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'Object').ifTrue; @@ -3782,7 +3781,7 @@ main() { }); test('promoted -> unchanged (unrelated)', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'String').ifTrue; @@ -3790,7 +3789,7 @@ main() { }); test('promoted -> subtype', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'int').ifTrue; @@ -3812,12 +3811,12 @@ main() { test('without declaration', () { // This should not happen in valid code, but test that we don't crash. - var s = FlowModel>(Reachability.initial)._write( + var s = FlowModel(Reachability.initial)._write( h, null, objectQVar, SharedTypeView(Type('Object?')), - new SsaNode>(null)); + new SsaNode(null)); expect( s.promotionInfo ?.get(h, h.promotionKeyStore.keyForVariable(objectQVar)), @@ -3825,10 +3824,10 @@ main() { }); test('unchanged', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('Object?')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2, isNot(same(s1))); expect(s2.reachable, same(s1.reachable)); expect( @@ -3841,10 +3840,10 @@ main() { }); test('marks as assigned', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, false); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int?')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.reachable.overallReachable, true); expect( s2._infoFor(h, objectQVar), @@ -3856,18 +3855,14 @@ main() { }); test('un-promotes fully', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; expect(s1.promotionInfo.unwrap(h), contains(h.promotionKeyStore.keyForVariable(objectQVar))); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('int?')), - new SsaNode>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('int?')), new SsaNode(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( @@ -3879,7 +3874,7 @@ main() { }); test('un-promotes partially, when no exact match', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3892,12 +3887,8 @@ main() { assigned: true, unassigned: false) }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num')), - new SsaNode>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num')), new SsaNode(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( @@ -3909,7 +3900,7 @@ main() { }); test('un-promotes partially, when exact match', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3924,12 +3915,8 @@ main() { assigned: true, unassigned: false) }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num')), - new SsaNode>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num')), new SsaNode(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( @@ -3941,7 +3928,7 @@ main() { }); test('leaves promoted, when exact match', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3955,7 +3942,7 @@ main() { unassigned: false) }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('num')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo, isNot(same(s1.promotionInfo))); expect(s2.promotionInfo.unwrap(h), { @@ -3968,7 +3955,7 @@ main() { }); test('leaves promoted, when writing a subtype', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3982,7 +3969,7 @@ main() { unassigned: false) }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo, isNot(same(s1.promotionInfo))); expect(s2.promotionInfo.unwrap(h), { @@ -3998,7 +3985,7 @@ main() { test('when declared type', () { var x = Var('x')..type = Type('int?'); - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, x, true); expect(s1.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): @@ -4006,7 +3993,7 @@ main() { }); var s2 = s1._write(h, null, x, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel(chain: ['int']), @@ -4016,7 +4003,7 @@ main() { test('when declared type, if write-captured', () { var x = Var('x')..type = Type('int?'); - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, x, true); expect(s1.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): @@ -4031,7 +4018,7 @@ main() { // 'x' is write-captured, so not promoted var s3 = s2._write(h, null, x, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); expect(s3.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel(chain: null, writeCaptured: true), @@ -4039,7 +4026,7 @@ main() { }); test('when promoted', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifTrue; @@ -4050,7 +4037,7 @@ main() { ), }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['int?', 'int'], @@ -4060,7 +4047,7 @@ main() { }); test('when not promoted', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifFalse; @@ -4071,7 +4058,7 @@ main() { ), }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['Object', 'int'], @@ -4082,7 +4069,7 @@ main() { }); test('Promotes to type of interest when not previously promoted', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifFalse; @@ -4092,12 +4079,8 @@ main() { ofInterest: ['num?'], ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num?')), - new SsaNode>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num?')), new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['num?'], @@ -4107,7 +4090,7 @@ main() { }); test('Promotes to type of interest when previously promoted', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -4119,12 +4102,8 @@ main() { ofInterest: ['num?', 'int?'], ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('int?')), - new SsaNode>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('int?')), new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['num?', 'int?'], @@ -4148,7 +4127,7 @@ main() { test('; first', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'B?') .ifFalse @@ -4162,7 +4141,7 @@ main() { }); var s2 = s1._write(h, null, x, SharedTypeView(Type('C')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['Object', 'B'], @@ -4174,7 +4153,7 @@ main() { test('; second', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'A?') .ifFalse @@ -4188,7 +4167,7 @@ main() { }); var s2 = s1._write(h, null, x, SharedTypeView(Type('C')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['Object', 'B'], @@ -4200,7 +4179,7 @@ main() { test('; nullable and non-nullable', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'A') .ifFalse @@ -4214,7 +4193,7 @@ main() { }); var s2 = s1._write(h, null, x, SharedTypeView(Type('B')), - new SsaNode>(null)); + new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['Object', 'A'], @@ -4226,7 +4205,7 @@ main() { group('; ambiguous', () { test('; no promotion', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifFalse @@ -4240,7 +4219,7 @@ main() { ), }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); // It's ambiguous whether to promote to num? or num*, so we don't // promote. expect(s2, isNot(same(s1))); @@ -4255,7 +4234,7 @@ main() { }); test('exact match', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifFalse @@ -4267,12 +4246,8 @@ main() { ofInterest: ['num?', 'num*'], ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num?')), - new SsaNode>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num?')), new SsaNode(null)); // It's ambiguous whether to promote to num? or num*, but since the // written type is exactly num?, we use that. expect(s2.promotionInfo.unwrap(h), { @@ -4289,7 +4264,7 @@ main() { test('when promoted via test', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'num?') .ifTrue @@ -4302,12 +4277,8 @@ main() { ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - x, - SharedTypeView(Type('double')), - new SsaNode>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), x, + SharedTypeView(Type('double')), new SsaNode(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['num?', 'num'], @@ -4325,7 +4296,7 @@ main() { }); test('initialized', () { - var s = FlowModel>(Reachability.initial) + var s = FlowModel(Reachability.initial) ._declare(h, objectQVar, true); expect(s.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): @@ -4334,7 +4305,7 @@ main() { }); test('not initialized', () { - var s = FlowModel>(Reachability.initial) + var s = FlowModel(Reachability.initial) ._declare(h, objectQVar, false); expect(s.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): @@ -4345,13 +4316,13 @@ main() { group('markNonNullable', () { test('unpromoted -> unchanged', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1._tryMarkNonNullable(h, intVar).ifTrue; expect(s2, same(s1)); }); test('unpromoted -> promoted', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1._tryMarkNonNullable(h, intQVar).ifTrue; expect(s2.reachable.overallReachable, true); expect(s2._infoFor(h, intQVar), @@ -4359,7 +4330,7 @@ main() { }); test('promoted -> unchanged', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryMarkNonNullable(h, objectQVar).ifTrue; @@ -4367,7 +4338,7 @@ main() { }); test('promoted -> re-promoted', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifTrue; var s2 = s1._tryMarkNonNullable(h, objectQVar).ifTrue; @@ -4379,7 +4350,7 @@ main() { }); test('promote to Never', () { - var s1 = FlowModel>(Reachability.initial); + var s1 = FlowModel(Reachability.initial); var s2 = s1._tryMarkNonNullable(h, nullVar).ifTrue; expect(s2.reachable.overallReachable, true); expect(s2._infoFor(h, nullVar), @@ -4389,7 +4360,7 @@ main() { group('conservativeJoin', () { test('unchanged', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._declare(h, intQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; @@ -4405,7 +4376,7 @@ main() { }); test('written', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue ._tryPromoteForTypeCheck(h, intQVar, 'int') @@ -4421,7 +4392,7 @@ main() { }); test('write captured', () { - var s1 = FlowModel>(Reachability.initial) + var s1 = FlowModel(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue ._tryPromoteForTypeCheck(h, intQVar, 'int') @@ -4439,7 +4410,7 @@ main() { group('rebaseForward', () { test('reachability', () { - var reachable = FlowModel>(Reachability.initial); + var reachable = FlowModel(Reachability.initial); var unreachable = reachable.setUnreachable(); expect(reachable.rebaseForward(h, reachable), same(reachable)); expect(reachable.rebaseForward(h, unreachable), same(unreachable)); @@ -4456,21 +4427,21 @@ main() { var b = Var('b')..type = Type('int'); var c = Var('c')..type = Type('int'); var d = Var('d')..type = Type('int'); - var s0 = FlowModel>(Reachability.initial) + var s0 = FlowModel(Reachability.initial) ._declare(h, a, false) ._declare(h, b, false) ._declare(h, c, false) ._declare(h, d, false); var s1 = s0 ._write(h, null, a, SharedTypeView(Type('int')), - new SsaNode>(null)) + new SsaNode(null)) ._write(h, null, b, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); var s2 = s0 ._write(h, null, a, SharedTypeView(Type('int')), - new SsaNode>(null)) + new SsaNode(null)) ._write(h, null, c, SharedTypeView(Type('int')), - new SsaNode>(null)); + new SsaNode(null)); var result = s1.rebaseForward(h, s2); expect(result._infoFor(h, a).assigned, true); expect(result._infoFor(h, b).assigned, true); @@ -4483,7 +4454,7 @@ main() { var b = Var('b')..type = Type('int'); var c = Var('c')..type = Type('int'); var d = Var('d')..type = Type('int'); - var s0 = FlowModel>(Reachability.initial) + var s0 = FlowModel(Reachability.initial) ._declare(h, a, false) ._declare(h, b, false) ._declare(h, c, false) @@ -4512,7 +4483,7 @@ main() { test('write captured and promoted', () { var a = Var('a')..type = Type('num'); - var s0 = FlowModel>(Reachability.initial) + var s0 = FlowModel(Reachability.initial) ._declare(h, a, false); // In s1, a is write captured. In s2 it's promoted. var s1 = s0._conservativeJoin(h, [a], [a]); @@ -4531,12 +4502,12 @@ main() { void _check(String? thisType, String? otherType, bool unsafe, List? expectedChain) { var x = Var('x')..type = Type('Object?'); - var s0 = FlowModel>(Reachability.initial) + var s0 = FlowModel(Reachability.initial) ._declare(h, x, true); var s1 = s0; if (unsafe) { s1 = s1._write(h, null, x, SharedTypeView(Type('Object?')), - new SsaNode>(null)); + new SsaNode(null)); } if (thisType != null) { s1 = s1._tryPromoteForTypeCheck(h, x, thisType).ifTrue; @@ -4554,7 +4525,7 @@ main() { result ._infoFor(h, x) .promotedTypes! - .map((t) => t.unwrapTypeView().type) + .map((t) => t.unwrapTypeView().type) .toList(), expectedChain); } @@ -4577,10 +4548,9 @@ main() { test('promotion chains', () { // Verify that the given promotion chain matches the expected list of // strings. - void _checkChain( - List>? chain, List expected) { - var strings = (chain ?? >[]) - .map((t) => t.unwrapTypeView().type) + void _checkChain(List? chain, List expected) { + var strings = (chain ?? []) + .map((t) => t.unwrapTypeView().type) .toList(); expect(strings, expected); } @@ -4597,9 +4567,8 @@ main() { void _check(List before, List inTry, List inFinally, List expectedResult) { var x = Var('x')..type = Type('Object?'); - var initialModel = - FlowModel>(Reachability.initial) - ._declare(h, x, true); + var initialModel = FlowModel(Reachability.initial) + ._declare(h, x, true); for (var t in before) { initialModel = initialModel._tryPromoteForTypeCheck(h, x, t).ifTrue; } @@ -4655,7 +4624,7 @@ main() { test('types of interest', () { var a = Var('a')..type = Type('Object'); - var s0 = FlowModel>(Reachability.initial) + var s0 = FlowModel(Reachability.initial) ._declare(h, a, false); var s1 = s0._tryPromoteForTypeCheck(h, a, 'int').ifFalse; var s2 = s0._tryPromoteForTypeCheck(h, a, 'String').ifFalse; @@ -4671,7 +4640,7 @@ main() { test('variable present in one state but not the other', () { var x = Var('x')..type = Type('Object?'); - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._declare(h, x, true); expect(s1.rebaseForward(h, s0), same(s1)); expect(s0.rebaseForward(h, s1), same(s1)); @@ -4771,8 +4740,8 @@ main() { h.addSuperInterfaces('B', (_) => [Type('A'), Type('Object')]); h.addSuperInterfaces('A', (_) => [Type('Object')]); - void check(List> chain1, - List> chain2, Matcher matcher) { + void check(List chain1, List chain2, + Matcher matcher) { expect( PromotionModel.joinPromotedTypes(chain1, chain2, h.typeOperations), matcher, @@ -4909,20 +4878,18 @@ main() { stringType = Type('String'); }); - PromotionModel> model( - List>? promotionChain, - {List>? typesOfInterest, - bool assigned = false}) => - PromotionModel>( + PromotionModel model(List? promotionChain, + {List? typesOfInterest, bool assigned = false}) => + PromotionModel( promotedTypes: promotionChain, tested: typesOfInterest ?? promotionChain ?? [], assigned: assigned, unassigned: !assigned, - ssaNode: new SsaNode>(null)); + ssaNode: new SsaNode(null)); group('without input reuse', () { test('promoted with unpromoted', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]), y: model(null) @@ -4939,7 +4906,7 @@ main() { }); group('should re-use an input if possible', () { test('identical inputs', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]), y: model([SharedTypeView(stringType)]) @@ -4948,7 +4915,7 @@ main() { }); test('one input empty', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]), y: model([SharedTypeView(stringType)]) @@ -4962,7 +4929,7 @@ main() { }); test('promoted with unpromoted', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -4977,7 +4944,7 @@ main() { }); test('related type chains', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intQType), SharedTypeView(intType)]) }); @@ -4994,7 +4961,7 @@ main() { }); test('unrelated type chains', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -5011,7 +4978,7 @@ main() { }); test('sub-map', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var xModel = model([SharedTypeView(intType)]); var s1 = s0._setInfo(h, { x: xModel, @@ -5026,7 +4993,7 @@ main() { }); test('sub-map with matched subtype', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intQType), SharedTypeView(intType)]), y: model([SharedTypeView(stringType)]) @@ -5044,7 +5011,7 @@ main() { }); test('sub-map with mismatched subtype', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intQType)]), y: model([SharedTypeView(stringType)]) @@ -5062,7 +5029,7 @@ main() { }); test('assigned', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var unassigned = model(null, assigned: false); var assigned = model(null, assigned: true); var s1 = s0._setInfo( @@ -5081,7 +5048,7 @@ main() { }); test('write captured', () { - var s0 = FlowModel>(Reachability.initial); + var s0 = FlowModel(Reachability.initial); var intQModel = model([SharedTypeView(intQType)]); var writeCapturedModel = intQModel.writeCapture(); var s1 = s0._setInfo(h, { @@ -5118,17 +5085,17 @@ main() { stringType = Type('String'); }); - PromotionModel> model( - List> typesOfInterest) => - PromotionModel>( + PromotionModel model( + List typesOfInterest) => + PromotionModel( promotedTypes: null, tested: typesOfInterest, assigned: true, unassigned: false, - ssaNode: new SsaNode>(null)); + ssaNode: new SsaNode(null)); test('inherits types of interest from other', () { - var m0 = FlowModel>(Reachability.initial); + var m0 = FlowModel(Reachability.initial); var m1 = m0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -5140,7 +5107,7 @@ main() { }); test('handles variable missing from other', () { - var m0 = FlowModel>(Reachability.initial); + var m0 = FlowModel(Reachability.initial); var m1 = m0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -5149,7 +5116,7 @@ main() { }); test('returns identical model when no changes', () { - var m0 = FlowModel>(Reachability.initial); + var m0 = FlowModel(Reachability.initial); var m1 = m0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -11491,16 +11458,16 @@ String _describeMatcher(Matcher matcher) { Matcher _matchOfInterestSet(List expectedTypes) { return predicate( - (List> x) => unorderedEquals(expectedTypes) - .matches(x.map((t) => t.unwrapTypeView().type).toList(), {}), + (List x) => unorderedEquals(expectedTypes) + .matches(x.map((t) => t.unwrapTypeView().type).toList(), {}), 'interest set $expectedTypes'); } Matcher _matchPromotionChain(List? expectedTypes) { if (expectedTypes == null) return isNull; return predicate( - (List> x) => equals(expectedTypes) - .matches(x.map((t) => t.unwrapTypeView().type).toList(), {}), + (List x) => equals(expectedTypes) + .matches(x.map((t) => t.unwrapTypeView().type).toList(), {}), 'promotion chain $expectedTypes'); } @@ -11523,7 +11490,7 @@ Matcher _matchVariableModel( Matcher assignedMatcher = wrapMatcher(assigned); Matcher unassignedMatcher = wrapMatcher(unassigned); Matcher writeCapturedMatcher = wrapMatcher(writeCaptured); - return predicate((PromotionModel> model) { + return predicate((PromotionModel model) { if (!chainMatcher.matches(model.promotedTypes, {})) return false; if (!ofInterestMatcher.matches(model.tested, {})) return false; if (!assignedMatcher.matches(model.assigned, {})) return false; @@ -11553,8 +11520,8 @@ class _MockNonPromotionReason extends NonPromotionReason { fail('Unexpected call to accept'); } -extension on FlowModel> { - FlowModel> _conservativeJoin(FlowAnalysisTestHarness h, +extension on FlowModel { + FlowModel _conservativeJoin(FlowAnalysisTestHarness h, Iterable writtenVariables, Iterable capturedVariables) => conservativeJoin(h, [ for (Var v in writtenVariables) h.promotionKeyStore.keyForVariable(v) @@ -11562,18 +11529,18 @@ extension on FlowModel> { for (Var v in capturedVariables) h.promotionKeyStore.keyForVariable(v) ]); - FlowModel> _declare( + FlowModel _declare( FlowAnalysisTestHarness h, Var variable, bool initialized) => this.declare( h, h.promotionKeyStore.keyForVariable(variable), initialized); - PromotionModel> _infoFor( + PromotionModel _infoFor( FlowAnalysisTestHarness h, Var variable) => infoFor(h, h.promotionKeyStore.keyForVariable(variable), ssaNode: new SsaNode(null)); - FlowModel> _setInfo(FlowAnalysisTestHarness h, - Map>> newInfo) { + FlowModel _setInfo(FlowAnalysisTestHarness h, + Map> newInfo) { var result = this; for (var core.MapEntry(:key, :value) in newInfo.entries) { if (result.promotionInfo?.get(h, key) != value) { @@ -11583,11 +11550,11 @@ extension on FlowModel> { return result; } - ExpressionInfo> _tryMarkNonNullable( + ExpressionInfo _tryMarkNonNullable( FlowAnalysisTestHarness h, Var variable) => tryMarkNonNullable(h, _varRefWithType(h, variable)); - ExpressionInfo> _tryPromoteForTypeCheck( + ExpressionInfo _tryPromoteForTypeCheck( FlowAnalysisTestHarness h, Var variable, String type) => tryPromoteForTypeCheck( h, _varRefWithType(h, variable), SharedTypeView(Type(type))); @@ -11595,9 +11562,9 @@ extension on FlowModel> { int _varRef(FlowAnalysisTestHarness h, Var variable) => h.promotionKeyStore.keyForVariable(variable); - TrivialVariableReference> _varRefWithType( + TrivialVariableReference _varRefWithType( FlowAnalysisTestHarness h, Var variable) => - new TrivialVariableReference>( + new TrivialVariableReference( promotionKey: _varRef(h, variable), model: this, type: promotionInfo @@ -11608,20 +11575,19 @@ extension on FlowModel> { isThisOrSuper: false, ssaNode: SsaNode(null)); - FlowModel> _write( + FlowModel _write( FlowAnalysisTestHarness h, NonPromotionReason? nonPromotionReason, Var variable, - SharedTypeView writtenType, - SsaNode> newSsaNode) => + SharedTypeView writtenType, + SsaNode newSsaNode) => write(h, nonPromotionReason, h.promotionKeyStore.keyForVariable(variable), writtenType, newSsaNode, h.typeOperations, unpromotedType: SharedTypeView(variable.type)); } -extension on PromotionInfo>? { - Map>> unwrap( - FlowAnalysisTestHarness h) => +extension on PromotionInfo? { + Map> unwrap(FlowAnalysisTestHarness h) => { for (var FlowLinkDiffEntry(:int key, right: second!) in h.reader.diff(null, this).entries) diff --git a/pkg/_fe_analyzer_shared/test/mini_ast.dart b/pkg/_fe_analyzer_shared/test/mini_ast.dart index a0f57e0c5722..afccac5bed1a 100644 --- a/pkg/_fe_analyzer_shared/test/mini_ast.dart +++ b/pkg/_fe_analyzer_shared/test/mini_ast.dart @@ -534,7 +534,7 @@ Pattern wildcard({String? type, String? expectInferredType}) { } typedef SharedMatchContext - = shared.MatchContext, Var>; + = shared.MatchContext; typedef SharedRecordPatternField = shared.RecordPatternField; @@ -553,8 +553,7 @@ class As extends Expression { String toString() => '$target as $type'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeTypeCast(this, target, type); } } @@ -624,11 +623,10 @@ class BooleanLiteral extends Expression { String toString() => '$value'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var type = h.typeAnalyzer.analyzeBoolLiteral(this, value); h.irBuilder.atom('$value', Kind.expression, location: location); - return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -717,8 +715,7 @@ class Cascade extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { // Form the IR for evaluating the LHS var targetType = h.typeAnalyzer.analyzeExpression(target, schema); var previousCascadeTargetIR = h.typeAnalyzer._currentCascadeTargetIR; @@ -792,8 +789,7 @@ class CascadePlaceholder extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { h.irBuilder .readTmp(h.typeAnalyzer._currentCascadeTargetIR!, location: location); return ExpressionTypeAnalysisResult( @@ -809,7 +805,7 @@ class CastPattern extends Pattern { CastPattern(this.inner, this.type, {required super.location}) : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeCastPatternSchema(); @override @@ -819,14 +815,14 @@ class CastPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var analysisResult = h.typeAnalyzer.analyzeCastPattern( context: context, pattern: this, innerPattern: inner, requiredType: SharedTypeView(type), ); - var matchedType = analysisResult.matchedValueType.unwrapTypeView(); + var matchedType = analysisResult.matchedValueType.unwrapTypeView(); h.irBuilder.atom(type.type, Kind.type, location: location); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.apply( @@ -885,8 +881,7 @@ class CheckAssigned extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { expect(h.flow.isAssigned(variable), expectedAssignedState, reason: 'at $location'); h.irBuilder.atom('null', Kind.expression, location: location); @@ -916,8 +911,7 @@ class CheckPromoted extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var promotedType = promotable._getPromotedType(h); expect(promotedType?.type, expectedTypeStr, reason: 'at $location'); return ExpressionTypeAnalysisResult( @@ -937,8 +931,7 @@ class CheckReachable extends Expression { String toString() => 'check reachable'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { expect(h.flow.isReachable, expectedReachable, reason: 'at $location'); h.irBuilder.atom('null', Kind.expression, location: location); return new ExpressionTypeAnalysisResult( @@ -963,8 +956,7 @@ class CheckUnassigned extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { expect(h.flow.isUnassigned(variable), expectedUnassignedState, reason: 'at $location'); h.irBuilder.atom('null', Kind.expression, location: location); @@ -1007,7 +999,7 @@ class CollectionElementContextMapEntry extends CollectionElementContext { } class CollectionElementContextType extends CollectionElementContext { - final SharedTypeSchemaView elementTypeSchema; + final SharedTypeSchemaView elementTypeSchema; CollectionElementContextType._(this.elementTypeSchema); } @@ -1033,8 +1025,7 @@ class Conditional extends Expression { String toString() => '$condition ? $ifTrue : $ifFalse'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer .analyzeConditionalExpression(this, condition, ifTrue, ifFalse); h.irBuilder.apply('if', [Kind.expression, Kind.expression, Kind.expression], @@ -1050,7 +1041,7 @@ class ConstantPattern extends Pattern { ConstantPattern(this.constant, {required super.location}) : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeConstantPatternSchema(); @override @@ -1060,10 +1051,10 @@ class ConstantPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var analysisResult = h.typeAnalyzer.analyzeConstantPattern(context, this, constant); - var matchedType = analysisResult.matchedValueType.unwrapTypeView(); + var matchedType = analysisResult.matchedValueType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.apply('const', [Kind.expression, Kind.type], Kind.pattern, names: ['matchedType'], location: location); @@ -1173,7 +1164,7 @@ class Declare extends Statement { initializer, declaredType?.wrapSharedTypeSchemaView() ?? h.operations.unknownType) - .unwrapTypeView(); + .unwrapTypeView(); h.flow.lateInitializer_end(); staticType = variable.type = declaredType ?? initializerType; h.flow.declare(variable, SharedTypeView(staticType), initialized: true); @@ -1201,7 +1192,7 @@ class Declare extends Statement { .analyzeUninitializedVariableDeclaration( this, pattern.variable, declaredType?.wrapSharedTypeView(), isFinal: isFinal) - .unwrapTypeView(); + .unwrapTypeView(); h.typeAnalyzer.handleDeclaredVariablePattern(pattern, matchedType: staticType, staticType: staticType); irName = 'declare'; @@ -1264,8 +1255,7 @@ class Equal extends Expression { String toString() => '$lhs ${isInverted ? '!=' : '=='} $rhs'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var operatorName = isInverted ? '!=' : '=='; var result = h.typeAnalyzer.analyzeBinaryExpression(this, lhs, operatorName, rhs); @@ -1303,8 +1293,7 @@ abstract class Expression extends Node void preVisit(PreVisitor visitor); - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema); + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema); } /// Representation of a single case clause in a switch expression. Use @@ -1353,10 +1342,9 @@ class ExpressionCollectionElement extends CollectionElement { @override void visit(Harness h, CollectionElementContext context) { - SharedTypeSchemaView typeSchema = - context is CollectionElementContextType - ? context.elementTypeSchema - : h.operations.unknownType; + SharedTypeSchemaView typeSchema = context is CollectionElementContextType + ? context.elementTypeSchema + : h.operations.unknownType; h.typeAnalyzer.analyzeExpression(expression, typeSchema); h.irBuilder.apply('celt', [Kind.expression], Kind.collectionElement, location: location); @@ -1366,7 +1354,7 @@ class ExpressionCollectionElement extends CollectionElement { class ExpressionInTypeSchema extends Statement { final Expression expr; - final SharedTypeSchemaView typeSchema; + final SharedTypeSchemaView typeSchema; ExpressionInTypeSchema._(this.expr, this.typeSchema, {required super.location}); @@ -1520,7 +1508,7 @@ class ForEach extends Statement { void visit(Harness h) { var iteratedType = h._getIteratedType(h.typeAnalyzer .analyzeExpression(iterable, h.operations.unknownType) - .unwrapTypeView()); + .unwrapTypeView()); h.flow.forEach_bodyBegin(this); var variable = this.variable; if (variable != null && !declaresVariable) { @@ -1565,8 +1553,8 @@ class Harness { bool _started = false; - late final FlowAnalysis> flow; + late final FlowAnalysis + flow; bool? _inferenceUpdate3Enabled; @@ -1740,7 +1728,7 @@ class Harness { } /// See [TypeAnalyzer.resolveRelationalPatternOperator]. - RelationalOperatorResolution? resolveRelationalPatternOperator( + RelationalOperatorResolution? resolveRelationalPatternOperator( Type matchedValueType, String operator) { if (operator == '==' || operator == '!=') { return RelationalOperatorResolution( @@ -1782,10 +1770,8 @@ class Harness { b.preVisit(visitor); flow = operations.legacy ? FlowAnalysis>.legacy( - operations, visitor._assignedVariables) - : FlowAnalysis>( + SharedTypeView>.legacy(operations, visitor._assignedVariables) + : FlowAnalysis( operations, visitor._assignedVariables, respectImplicitlyTypedVarInitializers: @@ -2044,8 +2030,7 @@ class IfNull extends Expression { String toString() => '$lhs ?? $rhs'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeIfNullExpression(this, lhs, rhs); h.irBuilder.apply( 'ifNull', [Kind.expression, Kind.expression], Kind.expression, @@ -2072,8 +2057,7 @@ class IntLiteral extends ConstExpression { String toString() => '$value'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeIntLiteral(schema); if (expectConversionToDouble != null) { expect(result.convertedToDouble, expectConversionToDouble); @@ -2120,8 +2104,7 @@ class InvokeMethod extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeMethodInvocation(this, target is CascadePlaceholder ? null : target, methodName, arguments, isNullAware: isNullAware); @@ -2144,8 +2127,7 @@ class Is extends Expression { String toString() => '$target is${isInverted ? '!' : ''} $type'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer .analyzeTypeTest(this, target, type, isInverted: isInverted); } @@ -2202,8 +2184,7 @@ class ListLiteral extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { for (var element in elements) { h.typeAnalyzer.dispatchCollectionElement(element, CollectionElementContextType._(SharedTypeSchemaView(elementType))); @@ -2234,7 +2215,7 @@ class ListPattern extends Pattern { : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeListPatternSchema( elementType: elementType?.wrapSharedTypeView(), elements: elements); @@ -2247,11 +2228,11 @@ class ListPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var listPatternResult = h.typeAnalyzer.analyzeListPattern(context, this, elementType: elementType?.wrapSharedTypeView(), elements: elements); - var matchedType = listPatternResult.matchedValueType.unwrapTypeView(); - var requiredType = listPatternResult.requiredType.unwrapTypeView(); + var matchedType = listPatternResult.matchedValueType.unwrapTypeView(); + var requiredType = listPatternResult.requiredType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.atom(requiredType.type, Kind.type, location: location); h.irBuilder.apply( @@ -2294,8 +2275,7 @@ class LocalFunction extends Expression { String toString() => '() $body'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { h.flow.functionExpression_begin(this); h.typeAnalyzer.dispatchStatement(body); h.flow.functionExpression_end(); @@ -2324,8 +2304,7 @@ class Logical extends Expression { String toString() => '$lhs ${isAnd ? '&&' : '||'} $rhs'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var operatorName = isAnd ? '&&' : '||'; var result = h.typeAnalyzer.analyzeBinaryExpression(this, lhs, operatorName, rhs); @@ -2345,7 +2324,7 @@ class LogicalAndPattern extends Pattern { : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeLogicalAndPatternSchema(lhs, rhs); @override @@ -2356,10 +2335,10 @@ class LogicalAndPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var analysisResult = h.typeAnalyzer.analyzeLogicalAndPattern(context, this, lhs, rhs); - var matchedType = analysisResult.matchedValueType.unwrapTypeView(); + var matchedType = analysisResult.matchedValueType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.apply('logicalAndPattern', [Kind.pattern, Kind.pattern, Kind.type], Kind.pattern, @@ -2383,7 +2362,7 @@ class LogicalOrPattern extends Pattern { LogicalOrPattern(this.lhs, this.rhs, {required super.location}) : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeLogicalOrPatternSchema(lhs, rhs); @override @@ -2397,10 +2376,10 @@ class LogicalOrPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var analysisResult = h.typeAnalyzer.analyzeLogicalOrPattern(context, this, lhs, rhs); - var matchedType = analysisResult.matchedValueType.unwrapTypeView(); + var matchedType = analysisResult.matchedValueType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.apply('logicalOrPattern', [Kind.pattern, Kind.pattern, Kind.type], Kind.pattern, @@ -2460,8 +2439,8 @@ class MapEntry extends CollectionElement { @override void visit(Harness h, CollectionElementContext context) { - SharedTypeSchemaView keySchema; - SharedTypeSchemaView valueSchema; + SharedTypeSchemaView keySchema; + SharedTypeSchemaView valueSchema; switch (context) { case CollectionElementContextMapEntry(:var keyType, :var valueType): keySchema = SharedTypeSchemaView(keyType); @@ -2498,8 +2477,7 @@ class MapLiteral extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var context = CollectionElementContextMapEntry._(keyType, valueType); for (var element in elements) { h.typeAnalyzer.dispatchCollectionElement(element, context); @@ -2523,7 +2501,7 @@ class MapPattern extends Pattern { : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeMapPatternSchema( typeArguments: typeArguments?.wrapSharedTypeMapEntryView(), elements: elements); @@ -2537,12 +2515,12 @@ class MapPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var mapPatternResult = h.typeAnalyzer.analyzeMapPattern(context, this, typeArguments: typeArguments?.wrapSharedTypeMapEntryView(), elements: elements); - var matchedType = mapPatternResult.matchedValueType.unwrapTypeView(); - var requiredType = mapPatternResult.requiredType.unwrapTypeView(); + var matchedType = mapPatternResult.matchedValueType.unwrapTypeView(); + var requiredType = mapPatternResult.requiredType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.atom(requiredType.type, Kind.type, location: location); h.irBuilder.apply( @@ -2591,8 +2569,8 @@ class MapPatternEntry extends Node implements MapPatternElement { } class MiniAstOperations - with TypeAnalyzerOperationsMixin - implements TypeAnalyzerOperations { + with TypeAnalyzerOperationsMixin + implements TypeAnalyzerOperations { static const Map _coreExhaustiveness = const { '()': true, '(int, int?)': false, @@ -2665,21 +2643,20 @@ class MiniAstOperations }; @override - late final SharedTypeView objectQuestionType = + late final SharedTypeView objectQuestionType = SharedTypeView(Type('Object?')); @override - late final SharedTypeView objectType = SharedTypeView(Type('Object')); + late final SharedTypeView objectType = SharedTypeView(Type('Object')); @override - late final SharedTypeSchemaView unknownType = - SharedTypeSchemaView(Type('_')); + late final SharedTypeSchemaView unknownType = SharedTypeSchemaView(Type('_')); @override - late final SharedTypeView intType = SharedTypeView(Type('int')); + late final SharedTypeView intType = SharedTypeView(Type('int')); @override - late final SharedTypeView doubleType = SharedTypeView(Type('double')); + late final SharedTypeView doubleType = SharedTypeView(Type('double')); bool? _legacy; @@ -2703,13 +2680,13 @@ class MiniAstOperations final _variance = >{}; @override - final SharedTypeView boolType = SharedTypeView(Type('bool')); + final SharedTypeView boolType = SharedTypeView(Type('bool')); @override - SharedTypeView get dynamicType => SharedTypeView(DynamicType.instance); + SharedTypeView get dynamicType => SharedTypeView(DynamicType.instance); @override - SharedTypeView get errorType => SharedTypeView(InvalidType.instance); + SharedTypeView get errorType => SharedTypeView(InvalidType.instance); bool get legacy => _legacy ?? false; @@ -2718,10 +2695,10 @@ class MiniAstOperations } @override - SharedTypeView get neverType => SharedTypeView(NeverType.instance); + SharedTypeView get neverType => SharedTypeView(NeverType.instance); @override - SharedTypeView get nullType => SharedTypeView(NullType.instance); + SharedTypeView get nullType => SharedTypeView(NullType.instance); /// Updates the harness with a new result for [downwardInfer]. void addDownwardInfer({ @@ -2763,10 +2740,11 @@ class MiniAstOperations } @override - TypeClassification classifyType(SharedTypeView type) { - if (isSubtypeOfInternal(type.unwrapTypeView(), Type('Object'))) { + TypeClassification classifyType(SharedTypeView type) { + if (isSubtypeOfInternal(type.unwrapTypeView(), Type('Object'))) { return TypeClassification.nonNullable; - } else if (isSubtypeOfInternal(type.unwrapTypeView(), NullType.instance)) { + } else if (isSubtypeOfInternal( + type.unwrapTypeView(), NullType.instance)) { return TypeClassification.nullOrEquivalent; } else { return TypeClassification.potentiallyNullable; @@ -2782,17 +2760,16 @@ class MiniAstOperations } @override - SharedTypeView extensionTypeErasure(SharedTypeView type) { + SharedTypeView extensionTypeErasure(SharedTypeView type) { var query = '${type.unwrapTypeView()}'; return SharedTypeView( _extensionTypeErasure[query] ?? type.unwrapTypeView()); } @override - SharedTypeView factor( - SharedTypeView from, SharedTypeView what) { - return SharedTypeView( - _typeSystem.factor(from.unwrapTypeView(), what.unwrapTypeView())); + SharedTypeView factor(SharedTypeView from, SharedTypeView what) { + return SharedTypeView(_typeSystem.factor( + from.unwrapTypeView(), what.unwrapTypeView())); } @override @@ -2827,39 +2804,38 @@ class MiniAstOperations } @override - SharedTypeView greatestClosure(SharedTypeSchemaView schema) { + SharedTypeView greatestClosure(SharedTypeSchemaView schema) { return SharedTypeView(schema - .unwrapTypeSchemaView() + .unwrapTypeSchemaView() .closureWithRespectToUnknown(covariant: true) ?? schema.unwrapTypeSchemaView()); } @override - Type greatestClosureOfTypeInternal(Type type, - List> typeParametersToEliminate) { + Type greatestClosureOfTypeInternal( + Type type, List typeParametersToEliminate) { // TODO(paulberry): Implement greatest closure of types in mini ast. throw UnimplementedError(); } @override - bool isAlwaysExhaustiveType(SharedTypeView type) { - var query = type.unwrapTypeView().type; + bool isAlwaysExhaustiveType(SharedTypeView type) { + var query = type.unwrapTypeView().type; return _exhaustiveness[query] ?? fail('Unknown exhaustiveness query: $query'); } @override - bool isAssignableTo( - SharedTypeView fromType, SharedTypeView toType) { + bool isAssignableTo(SharedTypeView fromType, SharedTypeView toType) { if (legacy && isSubtypeOfInternal( - toType.unwrapTypeView(), fromType.unwrapTypeView())) { + toType.unwrapTypeView(), fromType.unwrapTypeView())) { return true; } if (fromType is DynamicType) return true; if (fromType is InvalidType) return true; return isSubtypeOfInternal( - fromType.unwrapTypeView(), toType.unwrapTypeView()); + fromType.unwrapTypeView(), toType.unwrapTypeView()); } @override @@ -2896,7 +2872,7 @@ class MiniAstOperations } @override - bool isNever(SharedTypeView type) { + bool isNever(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); return unwrappedType is NeverType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none; @@ -2906,7 +2882,7 @@ class MiniAstOperations bool isNonNullableInternal(Type type) { Type unwrappedType = type; if (unwrappedType is DynamicType || - unwrappedType is SharedUnknownTypeStructure || + unwrappedType is SharedUnknownType || unwrappedType is VoidType || unwrappedType is NullType || unwrappedType is InvalidType) { @@ -2934,7 +2910,7 @@ class MiniAstOperations bool isNullableInternal(Type type) { Type unwrappedType = type; if (unwrappedType is DynamicType || - unwrappedType is SharedUnknownTypeStructure || + unwrappedType is SharedUnknownType || unwrappedType is VoidType || unwrappedType is NullType) { return true; @@ -2950,7 +2926,7 @@ class MiniAstOperations } @override - bool isObject(SharedTypeView type) { + bool isObject(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); return unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -2968,7 +2944,7 @@ class MiniAstOperations } @override - bool isTypeParameterType(SharedTypeView type) { + bool isTypeParameterType(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); return unwrappedType is TypeParameterType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none; @@ -2976,10 +2952,10 @@ class MiniAstOperations @override bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView typeSchema, - required SharedTypeView type}) { + {required SharedTypeSchemaView typeSchema, + required SharedTypeView type}) { return isSubtypeOfInternal( - type.unwrapTypeView(), typeSchema.unwrapTypeSchemaView()); + type.unwrapTypeView(), typeSchema.unwrapTypeSchemaView()); } @override @@ -2988,15 +2964,15 @@ class MiniAstOperations } @override - SharedTypeSchemaView iterableTypeSchema( - SharedTypeSchemaView elementTypeSchema) { + SharedTypeSchemaView iterableTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(PrimaryType(TypeRegistry.iterable, - args: [elementTypeSchema.unwrapTypeSchemaView()])); + args: [elementTypeSchema.unwrapTypeSchemaView()])); } @override - Type leastClosureOfTypeInternal(Type type, - List> typeParametersToEliminate) { + Type leastClosureOfTypeInternal( + Type type, List typeParametersToEliminate) { // TODO(paulberry): Implement greatest closure of types in mini ast. throw UnimplementedError(); } @@ -3083,7 +3059,7 @@ class MiniAstOperations } @override - SharedTypeView? matchListType(SharedTypeView type) { + SharedTypeView? matchListType(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -3095,8 +3071,8 @@ class MiniAstOperations } @override - ({SharedTypeView keyType, SharedTypeView valueType})? - matchMapType(SharedTypeView type) { + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -3111,7 +3087,7 @@ class MiniAstOperations } @override - SharedTypeView? matchStreamType(SharedTypeView type) { + SharedTypeView? matchStreamType(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -3124,8 +3100,8 @@ class MiniAstOperations } @override - TypeDeclarationMatchResult? - matchTypeDeclarationTypeInternal(Type type) { + TypeDeclarationMatchResult? matchTypeDeclarationTypeInternal( + Type type) { if (type is! PrimaryType) return null; TypeDeclarationKind typeDeclarationKind; if (type.isInterfaceType) { @@ -3157,14 +3133,14 @@ class MiniAstOperations } @override - SharedTypeView normalize(SharedTypeView type) { + SharedTypeView normalize(SharedTypeView type) { var query = '${type.unwrapTypeView()}'; return SharedTypeView( _normalizeResults[query] ?? fail('Unknown query: $query')); } @override - SharedTypeView promoteToNonNull(SharedTypeView type) { + SharedTypeView promoteToNonNull(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType.nullabilitySuffix == NullabilitySuffix.question) { return SharedTypeView( @@ -3178,31 +3154,33 @@ class MiniAstOperations @override RecordType recordTypeInternal( - {required List positional, required List<(String, Type)> named}) { + {required List positional, + required covariant List<(String, SharedType)> named}) { return RecordType( - positionalTypes: positional, + positionalTypes: positional.cast(), namedTypes: [ - for (var (name, type) in named) NamedType(name: name, type: type) + for (var (name, type) in named) + NamedType(name: name, type: type as Type) ]..sort((a, b) => a.name.compareTo(b.name)), ); } @override - SharedTypeSchemaView streamTypeSchema( - SharedTypeSchemaView elementTypeSchema) { + SharedTypeSchemaView streamTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(PrimaryType(TypeRegistry.stream, - args: [elementTypeSchema.unwrapTypeSchemaView()])); + args: [elementTypeSchema.unwrapTypeSchemaView()])); } @override - SharedTypeView? tryPromoteToType( - SharedTypeView to, SharedTypeView from) { - var exception = (_promotionExceptions[from.unwrapTypeView().type] ?? - {})[to.unwrapTypeView().type]; + SharedTypeView? tryPromoteToType(SharedTypeView to, SharedTypeView from) { + var exception = (_promotionExceptions[from.unwrapTypeView().type] ?? + {})[to.unwrapTypeView().type]; if (exception != null) { return SharedTypeView(Type(exception)); } - if (isSubtypeOfInternal(to.unwrapTypeView(), from.unwrapTypeView())) { + if (isSubtypeOfInternal( + to.unwrapTypeView(), from.unwrapTypeView())) { return to; } else { return null; @@ -3210,11 +3188,11 @@ class MiniAstOperations } @override - SharedTypeSchemaView typeToSchema(SharedTypeView type) => + SharedTypeSchemaView typeToSchema(SharedTypeView type) => SharedTypeSchemaView(type.unwrapTypeView()); @override - SharedTypeView variableType(Var variable) { + SharedTypeView variableType(Var variable) { return SharedTypeView(variable.type); } @@ -3229,18 +3207,20 @@ class MiniAstOperations } @override - TypeConstraintGenerator + TypeConstraintGenerator createTypeConstraintGenerator( {required TypeConstraintGenerationDataForTesting? typeConstraintGenerationDataForTesting, - required List typeParametersToInfer, - required TypeAnalyzerOperations + required List typeParametersToInfer, + required TypeAnalyzerOperations typeAnalyzerOperations, required bool inferenceUsingBoundsIsEnabled}) { - return TypeConstraintGatherer( - {for (var typeParameter in typeParametersToInfer) typeParameter.name}); + return TypeConstraintGatherer({ + for (var typeParameter in typeParametersToInfer) + typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure() + .name + }); } } @@ -3297,8 +3277,7 @@ class NonNullAssert extends Expression { String toString() => '$operand!'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeNonNullAssert(this, operand); } } @@ -3317,8 +3296,7 @@ class Not extends Expression { String toString() => '!$operand'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeLogicalNot(this, operand); } } @@ -3333,7 +3311,7 @@ class NullCheckOrAssertPattern extends Pattern { : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer .analyzeNullCheckOrAssertPatternSchema(inner, isAssert: isAssert); @override @@ -3343,11 +3321,11 @@ class NullCheckOrAssertPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var analysisResult = h.typeAnalyzer.analyzeNullCheckOrAssertPattern( context, this, inner, isAssert: isAssert); - var matchedType = analysisResult.matchedValueType.unwrapTypeView(); + var matchedType = analysisResult.matchedValueType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.apply(isAssert ? 'nullAssertPattern' : 'nullCheckPattern', [Kind.pattern, Kind.type], Kind.pattern, @@ -3370,8 +3348,7 @@ class NullLiteral extends ConstExpression { String toString() => 'null'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeNullLiteral(this); h.irBuilder.atom('null', Kind.expression, location: location); return result; @@ -3389,7 +3366,7 @@ class ObjectPattern extends Pattern { }) : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { return h.typeAnalyzer .analyzeObjectPatternSchema(SharedTypeView(requiredType)); } @@ -3404,11 +3381,12 @@ class ObjectPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var objectPatternResult = h.typeAnalyzer.analyzeObjectPattern(context, this, fields: fields); - var matchedType = objectPatternResult.matchedValueType.unwrapTypeView(); - var requiredType = objectPatternResult.requiredType.unwrapTypeView(); + var matchedType = + objectPatternResult.matchedValueType.unwrapTypeView(); + var requiredType = objectPatternResult.requiredType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.atom(requiredType.type, Kind.type, location: location); h.irBuilder.apply( @@ -3446,8 +3424,7 @@ class ParenthesizedExpression extends Expression { String toString() => '($expr)'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeParenthesizedExpression(this, expr, schema); } } @@ -3458,7 +3435,7 @@ class ParenthesizedPattern extends Pattern { ParenthesizedPattern._(this.inner, {required super.location}) : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => inner.computeSchema(h); + SharedTypeSchemaView computeSchema(Harness h) => inner.computeSchema(h); @override void preVisit(PreVisitor visitor, VariableBinder variableBinder, @@ -3466,7 +3443,7 @@ class ParenthesizedPattern extends Pattern { inner.preVisit(visitor, variableBinder, isInAssignment: isInAssignment); @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { return inner.visit(h, context); } @@ -3511,7 +3488,7 @@ abstract class Pattern extends Node location: location); } - SharedTypeSchemaView computeSchema(Harness h); + SharedTypeSchemaView computeSchema(Harness h); Pattern or(Pattern other) => LogicalOrPattern(this, other, location: computeLocation()); @@ -3527,7 +3504,7 @@ abstract class Pattern extends Node @override String toString() => _debugString(needsKeywordOrType: true); - PatternResult visit(Harness h, SharedMatchContext context); + PatternResult visit(Harness h, SharedMatchContext context); GuardedPattern when(ProtoExpression? guard) { return GuardedPattern._( @@ -3555,8 +3532,7 @@ class PatternAssignment extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzePatternAssignment(this, lhs, rhs); h.irBuilder.apply( 'patternAssignment', [Kind.expression, Kind.pattern], Kind.expression, @@ -3738,11 +3714,10 @@ class PlaceholderExpression extends ConstExpression { String toString() => '(expr with type $type)'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { h.irBuilder.atom(type.type, Kind.type, location: location); h.irBuilder.apply('expr', [Kind.type], Kind.expression, location: location); - return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -3794,13 +3769,12 @@ class PostIncDec extends Expression { String toString() => '$lhs++'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { Type type = h.typeAnalyzer .analyzeExpression(lhs, h.operations.unknownType) .unwrapTypeView(); lhs._visitPostIncDec(h, this, type); - return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -3857,8 +3831,7 @@ class Property extends PromotableLValue { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzePropertyGet( this, target is CascadePlaceholder ? null : target, propertyName, isNullAware: isNullAware); @@ -3873,7 +3846,7 @@ class Property extends PromotableLValue { } var receiverType = h.typeAnalyzer .analyzeExpression(target, h.operations.unknownType) - .unwrapTypeView(); + .unwrapTypeView(); var member = h.typeAnalyzer._lookupMember(receiverType, propertyName); return h.flow .promotedPropertyType(ExpressionPropertyTarget(target), propertyName, @@ -4182,7 +4155,7 @@ class RecordPattern extends Pattern { RecordPattern._(this.fields, {required super.location}) : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { return h.typeAnalyzer.analyzeRecordPatternSchema( fields: fields, ); @@ -4198,11 +4171,12 @@ class RecordPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var recordPatternResult = h.typeAnalyzer.analyzeRecordPattern(context, this, fields: fields); - var matchedType = recordPatternResult.matchedValueType.unwrapTypeView(); - var requiredType = recordPatternResult.requiredType.unwrapTypeView(); + var matchedType = + recordPatternResult.matchedValueType.unwrapTypeView(); + var requiredType = recordPatternResult.requiredType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.atom(requiredType.type, Kind.type, location: location); h.irBuilder.apply( @@ -4251,7 +4225,7 @@ class RelationalPattern extends Pattern { : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeRelationalPatternSchema(); @override @@ -4261,10 +4235,10 @@ class RelationalPattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var analysisResult = h.typeAnalyzer.analyzeRelationalPattern(context, this, operand); - var matchedType = analysisResult.matchedValueType.unwrapTypeView(); + var matchedType = analysisResult.matchedValueType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.apply(operator, [Kind.expression, Kind.type], Kind.pattern, names: ['matchedType'], location: location); @@ -4334,8 +4308,7 @@ class Second extends Expression { String toString() => 'second($first, $second)'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { h.typeAnalyzer.analyzeExpression(first, h.operations.unknownType); var type = h.typeAnalyzer.analyzeExpression(second, schema); h.irBuilder.apply( @@ -4396,8 +4369,7 @@ class SwitchExpression extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer .analyzeSwitchExpression(this, scrutinee, cases.length, schema); h.irBuilder.apply( @@ -4514,7 +4486,7 @@ class SwitchStatement extends Statement { expectLastCaseTerminates ?? anything); expect(analysisResult.requiresExhaustivenessValidation, expectRequiresExhaustivenessValidation ?? anything); - expect(analysisResult.scrutineeType.unwrapTypeView().type, + expect(analysisResult.scrutineeType.unwrapTypeView().type, expectScrutineeType ?? anything); h.irBuilder.apply( 'switch', @@ -4585,8 +4557,7 @@ class This extends Expression { String toString() => 'this'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeThis(this); h.irBuilder.atom('this', Kind.expression, location: location); return result; @@ -4606,8 +4577,7 @@ class ThisOrSuperProperty extends PromotableLValue { {_LValueDisposition disposition = _LValueDisposition.read}) {} @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeThisOrSuperPropertyGet( this, propertyName, isSuperAccess: isSuperAccess); @@ -4661,8 +4631,7 @@ class Throw extends Expression { String toString() => 'throw ...'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeThrow(this, operand); } } @@ -4870,7 +4839,7 @@ class VariablePattern extends Pattern { : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { if (isAssignedVariable) { return h.typeAnalyzer.analyzeAssignedVariablePatternSchema(variable); } else { @@ -4894,7 +4863,7 @@ class VariablePattern extends Pattern { } @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { if (isAssignedVariable) { var analysisResult = h.typeAnalyzer .analyzeAssignedVariablePattern(context, this, variable); @@ -4905,9 +4874,9 @@ class VariablePattern extends Pattern { .analyzeDeclaredVariablePattern(context, this, variable, variable.name, declaredType?.wrapSharedTypeView()); var matchedType = - declaredVariablePatternResult.matchedValueType.unwrapTypeView(); + declaredVariablePatternResult.matchedValueType.unwrapTypeView(); var staticType = - declaredVariablePatternResult.staticType.unwrapTypeView(); + declaredVariablePatternResult.staticType.unwrapTypeView(); h.typeAnalyzer.handleDeclaredVariablePattern(this, matchedType: matchedType, staticType: staticType); return declaredVariablePatternResult; @@ -4948,8 +4917,7 @@ class VariableReference extends LValue { String toString() => variable.name; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeVariableGet(this, variable, callback); h.irBuilder.atom(variable.name, Kind.expression, location: location); return result; @@ -5011,7 +4979,7 @@ class WildcardPattern extends Pattern { : super._(); @override - SharedTypeSchemaView computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { return h.typeAnalyzer.analyzeWildcardPatternSchema( declaredType: declaredType?.wrapSharedTypeView(), ); @@ -5022,13 +4990,13 @@ class WildcardPattern extends Pattern { {required bool isInAssignment}) {} @override - PatternResult visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { var analysisResult = h.typeAnalyzer.analyzeWildcardPattern( context: context, node: this, declaredType: declaredType?.wrapSharedTypeView(), ); - var matchedType = analysisResult.matchedValueType.unwrapTypeView(); + var matchedType = analysisResult.matchedValueType.unwrapTypeView(); h.irBuilder.atom(matchedType.type, Kind.type, location: location); h.irBuilder.apply('wildcardPattern', [Kind.type], Kind.pattern, names: ['matchedType'], location: location); @@ -5077,8 +5045,7 @@ class WrappedExpression extends Expression { } @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { late MiniIRTmp beforeTmp; if (before != null) { h.typeAnalyzer.dispatchStatement(before!); @@ -5101,7 +5068,7 @@ class WrappedExpression extends Expression { if (before != null) { h.irBuilder.let(beforeTmp, location: location); } - return new ExpressionTypeAnalysisResult(type: type); + return new ExpressionTypeAnalysisResult(type: type); } } @@ -5124,8 +5091,7 @@ class Write extends Expression { String toString() => '$lhs = $rhs'; @override - ExpressionTypeAnalysisResult visit( - Harness h, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var rhs = this.rhs; Type type; if (rhs == null) { @@ -5141,7 +5107,7 @@ class Write extends Expression { } lhs._visitWrite(h, this, type, rhs); // TODO(paulberry): null shorting - return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -5163,8 +5129,8 @@ enum _LValueDisposition { class _MiniAstErrors implements - TypeAnalyzerErrors, Pattern, void>, + TypeAnalyzerErrors, VariableBinderErrors { final Set _accumulatedErrors = {}; @@ -5185,8 +5151,8 @@ class _MiniAstErrors void caseExpressionTypeMismatch( {required Expression scrutinee, required Expression caseExpression, - required SharedTypeView scrutineeType, - required SharedTypeView caseExpressionType, + required SharedTypeView scrutineeType, + required SharedTypeView caseExpressionType, required bool nullSafetyEnabled}) { _recordError('caseExpressionTypeMismatch', { 'scrutinee': scrutinee, @@ -5289,7 +5255,7 @@ class _MiniAstErrors @override void matchedTypeIsStrictlyNonNullable({ required Pattern pattern, - required SharedTypeView matchedType, + required SharedTypeView matchedType, }) { _recordError('matchedTypeIsStrictlyNonNullable', { 'pattern': pattern, @@ -5300,8 +5266,8 @@ class _MiniAstErrors @override void matchedTypeIsSubtypeOfRequired({ required Pattern pattern, - required SharedTypeView matchedType, - required SharedTypeView requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { _recordError('matchedTypeIsSubtypeOfRequired', { 'pattern': pattern, @@ -5319,7 +5285,7 @@ class _MiniAstErrors void patternForInExpressionIsNotIterable({ required Node node, required Expression expression, - required SharedTypeView expressionType, + required SharedTypeView expressionType, }) { _recordError('patternForInExpressionIsNotIterable', { 'node': node, @@ -5332,8 +5298,8 @@ class _MiniAstErrors void patternTypeMismatchInIrrefutableContext( {required Node pattern, required Node context, - required SharedTypeView matchedType, - required SharedTypeView requiredType}) { + required SharedTypeView matchedType, + required SharedTypeView requiredType}) { _recordError('patternTypeMismatchInIrrefutableContext', { 'pattern': pattern, 'context': context, @@ -5352,8 +5318,8 @@ class _MiniAstErrors @override void relationalPatternOperandTypeNotAssignable({ required Pattern pattern, - required SharedTypeView operandType, - required SharedTypeView parameterType, + required SharedTypeView operandType, + required SharedTypeView parameterType, }) { _recordError('relationalPatternOperandTypeNotAssignable', { 'pattern': pattern, @@ -5365,7 +5331,7 @@ class _MiniAstErrors @override void relationalPatternOperatorReturnTypeNotAssignableToBool({ required Pattern pattern, - required SharedTypeView returnType, + required SharedTypeView returnType, }) { _recordError('relationalPatternOperatorReturnTypeNotAssignableToBool', { 'pattern': pattern, @@ -5428,9 +5394,9 @@ class _MiniAstErrors class _MiniAstTypeAnalyzer with - TypeAnalyzer, - NullShortingMixin> { + TypeAnalyzer, + NullShortingMixin { final Harness _harness; @override @@ -5453,13 +5419,13 @@ class _MiniAstTypeAnalyzer /// The type of the target of the innermost enclosing cascade expression /// (promoted to non-nullable, if it's a null-aware cascade), or `null` if no /// cascade expression is currently being visited. - SharedTypeView? _currentCascadeTargetType; + SharedTypeView? _currentCascadeTargetType; _MiniAstTypeAnalyzer(this._harness, this.options); @override - FlowAnalysis> - get flow => _harness.flow; + FlowAnalysis get flow => + _harness.flow; Type get nullType => NullType.instance; @@ -5481,7 +5447,7 @@ class _MiniAstTypeAnalyzer flow.assert_end(); } - ExpressionTypeAnalysisResult analyzeBinaryExpression( + ExpressionTypeAnalysisResult analyzeBinaryExpression( Expression node, Expression lhs, String operatorName, Expression rhs) { bool isEquals = false; bool isNot = false; @@ -5515,7 +5481,7 @@ class _MiniAstTypeAnalyzer flow.logicalBinaryOp_begin(); } var leftType = analyzeExpression(lhs, operations.unknownType); - ExpressionInfo>? leftInfo; + ExpressionInfo? leftInfo; if (isEquals) { leftInfo = flow.equalityOperand_end(lhs); } else if (isLogical) { @@ -5529,7 +5495,7 @@ class _MiniAstTypeAnalyzer } else if (isLogical) { flow.logicalBinaryOp_end(node, rhs, isAnd: isAnd); } - return new ExpressionTypeAnalysisResult(type: operations.boolType); + return new ExpressionTypeAnalysisResult(type: operations.boolType); } void analyzeBlock(Iterable statements) { @@ -5547,11 +5513,8 @@ class _MiniAstTypeAnalyzer flow.handleBreak(target); } - ExpressionTypeAnalysisResult analyzeConditionalExpression( - Expression node, - Expression condition, - Expression ifTrue, - Expression ifFalse) { + ExpressionTypeAnalysisResult analyzeConditionalExpression(Expression node, + Expression condition, Expression ifTrue, Expression ifFalse) { flow.conditional_conditionBegin(); analyzeExpression(condition, operations.unknownType); flow.conditional_thenBegin(condition, node); @@ -5560,7 +5523,7 @@ class _MiniAstTypeAnalyzer var ifFalseType = analyzeExpression(ifFalse, operations.unknownType); var lubType = operations.lub(ifTrueType, ifFalseType); flow.conditional_end(node, lubType, ifFalse, ifFalseType); - return new ExpressionTypeAnalysisResult(type: lubType); + return new ExpressionTypeAnalysisResult(type: lubType); } void analyzeContinueStatement(Statement? target) { @@ -5579,13 +5542,13 @@ class _MiniAstTypeAnalyzer analyzeExpression(expression, operations.unknownType); } - ExpressionTypeAnalysisResult analyzeIfNullExpression( + ExpressionTypeAnalysisResult analyzeIfNullExpression( Expression node, Expression lhs, Expression rhs) { var leftType = analyzeExpression(lhs, operations.unknownType); flow.ifNullExpression_rightBegin(lhs, leftType); var rightType = analyzeExpression(rhs, operations.unknownType); flow.ifNullExpression_end(); - return new ExpressionTypeAnalysisResult( + return new ExpressionTypeAnalysisResult( type: operations.lub( flow.operations.promoteToNonNull(leftType), rightType)); } @@ -5596,11 +5559,11 @@ class _MiniAstTypeAnalyzer flow.labeledStatement_end(); } - ExpressionTypeAnalysisResult analyzeLogicalNot( + ExpressionTypeAnalysisResult analyzeLogicalNot( Expression node, Expression expression) { analyzeExpression(expression, operations.unknownType); flow.logicalNot_end(node, expression); - return new ExpressionTypeAnalysisResult(type: operations.boolType); + return new ExpressionTypeAnalysisResult(type: operations.boolType); } /// Invokes the appropriate flow analysis methods, and creates the IR @@ -5611,7 +5574,7 @@ class _MiniAstTypeAnalyzer /// expressions. /// /// Named arguments are not supported. - ExpressionTypeAnalysisResult analyzeMethodInvocation(Expression node, + ExpressionTypeAnalysisResult analyzeMethodInvocation(Expression node, Expression? target, String methodName, List arguments, {required bool isNullAware}) { // Analyze the target, generate its IR, and look up the method's type. @@ -5644,31 +5607,27 @@ class _MiniAstTypeAnalyzer // Form the IR for the member invocation. _harness.irBuilder.apply(methodName, inputKinds, Kind.expression, location: node.location); - return new ExpressionTypeAnalysisResult( - type: SharedTypeView(returnType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(returnType)); } - ExpressionTypeAnalysisResult analyzeNonNullAssert( + ExpressionTypeAnalysisResult analyzeNonNullAssert( Expression node, Expression expression) { var type = analyzeExpression(expression, operations.unknownType); flow.nonNullAssert_end(expression); - return new ExpressionTypeAnalysisResult( + return new ExpressionTypeAnalysisResult( type: flow.operations.promoteToNonNull(type)); } - ExpressionTypeAnalysisResult analyzeNullLiteral(Expression node) { + ExpressionTypeAnalysisResult analyzeNullLiteral(Expression node) { flow.nullLiteral(node, SharedTypeView(nullType)); - return new ExpressionTypeAnalysisResult( - type: SharedTypeView(nullType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(nullType)); } - ExpressionTypeAnalysisResult analyzeParenthesizedExpression( - Expression node, - Expression expression, - SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult analyzeParenthesizedExpression( + Expression node, Expression expression, SharedTypeSchemaView schema) { var type = analyzeExpression(expression, schema); flow.parenthesizedExpression(node, expression); - return new ExpressionTypeAnalysisResult(type: type); + return new ExpressionTypeAnalysisResult(type: type); } /// Invokes the appropriate flow analysis methods, and creates the IR @@ -5678,7 +5637,7 @@ class _MiniAstTypeAnalyzer /// property being accessed. /// /// Null-aware property accesses are not supported. - ExpressionTypeAnalysisResult analyzePropertyGet( + ExpressionTypeAnalysisResult analyzePropertyGet( Expression node, Expression? target, String propertyName, {required bool isNullAware}) { // Analyze the target, generate its IR, and look up the property's type. @@ -5688,22 +5647,20 @@ class _MiniAstTypeAnalyzer // Build the property get IR. _harness.irBuilder.propertyGet(propertyName, location: node.location); // TODO(paulberry): handle null shorting - return new ExpressionTypeAnalysisResult( - type: SharedTypeView(propertyType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(propertyType)); } void analyzeReturnStatement() { flow.handleExit(); } - ExpressionTypeAnalysisResult analyzeThis(Expression node) { + ExpressionTypeAnalysisResult analyzeThis(Expression node) { var thisType = this.thisType; flow.thisOrSuper(node, SharedTypeView(thisType), isSuper: false); - return new ExpressionTypeAnalysisResult( - type: SharedTypeView(thisType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(thisType)); } - ExpressionTypeAnalysisResult analyzeThisOrSuperPropertyGet( + ExpressionTypeAnalysisResult analyzeThisOrSuperPropertyGet( Expression node, String propertyName, {required bool isSuperAccess}) { var member = _lookupMember(thisType, propertyName); @@ -5718,15 +5675,15 @@ class _MiniAstTypeAnalyzer member, SharedTypeView(memberType)) ?.unwrapTypeView(); - return new ExpressionTypeAnalysisResult( + return new ExpressionTypeAnalysisResult( type: SharedTypeView(promotedType ?? memberType)); } - ExpressionTypeAnalysisResult analyzeThrow( + ExpressionTypeAnalysisResult analyzeThrow( Expression node, Expression expression) { analyzeExpression(expression, operations.unknownType); flow.handleExit(); - return new ExpressionTypeAnalysisResult(type: operations.neverType); + return new ExpressionTypeAnalysisResult(type: operations.neverType); } void analyzeTryStatement(Statement node, Statement body, @@ -5757,26 +5714,26 @@ class _MiniAstTypeAnalyzer } } - ExpressionTypeAnalysisResult analyzeTypeCast( + ExpressionTypeAnalysisResult analyzeTypeCast( Expression node, Expression expression, Type type) { analyzeExpression(expression, operations.unknownType); flow.asExpression_end(expression, SharedTypeView(type)); - return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } - ExpressionTypeAnalysisResult analyzeTypeTest( + ExpressionTypeAnalysisResult analyzeTypeTest( Expression node, Expression expression, Type type, {bool isInverted = false}) { analyzeExpression(expression, operations.unknownType); flow.isExpression_end(node, expression, isInverted, SharedTypeView(type)); - return new ExpressionTypeAnalysisResult(type: operations.boolType); + return new ExpressionTypeAnalysisResult(type: operations.boolType); } - ExpressionTypeAnalysisResult analyzeVariableGet( + ExpressionTypeAnalysisResult analyzeVariableGet( Expression node, Var variable, void Function(Type?)? callback) { var promotedType = flow.variableRead(node, variable); callback?.call(promotedType?.unwrapTypeView()); - return new ExpressionTypeAnalysisResult( + return new ExpressionTypeAnalysisResult( type: promotedType ?? SharedTypeView(variable.type)); } @@ -5788,8 +5745,8 @@ class _MiniAstTypeAnalyzer flow.whileStatement_end(); } - SharedTypeView createNullAwareGuard( - Expression target, SharedTypeView targetType) { + SharedTypeView createNullAwareGuard( + Expression target, SharedTypeView targetType) { var tmp = _harness.irBuilder.allocateTmp(location: target.location); startNullShorting(tmp, target, targetType); _harness.irBuilder.readTmp(tmp, location: target.location); @@ -5809,15 +5766,15 @@ class _MiniAstTypeAnalyzer } @override - ExpressionTypeAnalysisResult dispatchExpression( - Expression expression, SharedTypeSchemaView schema) { + ExpressionTypeAnalysisResult dispatchExpression( + Expression expression, SharedTypeSchemaView schema) { if (expression._expectedSchema case var expectedSchema?) { - expect(schema.unwrapTypeSchemaView().type, expectedSchema); + expect(schema.unwrapTypeSchemaView().type, expectedSchema); } var result = _irBuilder.guard(expression, () => expression.visit(_harness, schema)); if (expression._expectedType case var expectedType?) { - expect(result.type.unwrapTypeView().type, expectedType, + expect(result.type.unwrapTypeView().type, expectedType, reason: 'at ${expression.location}'); } if (expression._expectedIR case var expectedIR?) { @@ -5828,13 +5785,13 @@ class _MiniAstTypeAnalyzer } @override - PatternResult dispatchPattern( + PatternResult dispatchPattern( SharedMatchContext context, covariant Pattern node) { return node.visit(_harness, context); } @override - SharedTypeSchemaView dispatchPatternSchema(covariant Pattern node) { + SharedTypeSchemaView dispatchPatternSchema(covariant Pattern node) { return node.computeSchema(_harness); } @@ -5848,8 +5805,8 @@ class _MiniAstTypeAnalyzer } @override - SharedTypeView downwardInferObjectPatternRequiredType({ - required SharedTypeView matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required covariant ObjectPattern pattern, }) { var requiredType = pattern.requiredType; @@ -5878,7 +5835,7 @@ class _MiniAstTypeAnalyzer required JoinedPatternVariableLocation location, required JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView type, + required SharedTypeView type, }) { variable.isFinal = isFinal; variable.type = type.unwrapTypeView(); @@ -6036,7 +5993,7 @@ class _MiniAstTypeAnalyzer @override void handleMapPatternEntry( - Pattern container, Node entryElement, SharedTypeView keyType) { + Pattern container, Node entryElement, SharedTypeView keyType) { _irBuilder.apply('mapPatternEntry', [Kind.expression, Kind.pattern], Kind.mapPatternElement, location: entryElement.location); @@ -6101,8 +6058,7 @@ class _MiniAstTypeAnalyzer } @override - void handleNullShortingStep( - MiniIRTmp guard, SharedTypeView inferredType) { + void handleNullShortingStep(MiniIRTmp guard, SharedTypeView inferredType) { _irBuilder.ifNotNull(guard, location: guard.location); } @@ -6114,11 +6070,11 @@ class _MiniAstTypeAnalyzer }) {} @override - void handleSwitchScrutinee(SharedTypeView type) {} + void handleSwitchScrutinee(SharedTypeView type) {} @override bool isLegacySwitchExhaustive( - covariant SwitchStatement node, SharedTypeView expressionType) { + covariant SwitchStatement node, SharedTypeView expressionType) { return node.isLegacyExhaustive!; } @@ -6136,9 +6092,9 @@ class _MiniAstTypeAnalyzer } @override - (_PropertyElement?, SharedTypeView) resolveObjectPatternPropertyGet({ + (_PropertyElement?, SharedTypeView) resolveObjectPatternPropertyGet({ required Pattern objectPattern, - required SharedTypeView receiverType, + required SharedTypeView receiverType, required shared.RecordPatternField field, }) { var propertyMember = @@ -6151,14 +6107,14 @@ class _MiniAstTypeAnalyzer } @override - RelationalOperatorResolution? resolveRelationalPatternOperator( - covariant RelationalPattern node, SharedTypeView matchedValueType) { + RelationalOperatorResolution? resolveRelationalPatternOperator( + covariant RelationalPattern node, SharedTypeView matchedValueType) { return _harness.resolveRelationalPatternOperator( matchedValueType.unwrapTypeView(), node.operator); } @override - void setVariableType(Var variable, SharedTypeView type) { + void setVariableType(Var variable, SharedTypeView type) { variable.type = type.unwrapTypeView(); } @@ -6166,8 +6122,7 @@ class _MiniAstTypeAnalyzer String toString() => _irBuilder.toString(); @override - SharedTypeView variableTypeFromInitializerType( - SharedTypeView type) { + SharedTypeView variableTypeFromInitializerType(SharedTypeView type) { // Variables whose initializer has type `Null` receive the inferred type // `dynamic`. if (_harness.operations.classifyType(type) == @@ -6180,7 +6135,7 @@ class _MiniAstTypeAnalyzer // TODO(paulberry): add language tests to verify that the behavior of // `type.recursivelyDemote` matches what the analyzer and CFE do. return SharedTypeView( - type.unwrapTypeView().recursivelyDemote(covariant: true) ?? + type.unwrapTypeView().recursivelyDemote(covariant: true) ?? type.unwrapTypeView()); } @@ -6199,7 +6154,7 @@ class _MiniAstTypeAnalyzer {required String location, required bool isNullAware}) { // Analyze the target, and generate its IR. PropertyTarget propertyTarget; - SharedTypeView targetType; + SharedTypeView targetType; if (target == null) { if (isNullAware) { fail( @@ -6219,7 +6174,8 @@ class _MiniAstTypeAnalyzer } // Look up the type of the member, applying type promotion if necessary. var member = _lookupMember(targetType.unwrapTypeView(), propertyName); - var memberType = member?._type ?? operations.dynamicType.unwrapTypeView(); + var memberType = + member?._type ?? operations.dynamicType.unwrapTypeView(); return flow .propertyGet(propertyGetNode, propertyTarget, propertyName, member, SharedTypeView(memberType)) diff --git a/pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart b/pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart index ef5dba028c55..aa0b2f37165f 100644 --- a/pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart +++ b/pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart @@ -9,11 +9,9 @@ import 'package:_fe_analyzer_shared/src/types/shared_type.dart'; import 'mini_ast.dart'; import 'mini_types.dart'; -class TypeConstraintGatherer extends TypeConstraintGenerator - with - TypeConstraintGeneratorMixin { +class TypeConstraintGatherer + extends TypeConstraintGenerator + with TypeConstraintGeneratorMixin { @override final Set typeParametersToConstrain = {}; @@ -51,8 +49,7 @@ class TypeConstraintGatherer extends TypeConstraintGenerator> + Map> computeConstraints() { // TODO(cstefantsova): implement computeConstraints throw UnimplementedError(); @@ -91,16 +88,10 @@ class TypeConstraintGatherer extends TypeConstraintGenerator typeParametersToEliminate - }) instantiateFunctionTypesAndProvideFreshTypeParameters( - SharedFunctionTypeStructure - p, - SharedFunctionTypeStructure - q, - {required bool leftSchema}) { + (Type, Type, {List typeParametersToEliminate}) + instantiateFunctionTypesAndProvideFreshTypeParameters( + SharedFunctionType p, SharedFunctionType q, + {required bool leftSchema}) { // TODO(paulberry): implement instantiateFunctionTypesAndProvideEliminator throw UnimplementedError(); } diff --git a/pkg/_fe_analyzer_shared/test/mini_types.dart b/pkg/_fe_analyzer_shared/test/mini_types.dart index 0dcf1e64e2ea..1b27904fd442 100644 --- a/pkg/_fe_analyzer_shared/test/mini_types.dart +++ b/pkg/_fe_analyzer_shared/test/mini_types.dart @@ -19,8 +19,7 @@ String _parenthesizeIf(bool condition, String s) => condition ? '($s)' : s; /// Representation of the type `dynamic` suitable for unit testing of code in /// the `_fe_analyzer_shared` package. -class DynamicType extends _SpecialSimpleType - implements SharedDynamicTypeStructure { +class DynamicType extends _SpecialSimpleType implements SharedDynamicType { static final instance = DynamicType._(); DynamicType._() @@ -58,10 +57,7 @@ class FreshTypeParameterGenerator { /// Representation of a function type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class FunctionType extends Type - implements - SharedFunctionTypeStructure { +class FunctionType extends Type implements SharedFunctionType { final Type returnType; @override @@ -398,8 +394,7 @@ class InterfaceTypeName extends TypeNameInfo { /// Representation of an invalid type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class InvalidType extends _SpecialSimpleType - implements SharedInvalidTypeStructure { +class InvalidType extends _SpecialSimpleType implements SharedInvalidType { static final instance = InvalidType._(); InvalidType._() @@ -412,7 +407,7 @@ class InvalidType extends _SpecialSimpleType /// A named parameter of a function type. class NamedFunctionParameter implements - SharedNamedFunctionParameterStructure, + SharedNamedFunctionParameter, _Substitutable { final String name; @@ -452,8 +447,7 @@ class NamedFunctionParameter String toString() => [if (isRequired) 'required', type, name].join(' '); } -class NamedType - implements SharedNamedTypeStructure, _Substitutable { +class NamedType implements SharedNamedType, _Substitutable { final String name; final Type type; @@ -496,8 +490,7 @@ class NeverType extends _SpecialSimpleType { /// Representation of the type `Null` suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class NullType extends _SpecialSimpleType - implements SharedNullTypeStructure { +class NullType extends _SpecialSimpleType implements SharedNullType { static final instance = NullType._(); NullType._() @@ -607,7 +600,7 @@ class PrimaryType extends Type { args.isEmpty ? name : '$name<${args.join(', ')}>'; } -class RecordType extends Type implements SharedRecordTypeStructure { +class RecordType extends Type implements SharedRecordType { final List positionalTypes; final List namedTypes; @@ -636,8 +629,7 @@ class RecordType extends Type implements SharedRecordTypeStructure { List get sortedNamedTypes => namedTypes; @override - List> get sortedNamedTypesShared => - sortedNamedTypes; + List get sortedNamedTypesShared => sortedNamedTypes; @override bool operator ==(Object other) => @@ -783,7 +775,7 @@ class SpecialTypeName extends TypeNameInfo { /// Representation of a type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -abstract class Type implements SharedTypeStructure, _Substitutable { +abstract class Type implements SharedType, _Substitutable { @override final NullabilitySuffix nullabilitySuffix; @@ -819,7 +811,7 @@ abstract class Type implements SharedTypeStructure, _Substitutable { String getDisplayString() => type; @override - bool isStructurallyEqualTo(SharedTypeStructure other) => '$this' == '$other'; + bool isStructurallyEqualTo(SharedType other) => '$this' == '$other'; /// Finds the nearest type that doesn't involve any type parameter promotion. /// If `covariant` is `true`, a supertype will be returned (replacing promoted @@ -890,8 +882,7 @@ sealed class TypeNameInfo { } /// A type name that represents a type variable. -class TypeParameter extends TypeNameInfo - implements SharedTypeParameterStructure { +class TypeParameter extends TypeNameInfo implements SharedTypeParameter { /// The type variable's bound. If `null`, the bound is `Object?`. /// /// This is non-final because it needs to be possible to set it after @@ -1704,7 +1695,7 @@ class TypeSystem { /// Representation of the unknown type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class UnknownType extends Type implements SharedUnknownTypeStructure { +class UnknownType extends Type implements SharedUnknownType { const UnknownType({super.nullabilitySuffix = NullabilitySuffix.none}) : super._(); @@ -1739,8 +1730,7 @@ class UnknownType extends Type implements SharedUnknownTypeStructure { /// Representation of the type `void` suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class VoidType extends _SpecialSimpleType - implements SharedVoidTypeStructure { +class VoidType extends _SpecialSimpleType implements SharedVoidType { static final instance = VoidType._(); VoidType._() diff --git a/pkg/analyzer/lib/dart/element/type.dart b/pkg/analyzer/lib/dart/element/type.dart index d1b1d13bc4f5..94492891d529 100644 --- a/pkg/analyzer/lib/dart/element/type.dart +++ b/pkg/analyzer/lib/dart/element/type.dart @@ -28,14 +28,13 @@ import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type_visitor.dart'; -import 'package:analyzer/src/dart/element/type.dart' - show RecordTypeImpl, TypeImpl; +import 'package:analyzer/src/dart/element/type.dart' show RecordTypeImpl; import 'package:meta/meta.dart'; /// The type associated with elements in the element model. /// /// Clients may not extend, implement or mix-in this class. -abstract class DartType implements SharedTypeStructure { +abstract class DartType implements SharedType { /// If this type is an instantiation of a type alias, information about /// the alias element, and the type arguments. /// Otherwise return `null`. diff --git a/pkg/analyzer/lib/src/dart/ast/ast.dart b/pkg/analyzer/lib/src/dart/ast/ast.dart index 11fe0665e1fd..61c4346ddbe2 100644 --- a/pkg/analyzer/lib/src/dart/ast/ast.dart +++ b/pkg/analyzer/lib/src/dart/ast/ast.dart @@ -833,7 +833,7 @@ final class AssignedVariablePatternImpl extends VariablePatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -2357,7 +2357,7 @@ final class CastPatternImpl extends DartPatternImpl implements CastPattern { } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -4031,7 +4031,7 @@ final class ConstantPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -4790,7 +4790,7 @@ sealed class DartPatternImpl extends AstNodeImpl /// Note: most code shouldn't call this method directly, but should instead /// call [ResolverVisitor.dispatchPattern], which has some special logic for /// handling dynamic contexts. - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ); @@ -5024,7 +5024,7 @@ final class DeclaredVariablePatternImpl extends VariablePatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11301,7 +11301,7 @@ final class ListPatternImpl extends DartPatternImpl implements ListPattern { } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11405,7 +11405,7 @@ final class LogicalAndPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11484,7 +11484,7 @@ final class LogicalOrPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11740,10 +11740,7 @@ final class MapPatternImpl extends DartPatternImpl implements MapPattern { @override DartType computePatternSchema(ResolverVisitor resolverVisitor) { var typeArgumentNodes = this.typeArguments?.arguments; - ({ - SharedTypeView keyType, - SharedTypeView valueType - })? typeArguments; + ({SharedTypeView keyType, SharedTypeView valueType})? typeArguments; if (typeArgumentNodes != null && typeArgumentNodes.length == 2) { typeArguments = ( keyType: SharedTypeView(typeArgumentNodes[0].typeOrThrow), @@ -11759,7 +11756,7 @@ final class MapPatternImpl extends DartPatternImpl implements MapPattern { } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13074,7 +13071,7 @@ final class NullAssertPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13210,7 +13207,7 @@ final class NullCheckPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13387,7 +13384,7 @@ final class ObjectPatternImpl extends DartPatternImpl implements ObjectPattern { } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13574,7 +13571,7 @@ final class ParenthesizedPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -14734,7 +14731,7 @@ final class RecordPatternImpl extends DartPatternImpl implements RecordPattern { } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -15186,7 +15183,7 @@ final class RelationalPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -18866,7 +18863,7 @@ final class WildcardPatternImpl extends DartPatternImpl } @override - PatternResult resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart index 8dee45102f73..6569a0bda0af 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart @@ -4662,9 +4662,7 @@ class FormalParameterElementImpl extends PromotableElementImpl2 /// A mixin that provides a common implementation for methods defined in /// [FormalParameterElement]. mixin FormalParameterElementMixin - implements - FormalParameterElement, - SharedNamedFunctionParameterStructure { + implements FormalParameterElement, SharedNamedFunctionParameter { @override void appendToWithoutDelimiters2(StringBuffer buffer) { buffer.write( @@ -11364,7 +11362,7 @@ class TypeParameterElementImpl2 extends TypeDefiningElementImpl2 FragmentedAnnotatableElementMixin, FragmentedElementMixin, _NonTopLevelVariableOrParameter - implements TypeParameterElement2, SharedTypeParameterStructure { + implements TypeParameterElement2, SharedTypeParameter { @override final TypeParameterElementImpl firstFragment; diff --git a/pkg/analyzer/lib/src/dart/element/generic_inferrer.dart b/pkg/analyzer/lib/src/dart/element/generic_inferrer.dart index 3fbdcd90de34..1b6af46bd3bd 100644 --- a/pkg/analyzer/lib/src/dart/element/generic_inferrer.dart +++ b/pkg/analyzer/lib/src/dart/element/generic_inferrer.dart @@ -593,7 +593,8 @@ class GenericInferrer { UnknownInferredType.instance)) { boundConstraint = _typeSystemOperations.mergeInConstraintsFromBound( typeParameterToInfer: typeParameterToInfer, - typeParametersToInfer: _typeFormals, + typeParametersToInfer: + _typeFormals.cast(), lower: constraint.lower.unwrapTypeSchemaView(), inferencePhaseConstraints: inferencePhaseConstraints, dataForTesting: dataForTesting, @@ -644,7 +645,8 @@ class GenericInferrer { UnknownInferredType.instance)) { boundConstraint = _typeSystemOperations.mergeInConstraintsFromBound( typeParameterToInfer: typeParameterToInfer, - typeParametersToInfer: _typeFormals, + typeParametersToInfer: + _typeFormals.cast(), lower: constraint.lower.unwrapTypeSchemaView(), inferencePhaseConstraints: inferencePhaseConstraints, dataForTesting: dataForTesting, diff --git a/pkg/analyzer/lib/src/dart/element/type.dart b/pkg/analyzer/lib/src/dart/element/type.dart index f7baa46c37d0..74ca4f0ba92d 100644 --- a/pkg/analyzer/lib/src/dart/element/type.dart +++ b/pkg/analyzer/lib/src/dart/element/type.dart @@ -35,7 +35,7 @@ List fixedTypeList(DartType e1, [DartType? e2]) { /// The [Type] representing the type `dynamic`. class DynamicTypeImpl extends TypeImpl - implements DynamicType, SharedDynamicTypeStructure { + implements DynamicType, SharedDynamicType { /// The unique instance of this class. static final DynamicTypeImpl instance = DynamicTypeImpl._(); @@ -88,10 +88,7 @@ class DynamicTypeImpl extends TypeImpl /// The type of a function, method, constructor, getter, or setter. class FunctionTypeImpl extends TypeImpl - implements - FunctionType, - SharedFunctionTypeStructure { + implements FunctionType, SharedFunctionType { @override late int hashCode = _computeHashCode(); @@ -1191,7 +1188,7 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { } class InvalidTypeImpl extends TypeImpl - implements InvalidType, SharedInvalidTypeStructure { + implements InvalidType, SharedInvalidType { /// The unique instance of this class. static final InvalidTypeImpl instance = InvalidTypeImpl._(); @@ -1315,8 +1312,7 @@ class NeverTypeImpl extends TypeImpl implements NeverType { /// A concrete implementation of [DartType] representing the type `Null`, with /// no type parameters and no nullability suffix. -class NullTypeImpl extends InterfaceTypeImpl - implements SharedNullTypeStructure { +class NullTypeImpl extends InterfaceTypeImpl implements SharedNullType { NullTypeImpl({ required super.element3, super.alias, @@ -1341,8 +1337,7 @@ abstract class RecordTypeFieldImpl implements RecordTypeField { type = type as TypeImpl; } -class RecordTypeImpl extends TypeImpl - implements RecordType, SharedRecordTypeStructure { +class RecordTypeImpl extends TypeImpl implements RecordType, SharedRecordType { @override final List positionalFields; @@ -1408,8 +1403,7 @@ class RecordTypeImpl extends TypeImpl List get sortedNamedTypes => namedTypes; @override - List> get sortedNamedTypesShared => - sortedNamedTypes; + List get sortedNamedTypesShared => sortedNamedTypes; @override bool operator ==(Object other) { @@ -1509,7 +1503,7 @@ class RecordTypeImpl extends TypeImpl } class RecordTypeNamedFieldImpl extends RecordTypeFieldImpl - implements RecordTypeNamedField, SharedNamedTypeStructure { + implements RecordTypeNamedField, SharedNamedType { @override final String name; @@ -1634,7 +1628,7 @@ abstract class TypeImpl implements DartType { } @override - bool isStructurallyEqualTo(SharedTypeStructure other) => this == other; + bool isStructurallyEqualTo(SharedType other) => this == other; /// Returns true if this type references any of the [parameters]. bool referencesAny(Set parameters) { @@ -1834,8 +1828,7 @@ class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType { } /// A concrete implementation of a [VoidType]. -class VoidTypeImpl extends TypeImpl - implements VoidType, SharedVoidTypeStructure { +class VoidTypeImpl extends TypeImpl implements VoidType, SharedVoidType { /// The unique instance of this class, with indeterminate nullability. static final VoidTypeImpl instance = VoidTypeImpl._(); diff --git a/pkg/analyzer/lib/src/dart/element/type_constraint_gatherer.dart b/pkg/analyzer/lib/src/dart/element/type_constraint_gatherer.dart index c4ddb0575f11..02a1ed763d91 100644 --- a/pkg/analyzer/lib/src/dart/element/type_constraint_gatherer.dart +++ b/pkg/analyzer/lib/src/dart/element/type_constraint_gatherer.dart @@ -32,90 +32,53 @@ import 'package:analyzer/src/dart/element/type_schema.dart'; import 'package:analyzer/src/dart/resolver/flow_analysis_visitor.dart'; /// Instance of [shared.GeneratedTypeConstraint] specific to the Analyzer. -typedef GeneratedTypeConstraint = shared.GeneratedTypeConstraint; +typedef GeneratedTypeConstraint + = shared.GeneratedTypeConstraint; /// Instance of [shared.MergedTypeConstraint] specific to the Analyzer. typedef MergedTypeConstraint = shared.MergedTypeConstraint< - DartType, - TypeParameterElementImpl2, - PromotableElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2>; + PromotableElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>; /// Instance of [shared.TypeConstraintFromArgument] specific to the Analyzer. typedef TypeConstraintFromArgument = shared.TypeConstraintFromArgument< - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2>; + PromotableElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>; /// Instance of [shared.TypeConstraintFromExtendsClause] specific to the Analyzer. typedef TypeConstraintFromExtendsClause - = shared.TypeConstraintFromExtendsClause; + = shared.TypeConstraintFromExtendsClause; /// Instance of [shared.TypeConstraintFromFunctionContext] specific to the Analyzer. typedef TypeConstraintFromFunctionContext - = shared.TypeConstraintFromFunctionContext< - DartType, - DartType, - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2>; + = shared.TypeConstraintFromFunctionContext; /// Instance of [shared.TypeConstraintFromReturnType] specific to the Analyzer. typedef TypeConstraintFromReturnType = shared.TypeConstraintFromReturnType< - DartType, - DartType, - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2>; + PromotableElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>; typedef TypeConstraintGenerationDataForTesting - = shared.TypeConstraintGenerationDataForTesting; + = shared.TypeConstraintGenerationDataForTesting; /// Instance of [shared.TypeConstraintOrigin] specific to the Analyzer. typedef TypeConstraintOrigin = shared.TypeConstraintOrigin< - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2>; + PromotableElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>; /// Instance of [shared.UnknownTypeConstraintOrigin] specific to the Analyzer. typedef UnknownTypeConstraintOrigin = shared.UnknownTypeConstraintOrigin< - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2>; + PromotableElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>; /// Creates sets of [GeneratedTypeConstraint]s for type parameters, based on an /// attempt to make one type schema a subtype of another. class TypeConstraintGatherer extends shared.TypeConstraintGenerator< - DartType, - FormalParameterElementMixin, PromotableElementImpl2, - TypeParameterElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2, AstNodeImpl> with - shared.TypeConstraintGeneratorMixin< - DartType, - FormalParameterElementMixin, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2, - AstNodeImpl> { + shared.TypeConstraintGeneratorMixin { @override final Set typeParametersToConstrain = Set.identity(); @@ -151,7 +114,8 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< TypeParameterElementImpl2 element, DartType lower, {required AstNodeImpl? astNodeForTesting}) { GeneratedTypeConstraint generatedTypeConstraint = - GeneratedTypeConstraint.lower(element, SharedTypeSchemaView(lower)); + GeneratedTypeConstraint.lower( + SharedTypeParameterView(element), SharedTypeSchemaView(lower)); _constraints.add(generatedTypeConstraint); if (dataForTesting != null && astNodeForTesting != null) { (dataForTesting!.generatedTypeConstraints[astNodeForTesting] ??= []) @@ -164,7 +128,8 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< TypeParameterElementImpl2 element, DartType upper, {required AstNodeImpl? astNodeForTesting}) { GeneratedTypeConstraint generatedTypeConstraint = - GeneratedTypeConstraint.upper(element, SharedTypeSchemaView(upper)); + GeneratedTypeConstraint.upper( + SharedTypeParameterView(element), SharedTypeSchemaView(upper)); _constraints.add(generatedTypeConstraint); if (dataForTesting != null && astNodeForTesting != null) { (dataForTesting!.generatedTypeConstraints[astNodeForTesting] ??= []) @@ -184,7 +149,9 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< } for (var constraint in _constraints) { - var parameter = constraint.typeParameter; + var parameter = constraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + TypeParameterElementImpl2>(); var mergedConstraint = result[parameter]!; mergedConstraint.mergeIn(constraint, _typeSystemOperations); @@ -203,13 +170,17 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< for (var constraint in constraints) { if (constraint.isUpper) { addUpperConstraintForParameter( - constraint.typeParameter, + constraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + TypeParameterElementImpl2>(), typeAnalyzerOperations.leastClosureOfTypeInternal( constraint.constraint.unwrapTypeSchemaView(), eliminator), astNodeForTesting: astNodeForTesting); } else { addLowerConstraintForParameter( - constraint.typeParameter, + constraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + TypeParameterElementImpl2>(), typeAnalyzerOperations.greatestClosureOfTypeInternal( constraint.constraint.unwrapTypeSchemaView(), eliminator), astNodeForTesting: astNodeForTesting); diff --git a/pkg/analyzer/lib/src/dart/element/type_schema.dart b/pkg/analyzer/lib/src/dart/element/type_schema.dart index 8c98df88b7bd..25b8df95854a 100644 --- a/pkg/analyzer/lib/src/dart/element/type_schema.dart +++ b/pkg/analyzer/lib/src/dart/element/type_schema.dart @@ -21,8 +21,7 @@ import 'package:analyzer/src/dart/element/type_visitor.dart'; /// parameters that we do not know yet. Notationally it is written `_`, for /// example `List<_>`. This is distinct from `List`. These types will /// never appear in the final resolved AST. -class UnknownInferredType extends TypeImpl - implements SharedUnknownTypeStructure { +class UnknownInferredType extends TypeImpl implements SharedUnknownType { static const UnknownInferredType instance = UnknownInferredType._(); const UnknownInferredType._(); diff --git a/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart b/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart index 2f98b98eeb88..f90f4f9b8eda 100644 --- a/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart +++ b/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart @@ -121,8 +121,7 @@ class AssignmentExpressionResolver { DartType writeType, Expression right, DartType rightType, { - required Map, NonPromotionReason> Function()? - whyNotPromoted, + required Map Function()? whyNotPromoted, }) { if (writeType is! VoidType && _checkForUseOfVoidResult(right)) { return; @@ -260,7 +259,7 @@ class AssignmentExpressionResolver { } void _resolveTypes(AssignmentExpressionImpl node, - {required Map, NonPromotionReason> Function()? + {required Map Function()? whyNotPromoted, required DartType contextType}) { DartType assignedType; diff --git a/pkg/analyzer/lib/src/dart/resolver/binary_expression_resolver.dart b/pkg/analyzer/lib/src/dart/resolver/binary_expression_resolver.dart index 9c3e91c94d0d..66d0494b4b0e 100644 --- a/pkg/analyzer/lib/src/dart/resolver/binary_expression_resolver.dart +++ b/pkg/analyzer/lib/src/dart/resolver/binary_expression_resolver.dart @@ -82,7 +82,7 @@ class BinaryExpressionResolver { } void _checkNonBoolOperand(Expression operand, String operator, - {required Map, NonPromotionReason> Function()? + {required Map Function()? whyNotPromoted}) { _resolver.boolExpressionVerifier.checkForNonBoolExpression( operand, @@ -99,7 +99,7 @@ class BinaryExpressionResolver { var flowAnalysis = _resolver.flowAnalysis; var flow = flowAnalysis.flow; - ExpressionInfo>? leftInfo; + ExpressionInfo? leftInfo; var leftExtensionOverride = left is ExtensionOverride; if (!leftExtensionOverride) { leftInfo = flow?.equalityOperand_end(left); diff --git a/pkg/analyzer/lib/src/dart/resolver/flow_analysis_visitor.dart b/pkg/analyzer/lib/src/dart/resolver/flow_analysis_visitor.dart index 848a3e141de8..2b9758992934 100644 --- a/pkg/analyzer/lib/src/dart/resolver/flow_analysis_visitor.dart +++ b/pkg/analyzer/lib/src/dart/resolver/flow_analysis_visitor.dart @@ -100,7 +100,7 @@ class FlowAnalysisHelper { /// The current flow, when resolving a function body, or `null` otherwise. FlowAnalysis>? flow; + PromotableElementImpl2, SharedTypeView>? flow; FlowAnalysisHelper(bool retainDataForTesting, FeatureSet featureSet, {required TypeSystemOperations typeSystemOperations}) @@ -182,7 +182,7 @@ class FlowAnalysisHelper { } flow = isNonNullableByDefault ? FlowAnalysis>( + PromotableElementImpl2, SharedTypeView>( typeOperations, assignedVariables!, respectImplicitlyTypedVarInitializers: @@ -190,9 +190,12 @@ class FlowAnalysisHelper { fieldPromotionEnabled: fieldPromotionEnabled, inferenceUpdate4Enabled: inferenceUpdate4Enabled, ) - : FlowAnalysis>.legacy( - typeOperations, assignedVariables!); + : FlowAnalysis< + AstNodeImpl, + StatementImpl, + ExpressionImpl, + PromotableElementImpl2, + SharedTypeView>.legacy(typeOperations, assignedVariables!); } /// This method is called whenever the [ResolverVisitor] leaves the body or @@ -432,14 +435,10 @@ class FlowAnalysisHelper { class TypeSystemOperations with - TypeAnalyzerOperationsMixin + TypeAnalyzerOperationsMixin implements - TypeAnalyzerOperations< - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, + TypeAnalyzerOperations { final bool strictCasts; final TypeSystemImpl typeSystem; @@ -447,57 +446,57 @@ class TypeSystemOperations TypeSystemOperations(this.typeSystem, {required this.strictCasts}); @override - SharedTypeView get boolType { + SharedTypeView get boolType { return SharedTypeView(typeSystem.typeProvider.boolType); } @override - SharedTypeView get doubleType { + SharedTypeView get doubleType { throw UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView get dynamicType { + SharedTypeView get dynamicType { return SharedTypeView(typeSystem.typeProvider.dynamicType); } @override - SharedTypeView get errorType { + SharedTypeView get errorType { return SharedTypeView(InvalidTypeImpl.instance); } @override - SharedTypeView get intType { + SharedTypeView get intType { throw UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView get neverType { + SharedTypeView get neverType { return SharedTypeView(typeSystem.typeProvider.neverType); } @override - SharedTypeView get nullType { + SharedTypeView get nullType { return SharedTypeView(typeSystem.typeProvider.nullType); } @override - SharedTypeView get objectQuestionType { + SharedTypeView get objectQuestionType { return SharedTypeView(typeSystem.objectQuestion); } @override - SharedTypeView get objectType { + SharedTypeView get objectType { return SharedTypeView(typeSystem.objectNone); } @override - SharedTypeSchemaView get unknownType { + SharedTypeSchemaView get unknownType { return SharedTypeSchemaView(UnknownInferredType.instance); } @override - TypeClassification classifyType(SharedTypeView type) { + TypeClassification classifyType(SharedTypeView type) { DartType unwrapped = type.unwrapTypeView(); if (type is InvalidType) { return TypeClassification.potentiallyNullable; @@ -513,35 +512,28 @@ class TypeSystemOperations } @override - TypeConstraintGenerator< - DartType, - FormalParameterElementMixin, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2, - AstNodeImpl> + TypeConstraintGenerator createTypeConstraintGenerator( {required covariant TypeConstraintGenerationDataForTesting? typeConstraintGenerationDataForTesting, - required List typeParametersToInfer, + required List typeParametersToInfer, required covariant TypeSystemOperations typeAnalyzerOperations, required bool inferenceUsingBoundsIsEnabled}) { return TypeConstraintGatherer( - typeParameters: typeParametersToInfer, + typeParameters: typeParametersToInfer.cast(), inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled, typeSystemOperations: typeAnalyzerOperations, dataForTesting: typeConstraintGenerationDataForTesting); } @override - SharedTypeView extensionTypeErasure(SharedTypeView type) { - return SharedTypeView(type.unwrapTypeView().extensionTypeErasure); + SharedTypeView extensionTypeErasure(SharedTypeView type) { + return SharedTypeView(type.unwrapTypeView().extensionTypeErasure); } @override - SharedTypeView factor( - SharedTypeView from, SharedTypeView what) { + SharedTypeView factor(SharedTypeView from, SharedTypeView what) { return SharedTypeView( typeSystem.factor(from.unwrapTypeView(), what.unwrapTypeView())); } @@ -574,27 +566,25 @@ class TypeSystemOperations } @override - SharedTypeView greatestClosure( - SharedTypeSchemaView schema) { + SharedTypeView greatestClosure(SharedTypeSchemaView schema) { return SharedTypeView( typeSystem.greatestClosureOfSchema(schema.unwrapTypeSchemaView())); } @override - DartType greatestClosureOfTypeInternal(DartType type, - List> typeParametersToEliminate) { + DartType greatestClosureOfTypeInternal( + DartType type, List typeParametersToEliminate) { return typeSystem.greatestClosure( type, typeParametersToEliminate.cast()); } @override - bool isAlwaysExhaustiveType(SharedTypeView type) { + bool isAlwaysExhaustiveType(SharedTypeView type) { return typeSystem.isAlwaysExhaustive(type.unwrapTypeView()); } @override - bool isAssignableTo( - SharedTypeView fromType, SharedTypeView toType) { + bool isAssignableTo(SharedTypeView fromType, SharedTypeView toType) { return typeSystem.isAssignableTo( fromType.unwrapTypeView(), toType.unwrapTypeView(), strictCasts: strictCasts); @@ -631,8 +621,8 @@ class TypeSystemOperations } @override - bool isNever(SharedTypeView type) { - return type.unwrapTypeView().isBottom; + bool isNever(SharedTypeView type) { + return type.unwrapTypeView().isBottom; } @override @@ -646,8 +636,8 @@ class TypeSystemOperations } @override - bool isObject(SharedTypeView type) { - return type.unwrapTypeView().isDartCoreObject && + bool isObject(SharedTypeView type) { + return type.unwrapTypeView().isDartCoreObject && type.nullabilitySuffix == NullabilitySuffix.none; } @@ -665,14 +655,14 @@ class TypeSystemOperations } @override - bool isTypeParameterType(SharedTypeView type) { - return type.unwrapTypeView() is TypeParameterType; + bool isTypeParameterType(SharedTypeView type) { + return type.unwrapTypeView() is TypeParameterType; } @override bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView typeSchema, - required SharedTypeView type}) { + {required SharedTypeSchemaView typeSchema, + required SharedTypeView type}) { return typeSystem.isSubtypeOf( type.unwrapTypeView(), typeSchema.unwrapTypeSchemaView()); } @@ -683,15 +673,15 @@ class TypeSystemOperations } @override - SharedTypeSchemaView iterableTypeSchema( - SharedTypeSchemaView elementTypeSchema) { + SharedTypeSchemaView iterableTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(typeSystem.typeProvider .iterableType(elementTypeSchema.unwrapTypeSchemaView())); } @override - DartType leastClosureOfTypeInternal(DartType type, - List> typeParametersToEliminate) { + DartType leastClosureOfTypeInternal( + DartType type, List typeParametersToEliminate) { return typeSystem.leastClosure( type, typeParametersToEliminate.cast()); } @@ -745,17 +735,17 @@ class TypeSystemOperations } @override - SharedTypeView? matchListType(SharedTypeView type) { + SharedTypeView? matchListType(SharedTypeView type) { var listElement = typeSystem.typeProvider.listElement; - var listType = type.unwrapTypeView().asInstanceOf(listElement); + var listType = type.unwrapTypeView().asInstanceOf(listElement); return listType == null ? null : SharedTypeView(listType.typeArguments[0]); } @override - ({SharedTypeView keyType, SharedTypeView valueType})? - matchMapType(SharedTypeView type) { + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type) { var mapElement = typeSystem.typeProvider.mapElement; - var mapType = type.unwrapTypeView().asInstanceOf(mapElement); + var mapType = type.unwrapTypeView().asInstanceOf(mapElement); if (mapType != null) { return ( keyType: SharedTypeView(mapType.typeArguments[0]), @@ -766,15 +756,15 @@ class TypeSystemOperations } @override - SharedTypeView? matchStreamType(SharedTypeView type) { + SharedTypeView? matchStreamType(SharedTypeView type) { var streamElement = typeSystem.typeProvider.streamElement; - var listType = type.unwrapTypeView().asInstanceOf(streamElement); + var listType = type.unwrapTypeView().asInstanceOf(streamElement); return listType == null ? null : SharedTypeView(listType.typeArguments[0]); } @override - TypeDeclarationMatchResult? matchTypeDeclarationTypeInternal(DartType type) { + TypeDeclarationMatchResult? + matchTypeDeclarationTypeInternal(DartType type) { if (isInterfaceTypeInternal(type)) { InterfaceTypeImpl interfaceType = type as InterfaceTypeImpl; return TypeDeclarationMatchResult( @@ -805,53 +795,52 @@ class TypeSystemOperations } @override - SharedTypeView normalize(SharedTypeView type) { + SharedTypeView normalize(SharedTypeView type) { return SharedTypeView(typeSystem.normalize(type.unwrapTypeView())); } @override - SharedTypeView promoteToNonNull(SharedTypeView type) { + SharedTypeView promoteToNonNull(SharedTypeView type) { return SharedTypeView(typeSystem.promoteToNonNull(type.unwrapTypeView())); } @override DartType recordTypeInternal( - {required List positional, - required List<(String, DartType)> named}) { + {required List positional, + required List<(String, SharedType)> named}) { return RecordTypeImpl( positionalFields: positional.map((type) { - return RecordTypePositionalFieldImpl(type: type); + return RecordTypePositionalFieldImpl(type: type as DartType); }).toList(), namedFields: named.map((namedType) { var (name, type) = namedType; - return RecordTypeNamedFieldImpl(name: name, type: type); + return RecordTypeNamedFieldImpl(name: name, type: type as DartType); }).toList(), nullabilitySuffix: NullabilitySuffix.none, ); } @override - SharedTypeSchemaView streamTypeSchema( - SharedTypeSchemaView elementTypeSchema) { + SharedTypeSchemaView streamTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(typeSystem.typeProvider .streamType(elementTypeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView? tryPromoteToType( - SharedTypeView to, SharedTypeView from) { + SharedTypeView? tryPromoteToType(SharedTypeView to, SharedTypeView from) { DartType? result = typeSystem.tryPromoteToType(to.unwrapTypeView(), from.unwrapTypeView()); return result == null ? null : SharedTypeView(result); } @override - SharedTypeSchemaView typeToSchema(SharedTypeView type) { + SharedTypeSchemaView typeToSchema(SharedTypeView type) { return SharedTypeSchemaView(type.unwrapTypeView()); } @override - SharedTypeView variableType(PromotableElement2 variable) { + SharedTypeView variableType(PromotableElement2 variable) { return SharedTypeView(variable.type); } @@ -1231,7 +1220,9 @@ class _LocalVariableTypeProvider implements LocalVariableTypeProvider { var promotedType = isRead ? _manager.flow?.variableRead(node, variable) : _manager.flow?.promotedType(variable); - if (promotedType != null) return promotedType.unwrapTypeView(); + if (promotedType != null) { + return promotedType.unwrapTypeView(); + } } return variable.type; } diff --git a/pkg/analyzer/lib/src/dart/resolver/invocation_inferrer.dart b/pkg/analyzer/lib/src/dart/resolver/invocation_inferrer.dart index e49ea39b5124..b8c07ed9d6e1 100644 --- a/pkg/analyzer/lib/src/dart/resolver/invocation_inferrer.dart +++ b/pkg/analyzer/lib/src/dart/resolver/invocation_inferrer.dart @@ -487,9 +487,9 @@ class InvocationInferrer { flow?.equalityOperation_end( argumentList.parent as ExpressionImpl, leftOperandInfo.expressionInfo, - SharedTypeView(leftOperandInfo.staticType), + SharedTypeView(leftOperandInfo.staticType), rightOperandInfo.expressionInfo, - SharedTypeView(rightOperandInfo.staticType)); + SharedTypeView(rightOperandInfo.staticType)); } } @@ -731,7 +731,7 @@ class _FunctionLiteralDependencies extends FunctionLiteralDependencies< class _IdenticalArgumentInfo { /// The [ExpressionInfo] returned by [FlowAnalysis.equalityOperand_end] for /// the argument. - final ExpressionInfo>? expressionInfo; + final ExpressionInfo? expressionInfo; /// The static type of the argument. final DartType staticType; diff --git a/pkg/analyzer/lib/src/dart/resolver/list_pattern_resolver.dart b/pkg/analyzer/lib/src/dart/resolver/list_pattern_resolver.dart index 5c356688eb21..0b9fa2486c52 100644 --- a/pkg/analyzer/lib/src/dart/resolver/list_pattern_resolver.dart +++ b/pkg/analyzer/lib/src/dart/resolver/list_pattern_resolver.dart @@ -15,7 +15,7 @@ class ListPatternResolver { ListPatternResolver(this.resolverVisitor); - PatternResult resolve({ + PatternResult resolve({ required ListPatternImpl node, required SharedMatchContext context, }) { diff --git a/pkg/analyzer/lib/src/dart/resolver/record_literal_resolver.dart b/pkg/analyzer/lib/src/dart/resolver/record_literal_resolver.dart index c2aa39177e62..e0f69f70465c 100644 --- a/pkg/analyzer/lib/src/dart/resolver/record_literal_resolver.dart +++ b/pkg/analyzer/lib/src/dart/resolver/record_literal_resolver.dart @@ -135,7 +135,7 @@ class RecordLiteralResolver { DartType _resolveField(ExpressionImpl field, DartType contextType) { var staticType = _resolver .analyzeExpression(field, SharedTypeSchemaView(contextType)) - .unwrapTypeView(); + .unwrapTypeView(); field = _resolver.popRewrite()!; // Implicit cast from `dynamic`. diff --git a/pkg/analyzer/lib/src/dart/resolver/shared_type_analyzer.dart b/pkg/analyzer/lib/src/dart/resolver/shared_type_analyzer.dart index a7b457a14898..e4151f27a2e7 100644 --- a/pkg/analyzer/lib/src/dart/resolver/shared_type_analyzer.dart +++ b/pkg/analyzer/lib/src/dart/resolver/shared_type_analyzer.dart @@ -7,7 +7,6 @@ import 'package:_fe_analyzer_shared/src/type_inference/type_analyzer.dart' as shared; import 'package:_fe_analyzer_shared/src/types/shared_type.dart'; import 'package:analyzer/dart/element/element2.dart'; -import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/element.dart'; @@ -21,14 +20,8 @@ typedef SharedPatternField /// analyzer's [ErrorReporter] class. class SharedTypeAnalyzerErrors implements - shared.TypeAnalyzerErrors< - AstNodeImpl, - StatementImpl, - ExpressionImpl, - PromotableElementImpl2, - SharedTypeView, - DartPatternImpl, - void> { + shared.TypeAnalyzerErrors { final ErrorReporter _errorReporter; SharedTypeAnalyzerErrors(this._errorReporter); @@ -40,8 +33,8 @@ class SharedTypeAnalyzerErrors void caseExpressionTypeMismatch( {required Expression scrutinee, required Expression caseExpression, - required SharedTypeView scrutineeType, - required SharedTypeView caseExpressionType, + required SharedTypeView scrutineeType, + required SharedTypeView caseExpressionType, required bool nullSafetyEnabled}) { _errorReporter.atNode( caseExpression, @@ -127,7 +120,7 @@ class SharedTypeAnalyzerErrors @override void matchedTypeIsStrictlyNonNullable({ required DartPattern pattern, - required SharedTypeView matchedType, + required SharedTypeView matchedType, }) { if (pattern is NullAssertPattern) { _errorReporter.atToken( @@ -147,8 +140,8 @@ class SharedTypeAnalyzerErrors @override void matchedTypeIsSubtypeOfRequired({ required covariant CastPatternImpl pattern, - required SharedTypeView matchedType, - required SharedTypeView requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { _errorReporter.atToken( pattern.asToken, @@ -168,7 +161,7 @@ class SharedTypeAnalyzerErrors void patternForInExpressionIsNotIterable({ required AstNode node, required Expression expression, - required SharedTypeView expressionType, + required SharedTypeView expressionType, }) { _errorReporter.atNode( expression, @@ -181,8 +174,8 @@ class SharedTypeAnalyzerErrors void patternTypeMismatchInIrrefutableContext({ required covariant DartPatternImpl pattern, required AstNode context, - required SharedTypeView matchedType, - required SharedTypeView requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { _errorReporter.atNode( pattern, @@ -203,8 +196,8 @@ class SharedTypeAnalyzerErrors @override void relationalPatternOperandTypeNotAssignable({ required covariant RelationalPatternImpl pattern, - required SharedTypeView operandType, - required SharedTypeView parameterType, + required SharedTypeView operandType, + required SharedTypeView parameterType, }) { _errorReporter.atNode( pattern.operand, @@ -216,7 +209,7 @@ class SharedTypeAnalyzerErrors @override void relationalPatternOperatorReturnTypeNotAssignableToBool({ required covariant RelationalPatternImpl pattern, - required SharedTypeView returnType, + required SharedTypeView returnType, }) { _errorReporter.atToken( pattern.operator, diff --git a/pkg/analyzer/lib/src/error/bool_expression_verifier.dart b/pkg/analyzer/lib/src/error/bool_expression_verifier.dart index dfa1410f82d7..7d26f0fc83e0 100644 --- a/pkg/analyzer/lib/src/error/bool_expression_verifier.dart +++ b/pkg/analyzer/lib/src/error/bool_expression_verifier.dart @@ -36,7 +36,7 @@ class BoolExpressionVerifier { /// /// See [CompileTimeErrorCode.NON_BOOL_CONDITION]. void checkForNonBoolCondition(Expression condition, - {required Map, NonPromotionReason> Function()? + {required Map Function()? whyNotPromoted}) { checkForNonBoolExpression( condition, @@ -50,7 +50,7 @@ class BoolExpressionVerifier { void checkForNonBoolExpression(Expression expression, {required ErrorCode errorCode, List arguments = const [], - required Map, NonPromotionReason> Function()? + required Map Function()? whyNotPromoted}) { var type = expression.typeOrThrow; if (!_checkForUseOfVoidResult(expression) && @@ -75,7 +75,7 @@ class BoolExpressionVerifier { /// Checks to ensure that the given [expression] is assignable to bool. void checkForNonBoolNegationExpression(Expression expression, - {required Map, NonPromotionReason> Function()? + {required Map Function()? whyNotPromoted}) { checkForNonBoolExpression( expression, diff --git a/pkg/analyzer/lib/src/generated/error_detection_helpers.dart b/pkg/analyzer/lib/src/generated/error_detection_helpers.dart index f256a59cf515..f120970e7b9e 100644 --- a/pkg/analyzer/lib/src/generated/error_detection_helpers.dart +++ b/pkg/analyzer/lib/src/generated/error_detection_helpers.dart @@ -43,8 +43,7 @@ mixin ErrorDetectionHelpers { DartType expectedStaticType, DartType actualStaticType, ErrorCode errorCode, - {Map, NonPromotionReason> Function()? - whyNotPromoted}) { + {Map Function()? whyNotPromoted}) { if (expectedStaticType is! VoidType && checkForUseOfVoidResult(expression)) { return; @@ -61,8 +60,7 @@ mixin ErrorDetectionHelpers { /// See [CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE]. void checkForArgumentTypeNotAssignableForArgument(Expression argument, {bool promoteParameterToNullable = false, - Map, NonPromotionReason> Function()? - whyNotPromoted}) { + Map Function()? whyNotPromoted}) { _checkForArgumentTypeNotAssignableForArgument( argument: argument is NamedExpression ? argument.expression : argument, parameter: argument.correspondingParameter, @@ -76,8 +74,7 @@ mixin ErrorDetectionHelpers { DartType actualStaticType, DartType expectedStaticType, ErrorCode errorCode, - {Map, NonPromotionReason> Function()? - whyNotPromoted}) { + {Map Function()? whyNotPromoted}) { if (expectedStaticType is! VoidType && checkForUseOfVoidResult(expression)) { return; @@ -172,7 +169,7 @@ mixin ErrorDetectionHelpers { void checkForFieldInitializerNotAssignable( ConstructorFieldInitializer initializer, FieldElement2 fieldElement, {required bool isConstConstructor, - required Map, NonPromotionReason> Function()? + required Map Function()? whyNotPromoted}) { // prepare field type DartType fieldType = fieldElement.type; @@ -262,8 +259,7 @@ mixin ErrorDetectionHelpers { Expression index, { required ExecutableElement2? readElement, required ExecutableElement2? writeElement, - required Map, NonPromotionReason> Function()? - whyNotPromoted, + required Map Function()? whyNotPromoted, }) { if (readElement is MethodElement2) { var parameters = readElement.formalParameters; @@ -303,7 +299,7 @@ mixin ErrorDetectionHelpers { /// analysis engine. List computeWhyNotPromotedMessages( SyntacticEntity errorEntity, - Map, NonPromotionReason>? whyNotPromoted); + Map? whyNotPromoted); /// If an assignment from [type] to [context] is a case of an implicit 'call' /// method, returns the element of the 'call' method. @@ -360,8 +356,7 @@ mixin ErrorDetectionHelpers { required Expression argument, required FormalParameterElement? parameter, required bool promoteParameterToNullable, - Map, NonPromotionReason> Function()? - whyNotPromoted, + Map Function()? whyNotPromoted, }) { var staticParameterType = parameter?.type; if (staticParameterType != null) { diff --git a/pkg/analyzer/lib/src/generated/error_verifier.dart b/pkg/analyzer/lib/src/generated/error_verifier.dart index 251cf10565c5..a6e3bf5e645e 100644 --- a/pkg/analyzer/lib/src/generated/error_verifier.dart +++ b/pkg/analyzer/lib/src/generated/error_verifier.dart @@ -342,7 +342,7 @@ class ErrorVerifier extends RecursiveAstVisitor @override List computeWhyNotPromotedMessages( SyntacticEntity errorEntity, - Map, NonPromotionReason>? whyNotPromoted) { + Map? whyNotPromoted) { return []; } diff --git a/pkg/analyzer/lib/src/generated/inference_log.dart b/pkg/analyzer/lib/src/generated/inference_log.dart index 9465f7e4a90f..5e1d4bd7e6c1 100644 --- a/pkg/analyzer/lib/src/generated/inference_log.dart +++ b/pkg/analyzer/lib/src/generated/inference_log.dart @@ -6,7 +6,6 @@ import 'package:_fe_analyzer_shared/src/type_inference/shared_inference_log.dart import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; -import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/generated/resolver.dart'; final bool _assertionsEnabled = () { @@ -73,9 +72,7 @@ enum ExpressionVisitCodePath { /// The [SharedInferenceLogWriter] interface, augmented with analyzer-specific /// functionality. abstract interface class InferenceLogWriter - implements - SharedInferenceLogWriter { + implements SharedInferenceLogWriter { /// Checks that [enterExpression] was properly called for [expression]. /// /// This is called from [ResolverVisitor.dispatchExpression], to verify that @@ -109,10 +106,8 @@ abstract interface class InferenceLogWriter /// The [SharedInferenceLogWriterImpl] implementation, augmented with /// analyzer-specific functionality. -final class _InferenceLogWriterImpl extends SharedInferenceLogWriterImpl< - DartType, - DartType, - TypeParameterElementImpl2> implements InferenceLogWriter { +final class _InferenceLogWriterImpl extends SharedInferenceLogWriterImpl + implements InferenceLogWriter { /// Whether type inference is currently inside the body of a top level /// function or method, or the initializer of a top level variable or field, /// or the initializers and body of a constructor. diff --git a/pkg/analyzer/lib/src/generated/resolver.dart b/pkg/analyzer/lib/src/generated/resolver.dart index 14a6e425748c..3164d0151d2a 100644 --- a/pkg/analyzer/lib/src/generated/resolver.dart +++ b/pkg/analyzer/lib/src/generated/resolver.dart @@ -100,14 +100,14 @@ import 'package:analyzer/src/utilities/extensions/object.dart'; bool Function(Source) inferenceLoggingPredicate = (_) => false; typedef SharedMatchContext = shared.MatchContext, PromotableElementImpl2>; + DartPatternImpl, SharedTypeView, PromotableElementImpl2>; typedef SharedPatternField = shared.RecordPatternField; /// A function which returns [NonPromotionReason]s that various types are not /// promoted. -typedef WhyNotPromotedGetter = Map, NonPromotionReason> +typedef WhyNotPromotedGetter = Map Function(); /// The context shared between different units of the same library. @@ -123,18 +123,16 @@ class ResolverVisitor extends ThrowingAstVisitor with ErrorDetectionHelpers, TypeAnalyzer< - DartType, AstNodeImpl, StatementImpl, ExpressionImpl, PromotableElementImpl2, DartPatternImpl, void, - TypeParameterElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>, // TODO(paulberry): not yet used. - NullShortingMixin> { + NullShortingMixin { /// Debug-only: if `true`, manipulations of [_rewriteStack] performed by /// [popRewrite], [pushRewrite], and [replaceExpression] will be printed. static const bool _debugRewriteStack = false; @@ -439,12 +437,8 @@ class ResolverVisitor extends ThrowingAstVisitor ExecutableElement? get enclosingFunction => _enclosingFunction; @override - FlowAnalysis< - AstNodeImpl, - StatementImpl, - ExpressionImpl, - PromotableElementImpl2, - SharedTypeView> get flow => flowAnalysis.flow!; + FlowAnalysis get flow => flowAnalysis.flow!; bool get isConstructorTearoffsEnabled => _featureSet.isEnabled(Feature.constructor_tearoffs); @@ -458,11 +452,7 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - shared.TypeAnalyzerOperations< - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, + shared.TypeAnalyzerOperations get operations => flowAnalysis.typeOperations; /// Gets the current depth of the [_rewriteStack]. This may be used in @@ -483,8 +473,8 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - SharedTypeView analyzeExpression( - ExpressionImpl node, SharedTypeSchemaView schema, + SharedTypeView analyzeExpression( + ExpressionImpl node, SharedTypeSchemaView schema, {bool continueNullShorting = false}) { inferenceLogWriter?.setExpressionVisitCodePath( node, ExpressionVisitCodePath.analyzeExpression); @@ -721,7 +711,7 @@ class ResolverVisitor extends ThrowingAstVisitor @override List computeWhyNotPromotedMessages( SyntacticEntity errorEntity, - Map, NonPromotionReason>? whyNotPromoted) { + Map? whyNotPromoted) { List messages = []; if (whyNotPromoted != null) { for (var entry in whyNotPromoted.entries) { @@ -771,9 +761,8 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - ExpressionTypeAnalysisResult dispatchExpression( - covariant ExpressionImpl expression, - SharedTypeSchemaView context) { + ExpressionTypeAnalysisResult dispatchExpression( + covariant ExpressionImpl expression, SharedTypeSchemaView context) { int? stackDepth; assert(() { stackDepth = rewriteStackDepth; @@ -783,11 +772,7 @@ class ResolverVisitor extends ThrowingAstVisitor // Stack: () pushRewrite(expression); // Stack: (Expression) - // TODO(paulberry): eliminate this cast by changing `ResolverVisitor` so - // that it supplies `TypeImpl` instead of `DartType` as a type parameter to - // `TypeAnalyzer`. - expression.resolveExpression( - this, context.unwrapTypeSchemaView() as TypeImpl); + expression.resolveExpression(this, context.unwrapTypeSchemaView()); inferenceLogWriter?.assertExpressionWasRecorded(expression); assert(rewriteStackDepth == stackDepth! + 1); var replacementExpression = peekRewrite()!; @@ -814,18 +799,14 @@ class ResolverVisitor extends ThrowingAstVisitor '(${replacementExpression.runtimeType}) $replacementExpression', ); } - // TODO(paulberry): remove this cast by changing the type of - // `operations.unknownType` to `SharedTypeSchemaView`. - staticType = operations.unknownType.unwrapTypeSchemaView() as TypeImpl; + staticType = operations.unknownType.unwrapTypeSchemaView(); } - return ExpressionTypeAnalysisResult( - type: SharedTypeView(staticType)); + return ExpressionTypeAnalysisResult(type: SharedTypeView(staticType)); } @override - PatternResult dispatchPattern( - SharedMatchContext context, AstNodeImpl node) { - shared.PatternResult analysisResult; + PatternResult dispatchPattern(SharedMatchContext context, AstNodeImpl node) { + shared.PatternResult analysisResult; if (node is DartPatternImpl) { analysisResult = node.resolvePattern(this, context); node.matchedValueType = analysisResult.matchedValueType.unwrapTypeView(); @@ -844,8 +825,7 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - SharedTypeSchemaView dispatchPatternSchema( - covariant DartPatternImpl node) { + SharedTypeSchemaView dispatchPatternSchema(covariant DartPatternImpl node) { return SharedTypeSchemaView(node.computePatternSchema(this)); } @@ -855,8 +835,8 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - SharedTypeView downwardInferObjectPatternRequiredType({ - required SharedTypeView matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required covariant ObjectPatternImpl pattern, }) { var typeNode = pattern.type; @@ -869,10 +849,7 @@ class ResolverVisitor extends ThrowingAstVisitor typeParameters: typeParameters, errorNode: typeNode, declaredType: typeNameElement.thisType, - // TODO(paulberry): eliminate this cast by changing - // `ResolverVisitor` so that it supplies `TypeImpl` instead of - // `DartType` as a type parameter to `TypeAnalyzer`. - contextType: matchedType.unwrapTypeView() as TypeImpl, + contextType: matchedType.unwrapTypeView(), nodeForTesting: pattern, ); return SharedTypeView(typeNode.type = typeNameElement.instantiate( @@ -887,10 +864,7 @@ class ResolverVisitor extends ThrowingAstVisitor typeParameters: typeParameters, errorNode: typeNode, declaredType: typeNameElement.aliasedType, - // TODO(paulberry): eliminate this cast by changing - // `ResolverVisitor` so that it supplies `TypeImpl` instead of - // `DartType` as a type parameter to `TypeAnalyzer`. - contextType: matchedType.unwrapTypeView() as TypeImpl, + contextType: matchedType.unwrapTypeView(), nodeForTesting: pattern, ); return SharedTypeView(typeNode.type = typeNameElement.instantiate( @@ -919,7 +893,7 @@ class ResolverVisitor extends ThrowingAstVisitor required JoinedPatternVariableLocation location, required shared.JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView type, + required SharedTypeView type, }) { variable.inconsistency = variable.inconsistency.maxWith(inconsistency); variable.isFinal = isFinal; @@ -1148,7 +1122,7 @@ class ResolverVisitor extends ThrowingAstVisitor void handleMapPatternEntry( DartPattern container, covariant MapPatternEntryImpl entry, - SharedTypeView keyType, + SharedTypeView keyType, ) { entry.key = popRewrite()!; } @@ -1197,7 +1171,7 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - void handleSwitchScrutinee(SharedTypeView type) { + void handleSwitchScrutinee(SharedTypeView type) { if (!options.patternsEnabled) { legacySwitchExhaustiveness = SwitchExhaustiveness(type.unwrapTypeView()); } @@ -1263,8 +1237,7 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - bool isLegacySwitchExhaustive( - AstNode node, SharedTypeView expressionType) => + bool isLegacySwitchExhaustive(AstNode node, SharedTypeView expressionType) => legacySwitchExhaustiveness!.isExhaustive; @override @@ -1412,7 +1385,7 @@ class ResolverVisitor extends ThrowingAstVisitor nullSafetyDeadCodeVerifier.maybeRewriteFirstDeadNode(oldNode, newNode); } - PatternResult resolveAssignedVariablePattern({ + PatternResult resolveAssignedVariablePattern({ required AssignedVariablePatternImpl node, required SharedMatchContext context, }) { @@ -1568,15 +1541,12 @@ class ResolverVisitor extends ThrowingAstVisitor } } - PatternResult resolveMapPattern({ + PatternResult resolveMapPattern({ required MapPatternImpl node, required SharedMatchContext context, }) { inferenceLogWriter?.enterPattern(node); - ({ - SharedTypeView keyType, - SharedTypeView valueType - })? typeArguments; + ({SharedTypeView keyType, SharedTypeView valueType})? typeArguments; var typeArgumentsList = node.typeArguments; if (typeArgumentsList != null) { typeArgumentsList.accept(this); @@ -1616,10 +1586,9 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - (ExecutableElement?, SharedTypeView) - resolveObjectPatternPropertyGet({ + (ExecutableElement?, SharedTypeView) resolveObjectPatternPropertyGet({ required covariant ObjectPatternImpl objectPattern, - required SharedTypeView receiverType, + required SharedTypeView receiverType, required covariant SharedPatternField field, }) { var fieldNode = field.node; @@ -1664,9 +1633,9 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - RelationalOperatorResolution? resolveRelationalPatternOperator( + RelationalOperatorResolution? resolveRelationalPatternOperator( covariant RelationalPatternImpl node, - SharedTypeView matchedType, + SharedTypeView matchedType, ) { var operatorLexeme = node.operator.lexeme; RelationalOperatorKind kind; @@ -1755,8 +1724,7 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - void setVariableType( - PromotableElement2 variable, SharedTypeView type) { + void setVariableType(PromotableElement2 variable, SharedTypeView type) { if (variable is LocalVariableElementImpl2) { variable.type = type.unwrapTypeView(); } else { @@ -1832,8 +1800,7 @@ class ResolverVisitor extends ThrowingAstVisitor } @override - SharedTypeView variableTypeFromInitializerType( - SharedTypeView type) { + SharedTypeView variableTypeFromInitializerType(SharedTypeView type) { DartType unwrapped = type.unwrapTypeView(); if (unwrapped.isDartCoreNull) { return SharedTypeView(DynamicTypeImpl.instance); @@ -1865,7 +1832,7 @@ class ResolverVisitor extends ThrowingAstVisitor } assert(flowAnalysis.flow != null); var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; _annotationResolver.resolve(node, whyNotPromotedArguments); var arguments = node.arguments; if (arguments != null) { @@ -2015,7 +1982,7 @@ class ResolverVisitor extends ThrowingAstVisitor inferenceLogWriter?.enterExpression(node, contextType); checkUnreachableNode(node); var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; var augmentation = enclosingAugmentation; var augmentationTarget = augmentation?.augmentationTarget; @@ -2604,7 +2571,7 @@ class ResolverVisitor extends ThrowingAstVisitor arguments.typeArguments?.accept(this); var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; checkForArgumentTypesNotAssignableInList( argumentList, whyNotPromotedArguments); } @@ -2704,7 +2671,7 @@ class ResolverVisitor extends ThrowingAstVisitor {TypeImpl contextType = UnknownInferredType.instance}) { inferenceLogWriter?.enterExtensionOverride(node, contextType); var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; node.typeArguments?.accept(this); var receiverContextType = @@ -2893,7 +2860,7 @@ class ResolverVisitor extends ThrowingAstVisitor node.function = popRewrite()!; var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; _functionExpressionInvocationResolver.resolve(node, whyNotPromotedArguments, contextType: contextType); nullShortingTermination(node); @@ -3257,7 +3224,7 @@ class ResolverVisitor extends ThrowingAstVisitor inferenceLogWriter?.enterExpression(node, contextType); checkUnreachableNode(node); var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; var target = node.target; if (target != null) { analyzeExpression(target, operations.unknownType); @@ -3570,7 +3537,7 @@ class ResolverVisitor extends ThrowingAstVisitor // invocation. // var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; elementResolver.visitRedirectingConstructorInvocation( node as RedirectingConstructorInvocationImpl); InvocationInferrer( @@ -3707,7 +3674,7 @@ class ResolverVisitor extends ThrowingAstVisitor // invocation. // var whyNotPromotedArguments = - , NonPromotionReason> Function()>[]; + Function()>[]; elementResolver.visitSuperConstructorInvocation( node as SuperConstructorInvocationImpl); InvocationInferrer( @@ -3748,7 +3715,7 @@ class ResolverVisitor extends ThrowingAstVisitor var staticType = analyzeSwitchExpression(node, node.expression, node.cases.length, SharedTypeSchemaView(contextType)) .type - .unwrapTypeView(); + .unwrapTypeView(); node.recordStaticType(staticType, resolver: this); popRewrite(); legacySwitchExhaustiveness = previousExhaustiveness; @@ -5620,7 +5587,7 @@ class SwitchExhaustiveness { class _WhyNotPromotedVisitor implements NonPromotionReasonVisitor, AstNode, - PromotableElement2, SharedTypeView> { + PromotableElement2, SharedTypeView> { final Source source; final SyntacticEntity _errorEntity; @@ -5649,7 +5616,7 @@ class _WhyNotPromotedVisitor @override List visitPropertyNotPromotedForInherentReason( - PropertyNotPromotedForInherentReason> reason) { + PropertyNotPromotedForInherentReason reason) { var receiverElement = reason.propertyMember; if (receiverElement is PropertyAccessorElement) { var property = propertyReference = receiverElement; @@ -5687,8 +5654,7 @@ class _WhyNotPromotedVisitor @override List visitPropertyNotPromotedForNonInherentReason( - PropertyNotPromotedForNonInherentReason> - reason) { + PropertyNotPromotedForNonInherentReason reason) { var receiverElement = reason.propertyMember; if (receiverElement is PropertyAccessorElement) { var property = propertyReference = receiverElement; diff --git a/pkg/analyzer/test/id_tests/type_constraint_generation_test.dart b/pkg/analyzer/test/id_tests/type_constraint_generation_test.dart index aff9cef1557c..7da51ffd9243 100644 --- a/pkg/analyzer/test/id_tests/type_constraint_generation_test.dart +++ b/pkg/analyzer/test/id_tests/type_constraint_generation_test.dart @@ -8,6 +8,7 @@ import 'package:_fe_analyzer_shared/src/testing/id.dart' show ActualData, Id; import 'package:_fe_analyzer_shared/src/testing/id_testing.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/src/dart/analysis/testing_data.dart'; +import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type_constraint_gatherer.dart'; import 'package:analyzer/src/util/ast_data_extractor.dart'; @@ -74,7 +75,11 @@ class _TypeConstraintGenerationDataInterpreter if (i > 0) { sb.write(','); } - var name = actualData[i].typeParameter.name3; + var name = actualData[i] + .typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + TypeParameterElementImpl2>() + .name3; if (actualData[i].isUpper) { sb.write("$name <: "); sb.write(actualData[i].constraint.getDisplayString()); diff --git a/pkg/front_end/lib/src/kernel/internal_ast.dart b/pkg/front_end/lib/src/kernel/internal_ast.dart index 356fa73ba6c6..6971d86ee5a0 100644 --- a/pkg/front_end/lib/src/kernel/internal_ast.dart +++ b/pkg/front_end/lib/src/kernel/internal_ast.dart @@ -35,7 +35,7 @@ import '../type_inference/inference_visitor.dart'; import '../type_inference/type_schema.dart' show UnknownType; typedef SharedMatchContext = shared.MatchContext, VariableDeclaration>; + SharedTypeView, VariableDeclaration>; int getExtensionTypeParameterCount(Arguments arguments) { if (arguments is ArgumentsImpl) { diff --git a/pkg/front_end/lib/src/type_inference/inference_visitor.dart b/pkg/front_end/lib/src/type_inference/inference_visitor.dart index dea75bbf7457..8dfb41ecbf17 100644 --- a/pkg/front_end/lib/src/type_inference/inference_visitor.dart +++ b/pkg/front_end/lib/src/type_inference/inference_visitor.dart @@ -104,24 +104,15 @@ abstract class InferenceVisitor { class InferenceVisitorImpl extends InferenceVisitorBase with - TypeAnalyzer< - DartType, - TreeNode, - Statement, - Expression, - VariableDeclaration, - Pattern, - InvalidExpression, - StructuralParameter, - TypeDeclarationType, - TypeDeclaration>, - NullShortingMixin>, + TypeAnalyzer, + NullShortingMixin, StackChecker implements ExpressionVisitor1, StatementVisitor, InitializerVisitor, - PatternVisitor1, SharedMatchContext>, + PatternVisitor1, InferenceVisitor { /// Debug-only: if `true`, manipulations of [_rewriteStack] performed by /// [popRewrite] and [pushRewrite] will be printed. @@ -272,7 +263,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase @override void handleNullShortingStep( - NullAwareGuard guard, SharedTypeView inferredType) { + NullAwareGuard guard, SharedTypeView inferredType) { pushRewrite(guard.createExpression( inferredType.unwrapTypeView(), popRewrite() as Expression)); } @@ -1028,8 +1019,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase if (nullAwareGuard != null) { pushRewrite(replacement); - SharedTypeView inferredType = - new SharedTypeView(result.inferredType); + SharedTypeView inferredType = new SharedTypeView(result.inferredType); // End non-nullable promotion of the null-aware variable. flow.nullAwareAccess_end(); handleNullShortingStep(nullAwareGuard, inferredType); @@ -1777,13 +1767,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternForInResult result = - analyzePatternForIn( - node: node, - hasAwait: isAsync, - pattern: patternVariableDeclaration.pattern, - expression: iterable, - dispatchBody: () {}); + PatternForInResult result = analyzePatternForIn( + node: node, + hasAwait: isAsync, + pattern: patternVariableDeclaration.pattern, + expression: iterable, + dispatchBody: () {}); patternVariableDeclaration.matchedValueType = result.elementType.unwrapTypeView(); if (result.patternForInExpressionIsNotIterableError != null) { @@ -2155,7 +2144,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - IfCaseStatementResult analysisResult = + IfCaseStatementResult analysisResult = analyzeIfCaseStatement(node, node.expression, node.patternGuard.pattern, node.patternGuard.guard, node.then, node.otherwise, { for (VariableDeclaration variable @@ -2494,7 +2483,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase inferredTypeArgument: inferredTypeArgument, inferredSpreadTypes: inferredSpreadTypes, inferredConditionTypes: inferredConditionTypes); - IfCaseStatementResult analysisResult = + IfCaseStatementResult analysisResult = analyzeIfCaseElement( node: element, expression: element.expression, @@ -2583,7 +2572,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase PatternVariableDeclaration patternVariableDeclaration = element.patternVariableDeclaration; - PatternVariableDeclarationAnalysisResult analysisResult = + PatternVariableDeclarationAnalysisResult analysisResult = analyzePatternVariableDeclaration( patternVariableDeclaration, patternVariableDeclaration.pattern, @@ -4773,7 +4762,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase offsets: offsets, inferredSpreadTypes: inferredSpreadTypes, inferredConditionTypes: inferredConditionTypes); - IfCaseStatementResult analysisResult = + IfCaseStatementResult analysisResult = analyzeIfCaseElement( node: entry, expression: entry.expression, @@ -4876,7 +4865,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase PatternVariableDeclaration patternVariableDeclaration = entry.patternVariableDeclaration; - PatternVariableDeclarationAnalysisResult analysisResult = + PatternVariableDeclarationAnalysisResult analysisResult = analyzePatternVariableDeclaration( patternVariableDeclaration, patternVariableDeclaration.pattern, @@ -6289,8 +6278,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase VariableDeclaration? indexVariable; Expression readIndex = indexResult.expression; - Map, NonPromotionReason> Function() - whyNotPromotedIndex = flowAnalysis.whyNotPromoted(readIndex); + Map Function() whyNotPromotedIndex = + flowAnalysis.whyNotPromoted(readIndex); Expression writeIndex; if (isPureExpression(readIndex)) { writeIndex = clonePureExpression(readIndex); @@ -6763,7 +6752,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase ExpressionInferenceResult _computeEqualsExpression( int fileOffset, Expression left, DartType leftType, Expression right, {required bool isNot}) { - ExpressionInfo>? equalityInfo = + ExpressionInfo? equalityInfo = flowAnalysis.equalityOperand_end(left); Expression? equals; @@ -6856,8 +6845,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase DartType leftType, Name binaryName, Expression right, - Map, NonPromotionReason> Function()? - whyNotPromoted) { + Map Function()? whyNotPromoted) { assert(binaryName != equalsName); ObjectAccessTarget binaryTarget = findInterfaceMember( @@ -7029,8 +7017,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase Expression expression, DartType expressionType, Name unaryName, - Map, NonPromotionReason> Function() - whyNotPromoted) { + Map Function() whyNotPromoted) { ObjectAccessTarget unaryTarget = findInterfaceMember( expressionType, unaryName, fileOffset, includeExtensionMethods: true, isSetter: false); @@ -7420,8 +7407,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase {required bool isThisReceiver, ObjectAccessTarget? readTarget, Expression? propertyGetNode}) { - Map, NonPromotionReason> Function() - whyNotPromoted = flowAnalysis.whyNotPromoted(receiver); + Map Function() whyNotPromoted = + flowAnalysis.whyNotPromoted(receiver); readTarget ??= findInterfaceMember(receiverType, propertyName, fileOffset, includeExtensionMethods: true, isSetter: false); @@ -7618,8 +7605,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase VariableDeclaration? indexVariable; Expression readIndex = indexResult.expression; - Map, NonPromotionReason> Function() - whyNotPromotedIndex = flowAnalysis.whyNotPromoted(readIndex); + Map Function() whyNotPromotedIndex = + flowAnalysis.whyNotPromoted(readIndex); Expression writeIndex; if (isPureExpression(readIndex)) { writeIndex = clonePureExpression(readIndex); @@ -8975,7 +8962,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - SwitchExpressionResult analysisResult = + SwitchExpressionResult analysisResult = analyzeSwitchExpression(node, node.expression, node.cases.length, new SharedTypeSchemaView(typeContext)); DartType valueType = analysisResult.type.unwrapTypeView(); @@ -9029,8 +9016,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase Set? previousEnumFields = _enumFields; Expression expression = node.expression; - SwitchStatementTypeAnalysisResult - analysisResult = + SwitchStatementTypeAnalysisResult analysisResult = analyzeSwitchStatement(node, expression, node.cases.length); node.expressionType = analysisResult.scrutineeType.unwrapTypeView(); @@ -9119,8 +9105,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - SwitchStatementTypeAnalysisResult - analysisResult = + SwitchStatementTypeAnalysisResult analysisResult = analyzeSwitchStatement(node, node.expression, node.cases.length); node.lastCaseTerminates = analysisResult.lastCaseTerminates; @@ -9607,7 +9592,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternVariableDeclarationAnalysisResult analysisResult = + PatternVariableDeclarationAnalysisResult analysisResult = analyzePatternVariableDeclaration(node, node.pattern, node.initializer, isFinal: node.isFinal); node.matchedValueType = analysisResult.initializerType.unwrapTypeView(); @@ -9831,8 +9816,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase BinaryExpression node, DartType typeContext) { ExpressionInferenceResult leftResult = inferExpression(node.left, const UnknownType()); - Map, NonPromotionReason> Function() - whyNotPromoted = flowAnalysis.whyNotPromoted(leftResult.expression); + Map Function() whyNotPromoted = + flowAnalysis.whyNotPromoted(leftResult.expression); return _computeBinaryExpression( node.fileOffset, typeContext, @@ -9913,8 +9898,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase if (expressionResult == null) { expressionResult = inferExpression(node.expression, const UnknownType()); } - Map, NonPromotionReason> Function() - whyNotPromoted = + Map Function() whyNotPromoted = flowAnalysis.whyNotPromoted(expressionResult.expression); return _computeUnaryExpression(node.fileOffset, expressionResult.expression, expressionResult.inferredType, node.unaryName, whyNotPromoted); @@ -10169,8 +10153,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - ExpressionTypeAnalysisResult dispatchExpression( - Expression node, SharedTypeSchemaView context) { + ExpressionTypeAnalysisResult dispatchExpression( + Expression node, SharedTypeSchemaView context) { // Normally the CFE performs expression coercion in the process of type // inference of the nodes where an assignment is executed. The inference on // the pattern-related nodes is driven by the shared analysis, and some of @@ -10226,8 +10210,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult dispatchPattern( - SharedMatchContext context, TreeNode node) { + PatternResult dispatchPattern(SharedMatchContext context, TreeNode node) { if (node is Pattern) { return node.accept1(this, context); } else { @@ -10236,7 +10219,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - SharedTypeSchemaView dispatchPatternSchema(Node node) { + SharedTypeSchemaView dispatchPatternSchema(Node node) { if (node is AndPattern) { return analyzeLogicalAndPatternSchema(node.left, node.right); } else if (node is AssignedVariablePattern) { @@ -10410,7 +10393,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase @override FlowAnalysis> get flow => flowAnalysis; + SharedTypeView> get flow => flowAnalysis; @override SwitchExpressionMemberInfo @@ -10626,7 +10609,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase }) {} @override - void handleSwitchScrutinee(SharedTypeView type) { + void handleSwitchScrutinee(SharedTypeView type) { DartType unwrapped = type.unwrapTypeView(); if ((!options.patternsEnabled) && unwrapped is InterfaceType && @@ -10634,7 +10617,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase _enumFields = { ...unwrapped.classNode.fields .where((Field field) => field.isEnumElement), - if (type.unwrapTypeView().isPotentiallyNullable) null + if (type.unwrapTypeView().isPotentiallyNullable) null }; } else { _enumFields = null; @@ -10644,8 +10627,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - bool isLegacySwitchExhaustive( - TreeNode node, SharedTypeView expressionType) { + bool isLegacySwitchExhaustive(TreeNode node, SharedTypeView expressionType) { Set? enumFields = _enumFields; return enumFields != null && enumFields.isEmpty; } @@ -10656,14 +10638,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - void setVariableType( - VariableDeclaration variable, SharedTypeView type) { + void setVariableType(VariableDeclaration variable, SharedTypeView type) { variable.type = type.unwrapTypeView(); } @override - SharedTypeView variableTypeFromInitializerType( - SharedTypeView type) { + SharedTypeView variableTypeFromInitializerType(SharedTypeView type) { // TODO(paulberry): make a test verifying that we don't need to pass // `forSyntheticVariable: true` (and possibly a language issue) return new SharedTypeView(inferDeclarationType(type.unwrapTypeView())); @@ -10675,12 +10655,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitVariablePattern( + PatternResult visitVariablePattern( VariablePattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - DeclaredVariablePatternResult analysisResult = + DeclaredVariablePatternResult analysisResult = analyzeDeclaredVariablePattern(context, node, node.variable, node.variable.name!, node.type?.wrapSharedTypeView()); @@ -10713,12 +10693,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitWildcardPattern( + PatternResult visitWildcardPattern( WildcardPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - WildcardPatternResult analysisResult = + WildcardPatternResult analysisResult = analyzeWildcardPattern( context: context, node: node, @@ -10744,12 +10724,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitConstantPattern( + PatternResult visitConstantPattern( ConstantPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - ConstantPatternResult analysisResult = + ConstantPatternResult analysisResult = analyzeConstantPattern(context, node, node.expression); Pattern? replacement; @@ -10794,12 +10774,11 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitAndPattern( - AndPattern node, SharedMatchContext context) { + PatternResult visitAndPattern(AndPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternResult analysisResult = + PatternResult analysisResult = analyzeLogicalAndPattern(context, node, node.left, node.right); assert(checkStack(node, stackBase, [ @@ -10828,12 +10807,11 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitOrPattern( - OrPattern node, SharedMatchContext context) { + PatternResult visitOrPattern(OrPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - LogicalOrPatternResult analysisResult = + LogicalOrPatternResult analysisResult = analyzeLogicalOrPattern(context, node, node.left, node.right); assert(checkStack(node, stackBase, [ @@ -10902,12 +10880,11 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitCastPattern( - CastPattern node, SharedMatchContext context) { + PatternResult visitCastPattern(CastPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternResult analysisResult = analyzeCastPattern( + PatternResult analysisResult = analyzeCastPattern( context: context, pattern: node, innerPattern: node.pattern, @@ -10933,12 +10910,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitNullAssertPattern( + PatternResult visitNullAssertPattern( NullAssertPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - NullCheckOrAssertPatternResult analysisResult = + NullCheckOrAssertPatternResult analysisResult = analyzeNullCheckOrAssertPattern(context, node, node.pattern, isAssert: true); @@ -10972,12 +10949,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitNullCheckPattern( + PatternResult visitNullCheckPattern( NullCheckPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - NullCheckOrAssertPatternResult analysisResult = + NullCheckOrAssertPatternResult analysisResult = analyzeNullCheckOrAssertPattern(context, node, node.pattern, isAssert: false); @@ -11000,15 +10977,14 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitListPattern( - ListPattern node, SharedMatchContext context) { + PatternResult visitListPattern(ListPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - ListPatternResult analysisResult = - analyzeListPattern(context, node, - elements: node.patterns, - elementType: node.typeArgument?.wrapSharedTypeView()); + ListPatternResult analysisResult = analyzeListPattern( + context, node, + elements: node.patterns, + elementType: node.typeArgument?.wrapSharedTypeView()); DartType matchedValueType = node.matchedValueType = analysisResult.matchedValueType.unwrapTypeView(); @@ -11166,12 +11142,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitObjectPattern( + PatternResult visitObjectPattern( ObjectPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - ObjectPatternResult analysisResult = + ObjectPatternResult analysisResult = analyzeObjectPattern(context, node, fields: >[ for (NamedPattern field in node.fields) @@ -11332,14 +11308,13 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitRestPattern( - RestPattern node, SharedMatchContext context) { + PatternResult visitRestPattern(RestPattern node, SharedMatchContext context) { // A rest pattern isn't a real pattern; this code should never be reached. throw new StateError('visitRestPattern should never be reached'); } @override - PatternResult visitInvalidPattern( + PatternResult visitInvalidPattern( InvalidPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); @@ -11355,12 +11330,12 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitRelationalPattern( + PatternResult visitRelationalPattern( RelationalPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - RelationalPatternResult analysisResult = + RelationalPatternResult analysisResult = analyzeRelationalPattern(context, node, node.expression); DartType matchedValueType = node.matchedValueType = @@ -11490,23 +11465,22 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitMapPattern( - MapPattern node, SharedMatchContext context) { + PatternResult visitMapPattern(MapPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); ({ - SharedTypeView keyType, - SharedTypeView valueType + SharedTypeView keyType, + SharedTypeView valueType })? typeArguments = node.keyType == null && node.valueType == null ? null : ( keyType: new SharedTypeView(node.keyType ?? const DynamicType()), valueType: new SharedTypeView(node.valueType ?? const DynamicType()) ); - MapPatternResult analysisResult = - analyzeMapPattern(context, node, - typeArguments: typeArguments, elements: node.entries); + MapPatternResult analysisResult = analyzeMapPattern( + context, node, + typeArguments: typeArguments, elements: node.entries); DartType matchedValueType = node.matchedValueType = analysisResult.matchedValueType.unwrapTypeView(); @@ -11610,14 +11584,14 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitNamedPattern( + PatternResult visitNamedPattern( NamedPattern node, SharedMatchContext context) { // NamedPattern isn't a real pattern; this code should never be reached. throw new StateError('visitNamedPattern should never be reached'); } @override - PatternResult visitRecordPattern( + PatternResult visitRecordPattern( RecordPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); @@ -11631,7 +11605,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase : fieldPattern, name: fieldPattern is NamedPattern ? fieldPattern.name : null) ]; - RecordPatternResult analysisResult = + RecordPatternResult analysisResult = analyzeRecordPattern(context, node, fields: fields); DartType matchedValueType = node.matchedValueType = @@ -11701,7 +11675,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternAssignmentAnalysisResult analysisResult = + PatternAssignmentAnalysisResult analysisResult = analyzePatternAssignment(node, node.pattern, node.expression); node.matchedValueType = analysisResult.type.unwrapTypeView(); @@ -11731,7 +11705,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - PatternResult visitAssignedVariablePattern( + PatternResult visitAssignedVariablePattern( AssignedVariablePattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); @@ -11775,7 +11749,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase ..fileOffset = node.fileOffset; } - AssignedVariablePatternResult analysisResult = + AssignedVariablePatternResult analysisResult = analyzeAssignedVariablePattern(context, node, node.variable); DartType matchedValueType = node.matchedValueType = @@ -11832,8 +11806,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - SharedTypeView downwardInferObjectPatternRequiredType({ - required SharedTypeView matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required covariant ObjectPatternInternal pattern, }) { DartType requiredType = pattern.requiredType; @@ -11947,9 +11921,9 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - (Member?, SharedTypeView) resolveObjectPatternPropertyGet({ + (Member?, SharedTypeView) resolveObjectPatternPropertyGet({ required Pattern objectPattern, - required SharedTypeView receiverType, + required SharedTypeView receiverType, required shared.RecordPatternField field, }) { String fieldName = field.name!; @@ -11978,7 +11952,7 @@ class InferenceVisitorImpl extends InferenceVisitorBase required JoinedPatternVariableLocation location, required JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView type, + required SharedTypeView type, }) { variable ..isFinal = isFinal @@ -12044,10 +12018,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - void handleMapPatternEntry( - Pattern container, - covariant MapPatternEntry entryElement, - SharedTypeView keyType) { + void handleMapPatternEntry(Pattern container, + covariant MapPatternEntry entryElement, SharedTypeView keyType) { Object? rewrite = popRewrite(); if (!identical(rewrite, entryElement.value)) { // Coverage-ignore-block(suite): Not run. @@ -12066,9 +12038,8 @@ class InferenceVisitorImpl extends InferenceVisitorBase } @override - RelationalOperatorResolution? resolveRelationalPatternOperator( - covariant RelationalPattern node, - SharedTypeView matchedValueType) { + RelationalOperatorResolution? resolveRelationalPatternOperator( + covariant RelationalPattern node, SharedTypeView matchedValueType) { // TODO(johnniwinther): Reuse computed values between here and // visitRelationalPattern. Name operatorName; diff --git a/pkg/front_end/lib/src/type_inference/inference_visitor_base.dart b/pkg/front_end/lib/src/type_inference/inference_visitor_base.dart index 6c87506cd357..5687abfa26da 100644 --- a/pkg/front_end/lib/src/type_inference/inference_visitor_base.dart +++ b/pkg/front_end/lib/src/type_inference/inference_visitor_base.dart @@ -154,7 +154,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { InferenceDataForTesting? get dataForTesting => _inferrer.dataForTesting; FlowAnalysis> get flowAnalysis => _inferrer.flowAnalysis; + SharedTypeView> get flowAnalysis => _inferrer.flowAnalysis; /// Provides access to the [OperationsCfe] object. This is needed by /// [isAssignable] and for caching types. @@ -213,7 +213,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { /// promoted, to be used when reporting an error for a larger expression /// containing [receiver]. [node] is the containing tree node. List? getWhyNotPromotedContext( - Map, NonPromotionReason>? whyNotPromoted, + Map? whyNotPromoted, TreeNode node, bool Function(DartType) typeFilter) { List? context; @@ -221,7 +221,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { // Coverage-ignore-block(suite): Not run. _WhyNotPromotedVisitor whyNotPromotedVisitor = new _WhyNotPromotedVisitor(this); - for (MapEntry, NonPromotionReason> entry + for (MapEntry entry in whyNotPromoted.entries) { if (!typeFilter(entry.key.unwrapTypeView())) continue; List messages = @@ -381,8 +381,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { nullabilityNullTypeErrorTemplate, Template? nullabilityPartErrorTemplate, - Map, NonPromotionReason> Function()? - whyNotPromoted}) { + Map Function()? whyNotPromoted}) { return ensureAssignableResult(expectedType, new ExpressionInferenceResult(expressionType, expression), fileOffset: fileOffset, @@ -496,8 +495,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { nullabilityNullTypeErrorTemplate, Template? nullabilityPartErrorTemplate, - Map, NonPromotionReason> Function()? - whyNotPromoted}) { + Map Function()? whyNotPromoted}) { // [errorTemplate], [nullabilityErrorTemplate], and // [nullabilityPartErrorTemplate] should be provided together. assert((errorTemplate == null) == (nullabilityErrorTemplate == null) && @@ -657,8 +655,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { nullabilityNullTypeErrorTemplate, Template? nullabilityPartErrorTemplate, - Map, NonPromotionReason> Function()? - whyNotPromoted}) { + Map Function()? whyNotPromoted}) { if (coerceExpression) { ExpressionInferenceResult? coercionResult = coerceExpressionForAssignment( contextType, inferenceResult, @@ -1705,7 +1702,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { return visitor.inferExpression(argumentExpression, inferredFormalType); } - List>?>? identicalInfo = + List?>? identicalInfo = isIdentical && arguments.positional.length == 2 ? [] : null; int positionalIndex = 0; int namedIndex = 0; @@ -2996,8 +2993,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { receiver = _hoist(receiver, receiverType, hoistedExpressions); } - Map, NonPromotionReason> Function()? - whyNotPromoted; + Map Function()? whyNotPromoted; if (target.isNullable) { // We won't report the error until later (after we have an // invocationResult), but we need to gather "why not promoted" info now, @@ -3970,8 +3966,7 @@ abstract class InferenceVisitorBase implements InferenceVisitor { DartType? readType, required DartType? promotedReadType, required bool isThisReceiver, - Map, NonPromotionReason> Function()? - whyNotPromoted}) { + Map Function()? whyNotPromoted}) { Expression read; ExpressionInferenceResult? readResult; @@ -4376,7 +4371,7 @@ FunctionType replaceReturnType(FunctionType functionType, DartType returnType) { class _WhyNotPromotedVisitor implements NonPromotionReasonVisitor, Node, - VariableDeclaration, SharedTypeView> { + VariableDeclaration, SharedTypeView> { final InferenceVisitorBase inferrer; Member? propertyReference; @@ -4403,8 +4398,7 @@ class _WhyNotPromotedVisitor @override List visitPropertyNotPromotedForNonInherentReason( - PropertyNotPromotedForNonInherentReason> - reason) { + PropertyNotPromotedForNonInherentReason reason) { FieldNonPromotabilityInfo? fieldNonPromotabilityInfo = this.inferrer.libraryBuilder.fieldNonPromotabilityInfo; if (fieldNonPromotabilityInfo == null) { @@ -4460,7 +4454,7 @@ class _WhyNotPromotedVisitor @override List visitPropertyNotPromotedForInherentReason( - PropertyNotPromotedForInherentReason> reason) { + PropertyNotPromotedForInherentReason reason) { Object? member = reason.propertyMember; if (member is Member) { if (member case Procedure(:var stubTarget?)) { @@ -4507,7 +4501,7 @@ class _WhyNotPromotedVisitor } void _addFieldPromotionUnavailableMessage( - PropertyNotPromoted> reason, + PropertyNotPromoted reason, List messages) { Object? member = reason.propertyMember; if (member is Member) { diff --git a/pkg/front_end/lib/src/type_inference/shared_type_analyzer.dart b/pkg/front_end/lib/src/type_inference/shared_type_analyzer.dart index f860ff15f77a..60440a5c5887 100644 --- a/pkg/front_end/lib/src/type_inference/shared_type_analyzer.dart +++ b/pkg/front_end/lib/src/type_inference/shared_type_analyzer.dart @@ -18,7 +18,7 @@ import 'inference_visitor.dart'; class SharedTypeAnalyzerErrors implements TypeAnalyzerErrors, Pattern, InvalidExpression> { + SharedTypeView, Pattern, InvalidExpression> { final InferenceVisitorImpl visitor; final InferenceHelper helper; @@ -41,8 +41,8 @@ class SharedTypeAnalyzerErrors InvalidExpression caseExpressionTypeMismatch( {required Expression scrutinee, required Expression caseExpression, - required SharedTypeView caseExpressionType, - required SharedTypeView scrutineeType, + required SharedTypeView caseExpressionType, + required SharedTypeView scrutineeType, required bool nullSafetyEnabled}) { return helper.buildProblem( nullSafetyEnabled @@ -133,7 +133,7 @@ class SharedTypeAnalyzerErrors @override InvalidExpression? matchedTypeIsStrictlyNonNullable({ required Pattern pattern, - required SharedTypeView matchedType, + required SharedTypeView matchedType, }) { // These are only warnings, so we don't report anything. return null; @@ -142,8 +142,8 @@ class SharedTypeAnalyzerErrors @override void matchedTypeIsSubtypeOfRequired({ required Pattern pattern, - required SharedTypeView matchedType, - required SharedTypeView requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { // TODO(scheglov) implement } @@ -158,7 +158,7 @@ class SharedTypeAnalyzerErrors InvalidExpression patternForInExpressionIsNotIterable({ required TreeNode node, required Expression expression, - required SharedTypeView expressionType, + required SharedTypeView expressionType, }) { return helper.buildProblem( templateForInLoopTypeNotIterable.withArguments( @@ -172,8 +172,8 @@ class SharedTypeAnalyzerErrors InvalidExpression patternTypeMismatchInIrrefutableContext( {required Pattern pattern, required TreeNode context, - required SharedTypeView matchedType, - required SharedTypeView requiredType}) { + required SharedTypeView matchedType, + required SharedTypeView requiredType}) { return helper.buildProblem( templatePatternTypeMismatchInIrrefutableContext.withArguments( matchedType.unwrapTypeView(), requiredType.unwrapTypeView()), @@ -191,8 +191,8 @@ class SharedTypeAnalyzerErrors @override InvalidExpression relationalPatternOperandTypeNotAssignable({ required covariant RelationalPattern pattern, - required SharedTypeView operandType, - required SharedTypeView parameterType, + required SharedTypeView operandType, + required SharedTypeView parameterType, }) { return helper.buildProblem( templateArgumentTypeNotAssignable.withArguments( @@ -204,7 +204,7 @@ class SharedTypeAnalyzerErrors @override InvalidExpression relationalPatternOperatorReturnTypeNotAssignableToBool({ required Pattern pattern, - required SharedTypeView returnType, + required SharedTypeView returnType, }) { return helper.buildProblem( templateInvalidAssignmentError.withArguments( diff --git a/pkg/front_end/lib/src/type_inference/type_constraint_gatherer.dart b/pkg/front_end/lib/src/type_inference/type_constraint_gatherer.dart index a809b1c10765..0c341edacfad 100644 --- a/pkg/front_end/lib/src/type_inference/type_constraint_gatherer.dart +++ b/pkg/front_end/lib/src/type_inference/type_constraint_gatherer.dart @@ -19,22 +19,10 @@ import 'type_schema_environment.dart'; /// Creates a collection of [TypeConstraint]s corresponding to type parameters, /// based on an attempt to make one type schema a subtype of another. class TypeConstraintGatherer extends shared.TypeConstraintGenerator< - DartType, - NamedType, - VariableDeclaration, - StructuralParameter, - TypeDeclarationType, - TypeDeclaration, - TreeNode> + VariableDeclaration, TypeDeclarationType, TypeDeclaration, TreeNode> with - shared.TypeConstraintGeneratorMixin< - DartType, - NamedType, - VariableDeclaration, - StructuralParameter, - TypeDeclarationType, - TypeDeclaration, - TreeNode> { + shared.TypeConstraintGeneratorMixin { final List _protoConstraints = []; @override @@ -130,7 +118,9 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< for (GeneratedTypeConstraint constraint in constraints) { if (constraint.isUpper) { addUpperConstraintForParameter( - constraint.typeParameter, + constraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + StructuralParameter>(), typeOperations.leastClosureOfTypeInternal( constraint.constraint.unwrapTypeSchemaView(), typeParametersToEliminate, @@ -139,7 +129,9 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< ); } else { addLowerConstraintForParameter( - constraint.typeParameter, + constraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + StructuralParameter>(), typeOperations.greatestClosureOfTypeInternal( constraint.constraint.unwrapTypeSchemaView(), typeParametersToEliminate, @@ -197,7 +189,10 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< ); } for (GeneratedTypeConstraint protoConstraint in _protoConstraints) { - result[protoConstraint.typeParameter]!.mergeIn( + result[protoConstraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + StructuralParameter>()]! + .mergeIn( protoConstraint, typeOperations, ); @@ -247,7 +242,7 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< }) { GeneratedTypeConstraint generatedTypeConstraint = new GeneratedTypeConstraint.lower( - parameter, + new SharedTypeParameterView(parameter), new SharedTypeSchemaView(lower), ); if (astNodeForTesting != null && _inferenceResultForTesting != null) { @@ -267,7 +262,7 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< }) { GeneratedTypeConstraint generatedTypeConstraint = new GeneratedTypeConstraint.upper( - parameter, + new SharedTypeParameterView(parameter), new SharedTypeSchemaView(upper), ); if (astNodeForTesting != null && _inferenceResultForTesting != null) { @@ -286,8 +281,7 @@ class TypeConstraintGatherer extends shared.TypeConstraintGenerator< required bool leftSchema, required TreeNode? astNodeForTesting, }) { - if (p is SharedInvalidTypeStructure || - q is SharedInvalidTypeStructure) { + if (p is SharedInvalidType || q is SharedInvalidType) { return false; } diff --git a/pkg/front_end/lib/src/type_inference/type_inference_engine.dart b/pkg/front_end/lib/src/type_inference/type_inference_engine.dart index 872f68d83778..b5daf3cd0350 100644 --- a/pkg/front_end/lib/src/type_inference/type_inference_engine.dart +++ b/pkg/front_end/lib/src/type_inference/type_inference_engine.dart @@ -395,9 +395,8 @@ class TypeInferenceEngineImpl extends TypeInferenceEngine { } // TODO(cstefantsova): Merge with [TypeInferenceResultForTesting]. -class InferenceDataForTesting - extends shared.TypeConstraintGenerationDataForTesting { +class InferenceDataForTesting extends shared + .TypeConstraintGenerationDataForTesting { final FlowAnalysisResult flowAnalysisResult = new FlowAnalysisResult(); final TypeInferenceResultForTesting typeInferenceResult = @@ -437,11 +436,11 @@ class FlowAnalysisResult { /// CFE-specific implementation of [FlowAnalysisOperations]. class OperationsCfe with - TypeAnalyzerOperationsMixin + TypeAnalyzerOperationsMixin implements - TypeAnalyzerOperations { + TypeAnalyzerOperations { final TypeEnvironment typeEnvironment; /// Information about which fields are promotable in this library. @@ -466,59 +465,59 @@ class OperationsCfe required this.typeCacheLegacy}); @override - SharedTypeView get boolType { + SharedTypeView get boolType { return new SharedTypeView( typeEnvironment.coreTypes.boolRawType(Nullability.nonNullable)); } @override - SharedTypeView get doubleType { + SharedTypeView get doubleType { throw new UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView get dynamicType { + SharedTypeView get dynamicType { return new SharedTypeView(const DynamicType()); } @override - SharedTypeView get errorType { + SharedTypeView get errorType { return new SharedTypeView(const InvalidType()); } @override - SharedTypeView get intType { + SharedTypeView get intType { throw new UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView get neverType { + SharedTypeView get neverType { return new SharedTypeView(const NeverType.nonNullable()); } @override - SharedTypeView get nullType { + SharedTypeView get nullType { return new SharedTypeView(const NullType()); } @override - SharedTypeView get objectQuestionType { + SharedTypeView get objectQuestionType { return new SharedTypeView(typeEnvironment.coreTypes.objectNullableRawType); } @override - SharedTypeView get objectType { + SharedTypeView get objectType { return new SharedTypeView( typeEnvironment.coreTypes.objectNonNullableRawType); } @override - SharedTypeSchemaView get unknownType { + SharedTypeSchemaView get unknownType { return new SharedTypeSchemaView(const UnknownType()); } @override - TypeClassification classifyType(SharedTypeView? type) { + TypeClassification classifyType(SharedTypeView? type) { DartType? unwrapped = type?.unwrapTypeView(); if (unwrapped == null) { // Note: this can happen during top-level inference. @@ -534,22 +533,20 @@ class OperationsCfe } @override - SharedTypeView factor( - SharedTypeView from, SharedTypeView what) { + SharedTypeView factor(SharedTypeView from, SharedTypeView what) { return new SharedTypeView(factorType( typeEnvironment, from.unwrapTypeView(), what.unwrapTypeView())); } @override - SharedTypeView greatestClosure( - SharedTypeSchemaView schema) { + SharedTypeView greatestClosure(SharedTypeSchemaView schema) { return new SharedTypeView(type_schema_elimination.greatestClosure( schema.unwrapTypeSchemaView(), topType: const DynamicType())); } @override - bool isAlwaysExhaustiveType(SharedTypeView type) { + bool isAlwaysExhaustiveType(SharedTypeView type) { return computeIsAlwaysExhaustiveType( type.unwrapTypeView(), typeEnvironment.coreTypes); } @@ -570,13 +567,13 @@ class OperationsCfe } @override - bool isNever(SharedTypeView type) { + bool isNever(SharedTypeView type) { return typeEnvironment.coreTypes.isBottom(type.unwrapTypeView()); } @override // Coverage-ignore(suite): Not run. - bool isObject(SharedTypeView type) { + bool isObject(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); return unwrappedType is InterfaceType && unwrappedType.classNode == typeEnvironment.objectClass && @@ -627,7 +624,7 @@ class OperationsCfe } @override - SharedTypeView promoteToNonNull(SharedTypeView type) { + SharedTypeView promoteToNonNull(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType.nullability == Nullability.nonNullable) { return type; @@ -642,7 +639,7 @@ class OperationsCfe } @override - SharedTypeView variableType(VariableDeclaration variable) { + SharedTypeView variableType(VariableDeclaration variable) { if (variable is VariableDeclarationImpl) { // When late variables get lowered, their type is changed, but the // original type is stored in `VariableDeclarationImpl.lateType`, so we @@ -653,14 +650,13 @@ class OperationsCfe } @override - bool isTypeParameterType(SharedTypeView type) { - return type.unwrapTypeView() is TypeParameterType || - type.unwrapTypeView() is IntersectionType; + bool isTypeParameterType(SharedTypeView type) { + return type.unwrapTypeView() is TypeParameterType || + type.unwrapTypeView() is IntersectionType; } @override - SharedTypeView tryPromoteToType( - SharedTypeView to, SharedTypeView from) { + SharedTypeView tryPromoteToType(SharedTypeView to, SharedTypeView from) { DartType unwrappedTo = to.unwrapTypeView(); DartType unwrappedFrom = from.unwrapTypeView(); if (isSubtypeOfInternal(unwrappedTo, unwrappedFrom)) { @@ -668,7 +664,7 @@ class OperationsCfe } if (unwrappedFrom is TypeParameterType) { if (isSubtypeOfInternal(unwrappedTo, unwrappedFrom.bound)) { - if (to.unwrapTypeView().nullability != Nullability.nullable) { + if (to.unwrapTypeView().nullability != Nullability.nullable) { // We treat promotions of the form `x is T`, where `T` is not // nullable, as a two-step promotions equivalent to // `x != null && x is T`. @@ -697,8 +693,7 @@ class OperationsCfe } @override - bool isAssignableTo( - SharedTypeView fromType, SharedTypeView toType) { + bool isAssignableTo(SharedTypeView fromType, SharedTypeView toType) { if (fromType is DynamicType) return true; return typeEnvironment .performNullabilityAwareSubtypeCheck( @@ -718,8 +713,8 @@ class OperationsCfe @override // Coverage-ignore(suite): Not run. bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView typeSchema, - required SharedTypeView type}) { + {required SharedTypeSchemaView typeSchema, + required SharedTypeView type}) { return isSubtypeOfInternal( type.unwrapTypeView(), typeSchema.unwrapTypeSchemaView()); } @@ -730,8 +725,8 @@ class OperationsCfe } @override - SharedTypeSchemaView iterableTypeSchema( - SharedTypeSchemaView elementTypeSchema) { + SharedTypeSchemaView iterableTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return new SharedTypeSchemaView(new InterfaceType( typeEnvironment.coreTypes.iterableClass, Nullability.nonNullable, @@ -777,7 +772,7 @@ class OperationsCfe } @override - SharedTypeView? matchListType(SharedTypeView type) { + SharedTypeView? matchListType(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType is TypeDeclarationType) { List? typeArguments = @@ -794,8 +789,8 @@ class OperationsCfe } @override - ({SharedTypeView keyType, SharedTypeView valueType})? - matchMapType(SharedTypeView type) { + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType is! TypeDeclarationType) { return null; @@ -816,7 +811,7 @@ class OperationsCfe } @override - SharedTypeView? matchStreamType(SharedTypeView type) { + SharedTypeView? matchStreamType(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType is TypeDeclarationType) { List? typeArguments = @@ -833,7 +828,7 @@ class OperationsCfe } @override - SharedTypeView normalize(SharedTypeView type) { + SharedTypeView normalize(SharedTypeView type) { return new SharedTypeView( norm(typeEnvironment.coreTypes, type.unwrapTypeView())); } @@ -857,19 +852,20 @@ class OperationsCfe @override DartType recordTypeInternal( - {required List positional, - required List<(String, DartType)> named}) { + {required List positional, + required List<(String, SharedType)> named}) { List namedFields = []; for (var (name, type) in named) { - namedFields.add(new NamedType(name, type)); + namedFields.add(new NamedType(name, type as DartType)); } namedFields.sort((f1, f2) => f1.name.compareTo(f2.name)); - return new RecordType(positional, namedFields, Nullability.nonNullable); + return new RecordType( + positional.cast(), namedFields, Nullability.nonNullable); } @override - SharedTypeSchemaView streamTypeSchema( - SharedTypeSchemaView elementTypeSchema) { + SharedTypeSchemaView streamTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return new SharedTypeSchemaView(new InterfaceType( typeEnvironment.coreTypes.streamClass, Nullability.nonNullable, @@ -877,12 +873,13 @@ class OperationsCfe } @override - SharedTypeView extensionTypeErasure(SharedTypeView type) { - return new SharedTypeView(type.unwrapTypeView().extensionTypeErasure); + SharedTypeView extensionTypeErasure(SharedTypeView type) { + return new SharedTypeView( + type.unwrapTypeView().extensionTypeErasure); } @override - SharedTypeSchemaView typeToSchema(SharedTypeView type) { + SharedTypeSchemaView typeToSchema(SharedTypeView type) { return new SharedTypeSchemaView(type.unwrapTypeView()); } @@ -932,7 +929,7 @@ class OperationsCfe } @override - TypeDeclarationMatchResult? + TypeDeclarationMatchResult? matchTypeDeclarationTypeInternal(DartType type) { if (type is TypeDeclarationType) { switch (type) { @@ -974,16 +971,16 @@ class OperationsCfe } @override - DartType greatestClosureOfTypeInternal(DartType type, - List> typeParametersToEliminate) { + DartType greatestClosureOfTypeInternal( + DartType type, List typeParametersToEliminate) { return new NullabilityAwareFreeTypeParameterEliminator( coreTypes: typeEnvironment.coreTypes) .eliminateToGreatest(type); } @override - DartType leastClosureOfTypeInternal(DartType type, - List> typeParametersToEliminate) { + DartType leastClosureOfTypeInternal( + DartType type, List typeParametersToEliminate) { return new NullabilityAwareFreeTypeParameterEliminator( coreTypes: typeEnvironment.coreTypes) .eliminateToLeast(type); @@ -1017,19 +1014,19 @@ class OperationsCfe } @override - TypeConstraintGenerator + TypeConstraintGenerator createTypeConstraintGenerator( {required covariant TypeInferenceResultForTesting? typeConstraintGenerationDataForTesting, - required List typeParametersToInfer, + required List typeParametersToInfer, required covariant OperationsCfe typeAnalyzerOperations, required bool inferenceUsingBoundsIsEnabled}) { // TODO(cstefantsova): Pass [typeConstraintGenerationDataForTesting] when // [InferenceDataForTesting] is merged with [TypeInferenceResultForTesting]. return new TypeConstraintGatherer( typeAnalyzerOperations.typeEnvironment as TypeSchemaEnvironment, - typeParametersToInfer, + typeParametersToInfer.cast(), typeOperations: typeAnalyzerOperations, inferenceResultForTesting: null, inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled); @@ -1037,9 +1034,8 @@ class OperationsCfe } /// Type inference results used for testing. -class TypeInferenceResultForTesting - extends shared.TypeConstraintGenerationDataForTesting { +class TypeInferenceResultForTesting extends shared + .TypeConstraintGenerationDataForTesting { final Map> inferredTypeArguments = {}; final Map inferredVariableTypes = {}; } diff --git a/pkg/front_end/lib/src/type_inference/type_inferrer.dart b/pkg/front_end/lib/src/type_inference/type_inferrer.dart index 96e174dd2eec..426df7b8266f 100644 --- a/pkg/front_end/lib/src/type_inference/type_inferrer.dart +++ b/pkg/front_end/lib/src/type_inference/type_inferrer.dart @@ -34,7 +34,7 @@ abstract class TypeInferrer { /// Returns the [FlowAnalysis] used during inference. FlowAnalysis> get flowAnalysis; + SharedTypeView> get flowAnalysis; AssignedVariables get assignedVariables; @@ -86,8 +86,9 @@ class TypeInferrerImpl implements TypeInferrer { @override late final FlowAnalysis> flowAnalysis = - new FlowAnalysis(operations, assignedVariables, + SharedTypeView> flowAnalysis = + new FlowAnalysis( + operations, assignedVariables, respectImplicitlyTypedVarInitializers: libraryBuilder.libraryFeatures.constructorTearoffs.isEnabled, fieldPromotionEnabled: @@ -313,7 +314,7 @@ class TypeInferrerImplBenchmarked implements TypeInferrer { @override FlowAnalysis> get flowAnalysis => impl.flowAnalysis; + SharedTypeView> get flowAnalysis => impl.flowAnalysis; @override TypeSchemaEnvironment get typeSchemaEnvironment => impl.typeSchemaEnvironment; diff --git a/pkg/front_end/lib/src/type_inference/type_schema.dart b/pkg/front_end/lib/src/type_inference/type_schema.dart index 129e972ab3fb..27aea654a648 100644 --- a/pkg/front_end/lib/src/type_inference/type_schema.dart +++ b/pkg/front_end/lib/src/type_inference/type_schema.dart @@ -49,8 +49,7 @@ class TypeSchemaPrinter extends Printer { /// /// The unknown type cannot appear in programs or in final inferred types: it is /// purely part of the local inference process. -class UnknownType extends AuxiliaryType - implements SharedUnknownTypeStructure { +class UnknownType extends AuxiliaryType implements SharedUnknownType { const UnknownType(); @override diff --git a/pkg/front_end/lib/src/type_inference/type_schema_environment.dart b/pkg/front_end/lib/src/type_inference/type_schema_environment.dart index d8cdd7e0528e..c387f25d5ef7 100644 --- a/pkg/front_end/lib/src/type_inference/type_schema_environment.dart +++ b/pkg/front_end/lib/src/type_inference/type_schema_environment.dart @@ -23,22 +23,14 @@ import 'type_inference_engine.dart'; import 'type_schema.dart' show UnknownType, isKnown; import 'type_schema_elimination.dart' show greatestClosure, leastClosure; -typedef GeneratedTypeConstraint = shared.GeneratedTypeConstraint; +typedef GeneratedTypeConstraint + = shared.GeneratedTypeConstraint; -typedef MergedTypeConstraint = shared.MergedTypeConstraint< - DartType, - StructuralParameter, - VariableDeclaration, - TypeDeclarationType, - TypeDeclaration>; +typedef MergedTypeConstraint = shared.MergedTypeConstraint; typedef UnknownTypeConstraintOrigin = shared.UnknownTypeConstraintOrigin< - DartType, - VariableDeclaration, - StructuralParameter, - TypeDeclarationType, - TypeDeclaration>; + VariableDeclaration, TypeDeclarationType, TypeDeclaration>; /// Given a [FunctionType], gets the type of the named parameter with the given /// [name], or `dynamic` if there is no parameter with the given name. @@ -366,7 +358,7 @@ class TypeSchemaEnvironment extends HierarchyBasedTypeEnvironment // Otherwise take whatever bound has partial information, // e.g. `Iterable` - if (constraint.lower is! SharedUnknownTypeSchemaView) { + if (constraint.lower is! SharedUnknownTypeSchemaView) { return grounded ? leastClosure(constraint.lower.unwrapTypeSchemaView(), coreTypes: coreTypes) @@ -479,13 +471,14 @@ class TypeSchemaEnvironment extends HierarchyBasedTypeEnvironment } if (inferenceUsingBoundsIsEnabled && - constraint.lower is! SharedUnknownTypeSchemaView && + constraint.lower is! SharedUnknownTypeSchemaView && !hasOmittedBound(typeParameterToInfer)) { MergedTypeConstraint constraintFromBound = operations.mergeInConstraintsFromBound( typeParameterToInfer: typeParameterToInfer, - typeParametersToInfer: typeParametersToInfer, - lower: constraint.lower.unwrapTypeSchemaView(), + typeParametersToInfer: + typeParametersToInfer.cast(), + lower: constraint.lower.unwrapTypeSchemaView(), inferencePhaseConstraints: constraints, dataForTesting: dataForTesting, inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled); @@ -539,14 +532,15 @@ class TypeSchemaEnvironment extends HierarchyBasedTypeEnvironment // If we consider the `T extends num` we conclude ``, which works. if (inferenceUsingBoundsIsEnabled && - constraint.lower is! SharedUnknownTypeSchemaView && + constraint.lower is! SharedUnknownTypeSchemaView && !hasOmittedBound(typeParameterToInfer)) { // Coverage-ignore-block(suite): Not run. MergedTypeConstraint constraintFromBound = operations.mergeInConstraintsFromBound( typeParameterToInfer: typeParameterToInfer, - typeParametersToInfer: typeParametersToInfer, - lower: constraint.lower.unwrapTypeSchemaView(), + typeParametersToInfer: + typeParametersToInfer.cast(), + lower: constraint.lower.unwrapTypeSchemaView(), inferencePhaseConstraints: constraints, dataForTesting: dataForTesting, inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled); diff --git a/pkg/front_end/test/id_tests/type_constraint_generation_test.dart b/pkg/front_end/test/id_tests/type_constraint_generation_test.dart index 843af315d043..d4aa9f3a67c8 100644 --- a/pkg/front_end/test/id_tests/type_constraint_generation_test.dart +++ b/pkg/front_end/test/id_tests/type_constraint_generation_test.dart @@ -90,11 +90,21 @@ class _InferredTypeArgumentsDataInterpreter sb.write(','); } if (actualData[i].isUpper) { - sb.write("${actualData[i].typeParameter.name} <: "); + String? parameterName = actualData[i] + .typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + StructuralParameter>() + .name; + sb.write("${parameterName} <: "); sb.write(typeToText(actualData[i].constraint.unwrapTypeSchemaView(), TypeRepresentation.analyzerNonNullableByDefault)); } else { - sb.write("${actualData[i].typeParameter.name} :> "); + String? parameterName = actualData[i] + .typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + StructuralParameter>() + .name; + sb.write("${parameterName} :> "); sb.write(typeToText(actualData[i].constraint.unwrapTypeSchemaView(), TypeRepresentation.analyzerNonNullableByDefault)); } diff --git a/pkg/front_end/test/type_inference/type_constraint_gatherer_nnbd_test.dart b/pkg/front_end/test/type_inference/type_constraint_gatherer_nnbd_test.dart index 6b613f30b777..4c1a3bab7ab3 100644 --- a/pkg/front_end/test/type_inference/type_constraint_gatherer_nnbd_test.dart +++ b/pkg/front_end/test/type_inference/type_constraint_gatherer_nnbd_test.dart @@ -409,12 +409,16 @@ class TypeConstraintGathererTest { constraint.upper is! UnknownType) { var s = t.name; if (constraint.lower is! UnknownType) { - s = '${typeSchemaToString(constraint.lower.unwrapTypeSchemaView())}' + s = '${typeSchemaToString( + constraint.lower.unwrapTypeSchemaView(), + )}' ' <: $s'; } if (constraint.upper is! UnknownType) { s = '$s <: ' - '${typeSchemaToString(constraint.upper.unwrapTypeSchemaView())}'; + '${typeSchemaToString( + constraint.upper.unwrapTypeSchemaView(), + )}'; } constraintStrings.add(s as String); } diff --git a/pkg/front_end/test/type_inference/type_constraint_gatherer_test.dart b/pkg/front_end/test/type_inference/type_constraint_gatherer_test.dart index 5050c19e0c05..8c8f11a12232 100644 --- a/pkg/front_end/test/type_inference/type_constraint_gatherer_test.dart +++ b/pkg/front_end/test/type_inference/type_constraint_gatherer_test.dart @@ -377,12 +377,16 @@ class TypeConstraintGathererTest { constraint.upper is! UnknownType) { var s = t.name; if (constraint.lower is! UnknownType) { - s = '${typeSchemaToString(constraint.lower.unwrapTypeSchemaView())}' + s = '${typeSchemaToString( + constraint.lower.unwrapTypeSchemaView(), + )}' ' <: $s'; } if (constraint.upper is! UnknownType) { s = '$s <: ' - '${typeSchemaToString(constraint.upper.unwrapTypeSchemaView())}'; + '${typeSchemaToString( + constraint.upper.unwrapTypeSchemaView(), + )}'; } constraintStrings.add(s as String); } diff --git a/pkg/kernel/lib/ast.dart b/pkg/kernel/lib/ast.dart index 56855875bc88..c4b0292bb5c5 100644 --- a/pkg/kernel/lib/ast.dart +++ b/pkg/kernel/lib/ast.dart @@ -73,16 +73,16 @@ import 'package:_fe_analyzer_shared/src/type_inference/type_analyzer_operations. show Variance; import 'package:_fe_analyzer_shared/src/types/shared_type.dart' show - SharedDynamicTypeStructure, - SharedFunctionTypeStructure, - SharedInvalidTypeStructure, - SharedNamedFunctionParameterStructure, - SharedNamedTypeStructure, - SharedNullTypeStructure, - SharedRecordTypeStructure, - SharedTypeParameterStructure, - SharedTypeStructure, - SharedVoidTypeStructure; + SharedDynamicType, + SharedFunctionType, + SharedInvalidType, + SharedNamedFunctionParameter, + SharedNamedType, + SharedNullType, + SharedRecordType, + SharedTypeParameter, + SharedType, + SharedVoidType; import 'src/extension_type_erasure.dart'; import 'visitor.dart'; diff --git a/pkg/kernel/lib/src/ast/types.dart b/pkg/kernel/lib/src/ast/types.dart index 720c49eb7ef9..cc3c80cc4da3 100644 --- a/pkg/kernel/lib/src/ast/types.dart +++ b/pkg/kernel/lib/src/ast/types.dart @@ -259,8 +259,7 @@ class TypeParameter extends TreeNode implements Annotatable { /// /// [StructuralParameter] objects should not be shared between different /// [FunctionType] objects. -class StructuralParameter extends Node - implements SharedTypeParameterStructure { +class StructuralParameter extends Node implements SharedTypeParameter { int flags = 0; String? name; // Cosmetic name. @@ -465,7 +464,7 @@ class Supertype extends Node { /// /// The `==` operator on [DartType]s compare based on type equality, not /// object identity. -sealed class DartType extends Node implements SharedTypeStructure { +sealed class DartType extends Node implements SharedType { const DartType(); @override @@ -584,7 +583,7 @@ sealed class DartType extends Node implements SharedTypeStructure { String getDisplayString() => toText(const AstTextStrategy()); @override - bool isStructurallyEqualTo(SharedTypeStructure other) { + bool isStructurallyEqualTo(SharedType other) { // TODO(cstefantsova): Use the actual algorithm for structural equality. return this == other; } @@ -632,8 +631,7 @@ abstract class AuxiliaryType extends DartType { /// /// Can usually be treated as 'dynamic', but should occasionally be handled /// differently, e.g. `x is ERROR` should evaluate to false. -class InvalidType extends DartType - implements SharedInvalidTypeStructure { +class InvalidType extends DartType implements SharedInvalidType { @override final int hashCode = 12345; @@ -686,8 +684,7 @@ class InvalidType extends DartType } } -class DynamicType extends DartType - implements SharedDynamicTypeStructure { +class DynamicType extends DartType implements SharedDynamicType { @override final int hashCode = 54321; @@ -732,7 +729,7 @@ class DynamicType extends DartType } } -class VoidType extends DartType implements SharedVoidTypeStructure { +class VoidType extends DartType implements SharedVoidType { @override final int hashCode = 123121; @@ -856,7 +853,7 @@ class NeverType extends DartType { } } -class NullType extends DartType implements SharedNullTypeStructure { +class NullType extends DartType implements SharedNullType { @override final int hashCode = 415324; @@ -1014,9 +1011,7 @@ class InterfaceType extends TypeDeclarationType { } /// A possibly generic function type. -class FunctionType extends DartType - implements - SharedFunctionTypeStructure { +class FunctionType extends DartType implements SharedFunctionType { final List typeParameters; final int requiredParameterCount; final List positionalParameters; @@ -1604,8 +1599,8 @@ class ExtensionType extends TypeDeclarationType { class NamedType extends Node implements Comparable, - SharedNamedTypeStructure, - SharedNamedFunctionParameterStructure { + SharedNamedType, + SharedNamedFunctionParameter { // Flag used for serialization if [isRequired]. static const int FlagRequiredNamedType = 1 << 0; @@ -2197,8 +2192,7 @@ class StructuralParameterType extends DartType { } } -class RecordType extends DartType - implements SharedRecordTypeStructure { +class RecordType extends DartType implements SharedRecordType { final List positional; final List named; @@ -2222,10 +2216,10 @@ class RecordType extends DartType "Named field types aren't sorted lexicographically " "in a RecordType: ${named}"); - List> get namedTypes => named; + List get namedTypes => named; @override - List> get sortedNamedTypesShared { + List get sortedNamedTypesShared { return namedTypes; }