Version 3.8.0-13.0.dev Merge d2000980d4a5508bace7c91e9cc0ec5904e4ec15 into dev
diff --git a/DEPS b/DEPS index 32fe8fc..d2081c9 100644 --- a/DEPS +++ b/DEPS
@@ -143,7 +143,7 @@ # dart-native-interop-team@ is rolling breaking changes manually while the assets features are in experimental. "native_rev": "ba34674d97ffe612a3df782e1695dab4e5010e66", # disable tools/rev_sdk_deps.dart "protobuf_rev": "b7dd58cdbd879beee4c3fbf8ee80fce8e97bad26", - "pub_rev": "58de642dc1d07601f6eb2b4ecd94555c0210106b", # disable tools/rev_sdk_deps.dart + "pub_rev": "710265bae23ad5860f33287fba10b5c369f19a93", # disable tools/rev_sdk_deps.dart "shelf_rev": "bf799519cda2898a7c5af06dcfdd5fe6443afd79", "sync_http_rev": "47e6b264a209d0d806cfe9cdad8b6c69ce231986", "tar_rev": "5a1ea943e70cdf3fa5e1102cdbb9418bd9b4b81a",
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 4e26453..7f00e8a 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 @@ required Type knownType, bool matchFailsIfWrongType = true, bool matchMayFailEvenIfCorrectType = false}) { - if (knownType is SharedInvalidTypeStructure) { + if (knownType is SharedInvalidType) { _unmatched = _join(_unmatched!, _current); return false; }
diff --git a/pkg/_fe_analyzer_shared/lib/src/type_inference/shared_inference_log.dart b/pkg/_fe_analyzer_shared/lib/src/type_inference/shared_inference_log.dart index 8a6715f..d167226 100644 --- a/pkg/_fe_analyzer_shared/lib/src/type_inference/shared_inference_log.dart +++ b/pkg/_fe_analyzer_shared/lib/src/type_inference/shared_inference_log.dart
@@ -121,11 +121,7 @@ /// 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<TypeStructure>, - Type extends SharedTypeStructure<Type>, - 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 @@ /// 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 @@ /// Called when generic type inference begins. void enterGenericInference( - List<TypeParameterStructure> typeFormals, Type template); + List<SharedTypeParameter> typeFormals, covariant SharedType template); /// Called when type inference begins inferring the left hand side of an /// assignment. @@ -202,7 +198,9 @@ /// Called when generic type inference ends. void exitGenericInference( - {bool aborted = false, bool failed = false, List<Type>? finalTypes}); + {bool aborted = false, + bool failed = false, + covariant List<SharedType>? finalTypes}); /// Called when type inference has finished inferring the left hand side of an /// assignment. @@ -236,26 +234,23 @@ /// Records a constraint that was generated during the process of matching one /// type schema to another. - void recordGeneratedConstraint( - TypeParameterStructure parameter, - MergedTypeConstraint<TypeStructure, TypeParameterStructure, Object, Type, - Object> - constraint); + void recordGeneratedConstraint(SharedTypeParameter parameter, + MergedTypeConstraint<Object, SharedType, Object> 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<Type> types); + void recordPreliminaryTypes(List<SharedType> 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 @@ /// 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<TypeStructure>, - Type extends SharedTypeStructure<Type>, - TypeParameterStructure extends SharedTypeParameterStructure< - TypeStructure>> - implements - SharedInferenceLogWriter<TypeStructure, Type, TypeParameterStructure> { +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 @@ @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 @@ } @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 @@ } @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 @@ @override void enterGenericInference( - List<TypeParameterStructure> typeFormals, Type template) { + List<SharedTypeParameter> 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 @@ @override void exitGenericInference( - {bool aborted = false, bool failed = false, List<Type>? finalTypes}) { + {bool aborted = false, + bool failed = false, + List<SharedType>? 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 @@ } @override - void recordGeneratedConstraint( - TypeParameterStructure parameter, - MergedTypeConstraint<TypeStructure, TypeParameterStructure, Object, Type, - Object> - constraint) { + void recordGeneratedConstraint(SharedTypeParameter parameter, + MergedTypeConstraint<Object, SharedType, Object> constraint) { checkCall( method: 'recordGeneratedConstraint', arguments: [parameter, constraint], @@ -694,7 +682,7 @@ @override void recordLookupResult( {required Object expression, - required Type type, + required SharedType type, required Object? target, required String methodName}) { checkCall( @@ -713,7 +701,7 @@ } @override - void recordPreliminaryTypes(List<Type> types) { + void recordPreliminaryTypes(List<SharedType> types) { checkCall( method: 'recordPreliminaryTypes', arguments: [types], @@ -727,7 +715,7 @@ } @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 d6f3592a..1b4c62c 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 @@ /// Result for analyzing an assigned variable pattern in /// [TypeAnalyzer.analyzeAssignedVariablePattern]. -class AssignedVariablePatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class AssignedVariablePatternResult<Error> extends PatternResult { /// Error for when a variable was assigned multiple times within a pattern. final Error? duplicateAssignmentPatternVariableError; @@ -25,11 +23,9 @@ /// Result for analyzing a constant pattern in /// [TypeAnalyzer.analyzeConstantPattern]. -class ConstantPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class ConstantPatternResult<Error> extends PatternResult { /// The static type of the constant expression. - final SharedTypeView<TypeStructure> expressionType; + final SharedTypeView expressionType; /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -47,11 +43,9 @@ /// Result for analyzing a declared variable pattern in /// [TypeAnalyzer.analyzeDeclaredVariablePattern]. -class DeclaredVariablePatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class DeclaredVariablePatternResult<Error> extends PatternResult { /// The static type of the variable. - final SharedTypeView<TypeStructure> 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 @@ /// 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<TypeStructure>> { +class ExpressionTypeAnalysisResult { /// The static type of the expression. - final SharedTypeView<TypeStructure> type; + final SharedTypeView type; ExpressionTypeAnalysisResult({required this.type}); } @@ -79,16 +72,15 @@ /// Result for analyzing an if-case statement or element in /// [TypeAnalyzer.analyzeIfCaseStatement] and /// [TypeAnalyzer.analyzeIfCaseElement]. -class IfCaseStatementResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, Error> { +class IfCaseStatementResult<Error> { /// The static type of the matched expression. - final SharedTypeView<TypeStructure> 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<TypeStructure>? guardType; + final SharedTypeView? guardType; IfCaseStatementResult( {required this.matchedExpressionType, @@ -97,9 +89,7 @@ } /// Container for the result of running type analysis on an integer literal. -class IntTypeAnalysisResult< - TypeStructure extends SharedTypeStructure<TypeStructure>> - extends ExpressionTypeAnalysisResult<TypeStructure> { +class IntTypeAnalysisResult extends ExpressionTypeAnalysisResult { /// Whether the integer literal was converted to a double. final bool convertedToDouble; @@ -107,11 +97,9 @@ } /// Result for analyzing a list pattern in [TypeAnalyzer.analyzeListPattern]. -class ListPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class ListPatternResult<Error> extends PatternResult { /// The required type of the list pattern. - final SharedTypeView<TypeStructure> requiredType; + final SharedTypeView requiredType; /// Errors for when multiple rest patterns occurred within the list pattern. /// @@ -133,9 +121,7 @@ /// Result for analyzing a logical or pattern in /// [TypeAnalyzer.analyzeLogicalOrPattern]. -class LogicalOrPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class LogicalOrPatternResult<Error> extends PatternResult { /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -145,10 +131,9 @@ } /// Result for analyzing a map pattern in [TypeAnalyzer.analyzeMapPattern]. -class MapPatternResult<TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class MapPatternResult<Error> extends PatternResult { /// The required type of the map pattern. - final SharedTypeView<TypeStructure> 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 @@ /// Result for analyzing a null check or null assert pattern in /// [TypeAnalyzer.analyzeNullCheckOrAssertPattern]. -class NullCheckOrAssertPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class NullCheckOrAssertPatternResult<Error> extends PatternResult { /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -275,11 +258,9 @@ /// Result for analyzing an object pattern in /// [TypeAnalyzer.analyzeObjectPattern]. -class ObjectPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class ObjectPatternResult<Error> extends PatternResult { /// The required type of the object pattern. - final SharedTypeView<TypeStructure> requiredType; + final SharedTypeView requiredType; /// Errors for when the same property name was used multiple times in the /// object pattern. @@ -301,11 +282,9 @@ } /// Container for the result of running type analysis on a pattern assignment. -class PatternAssignmentAnalysisResult< - TypeStructure extends SharedTypeStructure<TypeStructure>> - extends ExpressionTypeAnalysisResult<TypeStructure> { +class PatternAssignmentAnalysisResult extends ExpressionTypeAnalysisResult { /// The type schema of the pattern on the left hand size of the assignment. - final SharedTypeSchemaView<TypeStructure> patternSchema; + final SharedTypeSchemaView patternSchema; PatternAssignmentAnalysisResult({ required this.patternSchema, @@ -315,13 +294,12 @@ /// Result for analyzing a pattern-for-in statement or element in /// [TypeAnalyzer.analyzePatternForIn]. -class PatternForInResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, Error> { +class PatternForInResult<Error> { /// The static type of the elements of the for in expression. - final SharedTypeView<TypeStructure> elementType; + final SharedTypeView elementType; /// The static type of the collection of elements of the for in expression. - final SharedTypeView<TypeStructure> expressionType; + final SharedTypeView expressionType; /// Error for when the expression is not an iterable. final Error? patternForInExpressionIsNotIterableError; @@ -333,22 +311,21 @@ } /// Result for analyzing a pattern in [TypeAnalyzer]. -class PatternResult<TypeStructure extends SharedTypeStructure<TypeStructure>> { +class PatternResult { /// The matched value type that was used to type check the pattern. - final SharedTypeView<TypeStructure> 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<TypeStructure>> { +class PatternVariableDeclarationAnalysisResult { /// The type schema of the pattern on the left hand size of the declaration. - final SharedTypeSchemaView<TypeStructure> patternSchema; + final SharedTypeSchemaView patternSchema; /// The type of the initializer expression. - final SharedTypeView<TypeStructure> initializerType; + final SharedTypeView initializerType; PatternVariableDeclarationAnalysisResult({ required this.patternSchema, @@ -358,11 +335,9 @@ /// Result for analyzing a record pattern in /// [TypeAnalyzer.analyzeRecordPattern]. -class RecordPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class RecordPatternResult<Error> extends PatternResult { /// The required type of the record pattern. - final SharedTypeView<TypeStructure> requiredType; + final SharedTypeView requiredType; /// Errors for when the same property name was used multiple times in the /// record pattern. @@ -385,11 +360,9 @@ /// Result for analyzing a relational pattern in /// [TypeAnalyzer.analyzeRelationalPattern]. -class RelationalPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class RelationalPatternResult<Error> extends PatternResult { /// The static type of the operand. - final SharedTypeView<TypeStructure> operandType; + final SharedTypeView operandType; /// Error for when the pattern occurred in an irrefutable context. final Error? refutablePatternInIrrefutableContextError; @@ -411,9 +384,7 @@ /// Result for analyzing a switch expression in /// [TypeAnalyzer.analyzeSwitchExpression]. -class SwitchExpressionResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends ExpressionTypeAnalysisResult<TypeStructure> { +class SwitchExpressionResult<Error> extends ExpressionTypeAnalysisResult { /// Errors for non-bool guards. /// /// The key is the case index of the erroneous guard. @@ -426,7 +397,7 @@ /// The key is the case index of the guard. /// /// This is `null` if no such guards where present. - final Map<int, SharedTypeView<TypeStructure>>? guardTypes; + final Map<int, SharedTypeView>? guardTypes; SwitchExpressionResult( {required super.type, @@ -435,8 +406,7 @@ } /// Container for the result of running type analysis on an integer literal. -class SwitchStatementTypeAnalysisResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, Error> { +class SwitchStatementTypeAnalysisResult<Error> { /// Whether the switch statement had a `default` clause. final bool hasDefault; @@ -455,7 +425,7 @@ final bool requiresExhaustivenessValidation; /// The static type of the scrutinee expression. - final SharedTypeView<TypeStructure> scrutineeType; + final SharedTypeView scrutineeType; /// Errors for the cases that don't complete normally. /// @@ -474,7 +444,7 @@ /// The keys of the maps are case and head indices of the guard. /// /// This is `null` if no such guards where present. - final Map<int, Map<int, SharedTypeView<TypeStructure>>>? guardTypes; + final Map<int, Map<int, SharedTypeView>>? guardTypes; SwitchStatementTypeAnalysisResult({ required this.hasDefault, @@ -502,9 +472,7 @@ /// Result for analyzing a wildcard pattern /// [TypeAnalyzer.analyzeWildcardPattern]. -class WildcardPatternResult< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Error> extends PatternResult<TypeStructure> { +class WildcardPatternResult<Error> 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 89fa45f..992fa75 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 @@ } /// Information about a relational operator. -class RelationalOperatorResolution< - TypeStructure extends SharedTypeStructure<TypeStructure>> { +class RelationalOperatorResolution { final RelationalOperatorKind kind; - final SharedTypeView<TypeStructure> parameterType; - final SharedTypeView<TypeStructure> returnType; + final SharedTypeView parameterType; + final SharedTypeView returnType; RelationalOperatorResolution({ required this.kind, @@ -263,31 +262,24 @@ /// of each entry in order to verify that when an entity is popped, it has the /// expected kind. mixin TypeAnalyzer< - TypeStructure extends SharedTypeStructure<TypeStructure>, 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<TypeStructure>, TypeDeclarationType extends Object, TypeDeclaration extends Object> - implements - TypeAnalysisNullShortingInterface<Expression, - SharedTypeView<TypeStructure>> { - TypeAnalyzerErrors<Node, Statement, Expression, Variable, - SharedTypeView<TypeStructure>, Pattern, Error> get errors; + implements TypeAnalysisNullShortingInterface<Expression, SharedTypeView> { + TypeAnalyzerErrors<Node, Statement, Expression, Variable, SharedTypeView, + Pattern, Error> get errors; @override - FlowAnalysis<Node, Statement, Expression, Variable, - SharedTypeView<TypeStructure>> get flow; + FlowAnalysis<Node, Statement, Expression, Variable, SharedTypeView> get flow; @override - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> get operations; + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> + get operations; /// Options affecting the behavior of [TypeAnalyzer]. TypeAnalyzerOptions get options; @@ -305,14 +297,11 @@ /// [analyzeDeclaredVariablePattern] should be used instead. /// /// Stack effect: none. - AssignedVariablePatternResult<TypeStructure, Error> - analyzeAssignedVariablePattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, - Pattern node, - Variable variable) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + AssignedVariablePatternResult<Error> analyzeAssignedVariablePattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, + Pattern node, + Variable variable) { + SharedTypeView matchedValueType = flow.getMatchedValueType(); Error? duplicateAssignmentPatternVariableError; Map<Variable, Pattern>? assignedVariables = context.assignedVariables; if (assignedVariables != null) { @@ -329,15 +318,14 @@ } } - SharedTypeView<TypeStructure> 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 @@ /// Computes the type schema for a variable pattern appearing in an assignment /// context. [variable] is the variable being referenced. - SharedTypeSchemaView<TypeStructure> analyzeAssignedVariablePatternSchema( + SharedTypeSchemaView analyzeAssignedVariablePatternSchema( Variable variable) => operations.typeToSchema( flow.promotedType(variable) ?? operations.variableType(variable)); @@ -370,21 +358,20 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern innerPattern). - PatternResult<TypeStructure> analyzeCastPattern({ - required MatchContext<Node, Expression, Pattern, - SharedTypeView<TypeStructure>, Variable> + PatternResult analyzeCastPattern({ + required MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, required Pattern pattern, required Pattern innerPattern, - required SharedTypeView<TypeStructure> requiredType, + required SharedTypeView requiredType, }) { - SharedTypeView<TypeStructure> 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 @@ /// Computes the type schema for a cast pattern. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> 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 @@ /// and information about reported errors. /// /// Stack effect: pushes (Expression). - ConstantPatternResult<TypeStructure, Error> analyzeConstantPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + ConstantPatternResult<Error> analyzeConstantPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Node node, Expression expression) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () Node? irrefutableContext = context.irrefutableContext; Error? refutablePatternInIrrefutableContextError; @@ -435,7 +419,7 @@ errors.refutablePatternInIrrefutableContext( pattern: node, context: irrefutableContext); } - SharedTypeView<TypeStructure> expressionType = analyzeExpression( + SharedTypeView expressionType = analyzeExpression( expression, operations.typeToSchema(matchedValueType)); flow.constantPattern_end(expression, expressionType, patternsEnabled: options.patternsEnabled, @@ -470,7 +454,7 @@ /// Computes the type schema for a constant pattern. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> 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 @@ /// variable (possibly inferred) and information about reported errors. /// /// Stack effect: none. - DeclaredVariablePatternResult<TypeStructure, Error> - analyzeDeclaredVariablePattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + DeclaredVariablePatternResult<Error> analyzeDeclaredVariablePattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, Variable variable, String variableName, - SharedTypeView<TypeStructure>? declaredType, + SharedTypeView? declaredType, ) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); - SharedTypeView<TypeStructure> 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 @@ // 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<TypeStructure> 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 @@ /// declared type (if present). /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeDeclaredVariablePatternSchema( - SharedTypeView<TypeStructure>? declaredType) { + SharedTypeSchemaView analyzeDeclaredVariablePatternSchema( + SharedTypeView? declaredType) { return declaredType == null ? operations.unknownType : operations.typeToSchema(declaredType); @@ -567,22 +547,20 @@ /// [node] will be allowed to continue into the containing expression. /// /// Stack effect: pushes (Expression). - SharedTypeView<TypeStructure> analyzeExpression( - Expression node, SharedTypeSchemaView<TypeStructure> schema, + SharedTypeView analyzeExpression(Expression node, SharedTypeSchemaView schema, {bool continueNullShorting = false}) { int? nullShortingTargetDepth; if (!continueNullShorting) nullShortingTargetDepth = nullShortingDepth; // Stack: () - if (schema is SharedDynamicTypeSchemaView<TypeStructure>) { + if (schema is SharedDynamicTypeSchemaView) { schema = operations.unknownType; } - ExpressionTypeAnalysisResult<TypeStructure> result = - dispatchExpression(node, schema); + ExpressionTypeAnalysisResult result = dispatchExpression(node, schema); // Stack: (Expression) if (operations.isNever(result.type)) { flow.handleExit(); } - SharedTypeView<TypeStructure> type = result.type; + SharedTypeView type = result.type; if (nullShortingTargetDepth != null && nullShortingDepth > nullShortingTargetDepth) { type = finishNullShorting(nullShortingTargetDepth, type); @@ -610,7 +588,7 @@ /// `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<TypeStructure, Error> analyzeIfCaseElement({ + IfCaseStatementResult<Error> analyzeIfCaseElement({ required Node node, required Expression expression, required Pattern pattern, @@ -622,7 +600,7 @@ }) { // Stack: () flow.ifCaseStatement_begin(); - SharedTypeView<TypeStructure> initializerType = + SharedTypeView initializerType = analyzeExpression(expression, operations.unknownType); flow.ifCaseStatement_afterExpression(expression, initializerType); // Stack: (Expression) @@ -630,8 +608,7 @@ Map<String, int> patternVariablePromotionKeys = {}; // TODO(paulberry): rework handling of isFinal dispatchPattern( - new MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable>( + new MatchContext<Node, Expression, Pattern, SharedTypeView, Variable>( isFinal: false, componentVariables: componentVariables, patternVariablePromotionKeys: patternVariablePromotionKeys, @@ -643,7 +620,7 @@ variables, componentVariables, patternVariablePromotionKeys, location: JoinedPatternVariableLocation.singlePattern); Error? nonBooleanGuardError; - SharedTypeView<TypeStructure>? guardType; + SharedTypeView? guardType; if (guard != null) { guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); @@ -675,7 +652,7 @@ /// representation for `ifFalse` will be pushed by [handleNoStatement]. If /// there is no guard, the representation for `guard` will be pushed by /// [handleNoGuard]. - IfCaseStatementResult<TypeStructure, Error> analyzeIfCaseStatement( + IfCaseStatementResult<Error> analyzeIfCaseStatement( Statement node, Expression expression, Pattern pattern, @@ -686,7 +663,7 @@ ) { // Stack: () flow.ifCaseStatement_begin(); - SharedTypeView<TypeStructure> initializerType = + SharedTypeView initializerType = analyzeExpression(expression, operations.unknownType); flow.ifCaseStatement_afterExpression(expression, initializerType); // Stack: (Expression) @@ -694,8 +671,7 @@ Map<String, int> patternVariablePromotionKeys = {}; // TODO(paulberry): rework handling of isFinal dispatchPattern( - new MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable>( + new MatchContext<Node, Expression, Pattern, SharedTypeView, Variable>( isFinal: false, componentVariables: componentVariables, patternVariablePromotionKeys: patternVariablePromotionKeys, @@ -713,7 +689,7 @@ handle_ifCaseStatement_afterPattern(node: node); // Stack: (Expression, Pattern) Error? nonBooleanGuardError; - SharedTypeView<TypeStructure>? guardType; + SharedTypeView? guardType; if (guard != null) { guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); @@ -781,15 +757,14 @@ /// Analyzes an integer literal, given the type schema [schema]. /// /// Stack effect: none. - IntTypeAnalysisResult<TypeStructure> analyzeIntLiteral( - SharedTypeSchemaView<TypeStructure> schema) { + IntTypeAnalysisResult analyzeIntLiteral(SharedTypeSchemaView schema) { bool convertToDouble = !operations.isTypeSchemaSatisfied( type: operations.intType, typeSchema: schema) && operations.isTypeSchemaSatisfied( type: operations.doubleType, typeSchema: schema); - SharedTypeView<TypeStructure> type = + SharedTypeView type = convertToDouble ? operations.doubleType : operations.intType; - return new IntTypeAnalysisResult<TypeStructure>( + return new IntTypeAnalysisResult( type: type, convertedToDouble: convertToDouble); } @@ -803,31 +778,29 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * Pattern) where n = elements.length. - ListPatternResult<TypeStructure, Error> analyzeListPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + ListPatternResult<Error> analyzeListPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, - {SharedTypeView<TypeStructure>? elementType, + {SharedTypeView? elementType, required List<Node> elements}) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); - SharedTypeView<TypeStructure> valueType; + SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView valueType; if (elementType != null) { valueType = elementType; } else { - SharedTypeView<TypeStructure>? 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<TypeStructure> requiredType = operations.listType(valueType); + SharedTypeView requiredType = operations.listType(valueType); flow.promoteForPattern( matchedType: matchedValueType, knownType: requiredType, @@ -849,7 +822,7 @@ previousRestPattern = element; Pattern? subPattern = getRestPatternElementPattern(element); if (subPattern != null) { - SharedTypeView<TypeStructure> subPatternMatchedType = requiredType; + SharedTypeView subPatternMatchedType = requiredType; flow.pushSubpattern(subPatternMatchedType); dispatchPattern( context.withUnnecessaryWildcardKind(null), subPattern); @@ -887,8 +860,8 @@ /// subpatterns. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeListPatternSchema({ - required SharedTypeView<TypeStructure>? elementType, + SharedTypeSchemaView analyzeListPatternSchema({ + required SharedTypeView? elementType, required List<Node> elements, }) { if (elementType != null) { @@ -899,13 +872,13 @@ return operations.listTypeSchema(operations.unknownType); } - SharedTypeSchemaView<TypeStructure>? currentGLB; + SharedTypeSchemaView? currentGLB; for (Node element in elements) { - SharedTypeSchemaView<TypeStructure>? typeToAdd; + SharedTypeSchemaView? typeToAdd; if (isRestPatternElement(element)) { Pattern? subPattern = getRestPatternElementPattern(element); if (subPattern != null) { - SharedTypeSchemaView<TypeStructure> subPatternType = + SharedTypeSchemaView subPatternType = dispatchPatternSchema(subPattern); typeToAdd = operations.matchIterableTypeSchema(subPatternType); } @@ -930,14 +903,12 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern left, Pattern right) - PatternResult<TypeStructure> analyzeLogicalAndPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + PatternResult analyzeLogicalAndPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, Node lhs, Node rhs) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () dispatchPattern( context.withUnnecessaryWildcardKind( @@ -960,8 +931,7 @@ /// the left and right sides of the `&&` operator. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeLogicalAndPatternSchema( - Node lhs, Node rhs) { + SharedTypeSchemaView analyzeLogicalAndPatternSchema(Node lhs, Node rhs) { return operations.typeSchemaGlb( dispatchPatternSchema(lhs), dispatchPatternSchema(rhs)); } @@ -974,14 +944,12 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern left, Pattern right) - LogicalOrPatternResult<TypeStructure, Error> analyzeLogicalOrPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + LogicalOrPatternResult<Error> analyzeLogicalOrPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, Node lhs, Node rhs) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); Node? irrefutableContext = context.irrefutableContext; Error? refutablePatternInIrrefutableContextError; if (irrefutableContext != null) { @@ -1053,8 +1021,7 @@ /// the left and right sides of the `|` or `&` operator. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> 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 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * MapPatternElement) where n = elements.length. - MapPatternResult<TypeStructure, Error> analyzeMapPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + MapPatternResult<Error> analyzeMapPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, { required ({ - SharedTypeView<TypeStructure> keyType, - SharedTypeView<TypeStructure> valueType + SharedTypeView keyType, + SharedTypeView valueType })? typeArguments, required List<Node> elements, }) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); - SharedTypeView<TypeStructure> keyType; - SharedTypeView<TypeStructure> valueType; - SharedTypeSchemaView<TypeStructure> keySchema; + SharedTypeView matchedValueType = flow.getMatchedValueType(); + SharedTypeView keyType; + SharedTypeView valueType; + SharedTypeSchemaView keySchema; if (typeArguments != null) { keyType = typeArguments.keyType; valueType = typeArguments.valueType; @@ -1097,11 +1062,11 @@ 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 @@ keySchema = operations.unknownType; } } - SharedTypeView<TypeStructure> requiredType = operations.mapType( + SharedTypeView requiredType = operations.mapType( keyType: keyType, valueType: valueType, ); @@ -1134,8 +1099,7 @@ Node element = elements[i]; MapPatternEntry<Expression, Pattern>? entry = getMapPatternEntry(element); if (entry != null) { - SharedTypeView<TypeStructure> keyType = - analyzeExpression(entry.key, keySchema); + SharedTypeView keyType = analyzeExpression(entry.key, keySchema); flow.pushSubpattern(valueType); dispatchPattern( context.withUnnecessaryWildcardKind(null), @@ -1188,10 +1152,10 @@ /// subpatterns. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeMapPatternSchema({ + SharedTypeSchemaView analyzeMapPatternSchema({ required ({ - SharedTypeView<TypeStructure> keyType, - SharedTypeView<TypeStructure> valueType + SharedTypeView keyType, + SharedTypeView valueType })? typeArguments, required List<Node> elements, }) { @@ -1202,11 +1166,11 @@ )); } - SharedTypeSchemaView<TypeStructure>? valueType; + SharedTypeSchemaView? valueType; for (Node element in elements) { MapPatternEntry<Expression, Pattern>? entry = getMapPatternEntry(element); if (entry != null) { - SharedTypeSchemaView<TypeStructure> entryValueType = + SharedTypeSchemaView entryValueType = dispatchPatternSchema(entry.value); if (valueType == null) { valueType = entryValueType; @@ -1231,15 +1195,12 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Pattern innerPattern). - NullCheckOrAssertPatternResult<TypeStructure, Error> - analyzeNullCheckOrAssertPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, - Pattern node, - Pattern innerPattern, - {required bool isAssert}) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + NullCheckOrAssertPatternResult<Error> analyzeNullCheckOrAssertPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, + Pattern node, + Pattern innerPattern, + {required bool isAssert}) { + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () Error? refutablePatternInIrrefutableContextError; Error? matchedTypeIsStrictlyNonNullableError; @@ -1279,7 +1240,7 @@ /// a null-check or a null-assert pattern. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeNullCheckOrAssertPatternSchema( + SharedTypeSchemaView analyzeNullCheckOrAssertPatternSchema( Pattern innerPattern, {required bool isAssert}) { if (isAssert) { @@ -1303,19 +1264,16 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * Pattern) where n = fields.length. - ObjectPatternResult<TypeStructure, Error> analyzeObjectPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + ObjectPatternResult<Error> analyzeObjectPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, { required List<RecordPatternField<Node, Pattern>> fields, }) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); Map<int, Error>? duplicateRecordPatternFieldErrors = _reportDuplicateRecordPatternFields(node, fields); - SharedTypeView<TypeStructure> requiredType = - downwardInferObjectPatternRequiredType( + SharedTypeView requiredType = downwardInferObjectPatternRequiredType( matchedType: matchedValueType, pattern: node, ); @@ -1324,9 +1282,9 @@ // If the required type is `dynamic` or `Never`, then every getter is // treated as having the same type. - (Object?, SharedTypeView<TypeStructure>)? 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 @@ // Stack: () for (RecordPatternField<Node, Pattern> field in fields) { - var ( - Object? propertyMember, - SharedTypeView<TypeStructure> 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<TypeStructure> 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 @@ /// specified with the object name, and with the type arguments applied. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeObjectPatternSchema( - SharedTypeView<TypeStructure> type) { + SharedTypeSchemaView analyzeObjectPatternSchema(SharedTypeView type) { return operations.typeToSchema(type); } @@ -1397,20 +1351,17 @@ /// the pattern, and [rhs] for the right hand side. /// /// Stack effect: pushes (Expression, Pattern). - PatternAssignmentAnalysisResult<TypeStructure> analyzePatternAssignment( + PatternAssignmentAnalysisResult analyzePatternAssignment( Expression node, Pattern pattern, Expression rhs) { // Stack: () - SharedTypeSchemaView<TypeStructure> patternSchema = - dispatchPatternSchema(pattern); - SharedTypeView<TypeStructure> rhsType = - analyzeExpression(rhs, patternSchema); + SharedTypeSchemaView patternSchema = dispatchPatternSchema(pattern); + SharedTypeView rhsType = analyzeExpression(rhs, patternSchema); // Stack: (Expression) flow.patternAssignment_afterRhs(rhs, rhsType); Map<String, List<Variable>> componentVariables = {}; Map<String, int> patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable>( + new MatchContext<Node, Expression, Pattern, SharedTypeView, Variable>( isFinal: false, irrefutableContext: node, assignedVariables: <Variable, Pattern>{}, @@ -1426,7 +1377,7 @@ } flow.patternAssignment_end(); // Stack: (Expression, Pattern) - return new PatternAssignmentAnalysisResult<TypeStructure>( + return new PatternAssignmentAnalysisResult( patternSchema: patternSchema, type: rhsType, ); @@ -1446,7 +1397,7 @@ /// /// Note, however, that the caller is responsible for reporting an error if /// the static type of [expression] is potentially nullable. - PatternForInResult<TypeStructure, Error> analyzePatternForIn({ + PatternForInResult<Error> analyzePatternForIn({ required Node node, required bool hasAwait, required Pattern pattern, @@ -1454,23 +1405,22 @@ required void Function() dispatchBody, }) { // Stack: () - SharedTypeSchemaView<TypeStructure> patternTypeSchema = - dispatchPatternSchema(pattern); - SharedTypeSchemaView<TypeStructure> expressionTypeSchema = hasAwait + SharedTypeSchemaView patternTypeSchema = dispatchPatternSchema(pattern); + SharedTypeSchemaView expressionTypeSchema = hasAwait ? operations.streamTypeSchema(patternTypeSchema) : operations.iterableTypeSchema(patternTypeSchema); - SharedTypeView<TypeStructure> expressionType = + SharedTypeView expressionType = analyzeExpression(expression, expressionTypeSchema); // Stack: (Expression) Error? patternForInExpressionIsNotIterableError; - SharedTypeView<TypeStructure>? 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 @@ Map<String, List<Variable>> componentVariables = {}; Map<String, int> patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable>( + new MatchContext<Node, Expression, Pattern, SharedTypeView, Variable>( isFinal: false, irrefutableContext: node, componentVariables: componentVariables, @@ -1521,14 +1470,12 @@ /// type of the initializer and the type schema of the [pattern]. /// /// Stack effect: pushes (Expression, Pattern). - PatternVariableDeclarationAnalysisResult<TypeStructure> - analyzePatternVariableDeclaration( - Node node, Pattern pattern, Expression initializer, - {required bool isFinal}) { + PatternVariableDeclarationAnalysisResult analyzePatternVariableDeclaration( + Node node, Pattern pattern, Expression initializer, + {required bool isFinal}) { // Stack: () - SharedTypeSchemaView<TypeStructure> patternSchema = - dispatchPatternSchema(pattern); - SharedTypeView<TypeStructure> initializerType = + SharedTypeSchemaView patternSchema = dispatchPatternSchema(pattern); + SharedTypeView initializerType = analyzeExpression(initializer, patternSchema); // Stack: (Expression) flow.patternVariableDeclaration_afterInitializer( @@ -1536,8 +1483,7 @@ Map<String, List<Variable>> componentVariables = {}; Map<String, int> patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable>( + new MatchContext<Node, Expression, Pattern, SharedTypeView, Variable>( isFinal: isFinal, irrefutableContext: node, componentVariables: componentVariables, @@ -1563,29 +1509,26 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (n * Pattern) where n = fields.length. - RecordPatternResult<TypeStructure, Error> analyzeRecordPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + RecordPatternResult<Error> analyzeRecordPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, { required List<RecordPatternField<Node, Pattern>> fields, }) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); - List<SharedTypeView<TypeStructure>> demonstratedPositionalTypes = []; - List<(String, SharedTypeView<TypeStructure>)> demonstratedNamedTypes = []; + SharedTypeView matchedValueType = flow.getMatchedValueType(); + List<SharedTypeView> demonstratedPositionalTypes = []; + List<(String, SharedTypeView)> demonstratedNamedTypes = []; Map<int, Error>? duplicateRecordPatternFieldErrors = _reportDuplicateRecordPatternFields(node, fields); - void dispatchField(int i, SharedTypeView<TypeStructure> matchedType) { + void dispatchField(int i, SharedTypeView matchedType) { RecordPatternField<Node, Pattern> field = fields[i]; flow.pushSubpattern(matchedType); dispatchPattern( context.withUnnecessaryWildcardKind(null), field.pattern, ); - SharedTypeView<TypeStructure> demonstratedType = - flow.getMatchedValueType(); + SharedTypeView demonstratedType = flow.getMatchedValueType(); String? name = field.name; if (name == null) { demonstratedPositionalTypes.add(demonstratedType); @@ -1596,7 +1539,7 @@ flow.popSubpattern(); } - void dispatchFields(SharedTypeView<TypeStructure> matchedType) { + void dispatchFields(SharedTypeView matchedType) { for (int i = 0; i < fields.length; i++) { dispatchField(i, matchedType); } @@ -1604,7 +1547,7 @@ // Build the required type. int requiredTypePositionalCount = 0; - List<(String, SharedTypeView<TypeStructure>)> requiredTypeNamedTypes = []; + List<(String, SharedTypeView)> requiredTypeNamedTypes = []; for (int i = 0; i < fields.length; i++) { RecordPatternField<Node, Pattern> field = fields[i]; String? name = field.name; @@ -1617,7 +1560,7 @@ ); } } - SharedTypeView<TypeStructure> requiredType = operations.recordType( + SharedTypeView requiredType = operations.recordType( positional: new List.filled( requiredTypePositionalCount, operations.objectQuestionType, @@ -1628,8 +1571,8 @@ matchedType: matchedValueType, knownType: requiredType); // Stack: () - if (matchedValueType is SharedRecordTypeView<TypeStructure>) { - List<SharedTypeView<TypeStructure>>? fieldTypes = + if (matchedValueType is SharedRecordTypeView) { + List<SharedTypeView>? fieldTypes = _matchRecordTypeShape(fields, matchedValueType); if (fieldTypes != null) { assert(fieldTypes.length == fields.length); @@ -1639,9 +1582,9 @@ } 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 @@ ); } - SharedTypeView<TypeStructure> demonstratedType = operations.recordType( + SharedTypeView demonstratedType = operations.recordType( positional: demonstratedPositionalTypes, named: demonstratedNamedTypes); flow.promoteForPattern( matchedType: matchedValueType, @@ -1678,14 +1621,13 @@ /// Computes the type schema for a record pattern. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeRecordPatternSchema({ + SharedTypeSchemaView analyzeRecordPatternSchema({ required List<RecordPatternField<Node, Pattern>> fields, }) { - List<SharedTypeSchemaView<TypeStructure>> positional = []; - List<(String, SharedTypeSchemaView<TypeStructure>)> named = []; + List<SharedTypeSchemaView> positional = []; + List<(String, SharedTypeSchemaView)> named = []; for (RecordPatternField<Node, Pattern> field in fields) { - SharedTypeSchemaView<TypeStructure> fieldType = - dispatchPatternSchema(field.pattern); + SharedTypeSchemaView fieldType = dispatchPatternSchema(field.pattern); String? name = field.name; if (name != null) { named.add((name, fieldType)); @@ -1709,13 +1651,11 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: pushes (Expression). - RelationalPatternResult<TypeStructure, Error> analyzeRelationalPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + RelationalPatternResult<Error> analyzeRelationalPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Pattern node, Expression operand) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); // Stack: () Error? refutablePatternInIrrefutableContextError; Node? irrefutableContext = context.irrefutableContext; @@ -1724,9 +1664,9 @@ errors.refutablePatternInIrrefutableContext( pattern: node, context: irrefutableContext); } - RelationalOperatorResolution<TypeStructure>? operator = + RelationalOperatorResolution? operator = resolveRelationalPatternOperator(node, matchedValueType); - SharedTypeView<TypeStructure>? parameterType = operator?.parameterType; + SharedTypeView? parameterType = operator?.parameterType; bool isEquality = switch (operator?.kind) { RelationalOperatorKind.equals => true, RelationalOperatorKind.notEquals => true, @@ -1735,7 +1675,7 @@ if (isEquality && parameterType != null) { parameterType = operations.makeNullable(parameterType); } - SharedTypeView<TypeStructure> operandType = analyzeExpression( + SharedTypeView operandType = analyzeExpression( operand, parameterType == null ? operations.unknownType @@ -1782,7 +1722,7 @@ /// Computes the type schema for a relational pattern. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> 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 @@ /// /// Stack effect: pushes (Expression, n * ExpressionCase), where n is the /// number of cases. - SwitchExpressionResult<TypeStructure, Error> analyzeSwitchExpression( - Expression node, - Expression scrutinee, - int numCases, - SharedTypeSchemaView<TypeStructure> schema) { + SwitchExpressionResult<Error> 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 @@ // follows: // // - The scrutinee (`e0`) is first analyzed with context type `_`. - SharedTypeView<TypeStructure> expressionType = + SharedTypeView expressionType = analyzeExpression(scrutinee, operations.unknownType); // Stack: (Expression) handleSwitchScrutinee(expressionType); @@ -1817,8 +1754,8 @@ // - If the switch expression has no cases, its static type is `Never`. Map<int, Error>? nonBooleanGuardErrors; - Map<int, SharedTypeView<TypeStructure>>? guardTypes; - SharedTypeView<TypeStructure> staticType; + Map<int, SharedTypeView>? guardTypes; + SharedTypeView staticType; if (numCases == 0) { staticType = operations.neverType; } else { @@ -1827,8 +1764,8 @@ // - 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<TypeStructure>? t; - SharedTypeView<TypeStructure> 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 @@ Map<String, List<Variable>> componentVariables = {}; Map<String, int> patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext<Node, Expression, Pattern, - SharedTypeView<TypeStructure>, Variable>( + new MatchContext<Node, Expression, Pattern, SharedTypeView, + Variable>( isFinal: false, switchScrutinee: scrutinee, componentVariables: componentVariables, @@ -1862,7 +1799,7 @@ guard = memberInfo.head.guard; bool hasGuard = guard != null; if (hasGuard) { - SharedTypeView<TypeStructure> guardType = analyzeExpression( + SharedTypeView guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); Error? nonBooleanGuardError = _checkGuardType(guard, guardType); (guardTypes ??= {})[i] = guardType; @@ -1881,8 +1818,7 @@ flow.switchStatement_endAlternative(guard, {}); flow.switchStatement_endAlternatives(null, hasLabels: false); // Stack: (Expression, i * ExpressionCase, CaseHead) - SharedTypeView<TypeStructure> ti = - analyzeExpression(memberInfo.expression, schema); + SharedTypeView ti = analyzeExpression(memberInfo.expression, schema); if (allCasesSatisfyContext && !operations.isSubtypeOf(ti, s)) { allCasesSatisfyContext = false; } @@ -1925,11 +1861,10 @@ /// /// Stack effect: pushes (Expression, n * StatementCase), where n is the /// number of cases after merging together cases that share a body. - SwitchStatementTypeAnalysisResult<TypeStructure, Error> - analyzeSwitchStatement( - Statement node, Expression scrutinee, final int numCases) { + SwitchStatementTypeAnalysisResult<Error> analyzeSwitchStatement( + Statement node, Expression scrutinee, final int numCases) { // Stack: () - SharedTypeView<TypeStructure> scrutineeType = + SharedTypeView scrutineeType = analyzeExpression(scrutinee, operations.unknownType); // Stack: (Expression) handleSwitchScrutinee(scrutineeType); @@ -1938,7 +1873,7 @@ bool lastCaseTerminates = true; Map<int, Error>? switchCaseCompletesNormallyErrors; Map<int, Map<int, Error>>? nonBooleanGuardErrors; - Map<int, Map<int, SharedTypeView<TypeStructure>>>? guardTypes; + Map<int, Map<int, SharedTypeView>>? guardTypes; for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { // Stack: (Expression, numExecutionPaths * StatementCase) flow.switchStatement_beginAlternatives(); @@ -1960,8 +1895,8 @@ Map<String, List<Variable>> componentVariables = {}; Map<String, int> patternVariablePromotionKeys = {}; dispatchPattern( - new MatchContext<Node, Expression, Pattern, - SharedTypeView<TypeStructure>, Variable>( + new MatchContext<Node, Expression, Pattern, SharedTypeView, + Variable>( isFinal: false, switchScrutinee: scrutinee, componentVariables: componentVariables, @@ -1979,7 +1914,7 @@ // numHeads * CaseHead, Pattern), guard = head.guard; if (guard != null) { - SharedTypeView<TypeStructure> guardType = analyzeExpression( + SharedTypeView guardType = analyzeExpression( guard, operations.typeToSchema(operations.boolType)); Error? nonBooleanGuardError = _checkGuardType(guard, guardType); ((guardTypes ??= {})[caseIndex] ??= {})[headIndex] = guardType; @@ -2071,11 +2006,10 @@ /// Stack effect: none. /// /// Returns the inferred type of the variable. - SharedTypeView<TypeStructure> analyzeUninitializedVariableDeclaration( - Node node, Variable variable, SharedTypeView<TypeStructure>? declaredType, + SharedTypeView analyzeUninitializedVariableDeclaration( + Node node, Variable variable, SharedTypeView? declaredType, {required bool isFinal}) { - SharedTypeView<TypeStructure> inferredType = - declaredType ?? operations.dynamicType; + SharedTypeView inferredType = declaredType ?? operations.dynamicType; setVariableType(variable, inferredType); flow.declare(variable, inferredType, initialized: false); return inferredType; @@ -2088,14 +2022,13 @@ /// See [dispatchPattern] for the meaning of [context]. /// /// Stack effect: none. - WildcardPatternResult<TypeStructure, Error> analyzeWildcardPattern({ - required MatchContext<Node, Expression, Pattern, - SharedTypeView<TypeStructure>, Variable> + WildcardPatternResult<Error> analyzeWildcardPattern({ + required MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, required Pattern node, - required SharedTypeView<TypeStructure>? declaredType, + required SharedTypeView? declaredType, }) { - SharedTypeView<TypeStructure> matchedValueType = flow.getMatchedValueType(); + SharedTypeView matchedValueType = flow.getMatchedValueType(); Node? irrefutableContext = context.irrefutableContext; Error? patternTypeMismatchInIrrefutableContextError; if (irrefutableContext != null && declaredType != null) { @@ -2136,8 +2069,8 @@ /// explicitly declared type (if present). /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> analyzeWildcardPatternSchema({ - required SharedTypeView<TypeStructure>? declaredType, + SharedTypeSchemaView analyzeWildcardPatternSchema({ + required SharedTypeView? declaredType, }) { return declaredType == null ? operations.unknownType @@ -2161,8 +2094,8 @@ /// [analyzeSwitchExpression]. /// /// Stack effect: pushes (Expression). - ExpressionTypeAnalysisResult<TypeStructure> dispatchExpression( - Expression node, SharedTypeSchemaView<TypeStructure> schema); + ExpressionTypeAnalysisResult dispatchExpression( + Expression node, SharedTypeSchemaView schema); /// Calls the appropriate `analyze` method according to the form of [pattern]. /// @@ -2171,17 +2104,15 @@ /// and the information accumulated while matching previous patterns. /// /// Stack effect: pushes (Pattern). - PatternResult<TypeStructure> dispatchPattern( - MatchContext<Node, Expression, Pattern, SharedTypeView<TypeStructure>, - Variable> - context, + PatternResult dispatchPattern( + MatchContext<Node, Expression, Pattern, SharedTypeView, Variable> context, Node pattern); /// Calls the appropriate `analyze...Schema` method according to the form of /// [pattern]. /// /// Stack effect: none. - SharedTypeSchemaView<TypeStructure> 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 @@ void dispatchStatement(Statement statement); /// Infers the type for the [pattern], should be a subtype of [matchedType]. - SharedTypeView<TypeStructure> downwardInferObjectPatternRequiredType({ - required SharedTypeView<TypeStructure> matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required Pattern pattern, }); @@ -2212,7 +2143,7 @@ required JoinedPatternVariableLocation location, required JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView<TypeStructure> type, + required SharedTypeView type, }); /// If the [element] is a map pattern entry, returns it. @@ -2308,8 +2239,8 @@ /// Called after visiting an entry element in a map pattern. /// /// Stack effect: pushes (MapPatternElement). - void handleMapPatternEntry(Pattern container, Node entryElement, - SharedTypeView<TypeStructure> keyType); + void handleMapPatternEntry( + Pattern container, Node entryElement, SharedTypeView keyType); /// Called after visiting a rest element in a map pattern. /// @@ -2373,15 +2304,14 @@ /// eliminate this method. /// /// Stack effect: none. - void handleSwitchScrutinee(SharedTypeView<TypeStructure> 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<TypeStructure> 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 @@ /// 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<TypeStructure>) resolveObjectPatternPropertyGet({ + (Object?, SharedTypeView) resolveObjectPatternPropertyGet({ required Pattern objectPattern, - required SharedTypeView<TypeStructure> receiverType, + required SharedTypeView receiverType, required RecordPatternField<Node, Pattern> field, }); @@ -2404,18 +2334,17 @@ /// If no operator is found, `null` should be returned. (This could happen /// either because the code is invalid, or because [matchedValueType] is /// `dynamic`). - RelationalOperatorResolution<TypeStructure>? resolveRelationalPatternOperator( - Pattern node, SharedTypeView<TypeStructure> 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<TypeStructure> 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<TypeStructure> variableTypeFromInitializerType( - SharedTypeView<TypeStructure> type); + SharedTypeView variableTypeFromInitializerType(SharedTypeView type); /// Common functionality shared by [analyzeIfStatement] and /// [analyzeIfCaseStatement]. @@ -2461,8 +2390,7 @@ // Stack: (CollectionElement ifTrue, CollectionElement ifFalse) } - Error? _checkGuardType( - Expression expression, SharedTypeView<TypeStructure> 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 @@ Variable? variable = variables[variableName]; List<Variable> components = componentVariables[variableName] ?? []; bool isFirst = true; - SharedTypeView<TypeStructure>? typeIfConsistent; + SharedTypeView? typeIfConsistent; bool? isFinalIfConsistent; bool isIdenticalToComponent = false; for (Variable component in components) { if (identical(variable, component)) { isIdenticalToComponent = true; } - SharedTypeView<TypeStructure> componentType = - operations.variableType(component); + SharedTypeView componentType = operations.variableType(component); bool isComponentFinal = operations.isVariableFinal(component); if (isFirst) { typeIfConsistent = componentType; @@ -2546,22 +2473,21 @@ /// 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<SharedTypeView<TypeStructure>>? _matchRecordTypeShape( + List<SharedTypeView>? _matchRecordTypeShape( List<RecordPatternField<Node, Pattern>> fields, - SharedRecordTypeView<TypeStructure> matchedType, + SharedRecordTypeView matchedType, ) { - Map<String, SharedTypeView<TypeStructure>> matchedTypeNamed = {}; - for (var SharedNamedTypeView<TypeStructure>(:name, :type) - in matchedType.namedTypes) { + Map<String, SharedTypeView> matchedTypeNamed = {}; + for (var SharedNamedTypeView(:name, :type) in matchedType.namedTypes) { matchedTypeNamed[name] = type; } - List<SharedTypeView<TypeStructure>> result = []; + List<SharedTypeView> result = []; int namedCount = 0; - Iterator<SharedTypeView<TypeStructure>> positionalIterator = + Iterator<SharedTypeView> positionalIterator = matchedType.positionalTypes.iterator; for (RecordPatternField<Node, Pattern> field in fields) { - SharedTypeView<TypeStructure>? fieldType; + SharedTypeView? fieldType; String? name = field.name; if (name != null) { fieldType = matchedTypeNamed[name]; @@ -2613,10 +2539,10 @@ return errorResults; } - bool _structurallyEqualAfterNormTypes(SharedTypeView<TypeStructure> type1, - SharedTypeView<TypeStructure> type2) { - SharedTypeView<TypeStructure> norm1 = operations.normalize(type1); - SharedTypeView<TypeStructure> 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 d75cfe5..4142001 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 @@ /// 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<TypeStructure>, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - implements FlowAnalysisOperations<Variable, SharedTypeView<TypeStructure>> { +abstract interface class TypeAnalyzerOperations<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> + implements FlowAnalysisOperations<Variable, SharedTypeView> { /// Returns the type `double`. - SharedTypeView<TypeStructure> get doubleType; + SharedTypeView get doubleType; /// Returns the type `dynamic`. - SharedTypeView<TypeStructure> get dynamicType; + SharedTypeView get dynamicType; /// Returns the type used by the client in the case of errors. - SharedTypeView<TypeStructure> get errorType; + SharedTypeView get errorType; /// Returns the type `int`. - SharedTypeView<TypeStructure> get intType; + SharedTypeView get intType; /// Returns the type `Never`. - SharedTypeView<TypeStructure> get neverType; + SharedTypeView get neverType; /// Returns the type `Null`. - SharedTypeView<TypeStructure> get nullType; + SharedTypeView get nullType; /// Returns the type `Object?`. - SharedTypeView<TypeStructure> get objectQuestionType; + SharedTypeView get objectQuestionType; /// Returns the type `Object`. - SharedTypeView<TypeStructure> get objectType; + SharedTypeView get objectType; /// Returns the unknown type schema (`_`) used in type inference. - SharedTypeSchemaView<TypeStructure> get unknownType; + SharedTypeSchemaView get unknownType; /// Returns the type `Future` with omitted nullability and type argument /// [argumentType]. @@ -63,8 +57,7 @@ /// [TypeAnalyzerOperationsMixin] and implement [futureTypeInternal] to /// receive a concrete implementation of [futureType] instead of implementing /// [futureType] directly. - SharedTypeView<TypeStructure> futureType( - SharedTypeView<TypeStructure> argumentType); + SharedTypeView futureType(SharedTypeView argumentType); /// [futureTypeInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of [futureType] @@ -89,7 +82,7 @@ /// [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 @@ /// [TypeAnalyzerOperationsMixin] and implement [futureTypeInternal] to /// receive a concrete implementation of [futureTypeSchema] instead of /// implementing [futureTypeSchema] directly. - SharedTypeSchemaView<TypeStructure> futureTypeSchema( - SharedTypeSchemaView<TypeStructure> 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 @@ /// Examples of types derived from a class declarations are `A`, `A?`, `A*`, /// `B<T, S>`, where `A` and `B` are the names of class declarations or /// extension type declarations, `T` and `S` are types. - TypeDeclarationKind? getTypeDeclarationKind( - SharedTypeView<TypeStructure> 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 @@ /// and `B` are class declarations or extension type declarations, `T` and /// `S` are type schemas. TypeDeclarationKind? getTypeSchemaDeclarationKind( - SharedTypeSchemaView<TypeStructure> 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<TypeStructure> glb( - SharedTypeView<TypeStructure> type1, SharedTypeView<TypeStructure> 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 @@ /// 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<TypeStructure> greatestClosure( - SharedTypeSchemaView<TypeStructure> 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<SharedTypeParameterStructure<TypeStructure>> - typeParametersToEliminate); + SharedType greatestClosureOfTypeInternal(covariant SharedType type, + List<SharedTypeParameter> 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<TypeStructure> type); + bool isAlwaysExhaustiveType(SharedTypeView type); /// Returns `true` if [fromType] is assignable to [toType]. - bool isAssignableTo(SharedTypeView<TypeStructure> fromType, - SharedTypeView<TypeStructure> 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<T1, ..., Tn>`, `E<T1, ..., Tn>?`, or /// `E<T1, ..., Tn>*` 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<T1, ..., Tn>`, `A<T1, ..., Tn>?`, or /// `A<T1, ..., Tn>*` 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<X>` for any /// type `X`. - bool isInterfaceTypeInternal(TypeStructure type); + bool isInterfaceTypeInternal(covariant SharedType type); @override - bool isNever(SharedTypeView<TypeStructure> 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<TypeStructure> 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<TypeStructure> type); + bool isTypeParameterType(SharedTypeView type); /// Returns `true` if the type [type] satisfies the type schema [typeSchema]. bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView<TypeStructure> typeSchema, - required SharedTypeView<TypeStructure> 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<TypeStructure> iterableTypeSchema( - SharedTypeSchemaView<TypeStructure> 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<SharedTypeParameterStructure<TypeStructure>> - typeParametersToEliminate); + SharedType leastClosureOfTypeInternal(covariant SharedType type, + List<SharedTypeParameter> typeParametersToEliminate); /// Returns the type `List`, with type argument [elementType]. /// @@ -259,8 +246,7 @@ /// [TypeAnalyzerOperationsMixin] and implement [listTypeInternal] to receive /// a concrete implementation of [listType] instead of implementing [listType] /// directly. - SharedTypeView<TypeStructure> listType( - SharedTypeView<TypeStructure> elementType); + SharedTypeView listType(SharedTypeView elementType); /// [listTypeInternal] should be implemented by concrete classes implementing /// [TypeAnalyzerOperations]. The implementations of [listType] and @@ -284,7 +270,7 @@ /// [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 @@ /// [TypeAnalyzerOperationsMixin] and implement [listTypeInternal] to receive /// a concrete implementation of [listTypeSchema] instead of implementing /// [listTypeSchema] directly. - SharedTypeSchemaView<TypeStructure> listTypeSchema( - SharedTypeSchemaView<TypeStructure> 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<TypeStructure> lub( - SharedTypeView<TypeStructure> type1, SharedTypeView<TypeStructure> 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 @@ /// 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 @@ /// [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 @@ /// [TypeAnalyzerOperationsMixin] and implement [makeNullableInternal] to /// receive a concrete implementation of [makeTypeSchemaNullable] instead of /// implementing [makeTypeSchemaNullable] directly. - SharedTypeSchemaView<TypeStructure> makeTypeSchemaNullable( - SharedTypeSchemaView<TypeStructure> typeSchema); + SharedTypeSchemaView makeTypeSchemaNullable(SharedTypeSchemaView typeSchema); /// Returns the type `Map`, with type arguments. /// @@ -365,9 +349,9 @@ /// [TypeAnalyzerOperationsMixin] and implement [mapTypeInternal] to receive a /// concrete implementation of [mapType] instead of implementing [mapType] /// directly. - SharedTypeView<TypeStructure> mapType({ - required SharedTypeView<TypeStructure> keyType, - required SharedTypeView<TypeStructure> valueType, + SharedTypeView mapType({ + required SharedTypeView keyType, + required SharedTypeView valueType, }); /// [mapTypeInternal] should be implemented by concrete classes implementing @@ -393,9 +377,9 @@ /// [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 @@ /// [TypeAnalyzerOperationsMixin] and implement [mapTypeInternal] to receive a /// concrete implementation of [makeTypeSchemaNullable] instead of /// implementing [makeTypeSchemaNullable] directly. - SharedTypeSchemaView<TypeStructure> mapTypeSchema({ - required SharedTypeSchemaView<TypeStructure> keyTypeSchema, - required SharedTypeSchemaView<TypeStructure> valueTypeSchema, + SharedTypeSchemaView mapTypeSchema({ + required SharedTypeSchemaView keyTypeSchema, + required SharedTypeSchemaView valueTypeSchema, }); /// If [type] takes the form `FutureOr<T>`, `FutureOr<T>?`, or `FutureOr<T>*` @@ -417,8 +401,7 @@ /// [TypeAnalyzerOperationsMixin] and implement [matchFutureOrInternal] to /// receive a concrete implementation of [matchFutureOr] instead of /// implementing [matchFutureOr] directly. - SharedTypeView<TypeStructure>? matchFutureOr( - SharedTypeView<TypeStructure> type); + SharedTypeView? matchFutureOr(SharedTypeView type); /// [matchFutureOrInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of @@ -443,7 +426,7 @@ /// [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 @@ /// by `foo`. /// /// X foo<X>(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<T>?` for some `T`, returns /// the type `T`. Otherwise returns `null`. @@ -463,8 +447,7 @@ /// [TypeAnalyzerOperationsMixin] and implement [matchIterableTypeInternal] to /// receive a concrete implementation of [matchIterableType] instead of /// implementing [matchIterableType] directly. - SharedTypeView<TypeStructure>? matchIterableType( - SharedTypeView<TypeStructure> type); + SharedTypeView? matchIterableType(SharedTypeView type); /// [matchIterableTypeInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of @@ -489,7 +472,7 @@ /// [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<T>?` (or a subtype thereof), /// for some `T`, returns the type `T`. Otherwise returns `null`. @@ -498,25 +481,21 @@ /// [TypeAnalyzerOperationsMixin] and implement [matchIterableTypeInternal] to /// receive a concrete implementation of [matchIterableTypeSchema] instead of /// implementing [matchIterableTypeSchema] directly. - SharedTypeSchemaView<TypeStructure>? matchIterableTypeSchema( - SharedTypeSchemaView<TypeStructure> typeSchema); + SharedTypeSchemaView? matchIterableTypeSchema( + SharedTypeSchemaView typeSchema); /// If [type] is a subtype of the type `List<T>?` for some `T`, returns the /// type `T`. Otherwise returns `null`. - SharedTypeView<TypeStructure>? matchListType( - SharedTypeView<TypeStructure> type); + SharedTypeView? matchListType(SharedTypeView type); /// If [type] is a subtype of the type `Map<K, V>?` for some `K` and `V`, /// returns these `K` and `V`. Otherwise returns `null`. - ({ - SharedTypeView<TypeStructure> keyType, - SharedTypeView<TypeStructure> valueType - })? matchMapType(SharedTypeView<TypeStructure> type); + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type); /// If [type] is a subtype of the type `Stream<T>?` for some `T`, returns /// the type `T`. Otherwise returns `null`. - SharedTypeView<TypeStructure>? matchStreamType( - SharedTypeView<TypeStructure> 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 @@ /// /// If [type] isn't introduced by a class, mixin, enum, or extension type, /// returns null. - TypeDeclarationMatchResult<TypeDeclarationType, TypeDeclaration, - TypeStructure>? matchTypeDeclarationTypeInternal(TypeStructure type); + TypeDeclarationMatchResult<TypeDeclarationType, TypeDeclaration>? + 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 @@ /// return f(x); /// } /// } - TypeStructure? matchTypeParameterBoundInternal(TypeStructure type); + SharedType? matchTypeParameterBoundInternal(covariant SharedType type); /// If [typeSchema] takes the form `FutureOr<T>`, `FutureOr<T>?`, or /// `FutureOr<T>*` for some `T`, returns the type schema `T`. Otherwise @@ -556,17 +535,16 @@ /// [TypeAnalyzerOperationsMixin] and implement [matchFutureOrInternal] to /// receive a concrete implementation of [matchTypeSchemaFutureOr] instead of /// implementing [matchTypeSchemaFutureOr] directly. - SharedTypeSchemaView<TypeStructure>? matchTypeSchemaFutureOr( - SharedTypeSchemaView<TypeStructure> typeSchema); + SharedTypeSchemaView? matchTypeSchemaFutureOr( + SharedTypeSchemaView typeSchema); /// Computes `NORM` of [type]. /// https://github.com/dart-lang/language /// See `resources/type-system/normalization.md` - SharedTypeView<TypeStructure> normalize(SharedTypeView<TypeStructure> type); + SharedTypeView normalize(SharedTypeView type); @override - SharedTypeView<TypeStructure> promoteToNonNull( - SharedTypeView<TypeStructure> type); + SharedTypeView promoteToNonNull(SharedTypeView type); /// Builds the client specific record type. /// @@ -574,9 +552,9 @@ /// [TypeAnalyzerOperationsMixin] and implement [recordTypeInternal] to /// receive a concrete implementation of [recordType] instead of implementing /// [recordType] directly. - SharedTypeView<TypeStructure> recordType( - {required List<SharedTypeView<TypeStructure>> positional, - required List<(String, SharedTypeView<TypeStructure>)> named}); + SharedTypeView recordType( + {required List<SharedTypeView> positional, + required List<(String, SharedTypeView)> named}); /// [recordTypeInternal] should be implemented by concrete classes /// implementing [TypeAnalyzerOperations]. The implementations of [recordType] @@ -601,9 +579,9 @@ /// [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<TypeStructure> positional, - required List<(String, TypeStructure)> named}); + SharedType recordTypeInternal( + {required List<SharedType> positional, + required List<(String, SharedType)> named}); /// Builds the client specific record type schema. /// @@ -611,17 +589,15 @@ /// [TypeAnalyzerOperationsMixin] and implement [recordTypeInternal] to /// receive a concrete implementation of [recordTypeSchema] instead of /// implementing [recordTypeSchema] directly. - SharedTypeSchemaView<TypeStructure> recordTypeSchema( - {required List<SharedTypeSchemaView<TypeStructure>> positional, - required List<(String, SharedTypeSchemaView<TypeStructure>)> named}); + SharedTypeSchemaView recordTypeSchema( + {required List<SharedTypeSchemaView> positional, + required List<(String, SharedTypeSchemaView)> named}); /// Returns the type schema `Stream`, with type argument [elementTypeSchema]. - SharedTypeSchemaView<TypeStructure> streamTypeSchema( - SharedTypeSchemaView<TypeStructure> elementTypeSchema); + SharedTypeSchemaView streamTypeSchema(SharedTypeSchemaView elementTypeSchema); @override - SharedTypeView<TypeStructure>? tryPromoteToType( - SharedTypeView<TypeStructure> to, SharedTypeView<TypeStructure> from); + SharedTypeView? tryPromoteToType(SharedTypeView to, SharedTypeView from); /// Returns `true` if [leftType] is a subtype of the greatest closure of /// [rightSchema]. @@ -636,8 +612,8 @@ /// implement [isSubtypeOfInternal] and mix in [TypeAnalyzerOperationsMixin] /// to receive an implementation of [typeIsSubtypeOfTypeSchema] instead of /// implementing it directly. - bool typeIsSubtypeOfTypeSchema(SharedTypeView<TypeStructure> leftType, - SharedTypeSchemaView<TypeStructure> rightSchema); + bool typeIsSubtypeOfTypeSchema( + SharedTypeView leftType, SharedTypeSchemaView rightSchema); /// Computes the greatest lower bound of [typeSchema1] and [typeSchema2]. /// @@ -645,9 +621,8 @@ /// [TypeAnalyzerOperationsMixin] and implement [glbInternal] to receive a /// concrete implementation of [typeSchemaGlb] instead of implementing /// [typeSchemaGlb] directly. - SharedTypeSchemaView<TypeStructure> typeSchemaGlb( - SharedTypeSchemaView<TypeStructure> typeSchema1, - SharedTypeSchemaView<TypeStructure> typeSchema2); + SharedTypeSchemaView typeSchemaGlb( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2); /// Returns `true` if the least closure of [leftSchema] is a subtype of /// [rightType]. @@ -662,8 +637,8 @@ /// implement [isSubtypeOfInternal] and mix in [TypeAnalyzerOperationsMixin] /// to receive an implementation of [typeSchemaIsSubtypeOfType] instead of /// implementing it directly. - bool typeSchemaIsSubtypeOfType(SharedTypeSchemaView<TypeStructure> leftSchema, - SharedTypeView<TypeStructure> 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 @@ /// to receive an implementation of [typeSchemaIsSubtypeOfTypeSchema] instead /// of implementing it directly. bool typeSchemaIsSubtypeOfTypeSchema( - SharedTypeSchemaView<TypeStructure> leftSchema, - SharedTypeSchemaView<TypeStructure> rightSchema); + SharedTypeSchemaView leftSchema, SharedTypeSchemaView rightSchema); /// Computes the least upper bound of [typeSchema1] and [typeSchema2]. /// @@ -688,141 +662,114 @@ /// [TypeAnalyzerOperationsMixin] and implement [lubInternal] to receive a /// concrete implementation of [typeSchemaLub] instead of implementing /// [typeSchemaLub] directly. - SharedTypeSchemaView<TypeStructure> typeSchemaLub( - SharedTypeSchemaView<TypeStructure> typeSchema1, - SharedTypeSchemaView<TypeStructure> typeSchema2); + SharedTypeSchemaView typeSchemaLub( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2); /// Converts a type into a corresponding type schema. - SharedTypeSchemaView<TypeStructure> typeToSchema( - SharedTypeView<TypeStructure> type); + SharedTypeSchemaView typeToSchema(SharedTypeView type); /// Returns [type] suffixed with the [suffix]. - TypeStructure withNullabilitySuffixInternal( - TypeStructure type, NullabilitySuffix suffix); + SharedType withNullabilitySuffixInternal( + covariant SharedType type, NullabilitySuffix suffix); - TypeConstraintGenerator< - TypeStructure, - SharedNamedFunctionParameterStructure<TypeStructure>, - Variable, - TypeParameterStructure, - TypeDeclarationType, - TypeDeclaration, + TypeConstraintGenerator<Variable, TypeDeclarationType, TypeDeclaration, Object> createTypeConstraintGenerator( - {required TypeConstraintGenerationDataForTesting<TypeStructure, - TypeParameterStructure, Variable, Object>? + {required TypeConstraintGenerationDataForTesting<Variable, Object>? typeConstraintGenerationDataForTesting, - required List<TypeParameterStructure> typeParametersToInfer, - required TypeAnalyzerOperations<TypeStructure, Variable, - TypeParameterStructure, TypeDeclarationType, TypeDeclaration> + required List<SharedTypeParameterView> typeParametersToInfer, + required TypeAnalyzerOperations<Variable, TypeDeclarationType, + TypeDeclaration> typeAnalyzerOperations, required bool inferenceUsingBoundsIsEnabled}); - MergedTypeConstraint<TypeStructure, TypeParameterStructure, Variable, - TypeDeclarationType, TypeDeclaration> + MergedTypeConstraint<Variable, TypeDeclarationType, TypeDeclaration> mergeInConstraintsFromBound( - {required TypeParameterStructure typeParameterToInfer, - required List<TypeParameterStructure> typeParametersToInfer, - required TypeStructure lower, + {required SharedTypeParameter typeParameterToInfer, + required List<SharedTypeParameterView> typeParametersToInfer, + required SharedType lower, required Map< - TypeParameterStructure, - MergedTypeConstraint<TypeStructure, TypeParameterStructure, - Variable, TypeDeclarationType, TypeDeclaration>> + SharedTypeParameter, + MergedTypeConstraint<Variable, TypeDeclarationType, + TypeDeclaration>> inferencePhaseConstraints, - required TypeConstraintGenerationDataForTesting<TypeStructure, - TypeParameterStructure, Variable, Object>? + required TypeConstraintGenerationDataForTesting<Variable, Object>? dataForTesting, required bool inferenceUsingBoundsIsEnabled}); } -mixin TypeAnalyzerOperationsMixin< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> +mixin TypeAnalyzerOperationsMixin<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> implements - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> { + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> { @override - SharedTypeView<TypeStructure> futureType( - SharedTypeView<TypeStructure> argumentType) { + SharedTypeView futureType(SharedTypeView argumentType) { return new SharedTypeView( futureTypeInternal(argumentType.unwrapTypeView())); } @override - SharedTypeSchemaView<TypeStructure> futureTypeSchema( - SharedTypeSchemaView<TypeStructure> argumentTypeSchema) { + SharedTypeSchemaView futureTypeSchema( + SharedTypeSchemaView argumentTypeSchema) { return new SharedTypeSchemaView( futureTypeInternal(argumentTypeSchema.unwrapTypeSchemaView())); } @override - TypeDeclarationKind? getTypeDeclarationKind( - SharedTypeView<TypeStructure> type) { + TypeDeclarationKind? getTypeDeclarationKind(SharedTypeView type) { return getTypeDeclarationKindInternal(type.unwrapTypeView()); } @override TypeDeclarationKind? getTypeSchemaDeclarationKind( - SharedTypeSchemaView<TypeStructure> typeSchema) { + SharedTypeSchemaView typeSchema) { return getTypeDeclarationKindInternal(typeSchema.unwrapTypeSchemaView()); } @override - SharedTypeView<TypeStructure> glb(SharedTypeView<TypeStructure> type1, - SharedTypeView<TypeStructure> type2) { + SharedTypeView glb(SharedTypeView type1, SharedTypeView type2) { return new SharedTypeView( glbInternal(type1.unwrapTypeView(), type2.unwrapTypeView())); } @override - bool isSubtypeOf(SharedTypeView<TypeStructure> leftType, - SharedTypeView<TypeStructure> rightType) { + bool isSubtypeOf(SharedTypeView leftType, SharedTypeView rightType) { return isSubtypeOfInternal( leftType.unwrapTypeView(), rightType.unwrapTypeView()); } @override - SharedTypeView<TypeStructure> listType( - SharedTypeView<TypeStructure> elementType) { + SharedTypeView listType(SharedTypeView elementType) { return new SharedTypeView(listTypeInternal(elementType.unwrapTypeView())); } @override - SharedTypeSchemaView<TypeStructure> listTypeSchema( - SharedTypeSchemaView<TypeStructure> elementTypeSchema) { + SharedTypeSchemaView listTypeSchema(SharedTypeSchemaView elementTypeSchema) { return new SharedTypeSchemaView( listTypeInternal(elementTypeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView<TypeStructure> lub(SharedTypeView<TypeStructure> type1, - SharedTypeView<TypeStructure> type2) { + SharedTypeView lub(SharedTypeView type1, SharedTypeView type2) { return new SharedTypeView( lubInternal(type1.unwrapTypeView(), type2.unwrapTypeView())); } @override - SharedTypeView<TypeStructure> makeNullable( - SharedTypeView<TypeStructure> type) { + SharedTypeView makeNullable(SharedTypeView type) { return new SharedTypeView(makeNullableInternal(type.unwrapTypeView())); } @override - SharedTypeSchemaView<TypeStructure> makeTypeSchemaNullable( - SharedTypeSchemaView<TypeStructure> typeSchema) { + SharedTypeSchemaView makeTypeSchemaNullable(SharedTypeSchemaView typeSchema) { return new SharedTypeSchemaView( makeNullableInternal(typeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView<TypeStructure> mapType({ - required SharedTypeView<TypeStructure> keyType, - required SharedTypeView<TypeStructure> valueType, + SharedTypeView mapType({ + required SharedTypeView keyType, + required SharedTypeView valueType, }) { return new SharedTypeView(mapTypeInternal( keyType: keyType.unwrapTypeView(), @@ -830,119 +777,111 @@ } @override - SharedTypeSchemaView<TypeStructure> mapTypeSchema( - {required SharedTypeSchemaView<TypeStructure> keyTypeSchema, - required SharedTypeSchemaView<TypeStructure> valueTypeSchema}) { + SharedTypeSchemaView mapTypeSchema( + {required SharedTypeSchemaView keyTypeSchema, + required SharedTypeSchemaView valueTypeSchema}) { return new SharedTypeSchemaView(mapTypeInternal( keyType: keyTypeSchema.unwrapTypeSchemaView(), valueType: valueTypeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView<TypeStructure>? matchFutureOr( - SharedTypeView<TypeStructure> type) { + SharedTypeView? matchFutureOr(SharedTypeView type) { return matchFutureOrInternal(type.unwrapTypeView())?.wrapSharedTypeView(); } @override - SharedTypeView<TypeStructure>? matchIterableType( - SharedTypeView<TypeStructure> type) { + SharedTypeView? matchIterableType(SharedTypeView type) { return matchIterableTypeInternal(type.unwrapTypeView()) ?.wrapSharedTypeView(); } @override - SharedTypeSchemaView<TypeStructure>? matchIterableTypeSchema( - SharedTypeSchemaView<TypeStructure> typeSchema) { + SharedTypeSchemaView? matchIterableTypeSchema( + SharedTypeSchemaView typeSchema) { return matchIterableTypeInternal(typeSchema.unwrapTypeSchemaView()) ?.wrapSharedTypeSchemaView(); } @override - SharedTypeSchemaView<TypeStructure>? matchTypeSchemaFutureOr( - SharedTypeSchemaView<TypeStructure> typeSchema) { + SharedTypeSchemaView? matchTypeSchemaFutureOr( + SharedTypeSchemaView typeSchema) { return matchFutureOrInternal(typeSchema.unwrapTypeSchemaView()) ?.wrapSharedTypeSchemaView(); } @override - SharedTypeView<TypeStructure> recordType( - {required List<SharedTypeView<TypeStructure>> positional, - required List<(String, SharedTypeView<TypeStructure>)> named}) { + SharedTypeView recordType( + {required List<SharedTypeView> positional, + required List<(String, SharedTypeView)> named}) { return new SharedTypeView(recordTypeInternal( - positional: positional.cast<TypeStructure>(), - named: named.cast<(String, TypeStructure)>())); + positional: positional.cast<SharedType>(), + named: named.cast<(String, SharedType)>())); } @override - SharedTypeSchemaView<TypeStructure> recordTypeSchema( - {required List<SharedTypeSchemaView<TypeStructure>> positional, - required List<(String, SharedTypeSchemaView<TypeStructure>)> named}) { + SharedTypeSchemaView recordTypeSchema( + {required List<SharedTypeSchemaView> positional, + required List<(String, SharedTypeSchemaView)> named}) { return new SharedTypeSchemaView(recordTypeInternal( - positional: positional.cast<TypeStructure>(), - named: named.cast<(String, TypeStructure)>())); + positional: positional.cast<SharedType>(), + named: named.cast<(String, SharedType)>())); } @override - bool typeIsSubtypeOfTypeSchema(SharedTypeView<TypeStructure> leftType, - SharedTypeSchemaView<TypeStructure> rightSchema) { + bool typeIsSubtypeOfTypeSchema( + SharedTypeView leftType, SharedTypeSchemaView rightSchema) { return isSubtypeOfInternal( leftType.unwrapTypeView(), rightSchema.unwrapTypeSchemaView()); } @override - SharedTypeSchemaView<TypeStructure> typeSchemaGlb( - SharedTypeSchemaView<TypeStructure> typeSchema1, - SharedTypeSchemaView<TypeStructure> typeSchema2) { + SharedTypeSchemaView typeSchemaGlb( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2) { return new SharedTypeSchemaView(glbInternal( typeSchema1.unwrapTypeSchemaView(), typeSchema2.unwrapTypeSchemaView())); } @override - bool typeSchemaIsSubtypeOfType(SharedTypeSchemaView<TypeStructure> leftSchema, - SharedTypeView<TypeStructure> rightType) { + bool typeSchemaIsSubtypeOfType( + SharedTypeSchemaView leftSchema, SharedTypeView rightType) { return isSubtypeOfInternal( leftSchema.unwrapTypeSchemaView(), rightType.unwrapTypeView()); } @override bool typeSchemaIsSubtypeOfTypeSchema( - SharedTypeSchemaView<TypeStructure> leftSchema, - SharedTypeSchemaView<TypeStructure> rightSchema) { + SharedTypeSchemaView leftSchema, SharedTypeSchemaView rightSchema) { return isSubtypeOfInternal( leftSchema.unwrapTypeSchemaView(), rightSchema.unwrapTypeSchemaView()); } @override - SharedTypeSchemaView<TypeStructure> typeSchemaLub( - SharedTypeSchemaView<TypeStructure> typeSchema1, - SharedTypeSchemaView<TypeStructure> typeSchema2) { + SharedTypeSchemaView typeSchemaLub( + SharedTypeSchemaView typeSchema1, SharedTypeSchemaView typeSchema2) { return new SharedTypeSchemaView(lubInternal( typeSchema1.unwrapTypeSchemaView(), typeSchema2.unwrapTypeSchemaView())); } @override - SharedTypeSchemaView<TypeStructure> typeToSchema( - SharedTypeView<TypeStructure> type) { + SharedTypeSchemaView typeToSchema(SharedTypeView type) { return new SharedTypeSchemaView(type.unwrapTypeView()); } @override - MergedTypeConstraint<TypeStructure, TypeParameterStructure, Variable, - TypeDeclarationType, TypeDeclaration> + MergedTypeConstraint<Variable, TypeDeclarationType, TypeDeclaration> mergeInConstraintsFromBound( - {required TypeParameterStructure typeParameterToInfer, - required List<TypeParameterStructure> typeParametersToInfer, - required TypeStructure lower, + {required SharedTypeParameter typeParameterToInfer, + required List<SharedTypeParameterView> typeParametersToInfer, + required SharedType lower, required Map< - TypeParameterStructure, - MergedTypeConstraint<TypeStructure, TypeParameterStructure, - Variable, TypeDeclarationType, TypeDeclaration>> + SharedTypeParameter, + MergedTypeConstraint<Variable, TypeDeclarationType, + TypeDeclaration>> inferencePhaseConstraints, - required TypeConstraintGenerationDataForTesting<TypeStructure, - TypeParameterStructure, Variable, Object>? + required TypeConstraintGenerationDataForTesting<Variable, Object>? dataForTesting, required bool inferenceUsingBoundsIsEnabled}) { // The type parameter's bound may refer to itself (or other type @@ -967,17 +906,11 @@ // 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<TypeStructure>, - Variable, - TypeParameterStructure, - TypeDeclarationType, - TypeDeclaration, + TypeConstraintGenerator<Variable, TypeDeclarationType, TypeDeclaration, Object> typeConstraintGatherer = createTypeConstraintGenerator( typeConstraintGenerationDataForTesting: null, @@ -988,19 +921,13 @@ lower, typeParameterToInferBound, leftSchema: true, astNodeForTesting: null); Map< - TypeParameterStructure, - MergedTypeConstraint< - TypeStructure, - TypeParameterStructure, - Variable, - TypeDeclarationType, + SharedTypeParameter, + MergedTypeConstraint<Variable, TypeDeclarationType, TypeDeclaration>> constraintsPerTypeVariable = typeConstraintGatherer.computeConstraints(); - for (TypeParameterStructure typeParameter - in constraintsPerTypeVariable.keys) { - MergedTypeConstraint<TypeStructure, TypeParameterStructure, Variable, - TypeDeclarationType, TypeDeclaration> constraint = - constraintsPerTypeVariable[typeParameter]!; + for (SharedTypeParameter typeParameter in constraintsPerTypeVariable.keys) { + MergedTypeConstraint<Variable, TypeDeclarationType, TypeDeclaration> + constraint = constraintsPerTypeVariable[typeParameter]!; constraint.origin = new TypeConstraintFromExtendsClause( typeParameterName: typeParameterToInfer.displayName, boundType: new SharedTypeView(typeParameterToInferBound), @@ -1022,11 +949,7 @@ /// Abstract interface of a type constraint generator. abstract class TypeConstraintGenerator< - TypeStructure extends SharedTypeStructure<TypeStructure>, - FunctionParameterStructure extends SharedNamedFunctionParameterStructure< - TypeStructure>, Variable extends Object, - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, TypeDeclarationType extends Object, TypeDeclaration extends Object, AstNode extends Object> { @@ -1052,20 +975,20 @@ bool get enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr; /// Abstract type operations to be used in the matching methods. - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> get typeAnalyzerOperations; + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> + get typeAnalyzerOperations; /// Type parameters being constrained by [TypeConstraintGenerator]. - Iterable<TypeParameterStructure> get typeParametersToConstrain; + Iterable<SharedTypeParameter> 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 @@ /// 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<TypeParameterStructure> typeParametersToEliminate, + List<SharedTypeParameter> 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<TypeStructure>? getTypeArgumentsAsInstanceOf( + List<SharedType>? getTypeArgumentsAsInstanceOf( TypeDeclarationType type, TypeDeclaration typeDeclaration); /// Creates fresh type parameters, instantiates the non-generic parts of [p] @@ -1095,16 +1018,11 @@ /// 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<TypeParameterStructure> typeParametersToEliminate + SharedType, + SharedType, { + List<SharedTypeParameter> typeParametersToEliminate }) instantiateFunctionTypesAndProvideFreshTypeParameters( - SharedFunctionTypeStructure<TypeStructure, TypeParameterStructure, - FunctionParameterStructure> - p, - SharedFunctionTypeStructure<TypeStructure, TypeParameterStructure, - FunctionParameterStructure> - q, + covariant SharedFunctionType p, covariant SharedFunctionType q, {required bool leftSchema}); /// Matches [p] against [q]. @@ -1119,12 +1037,9 @@ /// 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<TypeStructure, TypeParameterStructure, - FunctionParameterStructure> && - q is SharedFunctionTypeStructure<TypeStructure, TypeParameterStructure, - FunctionParameterStructure>) { + 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 @@ /// 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<P0>` the match holds under constraint set `C1 + C2`: NullabilitySuffix pNullability = p.nullabilitySuffix; @@ -1160,7 +1075,7 @@ // If `Future<P0>` 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 @@ /// 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 @@ /// 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<TypeStructure> || - q is! SharedRecordTypeStructure<TypeStructure>) { + if (p is! SharedRecordType || q is! SharedRecordType) { return false; } @@ -1280,17 +1194,17 @@ /// 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<Q0>` 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<P0>` 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 @@ /// 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 @@ // 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 @@ // 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 @@ /// 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 @@ TypeDeclarationMatchResult( typeDeclarationKind: TypeDeclarationKind pTypeDeclarationKind, typeDeclaration: TypeDeclaration pDeclarationObject, - typeArguments: List<TypeStructure> pTypeArguments + typeArguments: List<SharedType> pTypeArguments ), TypeDeclarationMatchResult( typeDeclarationKind: TypeDeclarationKind qTypeDeclarationKind, typeDeclaration: TypeDeclaration qDeclarationObject, - typeArguments: List<TypeStructure> qTypeArguments + typeArguments: List<SharedType> qTypeArguments ) ) when pTypeDeclarationKind == qTypeDeclarationKind && @@ -1476,15 +1390,15 @@ /// 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 @@ // 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 @@ // 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 @@ // 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 @@ // constraints: // If `P` is a record type or `Record`. if (typeAnalyzerOperations.isDartCoreRecordInternal(q)) { - if (p is SharedRecordTypeStructure<TypeStructure>) { + if (p is SharedRecordType) { return true; } } @@ -1639,7 +1553,7 @@ /// 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<TypeStructure> p, SharedTypeView<TypeStructure> q, + SharedTypeSchemaView p, SharedTypeView q, {required AstNode? astNodeForTesting}); /// Matches type [p] against type schema [q] as a subtype against supertype, @@ -1656,7 +1570,7 @@ /// 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<TypeStructure> p, SharedTypeSchemaView<TypeStructure> q, + SharedTypeView p, SharedTypeSchemaView q, {required AstNode? astNodeForTesting}); /// Restores the constraint generator to [state]. @@ -1669,15 +1583,8 @@ /// /// See the documentation on /// [performSubtypeConstraintGenerationForFunctionTypes] for details. - bool _handleGenericFunctionTypes( - SharedFunctionTypeStructure<TypeStructure, TypeParameterStructure, - FunctionParameterStructure> - p, - SharedFunctionTypeStructure<TypeStructure, TypeParameterStructure, - FunctionParameterStructure> - 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 <T0 extends B00, ..., Tn extends B0n>F0 is a @@ -1749,14 +1656,8 @@ /// See the documentation on /// [performSubtypeConstraintGenerationForFunctionTypes] for details. bool _handleNonGenericFunctionTypes( - SharedFunctionTypeStructure<TypeStructure, TypeParameterStructure, - FunctionParameterStructure> - p, - SharedFunctionTypeStructure<TypeStructure, TypeParameterStructure, - FunctionParameterStructure> - 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 @@ /// If returns `false`, the constraints are unchanged. bool _interfaceTypeArguments( TypeDeclaration declaration, - List<TypeStructure> pTypeArguments, - List<TypeStructure> qTypeArguments, + List<SharedType> pTypeArguments, + List<SharedType> qTypeArguments, bool leftSchema, {required AstNode? astNodeForTesting}) { assert(pTypeArguments.length == qTypeArguments.length); @@ -1897,8 +1798,8 @@ 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 @@ /// 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 @@ ), TypeDeclarationMatchResult( typeDeclaration: TypeDeclaration qTypeDeclaration, - typeArguments: List<TypeStructure> qTypeArguments + typeArguments: List<SharedType> qTypeArguments ) )) { if (getTypeArgumentsAsInstanceOf(pTypeDeclarationType, qTypeDeclaration) - case List<TypeStructure> typeArguments) { + case List<SharedType> typeArguments) { return _interfaceTypeArguments( qTypeDeclaration, typeArguments, qTypeArguments, leftSchema, astNodeForTesting: astNodeForTesting); @@ -1965,36 +1866,21 @@ } /// Returns the set of type constraints that was gathered. - Map< - TypeParameterStructure, - MergedTypeConstraint<TypeStructure, TypeParameterStructure, Variable, - TypeDeclarationType, TypeDeclaration>> computeConstraints(); + Map<SharedTypeParameter, + MergedTypeConstraint<Variable, TypeDeclarationType, TypeDeclaration>> + computeConstraints(); } mixin TypeConstraintGeneratorMixin< - TypeStructure extends SharedTypeStructure<TypeStructure>, - // 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<TypeStructure>, TypeDeclarationType extends Object, TypeDeclaration extends Object, AstNode extends Object> - on TypeConstraintGenerator< - TypeStructure, - FunctionParameterStructure, - Variable, - TypeParameterStructure, - TypeDeclarationType, - TypeDeclaration, + on TypeConstraintGenerator<Variable, TypeDeclarationType, TypeDeclaration, AstNode> { @override bool performSubtypeConstraintGenerationLeftSchema( - SharedTypeSchemaView<TypeStructure> p, SharedTypeView<TypeStructure> q, + SharedTypeSchemaView p, SharedTypeView q, {required AstNode? astNodeForTesting}) { return performSubtypeConstraintGenerationInternal( p.unwrapTypeSchemaView(), q.unwrapTypeView(), @@ -2003,7 +1889,7 @@ @override bool performSubtypeConstraintGenerationRightSchema( - SharedTypeView<TypeStructure> p, SharedTypeSchemaView<TypeStructure> q, + SharedTypeView p, SharedTypeSchemaView q, {required AstNode? astNodeForTesting}) { return performSubtypeConstraintGenerationInternal( p.unwrapTypeView(), q.unwrapTypeSchemaView(), @@ -2035,11 +1921,12 @@ /// its components that can be used for the further analysis of the type in the /// algorithms related to type inference. class TypeDeclarationMatchResult<TypeDeclarationType extends Object, - TypeDeclaration extends Object, Type extends Object> { + 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, an enum, a mixin, or an extension type. final TypeDeclaration typeDeclaration; - /// Type arguments instantiating [typeDeclaration] to the matched type. + /// SharedTypeStructureInterface arguments instantiating [typeDeclaration] to + /// the matched type. /// /// If [typeDeclaration] is not generic, [typeArguments] is an empty list. - final List<Type> typeArguments; + final List<SharedType> 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 7a8a79d..23c6e06 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 @@ /// /// We require that `typeParameter <: constraint` if `isUpper` is true, and /// `constraint <: typeParameter` otherwise. -class GeneratedTypeConstraint< - TypeStructure extends SharedTypeStructure<TypeStructure>, - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - Variable extends Object> { +class GeneratedTypeConstraint<Variable extends Object> { /// The type parameter that is constrained by [constraint]. - final TypeParameterStructure typeParameter; + final SharedTypeParameterView typeParameter; /// The type schema constraining the type parameter. - final SharedTypeSchemaView<TypeStructure> constraint; + final SharedTypeSchemaView constraint; /// True if `typeParameter <: constraint`, and false otherwise. /// @@ -38,12 +35,8 @@ } /// A constraint on a type parameter that we're inferring. -class MergedTypeConstraint< - TypeStructure extends SharedTypeStructure<TypeStructure>, - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - Variable extends Object, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> { +class MergedTypeConstraint<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> { /// 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 @@ /// 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<TypeStructure> 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 @@ /// /// Here the [lower] will be `String` and the upper bound will be `num`, /// which cannot be satisfied, so this is ill typed. - SharedTypeSchemaView<TypeStructure> upper; + SharedTypeSchemaView upper; /// Where this constraint comes from, used for error messages. - TypeConstraintOrigin<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> origin; + TypeConstraintOrigin<Variable, TypeDeclarationType, TypeDeclaration> origin; MergedTypeConstraint( {required this.lower, required this.upper, required this.origin}); MergedTypeConstraint.fromExtends( {required String typeParameterName, - required SharedTypeView<TypeStructure> boundType, - required SharedTypeView<TypeStructure> extendsType, - required TypeAnalyzerOperations<TypeStructure, Variable, - TypeParameterStructure, TypeDeclarationType, TypeDeclaration> + required SharedTypeView boundType, + required SharedTypeView extendsType, + required TypeAnalyzerOperations<Variable, TypeDeclarationType, + TypeDeclaration> typeAnalyzerOperations}) : this( origin: new TypeConstraintFromExtendsClause( @@ -112,33 +104,27 @@ upper: typeAnalyzerOperations.typeToSchema(extendsType), lower: typeAnalyzerOperations.unknownType); - MergedTypeConstraint<TypeStructure, TypeParameterStructure, Variable, - TypeDeclarationType, TypeDeclaration> clone() { + MergedTypeConstraint<Variable, TypeDeclarationType, TypeDeclaration> clone() { return new MergedTypeConstraint(lower: lower, upper: upper, origin: origin); } bool isEmpty( - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { - return lower is SharedUnknownTypeStructure && - upper is SharedUnknownTypeStructure; + return lower is SharedUnknownType && upper is SharedUnknownType; } bool isSatisfiedBy( - SharedTypeView<TypeStructure> type, - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + SharedTypeView type, + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { return typeAnalyzerOperations.typeIsSubtypeOfTypeSchema(type, upper) && typeAnalyzerOperations.typeSchemaIsSubtypeOfType(lower, type); } void mergeIn( - GeneratedTypeConstraint<TypeStructure, TypeParameterStructure, Variable> - generatedTypeConstraint, - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + GeneratedTypeConstraint<Variable> generatedTypeConstraint, + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { if (generatedTypeConstraint.isUpper) { mergeInTypeSchemaUpper( @@ -150,17 +136,15 @@ } void mergeInTypeSchemaLower( - SharedTypeSchemaView<TypeStructure> constraint, - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + SharedTypeSchemaView constraint, + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { lower = typeAnalyzerOperations.typeSchemaLub(lower, constraint); } void mergeInTypeSchemaUpper( - SharedTypeSchemaView<TypeStructure> constraint, - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + SharedTypeSchemaView constraint, + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { upper = typeAnalyzerOperations.typeSchemaGlb(upper, constraint); } @@ -171,18 +155,12 @@ } } -class TypeConstraintFromArgument< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin<TypeStructure, Variable, - TypeParameterStructure, TypeDeclarationType, TypeDeclaration> { - final SharedTypeView<TypeStructure> argumentType; - final SharedTypeView<TypeStructure> parameterType; +class TypeConstraintFromArgument<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> + extends TypeConstraintOrigin<Variable, TypeDeclarationType, + TypeDeclaration> { + final SharedTypeView argumentType; + final SharedTypeView parameterType; final String parameterName; final String? genericClassName; final bool isGenericClassInDartCore; @@ -196,8 +174,7 @@ @override List<String> formatError( - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> 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 TypeConstraintFromExtendsClause< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin<TypeStructure, Variable, - TypeParameterStructure, TypeDeclarationType, TypeDeclaration> { +class TypeConstraintFromExtendsClause<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> + extends TypeConstraintOrigin<Variable, TypeDeclarationType, + TypeDeclaration> { /// Name of the type parameter with the extends clause. final String typeParameterName; @@ -239,13 +210,13 @@ /// this clause only when it is not `null`. /// /// For example `Iterable<T>` for `<T, E extends Iterable<T>>`. - final SharedTypeView<TypeStructure> boundType; + final SharedTypeView boundType; /// [boundType] in which type parameters are substituted with inferred /// type arguments. /// /// For example `Iterable<int>` if `T` inferred to `int`. - final SharedTypeView<TypeStructure> extendsType; + final SharedTypeView extendsType; TypeConstraintFromExtendsClause( {required this.typeParameterName, @@ -254,8 +225,7 @@ @override List<String> formatError( - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { String boundStr = boundType.getDisplayString(); String extendsStr = extendsType.getDisplayString(); @@ -266,28 +236,19 @@ } } -class TypeConstraintFromFunctionContext< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Type extends SharedTypeStructure<Type>, - TypeSchema extends SharedTypeStructure<TypeSchema>, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin<TypeStructure, Variable, - TypeParameterStructure, TypeDeclarationType, TypeDeclaration> { - final Type contextType; - final Type functionType; +class TypeConstraintFromFunctionContext<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> + extends TypeConstraintOrigin<Variable, TypeDeclarationType, + TypeDeclaration> { + final SharedType contextType; + final SharedType functionType; TypeConstraintFromFunctionContext( {required this.functionType, required this.contextType}); @override List<String> formatError( - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { return [ "Function type", @@ -297,28 +258,19 @@ } } -class TypeConstraintFromReturnType< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Type extends SharedTypeStructure<Type>, - TypeSchema extends SharedTypeStructure<TypeSchema>, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin<TypeStructure, Variable, - TypeParameterStructure, TypeDeclarationType, TypeDeclaration> { - final Type contextType; - final Type declaredType; +class TypeConstraintFromReturnType<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> + extends TypeConstraintOrigin<Variable, TypeDeclarationType, + TypeDeclaration> { + final SharedType contextType; + final SharedType declaredType; TypeConstraintFromReturnType( {required this.declaredType, required this.contextType}); @override List<String> formatError( - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { return [ "Return type", @@ -331,36 +283,24 @@ /// 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<TypeStructure>, - Variable extends Object, - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> { +abstract class TypeConstraintOrigin<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> { const TypeConstraintOrigin(); List<String> formatError( - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations); } -class UnknownTypeConstraintOrigin< - TypeStructure extends SharedTypeStructure<TypeStructure>, - Variable extends Object, - // Work around https://github.com/dart-lang/dart_style/issues/1568 - // ignore: lines_longer_than_80_chars - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - TypeDeclarationType extends Object, - TypeDeclaration extends Object> - extends TypeConstraintOrigin<TypeStructure, Variable, - TypeParameterStructure, TypeDeclarationType, TypeDeclaration> { +class UnknownTypeConstraintOrigin<Variable extends Object, + TypeDeclarationType extends Object, TypeDeclaration extends Object> + extends TypeConstraintOrigin<Variable, TypeDeclarationType, + TypeDeclaration> { const UnknownTypeConstraintOrigin(); @override List<String> formatError( - TypeAnalyzerOperations<TypeStructure, Variable, TypeParameterStructure, - TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperations<Variable, TypeDeclarationType, TypeDeclaration> typeAnalyzerOperations) { return <String>[]; } @@ -369,18 +309,12 @@ /// 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<TypeStructure>, - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - Variable extends Object, +class TypeConstraintGenerationDataForTesting<Variable extends Object, AstNode extends Object> { /// Map from nodes requiring type inference to the generated type constraints /// for the node. - final Map< - AstNode, - List< - GeneratedTypeConstraint<TypeStructure, TypeParameterStructure, - Variable>>> generatedTypeConstraints = {}; + final Map<AstNode, List<GeneratedTypeConstraint<Variable>>> + generatedTypeConstraints = {}; /// Merges [other] into the receiver, combining the constraints. /// @@ -389,9 +323,7 @@ /// because the changes made to the reused structures will be visible to /// [other]. void mergeIn( - TypeConstraintGenerationDataForTesting<TypeStructure, - TypeParameterStructure, Variable, AstNode> - other) { + TypeConstraintGenerationDataForTesting<Variable, AstNode> other) { for (AstNode node in other.generatedTypeConstraints.keys) { List<GeneratedTypeConstraint>? 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 5ed4fb1..a4f096c 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 @@ /// Common interface for data structures used by the implementations to /// represent the type `dynamic`. -abstract interface class SharedDynamicTypeStructure< - TypeStructure extends SharedTypeStructure<TypeStructure>> - implements SharedTypeStructure<TypeStructure> {} +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<TypeStructure>, - TypeParameterStructure extends SharedTypeParameterStructure<TypeStructure>, - FunctionParameterStructure extends SharedNamedFunctionParameterStructure< - TypeStructure>> implements SharedTypeStructure<TypeStructure> { +abstract interface class SharedFunctionType implements SharedType { /// All the positional parameter types, starting with the required ones, and /// followed by the optional ones. - List<TypeStructure> get positionalParameterTypesShared; + List<SharedType> 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<FunctionParameterStructure> get sortedNamedParametersShared; + List<SharedNamedFunctionParameter> get sortedNamedParametersShared; /// The type parameters of the function type. - List<TypeParameterStructure> get typeParametersShared; + List<SharedTypeParameter> get typeParametersShared; } /// Common interface for data structures used by the implementations to @@ -40,14 +34,11 @@ /// /// The implementations may choose to suppress further errors that arise from /// the use of this type. -abstract interface class SharedInvalidTypeStructure< - TypeStructure extends SharedTypeStructure<TypeStructure>> - implements SharedTypeStructure<TypeStructure> {} +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<TypeStructure>> { +abstract interface class SharedNamedFunctionParameter { /// Whether this named parameter is required. bool get isRequired; @@ -55,40 +46,35 @@ 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<TypeStructure>> { +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<TypeStructure>> - implements SharedTypeStructure<TypeStructure> {} +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<TypeStructure>> - implements SharedTypeStructure<TypeStructure> { - List<TypeStructure> get positionalTypesShared; +abstract interface class SharedRecordType implements SharedType { + List<SharedType> get positionalTypesShared; /// All the named fields, sorted by name. - List<SharedNamedTypeStructure<TypeStructure>> get sortedNamedTypesShared; + List<SharedNamedType> get sortedNamedTypesShared; } /// Common interface for data structures used by the implementations to /// represent a generic type parameter. -abstract interface class SharedTypeParameterStructure< - TypeStructure extends SharedTypeStructure<TypeStructure>> { +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 @@ /// Common interface for data structures used by the implementations to /// represent a type. -abstract interface class SharedTypeStructure< - TypeStructure extends SharedTypeStructure<TypeStructure>> { +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<TypeStructure> other); + bool isStructurallyEqualTo(covariant SharedType other); } /// Common interface for data structures used by the implementations to @@ -117,170 +102,143 @@ /// /// 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<TypeStructure>> - implements SharedTypeStructure<TypeStructure> {} +/// [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<TypeStructure>> - implements SharedTypeStructure<TypeStructure> {} +abstract interface class SharedVoidType implements SharedType {} -extension type SharedDynamicTypeSchemaView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedDynamicTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeSchemaView<TypeStructure> {} +extension type SharedDynamicTypeSchemaView(SharedDynamicType _typeStructure) + implements SharedTypeSchemaView {} -extension type SharedDynamicTypeView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedDynamicTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeView<TypeStructure> {} +extension type SharedDynamicTypeView(SharedDynamicType _typeStructure) + implements SharedTypeView {} -extension type SharedInvalidTypeSchemaView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedInvalidTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeSchemaView<TypeStructure> {} +extension type SharedInvalidTypeSchemaView(SharedInvalidType _typeStructure) + implements SharedTypeSchemaView {} -extension type SharedInvalidTypeView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedInvalidTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeView<TypeStructure> {} +extension type SharedInvalidTypeView(SharedInvalidType _typeStructure) + implements SharedTypeView {} -extension type SharedNamedTypeSchemaView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedNamedTypeStructure<TypeStructure> _typeStructure) implements Object {} +extension type SharedNamedTypeSchemaView(SharedNamedType _typeStructure) + implements Object {} -extension type SharedNamedTypeView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedNamedTypeStructure<TypeStructure> _namedTypeStructure) +extension type SharedNamedTypeView(SharedNamedType _namedTypeStructure) implements Object { String get name => _namedTypeStructure.nameShared; - SharedTypeView<TypeStructure> get type => - new SharedTypeView(_namedTypeStructure.typeShared); + SharedTypeView get type => new SharedTypeView(_namedTypeStructure.typeShared); } -extension type SharedRecordTypeSchemaView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedRecordTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeSchemaView<TypeStructure> { - List<SharedNamedTypeSchemaView<TypeStructure>> get namedTypes { +extension type SharedRecordTypeSchemaView(SharedRecordType _typeStructure) + implements SharedTypeSchemaView { + List<SharedNamedTypeSchemaView> get namedTypes { return _typeStructure.sortedNamedTypesShared - as List<SharedNamedTypeSchemaView<TypeStructure>>; + as List<SharedNamedTypeSchemaView>; } - List<SharedTypeSchemaView<TypeStructure>> get positionalTypes { - return _typeStructure.positionalTypesShared - as List<SharedTypeSchemaView<TypeStructure>>; + List<SharedTypeSchemaView> get positionalTypes { + return _typeStructure.positionalTypesShared as List<SharedTypeSchemaView>; } } -extension type SharedRecordTypeView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedRecordTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeView<TypeStructure> { - List<SharedNamedTypeView<TypeStructure>> get namedTypes { - return _typeStructure.sortedNamedTypesShared - as List<SharedNamedTypeView<TypeStructure>>; +extension type SharedRecordTypeView(SharedRecordType _typeStructure) + implements SharedTypeView { + List<SharedNamedTypeView> get namedTypes { + return _typeStructure.sortedNamedTypesShared as List<SharedNamedTypeView>; } - List<SharedTypeView<TypeStructure>> get positionalTypes { - return _typeStructure.positionalTypesShared - as List<SharedTypeView<TypeStructure>>; + List<SharedTypeView> get positionalTypes { + return _typeStructure.positionalTypesShared as List<SharedTypeView>; } } -extension type SharedTypeSchemaView< - TypeStructure extends SharedTypeStructure<TypeStructure>>._( - SharedTypeStructure<TypeStructure> _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()); + + TypeStructure unwrapTypeSchemaView<TypeStructure extends SharedType>() => + _typeStructure as TypeStructure; } -extension type SharedTypeView< - TypeStructure extends SharedTypeStructure<TypeStructure>>._( - SharedTypeStructure<TypeStructure> _typeStructure) implements Object { - SharedTypeView(TypeStructure typeStructure) : this._(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 extends SharedType>() => + _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<TypeStructure>>( - SharedUnknownTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeSchemaView<TypeStructure> {} +/// [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< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedVoidTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeSchemaView<TypeStructure> {} +extension type SharedVoidTypeSchemaView(SharedVoidType _typeStructure) + implements SharedTypeSchemaView {} -extension type SharedVoidTypeView< - TypeStructure extends SharedTypeStructure<TypeStructure>>( - SharedVoidTypeStructure<TypeStructure> _typeStructure) - implements SharedTypeView<TypeStructure> {} +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<TypeStructure>> on TypeStructure { - SharedTypeSchemaView<TypeStructure> wrapSharedTypeSchemaView() { +extension SharedTypeStructureExtension on SharedType { + SharedTypeSchemaView wrapSharedTypeSchemaView() { return new SharedTypeSchemaView(this); } - SharedTypeView<TypeStructure> wrapSharedTypeView() { + SharedTypeView wrapSharedTypeView() { return new SharedTypeView(this); } } -extension SharedTypeStructureMapEntryExtension< - TypeStructure extends SharedTypeStructure<TypeStructure>> on ({ - TypeStructure keyType, - TypeStructure valueType +extension SharedTypeStructureMapEntryExtension on ({ + SharedType keyType, + SharedType valueType }) { - ({ - SharedTypeView<TypeStructure> keyType, - SharedTypeView<TypeStructure> valueType - }) wrapSharedTypeMapEntryView() { + ({SharedTypeView keyType, SharedTypeView valueType}) + wrapSharedTypeMapEntryView() { return ( keyType: new SharedTypeView(this.keyType), valueType: new SharedTypeView(this.valueType) ); } - ({ - SharedTypeSchemaView<TypeStructure> keyType, - SharedTypeSchemaView<TypeStructure> 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 638cbba..a4ca874 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 @@ Expression getSsaNodes(void Function(SsaNodeHarness) callback) => new _GetSsaNodes(callback, location: computeLocation()); -Expression implicitThis_whyNotPromoted( - String staticType, - void Function(Map<SharedTypeView<Type>, NonPromotionReason>) - callback) => +Expression implicitThis_whyNotPromoted(String staticType, + void Function(Map<SharedTypeView, NonPromotionReason>) callback) => new _WhyNotPromoted_ImplicitThis(Type(staticType), callback, location: computeLocation()); @@ -29,15 +27,15 @@ /// the [FlowAnalysisOperations] needed by flow analysis, as well as other /// methods needed for testing. class FlowAnalysisTestHarness extends Harness - with FlowModelHelper<SharedTypeView<Type>> { + with FlowModelHelper<SharedTypeView> { @override final PromotionKeyStore<Var> promotionKeyStore = PromotionKeyStore(); @override - final SharedTypeView<Type> boolType = SharedTypeView(Type('bool')); + final SharedTypeView boolType = SharedTypeView(Type('bool')); @override - FlowAnalysisOperations<Var, SharedTypeView<Type>> get typeOperations => + FlowAnalysisOperations<Var, SharedTypeView> get typeOperations => typeAnalyzer.operations; @override @@ -50,21 +48,20 @@ /// Helper class allowing tests to examine the values of variables' SSA nodes. class SsaNodeHarness { - final FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView<Type>> - _flow; + final FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView> _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<SharedTypeView<Type>>? operator [](Var variable) => + SsaNode<SharedTypeView>? operator [](Var variable) => _flow.ssaNodeForTesting(variable); } class _GetExpressionInfo extends Expression { final Expression target; - final void Function(ExpressionInfo<SharedTypeView<Type>>?) callback; + final void Function(ExpressionInfo<SharedTypeView>?) callback; _GetExpressionInfo(this.target, this.callback, {required super.location}); @@ -74,13 +71,12 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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: type); + return new ExpressionTypeAnalysisResult(type: type); } } @@ -93,8 +89,7 @@ void preVisit(PreVisitor visitor) {} @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 _WhyNotPromoted extends Expression { final Expression target; - final void Function(Map<SharedTypeView<Type>, NonPromotionReason>) callback; + final void Function(Map<SharedTypeView, NonPromotionReason>) callback; _WhyNotPromoted(this.target, this.callback, {required super.location}); @@ -118,20 +113,19 @@ String toString() => '$target (whyNotPromoted)'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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: type); + return new ExpressionTypeAnalysisResult(type: type); } } class _WhyNotPromoted_ImplicitThis extends Expression { final Type staticType; - final void Function(Map<SharedTypeView<Type>, NonPromotionReason>) callback; + final void Function(Map<SharedTypeView, NonPromotionReason>) callback; _WhyNotPromoted_ImplicitThis(this.staticType, this.callback, {required super.location}); @@ -143,8 +137,7 @@ String toString() => 'implicit this (whyNotPromoted)'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ /// analysis information associated with it, `null` will be passed to /// [callback]. Expression getExpressionInfo( - void Function(ExpressionInfo<SharedTypeView<Type>>?) callback) { + void Function(ExpressionInfo<SharedTypeView>?) callback) { var location = computeLocation(); return new _GetExpressionInfo(asExpression(location: location), callback, location: location); @@ -170,7 +163,7 @@ /// 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<SharedTypeView<Type>, NonPromotionReason>) callback) { + void Function(Map<SharedTypeView, NonPromotionReason>) 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 ce7436c..3ecae7e 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 @@ group('API', () { test('asExpression_end promotes variables', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -213,7 +213,7 @@ test('equalityOp(x != null) promotes true branch', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -277,7 +277,7 @@ test('equalityOp(x == null) promotes false branch', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -340,7 +340,7 @@ test('equalityOp(null != x) promotes true branch', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -368,7 +368,7 @@ test('equalityOp(null == x) promotes false branch', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -480,7 +480,7 @@ test('doStatement_bodyBegin() un-promotes', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforeLoop; + late SsaNode<SharedTypeView> ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -635,12 +635,11 @@ test('finish checks proper nesting', () { var e = expr('Null'); var s = if_(e, []); - var flow = - FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView<Type>>( - h.typeOperations, AssignedVariables<Node, Var>(), - respectImplicitlyTypedVarInitializers: true, - fieldPromotionEnabled: true, - inferenceUpdate4Enabled: true); + var flow = FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView>( + h.typeOperations, AssignedVariables<Node, Var>(), + respectImplicitlyTypedVarInitializers: true, + fieldPromotionEnabled: true, + inferenceUpdate4Enabled: true); flow.ifStatement_conditionBegin(); flow.ifStatement_thenBegin(e, s); expect(() => flow.finish(), _asserts); @@ -648,7 +647,7 @@ test('for_conditionBegin() un-promotes', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforeLoop; + late SsaNode<SharedTypeView> ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -782,8 +781,8 @@ test('for_end() with break updates Ssa of modified vars', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> xSsaInsideLoop; - late SsaNode<SharedTypeView<Type>> ySsaInsideLoop; + late SsaNode<SharedTypeView> xSsaInsideLoop; + late SsaNode<SharedTypeView> ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -810,8 +809,8 @@ 'tested', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> xSsaInsideLoop; - late SsaNode<SharedTypeView<Type>> ySsaInsideLoop; + late SsaNode<SharedTypeView> xSsaInsideLoop; + late SsaNode<SharedTypeView> ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -836,7 +835,7 @@ test('forEach_bodyBegin() un-promotes', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforeLoop; + late SsaNode<SharedTypeView> ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -989,7 +988,7 @@ test('functionExpression_begin() cancels promotions of written vars', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> ssaBeforeFunction; + late SsaNode<SharedTypeView> ssaBeforeFunction; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -1401,7 +1400,7 @@ var x = Var('x'); var y = Var('y'); var z = Var('z'); - late SsaNode<SharedTypeView<Type>> xSsaNodeBeforeIf; + late SsaNode<SharedTypeView> xSsaNodeBeforeIf; h.run([ declare(w, type: 'Object', initializer: expr('Object')), declare(x, type: 'bool', initializer: expr('bool')), @@ -1429,7 +1428,7 @@ 'ifStatement_end() ignores non-matching SSA info from "then" path if ' 'unreachable', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> xSsaNodeBeforeIf; + late SsaNode<SharedTypeView> xSsaNodeBeforeIf; h.run([ declare(x, type: 'Object', initializer: expr('Object')), getSsaNodes((nodes) { @@ -1449,7 +1448,7 @@ 'ifStatement_end() ignores non-matching SSA info from "else" path if ' 'unreachable', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> xSsaNodeBeforeIf; + late SsaNode<SharedTypeView> xSsaNodeBeforeIf; h.run([ declare(x, type: 'Object', initializer: expr('Object')), getSsaNodes((nodes) { @@ -1565,7 +1564,7 @@ .get(h, key)! .promotedTypes! .single - .unwrapTypeView() + .unwrapTypeView<Type>() .type, 'int'); }), @@ -1655,7 +1654,7 @@ String? expectedPromotedTypeThen, String? expectedPromotedTypeElse, {bool inverted = false}) { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.run([ declare(x, type: declaredType, initializer: expr(declaredType)), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -1959,7 +1958,7 @@ test('nonNullAssert_end(x) promotes', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.run([ declare(x, type: 'int?', initializer: expr('int?')), getSsaNodes((nodes) => ssaBeforePromotion = nodes[x]!), @@ -1981,7 +1980,7 @@ test('nullAwareAccess temporarily promotes', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforePromotion; + late SsaNode<SharedTypeView> ssaBeforePromotion; h.addMember('int', 'f', 'Null Function(Object?)'); h.run([ declare(x, type: 'int?', initializer: expr('int?')), @@ -2338,7 +2337,7 @@ test('switchStatement_beginCase(true) un-promotes', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforeSwitch; + late SsaNode<SharedTypeView> ssaBeforeSwitch; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -2502,7 +2501,7 @@ test('tryCatchStatement_bodyEnd() un-promotes variables assigned in body', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaAfterTry; + late SsaNode<SharedTypeView> ssaAfterTry; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -2633,8 +2632,8 @@ 'tryFinallyStatement_finallyBegin() un-promotes variables assigned in ' 'body', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaAtStartOfTry; - late SsaNode<SharedTypeView<Type>> ssaAfterTry; + late SsaNode<SharedTypeView> ssaAtStartOfTry; + late SsaNode<SharedTypeView> ssaAfterTry; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -2703,8 +2702,8 @@ 'variables assigned in finally', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> xSsaAtEndOfFinally; - late SsaNode<SharedTypeView<Type>> ySsaAtEndOfFinally; + late SsaNode<SharedTypeView> xSsaAtEndOfFinally; + late SsaNode<SharedTypeView> ySsaAtEndOfFinally; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -2742,10 +2741,10 @@ 'is sound to do so', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> xSsaAtEndOfTry; - late SsaNode<SharedTypeView<Type>> ySsaAtEndOfTry; - late SsaNode<SharedTypeView<Type>> xSsaAtEndOfFinally; - late SsaNode<SharedTypeView<Type>> ySsaAtEndOfFinally; + late SsaNode<SharedTypeView> xSsaAtEndOfTry; + late SsaNode<SharedTypeView> ySsaAtEndOfTry; + late SsaNode<SharedTypeView> xSsaAtEndOfFinally; + late SsaNode<SharedTypeView> ySsaAtEndOfFinally; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3205,7 +3204,7 @@ test('whileStatement_conditionBegin() un-promotes', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforeLoop; + late SsaNode<SharedTypeView> ssaBeforeLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), x.as_('int'), @@ -3284,8 +3283,8 @@ test('whileStatement_end() with break updates Ssa of modified vars', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> xSsaInsideLoop; - late SsaNode<SharedTypeView<Type>> ySsaInsideLoop; + late SsaNode<SharedTypeView> xSsaInsideLoop; + late SsaNode<SharedTypeView> ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3312,8 +3311,8 @@ 'types were tested', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> xSsaInsideLoop; - late SsaNode<SharedTypeView<Type>> ySsaInsideLoop; + late SsaNode<SharedTypeView> xSsaInsideLoop; + late SsaNode<SharedTypeView> ySsaInsideLoop; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3339,8 +3338,8 @@ test('write() de-promotes and updates Ssa of a promoted variable', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> ssaBeforeWrite; - late ExpressionInfo<SharedTypeView<Type>> writtenValueInfo; + late SsaNode<SharedTypeView> ssaBeforeWrite; + late ExpressionInfo<SharedTypeView> writtenValueInfo; h.run([ declare(x, type: 'Object', initializer: expr('Object')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3362,8 +3361,8 @@ test('write() updates Ssa', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> ssaBeforeWrite; - late ExpressionInfo<SharedTypeView<Type>> writtenValueInfo; + late SsaNode<SharedTypeView> ssaBeforeWrite; + late ExpressionInfo<SharedTypeView> writtenValueInfo; h.run([ declare(x, type: 'Object', initializer: expr('Object')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3394,8 +3393,8 @@ var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> xSsaBeforeWrite; - late SsaNode<SharedTypeView<Type>> ySsa; + late SsaNode<SharedTypeView> xSsaBeforeWrite; + late SsaNode<SharedTypeView> ySsa; h.run([ declare(x, type: 'int?', initializer: expr('int?')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3414,7 +3413,7 @@ test('write() does not store expressionInfo for trivial expressions', () { var x = Var('x'); var y = Var('y'); - late SsaNode<SharedTypeView<Type>> ssaBeforeWrite; + late SsaNode<SharedTypeView> ssaBeforeWrite; h.run([ declare(x, type: 'Object', initializer: expr('Object')), declare(y, type: 'int?', initializer: expr('int?')), @@ -3436,7 +3435,7 @@ test('write() permits expression to be null', () { var x = Var('x'); - late SsaNode<SharedTypeView<Type>> ssaBeforeWrite; + late SsaNode<SharedTypeView> ssaBeforeWrite; h.run([ declare(x, type: 'Object', initializer: expr('Object')), getSsaNodes((nodes) => ssaBeforeWrite = nodes[x]!), @@ -3656,15 +3655,15 @@ }); group('setUnreachable', () { - var unreachable = FlowModel<SharedTypeView<Type>>( - Reachability.initial.setUnreachable()); - var reachable = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var unreachable = + FlowModel<SharedTypeView>(Reachability.initial.setUnreachable()); + var reachable = FlowModel<SharedTypeView>(Reachability.initial); test('unchanged', () { expect(unreachable.setUnreachable(), same(unreachable)); }); test('changed', () { - void _check(FlowModel<SharedTypeView<Type>> initial) { + void _check(FlowModel<SharedTypeView> initial) { var s = initial.setUnreachable(); expect(s, isNot(same(initial))); expect(s.reachable.overallReachable, false); @@ -3676,33 +3675,33 @@ }); test('split', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1.split(); expect(s2.reachable.parent, same(s1.reachable)); }); test('unsplit', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial.split()); + var s1 = FlowModel<SharedTypeView>(Reachability.initial.split()); var s2 = s1.unsplit(); expect(s2.reachable, same(Reachability.initial)); }); group('unsplitTo', () { test('no change', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial.split()); + var s1 = FlowModel<SharedTypeView>(Reachability.initial.split()); var result = s1.unsplitTo(s1.reachable.parent!); expect(result, same(s1)); }); test('unsplit once, reachable', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial.split()); + var s1 = FlowModel<SharedTypeView>(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<SharedTypeView<Type>>(Reachability.initial.split()); + var s1 = FlowModel<SharedTypeView>(Reachability.initial.split()); var s2 = s1.split().setUnreachable(); var result = s2.unsplitTo(s1.reachable.parent!); expect(result.reachable.locallyReachable, false); @@ -3710,7 +3709,7 @@ }); test('unsplit twice, reachable', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial.split()); + var s1 = FlowModel<SharedTypeView>(Reachability.initial.split()); var s2 = s1.split(); var s3 = s2.split(); var result = s3.unsplitTo(s1.reachable.parent!); @@ -3718,7 +3717,7 @@ }); test('unsplit twice, top unreachable', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial.split()); + var s1 = FlowModel<SharedTypeView>(Reachability.initial.split()); var s2 = s1.split(); var s3 = s2.split().setUnreachable(); var result = s3.unsplitTo(s1.reachable.parent!); @@ -3727,7 +3726,7 @@ }); test('unsplit twice, previous unreachable', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial.split()); + var s1 = FlowModel<SharedTypeView>(Reachability.initial.split()); var s2 = s1.split().setUnreachable(); var s3 = s2.split(); var result = s3.unsplitTo(s1.reachable.parent!); @@ -3738,25 +3737,25 @@ group('tryPromoteForTypeCheck', () { test('unpromoted -> unchanged (same)', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intVar, 'int').ifTrue; expect(s2, same(s1)); }); test('unpromoted -> unchanged (supertype)', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intVar, 'Object').ifTrue; expect(s2, same(s1)); }); test('unpromoted -> unchanged (unrelated)', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intVar, 'String').ifTrue; expect(s2, same(s1)); }); test('unpromoted -> subtype', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1._tryPromoteForTypeCheck(h, intQVar, 'int').ifTrue; expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { @@ -3766,7 +3765,7 @@ }); test('promoted -> unchanged (same)', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'int').ifTrue; @@ -3774,7 +3773,7 @@ }); test('promoted -> unchanged (supertype)', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'Object').ifTrue; @@ -3782,7 +3781,7 @@ }); test('promoted -> unchanged (unrelated)', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'String').ifTrue; @@ -3790,7 +3789,7 @@ }); test('promoted -> subtype', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifTrue; var s2 = s1._tryPromoteForTypeCheck(h, objectQVar, 'int').ifTrue; @@ -3812,12 +3811,12 @@ test('without declaration', () { // This should not happen in valid code, but test that we don't crash. - var s = FlowModel<SharedTypeView<Type>>(Reachability.initial)._write( + var s = FlowModel<SharedTypeView>(Reachability.initial)._write( h, null, objectQVar, SharedTypeView(Type('Object?')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect( s.promotionInfo ?.get(h, h.promotionKeyStore.keyForVariable(objectQVar)), @@ -3825,10 +3824,10 @@ }); test('unchanged', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('Object?')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2, isNot(same(s1))); expect(s2.reachable, same(s1.reachable)); expect( @@ -3841,10 +3840,10 @@ }); test('marks as assigned', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, false); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int?')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.reachable.overallReachable, true); expect( s2._infoFor(h, objectQVar), @@ -3856,18 +3855,14 @@ }); test('un-promotes fully', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(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<SharedTypeView<Type>>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('int?')), new SsaNode<SharedTypeView>(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( @@ -3879,7 +3874,7 @@ }); test('un-promotes partially, when no exact match', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3892,12 +3887,8 @@ assigned: true, unassigned: false) }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num')), - new SsaNode<SharedTypeView<Type>>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num')), new SsaNode<SharedTypeView>(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( @@ -3909,7 +3900,7 @@ }); test('un-promotes partially, when exact match', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3924,12 +3915,8 @@ assigned: true, unassigned: false) }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num')), - new SsaNode<SharedTypeView<Type>>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num')), new SsaNode<SharedTypeView>(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( @@ -3941,7 +3928,7 @@ }); test('leaves promoted, when exact match', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3955,7 +3942,7 @@ unassigned: false) }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('num')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo, isNot(same(s1.promotionInfo))); expect(s2.promotionInfo.unwrap(h), { @@ -3968,7 +3955,7 @@ }); test('leaves promoted, when writing a subtype', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -3982,7 +3969,7 @@ unassigned: false) }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.reachable.overallReachable, true); expect(s2.promotionInfo, isNot(same(s1.promotionInfo))); expect(s2.promotionInfo.unwrap(h), { @@ -3998,7 +3985,7 @@ test('when declared type', () { var x = Var('x')..type = Type('int?'); - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, x, true); expect(s1.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): @@ -4006,7 +3993,7 @@ }); var s2 = s1._write(h, null, x, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel(chain: ['int']), @@ -4016,7 +4003,7 @@ test('when declared type, if write-captured', () { var x = Var('x')..type = Type('int?'); - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, x, true); expect(s1.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): @@ -4031,7 +4018,7 @@ // 'x' is write-captured, so not promoted var s3 = s2._write(h, null, x, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s3.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel(chain: null, writeCaptured: true), @@ -4039,7 +4026,7 @@ }); test('when promoted', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifTrue; @@ -4050,7 +4037,7 @@ ), }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['int?', 'int'], @@ -4060,7 +4047,7 @@ }); test('when not promoted', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifFalse; @@ -4071,7 +4058,7 @@ ), }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['Object', 'int'], @@ -4082,7 +4069,7 @@ }); test('Promotes to type of interest when not previously promoted', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifFalse; @@ -4092,12 +4079,8 @@ ofInterest: ['num?'], ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num?')), - new SsaNode<SharedTypeView<Type>>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num?')), new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['num?'], @@ -4107,7 +4090,7 @@ }); test('Promotes to type of interest when previously promoted', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifTrue @@ -4119,12 +4102,8 @@ ofInterest: ['num?', 'int?'], ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('int?')), - new SsaNode<SharedTypeView<Type>>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('int?')), new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): _matchVariableModel( chain: ['num?', 'int?'], @@ -4148,7 +4127,7 @@ test('; first', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'B?') .ifFalse @@ -4162,7 +4141,7 @@ }); var s2 = s1._write(h, null, x, SharedTypeView(Type('C')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['Object', 'B'], @@ -4174,7 +4153,7 @@ test('; second', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'A?') .ifFalse @@ -4188,7 +4167,7 @@ }); var s2 = s1._write(h, null, x, SharedTypeView(Type('C')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['Object', 'B'], @@ -4200,7 +4179,7 @@ test('; nullable and non-nullable', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'A') .ifFalse @@ -4214,7 +4193,7 @@ }); var s2 = s1._write(h, null, x, SharedTypeView(Type('B')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['Object', 'A'], @@ -4226,7 +4205,7 @@ group('; ambiguous', () { test('; no promotion', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifFalse @@ -4240,7 +4219,7 @@ ), }); var s2 = s1._write(h, null, objectQVar, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(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 @@ }); test('exact match', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'num?') .ifFalse @@ -4267,12 +4246,8 @@ ofInterest: ['num?', 'num*'], ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - objectQVar, - SharedTypeView(Type('num?')), - new SsaNode<SharedTypeView<Type>>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), objectQVar, + SharedTypeView(Type('num?')), new SsaNode<SharedTypeView>(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 @@ test('when promoted via test', () { var x = Var('x')..type = Type('Object?'); - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, x, true) ._tryPromoteForTypeCheck(h, x, 'num?') .ifTrue @@ -4302,12 +4277,8 @@ ), }); - var s2 = s1._write( - h, - _MockNonPromotionReason(), - x, - SharedTypeView(Type('double')), - new SsaNode<SharedTypeView<Type>>(null)); + var s2 = s1._write(h, _MockNonPromotionReason(), x, + SharedTypeView(Type('double')), new SsaNode<SharedTypeView>(null)); expect(s2.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(x): _matchVariableModel( chain: ['num?', 'num'], @@ -4325,7 +4296,7 @@ }); test('initialized', () { - var s = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, true); expect(s.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): @@ -4334,7 +4305,7 @@ }); test('not initialized', () { - var s = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, objectQVar, false); expect(s.promotionInfo.unwrap(h), { h.promotionKeyStore.keyForVariable(objectQVar): @@ -4345,13 +4316,13 @@ group('markNonNullable', () { test('unpromoted -> unchanged', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1._tryMarkNonNullable(h, intVar).ifTrue; expect(s2, same(s1)); }); test('unpromoted -> promoted', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1._tryMarkNonNullable(h, intQVar).ifTrue; expect(s2.reachable.overallReachable, true); expect(s2._infoFor(h, intQVar), @@ -4359,7 +4330,7 @@ }); test('promoted -> unchanged', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; var s2 = s1._tryMarkNonNullable(h, objectQVar).ifTrue; @@ -4367,7 +4338,7 @@ }); test('promoted -> re-promoted', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int?') .ifTrue; var s2 = s1._tryMarkNonNullable(h, objectQVar).ifTrue; @@ -4379,7 +4350,7 @@ }); test('promote to Never', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s1 = FlowModel<SharedTypeView>(Reachability.initial); var s2 = s1._tryMarkNonNullable(h, nullVar).ifTrue; expect(s2.reachable.overallReachable, true); expect(s2._infoFor(h, nullVar), @@ -4389,7 +4360,7 @@ group('conservativeJoin', () { test('unchanged', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, intQVar, true) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue; @@ -4405,7 +4376,7 @@ }); test('written', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue ._tryPromoteForTypeCheck(h, intQVar, 'int') @@ -4421,7 +4392,7 @@ }); test('write captured', () { - var s1 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s1 = FlowModel<SharedTypeView>(Reachability.initial) ._tryPromoteForTypeCheck(h, objectQVar, 'int') .ifTrue ._tryPromoteForTypeCheck(h, intQVar, 'int') @@ -4439,7 +4410,7 @@ group('rebaseForward', () { test('reachability', () { - var reachable = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var reachable = FlowModel<SharedTypeView>(Reachability.initial); var unreachable = reachable.setUnreachable(); expect(reachable.rebaseForward(h, reachable), same(reachable)); expect(reachable.rebaseForward(h, unreachable), same(unreachable)); @@ -4456,21 +4427,21 @@ var b = Var('b')..type = Type('int'); var c = Var('c')..type = Type('int'); var d = Var('d')..type = Type('int'); - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s0 = FlowModel<SharedTypeView>(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<SharedTypeView<Type>>(null)) + new SsaNode<SharedTypeView>(null)) ._write(h, null, b, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); var s2 = s0 ._write(h, null, a, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)) + new SsaNode<SharedTypeView>(null)) ._write(h, null, c, SharedTypeView(Type('int')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(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 @@ var b = Var('b')..type = Type('int'); var c = Var('c')..type = Type('int'); var d = Var('d')..type = Type('int'); - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s0 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, a, false) ._declare(h, b, false) ._declare(h, c, false) @@ -4512,7 +4483,7 @@ test('write captured and promoted', () { var a = Var('a')..type = Type('num'); - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s0 = FlowModel<SharedTypeView>(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 @@ void _check(String? thisType, String? otherType, bool unsafe, List<String>? expectedChain) { var x = Var('x')..type = Type('Object?'); - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s0 = FlowModel<SharedTypeView>(Reachability.initial) ._declare(h, x, true); var s1 = s0; if (unsafe) { s1 = s1._write(h, null, x, SharedTypeView(Type('Object?')), - new SsaNode<SharedTypeView<Type>>(null)); + new SsaNode<SharedTypeView>(null)); } if (thisType != null) { s1 = s1._tryPromoteForTypeCheck(h, x, thisType).ifTrue; @@ -4554,7 +4525,7 @@ result ._infoFor(h, x) .promotedTypes! - .map((t) => t.unwrapTypeView().type) + .map((t) => t.unwrapTypeView<Type>().type) .toList(), expectedChain); } @@ -4577,10 +4548,9 @@ test('promotion chains', () { // Verify that the given promotion chain matches the expected list of // strings. - void _checkChain( - List<SharedTypeView<Type>>? chain, List<String> expected) { - var strings = (chain ?? <SharedTypeView<Type>>[]) - .map((t) => t.unwrapTypeView().type) + void _checkChain(List<SharedTypeView>? chain, List<String> expected) { + var strings = (chain ?? <SharedTypeView>[]) + .map((t) => t.unwrapTypeView<Type>().type) .toList(); expect(strings, expected); } @@ -4597,9 +4567,8 @@ void _check(List<String> before, List<String> inTry, List<String> inFinally, List<String> expectedResult) { var x = Var('x')..type = Type('Object?'); - var initialModel = - FlowModel<SharedTypeView<Type>>(Reachability.initial) - ._declare(h, x, true); + var initialModel = FlowModel<SharedTypeView>(Reachability.initial) + ._declare(h, x, true); for (var t in before) { initialModel = initialModel._tryPromoteForTypeCheck(h, x, t).ifTrue; } @@ -4655,7 +4624,7 @@ test('types of interest', () { var a = Var('a')..type = Type('Object'); - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial) + var s0 = FlowModel<SharedTypeView>(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 @@ test('variable present in one state but not the other', () { var x = Var('x')..type = Type('Object?'); - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(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 @@ h.addSuperInterfaces('B', (_) => [Type('A'), Type('Object')]); h.addSuperInterfaces('A', (_) => [Type('Object')]); - void check(List<SharedTypeView<Type>> chain1, - List<SharedTypeView<Type>> chain2, Matcher matcher) { + void check(List<SharedTypeView> chain1, List<SharedTypeView> chain2, + Matcher matcher) { expect( PromotionModel.joinPromotedTypes(chain1, chain2, h.typeOperations), matcher, @@ -4909,20 +4878,18 @@ stringType = Type('String'); }); - PromotionModel<SharedTypeView<Type>> model( - List<SharedTypeView<Type>>? promotionChain, - {List<SharedTypeView<Type>>? typesOfInterest, - bool assigned = false}) => - PromotionModel<SharedTypeView<Type>>( + PromotionModel<SharedTypeView> model(List<SharedTypeView>? promotionChain, + {List<SharedTypeView>? typesOfInterest, bool assigned = false}) => + PromotionModel<SharedTypeView>( promotedTypes: promotionChain, tested: typesOfInterest ?? promotionChain ?? [], assigned: assigned, unassigned: !assigned, - ssaNode: new SsaNode<SharedTypeView<Type>>(null)); + ssaNode: new SsaNode<SharedTypeView>(null)); group('without input reuse', () { test('promoted with unpromoted', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]), y: model(null) @@ -4939,7 +4906,7 @@ }); group('should re-use an input if possible', () { test('identical inputs', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]), y: model([SharedTypeView(stringType)]) @@ -4948,7 +4915,7 @@ }); test('one input empty', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]), y: model([SharedTypeView(stringType)]) @@ -4962,7 +4929,7 @@ }); test('promoted with unpromoted', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -4977,7 +4944,7 @@ }); test('related type chains', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intQType), SharedTypeView(intType)]) }); @@ -4994,7 +4961,7 @@ }); test('unrelated type chains', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -5011,7 +4978,7 @@ }); test('sub-map', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var xModel = model([SharedTypeView(intType)]); var s1 = s0._setInfo(h, { x: xModel, @@ -5026,7 +4993,7 @@ }); test('sub-map with matched subtype', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intQType), SharedTypeView(intType)]), y: model([SharedTypeView(stringType)]) @@ -5044,7 +5011,7 @@ }); test('sub-map with mismatched subtype', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var s1 = s0._setInfo(h, { x: model([SharedTypeView(intQType)]), y: model([SharedTypeView(stringType)]) @@ -5062,7 +5029,7 @@ }); test('assigned', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var unassigned = model(null, assigned: false); var assigned = model(null, assigned: true); var s1 = s0._setInfo( @@ -5081,7 +5048,7 @@ }); test('write captured', () { - var s0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var s0 = FlowModel<SharedTypeView>(Reachability.initial); var intQModel = model([SharedTypeView(intQType)]); var writeCapturedModel = intQModel.writeCapture(); var s1 = s0._setInfo(h, { @@ -5118,17 +5085,17 @@ stringType = Type('String'); }); - PromotionModel<SharedTypeView<Type>> model( - List<SharedTypeView<Type>> typesOfInterest) => - PromotionModel<SharedTypeView<Type>>( + PromotionModel<SharedTypeView> model( + List<SharedTypeView> typesOfInterest) => + PromotionModel<SharedTypeView>( promotedTypes: null, tested: typesOfInterest, assigned: true, unassigned: false, - ssaNode: new SsaNode<SharedTypeView<Type>>(null)); + ssaNode: new SsaNode<SharedTypeView>(null)); test('inherits types of interest from other', () { - var m0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var m0 = FlowModel<SharedTypeView>(Reachability.initial); var m1 = m0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -5140,7 +5107,7 @@ }); test('handles variable missing from other', () { - var m0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var m0 = FlowModel<SharedTypeView>(Reachability.initial); var m1 = m0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -5149,7 +5116,7 @@ }); test('returns identical model when no changes', () { - var m0 = FlowModel<SharedTypeView<Type>>(Reachability.initial); + var m0 = FlowModel<SharedTypeView>(Reachability.initial); var m1 = m0._setInfo(h, { x: model([SharedTypeView(intType)]) }); @@ -11491,16 +11458,16 @@ Matcher _matchOfInterestSet(List<String> expectedTypes) { return predicate( - (List<SharedTypeView<Type>> x) => unorderedEquals(expectedTypes) - .matches(x.map((t) => t.unwrapTypeView().type).toList(), {}), + (List<SharedTypeView> x) => unorderedEquals(expectedTypes) + .matches(x.map((t) => t.unwrapTypeView<Type>().type).toList(), {}), 'interest set $expectedTypes'); } Matcher _matchPromotionChain(List<String>? expectedTypes) { if (expectedTypes == null) return isNull; return predicate( - (List<SharedTypeView<Type>> x) => equals(expectedTypes) - .matches(x.map((t) => t.unwrapTypeView().type).toList(), {}), + (List<SharedTypeView> x) => equals(expectedTypes) + .matches(x.map((t) => t.unwrapTypeView<Type>().type).toList(), {}), 'promotion chain $expectedTypes'); } @@ -11523,7 +11490,7 @@ Matcher assignedMatcher = wrapMatcher(assigned); Matcher unassignedMatcher = wrapMatcher(unassigned); Matcher writeCapturedMatcher = wrapMatcher(writeCaptured); - return predicate((PromotionModel<SharedTypeView<Type>> model) { + return predicate((PromotionModel<SharedTypeView> 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 @@ fail('Unexpected call to accept'); } -extension on FlowModel<SharedTypeView<Type>> { - FlowModel<SharedTypeView<Type>> _conservativeJoin(FlowAnalysisTestHarness h, +extension on FlowModel<SharedTypeView> { + FlowModel<SharedTypeView> _conservativeJoin(FlowAnalysisTestHarness h, Iterable<Var> writtenVariables, Iterable<Var> capturedVariables) => conservativeJoin(h, [ for (Var v in writtenVariables) h.promotionKeyStore.keyForVariable(v) @@ -11562,18 +11529,18 @@ for (Var v in capturedVariables) h.promotionKeyStore.keyForVariable(v) ]); - FlowModel<SharedTypeView<Type>> _declare( + FlowModel<SharedTypeView> _declare( FlowAnalysisTestHarness h, Var variable, bool initialized) => this.declare( h, h.promotionKeyStore.keyForVariable(variable), initialized); - PromotionModel<SharedTypeView<Type>> _infoFor( + PromotionModel<SharedTypeView> _infoFor( FlowAnalysisTestHarness h, Var variable) => infoFor(h, h.promotionKeyStore.keyForVariable(variable), ssaNode: new SsaNode(null)); - FlowModel<SharedTypeView<Type>> _setInfo(FlowAnalysisTestHarness h, - Map<int, PromotionModel<SharedTypeView<Type>>> newInfo) { + FlowModel<SharedTypeView> _setInfo(FlowAnalysisTestHarness h, + Map<int, PromotionModel<SharedTypeView>> newInfo) { var result = this; for (var core.MapEntry(:key, :value) in newInfo.entries) { if (result.promotionInfo?.get(h, key) != value) { @@ -11583,11 +11550,11 @@ return result; } - ExpressionInfo<SharedTypeView<Type>> _tryMarkNonNullable( + ExpressionInfo<SharedTypeView> _tryMarkNonNullable( FlowAnalysisTestHarness h, Var variable) => tryMarkNonNullable(h, _varRefWithType(h, variable)); - ExpressionInfo<SharedTypeView<Type>> _tryPromoteForTypeCheck( + ExpressionInfo<SharedTypeView> _tryPromoteForTypeCheck( FlowAnalysisTestHarness h, Var variable, String type) => tryPromoteForTypeCheck( h, _varRefWithType(h, variable), SharedTypeView(Type(type))); @@ -11595,9 +11562,9 @@ int _varRef(FlowAnalysisTestHarness h, Var variable) => h.promotionKeyStore.keyForVariable(variable); - TrivialVariableReference<SharedTypeView<Type>> _varRefWithType( + TrivialVariableReference<SharedTypeView> _varRefWithType( FlowAnalysisTestHarness h, Var variable) => - new TrivialVariableReference<SharedTypeView<Type>>( + new TrivialVariableReference<SharedTypeView>( promotionKey: _varRef(h, variable), model: this, type: promotionInfo @@ -11608,20 +11575,19 @@ isThisOrSuper: false, ssaNode: SsaNode(null)); - FlowModel<SharedTypeView<Type>> _write( + FlowModel<SharedTypeView> _write( FlowAnalysisTestHarness h, NonPromotionReason? nonPromotionReason, Var variable, - SharedTypeView<Type> writtenType, - SsaNode<SharedTypeView<Type>> newSsaNode) => + SharedTypeView writtenType, + SsaNode<SharedTypeView> newSsaNode) => write(h, nonPromotionReason, h.promotionKeyStore.keyForVariable(variable), writtenType, newSsaNode, h.typeOperations, unpromotedType: SharedTypeView(variable.type)); } -extension on PromotionInfo<SharedTypeView<Type>>? { - Map<int, PromotionModel<SharedTypeView<Type>>> unwrap( - FlowAnalysisTestHarness h) => +extension on PromotionInfo<SharedTypeView>? { + Map<int, PromotionModel<SharedTypeView>> 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 a0f57e0..afccac5 100644 --- a/pkg/_fe_analyzer_shared/test/mini_ast.dart +++ b/pkg/_fe_analyzer_shared/test/mini_ast.dart
@@ -534,7 +534,7 @@ } typedef SharedMatchContext - = shared.MatchContext<Node, Expression, Pattern, SharedTypeView<Type>, Var>; + = shared.MatchContext<Node, Expression, Pattern, SharedTypeView, Var>; typedef SharedRecordPatternField = shared.RecordPatternField<Node, Pattern>; @@ -553,8 +553,7 @@ String toString() => '$target as $type'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeTypeCast(this, target, type); } } @@ -624,11 +623,10 @@ String toString() => '$value'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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>(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -717,8 +715,7 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { h.irBuilder .readTmp(h.typeAnalyzer._currentCascadeTargetIR!, location: location); return ExpressionTypeAnalysisResult( @@ -809,7 +805,7 @@ CastPattern(this.inner, this.type, {required super.location}) : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeCastPatternSchema(); @override @@ -819,14 +815,14 @@ } @override - PatternResult<Type> 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<Type>(); 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 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ String toString() => 'check reachable'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 CollectionElementContextType extends CollectionElementContext { - final SharedTypeSchemaView<Type> elementTypeSchema; + final SharedTypeSchemaView elementTypeSchema; CollectionElementContextType._(this.elementTypeSchema); } @@ -1033,8 +1025,7 @@ String toString() => '$condition ? $ifTrue : $ifFalse'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ ConstantPattern(this.constant, {required super.location}) : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeConstantPatternSchema(); @override @@ -1060,10 +1051,10 @@ } @override - PatternResult<Type> 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<Type>(); 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 @@ initializer, declaredType?.wrapSharedTypeSchemaView() ?? h.operations.unknownType) - .unwrapTypeView(); + .unwrapTypeView<Type>(); h.flow.lateInitializer_end(); staticType = variable.type = declaredType ?? initializerType; h.flow.declare(variable, SharedTypeView(staticType), initialized: true); @@ -1201,7 +1192,7 @@ .analyzeUninitializedVariableDeclaration( this, pattern.variable, declaredType?.wrapSharedTypeView(), isFinal: isFinal) - .unwrapTypeView(); + .unwrapTypeView<Type>(); h.typeAnalyzer.handleDeclaredVariablePattern(pattern, matchedType: staticType, staticType: staticType); irName = 'declare'; @@ -1264,8 +1255,7 @@ String toString() => '$lhs ${isInverted ? '!=' : '=='} $rhs'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var operatorName = isInverted ? '!=' : '=='; var result = h.typeAnalyzer.analyzeBinaryExpression(this, lhs, operatorName, rhs); @@ -1303,8 +1293,7 @@ void preVisit(PreVisitor visitor); - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema); + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema); } /// Representation of a single case clause in a switch expression. Use @@ -1353,10 +1342,9 @@ @override void visit(Harness h, CollectionElementContext context) { - SharedTypeSchemaView<Type> 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 ExpressionInTypeSchema extends Statement { final Expression expr; - final SharedTypeSchemaView<Type> typeSchema; + final SharedTypeSchemaView typeSchema; ExpressionInTypeSchema._(this.expr, this.typeSchema, {required super.location}); @@ -1520,7 +1508,7 @@ void visit(Harness h) { var iteratedType = h._getIteratedType(h.typeAnalyzer .analyzeExpression(iterable, h.operations.unknownType) - .unwrapTypeView()); + .unwrapTypeView<Type>()); h.flow.forEach_bodyBegin(this); var variable = this.variable; if (variable != null && !declaresVariable) { @@ -1565,8 +1553,8 @@ bool _started = false; - late final FlowAnalysis<Node, Statement, Expression, Var, - SharedTypeView<Type>> flow; + late final FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView> + flow; bool? _inferenceUpdate3Enabled; @@ -1740,7 +1728,7 @@ } /// See [TypeAnalyzer.resolveRelationalPatternOperator]. - RelationalOperatorResolution<Type>? resolveRelationalPatternOperator( + RelationalOperatorResolution? resolveRelationalPatternOperator( Type matchedValueType, String operator) { if (operator == '==' || operator == '!=') { return RelationalOperatorResolution( @@ -1782,10 +1770,8 @@ b.preVisit(visitor); flow = operations.legacy ? FlowAnalysis<Node, Statement, Expression, Var, - SharedTypeView<Type>>.legacy( - operations, visitor._assignedVariables) - : FlowAnalysis<Node, Statement, Expression, Var, - SharedTypeView<Type>>( + SharedTypeView>.legacy(operations, visitor._assignedVariables) + : FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView>( operations, visitor._assignedVariables, respectImplicitlyTypedVarInitializers: @@ -2044,8 +2030,7 @@ String toString() => '$lhs ?? $rhs'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ String toString() => '$value'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeIntLiteral(schema); if (expectConversionToDouble != null) { expect(result.convertedToDouble, expectConversionToDouble); @@ -2120,8 +2104,7 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ String toString() => '$target is${isInverted ? '!' : ''} $type'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer .analyzeTypeTest(this, target, type, isInverted: isInverted); } @@ -2202,8 +2184,7 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { for (var element in elements) { h.typeAnalyzer.dispatchCollectionElement(element, CollectionElementContextType._(SharedTypeSchemaView(elementType))); @@ -2234,7 +2215,7 @@ : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeListPatternSchema( elementType: elementType?.wrapSharedTypeView(), elements: elements); @@ -2247,11 +2228,11 @@ } @override - PatternResult<Type> 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<Type>(); + var requiredType = listPatternResult.requiredType.unwrapTypeView<Type>(); 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 @@ String toString() => '() $body'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { h.flow.functionExpression_begin(this); h.typeAnalyzer.dispatchStatement(body); h.flow.functionExpression_end(); @@ -2324,8 +2304,7 @@ String toString() => '$lhs ${isAnd ? '&&' : '||'} $rhs'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var operatorName = isAnd ? '&&' : '||'; var result = h.typeAnalyzer.analyzeBinaryExpression(this, lhs, operatorName, rhs); @@ -2345,7 +2324,7 @@ : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeLogicalAndPatternSchema(lhs, rhs); @override @@ -2356,10 +2335,10 @@ } @override - PatternResult<Type> 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<Type>(); 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 @@ LogicalOrPattern(this.lhs, this.rhs, {required super.location}) : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeLogicalOrPatternSchema(lhs, rhs); @override @@ -2397,10 +2376,10 @@ } @override - PatternResult<Type> 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<Type>(); 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 @@ @override void visit(Harness h, CollectionElementContext context) { - SharedTypeSchemaView<Type> keySchema; - SharedTypeSchemaView<Type> valueSchema; + SharedTypeSchemaView keySchema; + SharedTypeSchemaView valueSchema; switch (context) { case CollectionElementContextMapEntry(:var keyType, :var valueType): keySchema = SharedTypeSchemaView(keyType); @@ -2498,8 +2477,7 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeMapPatternSchema( typeArguments: typeArguments?.wrapSharedTypeMapEntryView(), elements: elements); @@ -2537,12 +2515,12 @@ } @override - PatternResult<Type> 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<Type>(); + var requiredType = mapPatternResult.requiredType.unwrapTypeView<Type>(); 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 MiniAstOperations - with TypeAnalyzerOperationsMixin<Type, Var, TypeParameter, Type, String> - implements TypeAnalyzerOperations<Type, Var, TypeParameter, Type, String> { + with TypeAnalyzerOperationsMixin<Var, Type, String> + implements TypeAnalyzerOperations<Var, Type, String> { static const Map<String, bool> _coreExhaustiveness = const { '()': true, '(int, int?)': false, @@ -2665,21 +2643,20 @@ }; @override - late final SharedTypeView<Type> objectQuestionType = + late final SharedTypeView objectQuestionType = SharedTypeView(Type('Object?')); @override - late final SharedTypeView<Type> objectType = SharedTypeView(Type('Object')); + late final SharedTypeView objectType = SharedTypeView(Type('Object')); @override - late final SharedTypeSchemaView<Type> unknownType = - SharedTypeSchemaView(Type('_')); + late final SharedTypeSchemaView unknownType = SharedTypeSchemaView(Type('_')); @override - late final SharedTypeView<Type> intType = SharedTypeView(Type('int')); + late final SharedTypeView intType = SharedTypeView(Type('int')); @override - late final SharedTypeView<Type> doubleType = SharedTypeView(Type('double')); + late final SharedTypeView doubleType = SharedTypeView(Type('double')); bool? _legacy; @@ -2703,13 +2680,13 @@ final _variance = <String, List<Variance>>{}; @override - final SharedTypeView<Type> boolType = SharedTypeView(Type('bool')); + final SharedTypeView boolType = SharedTypeView(Type('bool')); @override - SharedTypeView<Type> get dynamicType => SharedTypeView(DynamicType.instance); + SharedTypeView get dynamicType => SharedTypeView(DynamicType.instance); @override - SharedTypeView<Type> get errorType => SharedTypeView(InvalidType.instance); + SharedTypeView get errorType => SharedTypeView(InvalidType.instance); bool get legacy => _legacy ?? false; @@ -2718,10 +2695,10 @@ } @override - SharedTypeView<Type> get neverType => SharedTypeView(NeverType.instance); + SharedTypeView get neverType => SharedTypeView(NeverType.instance); @override - SharedTypeView<Type> 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 @@ } @override - TypeClassification classifyType(SharedTypeView<Type> type) { - if (isSubtypeOfInternal(type.unwrapTypeView(), Type('Object'))) { + TypeClassification classifyType(SharedTypeView type) { + if (isSubtypeOfInternal(type.unwrapTypeView<Type>(), Type('Object'))) { return TypeClassification.nonNullable; - } else if (isSubtypeOfInternal(type.unwrapTypeView(), NullType.instance)) { + } else if (isSubtypeOfInternal( + type.unwrapTypeView<Type>(), NullType.instance)) { return TypeClassification.nullOrEquivalent; } else { return TypeClassification.potentiallyNullable; @@ -2782,17 +2760,16 @@ } @override - SharedTypeView<Type> extensionTypeErasure(SharedTypeView<Type> type) { + SharedTypeView extensionTypeErasure(SharedTypeView type) { var query = '${type.unwrapTypeView()}'; return SharedTypeView( _extensionTypeErasure[query] ?? type.unwrapTypeView()); } @override - SharedTypeView<Type> factor( - SharedTypeView<Type> from, SharedTypeView<Type> what) { - return SharedTypeView( - _typeSystem.factor(from.unwrapTypeView(), what.unwrapTypeView())); + SharedTypeView factor(SharedTypeView from, SharedTypeView what) { + return SharedTypeView(_typeSystem.factor( + from.unwrapTypeView<Type>(), what.unwrapTypeView<Type>())); } @override @@ -2827,39 +2804,38 @@ } @override - SharedTypeView<Type> greatestClosure(SharedTypeSchemaView<Type> schema) { + SharedTypeView greatestClosure(SharedTypeSchemaView schema) { return SharedTypeView(schema - .unwrapTypeSchemaView() + .unwrapTypeSchemaView<Type>() .closureWithRespectToUnknown(covariant: true) ?? schema.unwrapTypeSchemaView()); } @override - Type greatestClosureOfTypeInternal(Type type, - List<SharedTypeParameterStructure<Type>> typeParametersToEliminate) { + Type greatestClosureOfTypeInternal( + Type type, List<SharedTypeParameter> typeParametersToEliminate) { // TODO(paulberry): Implement greatest closure of types in mini ast. throw UnimplementedError(); } @override - bool isAlwaysExhaustiveType(SharedTypeView<Type> type) { - var query = type.unwrapTypeView().type; + bool isAlwaysExhaustiveType(SharedTypeView type) { + var query = type.unwrapTypeView<Type>().type; return _exhaustiveness[query] ?? fail('Unknown exhaustiveness query: $query'); } @override - bool isAssignableTo( - SharedTypeView<Type> fromType, SharedTypeView<Type> toType) { + bool isAssignableTo(SharedTypeView fromType, SharedTypeView toType) { if (legacy && isSubtypeOfInternal( - toType.unwrapTypeView(), fromType.unwrapTypeView())) { + toType.unwrapTypeView<Type>(), fromType.unwrapTypeView<Type>())) { return true; } if (fromType is DynamicType) return true; if (fromType is InvalidType) return true; return isSubtypeOfInternal( - fromType.unwrapTypeView(), toType.unwrapTypeView()); + fromType.unwrapTypeView<Type>(), toType.unwrapTypeView<Type>()); } @override @@ -2896,7 +2872,7 @@ } @override - bool isNever(SharedTypeView<Type> type) { + bool isNever(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); return unwrappedType is NeverType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none; @@ -2906,7 +2882,7 @@ 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 @@ 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 @@ } @override - bool isObject(SharedTypeView<Type> type) { + bool isObject(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); return unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -2968,7 +2944,7 @@ } @override - bool isTypeParameterType(SharedTypeView<Type> type) { + bool isTypeParameterType(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); return unwrappedType is TypeParameterType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none; @@ -2976,10 +2952,10 @@ @override bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView<Type> typeSchema, - required SharedTypeView<Type> type}) { + {required SharedTypeSchemaView typeSchema, + required SharedTypeView type}) { return isSubtypeOfInternal( - type.unwrapTypeView(), typeSchema.unwrapTypeSchemaView()); + type.unwrapTypeView<Type>(), typeSchema.unwrapTypeSchemaView<Type>()); } @override @@ -2988,15 +2964,15 @@ } @override - SharedTypeSchemaView<Type> iterableTypeSchema( - SharedTypeSchemaView<Type> elementTypeSchema) { + SharedTypeSchemaView iterableTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(PrimaryType(TypeRegistry.iterable, - args: [elementTypeSchema.unwrapTypeSchemaView()])); + args: [elementTypeSchema.unwrapTypeSchemaView<Type>()])); } @override - Type leastClosureOfTypeInternal(Type type, - List<SharedTypeParameterStructure<Type>> typeParametersToEliminate) { + Type leastClosureOfTypeInternal( + Type type, List<SharedTypeParameter> typeParametersToEliminate) { // TODO(paulberry): Implement greatest closure of types in mini ast. throw UnimplementedError(); } @@ -3083,7 +3059,7 @@ } @override - SharedTypeView<Type>? matchListType(SharedTypeView<Type> type) { + SharedTypeView? matchListType(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -3095,8 +3071,8 @@ } @override - ({SharedTypeView<Type> keyType, SharedTypeView<Type> valueType})? - matchMapType(SharedTypeView<Type> type) { + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -3111,7 +3087,7 @@ } @override - SharedTypeView<Type>? matchStreamType(SharedTypeView<Type> type) { + SharedTypeView? matchStreamType(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType is PrimaryType && unwrappedType.nullabilitySuffix == NullabilitySuffix.none && @@ -3124,8 +3100,8 @@ } @override - TypeDeclarationMatchResult<Type, String, Type>? - matchTypeDeclarationTypeInternal(Type type) { + TypeDeclarationMatchResult<Type, String>? matchTypeDeclarationTypeInternal( + Type type) { if (type is! PrimaryType) return null; TypeDeclarationKind typeDeclarationKind; if (type.isInterfaceType) { @@ -3157,14 +3133,14 @@ } @override - SharedTypeView<Type> normalize(SharedTypeView<Type> type) { + SharedTypeView normalize(SharedTypeView type) { var query = '${type.unwrapTypeView()}'; return SharedTypeView( _normalizeResults[query] ?? fail('Unknown query: $query')); } @override - SharedTypeView<Type> promoteToNonNull(SharedTypeView<Type> type) { + SharedTypeView promoteToNonNull(SharedTypeView type) { Type unwrappedType = type.unwrapTypeView(); if (unwrappedType.nullabilitySuffix == NullabilitySuffix.question) { return SharedTypeView( @@ -3178,31 +3154,33 @@ @override RecordType recordTypeInternal( - {required List<Type> positional, required List<(String, Type)> named}) { + {required List<SharedType> positional, + required covariant List<(String, SharedType)> named}) { return RecordType( - positionalTypes: positional, + positionalTypes: positional.cast<Type>(), 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<Type> streamTypeSchema( - SharedTypeSchemaView<Type> elementTypeSchema) { + SharedTypeSchemaView streamTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(PrimaryType(TypeRegistry.stream, - args: [elementTypeSchema.unwrapTypeSchemaView()])); + args: [elementTypeSchema.unwrapTypeSchemaView<Type>()])); } @override - SharedTypeView<Type>? tryPromoteToType( - SharedTypeView<Type> to, SharedTypeView<Type> from) { - var exception = (_promotionExceptions[from.unwrapTypeView().type] ?? - {})[to.unwrapTypeView().type]; + SharedTypeView? tryPromoteToType(SharedTypeView to, SharedTypeView from) { + var exception = (_promotionExceptions[from.unwrapTypeView<Type>().type] ?? + {})[to.unwrapTypeView<Type>().type]; if (exception != null) { return SharedTypeView(Type(exception)); } - if (isSubtypeOfInternal(to.unwrapTypeView(), from.unwrapTypeView())) { + if (isSubtypeOfInternal( + to.unwrapTypeView<Type>(), from.unwrapTypeView<Type>())) { return to; } else { return null; @@ -3210,11 +3188,11 @@ } @override - SharedTypeSchemaView<Type> typeToSchema(SharedTypeView<Type> type) => + SharedTypeSchemaView typeToSchema(SharedTypeView type) => SharedTypeSchemaView(type.unwrapTypeView()); @override - SharedTypeView<Type> variableType(Var variable) { + SharedTypeView variableType(Var variable) { return SharedTypeView(variable.type); } @@ -3229,18 +3207,20 @@ } @override - TypeConstraintGenerator<Type, NamedFunctionParameter, Var, TypeParameter, - Type, String, Node> + TypeConstraintGenerator<Var, Type, String, Node> createTypeConstraintGenerator( {required TypeConstraintGenerationDataForTesting? typeConstraintGenerationDataForTesting, - required List<TypeParameter> typeParametersToInfer, - required TypeAnalyzerOperations<Type, Var, TypeParameter, Type, - String> + required List<SharedTypeParameterView> typeParametersToInfer, + required TypeAnalyzerOperations<Var, Type, String> typeAnalyzerOperations, required bool inferenceUsingBoundsIsEnabled}) { - return TypeConstraintGatherer( - {for (var typeParameter in typeParametersToInfer) typeParameter.name}); + return TypeConstraintGatherer({ + for (var typeParameter in typeParametersToInfer) + typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure<TypeParameter>() + .name + }); } } @@ -3297,8 +3277,7 @@ String toString() => '$operand!'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeNonNullAssert(this, operand); } } @@ -3317,8 +3296,7 @@ String toString() => '!$operand'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeLogicalNot(this, operand); } } @@ -3333,7 +3311,7 @@ : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => h.typeAnalyzer + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer .analyzeNullCheckOrAssertPatternSchema(inner, isAssert: isAssert); @override @@ -3343,11 +3321,11 @@ } @override - PatternResult<Type> 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<Type>(); 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 @@ String toString() => 'null'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ }) : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { return h.typeAnalyzer .analyzeObjectPatternSchema(SharedTypeView(requiredType)); } @@ -3404,11 +3381,12 @@ } @override - PatternResult<Type> 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<Type>(); + var requiredType = objectPatternResult.requiredType.unwrapTypeView<Type>(); 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 @@ String toString() => '($expr)'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeParenthesizedExpression(this, expr, schema); } } @@ -3458,7 +3435,7 @@ ParenthesizedPattern._(this.inner, {required super.location}) : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => inner.computeSchema(h); + SharedTypeSchemaView computeSchema(Harness h) => inner.computeSchema(h); @override void preVisit(PreVisitor visitor, VariableBinder<Node, Var> variableBinder, @@ -3466,7 +3443,7 @@ inner.preVisit(visitor, variableBinder, isInAssignment: isInAssignment); @override - PatternResult<Type> visit(Harness h, SharedMatchContext context) { + PatternResult visit(Harness h, SharedMatchContext context) { return inner.visit(h, context); } @@ -3511,7 +3488,7 @@ location: location); } - SharedTypeSchemaView<Type> computeSchema(Harness h); + SharedTypeSchemaView computeSchema(Harness h); Pattern or(Pattern other) => LogicalOrPattern(this, other, location: computeLocation()); @@ -3527,7 +3504,7 @@ @override String toString() => _debugString(needsKeywordOrType: true); - PatternResult<Type> visit(Harness h, SharedMatchContext context); + PatternResult visit(Harness h, SharedMatchContext context); GuardedPattern when(ProtoExpression? guard) { return GuardedPattern._( @@ -3555,8 +3532,7 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ String toString() => '(expr with type $type)'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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>(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -3794,13 +3769,12 @@ String toString() => '$lhs++'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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>(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -3857,8 +3831,7 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzePropertyGet( this, target is CascadePlaceholder ? null : target, propertyName, isNullAware: isNullAware); @@ -3873,7 +3846,7 @@ } var receiverType = h.typeAnalyzer .analyzeExpression(target, h.operations.unknownType) - .unwrapTypeView(); + .unwrapTypeView<Type>(); var member = h.typeAnalyzer._lookupMember(receiverType, propertyName); return h.flow .promotedPropertyType(ExpressionPropertyTarget(target), propertyName, @@ -4182,7 +4155,7 @@ RecordPattern._(this.fields, {required super.location}) : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { return h.typeAnalyzer.analyzeRecordPatternSchema( fields: fields, ); @@ -4198,11 +4171,12 @@ } @override - PatternResult<Type> 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<Type>(); + var requiredType = recordPatternResult.requiredType.unwrapTypeView<Type>(); 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 @@ : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) => + SharedTypeSchemaView computeSchema(Harness h) => h.typeAnalyzer.analyzeRelationalPatternSchema(); @override @@ -4261,10 +4235,10 @@ } @override - PatternResult<Type> 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<Type>(); 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 @@ String toString() => 'second($first, $second)'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer .analyzeSwitchExpression(this, scrutinee, cases.length, schema); h.irBuilder.apply( @@ -4514,7 +4486,7 @@ expectLastCaseTerminates ?? anything); expect(analysisResult.requiresExhaustivenessValidation, expectRequiresExhaustivenessValidation ?? anything); - expect(analysisResult.scrutineeType.unwrapTypeView().type, + expect(analysisResult.scrutineeType.unwrapTypeView<Type>().type, expectScrutineeType ?? anything); h.irBuilder.apply( 'switch', @@ -4585,8 +4557,7 @@ String toString() => 'this'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ {_LValueDisposition disposition = _LValueDisposition.read}) {} @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var result = h.typeAnalyzer.analyzeThisOrSuperPropertyGet( this, propertyName, isSuperAccess: isSuperAccess); @@ -4661,8 +4631,7 @@ String toString() => 'throw ...'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { return h.typeAnalyzer.analyzeThrow(this, operand); } } @@ -4870,7 +4839,7 @@ : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { if (isAssignedVariable) { return h.typeAnalyzer.analyzeAssignedVariablePatternSchema(variable); } else { @@ -4894,7 +4863,7 @@ } @override - PatternResult<Type> 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 @@ .analyzeDeclaredVariablePattern(context, this, variable, variable.name, declaredType?.wrapSharedTypeView()); var matchedType = - declaredVariablePatternResult.matchedValueType.unwrapTypeView(); + declaredVariablePatternResult.matchedValueType.unwrapTypeView<Type>(); var staticType = - declaredVariablePatternResult.staticType.unwrapTypeView(); + declaredVariablePatternResult.staticType.unwrapTypeView<Type>(); h.typeAnalyzer.handleDeclaredVariablePattern(this, matchedType: matchedType, staticType: staticType); return declaredVariablePatternResult; @@ -4948,8 +4917,7 @@ String toString() => variable.name; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> 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 @@ : super._(); @override - SharedTypeSchemaView<Type> computeSchema(Harness h) { + SharedTypeSchemaView computeSchema(Harness h) { return h.typeAnalyzer.analyzeWildcardPatternSchema( declaredType: declaredType?.wrapSharedTypeView(), ); @@ -5022,13 +4990,13 @@ {required bool isInAssignment}) {} @override - PatternResult<Type> 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<Type>(); 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 @@ } @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { late MiniIRTmp beforeTmp; if (before != null) { h.typeAnalyzer.dispatchStatement(before!); @@ -5101,7 +5068,7 @@ if (before != null) { h.irBuilder.let(beforeTmp, location: location); } - return new ExpressionTypeAnalysisResult<Type>(type: type); + return new ExpressionTypeAnalysisResult(type: type); } } @@ -5124,8 +5091,7 @@ String toString() => '$lhs = $rhs'; @override - ExpressionTypeAnalysisResult<Type> visit( - Harness h, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult visit(Harness h, SharedTypeSchemaView schema) { var rhs = this.rhs; Type type; if (rhs == null) { @@ -5141,7 +5107,7 @@ } lhs._visitWrite(h, this, type, rhs); // TODO(paulberry): null shorting - return new ExpressionTypeAnalysisResult<Type>(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } } @@ -5163,8 +5129,8 @@ class _MiniAstErrors implements - TypeAnalyzerErrors<Node, Statement, Expression, Var, - SharedTypeView<Type>, Pattern, void>, + TypeAnalyzerErrors<Node, Statement, Expression, Var, SharedTypeView, + Pattern, void>, VariableBinderErrors<Node, Var> { final Set<String> _accumulatedErrors = {}; @@ -5185,8 +5151,8 @@ void caseExpressionTypeMismatch( {required Expression scrutinee, required Expression caseExpression, - required SharedTypeView<Type> scrutineeType, - required SharedTypeView<Type> caseExpressionType, + required SharedTypeView scrutineeType, + required SharedTypeView caseExpressionType, required bool nullSafetyEnabled}) { _recordError('caseExpressionTypeMismatch', { 'scrutinee': scrutinee, @@ -5289,7 +5255,7 @@ @override void matchedTypeIsStrictlyNonNullable({ required Pattern pattern, - required SharedTypeView<Type> matchedType, + required SharedTypeView matchedType, }) { _recordError('matchedTypeIsStrictlyNonNullable', { 'pattern': pattern, @@ -5300,8 +5266,8 @@ @override void matchedTypeIsSubtypeOfRequired({ required Pattern pattern, - required SharedTypeView<Type> matchedType, - required SharedTypeView<Type> requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { _recordError('matchedTypeIsSubtypeOfRequired', { 'pattern': pattern, @@ -5319,7 +5285,7 @@ void patternForInExpressionIsNotIterable({ required Node node, required Expression expression, - required SharedTypeView<Type> expressionType, + required SharedTypeView expressionType, }) { _recordError('patternForInExpressionIsNotIterable', { 'node': node, @@ -5332,8 +5298,8 @@ void patternTypeMismatchInIrrefutableContext( {required Node pattern, required Node context, - required SharedTypeView<Type> matchedType, - required SharedTypeView<Type> requiredType}) { + required SharedTypeView matchedType, + required SharedTypeView requiredType}) { _recordError('patternTypeMismatchInIrrefutableContext', { 'pattern': pattern, 'context': context, @@ -5352,8 +5318,8 @@ @override void relationalPatternOperandTypeNotAssignable({ required Pattern pattern, - required SharedTypeView<Type> operandType, - required SharedTypeView<Type> parameterType, + required SharedTypeView operandType, + required SharedTypeView parameterType, }) { _recordError('relationalPatternOperandTypeNotAssignable', { 'pattern': pattern, @@ -5365,7 +5331,7 @@ @override void relationalPatternOperatorReturnTypeNotAssignableToBool({ required Pattern pattern, - required SharedTypeView<Type> returnType, + required SharedTypeView returnType, }) { _recordError('relationalPatternOperatorReturnTypeNotAssignableToBool', { 'pattern': pattern, @@ -5428,9 +5394,9 @@ class _MiniAstTypeAnalyzer with - TypeAnalyzer<Type, Node, Statement, Expression, Var, Pattern, void, - TypeParameter, Type, String>, - NullShortingMixin<MiniIRTmp, Expression, SharedTypeView<Type>> { + TypeAnalyzer<Node, Statement, Expression, Var, Pattern, void, Type, + String>, + NullShortingMixin<MiniIRTmp, Expression, SharedTypeView> { final Harness _harness; @override @@ -5453,13 +5419,13 @@ /// 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<Type>? _currentCascadeTargetType; + SharedTypeView? _currentCascadeTargetType; _MiniAstTypeAnalyzer(this._harness, this.options); @override - FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView<Type>> - get flow => _harness.flow; + FlowAnalysis<Node, Statement, Expression, Var, SharedTypeView> get flow => + _harness.flow; Type get nullType => NullType.instance; @@ -5481,7 +5447,7 @@ flow.assert_end(); } - ExpressionTypeAnalysisResult<Type> analyzeBinaryExpression( + ExpressionTypeAnalysisResult analyzeBinaryExpression( Expression node, Expression lhs, String operatorName, Expression rhs) { bool isEquals = false; bool isNot = false; @@ -5515,7 +5481,7 @@ flow.logicalBinaryOp_begin(); } var leftType = analyzeExpression(lhs, operations.unknownType); - ExpressionInfo<SharedTypeView<Type>>? leftInfo; + ExpressionInfo<SharedTypeView>? leftInfo; if (isEquals) { leftInfo = flow.equalityOperand_end(lhs); } else if (isLogical) { @@ -5529,7 +5495,7 @@ } else if (isLogical) { flow.logicalBinaryOp_end(node, rhs, isAnd: isAnd); } - return new ExpressionTypeAnalysisResult<Type>(type: operations.boolType); + return new ExpressionTypeAnalysisResult(type: operations.boolType); } void analyzeBlock(Iterable<Statement> statements) { @@ -5547,11 +5513,8 @@ flow.handleBreak(target); } - ExpressionTypeAnalysisResult<Type> 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 @@ var ifFalseType = analyzeExpression(ifFalse, operations.unknownType); var lubType = operations.lub(ifTrueType, ifFalseType); flow.conditional_end(node, lubType, ifFalse, ifFalseType); - return new ExpressionTypeAnalysisResult<Type>(type: lubType); + return new ExpressionTypeAnalysisResult(type: lubType); } void analyzeContinueStatement(Statement? target) { @@ -5579,13 +5542,13 @@ analyzeExpression(expression, operations.unknownType); } - ExpressionTypeAnalysisResult<Type> 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<Type>( + return new ExpressionTypeAnalysisResult( type: operations.lub( flow.operations.promoteToNonNull(leftType), rightType)); } @@ -5596,11 +5559,11 @@ flow.labeledStatement_end(); } - ExpressionTypeAnalysisResult<Type> analyzeLogicalNot( + ExpressionTypeAnalysisResult analyzeLogicalNot( Expression node, Expression expression) { analyzeExpression(expression, operations.unknownType); flow.logicalNot_end(node, expression); - return new ExpressionTypeAnalysisResult<Type>(type: operations.boolType); + return new ExpressionTypeAnalysisResult(type: operations.boolType); } /// Invokes the appropriate flow analysis methods, and creates the IR @@ -5611,7 +5574,7 @@ /// expressions. /// /// Named arguments are not supported. - ExpressionTypeAnalysisResult<Type> analyzeMethodInvocation(Expression node, + ExpressionTypeAnalysisResult analyzeMethodInvocation(Expression node, Expression? target, String methodName, List<Expression> arguments, {required bool isNullAware}) { // Analyze the target, generate its IR, and look up the method's type. @@ -5644,31 +5607,27 @@ // Form the IR for the member invocation. _harness.irBuilder.apply(methodName, inputKinds, Kind.expression, location: node.location); - return new ExpressionTypeAnalysisResult<Type>( - type: SharedTypeView(returnType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(returnType)); } - ExpressionTypeAnalysisResult<Type> analyzeNonNullAssert( + ExpressionTypeAnalysisResult analyzeNonNullAssert( Expression node, Expression expression) { var type = analyzeExpression(expression, operations.unknownType); flow.nonNullAssert_end(expression); - return new ExpressionTypeAnalysisResult<Type>( + return new ExpressionTypeAnalysisResult( type: flow.operations.promoteToNonNull(type)); } - ExpressionTypeAnalysisResult<Type> analyzeNullLiteral(Expression node) { + ExpressionTypeAnalysisResult analyzeNullLiteral(Expression node) { flow.nullLiteral(node, SharedTypeView(nullType)); - return new ExpressionTypeAnalysisResult<Type>( - type: SharedTypeView(nullType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(nullType)); } - ExpressionTypeAnalysisResult<Type> analyzeParenthesizedExpression( - Expression node, - Expression expression, - SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult analyzeParenthesizedExpression( + Expression node, Expression expression, SharedTypeSchemaView schema) { var type = analyzeExpression(expression, schema); flow.parenthesizedExpression(node, expression); - return new ExpressionTypeAnalysisResult<Type>(type: type); + return new ExpressionTypeAnalysisResult(type: type); } /// Invokes the appropriate flow analysis methods, and creates the IR @@ -5678,7 +5637,7 @@ /// property being accessed. /// /// Null-aware property accesses are not supported. - ExpressionTypeAnalysisResult<Type> 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 @@ // Build the property get IR. _harness.irBuilder.propertyGet(propertyName, location: node.location); // TODO(paulberry): handle null shorting - return new ExpressionTypeAnalysisResult<Type>( - type: SharedTypeView(propertyType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(propertyType)); } void analyzeReturnStatement() { flow.handleExit(); } - ExpressionTypeAnalysisResult<Type> analyzeThis(Expression node) { + ExpressionTypeAnalysisResult analyzeThis(Expression node) { var thisType = this.thisType; flow.thisOrSuper(node, SharedTypeView(thisType), isSuper: false); - return new ExpressionTypeAnalysisResult<Type>( - type: SharedTypeView(thisType)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(thisType)); } - ExpressionTypeAnalysisResult<Type> analyzeThisOrSuperPropertyGet( + ExpressionTypeAnalysisResult analyzeThisOrSuperPropertyGet( Expression node, String propertyName, {required bool isSuperAccess}) { var member = _lookupMember(thisType, propertyName); @@ -5718,15 +5675,15 @@ member, SharedTypeView(memberType)) ?.unwrapTypeView(); - return new ExpressionTypeAnalysisResult<Type>( + return new ExpressionTypeAnalysisResult( type: SharedTypeView(promotedType ?? memberType)); } - ExpressionTypeAnalysisResult<Type> analyzeThrow( + ExpressionTypeAnalysisResult analyzeThrow( Expression node, Expression expression) { analyzeExpression(expression, operations.unknownType); flow.handleExit(); - return new ExpressionTypeAnalysisResult<Type>(type: operations.neverType); + return new ExpressionTypeAnalysisResult(type: operations.neverType); } void analyzeTryStatement(Statement node, Statement body, @@ -5757,26 +5714,26 @@ } } - ExpressionTypeAnalysisResult<Type> analyzeTypeCast( + ExpressionTypeAnalysisResult analyzeTypeCast( Expression node, Expression expression, Type type) { analyzeExpression(expression, operations.unknownType); flow.asExpression_end(expression, SharedTypeView(type)); - return new ExpressionTypeAnalysisResult<Type>(type: SharedTypeView(type)); + return new ExpressionTypeAnalysisResult(type: SharedTypeView(type)); } - ExpressionTypeAnalysisResult<Type> 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>(type: operations.boolType); + return new ExpressionTypeAnalysisResult(type: operations.boolType); } - ExpressionTypeAnalysisResult<Type> analyzeVariableGet( + ExpressionTypeAnalysisResult analyzeVariableGet( Expression node, Var variable, void Function(Type?)? callback) { var promotedType = flow.variableRead(node, variable); callback?.call(promotedType?.unwrapTypeView()); - return new ExpressionTypeAnalysisResult<Type>( + return new ExpressionTypeAnalysisResult( type: promotedType ?? SharedTypeView(variable.type)); } @@ -5788,8 +5745,8 @@ flow.whileStatement_end(); } - SharedTypeView<Type> createNullAwareGuard( - Expression target, SharedTypeView<Type> 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 @@ } @override - ExpressionTypeAnalysisResult<Type> dispatchExpression( - Expression expression, SharedTypeSchemaView<Type> schema) { + ExpressionTypeAnalysisResult dispatchExpression( + Expression expression, SharedTypeSchemaView schema) { if (expression._expectedSchema case var expectedSchema?) { - expect(schema.unwrapTypeSchemaView().type, expectedSchema); + expect(schema.unwrapTypeSchemaView<Type>().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>().type, expectedType, reason: 'at ${expression.location}'); } if (expression._expectedIR case var expectedIR?) { @@ -5828,13 +5785,13 @@ } @override - PatternResult<Type> dispatchPattern( + PatternResult dispatchPattern( SharedMatchContext context, covariant Pattern node) { return node.visit(_harness, context); } @override - SharedTypeSchemaView<Type> dispatchPatternSchema(covariant Pattern node) { + SharedTypeSchemaView dispatchPatternSchema(covariant Pattern node) { return node.computeSchema(_harness); } @@ -5848,8 +5805,8 @@ } @override - SharedTypeView<Type> downwardInferObjectPatternRequiredType({ - required SharedTypeView<Type> matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required covariant ObjectPattern pattern, }) { var requiredType = pattern.requiredType; @@ -5878,7 +5835,7 @@ required JoinedPatternVariableLocation location, required JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView<Type> type, + required SharedTypeView type, }) { variable.isFinal = isFinal; variable.type = type.unwrapTypeView(); @@ -6036,7 +5993,7 @@ @override void handleMapPatternEntry( - Pattern container, Node entryElement, SharedTypeView<Type> keyType) { + Pattern container, Node entryElement, SharedTypeView keyType) { _irBuilder.apply('mapPatternEntry', [Kind.expression, Kind.pattern], Kind.mapPatternElement, location: entryElement.location); @@ -6101,8 +6058,7 @@ } @override - void handleNullShortingStep( - MiniIRTmp guard, SharedTypeView<Type> inferredType) { + void handleNullShortingStep(MiniIRTmp guard, SharedTypeView inferredType) { _irBuilder.ifNotNull(guard, location: guard.location); } @@ -6114,11 +6070,11 @@ }) {} @override - void handleSwitchScrutinee(SharedTypeView<Type> type) {} + void handleSwitchScrutinee(SharedTypeView type) {} @override bool isLegacySwitchExhaustive( - covariant SwitchStatement node, SharedTypeView<Type> expressionType) { + covariant SwitchStatement node, SharedTypeView expressionType) { return node.isLegacyExhaustive!; } @@ -6136,9 +6092,9 @@ } @override - (_PropertyElement?, SharedTypeView<Type>) resolveObjectPatternPropertyGet({ + (_PropertyElement?, SharedTypeView) resolveObjectPatternPropertyGet({ required Pattern objectPattern, - required SharedTypeView<Type> receiverType, + required SharedTypeView receiverType, required shared.RecordPatternField<Node, Pattern> field, }) { var propertyMember = @@ -6151,14 +6107,14 @@ } @override - RelationalOperatorResolution<Type>? resolveRelationalPatternOperator( - covariant RelationalPattern node, SharedTypeView<Type> matchedValueType) { + RelationalOperatorResolution? resolveRelationalPatternOperator( + covariant RelationalPattern node, SharedTypeView matchedValueType) { return _harness.resolveRelationalPatternOperator( matchedValueType.unwrapTypeView(), node.operator); } @override - void setVariableType(Var variable, SharedTypeView<Type> type) { + void setVariableType(Var variable, SharedTypeView type) { variable.type = type.unwrapTypeView(); } @@ -6166,8 +6122,7 @@ String toString() => _irBuilder.toString(); @override - SharedTypeView<Type> variableTypeFromInitializerType( - SharedTypeView<Type> 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 @@ // 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<Type>().recursivelyDemote(covariant: true) ?? type.unwrapTypeView()); } @@ -6199,7 +6154,7 @@ {required String location, required bool isNullAware}) { // Analyze the target, and generate its IR. PropertyTarget<Expression> propertyTarget; - SharedTypeView<Type> targetType; + SharedTypeView targetType; if (target == null) { if (isNullAware) { fail( @@ -6219,7 +6174,8 @@ } // 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<Type>(); 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 ef5dba0..aa0b2f3 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 'mini_ast.dart'; import 'mini_types.dart'; -class TypeConstraintGatherer extends TypeConstraintGenerator<Type, - NamedFunctionParameter, Var, TypeParameter, Type, String, Node> - with - TypeConstraintGeneratorMixin<Type, NamedFunctionParameter, Var, - TypeParameter, Type, String, Node> { +class TypeConstraintGatherer + extends TypeConstraintGenerator<Var, Type, String, Node> + with TypeConstraintGeneratorMixin<Var, Type, String, Node> { @override final Set<TypeParameter> typeParametersToConstrain = <TypeParameter>{}; @@ -51,8 +49,7 @@ } @override - Map<TypeParameter, - MergedTypeConstraint<Type, TypeParameter, Var, Type, String>> + Map<TypeParameter, MergedTypeConstraint<Var, Type, String>> computeConstraints() { // TODO(cstefantsova): implement computeConstraints throw UnimplementedError(); @@ -91,16 +88,10 @@ } @override - ( - Type, - Type, { - List<TypeParameter> typeParametersToEliminate - }) instantiateFunctionTypesAndProvideFreshTypeParameters( - SharedFunctionTypeStructure<Type, TypeParameter, NamedFunctionParameter> - p, - SharedFunctionTypeStructure<Type, TypeParameter, NamedFunctionParameter> - q, - {required bool leftSchema}) { + (Type, Type, {List<TypeParameter> 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 0dcf1e6..1b27904 100644 --- a/pkg/_fe_analyzer_shared/test/mini_types.dart +++ b/pkg/_fe_analyzer_shared/test/mini_types.dart
@@ -19,8 +19,7 @@ /// Representation of the type `dynamic` suitable for unit testing of code in /// the `_fe_analyzer_shared` package. -class DynamicType extends _SpecialSimpleType - implements SharedDynamicTypeStructure<Type> { +class DynamicType extends _SpecialSimpleType implements SharedDynamicType { static final instance = DynamicType._(); DynamicType._() @@ -58,10 +57,7 @@ /// Representation of a function type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class FunctionType extends Type - implements - SharedFunctionTypeStructure<Type, TypeParameter, - NamedFunctionParameter> { +class FunctionType extends Type implements SharedFunctionType { final Type returnType; @override @@ -398,8 +394,7 @@ /// Representation of an invalid type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class InvalidType extends _SpecialSimpleType - implements SharedInvalidTypeStructure<Type> { +class InvalidType extends _SpecialSimpleType implements SharedInvalidType { static final instance = InvalidType._(); InvalidType._() @@ -412,7 +407,7 @@ /// A named parameter of a function type. class NamedFunctionParameter implements - SharedNamedFunctionParameterStructure<Type>, + SharedNamedFunctionParameter, _Substitutable<NamedFunctionParameter> { final String name; @@ -452,8 +447,7 @@ String toString() => [if (isRequired) 'required', type, name].join(' '); } -class NamedType - implements SharedNamedTypeStructure<Type>, _Substitutable<NamedType> { +class NamedType implements SharedNamedType, _Substitutable<NamedType> { final String name; final Type type; @@ -496,8 +490,7 @@ /// Representation of the type `Null` suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class NullType extends _SpecialSimpleType - implements SharedNullTypeStructure<Type> { +class NullType extends _SpecialSimpleType implements SharedNullType { static final instance = NullType._(); NullType._() @@ -607,7 +600,7 @@ args.isEmpty ? name : '$name<${args.join(', ')}>'; } -class RecordType extends Type implements SharedRecordTypeStructure<Type> { +class RecordType extends Type implements SharedRecordType { final List<Type> positionalTypes; final List<NamedType> namedTypes; @@ -636,8 +629,7 @@ List<NamedType> get sortedNamedTypes => namedTypes; @override - List<SharedNamedTypeStructure<Type>> get sortedNamedTypesShared => - sortedNamedTypes; + List<SharedNamedType> get sortedNamedTypesShared => sortedNamedTypes; @override bool operator ==(Object other) => @@ -783,7 +775,7 @@ /// Representation of a type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -abstract class Type implements SharedTypeStructure<Type>, _Substitutable<Type> { +abstract class Type implements SharedType, _Substitutable<Type> { @override final NullabilitySuffix nullabilitySuffix; @@ -819,7 +811,7 @@ 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 @@ } /// A type name that represents a type variable. -class TypeParameter extends TypeNameInfo - implements SharedTypeParameterStructure<Type> { +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 @@ /// Representation of the unknown type suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class UnknownType extends Type implements SharedUnknownTypeStructure<Type> { +class UnknownType extends Type implements SharedUnknownType { const UnknownType({super.nullabilitySuffix = NullabilitySuffix.none}) : super._(); @@ -1739,8 +1730,7 @@ /// Representation of the type `void` suitable for unit testing of code in the /// `_fe_analyzer_shared` package. -class VoidType extends _SpecialSimpleType - implements SharedVoidTypeStructure<Type> { +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 d1b1d13..9449289 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/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<TypeImpl> { +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 11fe066..61c4346 100644 --- a/pkg/analyzer/lib/src/dart/ast/ast.dart +++ b/pkg/analyzer/lib/src/dart/ast/ast.dart
@@ -833,7 +833,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -2357,7 +2357,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -4031,7 +4031,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -4790,7 +4790,7 @@ /// 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<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ); @@ -5024,7 +5024,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11301,7 +11301,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11405,7 +11405,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11484,7 +11484,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -11740,10 +11740,7 @@ @override DartType computePatternSchema(ResolverVisitor resolverVisitor) { var typeArgumentNodes = this.typeArguments?.arguments; - ({ - SharedTypeView<DartType> keyType, - SharedTypeView<DartType> valueType - })? typeArguments; + ({SharedTypeView keyType, SharedTypeView valueType})? typeArguments; if (typeArgumentNodes != null && typeArgumentNodes.length == 2) { typeArguments = ( keyType: SharedTypeView(typeArgumentNodes[0].typeOrThrow), @@ -11759,7 +11756,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13074,7 +13071,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13210,7 +13207,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13387,7 +13384,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -13574,7 +13571,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -14734,7 +14731,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -15186,7 +15183,7 @@ } @override - PatternResult<DartType> resolvePattern( + PatternResult resolvePattern( ResolverVisitor resolverVisitor, SharedMatchContext context, ) { @@ -18866,7 +18863,7 @@ } @override - PatternResult<DartType> 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 8dee451..6569a0b 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart
@@ -4662,9 +4662,7 @@ /// A mixin that provides a common implementation for methods defined in /// [FormalParameterElement]. mixin FormalParameterElementMixin - implements - FormalParameterElement, - SharedNamedFunctionParameterStructure<TypeImpl> { + implements FormalParameterElement, SharedNamedFunctionParameter { @override void appendToWithoutDelimiters2(StringBuffer buffer) { buffer.write( @@ -11364,7 +11362,7 @@ FragmentedAnnotatableElementMixin<TypeParameterFragment>, FragmentedElementMixin<TypeParameterFragment>, _NonTopLevelVariableOrParameter - implements TypeParameterElement2, SharedTypeParameterStructure<TypeImpl> { + 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 3fbdcd9..1b6af46 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 @@ UnknownInferredType.instance)) { boundConstraint = _typeSystemOperations.mergeInConstraintsFromBound( typeParameterToInfer: typeParameterToInfer, - typeParametersToInfer: _typeFormals, + typeParametersToInfer: + _typeFormals.cast<SharedTypeParameterView>(), lower: constraint.lower.unwrapTypeSchemaView(), inferencePhaseConstraints: inferencePhaseConstraints, dataForTesting: dataForTesting, @@ -644,7 +645,8 @@ UnknownInferredType.instance)) { boundConstraint = _typeSystemOperations.mergeInConstraintsFromBound( typeParameterToInfer: typeParameterToInfer, - typeParametersToInfer: _typeFormals, + typeParametersToInfer: + _typeFormals.cast<SharedTypeParameterView>(), 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 f7baa46..74ca4f0 100644 --- a/pkg/analyzer/lib/src/dart/element/type.dart +++ b/pkg/analyzer/lib/src/dart/element/type.dart
@@ -35,7 +35,7 @@ /// The [Type] representing the type `dynamic`. class DynamicTypeImpl extends TypeImpl - implements DynamicType, SharedDynamicTypeStructure<TypeImpl> { + implements DynamicType, SharedDynamicType { /// The unique instance of this class. static final DynamicTypeImpl instance = DynamicTypeImpl._(); @@ -88,10 +88,7 @@ /// The type of a function, method, constructor, getter, or setter. class FunctionTypeImpl extends TypeImpl - implements - FunctionType, - SharedFunctionTypeStructure<TypeImpl, TypeParameterElementImpl2, - FormalParameterElementMixin> { + implements FunctionType, SharedFunctionType { @override late int hashCode = _computeHashCode(); @@ -1191,7 +1188,7 @@ } class InvalidTypeImpl extends TypeImpl - implements InvalidType, SharedInvalidTypeStructure<TypeImpl> { + implements InvalidType, SharedInvalidType { /// The unique instance of this class. static final InvalidTypeImpl instance = InvalidTypeImpl._(); @@ -1315,8 +1312,7 @@ /// A concrete implementation of [DartType] representing the type `Null`, with /// no type parameters and no nullability suffix. -class NullTypeImpl extends InterfaceTypeImpl - implements SharedNullTypeStructure<TypeImpl> { +class NullTypeImpl extends InterfaceTypeImpl implements SharedNullType { NullTypeImpl({ required super.element3, super.alias, @@ -1341,8 +1337,7 @@ type = type as TypeImpl; } -class RecordTypeImpl extends TypeImpl - implements RecordType, SharedRecordTypeStructure<TypeImpl> { +class RecordTypeImpl extends TypeImpl implements RecordType, SharedRecordType { @override final List<RecordTypePositionalFieldImpl> positionalFields; @@ -1408,8 +1403,7 @@ List<RecordTypeNamedFieldImpl> get sortedNamedTypes => namedTypes; @override - List<SharedNamedTypeStructure<TypeImpl>> get sortedNamedTypesShared => - sortedNamedTypes; + List<SharedNamedType> get sortedNamedTypesShared => sortedNamedTypes; @override bool operator ==(Object other) { @@ -1509,7 +1503,7 @@ } class RecordTypeNamedFieldImpl extends RecordTypeFieldImpl - implements RecordTypeNamedField, SharedNamedTypeStructure<TypeImpl> { + implements RecordTypeNamedField, SharedNamedType { @override final String name; @@ -1634,7 +1628,7 @@ } @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<TypeParameterElement> parameters) { @@ -1834,8 +1828,7 @@ } /// A concrete implementation of a [VoidType]. -class VoidTypeImpl extends TypeImpl - implements VoidType, SharedVoidTypeStructure<TypeImpl> { +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 c4ddb05..02a1ed7 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/resolver/flow_analysis_visitor.dart'; /// Instance of [shared.GeneratedTypeConstraint] specific to the Analyzer. -typedef GeneratedTypeConstraint = shared.GeneratedTypeConstraint<DartType, - TypeParameterElementImpl2, PromotableElementImpl2>; +typedef GeneratedTypeConstraint + = shared.GeneratedTypeConstraint<PromotableElementImpl2>; /// 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<DartType, PromotableElementImpl2, - TypeParameterElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>; + = shared.TypeConstraintFromExtendsClause<PromotableElementImpl2, + InterfaceTypeImpl, InterfaceElementImpl2>; /// Instance of [shared.TypeConstraintFromFunctionContext] specific to the Analyzer. typedef TypeConstraintFromFunctionContext - = shared.TypeConstraintFromFunctionContext< - DartType, - DartType, - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2>; + = shared.TypeConstraintFromFunctionContext<PromotableElementImpl2, + InterfaceTypeImpl, InterfaceElementImpl2>; /// 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<DartType, - TypeParameterElementImpl2, PromotableElementImpl2, AstNodeImpl>; + = shared.TypeConstraintGenerationDataForTesting<PromotableElementImpl2, + AstNodeImpl>; /// 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<PromotableElementImpl2, + InterfaceTypeImpl, InterfaceElementImpl2, AstNodeImpl> { @override final Set<TypeParameterElementImpl2> typeParametersToConstrain = Set.identity(); @@ -151,7 +114,8 @@ 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 @@ 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 @@ } 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 @@ 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 8c98df8..25b8df9 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 @@ /// parameters that we do not know yet. Notationally it is written `_`, for /// example `List<_>`. This is distinct from `List<dynamic>`. These types will /// never appear in the final resolved AST. -class UnknownInferredType extends TypeImpl - implements SharedUnknownTypeStructure<TypeImpl> { +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 2f98b98..f90f4f9 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 @@ DartType writeType, Expression right, DartType rightType, { - required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted, + required Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted, }) { if (writeType is! VoidType && _checkForUseOfVoidResult(right)) { return; @@ -260,7 +259,7 @@ } void _resolveTypes(AssignmentExpressionImpl node, - {required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? + {required Map<SharedTypeView, NonPromotionReason> 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 9c3e91c..66d0494 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 @@ } void _checkNonBoolOperand(Expression operand, String operator, - {required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? + {required Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { _resolver.boolExpressionVerifier.checkForNonBoolExpression( operand, @@ -99,7 +99,7 @@ var flowAnalysis = _resolver.flowAnalysis; var flow = flowAnalysis.flow; - ExpressionInfo<SharedTypeView<DartType>>? leftInfo; + ExpressionInfo<SharedTypeView>? 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 848a3e1..2b97589 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 @@ /// The current flow, when resolving a function body, or `null` otherwise. FlowAnalysis<AstNodeImpl, StatementImpl, ExpressionImpl, - PromotableElementImpl2, SharedTypeView<DartType>>? flow; + PromotableElementImpl2, SharedTypeView>? flow; FlowAnalysisHelper(bool retainDataForTesting, FeatureSet featureSet, {required TypeSystemOperations typeSystemOperations}) @@ -182,7 +182,7 @@ } flow = isNonNullableByDefault ? FlowAnalysis<AstNodeImpl, StatementImpl, ExpressionImpl, - PromotableElementImpl2, SharedTypeView<DartType>>( + PromotableElementImpl2, SharedTypeView>( typeOperations, assignedVariables!, respectImplicitlyTypedVarInitializers: @@ -190,9 +190,12 @@ fieldPromotionEnabled: fieldPromotionEnabled, inferenceUpdate4Enabled: inferenceUpdate4Enabled, ) - : FlowAnalysis<AstNodeImpl, StatementImpl, ExpressionImpl, - PromotableElementImpl2, SharedTypeView<DartType>>.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 TypeSystemOperations with - TypeAnalyzerOperationsMixin<DartType, PromotableElementImpl2, - TypeParameterElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2> + TypeAnalyzerOperationsMixin<PromotableElementImpl2, InterfaceTypeImpl, + InterfaceElementImpl2> implements - TypeAnalyzerOperations< - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, + TypeAnalyzerOperations<PromotableElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2> { final bool strictCasts; final TypeSystemImpl typeSystem; @@ -447,57 +446,57 @@ TypeSystemOperations(this.typeSystem, {required this.strictCasts}); @override - SharedTypeView<DartType> get boolType { + SharedTypeView get boolType { return SharedTypeView(typeSystem.typeProvider.boolType); } @override - SharedTypeView<DartType> get doubleType { + SharedTypeView get doubleType { throw UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView<DartType> get dynamicType { + SharedTypeView get dynamicType { return SharedTypeView(typeSystem.typeProvider.dynamicType); } @override - SharedTypeView<DartType> get errorType { + SharedTypeView get errorType { return SharedTypeView(InvalidTypeImpl.instance); } @override - SharedTypeView<DartType> get intType { + SharedTypeView get intType { throw UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView<DartType> get neverType { + SharedTypeView get neverType { return SharedTypeView(typeSystem.typeProvider.neverType); } @override - SharedTypeView<DartType> get nullType { + SharedTypeView get nullType { return SharedTypeView(typeSystem.typeProvider.nullType); } @override - SharedTypeView<DartType> get objectQuestionType { + SharedTypeView get objectQuestionType { return SharedTypeView(typeSystem.objectQuestion); } @override - SharedTypeView<DartType> get objectType { + SharedTypeView get objectType { return SharedTypeView(typeSystem.objectNone); } @override - SharedTypeSchemaView<DartType> get unknownType { + SharedTypeSchemaView get unknownType { return SharedTypeSchemaView(UnknownInferredType.instance); } @override - TypeClassification classifyType(SharedTypeView<DartType> type) { + TypeClassification classifyType(SharedTypeView type) { DartType unwrapped = type.unwrapTypeView(); if (type is InvalidType) { return TypeClassification.potentiallyNullable; @@ -513,35 +512,28 @@ } @override - TypeConstraintGenerator< - DartType, - FormalParameterElementMixin, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, - InterfaceElementImpl2, - AstNodeImpl> + TypeConstraintGenerator<PromotableElementImpl2, InterfaceTypeImpl, + InterfaceElementImpl2, AstNodeImpl> createTypeConstraintGenerator( {required covariant TypeConstraintGenerationDataForTesting? typeConstraintGenerationDataForTesting, - required List<TypeParameterElementImpl2> typeParametersToInfer, + required List<SharedTypeParameterView> typeParametersToInfer, required covariant TypeSystemOperations typeAnalyzerOperations, required bool inferenceUsingBoundsIsEnabled}) { return TypeConstraintGatherer( - typeParameters: typeParametersToInfer, + typeParameters: typeParametersToInfer.cast<TypeParameterElementImpl2>(), inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled, typeSystemOperations: typeAnalyzerOperations, dataForTesting: typeConstraintGenerationDataForTesting); } @override - SharedTypeView<DartType> extensionTypeErasure(SharedTypeView<DartType> type) { - return SharedTypeView(type.unwrapTypeView().extensionTypeErasure); + SharedTypeView extensionTypeErasure(SharedTypeView type) { + return SharedTypeView(type.unwrapTypeView<DartType>().extensionTypeErasure); } @override - SharedTypeView<DartType> factor( - SharedTypeView<DartType> from, SharedTypeView<DartType> what) { + SharedTypeView factor(SharedTypeView from, SharedTypeView what) { return SharedTypeView( typeSystem.factor(from.unwrapTypeView(), what.unwrapTypeView())); } @@ -574,27 +566,25 @@ } @override - SharedTypeView<DartType> greatestClosure( - SharedTypeSchemaView<DartType> schema) { + SharedTypeView greatestClosure(SharedTypeSchemaView schema) { return SharedTypeView( typeSystem.greatestClosureOfSchema(schema.unwrapTypeSchemaView())); } @override - DartType greatestClosureOfTypeInternal(DartType type, - List<SharedTypeParameterStructure<DartType>> typeParametersToEliminate) { + DartType greatestClosureOfTypeInternal( + DartType type, List<SharedTypeParameter> typeParametersToEliminate) { return typeSystem.greatestClosure( type, typeParametersToEliminate.cast<TypeParameterElementImpl2>()); } @override - bool isAlwaysExhaustiveType(SharedTypeView<DartType> type) { + bool isAlwaysExhaustiveType(SharedTypeView type) { return typeSystem.isAlwaysExhaustive(type.unwrapTypeView()); } @override - bool isAssignableTo( - SharedTypeView<DartType> fromType, SharedTypeView<DartType> toType) { + bool isAssignableTo(SharedTypeView fromType, SharedTypeView toType) { return typeSystem.isAssignableTo( fromType.unwrapTypeView(), toType.unwrapTypeView(), strictCasts: strictCasts); @@ -631,8 +621,8 @@ } @override - bool isNever(SharedTypeView<DartType> type) { - return type.unwrapTypeView().isBottom; + bool isNever(SharedTypeView type) { + return type.unwrapTypeView<DartType>().isBottom; } @override @@ -646,8 +636,8 @@ } @override - bool isObject(SharedTypeView<DartType> type) { - return type.unwrapTypeView().isDartCoreObject && + bool isObject(SharedTypeView type) { + return type.unwrapTypeView<DartType>().isDartCoreObject && type.nullabilitySuffix == NullabilitySuffix.none; } @@ -665,14 +655,14 @@ } @override - bool isTypeParameterType(SharedTypeView<DartType> type) { - return type.unwrapTypeView() is TypeParameterType; + bool isTypeParameterType(SharedTypeView type) { + return type.unwrapTypeView<DartType>() is TypeParameterType; } @override bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView<DartType> typeSchema, - required SharedTypeView<DartType> type}) { + {required SharedTypeSchemaView typeSchema, + required SharedTypeView type}) { return typeSystem.isSubtypeOf( type.unwrapTypeView(), typeSchema.unwrapTypeSchemaView()); } @@ -683,15 +673,15 @@ } @override - SharedTypeSchemaView<DartType> iterableTypeSchema( - SharedTypeSchemaView<DartType> elementTypeSchema) { + SharedTypeSchemaView iterableTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(typeSystem.typeProvider .iterableType(elementTypeSchema.unwrapTypeSchemaView())); } @override - DartType leastClosureOfTypeInternal(DartType type, - List<SharedTypeParameterStructure<DartType>> typeParametersToEliminate) { + DartType leastClosureOfTypeInternal( + DartType type, List<SharedTypeParameter> typeParametersToEliminate) { return typeSystem.leastClosure( type, typeParametersToEliminate.cast<TypeParameterElementImpl2>()); } @@ -745,17 +735,17 @@ } @override - SharedTypeView<DartType>? matchListType(SharedTypeView<DartType> type) { + SharedTypeView? matchListType(SharedTypeView type) { var listElement = typeSystem.typeProvider.listElement; - var listType = type.unwrapTypeView().asInstanceOf(listElement); + var listType = type.unwrapTypeView<DartType>().asInstanceOf(listElement); return listType == null ? null : SharedTypeView(listType.typeArguments[0]); } @override - ({SharedTypeView<DartType> keyType, SharedTypeView<DartType> valueType})? - matchMapType(SharedTypeView<DartType> type) { + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type) { var mapElement = typeSystem.typeProvider.mapElement; - var mapType = type.unwrapTypeView().asInstanceOf(mapElement); + var mapType = type.unwrapTypeView<DartType>().asInstanceOf(mapElement); if (mapType != null) { return ( keyType: SharedTypeView(mapType.typeArguments[0]), @@ -766,15 +756,15 @@ } @override - SharedTypeView<DartType>? matchStreamType(SharedTypeView<DartType> type) { + SharedTypeView? matchStreamType(SharedTypeView type) { var streamElement = typeSystem.typeProvider.streamElement; - var listType = type.unwrapTypeView().asInstanceOf(streamElement); + var listType = type.unwrapTypeView<DartType>().asInstanceOf(streamElement); return listType == null ? null : SharedTypeView(listType.typeArguments[0]); } @override - TypeDeclarationMatchResult<InterfaceTypeImpl, InterfaceElementImpl2, - DartType>? matchTypeDeclarationTypeInternal(DartType type) { + TypeDeclarationMatchResult<InterfaceTypeImpl, InterfaceElementImpl2>? + matchTypeDeclarationTypeInternal(DartType type) { if (isInterfaceTypeInternal(type)) { InterfaceTypeImpl interfaceType = type as InterfaceTypeImpl; return TypeDeclarationMatchResult( @@ -805,53 +795,52 @@ } @override - SharedTypeView<DartType> normalize(SharedTypeView<DartType> type) { + SharedTypeView normalize(SharedTypeView type) { return SharedTypeView(typeSystem.normalize(type.unwrapTypeView())); } @override - SharedTypeView<DartType> promoteToNonNull(SharedTypeView<DartType> type) { + SharedTypeView promoteToNonNull(SharedTypeView type) { return SharedTypeView(typeSystem.promoteToNonNull(type.unwrapTypeView())); } @override DartType recordTypeInternal( - {required List<DartType> positional, - required List<(String, DartType)> named}) { + {required List<SharedType> 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<DartType> streamTypeSchema( - SharedTypeSchemaView<DartType> elementTypeSchema) { + SharedTypeSchemaView streamTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return SharedTypeSchemaView(typeSystem.typeProvider .streamType(elementTypeSchema.unwrapTypeSchemaView())); } @override - SharedTypeView<DartType>? tryPromoteToType( - SharedTypeView<DartType> to, SharedTypeView<DartType> from) { + SharedTypeView? tryPromoteToType(SharedTypeView to, SharedTypeView from) { DartType? result = typeSystem.tryPromoteToType(to.unwrapTypeView(), from.unwrapTypeView()); return result == null ? null : SharedTypeView(result); } @override - SharedTypeSchemaView<DartType> typeToSchema(SharedTypeView<DartType> type) { + SharedTypeSchemaView typeToSchema(SharedTypeView type) { return SharedTypeSchemaView(type.unwrapTypeView()); } @override - SharedTypeView<DartType> variableType(PromotableElement2 variable) { + SharedTypeView variableType(PromotableElement2 variable) { return SharedTypeView(variable.type); } @@ -1231,7 +1220,9 @@ 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 e49ea39..b8c07ed 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 @@ flow?.equalityOperation_end( argumentList.parent as ExpressionImpl, leftOperandInfo.expressionInfo, - SharedTypeView<DartType>(leftOperandInfo.staticType), + SharedTypeView(leftOperandInfo.staticType), rightOperandInfo.expressionInfo, - SharedTypeView<DartType>(rightOperandInfo.staticType)); + SharedTypeView(rightOperandInfo.staticType)); } } @@ -731,7 +731,7 @@ class _IdenticalArgumentInfo { /// The [ExpressionInfo] returned by [FlowAnalysis.equalityOperand_end] for /// the argument. - final ExpressionInfo<SharedTypeView<DartType>>? expressionInfo; + final ExpressionInfo<SharedTypeView>? 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 5c35668..0b9fa24 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 @@ ListPatternResolver(this.resolverVisitor); - PatternResult<DartType> 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 c2aa391..e0f69f7 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 @@ DartType _resolveField(ExpressionImpl field, DartType contextType) { var staticType = _resolver .analyzeExpression(field, SharedTypeSchemaView(contextType)) - .unwrapTypeView(); + .unwrapTypeView<DartType>(); 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 a7b457a..e4151f2 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 @@ 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 @@ /// analyzer's [ErrorReporter] class. class SharedTypeAnalyzerErrors implements - shared.TypeAnalyzerErrors< - AstNodeImpl, - StatementImpl, - ExpressionImpl, - PromotableElementImpl2, - SharedTypeView<DartType>, - DartPatternImpl, - void> { + shared.TypeAnalyzerErrors<AstNodeImpl, StatementImpl, ExpressionImpl, + PromotableElementImpl2, SharedTypeView, DartPatternImpl, void> { final ErrorReporter _errorReporter; SharedTypeAnalyzerErrors(this._errorReporter); @@ -40,8 +33,8 @@ void caseExpressionTypeMismatch( {required Expression scrutinee, required Expression caseExpression, - required SharedTypeView<DartType> scrutineeType, - required SharedTypeView<DartType> caseExpressionType, + required SharedTypeView scrutineeType, + required SharedTypeView caseExpressionType, required bool nullSafetyEnabled}) { _errorReporter.atNode( caseExpression, @@ -127,7 +120,7 @@ @override void matchedTypeIsStrictlyNonNullable({ required DartPattern pattern, - required SharedTypeView<DartType> matchedType, + required SharedTypeView matchedType, }) { if (pattern is NullAssertPattern) { _errorReporter.atToken( @@ -147,8 +140,8 @@ @override void matchedTypeIsSubtypeOfRequired({ required covariant CastPatternImpl pattern, - required SharedTypeView<DartType> matchedType, - required SharedTypeView<DartType> requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { _errorReporter.atToken( pattern.asToken, @@ -168,7 +161,7 @@ void patternForInExpressionIsNotIterable({ required AstNode node, required Expression expression, - required SharedTypeView<DartType> expressionType, + required SharedTypeView expressionType, }) { _errorReporter.atNode( expression, @@ -181,8 +174,8 @@ void patternTypeMismatchInIrrefutableContext({ required covariant DartPatternImpl pattern, required AstNode context, - required SharedTypeView<DartType> matchedType, - required SharedTypeView<DartType> requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { _errorReporter.atNode( pattern, @@ -203,8 +196,8 @@ @override void relationalPatternOperandTypeNotAssignable({ required covariant RelationalPatternImpl pattern, - required SharedTypeView<DartType> operandType, - required SharedTypeView<DartType> parameterType, + required SharedTypeView operandType, + required SharedTypeView parameterType, }) { _errorReporter.atNode( pattern.operand, @@ -216,7 +209,7 @@ @override void relationalPatternOperatorReturnTypeNotAssignableToBool({ required covariant RelationalPatternImpl pattern, - required SharedTypeView<DartType> 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 dfa1410..7d26f0f 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 @@ /// /// See [CompileTimeErrorCode.NON_BOOL_CONDITION]. void checkForNonBoolCondition(Expression condition, - {required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? + {required Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { checkForNonBoolExpression( condition, @@ -50,7 +50,7 @@ void checkForNonBoolExpression(Expression expression, {required ErrorCode errorCode, List<Object> arguments = const [], - required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? + required Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { var type = expression.typeOrThrow; if (!_checkForUseOfVoidResult(expression) && @@ -75,7 +75,7 @@ /// Checks to ensure that the given [expression] is assignable to bool. void checkForNonBoolNegationExpression(Expression expression, - {required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? + {required Map<SharedTypeView, NonPromotionReason> 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 f256a59..f120970 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 @@ DartType expectedStaticType, DartType actualStaticType, ErrorCode errorCode, - {Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted}) { + {Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { if (expectedStaticType is! VoidType && checkForUseOfVoidResult(expression)) { return; @@ -61,8 +60,7 @@ /// See [CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE]. void checkForArgumentTypeNotAssignableForArgument(Expression argument, {bool promoteParameterToNullable = false, - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted}) { + Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { _checkForArgumentTypeNotAssignableForArgument( argument: argument is NamedExpression ? argument.expression : argument, parameter: argument.correspondingParameter, @@ -76,8 +74,7 @@ DartType actualStaticType, DartType expectedStaticType, ErrorCode errorCode, - {Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted}) { + {Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { if (expectedStaticType is! VoidType && checkForUseOfVoidResult(expression)) { return; @@ -172,7 +169,7 @@ void checkForFieldInitializerNotAssignable( ConstructorFieldInitializer initializer, FieldElement2 fieldElement, {required bool isConstConstructor, - required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? + required Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { // prepare field type DartType fieldType = fieldElement.type; @@ -262,8 +259,7 @@ Expression index, { required ExecutableElement2? readElement, required ExecutableElement2? writeElement, - required Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted, + required Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted, }) { if (readElement is MethodElement2) { var parameters = readElement.formalParameters; @@ -303,7 +299,7 @@ /// analysis engine. List<DiagnosticMessage> computeWhyNotPromotedMessages( SyntacticEntity errorEntity, - Map<SharedTypeView<DartType>, NonPromotionReason>? whyNotPromoted); + Map<SharedTypeView, NonPromotionReason>? 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 @@ required Expression argument, required FormalParameterElement? parameter, required bool promoteParameterToNullable, - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted, + Map<SharedTypeView, NonPromotionReason> 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 251cf10..a6e3bf5 100644 --- a/pkg/analyzer/lib/src/generated/error_verifier.dart +++ b/pkg/analyzer/lib/src/generated/error_verifier.dart
@@ -342,7 +342,7 @@ @override List<DiagnosticMessage> computeWhyNotPromotedMessages( SyntacticEntity errorEntity, - Map<SharedTypeView<DartType>, NonPromotionReason>? whyNotPromoted) { + Map<SharedTypeView, NonPromotionReason>? whyNotPromoted) { return []; }
diff --git a/pkg/analyzer/lib/src/generated/inference_log.dart b/pkg/analyzer/lib/src/generated/inference_log.dart index 9465f7e..5e1d4bd 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: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 @@ /// The [SharedInferenceLogWriter] interface, augmented with analyzer-specific /// functionality. abstract interface class InferenceLogWriter - implements - SharedInferenceLogWriter<DartType, DartType, - TypeParameterElementImpl2> { + implements SharedInferenceLogWriter { /// Checks that [enterExpression] was properly called for [expression]. /// /// This is called from [ResolverVisitor.dispatchExpression], to verify that @@ -109,10 +106,8 @@ /// 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 14a6e42..3164d01 100644 --- a/pkg/analyzer/lib/src/generated/resolver.dart +++ b/pkg/analyzer/lib/src/generated/resolver.dart
@@ -100,14 +100,14 @@ bool Function(Source) inferenceLoggingPredicate = (_) => false; typedef SharedMatchContext = shared.MatchContext<AstNodeImpl, ExpressionImpl, - DartPatternImpl, SharedTypeView<DartType>, PromotableElementImpl2>; + DartPatternImpl, SharedTypeView, PromotableElementImpl2>; typedef SharedPatternField = shared.RecordPatternField<PatternFieldImpl, DartPatternImpl>; /// A function which returns [NonPromotionReason]s that various types are not /// promoted. -typedef WhyNotPromotedGetter = Map<SharedTypeView<DartType>, NonPromotionReason> +typedef WhyNotPromotedGetter = Map<SharedTypeView, NonPromotionReason> Function(); /// The context shared between different units of the same library. @@ -123,18 +123,16 @@ with ErrorDetectionHelpers, TypeAnalyzer< - DartType, AstNodeImpl, StatementImpl, ExpressionImpl, PromotableElementImpl2, DartPatternImpl, void, - TypeParameterElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2>, // TODO(paulberry): not yet used. - NullShortingMixin<Null, ExpressionImpl, SharedTypeView<DartType>> { + NullShortingMixin<Null, ExpressionImpl, SharedTypeView> { /// 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 @@ ExecutableElement? get enclosingFunction => _enclosingFunction; @override - FlowAnalysis< - AstNodeImpl, - StatementImpl, - ExpressionImpl, - PromotableElementImpl2, - SharedTypeView<DartType>> get flow => flowAnalysis.flow!; + FlowAnalysis<AstNodeImpl, StatementImpl, ExpressionImpl, + PromotableElementImpl2, SharedTypeView> get flow => flowAnalysis.flow!; bool get isConstructorTearoffsEnabled => _featureSet.isEnabled(Feature.constructor_tearoffs); @@ -458,11 +452,7 @@ } @override - shared.TypeAnalyzerOperations< - DartType, - PromotableElementImpl2, - TypeParameterElementImpl2, - InterfaceTypeImpl, + shared.TypeAnalyzerOperations<PromotableElementImpl2, InterfaceTypeImpl, InterfaceElementImpl2> get operations => flowAnalysis.typeOperations; /// Gets the current depth of the [_rewriteStack]. This may be used in @@ -483,8 +473,8 @@ } @override - SharedTypeView<DartType> analyzeExpression( - ExpressionImpl node, SharedTypeSchemaView<DartType> schema, + SharedTypeView analyzeExpression( + ExpressionImpl node, SharedTypeSchemaView schema, {bool continueNullShorting = false}) { inferenceLogWriter?.setExpressionVisitCodePath( node, ExpressionVisitCodePath.analyzeExpression); @@ -721,7 +711,7 @@ @override List<DiagnosticMessage> computeWhyNotPromotedMessages( SyntacticEntity errorEntity, - Map<SharedTypeView<DartType>, NonPromotionReason>? whyNotPromoted) { + Map<SharedTypeView, NonPromotionReason>? whyNotPromoted) { List<DiagnosticMessage> messages = []; if (whyNotPromoted != null) { for (var entry in whyNotPromoted.entries) { @@ -771,9 +761,8 @@ } @override - ExpressionTypeAnalysisResult<DartType> dispatchExpression( - covariant ExpressionImpl expression, - SharedTypeSchemaView<DartType> context) { + ExpressionTypeAnalysisResult dispatchExpression( + covariant ExpressionImpl expression, SharedTypeSchemaView context) { int? stackDepth; assert(() { stackDepth = rewriteStackDepth; @@ -783,11 +772,7 @@ // 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 @@ '(${replacementExpression.runtimeType}) $replacementExpression', ); } - // TODO(paulberry): remove this cast by changing the type of - // `operations.unknownType` to `SharedTypeSchemaView<TypeImpl>`. - staticType = operations.unknownType.unwrapTypeSchemaView() as TypeImpl; + staticType = operations.unknownType.unwrapTypeSchemaView(); } - return ExpressionTypeAnalysisResult<DartType>( - type: SharedTypeView(staticType)); + return ExpressionTypeAnalysisResult(type: SharedTypeView(staticType)); } @override - PatternResult<DartType> dispatchPattern( - SharedMatchContext context, AstNodeImpl node) { - shared.PatternResult<DartType> 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 @@ } @override - SharedTypeSchemaView<DartType> dispatchPatternSchema( - covariant DartPatternImpl node) { + SharedTypeSchemaView dispatchPatternSchema(covariant DartPatternImpl node) { return SharedTypeSchemaView(node.computePatternSchema(this)); } @@ -855,8 +835,8 @@ } @override - SharedTypeView<DartType> downwardInferObjectPatternRequiredType({ - required SharedTypeView<DartType> matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required covariant ObjectPatternImpl pattern, }) { var typeNode = pattern.type; @@ -869,10 +849,7 @@ 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 @@ 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 @@ required JoinedPatternVariableLocation location, required shared.JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView<DartType> type, + required SharedTypeView type, }) { variable.inconsistency = variable.inconsistency.maxWith(inconsistency); variable.isFinal = isFinal; @@ -1148,7 +1122,7 @@ void handleMapPatternEntry( DartPattern container, covariant MapPatternEntryImpl entry, - SharedTypeView<DartType> keyType, + SharedTypeView keyType, ) { entry.key = popRewrite()!; } @@ -1197,7 +1171,7 @@ } @override - void handleSwitchScrutinee(SharedTypeView<DartType> type) { + void handleSwitchScrutinee(SharedTypeView type) { if (!options.patternsEnabled) { legacySwitchExhaustiveness = SwitchExhaustiveness(type.unwrapTypeView()); } @@ -1263,8 +1237,7 @@ } @override - bool isLegacySwitchExhaustive( - AstNode node, SharedTypeView<DartType> expressionType) => + bool isLegacySwitchExhaustive(AstNode node, SharedTypeView expressionType) => legacySwitchExhaustiveness!.isExhaustive; @override @@ -1412,7 +1385,7 @@ nullSafetyDeadCodeVerifier.maybeRewriteFirstDeadNode(oldNode, newNode); } - PatternResult<DartType> resolveAssignedVariablePattern({ + PatternResult resolveAssignedVariablePattern({ required AssignedVariablePatternImpl node, required SharedMatchContext context, }) { @@ -1568,15 +1541,12 @@ } } - PatternResult<DartType> resolveMapPattern({ + PatternResult resolveMapPattern({ required MapPatternImpl node, required SharedMatchContext context, }) { inferenceLogWriter?.enterPattern(node); - ({ - SharedTypeView<DartType> keyType, - SharedTypeView<DartType> valueType - })? typeArguments; + ({SharedTypeView keyType, SharedTypeView valueType})? typeArguments; var typeArgumentsList = node.typeArguments; if (typeArgumentsList != null) { typeArgumentsList.accept(this); @@ -1616,10 +1586,9 @@ } @override - (ExecutableElement?, SharedTypeView<DartType>) - resolveObjectPatternPropertyGet({ + (ExecutableElement?, SharedTypeView) resolveObjectPatternPropertyGet({ required covariant ObjectPatternImpl objectPattern, - required SharedTypeView<DartType> receiverType, + required SharedTypeView receiverType, required covariant SharedPatternField field, }) { var fieldNode = field.node; @@ -1664,9 +1633,9 @@ } @override - RelationalOperatorResolution<DartType>? resolveRelationalPatternOperator( + RelationalOperatorResolution? resolveRelationalPatternOperator( covariant RelationalPatternImpl node, - SharedTypeView<DartType> matchedType, + SharedTypeView matchedType, ) { var operatorLexeme = node.operator.lexeme; RelationalOperatorKind kind; @@ -1755,8 +1724,7 @@ } @override - void setVariableType( - PromotableElement2 variable, SharedTypeView<DartType> type) { + void setVariableType(PromotableElement2 variable, SharedTypeView type) { if (variable is LocalVariableElementImpl2) { variable.type = type.unwrapTypeView(); } else { @@ -1832,8 +1800,7 @@ } @override - SharedTypeView<DartType> variableTypeFromInitializerType( - SharedTypeView<DartType> type) { + SharedTypeView variableTypeFromInitializerType(SharedTypeView type) { DartType unwrapped = type.unwrapTypeView(); if (unwrapped.isDartCoreNull) { return SharedTypeView(DynamicTypeImpl.instance); @@ -1865,7 +1832,7 @@ } assert(flowAnalysis.flow != null); var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; _annotationResolver.resolve(node, whyNotPromotedArguments); var arguments = node.arguments; if (arguments != null) { @@ -2015,7 +1982,7 @@ inferenceLogWriter?.enterExpression(node, contextType); checkUnreachableNode(node); var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; var augmentation = enclosingAugmentation; var augmentationTarget = augmentation?.augmentationTarget; @@ -2604,7 +2571,7 @@ arguments.typeArguments?.accept(this); var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; checkForArgumentTypesNotAssignableInList( argumentList, whyNotPromotedArguments); } @@ -2704,7 +2671,7 @@ {TypeImpl contextType = UnknownInferredType.instance}) { inferenceLogWriter?.enterExtensionOverride(node, contextType); var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; node.typeArguments?.accept(this); var receiverContextType = @@ -2893,7 +2860,7 @@ node.function = popRewrite()!; var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; _functionExpressionInvocationResolver.resolve(node, whyNotPromotedArguments, contextType: contextType); nullShortingTermination(node); @@ -3257,7 +3224,7 @@ inferenceLogWriter?.enterExpression(node, contextType); checkUnreachableNode(node); var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; var target = node.target; if (target != null) { analyzeExpression(target, operations.unknownType); @@ -3570,7 +3537,7 @@ // invocation. // var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; elementResolver.visitRedirectingConstructorInvocation( node as RedirectingConstructorInvocationImpl); InvocationInferrer<RedirectingConstructorInvocationImpl>( @@ -3707,7 +3674,7 @@ // invocation. // var whyNotPromotedArguments = - <Map<SharedTypeView<DartType>, NonPromotionReason> Function()>[]; + <Map<SharedTypeView, NonPromotionReason> Function()>[]; elementResolver.visitSuperConstructorInvocation( node as SuperConstructorInvocationImpl); InvocationInferrer<SuperConstructorInvocationImpl>( @@ -3748,7 +3715,7 @@ var staticType = analyzeSwitchExpression(node, node.expression, node.cases.length, SharedTypeSchemaView(contextType)) .type - .unwrapTypeView(); + .unwrapTypeView<DartType>(); node.recordStaticType(staticType, resolver: this); popRewrite(); legacySwitchExhaustiveness = previousExhaustiveness; @@ -5620,7 +5587,7 @@ class _WhyNotPromotedVisitor implements NonPromotionReasonVisitor<List<DiagnosticMessage>, AstNode, - PromotableElement2, SharedTypeView<DartType>> { + PromotableElement2, SharedTypeView> { final Source source; final SyntacticEntity _errorEntity; @@ -5649,7 +5616,7 @@ @override List<DiagnosticMessage> visitPropertyNotPromotedForInherentReason( - PropertyNotPromotedForInherentReason<SharedTypeView<DartType>> reason) { + PropertyNotPromotedForInherentReason<SharedTypeView> reason) { var receiverElement = reason.propertyMember; if (receiverElement is PropertyAccessorElement) { var property = propertyReference = receiverElement; @@ -5687,8 +5654,7 @@ @override List<DiagnosticMessage> visitPropertyNotPromotedForNonInherentReason( - PropertyNotPromotedForNonInherentReason<SharedTypeView<DartType>> - reason) { + PropertyNotPromotedForNonInherentReason<SharedTypeView> 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 aff9cef..7da51ff 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_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 @@ 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/builder/class_builder.dart b/pkg/front_end/lib/src/builder/class_builder.dart index 13b94cc..ca14033 100644 --- a/pkg/front_end/lib/src/builder/class_builder.dart +++ b/pkg/front_end/lib/src/builder/class_builder.dart
@@ -232,6 +232,7 @@ return builder; } + // Coverage-ignore(suite): Not run. /// Find the first member of this class with [name]. This method isn't /// suitable for scope lookups as it will throw an error if the name isn't /// declared. The [scope] should be used for that. This method is used to
diff --git a/pkg/front_end/lib/src/builder/field_builder.dart b/pkg/front_end/lib/src/builder/field_builder.dart deleted file mode 100644 index 8b2dff7..0000000 --- a/pkg/front_end/lib/src/builder/field_builder.dart +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:kernel/ast.dart'; - -import 'member_builder.dart'; - -abstract class FieldBuilder implements MemberBuilder { - Field get field; -}
diff --git a/pkg/front_end/lib/src/builder/formal_parameter_builder.dart b/pkg/front_end/lib/src/builder/formal_parameter_builder.dart index 1d984b3..68aa737 100644 --- a/pkg/front_end/lib/src/builder/formal_parameter_builder.dart +++ b/pkg/front_end/lib/src/builder/formal_parameter_builder.dart
@@ -20,12 +20,12 @@ import '../source/constructor_declaration.dart'; import '../source/source_factory_builder.dart'; import '../source/source_library_builder.dart'; +import '../source/source_property_builder.dart'; import 'builder.dart'; import 'constructor_builder.dart'; import 'declaration_builders.dart'; import 'member_builder.dart'; import 'omitted_type_builder.dart'; -import 'property_builder.dart'; import 'type_builder.dart'; import 'variable_builder.dart'; @@ -229,7 +229,7 @@ ClassHierarchyBase hierarchy) { String fieldName = isWildcardLoweredFormalParameter(name) ? '_' : name; Builder? fieldBuilder = declarationBuilder.lookupLocalMember(fieldName); - if (fieldBuilder is PropertyBuilder && fieldBuilder.isField) { + if (fieldBuilder is SourcePropertyBuilder && fieldBuilder.isField) { DartType fieldType = fieldBuilder.inferType(hierarchy); fieldType = constructorDeclaration.substituteFieldType(fieldType); type.registerInferredType(fieldType);
diff --git a/pkg/front_end/lib/src/builder/property_builder.dart b/pkg/front_end/lib/src/builder/property_builder.dart index fe65c62..7a785c9 100644 --- a/pkg/front_end/lib/src/builder/property_builder.dart +++ b/pkg/front_end/lib/src/builder/property_builder.dart
@@ -2,40 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'package:kernel/ast.dart'; -import 'package:kernel/class_hierarchy.dart'; - import 'member_builder.dart'; -abstract class PropertyBuilder implements MemberBuilder { - bool get hasInitializer; - - @override - Uri get fileUri; - - bool get isExtensionTypeDeclaredInstanceField; - - bool get isLate; - - bool get isFinal; - - abstract DartType fieldType; - - DartType inferType(ClassHierarchyBase hierarchy); - - /// Builds the field initializers for each field used to encode this field - /// using the [fileOffset] for the created nodes and [value] as the initial - /// field value. - List<Initializer> buildInitializer(int fileOffset, Expression value, - {required bool isSynthetic}); - - /// Creates the AST node for this field as the default initializer. - void buildImplicitDefaultValue(); - - /// Create the [Initializer] for the implicit initialization of this field - /// in a constructor. - Initializer buildImplicitInitializer(); - - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}); -} +abstract class PropertyBuilder implements MemberBuilder {}
diff --git a/pkg/front_end/lib/src/dill/dill_member_builder.dart b/pkg/front_end/lib/src/dill/dill_member_builder.dart index 4133f5b..6dfb961 100644 --- a/pkg/front_end/lib/src/dill/dill_member_builder.dart +++ b/pkg/front_end/lib/src/dill/dill_member_builder.dart
@@ -18,9 +18,9 @@ import '../builder/builder.dart'; import '../builder/constructor_builder.dart'; import '../builder/declaration_builders.dart'; -import '../builder/field_builder.dart'; import '../builder/member_builder.dart'; import '../builder/procedure_builder.dart'; +import '../builder/property_builder.dart'; import '../kernel/hierarchy/class_member.dart'; import '../kernel/hierarchy/members_builder.dart' show ClassMembersBuilder; import '../kernel/member_covariance.dart'; @@ -122,8 +122,7 @@ Iterable<Annotatable> get annotatables => [member]; } -class DillFieldBuilder extends DillMemberBuilder implements FieldBuilder { - @override +class DillFieldBuilder extends DillMemberBuilder implements PropertyBuilder { final Field field; DillFieldBuilder(this.field, super.libraryBuilder,
diff --git a/pkg/front_end/lib/src/fragment/field/encoding.dart b/pkg/front_end/lib/src/fragment/field/encoding.dart index 4aaf45d..c6073a7 100644 --- a/pkg/front_end/lib/src/fragment/field/encoding.dart +++ b/pkg/front_end/lib/src/fragment/field/encoding.dart
@@ -32,16 +32,28 @@ /// The type of the declared field. abstract DartType type; + /// Builds the [Initializer]s for each field used to encode this field + /// using the [fileOffset] for the created nodes and [value] as the initial + /// field value. + /// + /// This is only used for instance fields. List<Initializer> createInitializer(int fileOffset, Expression value, {required bool isSynthetic}); /// Creates the AST node for this field as the default initializer. + /// + /// This is only used for instance fields. void buildImplicitDefaultValue(); - /// Create the [Initializer] for the implicit initialization of this field + /// Creates the [Initializer] for the implicit initialization of this field /// in a constructor. + /// + /// This is only used for instance fields. Initializer buildImplicitInitializer(); + /// Creates the [Initializer] for the invalid initialization of this field. + /// + /// This is only used for instance fields. Initializer buildErroneousInitializer(Expression effect, Expression value, {required int fileOffset});
diff --git a/pkg/front_end/lib/src/fragment/fragment.dart b/pkg/front_end/lib/src/fragment/fragment.dart index 41515c6..e0a0883 100644 --- a/pkg/front_end/lib/src/fragment/fragment.dart +++ b/pkg/front_end/lib/src/fragment/fragment.dart
@@ -38,7 +38,7 @@ import '../kernel/implicit_field_type.dart'; import '../kernel/internal_ast.dart'; import '../kernel/late_lowering.dart' as late_lowering; -import '../kernel/macro/metadata.dart' hide FieldReference; +import '../kernel/macro/metadata.dart'; import '../kernel/member_covariance.dart'; import '../kernel/type_algorithms.dart'; import '../source/name_scheme.dart';
diff --git a/pkg/front_end/lib/src/fragment/util.dart b/pkg/front_end/lib/src/fragment/util.dart index 972b493f..ae71d20 100644 --- a/pkg/front_end/lib/src/fragment/util.dart +++ b/pkg/front_end/lib/src/fragment/util.dart
@@ -171,19 +171,28 @@ /// The [DartType] of this field declaration. abstract DartType fieldType; + /// Creates the [Initializer] for the invalid initialization of this field. + /// + /// This is only used for instance fields. Initializer buildErroneousInitializer(Expression effect, Expression value, {required int fileOffset}); /// Creates the AST node for this field as the default initializer. + /// + /// This is only used for instance fields. void buildImplicitDefaultValue(); - /// Create the [Initializer] for the implicit initialization of this field + /// Creates the [Initializer] for the implicit initialization of this field /// in a constructor. + /// + /// This is only used for instance fields. Initializer buildImplicitInitializer(); - /// Builds the field initializers for each field used to encode this field + /// Builds the [Initializer]s for each field used to encode this field /// using the [fileOffset] for the created nodes and [value] as the initial /// field value. + /// + /// This is only used for instance fields. List<Initializer> buildInitializer(int fileOffset, Expression value, {required bool isSynthetic});
diff --git a/pkg/front_end/lib/src/kernel/body_builder.dart b/pkg/front_end/lib/src/kernel/body_builder.dart index 5d5c7b8..23d54f3 100644 --- a/pkg/front_end/lib/src/kernel/body_builder.dart +++ b/pkg/front_end/lib/src/kernel/body_builder.dart
@@ -73,7 +73,6 @@ import '../builder/nullability_builder.dart'; import '../builder/omitted_type_builder.dart'; import '../builder/prefix_builder.dart'; -import '../builder/property_builder.dart'; import '../builder/record_type_builder.dart'; import '../builder/type_builder.dart'; import '../builder/variable_builder.dart'; @@ -97,6 +96,7 @@ import '../source/offset_map.dart'; import '../source/source_library_builder.dart'; import '../source/source_member_builder.dart'; +import '../source/source_property_builder.dart'; import '../source/stack_listener_impl.dart' show StackListenerImpl, offsetForToken; import '../source/value_kinds.dart'; @@ -9071,7 +9071,7 @@ } Initializer buildDuplicatedInitializer( - PropertyBuilder fieldBuilder, + SourcePropertyBuilder fieldBuilder, Expression value, String name, int offset, @@ -9107,7 +9107,7 @@ // Duplicated name, already reported. while (builder != null) { if (builder.next == null && - builder is PropertyBuilder && + builder is SourcePropertyBuilder && builder.isField) { // Assume the first field has been initialized. _context.registerInitializedField(builder); @@ -9125,7 +9125,7 @@ ), fieldNameOffset) ]; - } else if (builder is PropertyBuilder && + } else if (builder is SourcePropertyBuilder && builder.isField && builder.isDeclarationInstanceMember) { if (builder.isExtensionTypeDeclaredInstanceField) {
diff --git a/pkg/front_end/lib/src/kernel/body_builder_context.dart b/pkg/front_end/lib/src/kernel/body_builder_context.dart index 511db32..f531347 100644 --- a/pkg/front_end/lib/src/kernel/body_builder_context.dart +++ b/pkg/front_end/lib/src/kernel/body_builder_context.dart
@@ -15,7 +15,6 @@ import '../builder/formal_parameter_builder.dart'; import '../builder/library_builder.dart'; import '../builder/named_type_builder.dart'; -import '../builder/property_builder.dart'; import '../builder/type_builder.dart'; import '../dill/dill_class_builder.dart'; import '../source/constructor_declaration.dart'; @@ -26,10 +25,10 @@ import '../source/source_extension_builder.dart'; import '../source/source_extension_type_declaration_builder.dart'; import '../source/source_factory_builder.dart'; -import '../source/source_field_builder.dart'; import '../source/source_function_builder.dart'; import '../source/source_library_builder.dart'; import '../source/source_member_builder.dart'; +import '../source/source_property_builder.dart'; import '../source/source_type_alias_builder.dart'; import '../type_inference/inference_results.dart' show InitializerInferenceResult; @@ -287,7 +286,7 @@ /// Registers that the field [builder] has been initialized in generative /// constructor whose body is being built. - void registerInitializedField(PropertyBuilder builder) { + void registerInitializedField(SourcePropertyBuilder builder) { throw new UnsupportedError('${runtimeType}.registerInitializedField'); } @@ -740,51 +739,6 @@ } } -class FieldBodyBuilderContext extends BodyBuilderContext - with _MemberBodyBuilderContext<SourceFieldBuilder> { - @override - SourceFieldBuilder _member; - - @override - final Member _builtMember; - - FieldBodyBuilderContext(this._member, this._builtMember) - : super(_member.libraryBuilder, _member.declarationBuilder, - isDeclarationInstanceMember: _member.isDeclarationInstanceMember); - - @override - // Coverage-ignore(suite): Not run. - bool get isLateField => _member.isLate; - - @override - // Coverage-ignore(suite): Not run. - bool get isAbstractField => _member.isAbstract; - - @override - // Coverage-ignore(suite): Not run. - bool get isExternalField => _member.isExternal; - - @override - // Coverage-ignore(suite): Not run. - InstanceTypeParameterAccessState get instanceTypeParameterAccessState { - if (_member.isExtensionMember && !_member.isExternal) { - return InstanceTypeParameterAccessState.Invalid; - } else { - return super.instanceTypeParameterAccessState; - } - } - - @override - // Coverage-ignore(suite): Not run. - ConstantContext get constantContext { - return _member.isConst - ? ConstantContext.inferred - : !_member.isStatic && _declarationContext.declaresConstConstructor - ? ConstantContext.required - : ConstantContext.none; - } -} - mixin _FunctionBodyBuilderContextMixin<T extends SourceFunctionBuilder> implements BodyBuilderContext { T get _member; @@ -862,7 +816,7 @@ } @override - void registerInitializedField(PropertyBuilder builder) { + void registerInitializedField(SourcePropertyBuilder builder) { _member.registerInitializedField(builder); }
diff --git a/pkg/front_end/lib/src/kernel/implicit_field_type.dart b/pkg/front_end/lib/src/kernel/implicit_field_type.dart index c0ccb6a..f2299c9 100644 --- a/pkg/front_end/lib/src/kernel/implicit_field_type.dart +++ b/pkg/front_end/lib/src/kernel/implicit_field_type.dart
@@ -8,16 +8,11 @@ import 'package:kernel/src/assumptions.dart'; import 'package:kernel/src/printer.dart'; -import '../base/constant_context.dart'; import '../base/problems.dart' show unsupported; import '../builder/inferable_type_builder.dart'; import '../builder/type_builder.dart'; import '../codes/cfe_codes.dart'; -import '../source/source_field_builder.dart'; import '../source/source_library_builder.dart'; -import '../type_inference/type_inferrer.dart'; -import 'body_builder.dart'; -import 'body_builder_context.dart'; abstract class InferredType extends AuxiliaryType { Uri? get fileUri; @@ -25,10 +20,6 @@ InferredType._(); - factory InferredType.fromFieldInitializer( - SourceFieldBuilder fieldBuilder, Token? initializerToken) = - _ImplicitFieldTypeRoot; - factory InferredType( {required SourceLibraryBuilder libraryBuilder, required TypeBuilder typeBuilder, @@ -101,100 +92,6 @@ DartType computeType(ClassHierarchyBase hierarchy); } -// Coverage-ignore(suite): Not run. -class _ImplicitFieldTypeRoot extends InferredType { - final SourceFieldBuilder fieldBuilder; - - Token? initializerToken; - bool isStarted = false; - - _ImplicitFieldTypeRoot(this.fieldBuilder, this.initializerToken) : super._(); - - @override - Uri get fileUri => fieldBuilder.fileUri; - - @override - int get charOffset => fieldBuilder.fileOffset; - - @override - DartType inferType(ClassHierarchyBase hierarchy) { - return fieldBuilder.inferType(hierarchy); - } - - @override - DartType computeType(ClassHierarchyBase hierarchy) { - if (isStarted) { - fieldBuilder.libraryBuilder.addProblem( - templateCantInferTypeDueToCircularity - .withArguments(fieldBuilder.name), - fieldBuilder.fileOffset, - fieldBuilder.name.length, - fieldBuilder.fileUri); - DartType type = const InvalidType(); - fieldBuilder.type.registerInferredType(type); - return type; - } - isStarted = true; - DartType? inferredType; - if (initializerToken != null) { - InterfaceType? enclosingClassThisType = fieldBuilder.classBuilder == null - ? null - : fieldBuilder.libraryBuilder.loader.typeInferenceEngine.coreTypes - .thisInterfaceType(fieldBuilder.classBuilder!.cls, - fieldBuilder.libraryBuilder.library.nonNullable); - TypeInferrer typeInferrer = fieldBuilder - .libraryBuilder.loader.typeInferenceEngine - .createTopLevelTypeInferrer( - fieldBuilder.fileUri, - enclosingClassThisType, - fieldBuilder.libraryBuilder, - fieldBuilder.dataForTesting?.inferenceData); - BodyBuilderContext bodyBuilderContext = - fieldBuilder.createBodyBuilderContext(); - BodyBuilder bodyBuilder = fieldBuilder.libraryBuilder.loader - .createBodyBuilderForField( - fieldBuilder.libraryBuilder, - bodyBuilderContext, - fieldBuilder.declarationBuilder?.scope ?? - fieldBuilder.libraryBuilder.scope, - typeInferrer, - fieldBuilder.fileUri); - bodyBuilder.constantContext = fieldBuilder.isConst - ? ConstantContext.inferred - : ConstantContext.none; - bodyBuilder.inFieldInitializer = true; - bodyBuilder.inLateFieldInitializer = fieldBuilder.isLate; - Expression initializer = - bodyBuilder.parseFieldInitializer(initializerToken!); - initializerToken = null; - - inferredType = - typeInferrer.inferImplicitFieldType(bodyBuilder, initializer); - } else { - inferredType = const DynamicType(); - } - return inferredType; - } - - @override - void toTextInternal(AstPrinter printer) { - printer.write('<implicit-field-type:$fieldBuilder>'); - } - - @override - bool equals(Object other, Assumptions? assumptions) { - if (identical(this, other)) return true; - return other is _ImplicitFieldTypeRoot && - fieldBuilder == other.fieldBuilder; - } - - @override - int get hashCode => fieldBuilder.hashCode; - - @override - String toString() => 'ImplicitFieldType(${toStringInternal()})'; -} - /// Signature for function called to trigger the inference of the type of /// [_ImplicitType], if it hasn't already been computed. typedef InferTypeFunction = DartType Function(ClassHierarchyBase hierarchy);
diff --git a/pkg/front_end/lib/src/kernel/internal_ast.dart b/pkg/front_end/lib/src/kernel/internal_ast.dart index 356fa73..6971d86 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/type_schema.dart' show UnknownType; typedef SharedMatchContext = shared.MatchContext<TreeNode, Expression, Pattern, - SharedTypeView<DartType>, VariableDeclaration>; + SharedTypeView, VariableDeclaration>; int getExtensionTypeParameterCount(Arguments arguments) { if (arguments is ArgumentsImpl) {
diff --git a/pkg/front_end/lib/src/kernel/kernel_target.dart b/pkg/front_end/lib/src/kernel/kernel_target.dart index 7386f7c..2703fca 100644 --- a/pkg/front_end/lib/src/kernel/kernel_target.dart +++ b/pkg/front_end/lib/src/kernel/kernel_target.dart
@@ -53,7 +53,6 @@ import '../builder/named_type_builder.dart'; import '../builder/nullability_builder.dart'; import '../builder/procedure_builder.dart'; -import '../builder/property_builder.dart'; import '../builder/type_builder.dart'; import '../dill/dill_target.dart' show DillTarget; import '../source/class_declaration.dart'; @@ -66,6 +65,7 @@ import '../source/source_loader.dart' show CompilationPhaseForProblemReporting, SourceLoader; import '../source/source_method_builder.dart'; +import '../source/source_property_builder.dart'; import '../type_inference/type_schema.dart'; import 'benchmarker.dart' show BenchmarkPhases, Benchmarker; import 'cfe_verifier.dart' show verifyComponent, verifyGetStaticType; @@ -1532,14 +1532,14 @@ /// Quotes below are from [Dart Programming Language Specification, 4th /// Edition](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-408.pdf): - List<PropertyBuilder> uninitializedFields = []; - List<PropertyBuilder> nonFinalFields = []; - List<PropertyBuilder> lateFinalFields = []; + List<SourcePropertyBuilder> uninitializedFields = []; + List<SourcePropertyBuilder> nonFinalFields = []; + List<SourcePropertyBuilder> lateFinalFields = []; - Iterator<PropertyBuilder> fieldIterator = - classDeclaration.fullMemberIterator<PropertyBuilder>(); + Iterator<SourcePropertyBuilder> fieldIterator = + classDeclaration.fullMemberIterator<SourcePropertyBuilder>(); while (fieldIterator.moveNext()) { - PropertyBuilder fieldBuilder = fieldIterator.current; + SourcePropertyBuilder fieldBuilder = fieldIterator.current; if (!fieldBuilder.isField) { continue; } @@ -1561,10 +1561,10 @@ } } - Map<ConstructorDeclaration, Set<PropertyBuilder>> + Map<ConstructorDeclaration, Set<SourcePropertyBuilder>> constructorInitializedFields = new Map.identity(); - Set<PropertyBuilder>? initializedFieldBuilders = null; - Set<PropertyBuilder>? uninitializedInstanceFields; + Set<SourcePropertyBuilder>? initializedFieldBuilders = null; + Set<SourcePropertyBuilder>? uninitializedInstanceFields; Iterator<ConstructorDeclaration> constructorIterator = classDeclaration.fullConstructorIterator<ConstructorDeclaration>(); @@ -1581,7 +1581,7 @@ nonFinalFields.clear(); } if (constructor.isConst && lateFinalFields.isNotEmpty) { - for (PropertyBuilder field in lateFinalFields) { + for (SourcePropertyBuilder field in lateFinalFields) { classDeclaration.addProblem( messageConstConstructorLateFinalFieldError, field.fileOffset, @@ -1597,23 +1597,24 @@ // Assume that an external constructor initializes all uninitialized // instance fields. uninitializedInstanceFields ??= uninitializedFields - .where((PropertyBuilder fieldBuilder) => !fieldBuilder.isStatic) + .where( + (SourcePropertyBuilder fieldBuilder) => !fieldBuilder.isStatic) .toSet(); constructorInitializedFields[constructor] = uninitializedInstanceFields; - (initializedFieldBuilders ??= new Set<PropertyBuilder>.identity()) + (initializedFieldBuilders ??= new Set<SourcePropertyBuilder>.identity()) .addAll(uninitializedInstanceFields); } else { - Set<PropertyBuilder> fields = + Set<SourcePropertyBuilder> fields = constructor.takeInitializedFields() ?? const {}; constructorInitializedFields[constructor] = fields; - (initializedFieldBuilders ??= new Set<PropertyBuilder>.identity()) + (initializedFieldBuilders ??= new Set<SourcePropertyBuilder>.identity()) .addAll(fields); } } // Run through all fields that aren't initialized by any constructor, and // set their initializer to `null`. - for (PropertyBuilder fieldBuilder in uninitializedFields) { + for (SourcePropertyBuilder fieldBuilder in uninitializedFields) { if (fieldBuilder.isExtensionTypeDeclaredInstanceField) continue; if (initializedFieldBuilders == null || !initializedFieldBuilders.contains(fieldBuilder)) { @@ -1653,11 +1654,11 @@ // Run through all fields that are initialized by some constructor, and // make sure that all other constructors also initialize them. - for (MapEntry<ConstructorDeclaration, Set<PropertyBuilder>> entry + for (MapEntry<ConstructorDeclaration, Set<SourcePropertyBuilder>> entry in constructorInitializedFields.entries) { ConstructorDeclaration constructorBuilder = entry.key; - Set<PropertyBuilder> fieldBuilders = entry.value; - for (PropertyBuilder fieldBuilder + Set<SourcePropertyBuilder> fieldBuilders = entry.value; + for (SourcePropertyBuilder fieldBuilder in initializedFieldBuilders!.difference(fieldBuilders)) { if (fieldBuilder.isExtensionTypeDeclaredInstanceField) continue; if (!fieldBuilder.hasInitializer && !fieldBuilder.isLate) {
diff --git a/pkg/front_end/lib/src/kernel/macro/introspectors.dart b/pkg/front_end/lib/src/kernel/macro/introspectors.dart index afc8a18..c1c11c2 100644 --- a/pkg/front_end/lib/src/kernel/macro/introspectors.dart +++ b/pkg/front_end/lib/src/kernel/macro/introspectors.dart
@@ -18,7 +18,6 @@ import '../../builder/type_builder.dart'; import '../../source/source_constructor_builder.dart'; import '../../source/source_factory_builder.dart'; -import '../../source/source_field_builder.dart'; import '../../source/source_loader.dart'; import '../../source/source_member_builder.dart'; import '../../source/source_method_builder.dart'; @@ -135,8 +134,6 @@ } else if (memberBuilder is SourcePropertyBuilder && memberBuilder.isField) { return _createFieldDeclaration(memberBuilder); - } else if (memberBuilder is SourceFieldBuilder) { - return _createVariableDeclaration(memberBuilder); } else if (memberBuilder is SourceConstructorBuilder) { return _createConstructorDeclaration(memberBuilder); } else if (memberBuilder is SourceFactoryBuilder) { @@ -700,62 +697,6 @@ return declaration; } - /// Creates the [macro.VariableDeclaration] corresponding to [builder]. - macro.VariableDeclaration _createVariableDeclaration( - SourceFieldBuilder builder) { - macro.ParameterizedTypeDeclaration? definingTypeDeclaration = null; - Builder? parent = builder.parent; - if (parent is ClassBuilder) { - definingTypeDeclaration = getClassDeclaration(parent); - } else if (parent is ExtensionTypeDeclarationBuilder) { - definingTypeDeclaration = getExtensionTypeDeclaration(parent); - } - final macro.LibraryImpl library = getLibrary(builder.libraryBuilder); - macro.VariableDeclaration declaration; - if (definingTypeDeclaration != null) { - // TODO(johnniwinther): Should static fields be field or variable - // declarations? - declaration = new macro.FieldDeclarationImpl( - id: macro.RemoteInstance.uniqueId, - identifier: new MemberBuilderIdentifier( - memberBuilder: builder, - id: macro.RemoteInstance.uniqueId, - name: builder.name), - library: library, - // TODO: Provide metadata annotations. - metadata: const [], - definingType: - definingTypeDeclaration.identifier as macro.IdentifierImpl, - hasAbstract: builder.isAbstract, - hasConst: builder.isConst, - hasExternal: builder.isExternal, - hasFinal: builder.isFinal, - hasInitializer: builder.hasInitializer, - hasLate: builder.isLate, - hasStatic: builder.isStatic, - type: types.getTypeAnnotation(builder.libraryBuilder, builder.type)); - } else { - declaration = new macro.VariableDeclarationImpl( - id: macro.RemoteInstance.uniqueId, - identifier: new MemberBuilderIdentifier( - memberBuilder: builder, - id: macro.RemoteInstance.uniqueId, - name: builder.name), - library: library, - // TODO: Provide metadata annotations. - metadata: const [], - hasConst: builder.isConst, - hasExternal: builder.isExternal, - hasFinal: builder.isFinal, - hasInitializer: builder.hasInitializer, - hasLate: builder.isLate, - type: types.getTypeAnnotation(builder.libraryBuilder, builder.type)); - } - _declarationOffsets[declaration] = - new UriOffset(builder.fileUri, builder.fileOffset); - return declaration; - } - /// Creates the [macro.TypeParameterDeclarationImpl] corresponding to the /// nominal parameter [builder] occurring in [libraryBuilder]. macro.TypeParameterDeclarationImpl _createTypeParameterDeclaration(
diff --git a/pkg/front_end/lib/src/kernel/macro/macro.dart b/pkg/front_end/lib/src/kernel/macro/macro.dart index b6019ee..6d6f4a9 100644 --- a/pkg/front_end/lib/src/kernel/macro/macro.dart +++ b/pkg/front_end/lib/src/kernel/macro/macro.dart
@@ -28,7 +28,6 @@ import '../../source/source_extension_builder.dart'; import '../../source/source_extension_type_declaration_builder.dart'; import '../../source/source_factory_builder.dart'; -import '../../source/source_field_builder.dart'; import '../../source/source_library_builder.dart'; import '../../source/source_loader.dart'; import '../../source/source_method_builder.dart'; @@ -504,18 +503,6 @@ new MemberApplicationData(_macroIntrospection, libraryBuilder, memberBuilder, macroApplications); } - } else if (memberBuilder is SourceFieldBuilder) { - List<MacroApplication>? macroApplications = prebuildAnnotations( - enclosingLibrary: libraryBuilder, - scope: builder.scope, - fileUri: memberBuilder.fileUri, - metadataBuilders: memberBuilder.metadata, - currentMacroDeclarations: currentMacroDeclarations); - if (macroApplications != null) { - classMacroApplicationData.memberApplications[memberBuilder] = - new MemberApplicationData(_macroIntrospection, libraryBuilder, - memberBuilder, macroApplications); - } } else { throw new UnsupportedError("Unexpected class member " "$memberBuilder (${memberBuilder.runtimeType})"); @@ -584,18 +571,6 @@ new MemberApplicationData(_macroIntrospection, libraryBuilder, builder, macroApplications); } - } else if (builder is SourceFieldBuilder) { - List<MacroApplication>? macroApplications = prebuildAnnotations( - enclosingLibrary: libraryBuilder, - scope: libraryBuilder.scope, - fileUri: builder.fileUri, - metadataBuilders: builder.metadata, - currentMacroDeclarations: currentMacroDeclarations); - if (macroApplications != null) { - libraryMacroApplicationData.memberApplications[builder] = - new MemberApplicationData(_macroIntrospection, libraryBuilder, - builder, macroApplications); - } } else if (builder is SourceExtensionTypeDeclarationBuilder) { ExtensionTypeMacroApplicationData extensionTypeMacroApplicationData = new ExtensionTypeMacroApplicationData(); @@ -639,19 +614,6 @@ new MemberApplicationData(_macroIntrospection, libraryBuilder, memberBuilder, macroApplications); } - } else if (memberBuilder is SourceFieldBuilder) { - List<MacroApplication>? macroApplications = prebuildAnnotations( - enclosingLibrary: libraryBuilder, - scope: builder.scope, - fileUri: memberBuilder.fileUri, - metadataBuilders: memberBuilder.metadata, - currentMacroDeclarations: currentMacroDeclarations); - if (macroApplications != null) { - extensionTypeMacroApplicationData - .memberApplications[memberBuilder] = - new MemberApplicationData(_macroIntrospection, libraryBuilder, - memberBuilder, macroApplications); - } } else { throw new UnsupportedError("Unexpected class member " "$memberBuilder (${memberBuilder.runtimeType})");
diff --git a/pkg/front_end/lib/src/kernel/macro/metadata.dart b/pkg/front_end/lib/src/kernel/macro/metadata.dart index 763aa31..aa24c73 100644 --- a/pkg/front_end/lib/src/kernel/macro/metadata.dart +++ b/pkg/front_end/lib/src/kernel/macro/metadata.dart
@@ -17,7 +17,6 @@ import '../../builder/builder.dart'; import '../../builder/declaration_builders.dart'; import '../../builder/dynamic_type_declaration_builder.dart'; -import '../../builder/field_builder.dart'; import '../../builder/future_or_type_declaration_builder.dart'; import '../../builder/member_builder.dart'; import '../../builder/never_type_declaration_builder.dart'; @@ -25,7 +24,6 @@ import '../../builder/prefix_builder.dart'; import '../../builder/procedure_builder.dart'; import '../../builder/property_builder.dart'; -import '../../source/source_field_builder.dart'; import '../../source/source_method_builder.dart'; import '../../source/source_property_builder.dart'; @@ -76,12 +74,7 @@ // Coverage-ignore(suite): Not run. /// Returns the [shared.Expression] for the constant initializer of [reference]. shared.Expression? getFieldInitializer(shared.FieldReference reference) { - if (reference is FieldReference) { - FieldBuilder element = reference.builder; - if (element is SourceFieldBuilder) { - return element.initializerExpression; - } - } else if (reference is PropertyReference) { + if (reference is PropertyReference) { PropertyBuilder element = reference.builder; if (element is SourcePropertyBuilder) { return element.initializerExpression; @@ -95,9 +88,7 @@ // Coverage-ignore(suite): Not run. shared.Proto builderToProto(Builder builder, String name) { - if (builder is FieldBuilder) { - return new shared.FieldProto(new FieldReference(builder)); - } else if (builder is PropertyBuilder) { + if (builder is PropertyBuilder) { return new shared.FieldProto(new PropertyReference(builder)); } else if (builder is ProcedureBuilder) { return new shared.FunctionProto(new FunctionReference(builder)); @@ -352,16 +343,6 @@ } // Coverage-ignore(suite): Not run. -class FieldReference extends shared.FieldReference { - final FieldBuilder builder; - - FieldReference(this.builder); - - @override - String get name => builder.name; -} - -// Coverage-ignore(suite): Not run. class PropertyReference extends shared.FieldReference { final PropertyBuilder builder;
diff --git a/pkg/front_end/lib/src/source/constructor_declaration.dart b/pkg/front_end/lib/src/source/constructor_declaration.dart index 17a90bc..c679343 100644 --- a/pkg/front_end/lib/src/source/constructor_declaration.dart +++ b/pkg/front_end/lib/src/source/constructor_declaration.dart
@@ -4,10 +4,10 @@ import 'package:kernel/ast.dart'; -import '../builder/property_builder.dart'; import '../kernel/expression_generator_helper.dart'; import '../type_inference/inference_results.dart'; import 'source_function_builder.dart'; +import 'source_property_builder.dart'; /// Common interface for builders for generative constructor declarations in /// source code, such as a generative constructor in a regular class or a @@ -41,14 +41,14 @@ /// /// The field can be initialized either via an initializing formal or via an /// entry in the constructor initializer list. - void registerInitializedField(PropertyBuilder fieldBuilder); + void registerInitializedField(SourcePropertyBuilder fieldBuilder); /// Returns the fields registered as initialized by this constructor. /// /// Returns the set of fields previously registered via /// [registerInitializedField] and passes on the ownership of the collection /// to the caller. - Set<PropertyBuilder>? takeInitializedFields(); + Set<SourcePropertyBuilder>? takeInitializedFields(); /// Substitute [fieldType] from the context of the enclosing class or /// extension type declaration to this constructor.
diff --git a/pkg/front_end/lib/src/source/source_constructor_builder.dart b/pkg/front_end/lib/src/source/source_constructor_builder.dart index 425d75a..a43afef 100644 --- a/pkg/front_end/lib/src/source/source_constructor_builder.dart +++ b/pkg/front_end/lib/src/source/source_constructor_builder.dart
@@ -30,7 +30,6 @@ import '../builder/member_builder.dart'; import '../builder/metadata_builder.dart'; import '../builder/omitted_type_builder.dart'; -import '../builder/property_builder.dart'; import '../builder/type_builder.dart'; import '../kernel/body_builder.dart' show BodyBuilder; import '../kernel/body_builder_context.dart'; @@ -57,6 +56,7 @@ import 'source_loader.dart' show CompilationPhaseForProblemReporting, SourceLoader; import 'source_member_builder.dart'; +import 'source_property_builder.dart'; abstract class SourceConstructorBuilder implements ConstructorBuilder, SourceMemberBuilder { @@ -417,7 +417,7 @@ @override late final Procedure? _constructorTearOff; - Set<PropertyBuilder>? _initializedFields; + Set<SourcePropertyBuilder>? _initializedFields; DeclaredSourceConstructorBuilder? actualOrigin; @@ -879,6 +879,9 @@ void buildOutlineExpressions(ClassHierarchy classHierarchy, List<DelayedDefaultValueCloner> delayedDefaultValueCloners) { if (_hasBuiltOutlines) return; + + inferFormals(formals, classHierarchy); + if (isConst && isAugmenting) { origin.buildOutlineExpressions( classHierarchy, delayedDefaultValueCloners); @@ -1011,7 +1014,7 @@ } @override - void registerInitializedField(PropertyBuilder fieldBuilder) { + void registerInitializedField(SourcePropertyBuilder fieldBuilder) { if (isAugmenting) { origin.registerInitializedField(fieldBuilder); } else { @@ -1020,8 +1023,8 @@ } @override - Set<PropertyBuilder>? takeInitializedFields() { - Set<PropertyBuilder>? result = _initializedFields; + Set<SourcePropertyBuilder>? takeInitializedFields() { + Set<SourcePropertyBuilder>? result = _initializedFields; _initializedFields = null; return result; } @@ -1325,7 +1328,7 @@ @override late final Procedure? _constructorTearOff; - Set<PropertyBuilder>? _initializedFields; + Set<SourcePropertyBuilder>? _initializedFields; @override List<Initializer> initializers = []; @@ -1565,13 +1568,13 @@ } @override - void registerInitializedField(PropertyBuilder fieldBuilder) { + void registerInitializedField(SourcePropertyBuilder fieldBuilder) { (_initializedFields ??= {}).add(fieldBuilder); } @override - Set<PropertyBuilder>? takeInitializedFields() { - Set<PropertyBuilder>? result = _initializedFields; + Set<SourcePropertyBuilder>? takeInitializedFields() { + Set<SourcePropertyBuilder>? result = _initializedFields; _initializedFields = null; return result; }
diff --git a/pkg/front_end/lib/src/source/source_enum_builder.dart b/pkg/front_end/lib/src/source/source_enum_builder.dart index 836ab98..46fd1ad 100644 --- a/pkg/front_end/lib/src/source/source_enum_builder.dart +++ b/pkg/front_end/lib/src/source/source_enum_builder.dart
@@ -2,14 +2,15 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. +import 'package:_fe_analyzer_shared/src/metadata/expressions.dart' as shared; import 'package:_fe_analyzer_shared/src/parser/formal_parameter_kind.dart'; import 'package:_fe_analyzer_shared/src/scanner/token.dart'; -import 'package:front_end/src/source/synthetic_method_builder.dart'; import 'package:kernel/ast.dart'; import 'package:kernel/class_hierarchy.dart'; import 'package:kernel/reference_from_index.dart' show IndexedClass; import 'package:kernel/src/bounds_checks.dart'; import 'package:kernel/transformations/flags.dart'; +import 'package:kernel/type_environment.dart'; import '../base/modifiers.dart' show Modifiers; import '../base/scope.dart'; @@ -35,12 +36,18 @@ import '../fragment/fragment.dart'; import '../kernel/body_builder_context.dart'; import '../kernel/constructor_tearoff_lowering.dart'; +import '../kernel/hierarchy/class_member.dart'; +import '../kernel/hierarchy/members_builder.dart'; import '../kernel/kernel_helper.dart'; +import '../kernel/member_covariance.dart'; +import '../kernel/type_algorithms.dart'; import 'name_scheme.dart'; import 'source_class_builder.dart' show SourceClassBuilder; import 'source_constructor_builder.dart'; -import 'source_field_builder.dart'; import 'source_library_builder.dart' show SourceLibraryBuilder; +import 'source_member_builder.dart'; +import 'source_property_builder.dart'; +import 'synthetic_method_builder.dart'; import 'type_parameter_scope_builder.dart'; class SourceEnumBuilder extends SourceClassBuilder { @@ -63,6 +70,8 @@ DeclaredSourceConstructorBuilder? synthesizedDefaultConstructorBuilder; + late final _EnumValuesFieldDeclaration _enumValuesFieldDeclaration; + SourceEnumBuilder.internal( {required List<MetadataBuilder>? metadata, required String name, @@ -239,9 +248,6 @@ Reference? constructorReference; Reference? tearOffReference; Reference? toStringReference; - Reference? valuesFieldReference; - Reference? valuesGetterReference; - Reference? valuesSetterReference; if (indexedClass != null) { constructorReference = indexedClass!.lookupConstructorReference(new Name("")); @@ -249,12 +255,12 @@ new Name(constructorTearOffName(""), indexedClass!.library)); toStringReference = indexedClass!.lookupGetterReference( new Name("_enumToString", coreLibrary.library)); - Name valuesName = new Name("values"); - valuesFieldReference = indexedClass!.lookupFieldReference(valuesName); - valuesGetterReference = indexedClass!.lookupGetterReference(valuesName); - valuesSetterReference = indexedClass!.lookupSetterReference(valuesName); } + FieldReference valuesReferences = new FieldReference( + "values", staticFieldNameScheme, indexedClass, + fieldIsLateWithLowering: false, isExternal: false); + Builder? customValuesDeclaration = nameSpace.lookupLocalMember("values", setter: false); if (customValuesDeclaration != null) { @@ -293,24 +299,22 @@ } } - SourceFieldBuilder valuesBuilder = new SourceFieldBuilder( - metadata: null, - type: listType, + _enumValuesFieldDeclaration = + new _EnumValuesFieldDeclaration(this, valuesReferences, listType); + + SourcePropertyBuilder valuesBuilder = new SourcePropertyBuilder.forField( + fileUri: fileUri, + fileOffset: fileOffset, name: "values", - modifiers: - Modifiers.Const | Modifiers.Static | Modifiers.HasInitializer, - isTopLevel: false, - isPrimaryConstructorField: false, libraryBuilder: libraryBuilder, declarationBuilder: this, - fileUri: fileUri, - nameOffset: fileOffset, - endOffset: fileOffset, nameScheme: staticFieldNameScheme, - fieldReference: valuesFieldReference, - fieldGetterReference: valuesGetterReference, - fieldSetterReference: valuesSetterReference, - isSynthesized: true); + fieldDeclaration: _enumValuesFieldDeclaration, + modifiers: + Modifiers.Const | Modifiers.Static | Modifiers.HasInitializer, + references: valuesReferences); + _enumValuesFieldDeclaration.builder = valuesBuilder; + if (customValuesDeclaration != null) { customValuesDeclaration.next = valuesBuilder; nameSpaceBuilder.checkTypeParameterConflict(libraryBuilder, @@ -477,22 +481,10 @@ @override void buildOutlineExpressions(ClassHierarchy classHierarchy, List<DelayedDefaultValueCloner> delayedDefaultValueCloners) { - List<Expression> values = <Expression>[]; for (EnumElementFragment enumElement in _enumElements) { enumElement.inferType(classHierarchy); - if (!enumElement.builder.isDuplicate) { - values.add(new StaticGet(enumElement.readTarget)); - } } - - SourceFieldBuilder valuesBuilder = - firstMemberNamed("values") as SourceFieldBuilder; - valuesBuilder.buildBody( - classHierarchy.coreTypes, - new ListLiteral(values, - typeArgument: instantiateToBounds(rawType(Nullability.nonNullable), - classHierarchy.coreTypes.objectClass), - isConst: true)); + _enumValuesFieldDeclaration.inferType(classHierarchy); super.buildOutlineExpressions(classHierarchy, delayedDefaultValueCloners); } @@ -567,3 +559,340 @@ } } } + +class _EnumValuesFieldDeclaration implements FieldDeclaration { + static const String name = "values"; + + final SourceEnumBuilder _sourceEnumBuilder; + final FieldReference fieldReference; + + SourcePropertyBuilder? _builder; + + DartType _type = const DynamicType(); + + Field? _field; + + @override + final TypeBuilder type; + + _EnumValuesFieldDeclaration( + this._sourceEnumBuilder, this.fieldReference, this.type); + + SourcePropertyBuilder get builder { + assert(_builder != null, "Builder has not been computed for $this."); + return _builder!; + } + + void set builder(SourcePropertyBuilder value) { + assert(_builder == null, "Builder has already been computed for $this."); + _builder = value; + } + + @override + Initializer buildErroneousInitializer(Expression effect, Expression value, + {required int fileOffset}) { + throw new UnsupportedError('${runtimeType}.buildErroneousInitializer'); + } + + @override + void buildImplicitDefaultValue() { + throw new UnsupportedError('${runtimeType}.buildImplicitDefaultValue'); + } + + @override + Initializer buildImplicitInitializer() { + throw new UnsupportedError('${runtimeType}.buildImplicitInitializer'); + } + + @override + List<Initializer> buildInitializer(int fileOffset, Expression value, + {required bool isSynthetic}) { + throw new UnsupportedError('${runtimeType}.buildInitializer'); + } + + @override + void buildOutlineExpressions( + ClassHierarchy classHierarchy, + SourceLibraryBuilder libraryBuilder, + DeclarationBuilder? declarationBuilder, + LookupScope parentScope, + List<Annotatable> annotatables, + {required bool isClassInstanceMember, + required bool createFileUriExpression}) { + List<Expression> values = <Expression>[]; + for (EnumElementFragment enumElement in _sourceEnumBuilder._enumElements) { + enumElement.inferType(classHierarchy); + if (!enumElement.builder.isDuplicate) { + values.add(new StaticGet(enumElement.readTarget)); + } + } + + _field!.initializer = new ListLiteral(values, + typeArgument: instantiateToBounds( + _sourceEnumBuilder.rawType(Nullability.nonNullable), + classHierarchy.coreTypes.objectClass), + isConst: true) + ..parent = _field; + } + + @override + void buildOutlineNode(SourceLibraryBuilder libraryBuilder, + NameScheme nameScheme, BuildNodesCallback f, FieldReference references, + {required List<TypeParameter>? classTypeParameters}) { + fieldType = type.build(libraryBuilder, TypeUse.fieldType); + _field = new Field.immutable(dummyName, + type: _type, + isFinal: false, + isConst: true, + isStatic: true, + fileUri: builder.fileUri, + fieldReference: references.fieldReference, + getterReference: references.fieldGetterReference, + isEnumElement: false) + ..fileOffset = builder.fileOffset + ..fileEndOffset = builder.fileOffset; + nameScheme + .getFieldMemberName(FieldNameType.Field, name, isSynthesized: false) + .attachMember(_field!); + f(member: _field!, kind: BuiltMemberKind.Field); + } + + @override + void checkTypes(SourceLibraryBuilder libraryBuilder, + TypeEnvironment typeEnvironment, SourcePropertyBuilder? setterBuilder, + {required bool isAbstract, required bool isExternal}) {} + + @override + // Coverage-ignore(suite): Not run. + void checkVariance( + SourceClassBuilder sourceClassBuilder, TypeEnvironment typeEnvironment) {} + + @override + int computeDefaultTypes(ComputeDefaultTypeContext context) { + return 0; + } + + @override + void ensureTypes( + ClassMembersBuilder membersBuilder, + Set<ClassMember>? getterOverrideDependencies, + Set<ClassMember>? setterOverrideDependencies) { + inferType(membersBuilder.hierarchyBuilder); + } + + @override + // Coverage-ignore(suite): Not run. + Iterable<Reference> getExportedMemberReferences(FieldReference references) { + return [references.fieldGetterReference]; + } + + @override + bool get hasInitializer => true; + + @override + bool get hasSetter => false; + + @override + // Coverage-ignore(suite): Not run. + shared.Expression? get initializerExpression => null; + + @override + // Coverage-ignore(suite): Not run. + bool get isEnumElement => false; + + @override + // Coverage-ignore(suite): Not run. + bool get isExtensionTypeDeclaredInstanceField => false; + + @override + // Coverage-ignore(suite): Not run. + bool get isFinal => false; + + @override + // Coverage-ignore(suite): Not run. + bool get isLate => false; + + @override + List<ClassMember> get localMembers => [new _EnumValuesClassMember(builder)]; + + @override + List<ClassMember> get localSetters => const []; + + @override + // Coverage-ignore(suite): Not run. + List<MetadataBuilder>? get metadata => null; + + @override + Member get readTarget => _field!; + + @override + Member? get writeTarget => null; + + @override + // Coverage-ignore(suite): Not run. + DartType get fieldType => _type; + + @override + void set fieldType(DartType value) { + _type = value; + _field + // Coverage-ignore(suite): Not run. + ?.type = value; + } + + @override + DartType inferType(ClassHierarchyBase hierarchy) { + return _type; + } +} + +class _EnumValuesClassMember implements ClassMember { + final SourcePropertyBuilder _builder; + + Covariance? _covariance; + + _EnumValuesClassMember(this._builder); + + @override + bool get forSetter => false; + + @override + int get charOffset => _builder.fileOffset; + + @override + DeclarationBuilder get declarationBuilder => _builder.declarationBuilder!; + + @override + // Coverage-ignore(suite): Not run. + List<ClassMember> get declarations => + throw new UnsupportedError('$runtimeType.declarations'); + + @override + // Coverage-ignore(suite): Not run. + Uri get fileUri => _builder.fileUri; + + @override + // Coverage-ignore(suite): Not run. + String get fullName { + String className = declarationBuilder.fullNameForErrors; + return "${className}.${fullNameForErrors}"; + } + + @override + String get fullNameForErrors => _builder.fullNameForErrors; + + @override + // Coverage-ignore(suite): Not run. + Covariance getCovariance(ClassMembersBuilder membersBuilder) { + return _covariance ??= forSetter + ? new Covariance.fromMember(getMember(membersBuilder), + forSetter: forSetter) + : const Covariance.empty(); + } + + @override + Member getMember(ClassMembersBuilder membersBuilder) { + _builder.ensureTypes(membersBuilder); + return forSetter + ? + // Coverage-ignore(suite): Not run. + _builder.writeTarget! + : _builder.readTarget!; + } + + @override + // Coverage-ignore(suite): Not run. + MemberResult getMemberResult(ClassMembersBuilder membersBuilder) { + return new StaticMemberResult(getMember(membersBuilder), memberKind, + isDeclaredAsField: true, + fullName: '${declarationBuilder.name}.${_builder.memberName.text}'); + } + + @override + // Coverage-ignore(suite): Not run. + Member? getTearOff(ClassMembersBuilder membersBuilder) => null; + + @override + bool get hasDeclarations => false; + + @override + // Coverage-ignore(suite): Not run. + void inferType(ClassMembersBuilder membersBuilder) { + _builder.ensureTypes(membersBuilder); + } + + @override + ClassMember get interfaceMember => this; + + @override + bool get isAbstract => false; + + @override + bool get isDuplicate => _builder.isDuplicate; + + @override + // Coverage-ignore(suite): Not run. + bool get isExtensionTypeMember => _builder.isExtensionTypeMember; + + @override + // Coverage-ignore(suite): Not run. + bool get isField => true; + + @override + // Coverage-ignore(suite): Not run. + bool get isGetter => false; + + @override + // Coverage-ignore(suite): Not run. + bool get isInternalImplementation => false; + + @override + // Coverage-ignore(suite): Not run. + bool get isNoSuchMethodForwarder => false; + + @override + // Coverage-ignore(suite): Not run. + bool isObjectMember(ClassBuilder objectClass) { + return declarationBuilder == objectClass; + } + + @override + bool get isProperty => true; + + @override + bool isSameDeclaration(ClassMember other) { + return other is _EnumValuesClassMember && + // Coverage-ignore(suite): Not run. + _builder == other._builder; + } + + @override + // Coverage-ignore(suite): Not run. + bool get isSetter => false; + + @override + // Coverage-ignore(suite): Not run. + bool get isSourceDeclaration => true; + + @override + bool get isStatic => true; + + @override + bool get isSynthesized => true; + + @override + // Coverage-ignore(suite): Not run. + ClassMemberKind get memberKind => ClassMemberKind.Getter; + + @override + Name get name => _builder.memberName; + + @override + // Coverage-ignore(suite): Not run. + void registerOverrideDependency(Set<ClassMember> overriddenMembers) { + _builder.registerGetterOverrideDependency(overriddenMembers); + } + + @override + String toString() => '$runtimeType($fullName)'; +}
diff --git a/pkg/front_end/lib/src/source/source_factory_builder.dart b/pkg/front_end/lib/src/source/source_factory_builder.dart index 8629118..6675afe 100644 --- a/pkg/front_end/lib/src/source/source_factory_builder.dart +++ b/pkg/front_end/lib/src/source/source_factory_builder.dart
@@ -25,7 +25,6 @@ import '../builder/formal_parameter_builder.dart'; import '../builder/function_builder.dart'; import '../builder/metadata_builder.dart'; -import '../builder/omitted_type_builder.dart'; import '../builder/type_builder.dart'; import '../codes/cfe_codes.dart'; import '../dill/dill_extension_type_member_builder.dart'; @@ -263,6 +262,9 @@ void buildOutlineExpressions(ClassHierarchy classHierarchy, List<DelayedDefaultValueCloner> delayedDefaultValueCloners) { if (_hasBuiltOutlines) return; + + inferFormals(formals, classHierarchy); + if (_delayedDefaultValueCloner != null) { delayedDefaultValueCloners.add(_delayedDefaultValueCloner!); } @@ -560,6 +562,9 @@ void buildOutlineExpressions(ClassHierarchy classHierarchy, List<DelayedDefaultValueCloner> delayedDefaultValueCloners) { if (_hasBuiltOutlines) return; + + inferFormals(formals, classHierarchy); + if (isConst && isAugmenting) { origin.buildOutlineExpressions( classHierarchy, delayedDefaultValueCloners); @@ -583,31 +588,6 @@ createBodyBuilderContext(), declarationBuilder.scope, fileUri); Builder? targetBuilder = redirectionTarget.target; - // Inference of target's formals should happen before building of the - // outline expressions in members and before inferring target's type - // arguments. - // - // (1) The outline expressions, such as formal parameter initializers, - // need properly inferred type contexts. Among other things, it ensures - // that the required coercions, such as int-to-double conversion, are - // run. - // - // (2) Type arguments for the targets of redirecting factories can only - // be inferred if the formal parameters of the targets are inferred too. - // That may not be the case when the target's parameters are initializing - // parameters referring to fields with types that are to be inferred. - if (targetBuilder is SourceFunctionBuilderImpl) { - List<FormalParameterBuilder>? formals = targetBuilder.formals; - if (formals != null) { - for (FormalParameterBuilder formal in formals) { - TypeBuilder formalType = formal.type; - if (formalType is InferableTypeBuilder) { - formalType.inferType(classHierarchy); - } - } - } - } - if (targetBuilder is SourceMemberBuilder) { // Ensure that target has been built. targetBuilder.buildOutlineExpressions(
diff --git a/pkg/front_end/lib/src/source/source_field_builder.dart b/pkg/front_end/lib/src/source/source_field_builder.dart deleted file mode 100644 index da30acb..0000000 --- a/pkg/front_end/lib/src/source/source_field_builder.dart +++ /dev/null
@@ -1,2332 +0,0 @@ -// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:_fe_analyzer_shared/src/metadata/expressions.dart' as shared; -import 'package:_fe_analyzer_shared/src/scanner/scanner.dart' show Token; -import 'package:kernel/ast.dart'; -import 'package:kernel/class_hierarchy.dart'; -import 'package:kernel/core_types.dart'; -import 'package:kernel/type_algebra.dart'; -import 'package:kernel/type_environment.dart'; - -import '../api_prototype/lowering_predicates.dart'; -import '../base/constant_context.dart' show ConstantContext; -import '../base/modifiers.dart' show Modifiers; -import '../base/name_space.dart'; -import '../base/problems.dart' show internalProblem; -import '../base/scope.dart' show LookupScope; -import '../builder/builder.dart'; -import '../builder/declaration_builders.dart'; -import '../builder/field_builder.dart'; -import '../builder/member_builder.dart'; -import '../builder/metadata_builder.dart'; -import '../builder/omitted_type_builder.dart'; -import '../builder/property_builder.dart'; -import '../builder/type_builder.dart'; -import '../codes/cfe_codes.dart' show messageInternalProblemAlreadyInitialized; -import '../kernel/body_builder.dart' show BodyBuilder; -import '../kernel/body_builder_context.dart'; -import '../kernel/hierarchy/class_member.dart'; -import '../kernel/hierarchy/members_builder.dart'; -import '../kernel/implicit_field_type.dart'; -import '../kernel/internal_ast.dart'; -import '../kernel/kernel_helper.dart'; -import '../kernel/late_lowering.dart' as late_lowering; -import '../kernel/macro/metadata.dart'; -import '../kernel/member_covariance.dart'; -import '../kernel/type_algorithms.dart'; -import '../source/name_scheme.dart'; -import '../source/source_extension_builder.dart'; -import '../source/source_library_builder.dart' show SourceLibraryBuilder; -import '../type_inference/type_inference_engine.dart' - show IncludesTypeParametersNonCovariantly; -import 'source_class_builder.dart'; -import 'source_extension_type_declaration_builder.dart'; -import 'source_member_builder.dart'; - -class SourceFieldBuilder extends SourceMemberBuilderImpl - implements FieldBuilder, InferredTypeListener, Inferable, PropertyBuilder { - @override - final SourceLibraryBuilder libraryBuilder; - - @override - final String name; - - final MemberName _memberName; - - final Modifiers modifiers; - - late FieldEncoding _fieldEncoding; - - final List<MetadataBuilder>? metadata; - - final TypeBuilder type; - - Token? _constInitializerToken; - - shared.Expression? _initializerExpression; - - /// Whether the body of this field has been built. - /// - /// Constant fields have their initializer built in the outline so we avoid - /// building them twice as part of the non-outline build. - bool hasBodyBeenBuilt = false; - - // TODO(johnniwinther): [parent] is not trust-worthy for determining - // properties since it is changed after the creation of the builder. For now - // we require it has an argument here. A follow-up should clean up the - // misuse of parent. - @override - final bool isTopLevel; - - final bool isPrimaryConstructorField; - - @override - final bool isSynthesized; - - /// If `true`, this field builder is for the field corresponding to an enum - /// element. - @override - final bool isEnumElement; - - @override - final DeclarationBuilder? declarationBuilder; - - final int nameOffset; - - @override - final Uri fileUri; - - SourceFieldBuilder( - {required this.metadata, - required this.type, - required this.name, - required this.modifiers, - required this.isTopLevel, - required this.isPrimaryConstructorField, - required this.libraryBuilder, - required this.declarationBuilder, - required this.fileUri, - required this.nameOffset, - required int endOffset, - required NameScheme nameScheme, - Reference? fieldReference, - Reference? fieldGetterReference, - Reference? fieldSetterReference, - Reference? lateIsSetFieldReference, - Reference? lateIsSetGetterReference, - Reference? lateIsSetSetterReference, - Reference? lateGetterReference, - Reference? lateSetterReference, - Token? initializerToken, - Token? constInitializerToken, - this.isSynthesized = false, - this.isEnumElement = false}) - : _constInitializerToken = constInitializerToken, - _memberName = nameScheme.getDeclaredName(name) { - type.registerInferredTypeListener(this); - - bool isInstanceMember = nameScheme.isInstanceMember; - - // If in mixed mode, late lowerings cannot use `null` as a sentinel on - // non-nullable fields since they can be assigned from legacy code. - late_lowering.IsSetStrategy isSetStrategy = - late_lowering.computeIsSetStrategy(libraryBuilder); - if (isAbstract || isExternal) { - // Coverage-ignore-block(suite): Not run. - assert(fieldReference == null); - assert(lateIsSetFieldReference == null); - assert(lateIsSetGetterReference == null); - assert(lateIsSetSetterReference == null); - assert(lateGetterReference == null); - assert(lateSetterReference == null); - assert(!isEnumElement, "Unexpected abstract/external enum element"); - _fieldEncoding = new AbstractOrExternalFieldEncoding( - this, - name, - nameScheme, - fileUri, - nameOffset, - endOffset, - fieldGetterReference, - fieldSetterReference, - isAbstract: isAbstract, - isExternal: isExternal, - isFinal: isFinal, - isCovariantByDeclaration: isCovariantByDeclaration); - } else if (nameScheme.isExtensionTypeMember && - // Coverage-ignore(suite): Not run. - nameScheme.isInstanceMember) { - // Coverage-ignore-block(suite): Not run. - assert(fieldReference == null); - assert(fieldSetterReference == null); - assert(lateIsSetFieldReference == null); - assert(lateIsSetGetterReference == null); - assert(lateIsSetSetterReference == null); - assert(lateGetterReference == null); - assert(lateSetterReference == null); - if (isPrimaryConstructorField) { - _fieldEncoding = new RepresentationFieldEncoding(this, name, nameScheme, - fileUri, nameOffset, endOffset, fieldGetterReference); - } else { - // Field on a extension type. Encode as abstract. - // TODO(johnniwinther): Should we have an erroneous flag on such - // members? - _fieldEncoding = new AbstractOrExternalFieldEncoding( - this, - name, - nameScheme, - fileUri, - nameOffset, - endOffset, - fieldGetterReference, - fieldSetterReference, - isAbstract: true, - isExternal: false, - isFinal: isFinal, - isCovariantByDeclaration: isCovariantByDeclaration, - isForcedExtension: true); - } - } else if (isLate && - // Coverage-ignore(suite): Not run. - libraryBuilder.loader.target.backendTarget.isLateFieldLoweringEnabled( - hasInitializer: hasInitializer, - isFinal: isFinal, - isStatic: !isInstanceMember)) { - // Coverage-ignore-block(suite): Not run. - assert(!isEnumElement, "Unexpected late enum element"); - if (hasInitializer) { - if (isFinal) { - _fieldEncoding = new LateFinalFieldWithInitializerEncoding( - name: name, - nameScheme: nameScheme, - fileUri: fileUri, - nameOffset: nameOffset, - endOffset: endOffset, - fieldReference: fieldReference, - fieldGetterReference: fieldGetterReference, - fieldSetterReference: fieldSetterReference, - lateIsSetFieldReference: lateIsSetFieldReference, - lateIsSetGetterReference: lateIsSetGetterReference, - lateIsSetSetterReference: lateIsSetSetterReference, - lateGetterReference: lateGetterReference, - lateSetterReference: lateSetterReference, - isCovariantByDeclaration: isCovariantByDeclaration, - isSetStrategy: isSetStrategy); - } else { - _fieldEncoding = new LateFieldWithInitializerEncoding( - name: name, - nameScheme: nameScheme, - fileUri: fileUri, - nameOffset: nameOffset, - endOffset: endOffset, - fieldReference: fieldReference, - fieldGetterReference: fieldGetterReference, - fieldSetterReference: fieldSetterReference, - lateIsSetFieldReference: lateIsSetFieldReference, - lateIsSetGetterReference: lateIsSetGetterReference, - lateIsSetSetterReference: lateIsSetSetterReference, - lateGetterReference: lateGetterReference, - lateSetterReference: lateSetterReference, - isCovariantByDeclaration: isCovariantByDeclaration, - isSetStrategy: isSetStrategy); - } - } else { - if (isFinal) { - _fieldEncoding = new LateFinalFieldWithoutInitializerEncoding( - name: name, - nameScheme: nameScheme, - fileUri: fileUri, - nameOffset: nameOffset, - endOffset: endOffset, - fieldReference: fieldReference, - fieldGetterReference: fieldGetterReference, - fieldSetterReference: fieldSetterReference, - lateIsSetFieldReference: lateIsSetFieldReference, - lateIsSetGetterReference: lateIsSetGetterReference, - lateIsSetSetterReference: lateIsSetSetterReference, - lateGetterReference: lateGetterReference, - lateSetterReference: lateSetterReference, - isCovariantByDeclaration: isCovariantByDeclaration, - isSetStrategy: isSetStrategy); - } else { - _fieldEncoding = new LateFieldWithoutInitializerEncoding( - name: name, - nameScheme: nameScheme, - fileUri: fileUri, - nameOffset: nameOffset, - endOffset: endOffset, - fieldReference: fieldReference, - fieldGetterReference: fieldGetterReference, - fieldSetterReference: fieldSetterReference, - lateIsSetFieldReference: lateIsSetFieldReference, - lateIsSetGetterReference: lateIsSetGetterReference, - lateIsSetSetterReference: lateIsSetSetterReference, - lateGetterReference: lateGetterReference, - lateSetterReference: lateSetterReference, - isCovariantByDeclaration: isCovariantByDeclaration, - isSetStrategy: isSetStrategy); - } - } - } else if (libraryBuilder - .loader.target.backendTarget.useStaticFieldLowering && - !isInstanceMember && - !isConst && - // Coverage-ignore(suite): Not run. - hasInitializer) { - // Coverage-ignore-block(suite): Not run. - assert(!isEnumElement, "Unexpected non-const enum element"); - if (isFinal) { - _fieldEncoding = new LateFinalFieldWithInitializerEncoding( - name: name, - nameScheme: nameScheme, - fileUri: fileUri, - nameOffset: nameOffset, - endOffset: endOffset, - fieldReference: fieldReference, - fieldGetterReference: fieldGetterReference, - fieldSetterReference: fieldSetterReference, - lateIsSetFieldReference: lateIsSetFieldReference, - lateIsSetGetterReference: lateIsSetGetterReference, - lateIsSetSetterReference: lateIsSetSetterReference, - lateGetterReference: lateGetterReference, - lateSetterReference: lateSetterReference, - isCovariantByDeclaration: isCovariantByDeclaration, - isSetStrategy: isSetStrategy); - } else { - _fieldEncoding = new LateFieldWithInitializerEncoding( - name: name, - nameScheme: nameScheme, - fileUri: fileUri, - nameOffset: nameOffset, - endOffset: endOffset, - fieldReference: fieldReference, - fieldGetterReference: fieldGetterReference, - fieldSetterReference: fieldSetterReference, - lateIsSetFieldReference: lateIsSetFieldReference, - lateIsSetGetterReference: lateIsSetGetterReference, - lateIsSetSetterReference: lateIsSetSetterReference, - lateGetterReference: lateGetterReference, - lateSetterReference: lateSetterReference, - isCovariantByDeclaration: isCovariantByDeclaration, - isSetStrategy: isSetStrategy); - } - } else { - assert(lateIsSetFieldReference == null); - assert(lateIsSetGetterReference == null); - assert(lateIsSetSetterReference == null); - assert(lateGetterReference == null); - assert(lateSetterReference == null); - _fieldEncoding = new RegularFieldEncoding( - name: name, - nameScheme: nameScheme, - fileUri: fileUri, - nameOffset: nameOffset, - endOffset: endOffset, - isFinal: isFinal, - isConst: isConst, - isLate: isLate, - hasInitializer: hasInitializer, - fieldReference: fieldReference, - getterReference: fieldGetterReference, - setterReference: fieldSetterReference, - isEnumElement: isEnumElement); - } - - if (type is InferableTypeBuilder) { - // Coverage-ignore-block(suite): Not run. - if (!hasInitializer && isStatic) { - // A static field without type and initializer will always be inferred - // to have type `dynamic`. - type.registerInferredType(const DynamicType()); - } else { - // A field with no type and initializer or an instance field without - // type and initializer need to have the type inferred. - _fieldEncoding.type = - new InferredType.fromFieldInitializer(this, initializerToken); - type.registerInferable(this); - } - } - } - - @override - int get fileOffset => nameOffset; - - @override - // Coverage-ignore(suite): Not run. - Iterable<MetadataBuilder>? get metadataForTesting => metadata; - - @override - // Coverage-ignore(suite): Not run. - bool get isProperty => true; - - @override - // Coverage-ignore(suite): Not run. - bool get isAugmentation => modifiers.isAugment; - - @override - bool get isExternal => modifiers.isExternal; - - @override - bool get isAbstract => modifiers.isAbstract; - - @override - // Coverage-ignore(suite): Not run. - bool get isExtensionTypeDeclaredInstanceField => - isExtensionTypeInstanceMember && !isPrimaryConstructorField; - - @override - bool get isConst => modifiers.isConst; - - @override - bool get isFinal => modifiers.isFinal; - - @override - bool get isStatic => modifiers.isStatic; - - @override - // Coverage-ignore(suite): Not run. - bool get isAugment => modifiers.isAugment; - - @override - Builder get parent => - declarationBuilder ?? // Coverage-ignore(suite): Not run. - libraryBuilder; - - @override - Name get memberName => _memberName.name; - - bool _typeEnsured = false; - Set<ClassMember>? _overrideDependencies; - - // Coverage-ignore(suite): Not run. - void registerOverrideDependency(Set<ClassMember> overriddenMembers) { - assert( - overriddenMembers.every((overriddenMember) => - overriddenMember.declarationBuilder != classBuilder), - "Unexpected override dependencies for $this: $overriddenMembers"); - _overrideDependencies ??= {}; - _overrideDependencies!.addAll(overriddenMembers); - } - - void _ensureType(ClassMembersBuilder membersBuilder) { - if (_typeEnsured) return; - if (_overrideDependencies != null) { - // Coverage-ignore-block(suite): Not run. - membersBuilder.inferFieldType(declarationBuilder as SourceClassBuilder, - type, _overrideDependencies!, - name: fullNameForErrors, - fileUri: fileUri, - nameOffset: nameOffset, - nameLength: fullNameForErrors.length, - isAssignable: isAssignable); - _overrideDependencies = null; - } else { - type.build(libraryBuilder, TypeUse.fieldType, - hierarchy: membersBuilder.hierarchyBuilder); - } - _typeEnsured = true; - } - - @override - bool get isField => true; - - @override - bool get isLate => modifiers.isLate; - - bool get isCovariantByDeclaration => modifiers.isCovariant; - - @override - bool get hasInitializer => modifiers.hasInitializer; - - /// Builds the body of this field using [initializer] as the initializer - /// expression. - void buildBody(CoreTypes coreTypes, Expression? initializer) { - assert(!hasBodyBeenBuilt, "Body has already been built for $this."); - hasBodyBeenBuilt = true; - if (!hasInitializer && - initializer != null && - // Coverage-ignore(suite): Not run. - initializer is! NullLiteral && - // Coverage-ignore(suite): Not run. - !isConst && - // Coverage-ignore(suite): Not run. - !isFinal) { - internalProblem( - messageInternalProblemAlreadyInitialized, fileOffset, fileUri); - } - _fieldEncoding.createBodies(coreTypes, initializer); - } - - @override - // Coverage-ignore(suite): Not run. - List<Initializer> buildInitializer(int fileOffset, Expression value, - {required bool isSynthetic}) { - return _fieldEncoding.createInitializer(fileOffset, value, - isSynthetic: isSynthetic); - } - - @override - // Coverage-ignore(suite): Not run. - void buildImplicitDefaultValue() { - _fieldEncoding.buildImplicitDefaultValue(); - } - - @override - // Coverage-ignore(suite): Not run. - Initializer buildImplicitInitializer() { - return _fieldEncoding.buildImplicitInitializer(); - } - - @override - // Coverage-ignore(suite): Not run. - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}) { - return _fieldEncoding.buildErroneousInitializer(effect, value, - fileOffset: fileOffset); - } - - @override - bool get isAssignable { - if (isConst) return false; - // Coverage-ignore(suite): Not run. - if (isFinal) { - if (isLate) { - return !hasInitializer; - } - return false; - } - return true; - } - - @override - Field get field => _fieldEncoding.field; - - @override - Member get readTarget => _fieldEncoding.readTarget; - - @override - // Coverage-ignore(suite): Not run. - Reference get readTargetReference => _fieldEncoding.readTargetReference; - - @override - // Coverage-ignore(suite): Not run. - Member? get writeTarget { - return isAssignable ? _fieldEncoding.writeTarget : null; - } - - @override - // Coverage-ignore(suite): Not run. - Reference? get writeTargetReference => _fieldEncoding.writeTargetReference; - - @override - Member get invokeTarget => readTarget; - - @override - // Coverage-ignore(suite): Not run. - Reference get invokeTargetReference => _fieldEncoding.readTargetReference; - - @override - // Coverage-ignore(suite): Not run. - Iterable<Reference> get exportedMemberReferences => - _fieldEncoding.exportedReferenceMembers; - - @override - void buildOutlineNodes(BuildNodesCallback f) { - _build(); - _fieldEncoding.registerMembers(libraryBuilder, this, f); - } - - /// Builds the core AST structures for this field as needed for the outline. - void _build() { - if (type is! InferableTypeBuilder) { - fieldType = type.build(libraryBuilder, TypeUse.fieldType); - } - _fieldEncoding.build(libraryBuilder, this); - } - - BodyBuilderContext createBodyBuilderContext() { - return new FieldBodyBuilderContext(this, _fieldEncoding.builtMember); - } - - @override - Iterable<Annotatable> get annotatables => _fieldEncoding.annotatables; - - @override - void buildOutlineExpressions(ClassHierarchy classHierarchy, - List<DelayedDefaultValueCloner> delayedDefaultValueCloners) { - for (Annotatable annotatable in annotatables) { - MetadataBuilder.buildAnnotations( - annotatable, - metadata, - createBodyBuilderContext(), - libraryBuilder, - fileUri, - declarationBuilder?.scope ?? // Coverage-ignore(suite): Not run. - libraryBuilder.scope); - } - - // For modular compilation we need to include initializers of all const - // fields and all non-static final fields in classes with const constructors - // into the outline. - if ((isConst || - // Coverage-ignore(suite): Not run. - (isFinal && - !isStatic && - isClassMember && - classBuilder!.declaresConstConstructor)) && - _constInitializerToken != null) { - // Coverage-ignore-block(suite): Not run. - Token initializerToken = _constInitializerToken!; - LookupScope scope = declarationBuilder?.scope ?? libraryBuilder.scope; - BodyBuilder bodyBuilder = libraryBuilder.loader - .createBodyBuilderForOutlineExpression( - libraryBuilder, createBodyBuilderContext(), scope, fileUri); - bodyBuilder.constantContext = - isConst ? ConstantContext.inferred : ConstantContext.required; - Expression initializer = bodyBuilder.typeInferrer - .inferFieldInitializer(bodyBuilder, fieldType, - bodyBuilder.parseFieldInitializer(initializerToken)) - .expression; - buildBody(classHierarchy.coreTypes, initializer); - bodyBuilder.performBacklogComputations(); - if (computeSharedExpressionForTesting) { - _initializerExpression = parseFieldInitializer(libraryBuilder.loader, - initializerToken, libraryBuilder.importUri, fileUri, scope); - } - } - _constInitializerToken = null; - } - - // Coverage-ignore(suite): Not run. - shared.Expression? get initializerExpression => _initializerExpression; - - // Coverage-ignore(suite): Not run. - bool get hasOutlineExpressionsBuilt => _constInitializerToken == null; - - @override - DartType get fieldType => _fieldEncoding.type; - - @override - void set fieldType(DartType value) { - _fieldEncoding.type = value; - if (!isFinal && - !isConst && - // Coverage-ignore(suite): Not run. - parent is ClassBuilder) { - // Coverage-ignore-block(suite): Not run. - Class enclosingClass = classBuilder!.cls; - if (enclosingClass.typeParameters.isNotEmpty) { - IncludesTypeParametersNonCovariantly needsCheckVisitor = - new IncludesTypeParametersNonCovariantly( - enclosingClass.typeParameters, - // We are checking the field type as if it is the type of the - // parameter of the implicit setter and this is a contravariant - // position. - initialVariance: Variance.contravariant); - if (value.accept(needsCheckVisitor)) { - _fieldEncoding.setGenericCovariantImpl(); - } - } - } - } - - @override - // Coverage-ignore(suite): Not run. - void inferTypes(ClassHierarchyBase hierarchy) { - inferType(hierarchy); - } - - @override - // Coverage-ignore(suite): Not run. - DartType inferType(ClassHierarchyBase hierarchy) { - if (fieldType is! InferredType) { - // We have already inferred a type. - return fieldType; - } - - return libraryBuilder.loader.withUriForCrashReporting(fileUri, fileOffset, - () { - InferredType implicitFieldType = fieldType as InferredType; - DartType inferredType = implicitFieldType.computeType(hierarchy); - if (fieldType is InferredType) { - // `fieldType` may have changed if a circularity was detected when - // [inferredType] was computed. - type.registerInferredType(inferredType); - - IncludesTypeParametersNonCovariantly? needsCheckVisitor; - if (parent is ClassBuilder) { - Class enclosingClass = classBuilder!.cls; - if (enclosingClass.typeParameters.isNotEmpty) { - needsCheckVisitor = new IncludesTypeParametersNonCovariantly( - enclosingClass.typeParameters, - // We are checking the field type as if it is the type of the - // parameter of the implicit setter and this is a contravariant - // position. - initialVariance: Variance.contravariant); - } - } - if (needsCheckVisitor != null) { - if (fieldType.accept(needsCheckVisitor)) { - _fieldEncoding.setGenericCovariantImpl(); - } - } - } - return fieldType; - }); - } - - @override - // Coverage-ignore(suite): Not run. - void onInferredType(DartType type) { - fieldType = type; - } - - // Coverage-ignore(suite): Not run. - DartType get builtType => fieldType; - - List<ClassMember>? _localMembers; - List<ClassMember>? _localSetters; - - @override - List<ClassMember> get localMembers => - _localMembers ??= _fieldEncoding.getLocalMembers(this); - - @override - List<ClassMember> get localSetters => - _localSetters ??= _fieldEncoding.getLocalSetters(this); - - @override - int computeDefaultTypes(ComputeDefaultTypeContext context, - {required bool inErrorRecovery}) { - TypeBuilder? fieldType = type; - if (fieldType is! OmittedTypeBuilder) { - context.reportInboundReferenceIssuesForType(fieldType); - context.recursivelyReportGenericFunctionTypesAsBoundsForType(fieldType); - } - return 0; - } - - @override - void checkVariance( - SourceClassBuilder sourceClassBuilder, TypeEnvironment typeEnvironment) { - sourceClassBuilder.checkVarianceInField(typeEnvironment, - fieldType: fieldType, - isInstanceMember: isClassInstanceMember, - hasSetter: isAssignable, - isCovariantByDeclaration: isCovariantByDeclaration, - fileUri: fileUri, - fileOffset: fileOffset); - } - - @override - void checkTypes(SourceLibraryBuilder library, NameSpace nameSpace, - TypeEnvironment typeEnvironment) { - library.checkTypesInField(typeEnvironment, - isInstanceMember: isDeclarationInstanceMember, - isLate: isLate, - isExternal: isExternal, - hasInitializer: hasInitializer, - fieldType: fieldType, - name: name, - nameLength: name.length, - nameOffset: fileOffset, - fileUri: fileUri); - } - - @override - int buildBodyNodes(BuildNodesCallback f) { - return 0; - } -} - -/// Strategy pattern for creating different encodings of a declared field. -/// -/// This is used to provide lowerings for late fields using synthesized getters -/// and setters. -abstract class FieldEncoding { - /// The type of the declared field. - abstract DartType type; - - /// Creates the bodies needed for the field encoding using [initializer] as - /// the declared initializer expression. - /// - /// This method is not called for fields in outlines unless their are constant - /// or part of a const constructor. - void createBodies(CoreTypes coreTypes, Expression? initializer); - - List<Initializer> createInitializer(int fileOffset, Expression value, - {required bool isSynthetic}); - - /// Creates the AST node for this field as the default initializer. - void buildImplicitDefaultValue(); - - /// Create the [Initializer] for the implicit initialization of this field - /// in a constructor. - Initializer buildImplicitInitializer(); - - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}); - - /// Registers that the (implicit) setter associated with this field needs to - /// contain a runtime type check to deal with generic covariance. - void setGenericCovariantImpl(); - - /// Returns the field that holds the field value at runtime. - Field get field; - - /// The [Member] built during [SourceFieldBuilder.buildOutlineExpressions]. - Member get builtMember; - - /// Returns the members that holds the field annotations. - Iterable<Annotatable> get annotatables; - - /// Returns the member used to read the field value. - Member get readTarget; - - /// Returns the reference used to read the field value. - Reference get readTargetReference; - - /// Returns the member used to write to the field. - Member? get writeTarget; - - /// Returns the reference used to write to the field. - Reference? get writeTargetReference; - - /// Returns the references to the generated members that are visible through - /// exports. - /// - /// This is the getter reference, and, if available, the setter reference. - Iterable<Reference> get exportedReferenceMembers; - - /// Creates the members necessary for this field encoding. - /// - /// This method is called for both outline and full compilation so the created - /// members should be without body. The member bodies are created through - /// [createBodies]. - void build( - SourceLibraryBuilder libraryBuilder, SourceFieldBuilder fieldBuilder); - - /// Calls [f] for each member needed for this field encoding. - void registerMembers(SourceLibraryBuilder library, - SourceFieldBuilder fieldBuilder, BuildNodesCallback f); - - /// Returns a list of the field, getters and methods created by this field - /// encoding. - List<ClassMember> getLocalMembers(SourceFieldBuilder fieldBuilder); - - /// Returns a list of the setters created by this field encoding. - List<ClassMember> getLocalSetters(SourceFieldBuilder fieldBuilder); -} - -class RegularFieldEncoding implements FieldEncoding { - late final Field _field; - - RegularFieldEncoding( - {required String name, - required NameScheme nameScheme, - required Uri fileUri, - required int nameOffset, - required int endOffset, - required bool isFinal, - required bool isConst, - required bool isLate, - required bool hasInitializer, - required Reference? fieldReference, - required Reference? getterReference, - required Reference? setterReference, - required bool isEnumElement}) { - bool isImmutable = - isLate ? (isFinal && hasInitializer) : (isFinal || isConst); - _field = isImmutable - ? new Field.immutable(dummyName, - isFinal: isFinal, - isConst: isConst, - isLate: isLate, - fileUri: fileUri, - fieldReference: fieldReference, - getterReference: getterReference, - isEnumElement: isEnumElement) - : - // Coverage-ignore(suite): Not run. - new Field.mutable(dummyName, - isFinal: isFinal, - isLate: isLate, - fileUri: fileUri, - fieldReference: fieldReference, - getterReference: getterReference, - setterReference: setterReference); - nameScheme - .getFieldMemberName(FieldNameType.Field, name, isSynthesized: false) - .attachMember(_field); - _field - ..fileOffset = nameOffset - ..fileEndOffset = endOffset; - } - - @override - DartType get type => _field.type; - - @override - void set type(DartType value) { - _field.type = value; - } - - @override - void createBodies(CoreTypes coreTypes, Expression? initializer) { - if (initializer != null) { - _field.initializer = initializer..parent = _field; - } - } - - @override - // Coverage-ignore(suite): Not run. - List<Initializer> createInitializer(int fileOffset, Expression value, - {required bool isSynthetic}) { - return <Initializer>[ - new FieldInitializer(_field, value) - ..fileOffset = fileOffset - ..isSynthetic = isSynthetic - ]; - } - - @override - void build( - SourceLibraryBuilder libraryBuilder, SourceFieldBuilder fieldBuilder) { - _field..isCovariantByDeclaration = fieldBuilder.isCovariantByDeclaration; - if (fieldBuilder.isExtensionMember) { - // Coverage-ignore-block(suite): Not run. - _field - ..isStatic = true - ..isExtensionMember = true; - } else if (fieldBuilder.isExtensionTypeMember) { - // Coverage-ignore-block(suite): Not run. - _field - ..isStatic = fieldBuilder.isStatic - ..isExtensionTypeMember = true; - } else { - bool isInstanceMember = !fieldBuilder.isStatic && - // Coverage-ignore(suite): Not run. - !fieldBuilder.isTopLevel; - _field - ..isStatic = !isInstanceMember - ..isExtensionMember = false; - } - _field.isLate = fieldBuilder.isLate; - } - - @override - void registerMembers(SourceLibraryBuilder library, - SourceFieldBuilder fieldBuilder, BuildNodesCallback f) { - f( - member: _field, - kind: - fieldBuilder.isExtensionMember || fieldBuilder.isExtensionTypeMember - ? BuiltMemberKind.ExtensionField - : BuiltMemberKind.Field); - } - - @override - // Coverage-ignore(suite): Not run. - void setGenericCovariantImpl() { - if (_field.hasSetter) { - _field.isCovariantByClass = true; - } - } - - @override - Field get field => _field; - - @override - Member get builtMember => _field; - - @override - Iterable<Annotatable> get annotatables => [_field]; - - @override - Member get readTarget => _field; - - @override - // Coverage-ignore(suite): Not run. - Reference get readTargetReference => _field.getterReference; - - @override - // Coverage-ignore(suite): Not run. - Member get writeTarget => _field; - - @override - // Coverage-ignore(suite): Not run. - Reference? get writeTargetReference => _field.setterReference; - - @override - // Coverage-ignore(suite): Not run. - Iterable<Reference> get exportedReferenceMembers => - [_field.getterReference, if (_field.hasSetter) _field.setterReference!]; - - @override - List<ClassMember> getLocalMembers(SourceFieldBuilder fieldBuilder) => - <ClassMember>[ - new SourceFieldMember(fieldBuilder, ClassMemberKind.Getter) - ]; - - @override - List<ClassMember> getLocalSetters(SourceFieldBuilder fieldBuilder) => - fieldBuilder.isAssignable - ? - // Coverage-ignore(suite): Not run. - <ClassMember>[ - new SourceFieldMember(fieldBuilder, ClassMemberKind.Setter) - ] - : const <ClassMember>[]; - - @override - // Coverage-ignore(suite): Not run. - void buildImplicitDefaultValue() { - _field.initializer = new NullLiteral()..parent = _field; - } - - @override - // Coverage-ignore(suite): Not run. - Initializer buildImplicitInitializer() { - return new FieldInitializer(_field, new NullLiteral())..isSynthetic = true; - } - - @override - // Coverage-ignore(suite): Not run. - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}) { - return new ShadowInvalidFieldInitializer(type, value, effect) - ..fileOffset = fileOffset; - } -} - -class SourceFieldMember extends BuilderClassMember { - @override - final SourceFieldBuilder memberBuilder; - - Covariance? _covariance; - - @override - final ClassMemberKind memberKind; - - SourceFieldMember(this.memberBuilder, this.memberKind); - - @override - // Coverage-ignore(suite): Not run. - void inferType(ClassMembersBuilder membersBuilder) { - memberBuilder._ensureType(membersBuilder); - } - - @override - // Coverage-ignore(suite): Not run. - void registerOverrideDependency(Set<ClassMember> overriddenMembers) { - memberBuilder.registerOverrideDependency(overriddenMembers); - } - - @override - Member getMember(ClassMembersBuilder membersBuilder) { - memberBuilder._ensureType(membersBuilder); - return memberBuilder.field; - } - - @override - // Coverage-ignore(suite): Not run. - Member? getTearOff(ClassMembersBuilder membersBuilder) { - // Ensure field type is computed. - getMember(membersBuilder); - return null; - } - - @override - // Coverage-ignore(suite): Not run. - Covariance getCovariance(ClassMembersBuilder membersBuilder) { - return _covariance ??= forSetter - ? new Covariance.fromMember(getMember(membersBuilder), - forSetter: forSetter) - : const Covariance.empty(); - } - - @override - // Coverage-ignore(suite): Not run. - bool get isSourceDeclaration => true; - - @override - bool get isSynthesized => memberBuilder.isSynthesized; - - @override - bool isSameDeclaration(ClassMember other) { - return other is SourceFieldMember && - // Coverage-ignore(suite): Not run. - memberBuilder == other.memberBuilder; - } -} - -// Coverage-ignore(suite): Not run. -abstract class AbstractLateFieldEncoding implements FieldEncoding { - final String name; - final int fileOffset; - final int fileEndOffset; - DartType? _type; - late final Field _field; - Field? _lateIsSetField; - late Procedure _lateGetter; - Procedure? _lateSetter; - - // If `true`, an isSet field is used even when the type of the field is - // not potentially nullable. - // - // This is used to force use isSet fields in mixed mode encoding since - // we cannot trust non-nullable fields to be initialized with non-null values. - final late_lowering.IsSetStrategy _isSetStrategy; - late_lowering.IsSetEncoding? _isSetEncoding; - - // If `true`, the is-set field was register before the type was known to be - // nullable or non-nullable. In this case we do not try to remove it from - // the generated AST to avoid inconsistency between the class hierarchy used - // during and after inference. - // - // This is also used to force use isSet fields in mixed mode encoding since - // we cannot trust non-nullable fields to be initialized with non-null values. - bool _forceIncludeIsSetField; - - AbstractLateFieldEncoding( - {required this.name, - required NameScheme nameScheme, - required Uri fileUri, - required int nameOffset, - required int endOffset, - required Reference? fieldReference, - required Reference? fieldGetterReference, - required Reference? fieldSetterReference, - required Reference? lateIsSetFieldReference, - required Reference? lateIsSetGetterReference, - required Reference? lateIsSetSetterReference, - required Reference? lateGetterReference, - required Reference? lateSetterReference, - required bool isCovariantByDeclaration, - required late_lowering.IsSetStrategy isSetStrategy}) - : fileOffset = nameOffset, - fileEndOffset = endOffset, - _isSetStrategy = isSetStrategy, - _forceIncludeIsSetField = - isSetStrategy == late_lowering.IsSetStrategy.forceUseIsSetField { - _field = new Field.mutable(dummyName, - fileUri: fileUri, - fieldReference: fieldReference, - getterReference: fieldGetterReference, - setterReference: fieldSetterReference) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset - ..isInternalImplementation = true; - nameScheme - .getFieldMemberName(FieldNameType.Field, name, isSynthesized: true) - .attachMember(_field); - switch (_isSetStrategy) { - case late_lowering.IsSetStrategy.useSentinelOrNull: - case late_lowering.IsSetStrategy.forceUseSentinel: - // [_lateIsSetField] is never needed. - break; - case late_lowering.IsSetStrategy.forceUseIsSetField: - case late_lowering.IsSetStrategy.useIsSetFieldOrNull: - _lateIsSetField = new Field.mutable(dummyName, - fileUri: fileUri, - fieldReference: lateIsSetFieldReference, - getterReference: lateIsSetGetterReference, - setterReference: lateIsSetSetterReference) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset - ..isInternalImplementation = true; - nameScheme - .getFieldMemberName(FieldNameType.IsSetField, name, - isSynthesized: true) - .attachMember(_lateIsSetField!); - break; - } - _lateGetter = new Procedure( - dummyName, - ProcedureKind.Getter, - new FunctionNode(null) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset, - fileUri: fileUri, - reference: lateGetterReference) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset; - nameScheme - .getFieldMemberName(FieldNameType.Getter, name, isSynthesized: true) - .attachMember(_lateGetter); - _lateSetter = _createSetter(fileUri, nameOffset, lateSetterReference, - isCovariantByDeclaration: isCovariantByDeclaration); - if (_lateSetter != null) { - nameScheme - .getFieldMemberName(FieldNameType.Setter, name, isSynthesized: true) - .attachMember(_lateSetter!); - } - } - - late_lowering.IsSetEncoding get isSetEncoding { - assert(_type != null, "Type has not been computed for field $name."); - return _isSetEncoding ??= - late_lowering.computeIsSetEncoding(_type!, _isSetStrategy); - } - - @override - void createBodies(CoreTypes coreTypes, Expression? initializer) { - assert(_type != null, "Type has not been computed for field $name."); - if (isSetEncoding == late_lowering.IsSetEncoding.useSentinel) { - _field.initializer = new StaticInvocation(coreTypes.createSentinelMethod, - new Arguments([], types: [_type!])..fileOffset = fileOffset) - ..fileOffset = fileOffset - ..parent = _field; - } else { - _field.initializer = new NullLiteral() - ..fileOffset = fileOffset - ..parent = _field; - } - if (_lateIsSetField != null) { - _lateIsSetField!.initializer = new BoolLiteral(false) - ..fileOffset = fileOffset - ..parent = _lateIsSetField; - } - _lateGetter.function.body = _createGetterBody(coreTypes, name, initializer) - ..parent = _lateGetter.function; - // The initializer is copied from [_field] to [_lateGetter] so we copy the - // transformer flags to reflect whether the getter contains super calls. - _lateGetter.transformerFlags = _field.transformerFlags; - - if (_lateSetter != null) { - _lateSetter!.function.body = _createSetterBody( - coreTypes, name, _lateSetter!.function.positionalParameters.first) - ..parent = _lateSetter!.function; - } - } - - @override - List<Initializer> createInitializer(int fileOffset, Expression value, - {required bool isSynthetic}) { - List<Initializer> initializers = <Initializer>[]; - if (_lateIsSetField != null) { - initializers.add(new FieldInitializer( - _lateIsSetField!, new BoolLiteral(true)..fileOffset = fileOffset) - ..fileOffset = fileOffset - ..isSynthetic = isSynthetic); - } - initializers.add(new FieldInitializer(_field, value) - ..fileOffset = fileOffset - ..isSynthetic = isSynthetic); - return initializers; - } - - /// Creates an [Expression] that reads [_field]. - /// - /// If [needsPromotion] is `true`, the field will be read through a `let` - /// expression that promotes the expression to [_type]. This is needed for a - /// sound encoding of fields with type parameter type of undetermined - /// nullability. - Expression _createFieldRead({bool needsPromotion = false}) { - assert(_type != null, "Type has not been computed for field $name."); - if (needsPromotion) { - VariableDeclaration variable = new VariableDeclaration.forValue( - _createFieldGet(_field), - type: _type!.withDeclaredNullability(Nullability.nullable)) - ..fileOffset = fileOffset; - return new Let( - variable, new VariableGet(variable, _type)..fileOffset = fileOffset); - } else { - return _createFieldGet(_field); - } - } - - /// Creates an [Expression] that reads [field]. - Expression _createFieldGet(Field field) { - if (field.isStatic) { - return new StaticGet(field)..fileOffset = fileOffset; - } else { - // No substitution needed for the result type, since any type parameters - // in there are also in scope at the access site. - return new InstanceGet(InstanceAccessKind.Instance, - new ThisExpression()..fileOffset = fileOffset, field.name, - interfaceTarget: field, resultType: field.type) - ..fileOffset = fileOffset; - } - } - - /// Creates an [Expression] that writes [value] to [field]. - Expression _createFieldSet(Field field, Expression value) { - if (field.isStatic) { - return new StaticSet(field, value)..fileOffset = fileOffset; - } else { - return new InstanceSet(InstanceAccessKind.Instance, - new ThisExpression()..fileOffset = fileOffset, field.name, value, - interfaceTarget: field) - ..fileOffset = fileOffset; - } - } - - Statement _createGetterBody( - CoreTypes coreTypes, String name, Expression? initializer); - - Procedure? _createSetter(Uri fileUri, int charOffset, Reference? reference, - {required bool isCovariantByDeclaration}) { - VariableDeclaration parameter = new VariableDeclaration("${name}#param") - ..isCovariantByDeclaration = isCovariantByDeclaration - ..fileOffset = fileOffset; - return new Procedure( - dummyName, - ProcedureKind.Setter, - new FunctionNode(null, - positionalParameters: [parameter], returnType: const VoidType()) - ..fileOffset = charOffset - ..fileEndOffset = fileEndOffset, - fileUri: fileUri, - reference: reference) - ..fileOffset = charOffset - ..fileEndOffset = fileEndOffset; - } - - Statement _createSetterBody( - CoreTypes coreTypes, String name, VariableDeclaration parameter); - - @override - DartType get type { - assert(_type != null, "Type has not been computed for field $name."); - return _type!; - } - - @override - void set type(DartType value) { - assert(_type == null || _type is InferredType, - "Type has already been computed for field $name."); - _type = value; - if (value is! InferredType) { - _field.type = value.withDeclaredNullability(Nullability.nullable); - _lateGetter.function.returnType = value; - if (_lateSetter != null) { - _lateSetter!.function.positionalParameters.single.type = value; - } - if (!_type!.isPotentiallyNullable && !_forceIncludeIsSetField) { - // We only need the is-set field if the field is potentially nullable. - // Otherwise we use `null` to signal that the field is uninitialized. - _lateIsSetField = null; - } - } - } - - @override - void setGenericCovariantImpl() { - if (_field.hasSetter) { - _field.isCovariantByClass = true; - } - _lateSetter?.function.positionalParameters.single.isCovariantByClass = true; - } - - @override - Field get field => _field; - - @override - Member get builtMember => _field; - - @override - Iterable<Annotatable> get annotatables { - List<Annotatable> list = [_lateGetter]; - if (_lateSetter != null) { - list.add(_lateSetter!); - } - return list; - } - - @override - Member get readTarget => _lateGetter; - - @override - Reference get readTargetReference => _lateGetter.reference; - - @override - Member? get writeTarget => _lateSetter; - - @override - Reference? get writeTargetReference => _lateSetter?.reference; - - @override - Iterable<Reference> get exportedReferenceMembers { - if (_lateSetter != null) { - return [_lateGetter.reference, _lateSetter!.reference]; - } - return [_lateGetter.reference]; - } - - @override - void build( - SourceLibraryBuilder libraryBuilder, SourceFieldBuilder fieldBuilder) { - bool isInstanceMember = !fieldBuilder.isStatic && !fieldBuilder.isTopLevel; - bool isExtensionMember = fieldBuilder.isExtensionMember; - bool isExtensionTypeMember = fieldBuilder.isExtensionTypeMember; - if (isExtensionMember) { - _field - ..isStatic = true - ..isExtensionMember = isExtensionMember; - isInstanceMember = false; - } else if (isExtensionTypeMember) { - _field - ..isStatic = fieldBuilder.isStatic - ..isExtensionTypeMember = true; - } else { - _field - ..isStatic = !isInstanceMember - ..isExtensionMember = false; - } - if (_lateIsSetField != null) { - _lateIsSetField! - ..isStatic = !isInstanceMember - ..isExtensionMember = isExtensionMember - ..isExtensionTypeMember = isExtensionTypeMember - ..type = libraryBuilder.loader - .createCoreType('bool', Nullability.nonNullable); - } - _lateGetter - ..isStatic = !isInstanceMember - ..isExtensionMember = isExtensionMember - ..isExtensionTypeMember = isExtensionTypeMember; - if (_lateSetter != null) { - _lateSetter! - ..isStatic = !isInstanceMember - ..isExtensionMember = isExtensionMember - ..isExtensionTypeMember = isExtensionTypeMember; - } - } - - @override - void registerMembers(SourceLibraryBuilder library, - SourceFieldBuilder fieldBuilder, BuildNodesCallback f) { - f( - member: _field, - kind: - fieldBuilder.isExtensionMember || fieldBuilder.isExtensionTypeMember - ? BuiltMemberKind.ExtensionField - : BuiltMemberKind.Field); - if (_lateIsSetField != null) { - _forceIncludeIsSetField = true; - f(member: _lateIsSetField!, kind: BuiltMemberKind.LateIsSetField); - } - f(member: _lateGetter, kind: BuiltMemberKind.LateGetter); - if (_lateSetter != null) { - f(member: _lateSetter!, kind: BuiltMemberKind.LateSetter); - } - } - - @override - List<ClassMember> getLocalMembers(SourceFieldBuilder fieldBuilder) { - List<ClassMember> list = <ClassMember>[ - new _SynthesizedFieldClassMember(fieldBuilder, field, field.name, - _SynthesizedFieldMemberKind.LateField, ClassMemberKind.Getter, - isInternalImplementation: true), - new _SynthesizedFieldClassMember( - fieldBuilder, - _lateGetter, - fieldBuilder.memberName, - _SynthesizedFieldMemberKind.LateGetterSetter, - ClassMemberKind.Getter, - isInternalImplementation: false) - ]; - if (_lateIsSetField != null) { - list.add(new _SynthesizedFieldClassMember( - fieldBuilder, - _lateIsSetField!, - _lateIsSetField!.name, - _SynthesizedFieldMemberKind.LateIsSet, - ClassMemberKind.Getter, - isInternalImplementation: true)); - } - return list; - } - - @override - List<ClassMember> getLocalSetters(SourceFieldBuilder fieldBuilder) { - List<ClassMember> list = <ClassMember>[ - new _SynthesizedFieldClassMember(fieldBuilder, field, field.name, - _SynthesizedFieldMemberKind.LateField, ClassMemberKind.Setter, - isInternalImplementation: true), - ]; - if (_lateIsSetField != null) { - list.add(new _SynthesizedFieldClassMember( - fieldBuilder, - _lateIsSetField!, - _lateIsSetField!.name, - _SynthesizedFieldMemberKind.LateIsSet, - ClassMemberKind.Setter, - isInternalImplementation: true)); - } - if (_lateSetter != null) { - list.add(new _SynthesizedFieldClassMember( - fieldBuilder, - _lateSetter!, - fieldBuilder.memberName, - _SynthesizedFieldMemberKind.LateGetterSetter, - ClassMemberKind.Setter, - isInternalImplementation: false)); - } - return list; - } -} - -mixin NonFinalLate on AbstractLateFieldEncoding { - @override - // Coverage-ignore(suite): Not run. - Statement _createSetterBody( - CoreTypes coreTypes, String name, VariableDeclaration parameter) { - assert(_type != null, "Type has not been computed for field $name."); - return late_lowering.createSetterBody( - coreTypes, fileOffset, name, parameter, _type!, - shouldReturnValue: false, - createVariableWrite: (Expression value) => - _createFieldSet(_field, value), - createIsSetWrite: (Expression value) => - _createFieldSet(_lateIsSetField!, value), - isSetEncoding: isSetEncoding); - } -} - -mixin LateWithoutInitializer on AbstractLateFieldEncoding { - @override - // Coverage-ignore(suite): Not run. - Statement _createGetterBody( - CoreTypes coreTypes, String name, Expression? initializer) { - assert(_type != null, "Type has not been computed for field $name."); - return late_lowering.createGetterBodyWithoutInitializer( - coreTypes, fileOffset, name, type, - createVariableRead: _createFieldRead, - createIsSetRead: () => _createFieldGet(_lateIsSetField!), - isSetEncoding: isSetEncoding, - forField: true); - } - - @override - void buildImplicitDefaultValue() { - throw new UnsupportedError("$runtimeType.buildImplicitDefaultValue"); - } - - @override - Initializer buildImplicitInitializer() { - throw new UnsupportedError("$runtimeType.buildImplicitInitializer"); - } - - @override - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}) { - throw new UnsupportedError("$runtimeType.buildDuplicatedInitializer"); - } -} - -// Coverage-ignore(suite): Not run. -class LateFieldWithoutInitializerEncoding extends AbstractLateFieldEncoding - with NonFinalLate, LateWithoutInitializer { - LateFieldWithoutInitializerEncoding( - {required super.name, - required super.nameScheme, - required super.fileUri, - required super.nameOffset, - required super.endOffset, - required super.fieldReference, - required super.fieldGetterReference, - required super.fieldSetterReference, - required super.lateIsSetFieldReference, - required super.lateIsSetGetterReference, - required super.lateIsSetSetterReference, - required super.lateGetterReference, - required super.lateSetterReference, - required super.isCovariantByDeclaration, - required super.isSetStrategy}); -} - -// Coverage-ignore(suite): Not run. -class LateFieldWithInitializerEncoding extends AbstractLateFieldEncoding - with NonFinalLate { - LateFieldWithInitializerEncoding( - {required super.name, - required super.nameScheme, - required super.fileUri, - required super.nameOffset, - required super.endOffset, - required super.fieldReference, - required super.fieldGetterReference, - required super.fieldSetterReference, - required super.lateIsSetFieldReference, - required super.lateIsSetGetterReference, - required super.lateIsSetSetterReference, - required super.lateGetterReference, - required super.lateSetterReference, - required super.isCovariantByDeclaration, - required super.isSetStrategy}); - - @override - Statement _createGetterBody( - CoreTypes coreTypes, String name, Expression? initializer) { - assert(_type != null, "Type has not been computed for field $name."); - return late_lowering.createGetterWithInitializer( - coreTypes, fileOffset, name, _type!, initializer!, - createVariableRead: _createFieldRead, - createVariableWrite: (Expression value) => - _createFieldSet(_field, value), - createIsSetRead: () => _createFieldGet(_lateIsSetField!), - createIsSetWrite: (Expression value) => - _createFieldSet(_lateIsSetField!, value), - isSetEncoding: isSetEncoding); - } - - @override - void buildImplicitDefaultValue() { - throw new UnsupportedError("$runtimeType.buildImplicitDefaultValue"); - } - - @override - Initializer buildImplicitInitializer() { - throw new UnsupportedError("$runtimeType.buildImplicitInitializer"); - } - - @override - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}) { - throw new UnsupportedError("$runtimeType.buildDuplicatedInitializer"); - } -} - -// Coverage-ignore(suite): Not run. -class LateFinalFieldWithoutInitializerEncoding extends AbstractLateFieldEncoding - with LateWithoutInitializer { - LateFinalFieldWithoutInitializerEncoding( - {required super.name, - required super.nameScheme, - required super.fileUri, - required super.nameOffset, - required super.endOffset, - required super.fieldReference, - required super.fieldGetterReference, - required super.fieldSetterReference, - required super.lateIsSetFieldReference, - required super.lateIsSetGetterReference, - required super.lateIsSetSetterReference, - required super.lateGetterReference, - required super.lateSetterReference, - required super.isCovariantByDeclaration, - required super.isSetStrategy}); - - @override - Statement _createSetterBody( - CoreTypes coreTypes, String name, VariableDeclaration parameter) { - assert(_type != null, "Type has not been computed for field $name."); - return late_lowering.createSetterBodyFinal( - coreTypes, fileOffset, name, parameter, type, - shouldReturnValue: false, - createVariableRead: () => _createFieldGet(_field), - createVariableWrite: (Expression value) => - _createFieldSet(_field, value), - createIsSetRead: () => _createFieldGet(_lateIsSetField!), - createIsSetWrite: (Expression value) => - _createFieldSet(_lateIsSetField!, value), - isSetEncoding: isSetEncoding, - forField: true); - } -} - -// Coverage-ignore(suite): Not run. -class LateFinalFieldWithInitializerEncoding extends AbstractLateFieldEncoding { - LateFinalFieldWithInitializerEncoding( - {required super.name, - required super.nameScheme, - required super.fileUri, - required super.nameOffset, - required super.endOffset, - required super.fieldReference, - required super.fieldGetterReference, - required super.fieldSetterReference, - required super.lateIsSetFieldReference, - required super.lateIsSetGetterReference, - required super.lateIsSetSetterReference, - required super.lateGetterReference, - required super.lateSetterReference, - required super.isCovariantByDeclaration, - required super.isSetStrategy}); - - @override - Statement _createGetterBody( - CoreTypes coreTypes, String name, Expression? initializer) { - assert(_type != null, "Type has not been computed for field $name."); - return late_lowering.createGetterWithInitializerWithRecheck( - coreTypes, fileOffset, name, _type!, initializer!, - createVariableRead: _createFieldRead, - createVariableWrite: (Expression value) => - _createFieldSet(_field, value), - createIsSetRead: () => _createFieldGet(_lateIsSetField!), - createIsSetWrite: (Expression value) => - _createFieldSet(_lateIsSetField!, value), - isSetEncoding: isSetEncoding, - forField: true); - } - - @override - Procedure? _createSetter(Uri fileUri, int charOffset, Reference? reference, - {required bool isCovariantByDeclaration}) => - null; - - @override - Statement _createSetterBody( - CoreTypes coreTypes, String name, VariableDeclaration parameter) => - throw new UnsupportedError( - '$runtimeType._createSetterBody is not supported.'); - - @override - void buildImplicitDefaultValue() { - throw new UnsupportedError("$runtimeType.buildImplicitDefaultValue"); - } - - @override - Initializer buildImplicitInitializer() { - throw new UnsupportedError("$runtimeType.buildImplicitInitializer"); - } - - @override - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}) { - throw new UnsupportedError("$runtimeType.buildDuplicatedInitializer"); - } -} - -// Coverage-ignore(suite): Not run. -class _SynthesizedFieldClassMember implements ClassMember { - final SourceFieldBuilder fieldBuilder; - final _SynthesizedFieldMemberKind _kind; - - final Member _member; - - final Name _name; - - Covariance? _covariance; - - @override - final bool isInternalImplementation; - - @override - final ClassMemberKind memberKind; - - _SynthesizedFieldClassMember( - this.fieldBuilder, this._member, this._name, this._kind, this.memberKind, - {required this.isInternalImplementation}); - - @override - Member getMember(ClassMembersBuilder membersBuilder) { - fieldBuilder._ensureType(membersBuilder); - return _member; - } - - @override - Member? getTearOff(ClassMembersBuilder membersBuilder) { - // Ensure field type is computed. - getMember(membersBuilder); - return null; - } - - @override - Covariance getCovariance(ClassMembersBuilder membersBuilder) { - return _covariance ??= new Covariance.fromMember(getMember(membersBuilder), - forSetter: forSetter); - } - - @override - MemberResult getMemberResult(ClassMembersBuilder membersBuilder) { - return new TypeDeclarationInstanceMemberResult( - getMember(membersBuilder), memberKind, - isDeclaredAsField: true); - } - - @override - void inferType(ClassMembersBuilder membersBuilder) { - fieldBuilder._ensureType(membersBuilder); - } - - @override - void registerOverrideDependency(Set<ClassMember> overriddenMembers) { - fieldBuilder.registerOverrideDependency(overriddenMembers); - } - - @override - bool get isSourceDeclaration => true; - - @override - bool get forSetter => memberKind == ClassMemberKind.Setter; - - @override - bool get isProperty => memberKind != ClassMemberKind.Method; - - @override - DeclarationBuilder get declarationBuilder => fieldBuilder.declarationBuilder!; - - @override - bool isObjectMember(ClassBuilder objectClass) { - return declarationBuilder == objectClass; - } - - @override - bool get isDuplicate => fieldBuilder.isDuplicate; - - @override - bool get isStatic => fieldBuilder.isStatic; - - @override - bool get isField => _member is Field; - - @override - bool get isSetter { - Member procedure = _member; - return procedure is Procedure && procedure.kind == ProcedureKind.Setter; - } - - @override - bool get isGetter { - Member procedure = _member; - return procedure is Procedure && procedure.kind == ProcedureKind.Getter; - } - - @override - Name get name => _name; - - @override - String get fullName { - String suffix = isSetter ? "=" : ""; - String className = declarationBuilder.fullNameForErrors; - return "${className}.${fullNameForErrors}$suffix"; - } - - @override - String get fullNameForErrors => fieldBuilder.fullNameForErrors; - - @override - Uri get fileUri => fieldBuilder.fileUri; - - @override - int get charOffset => fieldBuilder.fileOffset; - - @override - bool get isAbstract => _member.isAbstract; - - @override - bool get isSynthesized => false; - - @override - bool get hasDeclarations => false; - - @override - List<ClassMember> get declarations => - throw new UnsupportedError("$runtimeType.declarations"); - - @override - ClassMember get interfaceMember => this; - - @override - bool isSameDeclaration(ClassMember other) { - if (identical(this, other)) return true; - return other is _SynthesizedFieldClassMember && - fieldBuilder == other.fieldBuilder && - _kind == other._kind; - } - - @override - bool get isNoSuchMethodForwarder => false; - - @override - String toString() => '_SynthesizedFieldClassMember(' - '$fieldBuilder,$_member,$_kind,forSetter=${forSetter})'; - - @override - bool get isExtensionTypeMember => fieldBuilder.isExtensionTypeMember; -} - -// Coverage-ignore(suite): Not run. -class AbstractOrExternalFieldEncoding implements FieldEncoding { - final SourceFieldBuilder _fieldBuilder; - final bool isAbstract; - final bool isExternal; - final bool _isExtensionInstanceMember; - final bool _isExtensionTypeInstanceMember; - - late Procedure _getter; - Procedure? _setter; - DartType? _type; - - AbstractOrExternalFieldEncoding( - this._fieldBuilder, - String name, - NameScheme nameScheme, - Uri fileUri, - int nameOffset, - int endOffset, - Reference? getterReference, - Reference? setterReference, - {required this.isAbstract, - required this.isExternal, - required bool isFinal, - required bool isCovariantByDeclaration, - bool isForcedExtension = false}) - : _isExtensionInstanceMember = (isExternal || isForcedExtension) && - nameScheme.isExtensionMember && - nameScheme.isInstanceMember, - _isExtensionTypeInstanceMember = (isExternal || isForcedExtension) && - nameScheme.isExtensionTypeMember && - nameScheme.isInstanceMember { - if (_isExtensionInstanceMember || _isExtensionTypeInstanceMember) { - _getter = new Procedure( - dummyName, - ProcedureKind.Method, - new FunctionNode(null, positionalParameters: [ - new VariableDeclaration(syntheticThisName) - ..fileOffset = nameOffset - ..isLowered = true - ]), - fileUri: fileUri, - reference: getterReference) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset; - nameScheme - .getProcedureMemberName(ProcedureKind.Getter, name) - .attachMember(_getter); - if (!isFinal) { - VariableDeclaration parameter = - new VariableDeclaration("#externalFieldValue", isSynthesized: true) - ..isCovariantByDeclaration = isCovariantByDeclaration - ..fileOffset = nameOffset; - _setter = new Procedure( - dummyName, - ProcedureKind.Method, - new FunctionNode(null, - positionalParameters: [ - new VariableDeclaration(syntheticThisName) - ..fileOffset = nameOffset - ..isLowered = true, - parameter - ], - returnType: const VoidType()) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset, - fileUri: fileUri, - reference: setterReference) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset; - nameScheme - .getProcedureMemberName(ProcedureKind.Setter, name) - .attachMember(_setter!); - } - } else { - _getter = new Procedure( - dummyName, ProcedureKind.Getter, new FunctionNode(null), - fileUri: fileUri, reference: getterReference) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset; - nameScheme - .getFieldMemberName(FieldNameType.Getter, name, isSynthesized: true) - .attachMember(_getter); - if (!isFinal) { - VariableDeclaration parameter = - new VariableDeclaration("#externalFieldValue", isSynthesized: true) - ..isCovariantByDeclaration = isCovariantByDeclaration - ..fileOffset = nameOffset; - _setter = new Procedure( - dummyName, - ProcedureKind.Setter, - new FunctionNode(null, - positionalParameters: [parameter], returnType: const VoidType()) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset, - fileUri: fileUri, - reference: setterReference) - ..fileOffset = nameOffset - ..fileEndOffset = endOffset; - nameScheme - .getFieldMemberName(FieldNameType.Setter, name, isSynthesized: true) - .attachMember(_setter!); - } - } - } - - @override - DartType get type { - assert(_type != null, - "Type has not been computed for field ${_fieldBuilder.name}."); - return _type!; - } - - @override - void set type(DartType value) { - assert(_type == null || _type is InferredType, - "Type has already been computed for field ${_fieldBuilder.name}."); - _type = value; - if (value is! InferredType) { - if (_isExtensionInstanceMember || _isExtensionTypeInstanceMember) { - DartType thisParameterType; - List<TypeParameter> typeParameters; - if (_isExtensionInstanceMember) { - SourceExtensionBuilder extensionBuilder = - _fieldBuilder.parent as SourceExtensionBuilder; - thisParameterType = extensionBuilder.extension.onType; - typeParameters = extensionBuilder.extension.typeParameters; - } else { - SourceExtensionTypeDeclarationBuilder - extensionTypeDeclarationBuilder = - _fieldBuilder.parent as SourceExtensionTypeDeclarationBuilder; - thisParameterType = extensionTypeDeclarationBuilder - .extensionTypeDeclaration.declaredRepresentationType; - typeParameters = extensionTypeDeclarationBuilder - .extensionTypeDeclaration.typeParameters; - } - if (typeParameters.isNotEmpty) { - FreshTypeParameters getterTypeParameters = - getFreshTypeParameters(typeParameters); - _getter.function.positionalParameters.first.type = - getterTypeParameters.substitute(thisParameterType); - _getter.function.returnType = getterTypeParameters.substitute(value); - _getter.function.typeParameters = - getterTypeParameters.freshTypeParameters; - setParents( - getterTypeParameters.freshTypeParameters, _getter.function); - - Procedure? setter = _setter; - if (setter != null) { - FreshTypeParameters setterTypeParameters = - getFreshTypeParameters(typeParameters); - setter.function.positionalParameters.first.type = - setterTypeParameters.substitute(thisParameterType); - setter.function.positionalParameters[1].type = - setterTypeParameters.substitute(value); - setter.function.typeParameters = - setterTypeParameters.freshTypeParameters; - setParents( - setterTypeParameters.freshTypeParameters, setter.function); - } - } else { - _getter.function.returnType = value; - _setter?.function.positionalParameters[1].type = value; - _getter.function.positionalParameters.first.type = thisParameterType; - _setter?.function.positionalParameters.first.type = thisParameterType; - } - } else { - _getter.function.returnType = value; - Procedure? setter = _setter; - if (setter != null) { - if (setter.kind == ProcedureKind.Method) { - setter.function.positionalParameters[1].type = value; - } else { - setter.function.positionalParameters.first.type = value; - } - } - } - } - } - - @override - void createBodies(CoreTypes coreTypes, Expression? initializer) { - // TODO(johnniwinther): Enable this assert. - //assert(initializer != null); - } - - @override - List<Initializer> createInitializer(int fileOffset, Expression value, - {required bool isSynthetic}) { - throw new UnsupportedError('ExternalFieldEncoding.createInitializer'); - } - - @override - void build( - SourceLibraryBuilder libraryBuilder, SourceFieldBuilder fieldBuilder) { - bool isExtensionMember = fieldBuilder.isExtensionMember; - bool isExtensionTypeMember = fieldBuilder.isExtensionTypeMember; - bool isInstanceMember = !isExtensionMember && - !isExtensionTypeMember && - !fieldBuilder.isStatic && - !fieldBuilder.isTopLevel; - _getter..isConst = fieldBuilder.isConst; - _getter - ..isStatic = !isInstanceMember - ..isExtensionMember = isExtensionMember - ..isExtensionTypeMember = isExtensionTypeMember - ..isAbstract = isAbstract && !isExternal - ..isExternal = isExternal; - - if (_setter != null) { - _setter! - ..isStatic = !isInstanceMember - ..isExtensionMember = isExtensionMember - ..isExtensionTypeMember = isExtensionTypeMember - ..isAbstract = isAbstract && !isExternal - ..isExternal = isExternal; - } - } - - @override - void registerMembers(SourceLibraryBuilder library, - SourceFieldBuilder fieldBuilder, BuildNodesCallback f) { - BuiltMemberKind getterMemberKind; - if (fieldBuilder.isExtensionMember) { - getterMemberKind = BuiltMemberKind.ExtensionGetter; - } else if (fieldBuilder.isExtensionTypeMember) { - getterMemberKind = BuiltMemberKind.ExtensionTypeGetter; - } else { - getterMemberKind = BuiltMemberKind.Method; - } - f(member: _getter, kind: getterMemberKind); - if (_setter != null) { - BuiltMemberKind setterMemberKind; - if (fieldBuilder.isExtensionMember) { - setterMemberKind = BuiltMemberKind.ExtensionSetter; - } else if (fieldBuilder.isExtensionTypeMember) { - setterMemberKind = BuiltMemberKind.ExtensionTypeSetter; - } else { - setterMemberKind = BuiltMemberKind.Method; - } - f(member: _setter!, kind: setterMemberKind); - } - } - - @override - void setGenericCovariantImpl() { - _setter!.function.positionalParameters.first.isCovariantByClass = true; - } - - @override - Field get field { - throw new UnsupportedError("ExternalFieldEncoding.field"); - } - - @override - Member get builtMember => _getter; - - @override - Iterable<Annotatable> get annotatables { - List<Annotatable> list = [_getter]; - if (_setter != null) { - list.add(_setter!); - } - return list; - } - - @override - Member get readTarget => _getter; - - @override - Reference get readTargetReference => _getter.reference; - - @override - Member? get writeTarget => _setter; - - @override - Reference? get writeTargetReference => _setter?.reference; - - @override - Iterable<Reference> get exportedReferenceMembers { - if (_setter != null) { - return [_getter.reference, _setter!.reference]; - } - return [_getter.reference]; - } - - @override - List<ClassMember> getLocalMembers(SourceFieldBuilder fieldBuilder) => - <ClassMember>[ - new _SynthesizedFieldClassMember( - fieldBuilder, - _getter, - fieldBuilder.memberName, - _SynthesizedFieldMemberKind.AbstractExternalGetterSetter, - ClassMemberKind.Getter, - isInternalImplementation: false) - ]; - - @override - List<ClassMember> getLocalSetters(SourceFieldBuilder fieldBuilder) => - _setter != null - ? <ClassMember>[ - new _SynthesizedFieldClassMember( - fieldBuilder, - _setter!, - fieldBuilder.memberName, - _SynthesizedFieldMemberKind.AbstractExternalGetterSetter, - ClassMemberKind.Setter, - isInternalImplementation: false) - ] - : const <ClassMember>[]; - - @override - void buildImplicitDefaultValue() { - throw new UnsupportedError("$runtimeType.buildImplicitDefaultValue"); - } - - @override - Initializer buildImplicitInitializer() { - throw new UnsupportedError("$runtimeType.buildImplicitInitializer"); - } - - @override - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}) { - return new ShadowInvalidFieldInitializer(type, value, effect) - ..fileOffset = fileOffset; - } -} - -// Coverage-ignore(suite): Not run. -/// The encoding of an extension type declaration representation field. -class RepresentationFieldEncoding implements FieldEncoding { - final SourceFieldBuilder _fieldBuilder; - - late Procedure _getter; - DartType? _type; - - RepresentationFieldEncoding( - this._fieldBuilder, - String name, - NameScheme nameScheme, - Uri fileUri, - int charOffset, - int charEndOffset, - Reference? getterReference) { - _getter = new Procedure( - dummyName, ProcedureKind.Getter, new FunctionNode(null), - fileUri: fileUri, reference: getterReference) - ..stubKind = ProcedureStubKind.RepresentationField - ..fileOffset = charOffset - ..fileEndOffset = charEndOffset; - nameScheme - .getFieldMemberName(FieldNameType.RepresentationField, name, - isSynthesized: true) - .attachMember(_getter); - } - - @override - DartType get type { - assert(_type != null, - "Type has not been computed for field ${_fieldBuilder.name}."); - return _type!; - } - - @override - void set type(DartType value) { - assert(_type == null || _type is InferredType, - "Type has already been computed for field ${_fieldBuilder.name}."); - _type = value; - if (value is! InferredType) { - _getter.function.returnType = value; - } - } - - @override - void createBodies(CoreTypes coreTypes, Expression? initializer) { - // TODO(johnniwinther): Enable this assert. - //assert(initializer != null); - } - - @override - List<Initializer> createInitializer(int fileOffset, Expression value, - {required bool isSynthetic}) { - return <Initializer>[ - new ExtensionTypeRepresentationFieldInitializer(_getter, value) - ]; - } - - @override - void build( - SourceLibraryBuilder libraryBuilder, SourceFieldBuilder fieldBuilder) { - _getter..isConst = fieldBuilder.isConst; - _getter - ..isStatic = false - ..isExtensionMember = false - ..isExtensionTypeMember = true - ..isAbstract = true - ..isExternal = false; - } - - @override - void registerMembers(SourceLibraryBuilder library, - SourceFieldBuilder fieldBuilder, BuildNodesCallback f) { - f(member: _getter, kind: BuiltMemberKind.ExtensionTypeRepresentationField); - } - - @override - void setGenericCovariantImpl() { - throw new UnsupportedError("$runtimeType.setGenericCovariantImpl"); - } - - @override - Field get field { - throw new UnsupportedError("$runtimeType.field"); - } - - @override - Member get builtMember => _getter; - - @override - Iterable<Annotatable> get annotatables => [_getter]; - - @override - Member get readTarget => _getter; - - @override - Reference get readTargetReference => _getter.reference; - - @override - Member? get writeTarget => null; - - @override - Reference? get writeTargetReference => null; - - @override - Iterable<Reference> get exportedReferenceMembers => [_getter.reference]; - - @override - List<ClassMember> getLocalMembers(SourceFieldBuilder fieldBuilder) => - <ClassMember>[ - new _SynthesizedFieldClassMember( - fieldBuilder, - _getter, - fieldBuilder.memberName, - _SynthesizedFieldMemberKind.RepresentationField, - ClassMemberKind.Getter, - isInternalImplementation: false) - ]; - - @override - List<ClassMember> getLocalSetters(SourceFieldBuilder fieldBuilder) => - const <ClassMember>[]; - - @override - void buildImplicitDefaultValue() { - // Not needed. - } - - @override - Initializer buildImplicitInitializer() { - return new ExtensionTypeRepresentationFieldInitializer( - _getter, new NullLiteral()); - } - - @override - Initializer buildErroneousInitializer(Expression effect, Expression value, - {required int fileOffset}) { - return new ShadowInvalidFieldInitializer(type, value, effect) - ..fileOffset = fileOffset; - } -} - -enum _SynthesizedFieldMemberKind { - /// A `isSet` field used for late lowering. - LateIsSet, - - /// A field used for the value of a late lowered field. - LateField, - - /// A getter or setter used for late lowering. - LateGetterSetter, - - /// A getter or setter used for abstract or external fields. - AbstractExternalGetterSetter, - - /// A getter for an extension type declaration representation field. - RepresentationField, -}
diff --git a/pkg/front_end/lib/src/source/source_function_builder.dart b/pkg/front_end/lib/src/source/source_function_builder.dart index 122ad35..9448c14 100644 --- a/pkg/front_end/lib/src/source/source_function_builder.dart +++ b/pkg/front_end/lib/src/source/source_function_builder.dart
@@ -423,6 +423,8 @@ void buildOutlineExpressions(ClassHierarchy classHierarchy, List<DelayedDefaultValueCloner> delayedDefaultValueCloners) { if (!hasBuiltOutlineExpressions) { + inferFormals(formals, classHierarchy); + DeclarationBuilder? classOrExtensionBuilder = isClassMember || isExtensionMember || isExtensionTypeMember ? parent as DeclarationBuilder @@ -572,3 +574,16 @@ origin.fileUri!, origin.fileOffset, noLength) ]); } + +/// Ensures the type of each of the [formals] is inferred. +void inferFormals( + List<FormalParameterBuilder>? formals, ClassHierarchy classHierarchy) { + if (formals != null) { + for (FormalParameterBuilder formal in formals) { + TypeBuilder formalType = formal.type; + if (formalType is InferableTypeBuilder) { + formalType.inferType(classHierarchy); + } + } + } +}
diff --git a/pkg/front_end/lib/src/source/source_property_builder.dart b/pkg/front_end/lib/src/source/source_property_builder.dart index 66c0f85..3a5c3b9 100644 --- a/pkg/front_end/lib/src/source/source_property_builder.dart +++ b/pkg/front_end/lib/src/source/source_property_builder.dart
@@ -49,9 +49,6 @@ @override final DeclarationBuilder? declarationBuilder; - @override - final bool isStatic; - final NameScheme _nameScheme; /// The declarations that introduces this property. Subsequent property of the @@ -90,7 +87,6 @@ required this.name, required this.libraryBuilder, required this.declarationBuilder, - required this.isStatic, required NameScheme nameScheme, required GetterFragment fragment, required PropertyReferences references}) @@ -106,7 +102,6 @@ required this.name, required this.libraryBuilder, required this.declarationBuilder, - required this.isStatic, required NameScheme nameScheme, required SetterFragment fragment, required PropertyReferences references}) @@ -122,13 +117,12 @@ required this.name, required this.libraryBuilder, required this.declarationBuilder, - required this.isStatic, required NameScheme nameScheme, - required FieldDeclaration fragment, + required FieldDeclaration fieldDeclaration, required Modifiers modifiers, required PropertyReferences references}) : _nameScheme = nameScheme, - _introductoryField = fragment, + _introductoryField = fieldDeclaration, _modifiers = modifiers, _references = references, _memberName = nameScheme.getDeclaredName(name); @@ -140,6 +134,9 @@ bool get isAugmentation => _modifiers.isAugment; @override + bool get isStatic => _modifiers.isStatic; + + @override bool get isExternal => _modifiers.isExternal; @override @@ -671,55 +668,55 @@ return setterType; } - @override DartType get fieldType { return _introductoryField!.fieldType; } - @override - // Coverage-ignore(suite): Not run. - void set fieldType(DartType value) { - _introductoryField!.fieldType = value; - } - - @override + /// Creates the [Initializer] for the invalid initialization of this field. + /// + /// This is only used for instance fields. Initializer buildErroneousInitializer(Expression effect, Expression value, {required int fileOffset}) { return _introductoryField! .buildErroneousInitializer(effect, value, fileOffset: fileOffset); } - @override + /// Creates the AST node for this field as the default initializer. + /// + /// This is only used for instance fields. void buildImplicitDefaultValue() { _introductoryField!.buildImplicitDefaultValue(); } - @override + /// Create the [Initializer] for the implicit initialization of this field + /// in a constructor. + /// + /// This is only used for instance fields. Initializer buildImplicitInitializer() { return _introductoryField!.buildImplicitInitializer(); } - @override + /// Builds the [Initializer]s for each field used to encode this field + /// using the [fileOffset] for the created nodes and [value] as the initial + /// field value. + /// + /// This is only used for instance fields. List<Initializer> buildInitializer(int fileOffset, Expression value, {required bool isSynthetic}) { return _introductoryField! .buildInitializer(fileOffset, value, isSynthetic: isSynthetic); } - @override bool get hasInitializer => _introductoryField!.hasInitializer; - @override bool get isExtensionTypeDeclaredInstanceField => _introductoryField!.isExtensionTypeDeclaredInstanceField; @override bool get isFinal => _introductoryField!.isFinal; - @override bool get isLate => _introductoryField!.isLate; - @override DartType inferType(ClassHierarchyBase hierarchy) { return _introductoryField!.inferType(hierarchy); }
diff --git a/pkg/front_end/lib/src/source/type_parameter_scope_builder.dart b/pkg/front_end/lib/src/source/type_parameter_scope_builder.dart index 5f992b4..4ebfce4 100644 --- a/pkg/front_end/lib/src/source/type_parameter_scope_builder.dart +++ b/pkg/front_end/lib/src/source/type_parameter_scope_builder.dart
@@ -1514,9 +1514,8 @@ name: name, libraryBuilder: enclosingLibraryBuilder, declarationBuilder: declarationBuilder, - isStatic: fragment.modifiers.isStatic, nameScheme: nameScheme, - fragment: fragment, + fieldDeclaration: fragment, modifiers: fragment.modifiers, references: references); fragment.builder = propertyBuilder; @@ -1565,7 +1564,6 @@ name: name, libraryBuilder: enclosingLibraryBuilder, declarationBuilder: declarationBuilder, - isStatic: fragment.modifiers.isStatic, fragment: fragment, nameScheme: nameScheme, references: references); @@ -1615,7 +1613,6 @@ name: name, libraryBuilder: enclosingLibraryBuilder, declarationBuilder: declarationBuilder, - isStatic: fragment.modifiers.isStatic, fragment: fragment, nameScheme: nameScheme, references: references); @@ -2018,9 +2015,8 @@ name: name, libraryBuilder: enclosingLibraryBuilder, declarationBuilder: declarationBuilder, - isStatic: true, nameScheme: nameScheme, - fragment: fragment, + fieldDeclaration: fragment, modifiers: Modifiers.Const | Modifiers.Static | Modifiers.HasInitializer,
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 dea75bb..8dfb41e 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 @@ class InferenceVisitorImpl extends InferenceVisitorBase with - TypeAnalyzer< - DartType, - TreeNode, - Statement, - Expression, - VariableDeclaration, - Pattern, - InvalidExpression, - StructuralParameter, - TypeDeclarationType, - TypeDeclaration>, - NullShortingMixin<NullAwareGuard, Expression, SharedTypeView<DartType>>, + TypeAnalyzer<TreeNode, Statement, Expression, VariableDeclaration, + Pattern, InvalidExpression, TypeDeclarationType, TypeDeclaration>, + NullShortingMixin<NullAwareGuard, Expression, SharedTypeView>, StackChecker implements ExpressionVisitor1<ExpressionInferenceResult, DartType>, StatementVisitor<StatementInferenceResult>, InitializerVisitor<InitializerInferenceResult>, - PatternVisitor1<PatternResult<DartType>, SharedMatchContext>, + PatternVisitor1<PatternResult, SharedMatchContext>, InferenceVisitor { /// Debug-only: if `true`, manipulations of [_rewriteStack] performed by /// [popRewrite] and [pushRewrite] will be printed. @@ -272,7 +263,7 @@ @override void handleNullShortingStep( - NullAwareGuard guard, SharedTypeView<DartType> inferredType) { + NullAwareGuard guard, SharedTypeView inferredType) { pushRewrite(guard.createExpression( inferredType.unwrapTypeView(), popRewrite() as Expression)); } @@ -1028,8 +1019,7 @@ if (nullAwareGuard != null) { pushRewrite(replacement); - SharedTypeView<DartType> 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 @@ int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternForInResult<DartType, InvalidExpression> result = - analyzePatternForIn( - node: node, - hasAwait: isAsync, - pattern: patternVariableDeclaration.pattern, - expression: iterable, - dispatchBody: () {}); + PatternForInResult<InvalidExpression> 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 @@ int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - IfCaseStatementResult<DartType, InvalidExpression> analysisResult = + IfCaseStatementResult<InvalidExpression> analysisResult = analyzeIfCaseStatement(node, node.expression, node.patternGuard.pattern, node.patternGuard.guard, node.then, node.otherwise, { for (VariableDeclaration variable @@ -2494,7 +2483,7 @@ inferredTypeArgument: inferredTypeArgument, inferredSpreadTypes: inferredSpreadTypes, inferredConditionTypes: inferredConditionTypes); - IfCaseStatementResult<DartType, InvalidExpression> analysisResult = + IfCaseStatementResult<InvalidExpression> analysisResult = analyzeIfCaseElement( node: element, expression: element.expression, @@ -2583,7 +2572,7 @@ PatternVariableDeclaration patternVariableDeclaration = element.patternVariableDeclaration; - PatternVariableDeclarationAnalysisResult<DartType> analysisResult = + PatternVariableDeclarationAnalysisResult analysisResult = analyzePatternVariableDeclaration( patternVariableDeclaration, patternVariableDeclaration.pattern, @@ -4773,7 +4762,7 @@ offsets: offsets, inferredSpreadTypes: inferredSpreadTypes, inferredConditionTypes: inferredConditionTypes); - IfCaseStatementResult<DartType, InvalidExpression> analysisResult = + IfCaseStatementResult<InvalidExpression> analysisResult = analyzeIfCaseElement( node: entry, expression: entry.expression, @@ -4876,7 +4865,7 @@ PatternVariableDeclaration patternVariableDeclaration = entry.patternVariableDeclaration; - PatternVariableDeclarationAnalysisResult<DartType> analysisResult = + PatternVariableDeclarationAnalysisResult analysisResult = analyzePatternVariableDeclaration( patternVariableDeclaration, patternVariableDeclaration.pattern, @@ -6289,8 +6278,8 @@ VariableDeclaration? indexVariable; Expression readIndex = indexResult.expression; - Map<SharedTypeView<DartType>, NonPromotionReason> Function() - whyNotPromotedIndex = flowAnalysis.whyNotPromoted(readIndex); + Map<SharedTypeView, NonPromotionReason> Function() whyNotPromotedIndex = + flowAnalysis.whyNotPromoted(readIndex); Expression writeIndex; if (isPureExpression(readIndex)) { writeIndex = clonePureExpression(readIndex); @@ -6763,7 +6752,7 @@ ExpressionInferenceResult _computeEqualsExpression( int fileOffset, Expression left, DartType leftType, Expression right, {required bool isNot}) { - ExpressionInfo<SharedTypeView<DartType>>? equalityInfo = + ExpressionInfo<SharedTypeView>? equalityInfo = flowAnalysis.equalityOperand_end(left); Expression? equals; @@ -6856,8 +6845,7 @@ DartType leftType, Name binaryName, Expression right, - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted) { + Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted) { assert(binaryName != equalsName); ObjectAccessTarget binaryTarget = findInterfaceMember( @@ -7029,8 +7017,7 @@ Expression expression, DartType expressionType, Name unaryName, - Map<SharedTypeView<DartType>, NonPromotionReason> Function() - whyNotPromoted) { + Map<SharedTypeView, NonPromotionReason> Function() whyNotPromoted) { ObjectAccessTarget unaryTarget = findInterfaceMember( expressionType, unaryName, fileOffset, includeExtensionMethods: true, isSetter: false); @@ -7420,8 +7407,8 @@ {required bool isThisReceiver, ObjectAccessTarget? readTarget, Expression? propertyGetNode}) { - Map<SharedTypeView<DartType>, NonPromotionReason> Function() - whyNotPromoted = flowAnalysis.whyNotPromoted(receiver); + Map<SharedTypeView, NonPromotionReason> Function() whyNotPromoted = + flowAnalysis.whyNotPromoted(receiver); readTarget ??= findInterfaceMember(receiverType, propertyName, fileOffset, includeExtensionMethods: true, isSetter: false); @@ -7618,8 +7605,8 @@ VariableDeclaration? indexVariable; Expression readIndex = indexResult.expression; - Map<SharedTypeView<DartType>, NonPromotionReason> Function() - whyNotPromotedIndex = flowAnalysis.whyNotPromoted(readIndex); + Map<SharedTypeView, NonPromotionReason> Function() whyNotPromotedIndex = + flowAnalysis.whyNotPromoted(readIndex); Expression writeIndex; if (isPureExpression(readIndex)) { writeIndex = clonePureExpression(readIndex); @@ -8975,7 +8962,7 @@ int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - SwitchExpressionResult<DartType, InvalidExpression> analysisResult = + SwitchExpressionResult<InvalidExpression> analysisResult = analyzeSwitchExpression(node, node.expression, node.cases.length, new SharedTypeSchemaView(typeContext)); DartType valueType = analysisResult.type.unwrapTypeView(); @@ -9029,8 +9016,7 @@ Set<Field?>? previousEnumFields = _enumFields; Expression expression = node.expression; - SwitchStatementTypeAnalysisResult<DartType, InvalidExpression> - analysisResult = + SwitchStatementTypeAnalysisResult<InvalidExpression> analysisResult = analyzeSwitchStatement(node, expression, node.cases.length); node.expressionType = analysisResult.scrutineeType.unwrapTypeView(); @@ -9119,8 +9105,7 @@ int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - SwitchStatementTypeAnalysisResult<DartType, InvalidExpression> - analysisResult = + SwitchStatementTypeAnalysisResult<InvalidExpression> analysisResult = analyzeSwitchStatement(node, node.expression, node.cases.length); node.lastCaseTerminates = analysisResult.lastCaseTerminates; @@ -9607,7 +9592,7 @@ int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternVariableDeclarationAnalysisResult<DartType> analysisResult = + PatternVariableDeclarationAnalysisResult analysisResult = analyzePatternVariableDeclaration(node, node.pattern, node.initializer, isFinal: node.isFinal); node.matchedValueType = analysisResult.initializerType.unwrapTypeView(); @@ -9831,8 +9816,8 @@ BinaryExpression node, DartType typeContext) { ExpressionInferenceResult leftResult = inferExpression(node.left, const UnknownType()); - Map<SharedTypeView<DartType>, NonPromotionReason> Function() - whyNotPromoted = flowAnalysis.whyNotPromoted(leftResult.expression); + Map<SharedTypeView, NonPromotionReason> Function() whyNotPromoted = + flowAnalysis.whyNotPromoted(leftResult.expression); return _computeBinaryExpression( node.fileOffset, typeContext, @@ -9913,8 +9898,7 @@ if (expressionResult == null) { expressionResult = inferExpression(node.expression, const UnknownType()); } - Map<SharedTypeView<DartType>, NonPromotionReason> Function() - whyNotPromoted = + Map<SharedTypeView, NonPromotionReason> Function() whyNotPromoted = flowAnalysis.whyNotPromoted(expressionResult.expression); return _computeUnaryExpression(node.fileOffset, expressionResult.expression, expressionResult.inferredType, node.unaryName, whyNotPromoted); @@ -10169,8 +10153,8 @@ } @override - ExpressionTypeAnalysisResult<DartType> dispatchExpression( - Expression node, SharedTypeSchemaView<DartType> 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 @@ } @override - PatternResult<DartType> 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 @@ } @override - SharedTypeSchemaView<DartType> 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 @@ @override FlowAnalysis<TreeNode, Statement, Expression, VariableDeclaration, - SharedTypeView<DartType>> get flow => flowAnalysis; + SharedTypeView> get flow => flowAnalysis; @override SwitchExpressionMemberInfo<TreeNode, Expression, VariableDeclaration> @@ -10626,7 +10609,7 @@ }) {} @override - void handleSwitchScrutinee(SharedTypeView<DartType> type) { + void handleSwitchScrutinee(SharedTypeView type) { DartType unwrapped = type.unwrapTypeView(); if ((!options.patternsEnabled) && unwrapped is InterfaceType && @@ -10634,7 +10617,7 @@ _enumFields = <Field?>{ ...unwrapped.classNode.fields .where((Field field) => field.isEnumElement), - if (type.unwrapTypeView().isPotentiallyNullable) null + if (type.unwrapTypeView<DartType>().isPotentiallyNullable) null }; } else { _enumFields = null; @@ -10644,8 +10627,7 @@ } @override - bool isLegacySwitchExhaustive( - TreeNode node, SharedTypeView<DartType> expressionType) { + bool isLegacySwitchExhaustive(TreeNode node, SharedTypeView expressionType) { Set<Field?>? enumFields = _enumFields; return enumFields != null && enumFields.isEmpty; } @@ -10656,14 +10638,12 @@ } @override - void setVariableType( - VariableDeclaration variable, SharedTypeView<DartType> type) { + void setVariableType(VariableDeclaration variable, SharedTypeView type) { variable.type = type.unwrapTypeView(); } @override - SharedTypeView<DartType> variableTypeFromInitializerType( - SharedTypeView<DartType> 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 @@ } @override - PatternResult<DartType> visitVariablePattern( + PatternResult visitVariablePattern( VariablePattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - DeclaredVariablePatternResult<DartType, InvalidExpression> analysisResult = + DeclaredVariablePatternResult<InvalidExpression> analysisResult = analyzeDeclaredVariablePattern(context, node, node.variable, node.variable.name!, node.type?.wrapSharedTypeView()); @@ -10713,12 +10693,12 @@ } @override - PatternResult<DartType> visitWildcardPattern( + PatternResult visitWildcardPattern( WildcardPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - WildcardPatternResult<DartType, InvalidExpression> analysisResult = + WildcardPatternResult<InvalidExpression> analysisResult = analyzeWildcardPattern( context: context, node: node, @@ -10744,12 +10724,12 @@ } @override - PatternResult<DartType> visitConstantPattern( + PatternResult visitConstantPattern( ConstantPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - ConstantPatternResult<DartType, InvalidExpression> analysisResult = + ConstantPatternResult<InvalidExpression> analysisResult = analyzeConstantPattern(context, node, node.expression); Pattern? replacement; @@ -10794,12 +10774,11 @@ } @override - PatternResult<DartType> visitAndPattern( - AndPattern node, SharedMatchContext context) { + PatternResult visitAndPattern(AndPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternResult<DartType> analysisResult = + PatternResult analysisResult = analyzeLogicalAndPattern(context, node, node.left, node.right); assert(checkStack(node, stackBase, [ @@ -10828,12 +10807,11 @@ } @override - PatternResult<DartType> visitOrPattern( - OrPattern node, SharedMatchContext context) { + PatternResult visitOrPattern(OrPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - LogicalOrPatternResult<DartType, InvalidExpression> analysisResult = + LogicalOrPatternResult<InvalidExpression> analysisResult = analyzeLogicalOrPattern(context, node, node.left, node.right); assert(checkStack(node, stackBase, [ @@ -10902,12 +10880,11 @@ } @override - PatternResult<DartType> visitCastPattern( - CastPattern node, SharedMatchContext context) { + PatternResult visitCastPattern(CastPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternResult<DartType> analysisResult = analyzeCastPattern( + PatternResult analysisResult = analyzeCastPattern( context: context, pattern: node, innerPattern: node.pattern, @@ -10933,12 +10910,12 @@ } @override - PatternResult<DartType> visitNullAssertPattern( + PatternResult visitNullAssertPattern( NullAssertPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - NullCheckOrAssertPatternResult<DartType, InvalidExpression> analysisResult = + NullCheckOrAssertPatternResult<InvalidExpression> analysisResult = analyzeNullCheckOrAssertPattern(context, node, node.pattern, isAssert: true); @@ -10972,12 +10949,12 @@ } @override - PatternResult<DartType> visitNullCheckPattern( + PatternResult visitNullCheckPattern( NullCheckPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - NullCheckOrAssertPatternResult<DartType, InvalidExpression> analysisResult = + NullCheckOrAssertPatternResult<InvalidExpression> analysisResult = analyzeNullCheckOrAssertPattern(context, node, node.pattern, isAssert: false); @@ -11000,15 +10977,14 @@ } @override - PatternResult<DartType> visitListPattern( - ListPattern node, SharedMatchContext context) { + PatternResult visitListPattern(ListPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - ListPatternResult<DartType, InvalidExpression> analysisResult = - analyzeListPattern(context, node, - elements: node.patterns, - elementType: node.typeArgument?.wrapSharedTypeView()); + ListPatternResult<InvalidExpression> analysisResult = analyzeListPattern( + context, node, + elements: node.patterns, + elementType: node.typeArgument?.wrapSharedTypeView()); DartType matchedValueType = node.matchedValueType = analysisResult.matchedValueType.unwrapTypeView(); @@ -11166,12 +11142,12 @@ } @override - PatternResult<DartType> visitObjectPattern( + PatternResult visitObjectPattern( ObjectPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - ObjectPatternResult<DartType, InvalidExpression> analysisResult = + ObjectPatternResult<InvalidExpression> analysisResult = analyzeObjectPattern(context, node, fields: <RecordPatternField<TreeNode, Pattern>>[ for (NamedPattern field in node.fields) @@ -11332,14 +11308,13 @@ } @override - PatternResult<DartType> 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<DartType> visitInvalidPattern( + PatternResult visitInvalidPattern( InvalidPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); @@ -11355,12 +11330,12 @@ } @override - PatternResult<DartType> visitRelationalPattern( + PatternResult visitRelationalPattern( RelationalPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - RelationalPatternResult<DartType, InvalidExpression> analysisResult = + RelationalPatternResult<InvalidExpression> analysisResult = analyzeRelationalPattern(context, node, node.expression); DartType matchedValueType = node.matchedValueType = @@ -11490,23 +11465,22 @@ } @override - PatternResult<DartType> visitMapPattern( - MapPattern node, SharedMatchContext context) { + PatternResult visitMapPattern(MapPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); ({ - SharedTypeView<DartType> keyType, - SharedTypeView<DartType> 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<DartType, InvalidExpression> analysisResult = - analyzeMapPattern(context, node, - typeArguments: typeArguments, elements: node.entries); + MapPatternResult<InvalidExpression> analysisResult = analyzeMapPattern( + context, node, + typeArguments: typeArguments, elements: node.entries); DartType matchedValueType = node.matchedValueType = analysisResult.matchedValueType.unwrapTypeView(); @@ -11610,14 +11584,14 @@ } @override - PatternResult<DartType> 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<DartType> visitRecordPattern( + PatternResult visitRecordPattern( RecordPattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); @@ -11631,7 +11605,7 @@ : fieldPattern, name: fieldPattern is NamedPattern ? fieldPattern.name : null) ]; - RecordPatternResult<DartType, InvalidExpression> analysisResult = + RecordPatternResult<InvalidExpression> analysisResult = analyzeRecordPattern(context, node, fields: fields); DartType matchedValueType = node.matchedValueType = @@ -11701,7 +11675,7 @@ int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); - PatternAssignmentAnalysisResult<DartType> analysisResult = + PatternAssignmentAnalysisResult analysisResult = analyzePatternAssignment(node, node.pattern, node.expression); node.matchedValueType = analysisResult.type.unwrapTypeView(); @@ -11731,7 +11705,7 @@ } @override - PatternResult<DartType> visitAssignedVariablePattern( + PatternResult visitAssignedVariablePattern( AssignedVariablePattern node, SharedMatchContext context) { int? stackBase; assert(checkStackBase(node, stackBase = stackHeight)); @@ -11775,7 +11749,7 @@ ..fileOffset = node.fileOffset; } - AssignedVariablePatternResult<DartType, InvalidExpression> analysisResult = + AssignedVariablePatternResult<InvalidExpression> analysisResult = analyzeAssignedVariablePattern(context, node, node.variable); DartType matchedValueType = node.matchedValueType = @@ -11832,8 +11806,8 @@ } @override - SharedTypeView<DartType> downwardInferObjectPatternRequiredType({ - required SharedTypeView<DartType> matchedType, + SharedTypeView downwardInferObjectPatternRequiredType({ + required SharedTypeView matchedType, required covariant ObjectPatternInternal pattern, }) { DartType requiredType = pattern.requiredType; @@ -11947,9 +11921,9 @@ } @override - (Member?, SharedTypeView<DartType>) resolveObjectPatternPropertyGet({ + (Member?, SharedTypeView) resolveObjectPatternPropertyGet({ required Pattern objectPattern, - required SharedTypeView<DartType> receiverType, + required SharedTypeView receiverType, required shared.RecordPatternField<TreeNode, Pattern> field, }) { String fieldName = field.name!; @@ -11978,7 +11952,7 @@ required JoinedPatternVariableLocation location, required JoinedPatternVariableInconsistency inconsistency, required bool isFinal, - required SharedTypeView<DartType> type, + required SharedTypeView type, }) { variable ..isFinal = isFinal @@ -12044,10 +12018,8 @@ } @override - void handleMapPatternEntry( - Pattern container, - covariant MapPatternEntry entryElement, - SharedTypeView<DartType> 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 @@ } @override - RelationalOperatorResolution<DartType>? resolveRelationalPatternOperator( - covariant RelationalPattern node, - SharedTypeView<DartType> 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 6c87506..5687abf 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 @@ InferenceDataForTesting? get dataForTesting => _inferrer.dataForTesting; FlowAnalysis<TreeNode, Statement, Expression, VariableDeclaration, - SharedTypeView<DartType>> 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 @@ /// promoted, to be used when reporting an error for a larger expression /// containing [receiver]. [node] is the containing tree node. List<LocatedMessage>? getWhyNotPromotedContext( - Map<SharedTypeView<DartType>, NonPromotionReason>? whyNotPromoted, + Map<SharedTypeView, NonPromotionReason>? whyNotPromoted, TreeNode node, bool Function(DartType) typeFilter) { List<LocatedMessage>? context; @@ -221,7 +221,7 @@ // Coverage-ignore-block(suite): Not run. _WhyNotPromotedVisitor whyNotPromotedVisitor = new _WhyNotPromotedVisitor(this); - for (MapEntry<SharedTypeView<DartType>, NonPromotionReason> entry + for (MapEntry<SharedTypeView, NonPromotionReason> entry in whyNotPromoted.entries) { if (!typeFilter(entry.key.unwrapTypeView())) continue; List<LocatedMessage> messages = @@ -381,8 +381,7 @@ nullabilityNullTypeErrorTemplate, Template<Message Function(DartType, DartType, DartType, DartType)>? nullabilityPartErrorTemplate, - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted}) { + Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { return ensureAssignableResult(expectedType, new ExpressionInferenceResult(expressionType, expression), fileOffset: fileOffset, @@ -496,8 +495,7 @@ nullabilityNullTypeErrorTemplate, Template<Message Function(DartType, DartType, DartType, DartType)>? nullabilityPartErrorTemplate, - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted}) { + Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { // [errorTemplate], [nullabilityErrorTemplate], and // [nullabilityPartErrorTemplate] should be provided together. assert((errorTemplate == null) == (nullabilityErrorTemplate == null) && @@ -657,8 +655,7 @@ nullabilityNullTypeErrorTemplate, Template<Message Function(DartType, DartType, DartType, DartType)>? nullabilityPartErrorTemplate, - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted}) { + Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { if (coerceExpression) { ExpressionInferenceResult? coercionResult = coerceExpressionForAssignment( contextType, inferenceResult, @@ -1705,7 +1702,7 @@ return visitor.inferExpression(argumentExpression, inferredFormalType); } - List<ExpressionInfo<SharedTypeView<DartType>>?>? identicalInfo = + List<ExpressionInfo<SharedTypeView>?>? identicalInfo = isIdentical && arguments.positional.length == 2 ? [] : null; int positionalIndex = 0; int namedIndex = 0; @@ -2996,8 +2993,7 @@ receiver = _hoist(receiver, receiverType, hoistedExpressions); } - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted; + Map<SharedTypeView, NonPromotionReason> 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 @@ DartType? readType, required DartType? promotedReadType, required bool isThisReceiver, - Map<SharedTypeView<DartType>, NonPromotionReason> Function()? - whyNotPromoted}) { + Map<SharedTypeView, NonPromotionReason> Function()? whyNotPromoted}) { Expression read; ExpressionInferenceResult? readResult; @@ -4376,7 +4371,7 @@ class _WhyNotPromotedVisitor implements NonPromotionReasonVisitor<List<LocatedMessage>, Node, - VariableDeclaration, SharedTypeView<DartType>> { + VariableDeclaration, SharedTypeView> { final InferenceVisitorBase inferrer; Member? propertyReference; @@ -4403,8 +4398,7 @@ @override List<LocatedMessage> visitPropertyNotPromotedForNonInherentReason( - PropertyNotPromotedForNonInherentReason<SharedTypeView<DartType>> - reason) { + PropertyNotPromotedForNonInherentReason<SharedTypeView> reason) { FieldNonPromotabilityInfo? fieldNonPromotabilityInfo = this.inferrer.libraryBuilder.fieldNonPromotabilityInfo; if (fieldNonPromotabilityInfo == null) { @@ -4460,7 +4454,7 @@ @override List<LocatedMessage> visitPropertyNotPromotedForInherentReason( - PropertyNotPromotedForInherentReason<SharedTypeView<DartType>> reason) { + PropertyNotPromotedForInherentReason<SharedTypeView> reason) { Object? member = reason.propertyMember; if (member is Member) { if (member case Procedure(:var stubTarget?)) { @@ -4507,7 +4501,7 @@ } void _addFieldPromotionUnavailableMessage( - PropertyNotPromoted<SharedTypeView<DartType>> reason, + PropertyNotPromoted<SharedTypeView> reason, List<LocatedMessage> 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 f860ff1..60440a5 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 @@ class SharedTypeAnalyzerErrors implements TypeAnalyzerErrors<TreeNode, Statement, Expression, VariableDeclaration, - SharedTypeView<DartType>, Pattern, InvalidExpression> { + SharedTypeView, Pattern, InvalidExpression> { final InferenceVisitorImpl visitor; final InferenceHelper helper; @@ -41,8 +41,8 @@ InvalidExpression caseExpressionTypeMismatch( {required Expression scrutinee, required Expression caseExpression, - required SharedTypeView<DartType> caseExpressionType, - required SharedTypeView<DartType> scrutineeType, + required SharedTypeView caseExpressionType, + required SharedTypeView scrutineeType, required bool nullSafetyEnabled}) { return helper.buildProblem( nullSafetyEnabled @@ -133,7 +133,7 @@ @override InvalidExpression? matchedTypeIsStrictlyNonNullable({ required Pattern pattern, - required SharedTypeView<DartType> matchedType, + required SharedTypeView matchedType, }) { // These are only warnings, so we don't report anything. return null; @@ -142,8 +142,8 @@ @override void matchedTypeIsSubtypeOfRequired({ required Pattern pattern, - required SharedTypeView<DartType> matchedType, - required SharedTypeView<DartType> requiredType, + required SharedTypeView matchedType, + required SharedTypeView requiredType, }) { // TODO(scheglov) implement } @@ -158,7 +158,7 @@ InvalidExpression patternForInExpressionIsNotIterable({ required TreeNode node, required Expression expression, - required SharedTypeView<DartType> expressionType, + required SharedTypeView expressionType, }) { return helper.buildProblem( templateForInLoopTypeNotIterable.withArguments( @@ -172,8 +172,8 @@ InvalidExpression patternTypeMismatchInIrrefutableContext( {required Pattern pattern, required TreeNode context, - required SharedTypeView<DartType> matchedType, - required SharedTypeView<DartType> requiredType}) { + required SharedTypeView matchedType, + required SharedTypeView requiredType}) { return helper.buildProblem( templatePatternTypeMismatchInIrrefutableContext.withArguments( matchedType.unwrapTypeView(), requiredType.unwrapTypeView()), @@ -191,8 +191,8 @@ @override InvalidExpression relationalPatternOperandTypeNotAssignable({ required covariant RelationalPattern pattern, - required SharedTypeView<DartType> operandType, - required SharedTypeView<DartType> parameterType, + required SharedTypeView operandType, + required SharedTypeView parameterType, }) { return helper.buildProblem( templateArgumentTypeNotAssignable.withArguments( @@ -204,7 +204,7 @@ @override InvalidExpression relationalPatternOperatorReturnTypeNotAssignableToBool({ required Pattern pattern, - required SharedTypeView<DartType> 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 a809b1c..0c341ed 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 @@ /// 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<VariableDeclaration, + TypeDeclarationType, TypeDeclaration, TreeNode> { final List<GeneratedTypeConstraint> _protoConstraints = []; @override @@ -130,7 +118,9 @@ 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 @@ ); } else { addLowerConstraintForParameter( - constraint.typeParameter, + constraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + StructuralParameter>(), typeOperations.greatestClosureOfTypeInternal( constraint.constraint.unwrapTypeSchemaView(), typeParametersToEliminate, @@ -197,7 +189,10 @@ ); } for (GeneratedTypeConstraint protoConstraint in _protoConstraints) { - result[protoConstraint.typeParameter]!.mergeIn( + result[protoConstraint.typeParameter + .unwrapTypeParameterViewAsTypeParameterStructure< + StructuralParameter>()]! + .mergeIn( protoConstraint, typeOperations, ); @@ -247,7 +242,7 @@ }) { GeneratedTypeConstraint generatedTypeConstraint = new GeneratedTypeConstraint.lower( - parameter, + new SharedTypeParameterView(parameter), new SharedTypeSchemaView(lower), ); if (astNodeForTesting != null && _inferenceResultForTesting != null) { @@ -267,7 +262,7 @@ }) { GeneratedTypeConstraint generatedTypeConstraint = new GeneratedTypeConstraint.upper( - parameter, + new SharedTypeParameterView(parameter), new SharedTypeSchemaView(upper), ); if (astNodeForTesting != null && _inferenceResultForTesting != null) { @@ -286,8 +281,7 @@ required bool leftSchema, required TreeNode? astNodeForTesting, }) { - if (p is SharedInvalidTypeStructure<DartType> || - q is SharedInvalidTypeStructure<DartType>) { + 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 872f68d..b5daf3c 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 @@ } // TODO(cstefantsova): Merge with [TypeInferenceResultForTesting]. -class InferenceDataForTesting - extends shared.TypeConstraintGenerationDataForTesting<DartType, - StructuralParameter, VariableDeclaration, TreeNode> { +class InferenceDataForTesting extends shared + .TypeConstraintGenerationDataForTesting<VariableDeclaration, TreeNode> { final FlowAnalysisResult flowAnalysisResult = new FlowAnalysisResult(); final TypeInferenceResultForTesting typeInferenceResult = @@ -437,11 +436,11 @@ /// CFE-specific implementation of [FlowAnalysisOperations]. class OperationsCfe with - TypeAnalyzerOperationsMixin<DartType, VariableDeclaration, - StructuralParameter, TypeDeclarationType, TypeDeclaration> + TypeAnalyzerOperationsMixin<VariableDeclaration, TypeDeclarationType, + TypeDeclaration> implements - TypeAnalyzerOperations<DartType, VariableDeclaration, - StructuralParameter, TypeDeclarationType, TypeDeclaration> { + TypeAnalyzerOperations<VariableDeclaration, TypeDeclarationType, + TypeDeclaration> { final TypeEnvironment typeEnvironment; /// Information about which fields are promotable in this library. @@ -466,59 +465,59 @@ required this.typeCacheLegacy}); @override - SharedTypeView<DartType> get boolType { + SharedTypeView get boolType { return new SharedTypeView( typeEnvironment.coreTypes.boolRawType(Nullability.nonNullable)); } @override - SharedTypeView<DartType> get doubleType { + SharedTypeView get doubleType { throw new UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView<DartType> get dynamicType { + SharedTypeView get dynamicType { return new SharedTypeView(const DynamicType()); } @override - SharedTypeView<DartType> get errorType { + SharedTypeView get errorType { return new SharedTypeView(const InvalidType()); } @override - SharedTypeView<DartType> get intType { + SharedTypeView get intType { throw new UnimplementedError('TODO(paulberry)'); } @override - SharedTypeView<DartType> get neverType { + SharedTypeView get neverType { return new SharedTypeView(const NeverType.nonNullable()); } @override - SharedTypeView<DartType> get nullType { + SharedTypeView get nullType { return new SharedTypeView(const NullType()); } @override - SharedTypeView<DartType> get objectQuestionType { + SharedTypeView get objectQuestionType { return new SharedTypeView(typeEnvironment.coreTypes.objectNullableRawType); } @override - SharedTypeView<DartType> get objectType { + SharedTypeView get objectType { return new SharedTypeView( typeEnvironment.coreTypes.objectNonNullableRawType); } @override - SharedTypeSchemaView<DartType> get unknownType { + SharedTypeSchemaView get unknownType { return new SharedTypeSchemaView(const UnknownType()); } @override - TypeClassification classifyType(SharedTypeView<DartType>? type) { + TypeClassification classifyType(SharedTypeView? type) { DartType? unwrapped = type?.unwrapTypeView(); if (unwrapped == null) { // Note: this can happen during top-level inference. @@ -534,22 +533,20 @@ } @override - SharedTypeView<DartType> factor( - SharedTypeView<DartType> from, SharedTypeView<DartType> what) { + SharedTypeView factor(SharedTypeView from, SharedTypeView what) { return new SharedTypeView(factorType( typeEnvironment, from.unwrapTypeView(), what.unwrapTypeView())); } @override - SharedTypeView<DartType> greatestClosure( - SharedTypeSchemaView<DartType> schema) { + SharedTypeView greatestClosure(SharedTypeSchemaView schema) { return new SharedTypeView(type_schema_elimination.greatestClosure( schema.unwrapTypeSchemaView(), topType: const DynamicType())); } @override - bool isAlwaysExhaustiveType(SharedTypeView<DartType> type) { + bool isAlwaysExhaustiveType(SharedTypeView type) { return computeIsAlwaysExhaustiveType( type.unwrapTypeView(), typeEnvironment.coreTypes); } @@ -570,13 +567,13 @@ } @override - bool isNever(SharedTypeView<DartType> type) { + bool isNever(SharedTypeView type) { return typeEnvironment.coreTypes.isBottom(type.unwrapTypeView()); } @override // Coverage-ignore(suite): Not run. - bool isObject(SharedTypeView<DartType> type) { + bool isObject(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); return unwrappedType is InterfaceType && unwrappedType.classNode == typeEnvironment.objectClass && @@ -627,7 +624,7 @@ } @override - SharedTypeView<DartType> promoteToNonNull(SharedTypeView<DartType> type) { + SharedTypeView promoteToNonNull(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType.nullability == Nullability.nonNullable) { return type; @@ -642,7 +639,7 @@ } @override - SharedTypeView<DartType> 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 @@ } @override - bool isTypeParameterType(SharedTypeView<DartType> type) { - return type.unwrapTypeView() is TypeParameterType || - type.unwrapTypeView() is IntersectionType; + bool isTypeParameterType(SharedTypeView type) { + return type.unwrapTypeView<DartType>() is TypeParameterType || + type.unwrapTypeView<DartType>() is IntersectionType; } @override - SharedTypeView<DartType> tryPromoteToType( - SharedTypeView<DartType> to, SharedTypeView<DartType> from) { + SharedTypeView tryPromoteToType(SharedTypeView to, SharedTypeView from) { DartType unwrappedTo = to.unwrapTypeView(); DartType unwrappedFrom = from.unwrapTypeView(); if (isSubtypeOfInternal(unwrappedTo, unwrappedFrom)) { @@ -668,7 +664,7 @@ } if (unwrappedFrom is TypeParameterType) { if (isSubtypeOfInternal(unwrappedTo, unwrappedFrom.bound)) { - if (to.unwrapTypeView().nullability != Nullability.nullable) { + if (to.unwrapTypeView<DartType>().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 @@ } @override - bool isAssignableTo( - SharedTypeView<DartType> fromType, SharedTypeView<DartType> toType) { + bool isAssignableTo(SharedTypeView fromType, SharedTypeView toType) { if (fromType is DynamicType) return true; return typeEnvironment .performNullabilityAwareSubtypeCheck( @@ -718,8 +713,8 @@ @override // Coverage-ignore(suite): Not run. bool isTypeSchemaSatisfied( - {required SharedTypeSchemaView<DartType> typeSchema, - required SharedTypeView<DartType> type}) { + {required SharedTypeSchemaView typeSchema, + required SharedTypeView type}) { return isSubtypeOfInternal( type.unwrapTypeView(), typeSchema.unwrapTypeSchemaView()); } @@ -730,8 +725,8 @@ } @override - SharedTypeSchemaView<DartType> iterableTypeSchema( - SharedTypeSchemaView<DartType> elementTypeSchema) { + SharedTypeSchemaView iterableTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return new SharedTypeSchemaView(new InterfaceType( typeEnvironment.coreTypes.iterableClass, Nullability.nonNullable, @@ -777,7 +772,7 @@ } @override - SharedTypeView<DartType>? matchListType(SharedTypeView<DartType> type) { + SharedTypeView? matchListType(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType is TypeDeclarationType) { List<DartType>? typeArguments = @@ -794,8 +789,8 @@ } @override - ({SharedTypeView<DartType> keyType, SharedTypeView<DartType> valueType})? - matchMapType(SharedTypeView<DartType> type) { + ({SharedTypeView keyType, SharedTypeView valueType})? matchMapType( + SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType is! TypeDeclarationType) { return null; @@ -816,7 +811,7 @@ } @override - SharedTypeView<DartType>? matchStreamType(SharedTypeView<DartType> type) { + SharedTypeView? matchStreamType(SharedTypeView type) { DartType unwrappedType = type.unwrapTypeView(); if (unwrappedType is TypeDeclarationType) { List<DartType>? typeArguments = @@ -833,7 +828,7 @@ } @override - SharedTypeView<DartType> normalize(SharedTypeView<DartType> type) { + SharedTypeView normalize(SharedTypeView type) { return new SharedTypeView( norm(typeEnvironment.coreTypes, type.unwrapTypeView())); } @@ -857,19 +852,20 @@ @override DartType recordTypeInternal( - {required List<DartType> positional, - required List<(String, DartType)> named}) { + {required List<SharedType> positional, + required List<(String, SharedType)> named}) { List<NamedType> 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<DartType>(), namedFields, Nullability.nonNullable); } @override - SharedTypeSchemaView<DartType> streamTypeSchema( - SharedTypeSchemaView<DartType> elementTypeSchema) { + SharedTypeSchemaView streamTypeSchema( + SharedTypeSchemaView elementTypeSchema) { return new SharedTypeSchemaView(new InterfaceType( typeEnvironment.coreTypes.streamClass, Nullability.nonNullable, @@ -877,12 +873,13 @@ } @override - SharedTypeView<DartType> extensionTypeErasure(SharedTypeView<DartType> type) { - return new SharedTypeView(type.unwrapTypeView().extensionTypeErasure); + SharedTypeView extensionTypeErasure(SharedTypeView type) { + return new SharedTypeView( + type.unwrapTypeView<DartType>().extensionTypeErasure); } @override - SharedTypeSchemaView<DartType> typeToSchema(SharedTypeView<DartType> type) { + SharedTypeSchemaView typeToSchema(SharedTypeView type) { return new SharedTypeSchemaView(type.unwrapTypeView()); } @@ -932,7 +929,7 @@ } @override - TypeDeclarationMatchResult<TypeDeclarationType, TypeDeclaration, DartType>? + TypeDeclarationMatchResult<TypeDeclarationType, TypeDeclaration>? matchTypeDeclarationTypeInternal(DartType type) { if (type is TypeDeclarationType) { switch (type) { @@ -974,16 +971,16 @@ } @override - DartType greatestClosureOfTypeInternal(DartType type, - List<SharedTypeParameterStructure<DartType>> typeParametersToEliminate) { + DartType greatestClosureOfTypeInternal( + DartType type, List<SharedTypeParameter> typeParametersToEliminate) { return new NullabilityAwareFreeTypeParameterEliminator( coreTypes: typeEnvironment.coreTypes) .eliminateToGreatest(type); } @override - DartType leastClosureOfTypeInternal(DartType type, - List<SharedTypeParameterStructure<DartType>> typeParametersToEliminate) { + DartType leastClosureOfTypeInternal( + DartType type, List<SharedTypeParameter> typeParametersToEliminate) { return new NullabilityAwareFreeTypeParameterEliminator( coreTypes: typeEnvironment.coreTypes) .eliminateToLeast(type); @@ -1017,19 +1014,19 @@ } @override - TypeConstraintGenerator<DartType, NamedType, VariableDeclaration, - StructuralParameter, TypeDeclarationType, TypeDeclaration, TreeNode> + TypeConstraintGenerator<VariableDeclaration, TypeDeclarationType, + TypeDeclaration, TreeNode> createTypeConstraintGenerator( {required covariant TypeInferenceResultForTesting? typeConstraintGenerationDataForTesting, - required List<StructuralParameter> typeParametersToInfer, + required List<SharedTypeParameterView> 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<StructuralParameter>(), typeOperations: typeAnalyzerOperations, inferenceResultForTesting: null, inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled); @@ -1037,9 +1034,8 @@ } /// Type inference results used for testing. -class TypeInferenceResultForTesting - extends shared.TypeConstraintGenerationDataForTesting<DartType, - StructuralParameter, VariableDeclaration, TreeNode> { +class TypeInferenceResultForTesting extends shared + .TypeConstraintGenerationDataForTesting<VariableDeclaration, TreeNode> { final Map<TreeNode, List<DartType>> inferredTypeArguments = {}; final Map<TreeNode, DartType> 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 96e174d..426df7b 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 @@ /// Returns the [FlowAnalysis] used during inference. FlowAnalysis<TreeNode, Statement, Expression, VariableDeclaration, - SharedTypeView<DartType>> get flowAnalysis; + SharedTypeView> get flowAnalysis; AssignedVariables<TreeNode, VariableDeclaration> get assignedVariables; @@ -86,8 +86,9 @@ @override late final FlowAnalysis<TreeNode, Statement, Expression, VariableDeclaration, - SharedTypeView<DartType>> flowAnalysis = - new FlowAnalysis(operations, assignedVariables, + SharedTypeView> flowAnalysis = + new FlowAnalysis( + operations, assignedVariables, respectImplicitlyTypedVarInitializers: libraryBuilder.libraryFeatures.constructorTearoffs.isEnabled, fieldPromotionEnabled: @@ -313,7 +314,7 @@ @override FlowAnalysis<TreeNode, Statement, Expression, VariableDeclaration, - SharedTypeView<DartType>> 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 129e972..27aea65 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 @@ /// /// 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<DartType> { +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 d8cdd7e..c387f25 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_schema.dart' show UnknownType, isKnown; import 'type_schema_elimination.dart' show greatestClosure, leastClosure; -typedef GeneratedTypeConstraint = shared.GeneratedTypeConstraint<DartType, - StructuralParameter, VariableDeclaration>; +typedef GeneratedTypeConstraint + = shared.GeneratedTypeConstraint<VariableDeclaration>; -typedef MergedTypeConstraint = shared.MergedTypeConstraint< - DartType, - StructuralParameter, - VariableDeclaration, - TypeDeclarationType, - TypeDeclaration>; +typedef MergedTypeConstraint = shared.MergedTypeConstraint<VariableDeclaration, + TypeDeclarationType, TypeDeclaration>; 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 @@ // Otherwise take whatever bound has partial information, // e.g. `Iterable<?>` - if (constraint.lower is! SharedUnknownTypeSchemaView<DartType>) { + if (constraint.lower is! SharedUnknownTypeSchemaView) { return grounded ? leastClosure(constraint.lower.unwrapTypeSchemaView(), coreTypes: coreTypes) @@ -479,13 +471,14 @@ } if (inferenceUsingBoundsIsEnabled && - constraint.lower is! SharedUnknownTypeSchemaView<DartType> && + constraint.lower is! SharedUnknownTypeSchemaView && !hasOmittedBound(typeParameterToInfer)) { MergedTypeConstraint constraintFromBound = operations.mergeInConstraintsFromBound( typeParameterToInfer: typeParameterToInfer, - typeParametersToInfer: typeParametersToInfer, - lower: constraint.lower.unwrapTypeSchemaView(), + typeParametersToInfer: + typeParametersToInfer.cast<SharedTypeParameterView>(), + lower: constraint.lower.unwrapTypeSchemaView<DartType>(), inferencePhaseConstraints: constraints, dataForTesting: dataForTesting, inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled); @@ -539,14 +532,15 @@ // If we consider the `T extends num` we conclude `<num>`, which works. if (inferenceUsingBoundsIsEnabled && - constraint.lower is! SharedUnknownTypeSchemaView<DartType> && + 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<SharedTypeParameterView>(), + lower: constraint.lower.unwrapTypeSchemaView<DartType>(), inferencePhaseConstraints: constraints, dataForTesting: dataForTesting, inferenceUsingBoundsIsEnabled: inferenceUsingBoundsIsEnabled);
diff --git a/pkg/front_end/test/coverage_suite_expected.dart b/pkg/front_end/test/coverage_suite_expected.dart index 7962768..725798a 100644 --- a/pkg/front_end/test/coverage_suite_expected.dart +++ b/pkg/front_end/test/coverage_suite_expected.dart
@@ -255,7 +255,7 @@ ), // 100.0%. "package:front_end/src/builder/class_builder.dart": ( - hitCount: 141, + hitCount: 137, missCount: 0, ), // 100.0%. @@ -585,7 +585,7 @@ ), // 100.0%. "package:front_end/src/kernel/body_builder_context.dart": ( - hitCount: 324, + hitCount: 319, missCount: 0, ), // 100.0%. @@ -925,7 +925,7 @@ ), // 100.0%. "package:front_end/src/source/source_enum_builder.dart": ( - hitCount: 331, + hitCount: 420, missCount: 0, ), // 100.0%. @@ -945,11 +945,6 @@ missCount: 0, ), // 100.0%. - "package:front_end/src/source/source_field_builder.dart": ( - hitCount: 232, - missCount: 0, - ), - // 100.0%. "package:front_end/src/source/source_function_builder.dart": ( hitCount: 243, missCount: 0, @@ -976,7 +971,7 @@ ), // 100.0%. "package:front_end/src/source/source_property_builder.dart": ( - hitCount: 768, + hitCount: 771, missCount: 0, ), // 100.0%. @@ -996,7 +991,7 @@ ), // 100.0%. "package:front_end/src/source/type_parameter_scope_builder.dart": ( - hitCount: 1514, + hitCount: 1508, missCount: 0, ), // 100.0%.
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 843af31..d4aa9f3 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 @@ 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/macros/application/macro_application_test.dart b/pkg/front_end/test/macros/application/macro_application_test.dart index 16dd38a..5834962 100644 --- a/pkg/front_end/test/macros/application/macro_application_test.dart +++ b/pkg/front_end/test/macros/application/macro_application_test.dart
@@ -9,7 +9,6 @@ import 'package:_fe_analyzer_shared/src/testing/id_testing.dart'; import 'package:front_end/src/api_prototype/compiler_options.dart'; import 'package:front_end/src/api_prototype/experimental_flags.dart'; -import 'package:front_end/src/builder/field_builder.dart'; import 'package:front_end/src/builder/member_builder.dart'; import 'package:front_end/src/builder/property_builder.dart'; import 'package:front_end/src/kernel/macro/macro.dart'; @@ -123,10 +122,7 @@ } bool _isMember(MemberBuilder memberBuilder, Member member) { - if (memberBuilder is FieldBuilder) { - // Only show annotations for the field or getter. - return memberBuilder.readTarget == member; - } else if (memberBuilder is PropertyBuilder && memberBuilder.isField) { + if (memberBuilder is PropertyBuilder && memberBuilder.isField) { // Only show annotations for the field or getter. return memberBuilder.readTarget == member; } else if (member is Procedure && member.isSetter) {
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 6b613f3..4c1a3ba 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 @@ 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 5050c19..8c8f11a 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 @@ 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 5685587..c4b0292 100644 --- a/pkg/kernel/lib/ast.dart +++ b/pkg/kernel/lib/ast.dart
@@ -73,16 +73,16 @@ 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 720c49e..cc3c80c 100644 --- a/pkg/kernel/lib/src/ast/types.dart +++ b/pkg/kernel/lib/src/ast/types.dart
@@ -259,8 +259,7 @@ /// /// [StructuralParameter] objects should not be shared between different /// [FunctionType] objects. -class StructuralParameter extends Node - implements SharedTypeParameterStructure<DartType> { +class StructuralParameter extends Node implements SharedTypeParameter { int flags = 0; String? name; // Cosmetic name. @@ -465,7 +464,7 @@ /// /// The `==` operator on [DartType]s compare based on type equality, not /// object identity. -sealed class DartType extends Node implements SharedTypeStructure<DartType> { +sealed class DartType extends Node implements SharedType { const DartType(); @override @@ -584,7 +583,7 @@ 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 @@ /// /// 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<DartType> { +class InvalidType extends DartType implements SharedInvalidType { @override final int hashCode = 12345; @@ -686,8 +684,7 @@ } } -class DynamicType extends DartType - implements SharedDynamicTypeStructure<DartType> { +class DynamicType extends DartType implements SharedDynamicType { @override final int hashCode = 54321; @@ -732,7 +729,7 @@ } } -class VoidType extends DartType implements SharedVoidTypeStructure<DartType> { +class VoidType extends DartType implements SharedVoidType { @override final int hashCode = 123121; @@ -856,7 +853,7 @@ } } -class NullType extends DartType implements SharedNullTypeStructure<DartType> { +class NullType extends DartType implements SharedNullType { @override final int hashCode = 415324; @@ -1014,9 +1011,7 @@ } /// A possibly generic function type. -class FunctionType extends DartType - implements - SharedFunctionTypeStructure<DartType, StructuralParameter, NamedType> { +class FunctionType extends DartType implements SharedFunctionType { final List<StructuralParameter> typeParameters; final int requiredParameterCount; final List<DartType> positionalParameters; @@ -1604,8 +1599,8 @@ class NamedType extends Node implements Comparable<NamedType>, - SharedNamedTypeStructure<DartType>, - SharedNamedFunctionParameterStructure<DartType> { + SharedNamedType, + SharedNamedFunctionParameter { // Flag used for serialization if [isRequired]. static const int FlagRequiredNamedType = 1 << 0; @@ -2197,8 +2192,7 @@ } } -class RecordType extends DartType - implements SharedRecordTypeStructure<DartType> { +class RecordType extends DartType implements SharedRecordType { final List<DartType> positional; final List<NamedType> named; @@ -2222,10 +2216,10 @@ "Named field types aren't sorted lexicographically " "in a RecordType: ${named}"); - List<SharedNamedTypeStructure<DartType>> get namedTypes => named; + List<SharedNamedType> get namedTypes => named; @override - List<SharedNamedTypeStructure<DartType>> get sortedNamedTypesShared { + List<SharedNamedType> get sortedNamedTypesShared { return namedTypes; }
diff --git a/pkg/vm/lib/transformations/type_flow/summary_collector.dart b/pkg/vm/lib/transformations/type_flow/summary_collector.dart index 87cfc9f..0411c7f 100644 --- a/pkg/vm/lib/transformations/type_flow/summary_collector.dart +++ b/pkg/vm/lib/transformations/type_flow/summary_collector.dart
@@ -1578,10 +1578,30 @@ } else if (node is EqualsCall && node.left is VariableGet) { final lhs = node.left as VariableGet; final rhs = node.right; - if ((rhs is IntLiteral && + bool isIntConstant(Expression expr) => switch (expr) { + IntLiteral() => true, + ConstantExpression(constant: IntConstant()) => true, + _ => false + }; + bool isStringConstant(Expression expr) => switch (expr) { + StringLiteral() => true, + ConstantExpression(constant: StringConstant()) => true, + _ => false + }; + bool doubleIsSafeToPropagate(double d) => !d.isNaN && d != 0.0; + bool isDoubleConstantSafeToPropagate(Expression expr) => switch (expr) { + DoubleLiteral(value: var value) => doubleIsSafeToPropagate(value), + ConstantExpression(constant: DoubleConstant(value: var value)) => + doubleIsSafeToPropagate(value), + _ => false + }; + if ((isIntConstant(rhs) && _isSubtype(lhs.variable.type, _environment.coreTypes.intNullableRawType)) || - (rhs is StringLiteral && + (isDoubleConstantSafeToPropagate(rhs) && + _isSubtype(lhs.variable.type, + _environment.coreTypes.doubleNullableRawType)) || + (isStringConstant(rhs) && target.canInferStringClassAfterEqualityComparison && _isSubtype(lhs.variable.type, _environment.coreTypes.stringNullableRawType)) ||
diff --git a/pkg/vm/testcases/transformations/type_flow/transformer/const_prop_conditional.dart b/pkg/vm/testcases/transformations/type_flow/transformer/const_prop_conditional.dart new file mode 100644 index 0000000..11a82a7 --- /dev/null +++ b/pkg/vm/testcases/transformations/type_flow/transformer/const_prop_conditional.dart
@@ -0,0 +1,158 @@ +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Tests constant propagation inside considitonals. + +void testStringLiteral(String s) { + print(s); +} + +void testStringConstant(String s) { + print(s); +} + +void testIntLiteral(int i) { + print(i); +} + +void testIntConstant(int i) { + print(i); +} + +void testDefaultEq1(DefaultEq c) { + print(c); +} + +void testDefaultEq2(DefaultEq c) { + print(c); +} + +void testOverriddenEq1(OverriddenEq c) { + print(c); +} + +void testOverriddenEq2(OverriddenEq c) { + print(c); +} + +bool get runtimeTrue => int.parse('1') == 1; + +class DefaultEq { + final int i; + + const DefaultEq(this.i); + + @override + String toString() => 'DefaultEq(i=$i)'; +} + +class OverriddenEq { + final int i; + + const OverriddenEq(this.i); + + @override + bool operator ==(Object other) { + return true; + } + + @override + String toString() => 'OverriddenEq(i=$i)'; +} + +void testDoubleLiteral1(double i) { + print(i); +} + +void testDoubleLiteral2(double i) { + print(i); +} + +void testDoubleLiteral3(double i) { + print(i); +} + +void testDoubleConstant1(double i) { + print(i); +} + +void testDoubleConstant2(double i) { + print(i); +} + +void testDoubleConstant3(double i) { + print(i); +} + +void main() { + final s1 = runtimeTrue ? "foo" : "bar"; + if (s1 == "foo") { + testStringLiteral(s1); + } + + final s2 = runtimeTrue ? "1234" : "asdf"; + const sConst = "1234"; + if (s2 == sConst) { + testStringConstant(s2); + } + + final i1 = runtimeTrue ? 123 : 456; + if (i1 == 123) { + testIntLiteral(i1); + } + + final i2 = runtimeTrue ? 456 : 789; + const iConst = 456; + if (i2 == iConst) { + testIntConstant(i2); + } + + final c1 = runtimeTrue ? DefaultEq(1) : DefaultEq(2); + if (c1 == const DefaultEq(1)) { + testDefaultEq1(c1); // should propagate + } + + if (c1 == sConst) { + testDefaultEq2(c1); // OK to propagate as the branch won't be taken + } + + final c2 = runtimeTrue ? OverriddenEq(1) : OverriddenEq(2); + if (c2 == const OverriddenEq(1)) { + testOverriddenEq1(c2); // should not propagate + } + + if (c2 == sConst) { + testOverriddenEq2(c2); // should not propagate + } + + final d1 = runtimeTrue ? 1.21 : 3.41; + if (d1 == 1.2) { + testDoubleLiteral1(d1); // should propagate + } + + const d1Const = 12.34; + if (d1 == d1Const) { + testDoubleConstant1(d1); // should propagate + } + + final d2 = runtimeTrue ? 1.34 : 5.67; + if (d2 == double.nan) { + testDoubleLiteral2(d2); // should not propagate + } + + const d2Const = double.nan; + if (d2 == d2Const) { + testDoubleConstant2(d2); // should not propagate + } + + final d3 = runtimeTrue ? 8.7 : 9.6; + if (d3 == -0.0) { + testDoubleLiteral3(d3); // should not propagate + } + + const d3Const = -0.0; + if (d3 == d3Const) { + testDoubleConstant3(d3); // should not propagate + } +}
diff --git a/pkg/vm/testcases/transformations/type_flow/transformer/const_prop_conditional.dart.expect b/pkg/vm/testcases/transformations/type_flow/transformer/const_prop_conditional.dart.expect new file mode 100644 index 0000000..1486340 --- /dev/null +++ b/pkg/vm/testcases/transformations/type_flow/transformer/const_prop_conditional.dart.expect
@@ -0,0 +1,193 @@ +library #lib; +import self as self; +import "dart:core" as core; + +class DefaultEq extends core::Object /*hasConstConstructor*/ { + + [@vm.inferred-type.metadata=dart.core::_Smi] + [@vm.procedure-attributes.metadata=methodOrSetterCalledDynamically:false,getterCalledDynamically:false,hasThisUses:false,hasNonThisUses:false,hasTearOffUses:false,getterSelectorId:1] + [@vm.unboxing-info.metadata=()->i] + final field core::int i; + + [@vm.unboxing-info.metadata=(i)->b] + const constructor •([@vm.inferred-arg-type.metadata=dart.core::_Smi] core::int i) → self::DefaultEq + : self::DefaultEq::i = i, super core::Object::•() + ; + + [@vm.inferred-return-type.metadata=!] + [@vm.procedure-attributes.metadata=methodOrSetterCalledDynamically:false,getterCalledDynamically:false,hasThisUses:false,hasTearOffUses:false,methodOrSetterSelectorId:2,getterSelectorId:3] + [@vm.unboxing-info.metadata=[!regcc]] + method toString() → core::String + return "DefaultEq(i=${[@vm.direct-call.metadata=#lib::DefaultEq.i] this.{self::DefaultEq::i}{core::int}})"; +} +class OverriddenEq extends core::Object /*hasConstConstructor*/ { + + [@vm.inferred-type.metadata=dart.core::_Smi] + [@vm.procedure-attributes.metadata=methodOrSetterCalledDynamically:false,getterCalledDynamically:false,hasThisUses:false,hasNonThisUses:false,hasTearOffUses:false,getterSelectorId:4] + [@vm.unboxing-info.metadata=()->i] + final field core::int i; + + [@vm.unboxing-info.metadata=(i)->b] + const constructor •([@vm.inferred-arg-type.metadata=dart.core::_Smi] core::int i) → self::OverriddenEq + : self::OverriddenEq::i = i, super core::Object::•() + ; + + [@vm.inferred-return-type.metadata=dart.core::bool] + [@vm.procedure-attributes.metadata=methodOrSetterCalledDynamically:false,getterCalledDynamically:false,hasThisUses:false,hasTearOffUses:false,methodOrSetterSelectorId:5] + [@vm.unboxing-info.metadata=[!regcc]] + operator ==(core::Object other) → core::bool { + return true; + } + + [@vm.inferred-return-type.metadata=!] + [@vm.procedure-attributes.metadata=methodOrSetterCalledDynamically:false,getterCalledDynamically:false,hasThisUses:false,hasTearOffUses:false,methodOrSetterSelectorId:2,getterSelectorId:3] + [@vm.unboxing-info.metadata=[!regcc]] + method toString() → core::String + return "OverriddenEq(i=${[@vm.direct-call.metadata=#lib::OverriddenEq.i] this.{self::OverriddenEq::i}{core::int}})"; +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testStringLiteral() → void { + core::print(#C1); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testStringConstant() → void { + core::print(#C2); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testIntLiteral() → void { + core::print(#C3); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testIntConstant() → void { + core::print(#C4); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testDefaultEq1() → void { + core::print(#C6); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testDefaultEq2() → void { + throw "Attempt to execute code removed by Dart AOT compiler (TFA)"; +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testOverriddenEq1([@vm.inferred-arg-type.metadata=#lib::OverriddenEq] self::OverriddenEq c) → void { + core::print(c); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testOverriddenEq2([@vm.inferred-arg-type.metadata=#lib::OverriddenEq] self::OverriddenEq c) → void { + core::print(c); +} + +[@vm.inferred-return-type.metadata=dart.core::bool] +static get runtimeTrue() → core::bool + return [@vm.direct-call.metadata=dart.core::_IntegerImplementation.==] [@vm.inferred-type.metadata=dart.core::bool (skip check)] [@vm.inferred-type.metadata=int] core::int::parse("1") =={core::num::==}{(core::Object) → core::bool} 1; + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testDoubleLiteral1() → void { + core::print(#C7); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +[@vm.unboxing-info.metadata=(d)->b] +static method testDoubleLiteral2([@vm.inferred-arg-type.metadata=dart.core::_Double] core::double i) → void { + core::print(i); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +[@vm.unboxing-info.metadata=(d)->b] +static method testDoubleLiteral3([@vm.inferred-arg-type.metadata=dart.core::_Double] core::double i) → void { + core::print(i); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method testDoubleConstant1() → void { + core::print(#C8); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +[@vm.unboxing-info.metadata=(d)->b] +static method testDoubleConstant2([@vm.inferred-arg-type.metadata=dart.core::_Double] core::double i) → void { + core::print(i); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +[@vm.unboxing-info.metadata=(d)->b] +static method testDoubleConstant3([@vm.inferred-arg-type.metadata=dart.core::_Double] core::double i) → void { + core::print(i); +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method main() → void { + final core::String s1 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{core::String} "foo" : "bar"; + if([@vm.inferred-type.metadata=dart.core::bool (receiver not int)] s1 =={core::String::==}{(core::Object) → core::bool} "foo") { + self::testStringLiteral(); + } + final core::String s2 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{core::String} "1234" : "asdf"; + if([@vm.inferred-type.metadata=dart.core::bool (receiver not int)] s2 =={core::String::==}{(core::Object) → core::bool} #C2) { + self::testStringConstant(); + } + final core::int i1 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{core::int} 123 : 456; + if([@vm.direct-call.metadata=dart.core::_IntegerImplementation.==] [@vm.inferred-type.metadata=dart.core::bool (skip check)] i1 =={core::num::==}{(core::Object) → core::bool} 123) { + self::testIntLiteral(); + } + final core::int i2 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{core::int} 456 : 789; + if([@vm.direct-call.metadata=dart.core::_IntegerImplementation.==] [@vm.inferred-type.metadata=dart.core::bool (skip check)] i2 =={core::num::==}{(core::Object) → core::bool} #C4) { + self::testIntConstant(); + } + final self::DefaultEq c1 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{self::DefaultEq} new self::DefaultEq::•(1) : new self::DefaultEq::•(2); + if([@vm.direct-call.metadata=dart.core::Object.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] c1 =={core::Object::==}{(core::Object) → core::bool} #C6) { + self::testDefaultEq1(); + } + if([@vm.direct-call.metadata=dart.core::Object.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] c1 =={core::Object::==}{(core::Object) → core::bool} #C2) { + self::testDefaultEq2(); + } + final self::OverriddenEq c2 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{self::OverriddenEq} new self::OverriddenEq::•(1) : new self::OverriddenEq::•(2); + if([@vm.direct-call.metadata=#lib::OverriddenEq.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] c2 =={self::OverriddenEq::==}{(core::Object) → core::bool} #C9) { + self::testOverriddenEq1(c2); + } + if([@vm.direct-call.metadata=#lib::OverriddenEq.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] c2 =={self::OverriddenEq::==}{(core::Object) → core::bool} #C2) { + self::testOverriddenEq2(c2); + } + final core::double d1 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{core::double} 1.21 : 3.41; + if([@vm.direct-call.metadata=dart.core::_Double.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] d1 =={core::num::==}{(core::Object) → core::bool} 1.2) { + self::testDoubleLiteral1(); + } + if([@vm.direct-call.metadata=dart.core::_Double.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] d1 =={core::num::==}{(core::Object) → core::bool} #C8) { + self::testDoubleConstant1(); + } + final core::double d2 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{core::double} 1.34 : 5.67; + if([@vm.direct-call.metadata=dart.core::_Double.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] d2 =={core::num::==}{(core::Object) → core::bool} #C10) { + self::testDoubleLiteral2(d2); + } + if([@vm.direct-call.metadata=dart.core::_Double.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] d2 =={core::num::==}{(core::Object) → core::bool} #C10) { + self::testDoubleConstant2(d2); + } + final core::double d3 = [@vm.inferred-type.metadata=dart.core::bool] self::runtimeTrue ?{core::double} 8.7 : 9.6; + if([@vm.direct-call.metadata=dart.core::_Double.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] d3 =={core::num::==}{(core::Object) → core::bool} [@vm.direct-call.metadata=dart.core::_Double.unary-] [@vm.inferred-type.metadata=dart.core::_Double (skip check)] 0.0.{core::double::unary-}(){() → core::double}) { + self::testDoubleLiteral3(d3); + } + if([@vm.direct-call.metadata=dart.core::_Double.==] [@vm.inferred-type.metadata=dart.core::bool (skip check) (receiver not int)] d3 =={core::num::==}{(core::Object) → core::bool} #C11) { + self::testDoubleConstant3(d3); + } +} +constants { + #C1 = "foo" + #C2 = "1234" + #C3 = 123 + #C4 = 456 + #C5 = 1 + #C6 = self::DefaultEq {i:#C5} + #C7 = 1.2 + #C8 = 12.34 + #C9 = self::OverriddenEq {i:#C5} + #C10 = NaN + #C11 = -0.0 +}
diff --git a/tools/VERSION b/tools/VERSION index 92e76e8..8806c73 100644 --- a/tools/VERSION +++ b/tools/VERSION
@@ -27,5 +27,5 @@ MAJOR 3 MINOR 8 PATCH 0 -PRERELEASE 12 +PRERELEASE 13 PRERELEASE_PATCH 0