repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/visitors.dart
// Copyright (c) 2015, 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. @deprecated library analyzer.src.generated.visitors; export 'package:analyzer/dart/ast/visitor.dart' show DelegatingAstVisitor;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/error_verifier.dart
// Copyright (c) 2014, 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 'dart:collection'; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/dart/element/visitor.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/inheritance_manager3.dart'; import 'package:analyzer/src/dart/element/member.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/resolver/variance.dart'; import 'package:analyzer/src/diagnostic/diagnostic_factory.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/error/duplicate_definition_verifier.dart'; import 'package:analyzer/src/error/literal_element_verifier.dart'; import 'package:analyzer/src/error/required_parameters_verifier.dart'; import 'package:analyzer/src/error/type_arguments_verifier.dart'; import 'package:analyzer/src/generated/element_resolver.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/java_engine.dart'; import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/sdk.dart' show DartSdk, SdkLibrary; import 'package:meta/meta.dart'; /** * A visitor used to traverse an AST structure looking for additional errors and * warnings not covered by the parser and resolver. */ class ErrorVerifier extends RecursiveAstVisitor<void> { /** * Properties on the object class which are safe to call on nullable types. * * Note that this must include tear-offs. * * TODO(mfairhurst): Calculate these fields rather than hard-code them. */ static final _objectPropertyNames = Set.from(['hashCode', 'runtimeType', 'noSuchMethod', 'toString']); /** * The error reporter by which errors will be reported. */ final ErrorReporter _errorReporter; /** * The current library that is being analyzed. */ final LibraryElement _currentLibrary; /** * The type representing the type 'bool'. */ InterfaceType _boolType; /** * The type representing the type 'int'. */ InterfaceType _intType; /** * The options for verification. */ AnalysisOptionsImpl _options; /** * The object providing access to the types defined by the language. */ final TypeProvider _typeProvider; /** * The type system primitives */ TypeSystem _typeSystem; /** * The manager for the inheritance mappings. */ final InheritanceManager3 _inheritanceManager; /** * A flag indicating whether the visitor is currently within a constructor * declaration that is 'const'. * * See [visitConstructorDeclaration]. */ bool _isEnclosingConstructorConst = false; /** * A flag indicating whether we are currently within a function body marked as * being asynchronous. */ bool _inAsync = false; /** * A flag indicating whether we are currently within a function body marked a * being a generator. */ bool _inGenerator = false; /** * A flag indicating whether the visitor is currently within a catch clause. * * See [visitCatchClause]. */ bool _isInCatchClause = false; /** * A flag indicating whether the visitor is currently within a comment. */ bool _isInComment = false; /** * A flag indicating whether the visitor is currently within an instance * creation expression. */ bool _isInConstInstanceCreation = false; /** * A flag indicating whether the visitor is currently within a native class * declaration. */ bool _isInNativeClass = false; /** * A flag indicating whether the visitor is currently within a static variable * declaration. */ bool _isInStaticVariableDeclaration = false; /** * A flag indicating whether the visitor is currently within an instance * variable declaration. */ bool _isInInstanceVariableDeclaration = false; /** * A flag indicating whether the visitor is currently within an instance * variable initializer. */ bool _isInInstanceVariableInitializer = false; /** * A flag indicating whether the visitor is currently within a constructor * initializer. */ bool _isInConstructorInitializer = false; /** * This is set to `true` iff the visitor is currently within a function typed * formal parameter. */ bool _isInFunctionTypedFormalParameter = false; /** * A flag indicating whether the visitor is currently within a static method. * By "method" here getter, setter and operator declarations are also implied * since they are all represented with a [MethodDeclaration] in the AST * structure. */ bool _isInStaticMethod = false; /** * A flag indicating whether the visitor is currently within a factory * constructor. */ bool _isInFactory = false; /** * A flag indicating whether the visitor is currently within code in the SDK. */ bool _isInSystemLibrary = false; /** * A flag indicating whether the current library contains at least one import * directive with a URI that uses the "dart-ext" scheme. */ bool _hasExtUri = false; /** * This is set to `false` on the entry of every [BlockFunctionBody], and is * restored to the enclosing value on exit. The value is used in * [_checkForMixedReturns] to prevent both * [StaticWarningCode.MIXED_RETURN_TYPES] and * [StaticWarningCode.RETURN_WITHOUT_VALUE] from being generated in the same * function body. */ bool _hasReturnWithoutValue = false; /** * The class containing the AST nodes being visited, or `null` if we are not * in the scope of a class. */ ClassElementImpl _enclosingClass; /** * The enum containing the AST nodes being visited, or `null` if we are not * in the scope of an enum. */ ClassElement _enclosingEnum; /** * The element of the extension being visited, or `null` if we are not * in the scope of an extension. */ ExtensionElement _enclosingExtension; /** * The method or function that we are currently visiting, or `null` if we are * not inside a method or function. */ ExecutableElement _enclosingFunction; /** * The return statements found in the method or function that we are currently * visiting that have a return value. */ List<ReturnStatement> _returnsWith = new List<ReturnStatement>(); /** * The return statements found in the method or function that we are currently * visiting that do not have a return value. */ List<ReturnStatement> _returnsWithout = new List<ReturnStatement>(); /** * This map is initialized when visiting the contents of a class declaration. * If the visitor is not in an enclosing class declaration, then the map is * set to `null`. * * When set the map maps the set of [FieldElement]s in the class to an * [INIT_STATE.NOT_INIT] or [INIT_STATE.INIT_IN_DECLARATION]. The `checkFor*` * methods, specifically [_checkForAllFinalInitializedErrorCodes], can make a * copy of the map to compute error code states. The `checkFor*` methods * should only ever make a copy, or read from this map after it has been set * in [visitClassDeclaration]. * * See [visitClassDeclaration], and [_checkForAllFinalInitializedErrorCodes]. */ Map<FieldElement, INIT_STATE> _initialFieldElementsMap; /** * A table mapping name of the library to the export directive which export * this library. */ Map<String, LibraryElement> _nameToExportElement = new HashMap<String, LibraryElement>(); /** * A table mapping name of the library to the import directive which import * this library. */ Map<String, LibraryElement> _nameToImportElement = new HashMap<String, LibraryElement>(); /** * A table mapping names to the exported elements. */ Map<String, Element> _exportedElements = new HashMap<String, Element>(); /** * A set of the names of the variable initializers we are visiting now. */ HashSet<String> _namesForReferenceToDeclaredVariableInInitializer = new HashSet<String>(); /** * The elements that will be defined later in the current scope, but right * now are not declared. */ HiddenElements _hiddenElements; /** * A list of types used by the [CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS] * and [CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS] error codes. */ List<InterfaceType> _DISALLOWED_TYPES_TO_EXTEND_OR_IMPLEMENT; final _UninstantiatedBoundChecker _uninstantiatedBoundChecker; /// Setting this flag to `true` disables the check for conflicting generics. /// This is used when running with the old task model to work around /// dartbug.com/32421. /// /// TODO(paulberry): remove this flag once dartbug.com/32421 is properly /// fixed. final bool disableConflictingGenericsCheck; /// The features enabled in the unit currently being checked for errors. FeatureSet _featureSet; final RequiredParametersVerifier _requiredParametersVerifier; final DuplicateDefinitionVerifier _duplicateDefinitionVerifier; TypeArgumentsVerifier _typeArgumentsVerifier; /** * Initialize a newly created error verifier. * * [inheritanceManager] should be an instance of either [InheritanceManager2] * or [InheritanceManager3]. If an [InheritanceManager2] is supplied, it * will be converted into an [InheritanceManager3] internally. The ability * to pass in [InheritanceManager2] exists for backward compatibility; in a * future major version of the analyzer, an [InheritanceManager3] will * be required. */ ErrorVerifier( ErrorReporter errorReporter, this._currentLibrary, this._typeProvider, InheritanceManagerBase inheritanceManager, bool enableSuperMixins, {this.disableConflictingGenericsCheck: false}) : _errorReporter = errorReporter, _inheritanceManager = inheritanceManager.asInheritanceManager3, _uninstantiatedBoundChecker = new _UninstantiatedBoundChecker(errorReporter), _requiredParametersVerifier = RequiredParametersVerifier(errorReporter), _duplicateDefinitionVerifier = DuplicateDefinitionVerifier(_currentLibrary, errorReporter) { this._isInSystemLibrary = _currentLibrary.source.isInSystemLibrary; this._hasExtUri = _currentLibrary.hasExtUri; _isEnclosingConstructorConst = false; _isInCatchClause = false; _isInStaticVariableDeclaration = false; _isInInstanceVariableDeclaration = false; _isInInstanceVariableInitializer = false; _isInConstructorInitializer = false; _isInStaticMethod = false; _boolType = _typeProvider.boolType; _intType = _typeProvider.intType; _DISALLOWED_TYPES_TO_EXTEND_OR_IMPLEMENT = _typeProvider.nonSubtypableTypes; _typeSystem = _currentLibrary.context.typeSystem; _options = _currentLibrary.context.analysisOptions; _typeArgumentsVerifier = TypeArgumentsVerifier(_options, _typeSystem, _errorReporter); } /** * If `true`, mixins are allowed to inherit from types other than Object, and * are allowed to reference `super`. */ @deprecated bool get enableSuperMixins => false; ClassElement get enclosingClass => _enclosingClass; /** * For consumers of error verification as a library, (currently just the * angular plugin), expose a setter that can make the errors reported more * accurate when dangling code snippets are being resolved from a class * context. Note that this setter is very defensive for potential misuse; it * should not be modified in the middle of visiting a tree and requires an * analyzer-provided Impl instance to work. */ set enclosingClass(ClassElement classElement) { assert(classElement is ClassElementImpl); assert(_enclosingClass == null); assert(_enclosingEnum == null); assert(_enclosingFunction == null); _enclosingClass = classElement; } bool get _isNonNullable => _featureSet?.isEnabled(Feature.non_nullable) ?? false; @override void visitAnnotation(Annotation node) { _checkForInvalidAnnotationFromDeferredLibrary(node); _checkForMissingJSLibAnnotation(node); super.visitAnnotation(node); } @override void visitArgumentList(ArgumentList node) { if (node.parent is! ExtensionOverride) { _checkForArgumentTypesNotAssignableInList(node); } super.visitArgumentList(node); } @override void visitAsExpression(AsExpression node) { _checkForTypeAnnotationDeferredClass(node.type); super.visitAsExpression(node); } @override void visitAssertInitializer(AssertInitializer node) { _checkForNonBoolExpression(node.condition, errorCode: StaticTypeWarningCode.NON_BOOL_EXPRESSION); super.visitAssertInitializer(node); } @override void visitAssertStatement(AssertStatement node) { _checkForNonBoolExpression(node.condition, errorCode: StaticTypeWarningCode.NON_BOOL_EXPRESSION); super.visitAssertStatement(node); } @override void visitAssignmentExpression(AssignmentExpression node) { TokenType operatorType = node.operator.type; Expression lhs = node.leftHandSide; Expression rhs = node.rightHandSide; if (operatorType == TokenType.EQ || operatorType == TokenType.QUESTION_QUESTION_EQ) { _checkForInvalidAssignment(lhs, rhs); } else { _checkForArgumentTypeNotAssignableForArgument(rhs); _checkForNullableDereference(lhs); } _checkForAssignmentToFinal(lhs); super.visitAssignmentExpression(node); } @override void visitAwaitExpression(AwaitExpression node) { if (!_inAsync) { _errorReporter.reportErrorForToken( CompileTimeErrorCode.AWAIT_IN_WRONG_CONTEXT, node.awaitKeyword); } super.visitAwaitExpression(node); } @override void visitBinaryExpression(BinaryExpression node) { Token operator = node.operator; TokenType type = operator.type; if (type == TokenType.AMPERSAND_AMPERSAND || type == TokenType.BAR_BAR) { String lexeme = operator.lexeme; _checkForAssignability(node.leftOperand, _boolType, StaticTypeWarningCode.NON_BOOL_OPERAND, [lexeme]); _checkForAssignability(node.rightOperand, _boolType, StaticTypeWarningCode.NON_BOOL_OPERAND, [lexeme]); _checkForUseOfVoidResult(node.rightOperand); } else if (type == TokenType.EQ_EQ || type == TokenType.BANG_EQ) { _checkForArgumentTypeNotAssignableForArgument(node.rightOperand, promoteParameterToNullable: true); } else if (type != TokenType.QUESTION_QUESTION) { _checkForArgumentTypeNotAssignableForArgument(node.rightOperand); _checkForNullableDereference(node.leftOperand); } else { _checkForArgumentTypeNotAssignableForArgument(node.rightOperand); } _checkForUseOfVoidResult(node.leftOperand); super.visitBinaryExpression(node); } @override void visitBlock(Block node) { _hiddenElements = new HiddenElements(_hiddenElements, node); try { _duplicateDefinitionVerifier.checkStatements(node.statements); super.visitBlock(node); } finally { _hiddenElements = _hiddenElements.outerElements; } } @override void visitBlockFunctionBody(BlockFunctionBody node) { bool wasInAsync = _inAsync; bool wasInGenerator = _inGenerator; bool previousHasReturnWithoutValue = _hasReturnWithoutValue; _hasReturnWithoutValue = false; List<ReturnStatement> previousReturnsWith = _returnsWith; List<ReturnStatement> previousReturnsWithout = _returnsWithout; try { _inAsync = node.isAsynchronous; _inGenerator = node.isGenerator; _returnsWith = new List<ReturnStatement>(); _returnsWithout = new List<ReturnStatement>(); super.visitBlockFunctionBody(node); _checkForMixedReturns(node); } finally { _inAsync = wasInAsync; _inGenerator = wasInGenerator; _returnsWith = previousReturnsWith; _returnsWithout = previousReturnsWithout; _hasReturnWithoutValue = previousHasReturnWithoutValue; } } @override void visitBreakStatement(BreakStatement node) { SimpleIdentifier labelNode = node.label; if (labelNode != null) { Element labelElement = labelNode.staticElement; if (labelElement is LabelElementImpl && labelElement.isOnSwitchMember) { _errorReporter.reportErrorForNode( ResolverErrorCode.BREAK_LABEL_ON_SWITCH_MEMBER, labelNode); } } } void visitCascadeExpression(CascadeExpression node) { _checkForNullableDereference(node.target); super.visitCascadeExpression(node); } @override void visitCatchClause(CatchClause node) { _duplicateDefinitionVerifier.checkCatchClause(node); bool previousIsInCatchClause = _isInCatchClause; try { _isInCatchClause = true; _checkForTypeAnnotationDeferredClass(node.exceptionType); _checkForPotentiallyNullableType(node.exceptionType); super.visitCatchClause(node); } finally { _isInCatchClause = previousIsInCatchClause; } } @override void visitClassDeclaration(ClassDeclaration node) { ClassElementImpl outerClass = _enclosingClass; try { _isInNativeClass = node.nativeClause != null; _enclosingClass = AbstractClassElementImpl.getImpl(node.declaredElement); List<ClassMember> members = node.members; _duplicateDefinitionVerifier.checkClass(node); _checkForBuiltInIdentifierAsName( node.name, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME); _checkForMemberWithClassName(); _checkForNoDefaultSuperConstructorImplicit(node); _checkForConflictingTypeVariableErrorCodes(); TypeName superclass = node.extendsClause?.superclass; ImplementsClause implementsClause = node.implementsClause; WithClause withClause = node.withClause; // Only do error checks on the clause nodes if there is a non-null clause if (implementsClause != null || superclass != null || withClause != null) { _checkClassInheritance(node, superclass, withClause, implementsClause); } _initializeInitialFieldElementsMap(_enclosingClass.fields); _checkForFinalNotInitializedInClass(members); _checkForBadFunctionUse(node); _checkForWrongTypeParameterVarianceInSuperinterfaces(); super.visitClassDeclaration(node); } finally { _isInNativeClass = false; _initialFieldElementsMap = null; _enclosingClass = outerClass; } } @override void visitClassTypeAlias(ClassTypeAlias node) { _checkForBuiltInIdentifierAsName( node.name, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME); ClassElementImpl outerClassElement = _enclosingClass; try { _enclosingClass = AbstractClassElementImpl.getImpl(node.declaredElement); _checkClassInheritance( node, node.superclass, node.withClause, node.implementsClause); _checkForWrongTypeParameterVarianceInSuperinterfaces(); } finally { _enclosingClass = outerClassElement; } super.visitClassTypeAlias(node); } @override void visitComment(Comment node) { _isInComment = true; try { super.visitComment(node); } finally { _isInComment = false; } } @override void visitCompilationUnit(CompilationUnit node) { _featureSet = node.featureSet; _duplicateDefinitionVerifier.checkUnit(node); _checkForDeferredPrefixCollisions(node); super.visitCompilationUnit(node); _featureSet = null; } @override void visitConditionalExpression(ConditionalExpression node) { _checkForNonBoolCondition(node.condition); super.visitConditionalExpression(node); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { ExecutableElement outerFunction = _enclosingFunction; try { ConstructorElement constructorElement = node.declaredElement; _enclosingFunction = constructorElement; _isEnclosingConstructorConst = node.constKeyword != null; _isInFactory = node.factoryKeyword != null; _checkForInvalidModifierOnBody( node.body, CompileTimeErrorCode.INVALID_MODIFIER_ON_CONSTRUCTOR); _checkForConstConstructorWithNonFinalField(node, constructorElement); _checkForConstConstructorWithNonConstSuper(node); _checkForAllFinalInitializedErrorCodes(node); _checkForRedirectingConstructorErrorCodes(node); _checkForMultipleSuperInitializers(node); _checkForRecursiveConstructorRedirect(node, constructorElement); if (!_checkForRecursiveFactoryRedirect(node, constructorElement)) { _checkForAllRedirectConstructorErrorCodes(node); } _checkForUndefinedConstructorInInitializerImplicit(node); _checkForRedirectToNonConstConstructor(node, constructorElement); _checkForReturnInGenerativeConstructor(node); super.visitConstructorDeclaration(node); } finally { _isEnclosingConstructorConst = false; _isInFactory = false; _enclosingFunction = outerFunction; } } @override void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { _isInConstructorInitializer = true; try { SimpleIdentifier fieldName = node.fieldName; Element staticElement = fieldName.staticElement; _checkForInvalidField(node, fieldName, staticElement); if (staticElement is FieldElement) { _checkForFieldInitializerNotAssignable(node, staticElement); } super.visitConstructorFieldInitializer(node); } finally { _isInConstructorInitializer = false; } } @override void visitContinueStatement(ContinueStatement node) { SimpleIdentifier labelNode = node.label; if (labelNode != null) { Element labelElement = labelNode.staticElement; if (labelElement is LabelElementImpl && labelElement.isOnSwitchStatement) { _errorReporter.reportErrorForNode( ResolverErrorCode.CONTINUE_LABEL_ON_SWITCH, labelNode); } } } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { _checkForInvalidAssignment(node.identifier, node.defaultValue); _checkForDefaultValueInFunctionTypedParameter(node); super.visitDefaultFormalParameter(node); } @override void visitDoStatement(DoStatement node) { _checkForNonBoolCondition(node.condition); super.visitDoStatement(node); } @override void visitEnumDeclaration(EnumDeclaration node) { ClassElement outerEnum = _enclosingEnum; try { _enclosingEnum = node.declaredElement; _duplicateDefinitionVerifier.checkEnum(node); super.visitEnumDeclaration(node); } finally { _enclosingEnum = outerEnum; } } @override void visitExportDirective(ExportDirective node) { ExportElement exportElement = node.element; if (exportElement != null) { LibraryElement exportedLibrary = exportElement.exportedLibrary; _checkForAmbiguousExport(node, exportElement, exportedLibrary); _checkForExportDuplicateLibraryName(node, exportElement, exportedLibrary); _checkForExportInternalLibrary(node, exportElement); } super.visitExportDirective(node); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { bool wasInAsync = _inAsync; bool wasInGenerator = _inGenerator; try { _inAsync = node.isAsynchronous; _inGenerator = node.isGenerator; FunctionType functionType = _enclosingFunction?.type; DartType expectedReturnType = functionType == null ? DynamicTypeImpl.instance : functionType.returnType; ExecutableElement function = _enclosingFunction; bool isSetterWithImplicitReturn = function.hasImplicitReturnType && function is PropertyAccessorElement && function.isSetter; if (!isSetterWithImplicitReturn) { _checkForReturnOfInvalidType(node.expression, expectedReturnType, isArrowFunction: true); } super.visitExpressionFunctionBody(node); } finally { _inAsync = wasInAsync; _inGenerator = wasInGenerator; } } @override void visitExtensionDeclaration(ExtensionDeclaration node) { _enclosingExtension = node.declaredElement; _duplicateDefinitionVerifier.checkExtension(node); _checkForFinalNotInitializedInClass(node.members); _checkForMismatchedAccessorTypesInExtension(node); final name = node.name; if (name != null) { _checkForBuiltInIdentifierAsName( name, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_EXTENSION_NAME); } super.visitExtensionDeclaration(node); _enclosingExtension = null; } @override void visitFieldDeclaration(FieldDeclaration node) { _isInStaticVariableDeclaration = node.isStatic; _isInInstanceVariableDeclaration = !_isInStaticVariableDeclaration; if (_isInInstanceVariableDeclaration) { VariableDeclarationList variables = node.fields; if (variables.isConst) { _errorReporter.reportErrorForToken( CompileTimeErrorCode.CONST_INSTANCE_FIELD, variables.keyword); } } try { _checkForNotInitializedNonNullableStaticField(node); super.visitFieldDeclaration(node); } finally { _isInStaticVariableDeclaration = false; _isInInstanceVariableDeclaration = false; } } @override void visitFieldFormalParameter(FieldFormalParameter node) { _checkForValidField(node); _checkForConstFormalParameter(node); _checkForPrivateOptionalParameter(node); _checkForFieldInitializingFormalRedirectingConstructor(node); _checkForTypeAnnotationDeferredClass(node.type); super.visitFieldFormalParameter(node); } @override void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) { DeclaredIdentifier loopVariable = node.loopVariable; if (loopVariable == null) { // Ignore malformed for statements. return; } if (_checkForEachParts(node, loopVariable.identifier)) { if (loopVariable.isConst) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.FOR_IN_WITH_CONST_VARIABLE, loopVariable); } } super.visitForEachPartsWithDeclaration(node); } @override void visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) { SimpleIdentifier identifier = node.identifier; if (identifier == null) { // Ignore malformed for statements. return; } if (_checkForEachParts(node, identifier)) { _checkForAssignmentToFinal(identifier); } super.visitForEachPartsWithIdentifier(node); } @override void visitFormalParameterList(FormalParameterList node) { _duplicateDefinitionVerifier.checkParameters(node); _checkUseOfCovariantInParameters(node); _checkUseOfDefaultValuesInParameters(node); super.visitFormalParameterList(node); } @override void visitForPartsWithDeclarations(ForPartsWithDeclarations node) { if (node.condition != null) { _checkForNonBoolCondition(node.condition); } if (node.variables != null) { _duplicateDefinitionVerifier.checkForVariables(node.variables); } super.visitForPartsWithDeclarations(node); } @override void visitForPartsWithExpression(ForPartsWithExpression node) { if (node.condition != null) { _checkForNonBoolCondition(node.condition); } super.visitForPartsWithExpression(node); } @override void visitFunctionDeclaration(FunctionDeclaration node) { ExecutableElement functionElement = node.declaredElement; if (functionElement != null && functionElement.enclosingElement is! CompilationUnitElement) { _hiddenElements.declare(functionElement); } ExecutableElement outerFunction = _enclosingFunction; try { SimpleIdentifier identifier = node.name; String methodName = ""; if (identifier != null) { methodName = identifier.name; } _enclosingFunction = functionElement; TypeAnnotation returnType = node.returnType; if (node.isSetter || node.isGetter) { _checkForMismatchedAccessorTypes(node, methodName); if (node.isSetter) { FunctionExpression functionExpression = node.functionExpression; if (functionExpression != null) { _checkForWrongNumberOfParametersForSetter( identifier, functionExpression.parameters); } _checkForNonVoidReturnTypeForSetter(returnType); } } if (node.isSetter) { _checkForInvalidModifierOnBody(node.functionExpression.body, CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER); } _checkForTypeAnnotationDeferredClass(returnType); _checkForIllegalReturnType(returnType); _checkForImplicitDynamicReturn(node.name, node.declaredElement); super.visitFunctionDeclaration(node); } finally { _enclosingFunction = outerFunction; } } @override void visitFunctionExpression(FunctionExpression node) { // If this function expression is wrapped in a function declaration, don't // change the enclosingFunction field. if (node.parent is! FunctionDeclaration) { ExecutableElement outerFunction = _enclosingFunction; try { _enclosingFunction = node.declaredElement; super.visitFunctionExpression(node); } finally { _enclosingFunction = outerFunction; } } else { super.visitFunctionExpression(node); } } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { Expression functionExpression = node.function; if (functionExpression is ExtensionOverride) { return super.visitFunctionExpressionInvocation(node); } DartType expressionType = functionExpression.staticType; if (!_checkForNullableDereference(functionExpression) && !_checkForUseOfVoidResult(functionExpression) && !_checkForUseOfNever(functionExpression) && node.staticElement == null && !_isFunctionType(expressionType)) { _errorReporter.reportErrorForNode( StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION_EXPRESSION, functionExpression); } else if (expressionType is FunctionType) { _typeArgumentsVerifier.checkFunctionExpressionInvocation(node); } _checkForNullableDereference(functionExpression); _requiredParametersVerifier.visitFunctionExpressionInvocation(node); super.visitFunctionExpressionInvocation(node); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { _checkForBuiltInIdentifierAsName( node.name, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME); _checkForDefaultValueInFunctionTypeAlias(node); _checkForTypeAliasCannotReferenceItself_function(node); super.visitFunctionTypeAlias(node); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { bool old = _isInFunctionTypedFormalParameter; _isInFunctionTypedFormalParameter = true; try { _checkForTypeAnnotationDeferredClass(node.returnType); // TODO(jmesserly): ideally we'd use _checkForImplicitDynamicReturn, and // we can get the function element via `node?.element?.type?.element` but // it doesn't have hasImplicitReturnType set correctly. if (!_options.implicitDynamic && node.returnType == null) { DartType parameterType = node.declaredElement.type; if (parameterType is FunctionType && parameterType.returnType.isDynamic) { _errorReporter.reportErrorForNode( StrongModeCode.IMPLICIT_DYNAMIC_RETURN, node.identifier, [node.identifier]); } } super.visitFunctionTypedFormalParameter(node); } finally { _isInFunctionTypedFormalParameter = old; } } @override void visitGenericTypeAlias(GenericTypeAlias node) { if (_hasTypedefSelfReference(node.declaredElement)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.TYPE_ALIAS_CANNOT_REFERENCE_ITSELF, node); } super.visitGenericTypeAlias(node); } @override void visitIfElement(IfElement node) { _checkForNonBoolCondition(node.condition); super.visitIfElement(node); } @override void visitIfStatement(IfStatement node) { _checkForNonBoolCondition(node.condition); super.visitIfStatement(node); } @override void visitImplementsClause(ImplementsClause node) { node.interfaces.forEach(_checkForImplicitDynamicType); super.visitImplementsClause(node); } @override void visitImportDirective(ImportDirective node) { ImportElement importElement = node.element; if (node.prefix != null) { _checkForBuiltInIdentifierAsName( node.prefix, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_PREFIX_NAME); } if (importElement != null) { _checkForImportDuplicateLibraryName(node, importElement); _checkForImportInternalLibrary(node, importElement); } super.visitImportDirective(node); } @override void visitIndexExpression(IndexExpression node) { _checkForArgumentTypeNotAssignableForArgument(node.index); if (!node.isNullAware) { _checkForNullableDereference(node.target); } super.visitIndexExpression(node); } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { bool wasInConstInstanceCreation = _isInConstInstanceCreation; _isInConstInstanceCreation = node.isConst; try { ConstructorName constructorName = node.constructorName; TypeName typeName = constructorName.type; DartType type = typeName.type; if (type is InterfaceType) { _checkForConstOrNewWithAbstractClass(node, typeName, type); _checkForConstOrNewWithEnum(node, typeName, type); _checkForConstOrNewWithMixin(node, typeName, type); _requiredParametersVerifier.visitInstanceCreationExpression(node); if (_isInConstInstanceCreation) { _checkForConstWithNonConst(node); _checkForConstWithUndefinedConstructor( node, constructorName, typeName); _checkForConstDeferredClass(node, constructorName, typeName); } else { _checkForNewWithUndefinedConstructor(node, constructorName, typeName); } _checkForListConstructor(node, type); } _checkForImplicitDynamicType(typeName); super.visitInstanceCreationExpression(node); } finally { _isInConstInstanceCreation = wasInConstInstanceCreation; } } @override void visitIntegerLiteral(IntegerLiteral node) { _checkForOutOfRange(node); super.visitIntegerLiteral(node); } @override void visitInterpolationExpression(InterpolationExpression node) { _checkForUseOfVoidResult(node.expression); super.visitInterpolationExpression(node); } @override void visitIsExpression(IsExpression node) { _checkForTypeAnnotationDeferredClass(node.type); _checkForUseOfVoidResult(node.expression); super.visitIsExpression(node); } @override void visitListLiteral(ListLiteral node) { _typeArgumentsVerifier.checkListLiteral(node); _checkForListElementTypeNotAssignable(node); super.visitListLiteral(node); } @override void visitMethodDeclaration(MethodDeclaration node) { ExecutableElement previousFunction = _enclosingFunction; try { _isInStaticMethod = node.isStatic; _enclosingFunction = node.declaredElement; TypeAnnotation returnType = node.returnType; if (node.isSetter) { _checkForInvalidModifierOnBody( node.body, CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER); _checkForWrongNumberOfParametersForSetter(node.name, node.parameters); _checkForNonVoidReturnTypeForSetter(returnType); } else if (node.isOperator) { _checkForOptionalParameterInOperator(node); _checkForWrongNumberOfParametersForOperator(node); _checkForNonVoidReturnTypeForOperator(node); } _checkForExtensionDeclaresMemberOfObject(node); _checkForTypeAnnotationDeferredClass(returnType); _checkForIllegalReturnType(returnType); _checkForImplicitDynamicReturn(node, node.declaredElement); _checkForMustCallSuper(node); super.visitMethodDeclaration(node); } finally { _enclosingFunction = previousFunction; _isInStaticMethod = false; } } @override void visitMethodInvocation(MethodInvocation node) { Expression target = node.realTarget; SimpleIdentifier methodName = node.methodName; if (target != null) { ClassElement typeReference = ElementResolver.getTypeReference(target); _checkForStaticAccessToInstanceMember(typeReference, methodName); _checkForInstanceAccessToStaticMember( typeReference, node.target, methodName); _checkForUnnecessaryNullAware(target, node.operator); } else { _checkForUnqualifiedReferenceToNonLocalStaticMember(methodName); _checkForNullableDereference(node.function); } _typeArgumentsVerifier.checkMethodInvocation(node); _checkForNullableDereference(methodName); _requiredParametersVerifier.visitMethodInvocation(node); if (!node.isNullAware && methodName.name != 'toString' && methodName.name != 'noSuchMethod') { _checkForNullableDereference(target); } super.visitMethodInvocation(node); } @override void visitMixinDeclaration(MixinDeclaration node) { // TODO(scheglov) Verify for all mixin errors. ClassElementImpl outerClass = _enclosingClass; try { _enclosingClass = AbstractClassElementImpl.getImpl(node.declaredElement); List<ClassMember> members = node.members; _duplicateDefinitionVerifier.checkMixin(node); _checkForBuiltInIdentifierAsName( node.name, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME); _checkForMemberWithClassName(); _checkForConflictingTypeVariableErrorCodes(); OnClause onClause = node.onClause; ImplementsClause implementsClause = node.implementsClause; // Only do error checks only if there is a non-null clause. if (onClause != null || implementsClause != null) { _checkMixinInheritance(node, onClause, implementsClause); } _initializeInitialFieldElementsMap(_enclosingClass.fields); _checkForFinalNotInitializedInClass(members); _checkForWrongTypeParameterVarianceInSuperinterfaces(); // _checkForBadFunctionUse(node); super.visitMixinDeclaration(node); } finally { _initialFieldElementsMap = null; _enclosingClass = outerClass; } } @override void visitNativeClause(NativeClause node) { // TODO(brianwilkerson) Figure out the right rule for when 'native' is // allowed. if (!_isInSystemLibrary) { _errorReporter.reportErrorForNode( ParserErrorCode.NATIVE_CLAUSE_IN_NON_SDK_CODE, node); } super.visitNativeClause(node); } @override void visitNativeFunctionBody(NativeFunctionBody node) { _checkForNativeFunctionBodyInNonSdkCode(node); super.visitNativeFunctionBody(node); } @override void visitPostfixExpression(PostfixExpression node) { if (node.operator.type == TokenType.BANG) { _checkForUseOfVoidResult(node); _checkForUnnecessaryNullAware(node.operand, node.operator); } else { _checkForAssignmentToFinal(node.operand); _checkForIntNotAssignable(node.operand); _checkForNullableDereference(node.operand); } super.visitPostfixExpression(node); } @override void visitPrefixedIdentifier(PrefixedIdentifier node) { if (node.parent is! Annotation) { ClassElement typeReference = ElementResolver.getTypeReference(node.prefix); SimpleIdentifier name = node.identifier; _checkForStaticAccessToInstanceMember(typeReference, name); _checkForInstanceAccessToStaticMember(typeReference, node.prefix, name); } String property = node.identifier.name; if (node.staticElement is ExecutableElement && !_objectPropertyNames.contains(property)) { _checkForNullableDereference(node.prefix); } super.visitPrefixedIdentifier(node); } @override void visitPrefixExpression(PrefixExpression node) { TokenType operatorType = node.operator.type; Expression operand = node.operand; if (operatorType == TokenType.BANG) { _checkForNonBoolNegationExpression(operand); } else { if (operatorType.isIncrementOperator) { _checkForAssignmentToFinal(operand); } _checkForNullableDereference(operand); _checkForUseOfVoidResult(operand); _checkForIntNotAssignable(operand); } super.visitPrefixExpression(node); } @override void visitPropertyAccess(PropertyAccess node) { ClassElement typeReference = ElementResolver.getTypeReference(node.realTarget); SimpleIdentifier propertyName = node.propertyName; _checkForStaticAccessToInstanceMember(typeReference, propertyName); _checkForInstanceAccessToStaticMember( typeReference, node.target, propertyName); if (!node.isNullAware && !_objectPropertyNames.contains(propertyName.name)) { _checkForNullableDereference(node.target); } _checkForUnnecessaryNullAware(node.target, node.operator); super.visitPropertyAccess(node); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { _requiredParametersVerifier.visitRedirectingConstructorInvocation(node); _isInConstructorInitializer = true; try { super.visitRedirectingConstructorInvocation(node); } finally { _isInConstructorInitializer = false; } } @override void visitRethrowExpression(RethrowExpression node) { _checkForRethrowOutsideCatch(node); super.visitRethrowExpression(node); } @override void visitReturnStatement(ReturnStatement node) { if (node.expression == null) { _returnsWithout.add(node); } else { _returnsWith.add(node); } _checkForAllReturnStatementErrorCodes(node); super.visitReturnStatement(node); } @override void visitSetOrMapLiteral(SetOrMapLiteral node) { if (node.isMap) { _typeArgumentsVerifier.checkMapLiteral(node); _checkForMapTypeNotAssignable(node); _checkForNonConstMapAsExpressionStatement3(node); } else if (node.isSet) { _typeArgumentsVerifier.checkSetLiteral(node); _checkForSetElementTypeNotAssignable3(node); } super.visitSetOrMapLiteral(node); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { _checkForConstFormalParameter(node); _checkForPrivateOptionalParameter(node); _checkForTypeAnnotationDeferredClass(node.type); // Checks for an implicit dynamic parameter type. // // We can skip other parameter kinds besides simple formal, because: // - DefaultFormalParameter contains a simple one, so it gets here, // - FieldFormalParameter error should be reported on the field, // - FunctionTypedFormalParameter is a function type, not dynamic. _checkForImplicitDynamicIdentifier(node, node.identifier); super.visitSimpleFormalParameter(node); } @override void visitSimpleIdentifier(SimpleIdentifier node) { _checkForAmbiguousImport(node); _checkForReferenceBeforeDeclaration(node); _checkForImplicitThisReferenceInInitializer(node); _checkForTypeParameterReferencedByStatic(node); if (!_isUnqualifiedReferenceToNonLocalStaticMemberAllowed(node)) { _checkForUnqualifiedReferenceToNonLocalStaticMember(node); } super.visitSimpleIdentifier(node); } @override void visitSpreadElement(SpreadElement node) { if (!node.isNullAware) { _checkForNullableDereference(node.expression); } else { _checkForUnnecessaryNullAware(node.expression, node.spreadOperator); } super.visitSpreadElement(node); } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { _requiredParametersVerifier.visitSuperConstructorInvocation(node); _isInConstructorInitializer = true; try { super.visitSuperConstructorInvocation(node); } finally { _isInConstructorInitializer = false; } } @override void visitSwitchCase(SwitchCase node) { _duplicateDefinitionVerifier.checkStatements(node.statements); super.visitSwitchCase(node); } @override void visitSwitchDefault(SwitchDefault node) { _duplicateDefinitionVerifier.checkStatements(node.statements); super.visitSwitchDefault(node); } @override void visitSwitchStatement(SwitchStatement node) { _checkForSwitchExpressionNotAssignable(node); _checkForCaseBlocksNotTerminated(node); _checkForMissingEnumConstantInSwitch(node); super.visitSwitchStatement(node); } @override void visitThisExpression(ThisExpression node) { _checkForInvalidReferenceToThis(node); super.visitThisExpression(node); } @override void visitThrowExpression(ThrowExpression node) { _checkForConstEvalThrowsException(node); _checkForNullableDereference(node.expression); _checkForUseOfVoidResult(node.expression); super.visitThrowExpression(node); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { _checkForFinalNotInitialized(node.variables); _checkForNotInitializedNonNullableVariable(node.variables); super.visitTopLevelVariableDeclaration(node); } @override void visitTypeArgumentList(TypeArgumentList node) { NodeList<TypeAnnotation> list = node.arguments; for (TypeAnnotation type in list) { _checkForTypeAnnotationDeferredClass(type); } super.visitTypeArgumentList(node); } @override void visitTypeName(TypeName node) { _typeArgumentsVerifier.checkTypeName(node); super.visitTypeName(node); } @override void visitTypeParameter(TypeParameter node) { _checkForBuiltInIdentifierAsName(node.name, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME); _checkForTypeAnnotationDeferredClass(node.bound); _checkForImplicitDynamicType(node.bound); _checkForGenericFunctionType(node.bound); node.bound?.accept(_uninstantiatedBoundChecker); super.visitTypeParameter(node); } @override void visitTypeParameterList(TypeParameterList node) { _duplicateDefinitionVerifier.checkTypeParameters(node); _checkForTypeParameterBoundRecursion(node.typeParameters); super.visitTypeParameterList(node); } @override void visitVariableDeclaration(VariableDeclaration node) { SimpleIdentifier nameNode = node.name; Expression initializerNode = node.initializer; // do checks _checkForInvalidAssignment(nameNode, initializerNode); _checkForImplicitDynamicIdentifier(node, nameNode); // visit name nameNode.accept(this); // visit initializer String name = nameNode.name; _namesForReferenceToDeclaredVariableInInitializer.add(name); bool wasInInstanceVariableInitializer = _isInInstanceVariableInitializer; _isInInstanceVariableInitializer = _isInInstanceVariableDeclaration; try { if (initializerNode != null) { initializerNode.accept(this); } } finally { _isInInstanceVariableInitializer = wasInInstanceVariableInitializer; _namesForReferenceToDeclaredVariableInInitializer.remove(name); } // declare the variable AstNode grandparent = node.parent.parent; if (grandparent is! TopLevelVariableDeclaration && grandparent is! FieldDeclaration) { VariableElement element = node.declaredElement; if (element != null) { // There is no hidden elements if we are outside of a function body, // which will happen for variables declared in control flow elements. _hiddenElements?.declare(element); } } } @override void visitVariableDeclarationList(VariableDeclarationList node) { _checkForTypeAnnotationDeferredClass(node.type); super.visitVariableDeclarationList(node); } @override void visitVariableDeclarationStatement(VariableDeclarationStatement node) { _checkForFinalNotInitialized(node.variables); super.visitVariableDeclarationStatement(node); } @override void visitWhileStatement(WhileStatement node) { _checkForNonBoolCondition(node.condition); super.visitWhileStatement(node); } @override void visitWithClause(WithClause node) { node.mixinTypes.forEach(_checkForImplicitDynamicType); super.visitWithClause(node); } @override void visitYieldStatement(YieldStatement node) { if (_inGenerator) { _checkForYieldOfInvalidType(node.expression, node.star != null); if (node.star != null) { _checkForNullableDereference(node.expression); } } else { CompileTimeErrorCode errorCode; if (node.star != null) { errorCode = CompileTimeErrorCode.YIELD_EACH_IN_NON_GENERATOR; } else { errorCode = CompileTimeErrorCode.YIELD_IN_NON_GENERATOR; } _errorReporter.reportErrorForNode(errorCode, node); } _checkForUseOfVoidResult(node.expression); super.visitYieldStatement(node); } /** * Checks the class for problems with the superclass, mixins, or implemented * interfaces. */ void _checkClassInheritance( NamedCompilationUnitMember node, TypeName superclass, WithClause withClause, ImplementsClause implementsClause) { // Only check for all of the inheritance logic around clauses if there // isn't an error code such as "Cannot extend double" already on the // class. if (!_checkForExtendsDisallowedClass(superclass) && !_checkForImplementsClauseErrorCodes(implementsClause) && !_checkForAllMixinErrorCodes(withClause)) { _checkForImplicitDynamicType(superclass); _checkForExtendsDeferredClass(superclass); _checkForConflictingClassMembers(); _checkForRepeatedType(implementsClause?.interfaces, CompileTimeErrorCode.IMPLEMENTS_REPEATED); _checkImplementsSuperClass(implementsClause); _checkMixinInference(node, withClause); _checkForMixinWithConflictingPrivateMember(withClause, superclass); if (!disableConflictingGenericsCheck) { _checkForConflictingGenerics(node); } } } /** * Given a list of [directives] that have the same prefix, generate an error * if there is more than one import and any of those imports is deferred. * * See [CompileTimeErrorCode.SHARED_DEFERRED_PREFIX]. */ void _checkDeferredPrefixCollision(List<ImportDirective> directives) { int count = directives.length; if (count > 1) { for (int i = 0; i < count; i++) { Token deferredToken = directives[i].deferredKeyword; if (deferredToken != null) { _errorReporter.reportErrorForToken( CompileTimeErrorCode.SHARED_DEFERRED_PREFIX, deferredToken); } } } } /** * Check that return statements without expressions are not in a generative * constructor and the return type is not assignable to `null`; that is, we * don't have `return;` if the enclosing method has a non-void containing * return type. * * See [CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR], * [StaticWarningCode.RETURN_WITHOUT_VALUE], and * [StaticTypeWarningCode.RETURN_OF_INVALID_TYPE]. */ void _checkForAllEmptyReturnStatementErrorCodes( ReturnStatement statement, DartType expectedReturnType) { if (_inGenerator) { return; } var returnType = _inAsync ? _typeSystem.flatten(expectedReturnType) : expectedReturnType; if (returnType.isDynamic || returnType.isDartCoreNull || returnType.isVoid) { return; } // If we reach here, this is an invalid return _hasReturnWithoutValue = true; _errorReporter.reportErrorForNode( StaticWarningCode.RETURN_WITHOUT_VALUE, statement); return; } /** * Verify that the given [constructor] declaration does not violate any of the * error codes relating to the initialization of fields in the enclosing * class. * * See [_initialFieldElementsMap], * [StaticWarningCode.FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR], and * [CompileTimeErrorCode.FINAL_INITIALIZED_MULTIPLE_TIMES]. */ void _checkForAllFinalInitializedErrorCodes( ConstructorDeclaration constructor) { if (constructor.factoryKeyword != null || constructor.redirectedConstructor != null || constructor.externalKeyword != null) { return; } // Ignore if native class. if (_isInNativeClass) { return; } Map<FieldElement, INIT_STATE> fieldElementsMap = new HashMap<FieldElement, INIT_STATE>.from(_initialFieldElementsMap); // Visit all of the field formal parameters NodeList<FormalParameter> formalParameters = constructor.parameters.parameters; for (FormalParameter formalParameter in formalParameters) { FormalParameter baseParameter(FormalParameter parameter) { if (parameter is DefaultFormalParameter) { return parameter.parameter; } return parameter; } FormalParameter parameter = baseParameter(formalParameter); if (parameter is FieldFormalParameter) { FieldElement fieldElement = (parameter.declaredElement as FieldFormalParameterElementImpl) .field; INIT_STATE state = fieldElementsMap[fieldElement]; if (state == INIT_STATE.NOT_INIT) { fieldElementsMap[fieldElement] = INIT_STATE.INIT_IN_FIELD_FORMAL; } else if (state == INIT_STATE.INIT_IN_DECLARATION) { if (fieldElement.isFinal || fieldElement.isConst) { _errorReporter.reportErrorForNode( StaticWarningCode .FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR, formalParameter.identifier, [fieldElement.displayName]); } } else if (state == INIT_STATE.INIT_IN_FIELD_FORMAL) { if (fieldElement.isFinal || fieldElement.isConst) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.FINAL_INITIALIZED_MULTIPLE_TIMES, formalParameter.identifier, [fieldElement.displayName]); } } } } // Visit all of the initializers NodeList<ConstructorInitializer> initializers = constructor.initializers; for (ConstructorInitializer constructorInitializer in initializers) { if (constructorInitializer is RedirectingConstructorInvocation) { return; } if (constructorInitializer is ConstructorFieldInitializer) { SimpleIdentifier fieldName = constructorInitializer.fieldName; Element element = fieldName.staticElement; if (element is FieldElement) { INIT_STATE state = fieldElementsMap[element]; if (state == INIT_STATE.NOT_INIT) { fieldElementsMap[element] = INIT_STATE.INIT_IN_INITIALIZERS; } else if (state == INIT_STATE.INIT_IN_DECLARATION) { if (element.isFinal || element.isConst) { _errorReporter.reportErrorForNode( StaticWarningCode .FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION, fieldName); } } else if (state == INIT_STATE.INIT_IN_FIELD_FORMAL) { _errorReporter.reportErrorForNode( CompileTimeErrorCode .FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER, fieldName); } else if (state == INIT_STATE.INIT_IN_INITIALIZERS) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS, fieldName, [element.displayName]); } } } } // Prepare lists of not initialized fields. List<FieldElement> notInitFinalFields = <FieldElement>[]; List<FieldElement> notInitNonNullableFields = <FieldElement>[]; fieldElementsMap.forEach((FieldElement field, INIT_STATE state) { if (state != INIT_STATE.NOT_INIT) return; if (field.isLate) return; if (field.isFinal) { notInitFinalFields.add(field); } else if (_isNonNullable && _typeSystem.isPotentiallyNonNullable(field.type)) { notInitNonNullableFields.add(field); } }); // Visit all of the states in the map to ensure that none were never // initialized. fieldElementsMap.forEach((FieldElement fieldElement, INIT_STATE state) { if (state == INIT_STATE.NOT_INIT) { if (fieldElement.isConst) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_NOT_INITIALIZED, constructor.returnType, [fieldElement.name]); } } }); if (notInitFinalFields.isNotEmpty) { List<String> names = notInitFinalFields.map((item) => item.name).toList(); names.sort(); if (names.length == 1) { _errorReporter.reportErrorForNode( StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_1, constructor.returnType, names); } else if (names.length == 2) { _errorReporter.reportErrorForNode( StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_2, constructor.returnType, names); } else { _errorReporter.reportErrorForNode( StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS, constructor.returnType, [names[0], names[1], names.length - 2]); } } if (notInitNonNullableFields.isNotEmpty) { var names = notInitNonNullableFields.map((f) => f.name).toList()..sort(); for (var name in names) { _errorReporter.reportErrorForNode( CompileTimeErrorCode .NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD_CONSTRUCTOR, constructor.returnType, [name]); } } } /** * Verify that all classes of the given [withClause] are valid. * * See [CompileTimeErrorCode.MIXIN_CLASS_DECLARES_CONSTRUCTOR], * [CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT], and * [CompileTimeErrorCode.MIXIN_REFERENCES_SUPER]. */ bool _checkForAllMixinErrorCodes(WithClause withClause) { if (withClause == null) { return false; } bool problemReported = false; int mixinTypeIndex = -1; for (int mixinNameIndex = 0; mixinNameIndex < withClause.mixinTypes.length; mixinNameIndex++) { TypeName mixinName = withClause.mixinTypes[mixinNameIndex]; DartType mixinType = mixinName.type; if (mixinType is InterfaceType) { mixinTypeIndex++; if (_checkForExtendsOrImplementsDisallowedClass( mixinName, CompileTimeErrorCode.MIXIN_OF_DISALLOWED_CLASS)) { problemReported = true; } else { ClassElement mixinElement = mixinType.element; if (_checkForExtendsOrImplementsDeferredClass( mixinName, CompileTimeErrorCode.MIXIN_DEFERRED_CLASS)) { problemReported = true; } if (mixinElement.isMixin) { if (_checkForMixinSuperclassConstraints( mixinNameIndex, mixinName)) { problemReported = true; } else if (_checkForMixinSuperInvokedMembers( mixinTypeIndex, mixinName, mixinElement, mixinType)) { problemReported = true; } } else { if (_checkForMixinClassDeclaresConstructor( mixinName, mixinElement)) { problemReported = true; } if (_checkForMixinInheritsNotFromObject(mixinName, mixinElement)) { problemReported = true; } if (_checkForMixinReferencesSuper(mixinName, mixinElement)) { problemReported = true; } } } } } return problemReported; } /** * Check for errors related to the redirected constructors. */ void _checkForAllRedirectConstructorErrorCodes( ConstructorDeclaration declaration) { // Prepare redirected constructor node ConstructorName redirectedConstructor = declaration.redirectedConstructor; if (redirectedConstructor == null) { return; } // Prepare redirected constructor type ConstructorElement redirectedElement = redirectedConstructor.staticElement; if (redirectedElement == null) { // If the element is null, we check for the // REDIRECT_TO_MISSING_CONSTRUCTOR case TypeName constructorTypeName = redirectedConstructor.type; DartType redirectedType = constructorTypeName.type; if (redirectedType != null && redirectedType.element != null && !redirectedType.isDynamic) { // Prepare the constructor name String constructorStrName = constructorTypeName.name.name; if (redirectedConstructor.name != null) { constructorStrName += ".${redirectedConstructor.name.name}"; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.REDIRECT_TO_MISSING_CONSTRUCTOR, redirectedConstructor, [constructorStrName, redirectedType.displayName]); } return; } FunctionType redirectedType = redirectedElement.type; DartType redirectedReturnType = redirectedType.returnType; // Report specific problem when return type is incompatible FunctionType constructorType = declaration.declaredElement.type; DartType constructorReturnType = constructorType.returnType; if (!_typeSystem.isAssignableTo(redirectedReturnType, constructorReturnType, featureSet: _featureSet)) { _errorReporter.reportErrorForNode( StaticWarningCode.REDIRECT_TO_INVALID_RETURN_TYPE, redirectedConstructor, [redirectedReturnType, constructorReturnType]); return; } else if (!_typeSystem.isSubtypeOf(redirectedType, constructorType)) { // Check parameters. _errorReporter.reportErrorForNode( StaticWarningCode.REDIRECT_TO_INVALID_FUNCTION_TYPE, redirectedConstructor, [redirectedType, constructorType]); } } /** * Check that the return [statement] of the form <i>return e;</i> is not in a * generative constructor. * * Check that return statements without expressions are not in a generative * constructor and the return type is not assignable to `null`; that is, we * don't have `return;` if the enclosing method has a non-void containing * return type. * * Check that the return type matches the type of the declared return type in * the enclosing method or function. * * See [CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR], * [StaticWarningCode.RETURN_WITHOUT_VALUE], and * [StaticTypeWarningCode.RETURN_OF_INVALID_TYPE]. */ void _checkForAllReturnStatementErrorCodes(ReturnStatement statement) { FunctionType functionType = _enclosingFunction?.type; DartType expectedReturnType = functionType == null ? DynamicTypeImpl.instance : functionType.returnType; Expression returnExpression = statement.expression; // RETURN_IN_GENERATIVE_CONSTRUCTOR bool isGenerativeConstructor(ExecutableElement element) => element is ConstructorElement && !element.isFactory; if (isGenerativeConstructor(_enclosingFunction)) { if (returnExpression == null) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR, returnExpression); return; } // RETURN_WITHOUT_VALUE if (returnExpression == null) { _checkForAllEmptyReturnStatementErrorCodes(statement, expectedReturnType); return; } else if (_inGenerator) { // RETURN_IN_GENERATOR _errorReporter.reportErrorForNode( CompileTimeErrorCode.RETURN_IN_GENERATOR, statement, [_inAsync ? "async*" : "sync*"]); return; } _checkForReturnOfInvalidType(returnExpression, expectedReturnType); } /** * Verify that the export namespace of the given export [directive] does not * export any name already exported by another export directive. The * [exportElement] is the [ExportElement] retrieved from the node. If the * element in the node was `null`, then this method is not called. The * [exportedLibrary] is the library element containing the exported element. * * See [CompileTimeErrorCode.AMBIGUOUS_EXPORT]. */ void _checkForAmbiguousExport(ExportDirective directive, ExportElement exportElement, LibraryElement exportedLibrary) { if (exportedLibrary == null) { return; } // check exported names Namespace namespace = new NamespaceBuilder().createExportNamespaceForDirective(exportElement); Map<String, Element> definedNames = namespace.definedNames; for (String name in definedNames.keys) { Element element = definedNames[name]; Element prevElement = _exportedElements[name]; if (element != null && prevElement != null && prevElement != element) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.AMBIGUOUS_EXPORT, directive, [ name, prevElement.library.definingCompilationUnit.source.uri, element.library.definingCompilationUnit.source.uri ]); return; } else { _exportedElements[name] = element; } } } /** * Check the given node to see whether it was ambiguous because the name was * imported from two or more imports. */ void _checkForAmbiguousImport(SimpleIdentifier node) { Element element = node.staticElement; if (element is MultiplyDefinedElementImpl) { String name = element.displayName; List<Element> conflictingMembers = element.conflictingElements; int count = conflictingMembers.length; List<String> libraryNames = new List<String>(count); for (int i = 0; i < count; i++) { libraryNames[i] = _getLibraryName(conflictingMembers[i]); } libraryNames.sort(); _errorReporter.reportErrorForNode(StaticWarningCode.AMBIGUOUS_IMPORT, node, [name, StringUtilities.printListOfQuotedNames(libraryNames)]); } } /** * Verify that the given [expression] can be assigned to its corresponding * parameters. The [expectedStaticType] is the expected static type of the * parameter. The [actualStaticType] is the actual static type of the * argument. */ void _checkForArgumentTypeNotAssignable( Expression expression, DartType expectedStaticType, DartType actualStaticType, ErrorCode errorCode) { // Warning case: test static type information if (actualStaticType != null && expectedStaticType != null) { if (!expectedStaticType.isVoid && _checkForUseOfVoidResult(expression)) { return; } _checkForAssignableExpressionAtType( expression, actualStaticType, expectedStaticType, errorCode); } } /** * Verify that the given [argument] can be assigned to its corresponding * parameter. * * This method corresponds to * [BestPracticesVerifier.checkForArgumentTypeNotAssignableForArgument]. * * See [StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE]. */ void _checkForArgumentTypeNotAssignableForArgument(Expression argument, {bool promoteParameterToNullable = false}) { if (argument == null) { return; } ParameterElement staticParameterElement = argument.staticParameterElement; DartType staticParameterType = staticParameterElement?.type; if (promoteParameterToNullable && staticParameterType != null) { staticParameterType = _typeSystem.makeNullable(staticParameterType); } _checkForArgumentTypeNotAssignableWithExpectedTypes(argument, staticParameterType, StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE); } /** * Verify that the given [expression] can be assigned to its corresponding * parameters. The [expectedStaticType] is the expected static type. * * This method corresponds to * [BestPracticesVerifier.checkForArgumentTypeNotAssignableWithExpectedTypes]. * * See [StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE], * [CompileTimeErrorCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE], * [StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE], * [CompileTimeErrorCode.MAP_KEY_TYPE_NOT_ASSIGNABLE], * [CompileTimeErrorCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE], * [StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE], and * [StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE]. */ void _checkForArgumentTypeNotAssignableWithExpectedTypes( Expression expression, DartType expectedStaticType, ErrorCode errorCode) { _checkForArgumentTypeNotAssignable( expression, expectedStaticType, getStaticType(expression), errorCode); } /** * Verify that the arguments in the given [argumentList] can be assigned to * their corresponding parameters. * * This method corresponds to * [BestPracticesVerifier.checkForArgumentTypesNotAssignableInList]. * * See [StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE]. */ void _checkForArgumentTypesNotAssignableInList(ArgumentList argumentList) { if (argumentList == null) { return; } for (Expression argument in argumentList.arguments) { _checkForArgumentTypeNotAssignableForArgument(argument); } } /** * Check that the static type of the given expression is assignable to the * given type. If it isn't, report an error with the given error code. The * [type] is the type that the expression must be assignable to. The * [errorCode] is the error code to be reported. The [arguments] are the * arguments to pass in when creating the error. */ void _checkForAssignability(Expression expression, InterfaceType type, ErrorCode errorCode, List<Object> arguments) { if (expression == null) { return; } DartType expressionType = expression.staticType; if (expressionType == null) { return; } if (_typeSystem.isAssignableTo(expressionType, type, featureSet: _featureSet)) { return; } if (expressionType.element == type.element) { _errorReporter.reportErrorForNode( StaticWarningCode.UNCHECKED_USE_OF_NULLABLE_VALUE, expression); } else { _errorReporter.reportErrorForNode(errorCode, expression, arguments); } } bool _checkForAssignableExpression( Expression expression, DartType expectedStaticType, ErrorCode errorCode) { DartType actualStaticType = getStaticType(expression); return actualStaticType != null && _checkForAssignableExpressionAtType( expression, actualStaticType, expectedStaticType, errorCode); } bool _checkForAssignableExpressionAtType( Expression expression, DartType actualStaticType, DartType expectedStaticType, ErrorCode errorCode) { if (!_typeSystem.isAssignableTo(actualStaticType, expectedStaticType, featureSet: _featureSet)) { _errorReporter.reportTypeErrorForNode( errorCode, expression, [actualStaticType, expectedStaticType]); return false; } return true; } /** * Verify that the given [expression] is not final. * * See [StaticWarningCode.ASSIGNMENT_TO_CONST], * [StaticWarningCode.ASSIGNMENT_TO_FINAL], and * [StaticWarningCode.ASSIGNMENT_TO_METHOD]. */ void _checkForAssignmentToFinal(Expression expression) { // prepare element Element element; AstNode highlightedNode = expression; if (expression is Identifier) { element = expression.staticElement; if (expression is PrefixedIdentifier) { highlightedNode = expression.identifier; } } else if (expression is PropertyAccess) { element = expression.propertyName.staticElement; highlightedNode = expression.propertyName; } // check if element is assignable Element toVariable(Element element) { return element is PropertyAccessorElement ? element.variable : element; } element = toVariable(element); if (element is VariableElement) { if (element.isConst) { _errorReporter.reportErrorForNode( StaticWarningCode.ASSIGNMENT_TO_CONST, expression); } else if (element.isFinal && !element.isLate) { if (element is FieldElementImpl) { if (element.setter == null && element.isSynthetic) { _errorReporter.reportErrorForNode( StaticWarningCode.ASSIGNMENT_TO_FINAL_NO_SETTER, highlightedNode, [element.name, element.enclosingElement.displayName]); } else { _errorReporter.reportErrorForNode( StaticWarningCode.ASSIGNMENT_TO_FINAL, highlightedNode, [element.name]); } return; } _errorReporter.reportErrorForNode( StaticWarningCode.ASSIGNMENT_TO_FINAL_LOCAL, highlightedNode, [element.name]); } } else if (element is FunctionElement) { _errorReporter.reportErrorForNode( StaticWarningCode.ASSIGNMENT_TO_FUNCTION, expression); } else if (element is MethodElement) { _errorReporter.reportErrorForNode( StaticWarningCode.ASSIGNMENT_TO_METHOD, expression); } else if (element is ClassElement || element is FunctionTypeAliasElement || element is TypeParameterElement) { _errorReporter.reportErrorForNode( StaticWarningCode.ASSIGNMENT_TO_TYPE, expression); } } /** * Verifies that the class is not named `Function` and that it doesn't * extends/implements/mixes in `Function`. */ void _checkForBadFunctionUse(ClassDeclaration node) { ExtendsClause extendsClause = node.extendsClause; WithClause withClause = node.withClause; if (node.name.name == "Function") { _errorReporter.reportErrorForNode( HintCode.DEPRECATED_FUNCTION_CLASS_DECLARATION, node.name); } if (extendsClause != null) { InterfaceType superclassType = _enclosingClass.supertype; ClassElement superclassElement = superclassType?.element; if (superclassElement != null && superclassElement.name == "Function") { _errorReporter.reportErrorForNode( HintCode.DEPRECATED_EXTENDS_FUNCTION, extendsClause.superclass); } } if (withClause != null) { for (TypeName type in withClause.mixinTypes) { Element mixinElement = type.name.staticElement; if (mixinElement != null && mixinElement.name == "Function") { _errorReporter.reportErrorForNode( HintCode.DEPRECATED_MIXIN_FUNCTION, type); } } } } /** * Verify that the given [identifier] is not a keyword, and generates the * given [errorCode] on the identifier if it is a keyword. * * See [CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_EXTENSION_NAME], * [CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME], * [CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME], and * [CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME]. */ void _checkForBuiltInIdentifierAsName( SimpleIdentifier identifier, ErrorCode errorCode) { Token token = identifier.token; if (token.type.isKeyword && token.keyword?.isPseudo != true) { _errorReporter .reportErrorForNode(errorCode, identifier, [identifier.name]); } } /** * Verify that the given [switchCase] is terminated with 'break', 'continue', * 'return' or 'throw'. * * see [StaticWarningCode.CASE_BLOCK_NOT_TERMINATED]. */ void _checkForCaseBlockNotTerminated(SwitchCase switchCase) { NodeList<Statement> statements = switchCase.statements; if (statements.isEmpty) { // fall-through without statements at all AstNode parent = switchCase.parent; if (parent is SwitchStatement) { NodeList<SwitchMember> members = parent.members; int index = members.indexOf(switchCase); if (index != -1 && index < members.length - 1) { return; } } // no other switch member after this one } else { Statement statement = statements.last; if (statement is Block && statement.statements.isNotEmpty) { Block block = statement; statement = block.statements.last; } // terminated with statement if (statement is BreakStatement || statement is ContinueStatement || statement is ReturnStatement) { return; } // terminated with 'throw' expression if (statement is ExpressionStatement) { Expression expression = statement.expression; if (expression is ThrowExpression || expression is RethrowExpression) { return; } } } _errorReporter.reportErrorForToken( StaticWarningCode.CASE_BLOCK_NOT_TERMINATED, switchCase.keyword); } /** * Verify that the switch cases in the given switch [statement] are terminated * with 'break', 'continue', 'rethrow', 'return' or 'throw'. * * See [StaticWarningCode.CASE_BLOCK_NOT_TERMINATED]. */ void _checkForCaseBlocksNotTerminated(SwitchStatement statement) { NodeList<SwitchMember> members = statement.members; int lastMember = members.length - 1; for (int i = 0; i < lastMember; i++) { SwitchMember member = members[i]; if (member is SwitchCase) { _checkForCaseBlockNotTerminated(member); } } } /** * Verify that the [_enclosingClass] does not have a method and getter pair * with the same name on, via inheritance. * * See [CompileTimeErrorCode.CONFLICTING_STATIC_AND_INSTANCE], * [CompileTimeErrorCode.CONFLICTING_METHOD_AND_FIELD], and * [CompileTimeErrorCode.CONFLICTING_FIELD_AND_METHOD]. */ void _checkForConflictingClassMembers() { if (_enclosingClass == null) { return; } InterfaceType enclosingType = _enclosingClass.thisType; Uri libraryUri = _currentLibrary.source.uri; // method declared in the enclosing class vs. inherited getter/setter for (MethodElement method in _enclosingClass.methods) { String name = method.name; // find inherited property accessor ExecutableElement inherited = _inheritanceManager.getInherited( enclosingType, new Name(libraryUri, name)); inherited ??= _inheritanceManager.getInherited( enclosingType, new Name(libraryUri, '$name=')); if (method.isStatic && inherited != null) { _errorReporter.reportErrorForElement( CompileTimeErrorCode.CONFLICTING_STATIC_AND_INSTANCE, method, [ _enclosingClass.displayName, name, inherited.enclosingElement.displayName, ]); } else if (inherited is PropertyAccessorElement) { _errorReporter.reportErrorForElement( CompileTimeErrorCode.CONFLICTING_METHOD_AND_FIELD, method, [ _enclosingClass.displayName, name, inherited.enclosingElement.displayName ]); } } // getter declared in the enclosing class vs. inherited method for (PropertyAccessorElement accessor in _enclosingClass.accessors) { String name = accessor.displayName; // find inherited method or property accessor ExecutableElement inherited = _inheritanceManager.getInherited( enclosingType, new Name(libraryUri, name)); inherited ??= _inheritanceManager.getInherited( enclosingType, new Name(libraryUri, '$name=')); if (accessor.isStatic && inherited != null) { _errorReporter.reportErrorForElement( CompileTimeErrorCode.CONFLICTING_STATIC_AND_INSTANCE, accessor, [ _enclosingClass.displayName, name, inherited.enclosingElement.displayName, ]); } else if (inherited is MethodElement) { _errorReporter.reportErrorForElement( CompileTimeErrorCode.CONFLICTING_FIELD_AND_METHOD, accessor, [ _enclosingClass.displayName, name, inherited.enclosingElement.displayName ]); } } } void _checkForConflictingGenerics(NamedCompilationUnitMember node) { var visitedClasses = <ClassElement>[]; var interfaces = <ClassElement, InterfaceType>{}; void visit(InterfaceType type) { if (type == null) return; var element = type.element; if (visitedClasses.contains(element)) return; visitedClasses.add(element); if (element.typeParameters.isNotEmpty) { var oldType = interfaces[element]; if (oldType == null) { interfaces[element] = type; } else if (type != oldType) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONFLICTING_GENERIC_INTERFACES, node, [_enclosingClass.name, oldType, type]); } } visit(type.superclass); type.mixins.forEach(visit); type.superclassConstraints.forEach(visit); type.interfaces.forEach(visit); visitedClasses.removeLast(); } visit(_enclosingClass.thisType); } /** * Verify all conflicts between type variable and enclosing class. * TODO(scheglov) * * See [CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_CLASS], and * [CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_MEMBER]. */ void _checkForConflictingTypeVariableErrorCodes() { for (TypeParameterElement typeParameter in _enclosingClass.typeParameters) { String name = typeParameter.name; // name is same as the name of the enclosing class if (_enclosingClass.name == name) { _errorReporter.reportErrorForElement( CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_CLASS, typeParameter, [name]); } // check members if (_enclosingClass.getMethod(name) != null || _enclosingClass.getGetter(name) != null || _enclosingClass.getSetter(name) != null) { _errorReporter.reportErrorForElement( CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_MEMBER, typeParameter, [name]); } } } /** * Verify that if the given [constructor] declaration is 'const' then there * are no invocations of non-'const' super constructors. * * See [CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER]. */ void _checkForConstConstructorWithNonConstSuper( ConstructorDeclaration constructor) { if (!_isEnclosingConstructorConst) { return; } // OK, const factory, checked elsewhere if (constructor.factoryKeyword != null) { return; } // check for mixins var hasInstanceField = false; for (var mixin in _enclosingClass.mixins) { var fields = mixin.element.fields; for (var i = 0; i < fields.length; ++i) { if (!fields[i].isStatic) { hasInstanceField = true; break; } } } if (hasInstanceField) { // TODO(scheglov) Provide the list of fields. _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_MIXIN_WITH_FIELD, constructor.returnType); return; } // try to find and check super constructor invocation for (ConstructorInitializer initializer in constructor.initializers) { if (initializer is SuperConstructorInvocation) { ConstructorElement element = initializer.staticElement; if (element == null || element.isConst) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER, initializer, [element.enclosingElement.displayName]); return; } } // no explicit super constructor invocation, check default constructor InterfaceType supertype = _enclosingClass.supertype; if (supertype == null) { return; } if (supertype.isObject) { return; } ConstructorElement unnamedConstructor = supertype.element.unnamedConstructor; if (unnamedConstructor == null || unnamedConstructor.isConst) { return; } // default constructor is not 'const', report problem _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER, constructor.returnType, [supertype.displayName]); } /** * Verify that if the given [constructor] declaration is 'const' then there * are no non-final instance variable. The [constructorElement] is the * constructor element. * * See [CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD]. */ void _checkForConstConstructorWithNonFinalField( ConstructorDeclaration constructor, ConstructorElement constructorElement) { if (!_isEnclosingConstructorConst) { return; } // check if there is non-final field ClassElement classElement = constructorElement.enclosingElement; if (!classElement.hasNonFinalField) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD, constructor); } /** * Verify that the given 'const' instance creation [expression] is not * creating a deferred type. The [constructorName] is the constructor name, * always non-`null`. The [typeName] is the name of the type defining the * constructor, always non-`null`. * * See [CompileTimeErrorCode.CONST_DEFERRED_CLASS]. */ void _checkForConstDeferredClass(InstanceCreationExpression expression, ConstructorName constructorName, TypeName typeName) { if (typeName.isDeferred) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_DEFERRED_CLASS, constructorName, [typeName.name.name]); } } /** * Verify that the given throw [expression] is not enclosed in a 'const' * constructor declaration. * * See [CompileTimeErrorCode.CONST_CONSTRUCTOR_THROWS_EXCEPTION]. */ void _checkForConstEvalThrowsException(ThrowExpression expression) { if (_isEnclosingConstructorConst) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_CONSTRUCTOR_THROWS_EXCEPTION, expression); } } /** * Verify that the given normal formal [parameter] is not 'const'. * * See [CompileTimeErrorCode.CONST_FORMAL_PARAMETER]. */ void _checkForConstFormalParameter(NormalFormalParameter parameter) { if (parameter.isConst) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_FORMAL_PARAMETER, parameter); } } /** * Verify that the given instance creation [expression] is not being invoked * on an abstract class. The [typeName] is the [TypeName] of the * [ConstructorName] from the [InstanceCreationExpression], this is the AST * node that the error is attached to. The [type] is the type being * constructed with this [InstanceCreationExpression]. * * See [StaticWarningCode.CONST_WITH_ABSTRACT_CLASS], and * [StaticWarningCode.NEW_WITH_ABSTRACT_CLASS]. */ void _checkForConstOrNewWithAbstractClass( InstanceCreationExpression expression, TypeName typeName, InterfaceType type) { if (type.element.isAbstract && !type.element.isMixin) { ConstructorElement element = expression.staticElement; if (element != null && !element.isFactory) { bool isImplicit = (expression as InstanceCreationExpressionImpl).isImplicit; if (!isImplicit) { _errorReporter.reportErrorForNode( expression.isConst ? StaticWarningCode.CONST_WITH_ABSTRACT_CLASS : StaticWarningCode.NEW_WITH_ABSTRACT_CLASS, typeName); } else { // TODO(brianwilkerson/jwren) Create a new different StaticWarningCode // which does not call out the new keyword so explicitly. _errorReporter.reportErrorForNode( StaticWarningCode.NEW_WITH_ABSTRACT_CLASS, typeName); } } } } /** * Verify that the given instance creation [expression] is not being invoked * on an enum. The [typeName] is the [TypeName] of the [ConstructorName] from * the [InstanceCreationExpression], this is the AST node that the error is * attached to. The [type] is the type being constructed with this * [InstanceCreationExpression]. * * See [CompileTimeErrorCode.INSTANTIATE_ENUM]. */ void _checkForConstOrNewWithEnum(InstanceCreationExpression expression, TypeName typeName, InterfaceType type) { if (type.element.isEnum) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INSTANTIATE_ENUM, typeName); } } /** * Verify that the given [expression] is not a mixin instantiation. */ void _checkForConstOrNewWithMixin(InstanceCreationExpression expression, TypeName typeName, InterfaceType type) { if (type.element.isMixin) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MIXIN_INSTANTIATE, typeName); } } /** * Verify that the given 'const' instance creation [expression] is not being * invoked on a constructor that is not 'const'. * * This method assumes that the instance creation was tested to be 'const' * before being called. * * See [CompileTimeErrorCode.CONST_WITH_NON_CONST]. */ void _checkForConstWithNonConst(InstanceCreationExpression expression) { ConstructorElement constructorElement = expression.staticElement; if (constructorElement != null && !constructorElement.isConst) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_WITH_NON_CONST, expression); } } /** * Verify that if the given 'const' instance creation [expression] is being * invoked on the resolved constructor. The [constructorName] is the * constructor name, always non-`null`. The [typeName] is the name of the type * defining the constructor, always non-`null`. * * This method assumes that the instance creation was tested to be 'const' * before being called. * * See [CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR], and * [CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT]. */ void _checkForConstWithUndefinedConstructor( InstanceCreationExpression expression, ConstructorName constructorName, TypeName typeName) { // OK if resolved if (expression.staticElement != null) { return; } DartType type = typeName.type; if (type is InterfaceType) { ClassElement element = type.element; if (element != null && element.isEnum) { // We have already reported the error. return; } } Identifier className = typeName.name; // report as named or default constructor absence SimpleIdentifier name = constructorName.name; if (name != null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR, name, [className, name]); } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT, constructorName, [className]); } } /** * Verify that there are no default parameters in the given function type * [alias]. * * See [CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS]. */ void _checkForDefaultValueInFunctionTypeAlias(FunctionTypeAlias alias) { FormalParameterList formalParameterList = alias.parameters; NodeList<FormalParameter> parameters = formalParameterList.parameters; for (FormalParameter parameter in parameters) { if (parameter is DefaultFormalParameter) { if (parameter.defaultValue != null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS, alias); } } } } /** * Verify that the given default formal [parameter] is not part of a function * typed parameter. * * See [CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER]. */ void _checkForDefaultValueInFunctionTypedParameter( DefaultFormalParameter parameter) { // OK, not in a function typed parameter. if (!_isInFunctionTypedFormalParameter) { return; } // OK, no default value. if (parameter.defaultValue == null) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER, parameter); } /** * Verify that any deferred imports in the given compilation [unit] have a * unique prefix. * * See [CompileTimeErrorCode.SHARED_DEFERRED_PREFIX]. */ void _checkForDeferredPrefixCollisions(CompilationUnit unit) { NodeList<Directive> directives = unit.directives; int count = directives.length; if (count > 0) { Map<PrefixElement, List<ImportDirective>> prefixToDirectivesMap = new HashMap<PrefixElement, List<ImportDirective>>(); for (int i = 0; i < count; i++) { Directive directive = directives[i]; if (directive is ImportDirective) { SimpleIdentifier prefix = directive.prefix; if (prefix != null) { Element element = prefix.staticElement; if (element is PrefixElement) { List<ImportDirective> elements = prefixToDirectivesMap[element]; if (elements == null) { elements = new List<ImportDirective>(); prefixToDirectivesMap[element] = elements; } elements.add(directive); } } } } for (List<ImportDirective> imports in prefixToDirectivesMap.values) { _checkDeferredPrefixCollision(imports); } } } /** * Return `true` if the caller should continue checking the rest of the * information in the for-each part. */ bool _checkForEachParts(ForEachParts node, SimpleIdentifier variable) { if (_checkForNullableDereference(node.iterable)) { return false; } if (_checkForUseOfVoidResult(node.iterable)) { return false; } DartType iterableType = getStaticType(node.iterable); if (iterableType.isDynamic) { return false; } // The type of the loop variable. DartType variableType = getStaticType(variable); AstNode parent = node.parent; Token awaitKeyword; if (parent is ForStatement) { awaitKeyword = parent.awaitKeyword; } else if (parent is ForElement) { awaitKeyword = parent.awaitKeyword; } // Use an explicit string instead of [loopType] to remove the "<E>". String loopTypeName = awaitKeyword != null ? "Stream" : "Iterable"; // The object being iterated has to implement Iterable<T> for some T that // is assignable to the variable's type. // TODO(rnystrom): Move this into mostSpecificTypeArgument()? iterableType = iterableType.resolveToBound(_typeProvider.objectType); ClassElement sequenceElement = awaitKeyword != null ? _typeProvider.streamElement : _typeProvider.iterableElement; DartType bestIterableType; if (iterableType is InterfaceTypeImpl) { var sequenceType = iterableType.asInstanceOf(sequenceElement); if (sequenceType != null) { bestIterableType = sequenceType.typeArguments[0]; } } // Allow it to be a supertype of Iterable<T> (basically just Object) and do // an implicit downcast to Iterable<dynamic>. if (bestIterableType == null) { if (iterableType == _typeProvider.objectType) { bestIterableType = DynamicTypeImpl.instance; } } if (bestIterableType == null) { _errorReporter.reportTypeErrorForNode( StaticTypeWarningCode.FOR_IN_OF_INVALID_TYPE, node.iterable, [iterableType, loopTypeName]); } else if (!_typeSystem.isAssignableTo(bestIterableType, variableType, featureSet: _featureSet)) { _errorReporter.reportTypeErrorForNode( StaticTypeWarningCode.FOR_IN_OF_INVALID_ELEMENT_TYPE, node.iterable, [iterableType, loopTypeName, variableType]); } return true; } /** * Verify that the given export [directive] has a unique name among other * exported libraries. The [exportElement] is the [ExportElement] retrieved * from the node, if the element in the node was `null`, then this method is * not called. The [exportedLibrary] is the library element containing the * exported element. * * See [CompileTimeErrorCode.EXPORT_DUPLICATED_LIBRARY_NAME]. */ void _checkForExportDuplicateLibraryName(ExportDirective directive, ExportElement exportElement, LibraryElement exportedLibrary) { if (exportedLibrary == null) { return; } String name = exportedLibrary.name; // check if there is other exported library with the same name LibraryElement prevLibrary = _nameToExportElement[name]; if (prevLibrary != null) { if (prevLibrary != exportedLibrary) { if (name.isNotEmpty) { _errorReporter.reportErrorForNode( StaticWarningCode.EXPORT_DUPLICATED_LIBRARY_NAMED, directive, [ prevLibrary.definingCompilationUnit.source.uri.toString(), exportedLibrary.definingCompilationUnit.source.uri.toString(), name ]); } return; } } else { _nameToExportElement[name] = exportedLibrary; } } /** * Check that if the visiting library is not system, then any given library * should not be SDK internal library. The [exportElement] is the * [ExportElement] retrieved from the node, if the element in the node was * `null`, then this method is not called. * * See [CompileTimeErrorCode.EXPORT_INTERNAL_LIBRARY]. */ void _checkForExportInternalLibrary( ExportDirective directive, ExportElement exportElement) { if (_isInSystemLibrary) { return; } LibraryElement exportedLibrary = exportElement.exportedLibrary; if (exportedLibrary == null) { return; } // should be private DartSdk sdk = _currentLibrary.context.sourceFactory.dartSdk; String uri = exportedLibrary.source.uri.toString(); SdkLibrary sdkLibrary = sdk.getSdkLibrary(uri); if (sdkLibrary == null) { return; } if (!sdkLibrary.isInternal) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.EXPORT_INTERNAL_LIBRARY, directive, [directive.uri]); } /** * Verify that the given extends [clause] does not extend a deferred class. * * See [CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS]. */ void _checkForExtendsDeferredClass(TypeName superclass) { if (superclass == null) { return; } _checkForExtendsOrImplementsDeferredClass( superclass, CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS); } /** * Verify that the given extends [clause] does not extend classes such as * 'num' or 'String'. * * See [CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS]. */ bool _checkForExtendsDisallowedClass(TypeName superclass) { if (superclass == null) { return false; } return _checkForExtendsOrImplementsDisallowedClass( superclass, CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS); } /** * Verify that the given [typeName] does not extend, implement or mixin * classes that are deferred. * * See [_checkForExtendsDeferredClass], * [_checkForExtendsDeferredClassInTypeAlias], * [_checkForImplementsDeferredClass], * [_checkForAllMixinErrorCodes], * [CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS], * [CompileTimeErrorCode.IMPLEMENTS_DEFERRED_CLASS], and * [CompileTimeErrorCode.MIXIN_DEFERRED_CLASS]. */ bool _checkForExtendsOrImplementsDeferredClass( TypeName typeName, ErrorCode errorCode) { if (typeName.isSynthetic) { return false; } if (typeName.isDeferred) { _errorReporter.reportErrorForNode(errorCode, typeName); return true; } return false; } /** * Verify that the given [typeName] does not extend, implement or mixin * classes such as 'num' or 'String'. * * TODO(scheglov) Remove this method, when all inheritance / override * is concentrated. We keep it for now only because we need to know when * inheritance is completely wrong, so that we don't need to check anything * else. */ bool _checkForExtendsOrImplementsDisallowedClass( TypeName typeName, ErrorCode errorCode) { if (typeName.isSynthetic) { return false; } // The SDK implementation may implement disallowed types. For example, // JSNumber in dart2js and _Smi in Dart VM both implement int. if (_currentLibrary.source.isInSystemLibrary) { return false; } return _DISALLOWED_TYPES_TO_EXTEND_OR_IMPLEMENT.contains(typeName.type); } void _checkForExtensionDeclaresMemberOfObject(MethodDeclaration node) { if (_enclosingExtension == null) return; var name = node.name.name; if (name == '==' || name == 'hashCode' || name == 'toString' || name == 'runtimeType' || name == 'noSuchMethod') { _errorReporter.reportErrorForNode( CompileTimeErrorCode.EXTENSION_DECLARES_MEMBER_OF_OBJECT, node.name, ); } } /** * Verify that the given constructor field [initializer] has compatible field * and initializer expression types. The [fieldElement] is the static element * from the name in the [ConstructorFieldInitializer]. * * See [CompileTimeErrorCode.CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE], and * [StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE]. */ void _checkForFieldInitializerNotAssignable( ConstructorFieldInitializer initializer, FieldElement fieldElement) { // prepare field type DartType fieldType = fieldElement.type; // prepare expression type Expression expression = initializer.expression; if (expression == null) { return; } // test the static type of the expression DartType staticType = getStaticType(expression); if (staticType == null) { return; } if (_typeSystem.isAssignableTo(staticType, fieldType, featureSet: _featureSet)) { return; } // report problem if (_isEnclosingConstructorConst) { // TODO(paulberry): this error should be based on the actual type of the // constant, not the static type. See dartbug.com/21119. _errorReporter.reportTypeErrorForNode( CheckedModeCompileTimeErrorCode .CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE, expression, [staticType, fieldType]); } _errorReporter.reportTypeErrorForNode( StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE, expression, [staticType, fieldType]); // TODO(brianwilkerson) Define a hint corresponding to these errors and // report it if appropriate. // // test the propagated type of the expression // Type propagatedType = expression.getPropagatedType(); // if (propagatedType != null && propagatedType.isAssignableTo(fieldType)) { // return false; // } // // report problem // if (isEnclosingConstructorConst) { // errorReporter.reportTypeErrorForNode( // CompileTimeErrorCode.CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE, // expression, // propagatedType == null ? staticType : propagatedType, // fieldType); // } else { // errorReporter.reportTypeErrorForNode( // StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE, // expression, // propagatedType == null ? staticType : propagatedType, // fieldType); // } // return true; } /** * Verify that the given field formal [parameter] is in a constructor * declaration. * * See [CompileTimeErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR]. */ void _checkForFieldInitializingFormalRedirectingConstructor( FieldFormalParameter parameter) { // prepare the node that should be a ConstructorDeclaration AstNode formalParameterList = parameter.parent; if (formalParameterList is! FormalParameterList) { formalParameterList = formalParameterList?.parent; } AstNode constructor = formalParameterList?.parent; // now check whether the node is actually a ConstructorDeclaration if (constructor is ConstructorDeclaration) { // constructor cannot be a factory if (constructor.factoryKeyword != null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.FIELD_INITIALIZER_FACTORY_CONSTRUCTOR, parameter); return; } // constructor cannot have a redirection for (ConstructorInitializer initializer in constructor.initializers) { if (initializer is RedirectingConstructorInvocation) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR, parameter); return; } } } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR, parameter); } } /** * Verify that the given variable declaration [list] has only initialized * variables if the list is final or const. * * See [CompileTimeErrorCode.CONST_NOT_INITIALIZED], and * [StaticWarningCode.FINAL_NOT_INITIALIZED]. */ void _checkForFinalNotInitialized(VariableDeclarationList list) { if (_isInNativeClass || list.isSynthetic) { return; } bool isConst = list.isConst; if (!(isConst || list.isFinal)) { return; } NodeList<VariableDeclaration> variables = list.variables; for (VariableDeclaration variable in variables) { if (variable.initializer == null) { if (isConst) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONST_NOT_INITIALIZED, variable.name, [variable.name.name]); } else if (!_isNonNullable || !variable.isLate) { _errorReporter.reportErrorForNode( StaticWarningCode.FINAL_NOT_INITIALIZED, variable.name, [variable.name.name]); } } } } /** * If there are no constructors in the given [members], verify that all * final fields are initialized. Cases in which there is at least one * constructor are handled in [_checkForAllFinalInitializedErrorCodes]. * * See [CompileTimeErrorCode.CONST_NOT_INITIALIZED], and * [StaticWarningCode.FINAL_NOT_INITIALIZED]. */ void _checkForFinalNotInitializedInClass(List<ClassMember> members) { for (ClassMember classMember in members) { if (classMember is ConstructorDeclaration) { return; } } for (ClassMember classMember in members) { if (classMember is FieldDeclaration) { var fields = classMember.fields; _checkForFinalNotInitialized(fields); _checkForNotInitializedNonNullableInstanceFields(classMember); } } } void _checkForGenericFunctionType(TypeAnnotation node) { if (node == null) { return; } DartType type = node.type; if (type is FunctionType && type.typeFormals.isNotEmpty) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.GENERIC_FUNCTION_TYPE_CANNOT_BE_BOUND, node, [type]); } } /** * If the current function is async, async*, or sync*, verify that its * declared return type is assignable to Future, Stream, or Iterable, * respectively. If not, report the error using [returnType]. */ void _checkForIllegalReturnType(TypeAnnotation returnType) { if (returnType == null) { // No declared return type, so the return type must be dynamic, which is // assignable to everything. return; } if (_enclosingFunction.isAsynchronous) { if (_enclosingFunction.isGenerator) { _checkForIllegalReturnTypeCode( returnType, _typeProvider.streamElement, StaticTypeWarningCode.ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE, ); } else { _checkForIllegalReturnTypeCode( returnType, _typeProvider.futureElement, StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE, ); } } else if (_enclosingFunction.isGenerator) { _checkForIllegalReturnTypeCode( returnType, _typeProvider.iterableElement, StaticTypeWarningCode.ILLEGAL_SYNC_GENERATOR_RETURN_TYPE, ); } } /** * If the current function is async, async*, or sync*, verify that its * declared return type is assignable to Future, Stream, or Iterable, * respectively. This is called by [_checkForIllegalReturnType] to check if * the declared [returnTypeName] is assignable to the required [expectedType] * and if not report [errorCode]. */ void _checkForIllegalReturnTypeCode(TypeAnnotation returnTypeName, ClassElement expectedElement, StaticTypeWarningCode errorCode) { DartType returnType = _enclosingFunction.returnType; // // When checking an async/sync*/async* method, we know the exact type // that will be returned (e.g. Future, Iterable, or Stream). // // For example an `async` function body will return a `Future<T>` for // some `T` (possibly `dynamic`). // // We allow the declared return type to be a supertype of that // (e.g. `dynamic`, `Object`), or Future<S> for some S. // (We assume the T <: S relation is checked elsewhere.) // // We do not allow user-defined subtypes of Future, because an `async` // method will never return those. // // To check for this, we ensure that `Future<bottom> <: returnType`. // // Similar logic applies for sync* and async*. // var lowerBound = expectedElement.instantiate( typeArguments: [BottomTypeImpl.instance], nullabilitySuffix: NullabilitySuffix.star, ); if (!_typeSystem.isSubtypeOf(lowerBound, returnType)) { _errorReporter.reportErrorForNode(errorCode, returnTypeName); } } /** * Verify that the given implements [clause] does not implement classes such * as 'num' or 'String'. * * See [CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS], * [CompileTimeErrorCode.IMPLEMENTS_DEFERRED_CLASS]. */ bool _checkForImplementsClauseErrorCodes(ImplementsClause clause) { if (clause == null) { return false; } bool foundError = false; for (TypeName type in clause.interfaces) { if (_checkForExtendsOrImplementsDisallowedClass( type, CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS)) { foundError = true; } else if (_checkForExtendsOrImplementsDeferredClass( type, CompileTimeErrorCode.IMPLEMENTS_DEFERRED_CLASS)) { foundError = true; } } return foundError; } void _checkForImplicitDynamicIdentifier(AstNode node, Identifier id) { if (_options.implicitDynamic) { return; } VariableElement variable = getVariableElement(id); if (variable != null && variable.hasImplicitType && variable.type.isDynamic) { ErrorCode errorCode; if (variable is FieldElement) { errorCode = StrongModeCode.IMPLICIT_DYNAMIC_FIELD; } else if (variable is ParameterElement) { errorCode = StrongModeCode.IMPLICIT_DYNAMIC_PARAMETER; } else { errorCode = StrongModeCode.IMPLICIT_DYNAMIC_VARIABLE; } _errorReporter.reportErrorForNode(errorCode, node, [id]); } } void _checkForImplicitDynamicReturn( AstNode functionName, ExecutableElement element) { if (_options.implicitDynamic) { return; } if (element is PropertyAccessorElement && element.isSetter) { return; } if (element != null && element.hasImplicitReturnType && element.returnType.isDynamic) { _errorReporter.reportErrorForNode(StrongModeCode.IMPLICIT_DYNAMIC_RETURN, functionName, [element.displayName]); } } void _checkForImplicitDynamicType(TypeAnnotation node) { if (_options.implicitDynamic || node == null || (node is TypeName && node.typeArguments != null)) { return; } DartType type = node.type; if (type is ParameterizedType && type.typeArguments.isNotEmpty && type.typeArguments.any((t) => t.isDynamic)) { _errorReporter.reportErrorForNode( StrongModeCode.IMPLICIT_DYNAMIC_TYPE, node, [type]); } } /** * Verify that if the given [identifier] is part of a constructor initializer, * then it does not implicitly reference 'this' expression. * * See [CompileTimeErrorCode.IMPLICIT_THIS_REFERENCE_IN_INITIALIZER], and * [CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_STATIC]. * TODO(scheglov) rename thid method */ void _checkForImplicitThisReferenceInInitializer( SimpleIdentifier identifier) { if (!_isInConstructorInitializer && !_isInStaticMethod && !_isInFactory && !_isInInstanceVariableInitializer && !_isInStaticVariableDeclaration) { return; } // prepare element Element element = identifier.staticElement; if (!(element is MethodElement || element is PropertyAccessorElement)) { return; } // static element ExecutableElement executableElement = element as ExecutableElement; if (executableElement.isStatic) { return; } // not a class member Element enclosingElement = element.enclosingElement; if (enclosingElement is! ClassElement) { return; } // comment AstNode parent = identifier.parent; if (parent is CommentReference) { return; } // qualified method invocation if (parent is MethodInvocation) { if (identical(parent.methodName, identifier) && parent.realTarget != null) { return; } } // qualified property access if (parent is PropertyAccess) { if (identical(parent.propertyName, identifier) && parent.realTarget != null) { return; } } if (parent is PrefixedIdentifier) { if (identical(parent.identifier, identifier)) { return; } } if (_isInStaticMethod) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_STATIC, identifier); } else if (_isInFactory) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_FACTORY, identifier); } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.IMPLICIT_THIS_REFERENCE_IN_INITIALIZER, identifier); } } /** * Verify that the given import [directive] has a unique name among other * imported libraries. The [importElement] is the [ImportElement] retrieved * from the node, if the element in the node was `null`, then this method is * not called. * * See [CompileTimeErrorCode.IMPORT_DUPLICATED_LIBRARY_NAME]. */ void _checkForImportDuplicateLibraryName( ImportDirective directive, ImportElement importElement) { // prepare imported library LibraryElement nodeLibrary = importElement.importedLibrary; if (nodeLibrary == null) { return; } String name = nodeLibrary.name; // check if there is another imported library with the same name LibraryElement prevLibrary = _nameToImportElement[name]; if (prevLibrary != null) { if (prevLibrary != nodeLibrary && name.isNotEmpty) { _errorReporter.reportErrorForNode( StaticWarningCode.IMPORT_DUPLICATED_LIBRARY_NAMED, directive, [ prevLibrary.definingCompilationUnit.source.uri, nodeLibrary.definingCompilationUnit.source.uri, name ]); } } else { _nameToImportElement[name] = nodeLibrary; } } /** * Check that if the visiting library is not system, then any given library * should not be SDK internal library. The [importElement] is the * [ImportElement] retrieved from the node, if the element in the node was * `null`, then this method is not called * * See [CompileTimeErrorCode.IMPORT_INTERNAL_LIBRARY]. */ void _checkForImportInternalLibrary( ImportDirective directive, ImportElement importElement) { if (_isInSystemLibrary) { return; } LibraryElement importedLibrary = importElement.importedLibrary; if (importedLibrary == null) { return; } // should be private DartSdk sdk = _currentLibrary.context.sourceFactory.dartSdk; String uri = importedLibrary.source.uri.toString(); SdkLibrary sdkLibrary = sdk.getSdkLibrary(uri); if (sdkLibrary == null || !sdkLibrary.isInternal) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.IMPORT_INTERNAL_LIBRARY, directive.uri, [directive.uri.stringValue]); } /** * Check that the given [typeReference] is not a type reference and that then * the [name] is reference to an instance member. * * See [StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER]. */ void _checkForInstanceAccessToStaticMember( ClassElement typeReference, Expression target, SimpleIdentifier name) { if (_isInComment) { // OK, in comment return; } // prepare member Element Element element = name.staticElement; if (element is ExecutableElement) { if (!element.isStatic) { // OK, instance member return; } Element enclosingElement = element.enclosingElement; if (enclosingElement is ExtensionElement) { if (target is ExtensionOverride) { // OK, target is an extension override return; } else if (target is SimpleIdentifier && target.staticElement is ExtensionElement) { return; } else if (target is PrefixedIdentifier && target.staticElement is ExtensionElement) { return; } } else { if (typeReference != null) { // OK, target is a type return; } if (enclosingElement is! ClassElement) { // OK, top-level element return; } } _errorReporter.reportErrorForNode( StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER, name, [name.name, _getKind(element), element.enclosingElement.name]); } } /** * Verify that an 'int' can be assigned to the parameter corresponding to the * given [argument]. This is used for prefix and postfix expressions where * the argument value is implicit. * * See [StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE]. */ void _checkForIntNotAssignable(Expression argument) { if (argument == null) { return; } ParameterElement staticParameterElement = argument.staticParameterElement; DartType staticParameterType = staticParameterElement?.type; _checkForArgumentTypeNotAssignable(argument, staticParameterType, _intType, StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE); } /** * Verify that the given [annotation] isn't defined in a deferred library. * * See [CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY]. */ void _checkForInvalidAnnotationFromDeferredLibrary(Annotation annotation) { Identifier nameIdentifier = annotation.name; if (nameIdentifier is PrefixedIdentifier && nameIdentifier.isDeferred) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY, annotation.name); } } /** * Verify that the given left hand side ([lhs]) and right hand side ([rhs]) * represent a valid assignment. * * See [StaticTypeWarningCode.INVALID_ASSIGNMENT]. */ void _checkForInvalidAssignment(Expression lhs, Expression rhs) { if (lhs == null || rhs == null) { return; } VariableElement leftVariableElement = getVariableElement(lhs); DartType leftType = (leftVariableElement == null) ? getStaticType(lhs) : leftVariableElement.type; if (!leftType.isVoid && _checkForUseOfVoidResult(rhs)) { return; } _checkForAssignableExpression( rhs, leftType, StaticTypeWarningCode.INVALID_ASSIGNMENT); } /** * Check the given [initializer] to ensure that the field being initialized is * a valid field. The [fieldName] is the field name from the * [ConstructorFieldInitializer]. The [staticElement] is the static element * from the name in the [ConstructorFieldInitializer]. */ void _checkForInvalidField(ConstructorFieldInitializer initializer, SimpleIdentifier fieldName, Element staticElement) { if (staticElement is FieldElement) { if (staticElement.isSynthetic) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZER_FOR_NON_EXISTENT_FIELD, initializer, [fieldName]); } else if (staticElement.isStatic) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZER_FOR_STATIC_FIELD, initializer, [fieldName]); } } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZER_FOR_NON_EXISTENT_FIELD, initializer, [fieldName]); return; } } /** * Check to see whether the given function [body] has a modifier associated * with it, and report it as an error if it does. */ void _checkForInvalidModifierOnBody( FunctionBody body, CompileTimeErrorCode errorCode) { Token keyword = body.keyword; if (keyword != null) { _errorReporter.reportErrorForToken(errorCode, keyword, [keyword.lexeme]); } } /** * Verify that the usage of the given 'this' is valid. * * See [CompileTimeErrorCode.INVALID_REFERENCE_TO_THIS]. */ void _checkForInvalidReferenceToThis(ThisExpression expression) { if (!_isThisInValidContext(expression)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_REFERENCE_TO_THIS, expression); } } void _checkForListConstructor( InstanceCreationExpression node, InterfaceType type) { if (!_isNonNullable) return; if (node.argumentList.arguments.length == 1 && _isDartCoreList(type) && _typeSystem.isPotentiallyNonNullable(type.typeArguments[0])) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.DEFAULT_LIST_CONSTRUCTOR_MISMATCH, node.constructorName); } } /** * Verify that the elements of the given list [literal] are subtypes of the * list's static type. * * See [CompileTimeErrorCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE], and * [StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE]. */ void _checkForListElementTypeNotAssignable(ListLiteral literal) { // Determine the list's element type. We base this on the static type and // not the literal's type arguments because in strong mode, the type // arguments may be inferred. DartType listType = literal.staticType; assert(listType is InterfaceTypeImpl); List<DartType> typeArguments = (listType as InterfaceTypeImpl).typeArguments; assert(typeArguments.length == 1); DartType listElementType = typeArguments[0]; // Check every list element. var verifier = LiteralElementVerifier( _typeProvider, _typeSystem, _errorReporter, _checkForUseOfVoidResult, forList: true, elementType: listElementType, featureSet: _featureSet, ); for (CollectionElement element in literal.elements) { verifier.verify(element); } } void _checkForMapTypeNotAssignable(SetOrMapLiteral literal) { // Determine the map's key and value types. We base this on the static type // and not the literal's type arguments because in strong mode, the type // arguments may be inferred. DartType mapType = literal.staticType; if (mapType == null) { // This is known to happen when the literal is the default value in an // optional parameter in a generic function type alias. return; } assert(mapType is InterfaceTypeImpl); List<DartType> typeArguments = (mapType as InterfaceTypeImpl).typeArguments; // It is possible for the number of type arguments to be inconsistent when // the literal is ambiguous and a non-map type was selected. // TODO(brianwilkerson) Unify this and _checkForSetElementTypeNotAssignable3 // to better handle recovery situations. if (typeArguments.length == 2) { DartType keyType = typeArguments[0]; DartType valueType = typeArguments[1]; var verifier = LiteralElementVerifier( _typeProvider, _typeSystem, _errorReporter, _checkForUseOfVoidResult, forMap: true, mapKeyType: keyType, mapValueType: valueType, featureSet: _featureSet, ); for (CollectionElement element in literal.elements) { verifier.verify(element); } } } /** * Verify that the [_enclosingClass] does not define members with the same name * as the enclosing class. * * See [CompileTimeErrorCode.MEMBER_WITH_CLASS_NAME]. */ void _checkForMemberWithClassName() { if (_enclosingClass == null) { return; } String className = _enclosingClass.name; if (className == null) { return; } // check accessors for (PropertyAccessorElement accessor in _enclosingClass.accessors) { if (className == accessor.displayName) { _errorReporter.reportErrorForElement( CompileTimeErrorCode.MEMBER_WITH_CLASS_NAME, accessor); } } // don't check methods, they would be constructors } /** * Check to make sure that all similarly typed accessors are of the same type * (including inherited accessors). * * See [StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES]. */ void _checkForMismatchedAccessorTypes( Declaration accessorDeclaration, String accessorTextName) { ExecutableElement accessorElement = accessorDeclaration.declaredElement as ExecutableElement; if (accessorElement is PropertyAccessorElement) { PropertyAccessorElement counterpartAccessor; if (accessorElement.isGetter) { counterpartAccessor = accessorElement.correspondingSetter; } else { counterpartAccessor = accessorElement.correspondingGetter; // If the setter and getter are in the same enclosing element, return, // this prevents having MISMATCHED_GETTER_AND_SETTER_TYPES reported twice. if (counterpartAccessor != null && identical(counterpartAccessor.enclosingElement, accessorElement.enclosingElement)) { return; } } if (counterpartAccessor == null) { return; } // Default of null == no accessor or no type (dynamic) DartType getterType; DartType setterType; // Get an existing counterpart accessor if any. if (accessorElement.isGetter) { getterType = _getGetterType(accessorElement); setterType = _getSetterType(counterpartAccessor); } else if (accessorElement.isSetter) { setterType = _getSetterType(accessorElement); getterType = _getGetterType(counterpartAccessor); } // If either types are not assignable to each other, report an error // (if the getter is null, it is dynamic which is assignable to everything). if (setterType != null && getterType != null && !_typeSystem.isAssignableTo(getterType, setterType, featureSet: _featureSet)) { _errorReporter.reportTypeErrorForNode( StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES, accessorDeclaration, [accessorTextName, getterType, setterType, accessorTextName]); } } } /** * Check whether all similarly named accessors have consistent types. */ void _checkForMismatchedAccessorTypesInExtension( ExtensionDeclaration extension) { for (ClassMember member in extension.members) { if (member is MethodDeclaration && member.isGetter) { PropertyAccessorElement getterElement = member.declaredElement as PropertyAccessorElement; PropertyAccessorElement setterElement = getterElement.correspondingSetter; if (setterElement != null) { DartType getterType = _getGetterType(getterElement); DartType setterType = _getSetterType(setterElement); if (setterType != null && getterType != null && !_typeSystem.isAssignableTo(getterType, setterType, featureSet: _featureSet)) { SimpleIdentifier nameNode = member.name; String name = nameNode.name; _errorReporter.reportTypeErrorForNode( StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES, nameNode, [name, getterType, setterType, name]); } } } } } /** * Check to make sure that the given switch [statement] whose static type is * an enum type either have a default case or include all of the enum * constants. */ void _checkForMissingEnumConstantInSwitch(SwitchStatement statement) { // TODO(brianwilkerson) This needs to be checked after constant values have // been computed. Expression expression = statement.expression; DartType expressionType = getStaticType(expression); if (expressionType == null) { return; } Element expressionElement = expressionType.element; if (expressionElement is ClassElement) { if (!expressionElement.isEnum) { return; } List<String> constantNames = <String>[]; List<FieldElement> fields = expressionElement.fields; int fieldCount = fields.length; for (int i = 0; i < fieldCount; i++) { FieldElement field = fields[i]; if (field.isStatic && !field.isSynthetic) { constantNames.add(field.name); } } NodeList<SwitchMember> members = statement.members; int memberCount = members.length; for (int i = 0; i < memberCount; i++) { SwitchMember member = members[i]; if (member is SwitchDefault) { return; } String constantName = _getConstantName((member as SwitchCase).expression); if (constantName != null) { constantNames.remove(constantName); } } if (constantNames.isEmpty) { return; } for (int i = 0; i < constantNames.length; i++) { int offset = statement.offset; int end = statement.rightParenthesis.end; _errorReporter.reportErrorForOffset( StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH, offset, end - offset, [constantNames[i]]); } } } void _checkForMissingJSLibAnnotation(Annotation node) { if (node.elementAnnotation?.isJS ?? false) { if (_currentLibrary.hasJS != true) { _errorReporter.reportErrorForNode( HintCode.MISSING_JS_LIB_ANNOTATION, node); } } } /** * Verify that the given function [body] does not contain return statements * that both have and do not have return values. * * See [StaticWarningCode.MIXED_RETURN_TYPES]. */ void _checkForMixedReturns(BlockFunctionBody body) { if (_hasReturnWithoutValue) { return; } var nonVoidReturnsWith = _returnsWith.where((stmt) => !getStaticType(stmt.expression).isVoid); if (nonVoidReturnsWith.isNotEmpty && _returnsWithout.isNotEmpty) { for (ReturnStatement returnWith in nonVoidReturnsWith) { _errorReporter.reportErrorForToken( StaticWarningCode.MIXED_RETURN_TYPES, returnWith.returnKeyword); } for (ReturnStatement returnWithout in _returnsWithout) { _errorReporter.reportErrorForToken( StaticWarningCode.MIXED_RETURN_TYPES, returnWithout.returnKeyword); } } } /** * Verify that the given mixin does not have an explicitly declared * constructor. The [mixinName] is the node to report problem on. The * [mixinElement] is the mixing to evaluate. * * See [CompileTimeErrorCode.MIXIN_CLASS_DECLARES_CONSTRUCTOR]. */ bool _checkForMixinClassDeclaresConstructor( TypeName mixinName, ClassElement mixinElement) { for (ConstructorElement constructor in mixinElement.constructors) { if (!constructor.isSynthetic && !constructor.isFactory) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MIXIN_CLASS_DECLARES_CONSTRUCTOR, mixinName, [mixinElement.name]); return true; } } return false; } /** * Verify that the given mixin has the 'Object' superclass. The [mixinName] is * the node to report problem on. The [mixinElement] is the mixing to * evaluate. * * See [CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT]. */ bool _checkForMixinInheritsNotFromObject( TypeName mixinName, ClassElement mixinElement) { InterfaceType mixinSupertype = mixinElement.supertype; if (mixinSupertype != null) { if (!mixinSupertype.isObject || !mixinElement.isMixinApplication && mixinElement.mixins.isNotEmpty) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, mixinName, [mixinElement.name]); return true; } } return false; } /** * Verify that the given mixin does not reference 'super'. The [mixinName] is * the node to report problem on. The [mixinElement] is the mixing to * evaluate. * * See [CompileTimeErrorCode.MIXIN_REFERENCES_SUPER]. */ bool _checkForMixinReferencesSuper( TypeName mixinName, ClassElement mixinElement) { if (mixinElement.hasReferenceToSuper) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MIXIN_REFERENCES_SUPER, mixinName, [mixinElement.name]); } return false; } /// Check that superclass constrains for the mixin type of [mixinName] at /// the [mixinIndex] position in the mixins list are satisfied by the /// [_enclosingClass], or a previous mixin. bool _checkForMixinSuperclassConstraints(int mixinIndex, TypeName mixinName) { InterfaceType mixinType = mixinName.type; for (var constraint in mixinType.superclassConstraints) { bool isSatisfied = _typeSystem.isSubtypeOf(_enclosingClass.supertype, constraint); if (!isSatisfied) { for (int i = 0; i < mixinIndex && !isSatisfied; i++) { isSatisfied = _typeSystem.isSubtypeOf(_enclosingClass.mixins[i], constraint); } } if (!isSatisfied) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MIXIN_APPLICATION_NOT_IMPLEMENTED_INTERFACE, mixinName.name, [ mixinName.type.displayName, _enclosingClass.supertype, constraint.displayName ]); return true; } } return false; } /// Check that the superclass of the given [mixinElement] at the given /// [mixinIndex] in the list of mixins of [_enclosingClass] has concrete /// implementations of all the super-invoked members of the [mixinElement]. bool _checkForMixinSuperInvokedMembers(int mixinIndex, TypeName mixinName, ClassElement mixinElement, InterfaceType mixinType) { ClassElementImpl mixinElementImpl = AbstractClassElementImpl.getImpl(mixinElement); if (mixinElementImpl.superInvokedNames.isEmpty) { return false; } InterfaceTypeImpl enclosingType = _enclosingClass.thisType; Uri mixinLibraryUri = mixinElement.librarySource.uri; for (var name in mixinElementImpl.superInvokedNames) { var nameObject = new Name(mixinLibraryUri, name); var superMember = _inheritanceManager.getMember(enclosingType, nameObject, forMixinIndex: mixinIndex, concrete: true, forSuper: true); if (superMember == null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode .MIXIN_APPLICATION_NO_CONCRETE_SUPER_INVOKED_MEMBER, mixinName.name, [name]); return true; } ExecutableElement mixinMember = _inheritanceManager.getMember(mixinType, nameObject, forSuper: true); if (mixinMember != null && !_typeSystem.isOverrideSubtypeOf( superMember.type, mixinMember.type)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode .MIXIN_APPLICATION_CONCRETE_SUPER_INVOKED_MEMBER_TYPE, mixinName.name, [name, mixinMember.type.displayName, superMember.type.displayName]); return true; } } return false; } /** * Check for the declaration of a mixin from a library other than the current * library that defines a private member that conflicts with a private name * from the same library but from a superclass or a different mixin. */ void _checkForMixinWithConflictingPrivateMember( WithClause withClause, TypeName superclassName) { if (withClause == null) { return; } DartType declaredSupertype = superclassName?.type; if (declaredSupertype is! InterfaceType) { return; } InterfaceType superclass = declaredSupertype; Map<LibraryElement, Map<String, String>> mixedInNames = <LibraryElement, Map<String, String>>{}; /// Report an error and return `true` if the given [name] is a private name /// (which is defined in the given [library]) and it conflicts with another /// definition of that name inherited from the superclass. bool isConflictingName( String name, LibraryElement library, TypeName typeName) { if (Identifier.isPrivateName(name)) { Map<String, String> names = mixedInNames.putIfAbsent(library, () => <String, String>{}); if (names.containsKey(name)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.PRIVATE_COLLISION_IN_MIXIN_APPLICATION, typeName, [name, typeName.name.name, names[name]]); return true; } names[name] = typeName.name.name; ExecutableElement inheritedMember = superclass.lookUpMethod(name, library) ?? superclass.lookUpGetter(name, library) ?? superclass.lookUpSetter(name, library); if (inheritedMember != null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.PRIVATE_COLLISION_IN_MIXIN_APPLICATION, typeName, [ name, typeName.name.name, inheritedMember.enclosingElement.name ]); return true; } } return false; } for (TypeName mixinType in withClause.mixinTypes) { DartType type = mixinType.type; if (type is InterfaceType) { LibraryElement library = type.element.library; if (library != _currentLibrary) { for (PropertyAccessorElement accessor in type.accessors) { if (isConflictingName(accessor.name, library, mixinType)) { return; } } for (MethodElement method in type.methods) { if (isConflictingName(method.name, library, mixinType)) { return; } } } } } } /** * Verify that the given [constructor] has at most one 'super' initializer. * * See [CompileTimeErrorCode.MULTIPLE_SUPER_INITIALIZERS]. */ void _checkForMultipleSuperInitializers(ConstructorDeclaration constructor) { bool hasSuperInitializer = false; for (ConstructorInitializer initializer in constructor.initializers) { if (initializer is SuperConstructorInvocation) { if (hasSuperInitializer) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MULTIPLE_SUPER_INITIALIZERS, initializer); } hasSuperInitializer = true; } } } void _checkForMustCallSuper(MethodDeclaration node) { if (node.isStatic || node.isAbstract) { return; } MethodElement element = _findOverriddenMemberThatMustCallSuper(node); if (element != null && _hasConcreteSuperMethod(node)) { _InvocationCollector collector = new _InvocationCollector(); node.accept(collector); if (!collector.superCalls.contains(element.name)) { _errorReporter.reportErrorForNode(HintCode.MUST_CALL_SUPER, node.name, [element.enclosingElement.name]); } } } /** * Checks to ensure that the given native function [body] is in SDK code. * * See [ParserErrorCode.NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE]. */ void _checkForNativeFunctionBodyInNonSdkCode(NativeFunctionBody body) { if (!_isInSystemLibrary && !_hasExtUri) { _errorReporter.reportErrorForNode( ParserErrorCode.NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE, body); } } /** * Verify that the given instance creation [expression] invokes an existing * constructor. The [constructorName] is the constructor name. The [typeName] * is the name of the type defining the constructor. * * This method assumes that the instance creation was tested to be 'new' * before being called. * * See [StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR]. */ void _checkForNewWithUndefinedConstructor( InstanceCreationExpression expression, ConstructorName constructorName, TypeName typeName) { // OK if resolved if (expression.staticElement != null) { return; } DartType type = typeName.type; if (type is InterfaceType) { ClassElement element = type.element; if (element.isEnum || element.isMixin) { // We have already reported the error. return; } } // prepare class name Identifier className = typeName.name; // report as named or default constructor absence SimpleIdentifier name = constructorName.name; if (name != null) { _errorReporter.reportErrorForNode( StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR, name, [className, name]); } else { _errorReporter.reportErrorForNode( StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT, constructorName, [className]); } } /** * Check that if the given class [declaration] implicitly calls default * constructor of its superclass, there should be such default constructor - * implicit or explicit. * * See [CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT]. */ void _checkForNoDefaultSuperConstructorImplicit( ClassDeclaration declaration) { // do nothing if there is explicit constructor List<ConstructorElement> constructors = _enclosingClass.constructors; if (!constructors[0].isSynthetic) { return; } // prepare super InterfaceType superType = _enclosingClass.supertype; if (superType == null) { return; } ClassElement superElement = superType.element; // try to find default generative super constructor ConstructorElement superUnnamedConstructor = superElement.unnamedConstructor; if (superUnnamedConstructor != null) { if (superUnnamedConstructor.isFactory) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR, declaration.name, [superUnnamedConstructor]); return; } if (superUnnamedConstructor.isDefaultConstructor) { return; } } _errorReporter.reportErrorForNode( CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT, declaration.name, [superType.displayName, _enclosingClass.displayName]); } /** * Check to ensure that the [condition] is of type bool, are. Otherwise an * error is reported on the expression. * * See [StaticTypeWarningCode.NON_BOOL_CONDITION]. */ void _checkForNonBoolCondition(Expression condition) { _checkForNonBoolExpression(condition, errorCode: StaticTypeWarningCode.NON_BOOL_CONDITION); } /** * Verify that the given [expression] is of type 'bool', and report * [errorCode] if not, or a nullability error if its improperly nullable. */ void _checkForNonBoolExpression(Expression expression, {@required ErrorCode errorCode}) { DartType type = getStaticType(expression); if (!_checkForUseOfVoidResult(expression) && !_typeSystem.isAssignableTo(type, _boolType, featureSet: _featureSet)) { if (type.element == _boolType.element) { _errorReporter.reportErrorForNode( StaticWarningCode.UNCHECKED_USE_OF_NULLABLE_VALUE, expression); } else { _errorReporter.reportErrorForNode(errorCode, expression); } } } /** * Checks to ensure that the given [expression] is assignable to bool. */ void _checkForNonBoolNegationExpression(Expression expression) { _checkForNonBoolExpression(expression, errorCode: StaticTypeWarningCode.NON_BOOL_NEGATION_EXPRESSION); } /** * Verify the given map [literal] either: * * has `const modifier` * * has explicit type arguments * * is not start of the statement * * See [CompileTimeErrorCode.NON_CONST_MAP_AS_EXPRESSION_STATEMENT]. */ void _checkForNonConstMapAsExpressionStatement3(SetOrMapLiteral literal) { // "const" if (literal.constKeyword != null) { return; } // has type arguments if (literal.typeArguments != null) { return; } // prepare statement Statement statement = literal.thisOrAncestorOfType<ExpressionStatement>(); if (statement == null) { return; } // OK, statement does not start with map if (!identical(statement.beginToken, literal.beginToken)) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.NON_CONST_MAP_AS_EXPRESSION_STATEMENT, literal); } /** * Verify that the given method [declaration] of operator `[]=`, has `void` * return type. * * See [StaticWarningCode.NON_VOID_RETURN_FOR_OPERATOR]. */ void _checkForNonVoidReturnTypeForOperator(MethodDeclaration declaration) { // check that []= operator SimpleIdentifier name = declaration.name; if (name.name != "[]=") { return; } // check return type TypeAnnotation annotation = declaration.returnType; if (annotation != null) { DartType type = annotation.type; if (type != null && !type.isVoid) { _errorReporter.reportErrorForNode( StaticWarningCode.NON_VOID_RETURN_FOR_OPERATOR, annotation); } } } /** * Verify the [typeName], used as the return type of a setter, is valid * (either `null` or the type 'void'). * * See [StaticWarningCode.NON_VOID_RETURN_FOR_SETTER]. */ void _checkForNonVoidReturnTypeForSetter(TypeAnnotation typeName) { if (typeName != null) { DartType type = typeName.type; if (type != null && !type.isVoid) { _errorReporter.reportErrorForNode( StaticWarningCode.NON_VOID_RETURN_FOR_SETTER, typeName); } } } void _checkForNotInitializedNonNullableInstanceFields( FieldDeclaration fieldDeclaration, ) { if (!_isNonNullable) return; if (fieldDeclaration.isStatic) return; var fields = fieldDeclaration.fields; if (fields.isLate) return; if (fields.isFinal) return; for (var field in fields.variables) { if (field.initializer != null) continue; var type = field.declaredElement.type; if (!_typeSystem.isPotentiallyNonNullable(type)) continue; _errorReporter.reportErrorForNode( CompileTimeErrorCode.NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD, field, [field.name.name], ); } } void _checkForNotInitializedNonNullableStaticField(FieldDeclaration node) { if (!node.isStatic) { return; } _checkForNotInitializedNonNullableVariable(node.fields); } void _checkForNotInitializedNonNullableVariable( VariableDeclarationList node, ) { if (!_isNonNullable) { return; } // Const and final checked separately. if (node.isConst || node.isFinal) { return; } if (node.isLate) { return; } if (node.type == null) { return; } var type = node.type.type; if (!_typeSystem.isPotentiallyNonNullable(type)) { return; } for (var variable in node.variables) { if (variable.initializer == null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.NOT_INITIALIZED_NON_NULLABLE_VARIABLE, variable.name, [variable.name.name], ); } } } /** * Check for illegal derefences of nullables, ie, "unchecked" usages of * nullable values. Note that *any* usage of a null value is an "unchecked" * usage, because proper checks will promote the type to a non-nullable value. */ bool _checkForNullableDereference(Expression expression) { if (expression == null || !_isNonNullable || expression.staticType == null || expression.staticType.isDynamic || !_typeSystem.isPotentiallyNullable(expression.staticType)) { return false; } StaticWarningCode code = expression.staticType == _typeProvider.nullType ? StaticWarningCode.INVALID_USE_OF_NULL_VALUE : StaticWarningCode.UNCHECKED_USE_OF_NULLABLE_VALUE; _errorReporter.reportErrorForNode(code, expression, []); return true; } /** * Verify that all classes of the given [onClause] are valid. * * See [CompileTimeErrorCode.MIXIN_SUPER_CLASS_CONSTRAINT_DISALLOWED_CLASS], * [CompileTimeErrorCode.MIXIN_SUPER_CLASS_CONSTRAINT_DEFERRED_CLASS]. */ bool _checkForOnClauseErrorCodes(OnClause onClause) { if (onClause == null) { return false; } bool problemReported = false; for (TypeName typeName in onClause.superclassConstraints) { DartType type = typeName.type; if (type is InterfaceType) { if (_checkForExtendsOrImplementsDisallowedClass( typeName, CompileTimeErrorCode .MIXIN_SUPER_CLASS_CONSTRAINT_DISALLOWED_CLASS)) { problemReported = true; } else { if (_checkForExtendsOrImplementsDeferredClass( typeName, CompileTimeErrorCode .MIXIN_SUPER_CLASS_CONSTRAINT_DEFERRED_CLASS)) { problemReported = true; } } } } return problemReported; } /** * Verify the given operator-method [declaration], does not have an optional * parameter. This method assumes that the method declaration was tested to be * an operator declaration before being called. * * See [CompileTimeErrorCode.OPTIONAL_PARAMETER_IN_OPERATOR]. */ void _checkForOptionalParameterInOperator(MethodDeclaration declaration) { FormalParameterList parameterList = declaration.parameters; if (parameterList == null) { return; } NodeList<FormalParameter> formalParameters = parameterList.parameters; for (FormalParameter formalParameter in formalParameters) { if (formalParameter.isOptional) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.OPTIONAL_PARAMETER_IN_OPERATOR, formalParameter); } } } /** * Via informal specification: dart-lang/language/issues/4 * * If e is an integer literal which is not the operand of a unary minus * operator, then: * - If the context type is double, it is a compile-time error if the * numerical value of e is not precisely representable by a double. * Otherwise the static type of e is double and the result of evaluating e * is a double instance representing that value. * - Otherwise (the current behavior of e, with a static type of int). * * and * * If e is -n and n is an integer literal, then * - If the context type is double, it is a compile-time error if the * numerical value of n is not precisley representable by a double. * Otherwise the static type of e is double and the result of evaluating e * is the result of calling the unary minus operator on a double instance * representing the numerical value of n. * - Otherwise (the current behavior of -n) */ void _checkForOutOfRange(IntegerLiteral node) { String lexeme = node.literal.lexeme; final bool isNegated = (node as IntegerLiteralImpl).immediatelyNegated; final List<Object> extraErrorArgs = []; final bool treatedAsDouble = node.staticType == _typeProvider.doubleType; final bool valid = treatedAsDouble ? IntegerLiteralImpl.isValidAsDouble(lexeme) : IntegerLiteralImpl.isValidAsInteger(lexeme, isNegated); if (!valid) { extraErrorArgs.add(isNegated ? '-$lexeme' : lexeme); if (treatedAsDouble) { // Suggest the nearest valid double (as a BigInt for printing reasons). extraErrorArgs .add(BigInt.from(IntegerLiteralImpl.nearestValidDouble(lexeme))); } _errorReporter.reportErrorForNode( treatedAsDouble ? CompileTimeErrorCode.INTEGER_LITERAL_IMPRECISE_AS_DOUBLE : CompileTimeErrorCode.INTEGER_LITERAL_OUT_OF_RANGE, node, extraErrorArgs); } } /** * Verify that the [type] is not potentially nullable. */ void _checkForPotentiallyNullableType(TypeAnnotation type) { if (_options.experimentStatus.non_nullable && type?.type != null && _typeSystem.isPotentiallyNullable(type.type)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.NULLABLE_TYPE_IN_CATCH_CLAUSE, type); } } /** * Check that the given named optional [parameter] does not begin with '_'. * * See [CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER]. */ void _checkForPrivateOptionalParameter(FormalParameter parameter) { // should be named parameter if (!parameter.isNamed) { return; } // name should start with '_' SimpleIdentifier name = parameter.identifier; if (name == null || name.isSynthetic || !StringUtilities.startsWithChar(name.name, 0x5F)) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER, parameter); } /** * Check whether the given constructor [declaration] is the redirecting * generative constructor and references itself directly or indirectly. The * [constructorElement] is the constructor element. * * See [CompileTimeErrorCode.RECURSIVE_CONSTRUCTOR_REDIRECT]. */ void _checkForRecursiveConstructorRedirect(ConstructorDeclaration declaration, ConstructorElement constructorElement) { // we check generative constructor here if (declaration.factoryKeyword != null) { return; } // try to find redirecting constructor invocation and analyze it for // recursion for (ConstructorInitializer initializer in declaration.initializers) { if (initializer is RedirectingConstructorInvocation) { if (_hasRedirectingFactoryConstructorCycle(constructorElement)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.RECURSIVE_CONSTRUCTOR_REDIRECT, initializer); } return; } } } /** * Check whether the given constructor [declaration] has redirected * constructor and references itself directly or indirectly. The * constructor [element] is the element introduced by the declaration. * * See [CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT]. */ bool _checkForRecursiveFactoryRedirect( ConstructorDeclaration declaration, ConstructorElement element) { // prepare redirected constructor ConstructorName redirectedConstructorNode = declaration.redirectedConstructor; if (redirectedConstructorNode == null) { return false; } // OK if no cycle if (!_hasRedirectingFactoryConstructorCycle(element)) { return false; } // report error _errorReporter.reportErrorForNode( CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT, redirectedConstructorNode); return true; } /** * Check that the given constructor [declaration] has a valid combination of * redirected constructor invocation(s), super constructor invocations and * field initializers. * * See [CompileTimeErrorCode.ASSERT_IN_REDIRECTING_CONSTRUCTOR], * [CompileTimeErrorCode.DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR], * [CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR], * [CompileTimeErrorCode.MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS], * [CompileTimeErrorCode.SUPER_IN_REDIRECTING_CONSTRUCTOR], and * [CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR]. */ void _checkForRedirectingConstructorErrorCodes( ConstructorDeclaration declaration) { // Check for default values in the parameters ConstructorName redirectedConstructor = declaration.redirectedConstructor; if (redirectedConstructor != null) { for (FormalParameter parameter in declaration.parameters.parameters) { if (parameter is DefaultFormalParameter && parameter.defaultValue != null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode .DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR, parameter.identifier); } } } // check if there are redirected invocations int numRedirections = 0; for (ConstructorInitializer initializer in declaration.initializers) { if (initializer is RedirectingConstructorInvocation) { if (numRedirections > 0) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS, initializer); } if (declaration.factoryKeyword == null) { RedirectingConstructorInvocation invocation = initializer; ConstructorElement redirectingElement = invocation.staticElement; if (redirectingElement == null) { String enclosingTypeName = _enclosingClass.displayName; String constructorStrName = enclosingTypeName; if (invocation.constructorName != null) { constructorStrName += ".${invocation.constructorName.name}"; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR, invocation, [constructorStrName, enclosingTypeName]); } else { if (redirectingElement.isFactory) { _errorReporter.reportErrorForNode( CompileTimeErrorCode .REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR, initializer); } } } numRedirections++; } } // check for other initializers if (numRedirections > 0) { for (ConstructorInitializer initializer in declaration.initializers) { if (initializer is SuperConstructorInvocation) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.SUPER_IN_REDIRECTING_CONSTRUCTOR, initializer); } if (initializer is ConstructorFieldInitializer) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR, initializer); } if (initializer is AssertInitializer) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.ASSERT_IN_REDIRECTING_CONSTRUCTOR, initializer); } } } } /** * Check whether the given constructor [declaration] has redirected * constructor and references itself directly or indirectly. The * constructor [element] is the element introduced by the declaration. * * See [CompileTimeErrorCode.REDIRECT_TO_NON_CONST_CONSTRUCTOR]. */ void _checkForRedirectToNonConstConstructor( ConstructorDeclaration declaration, ConstructorElement element) { // prepare redirected constructor ConstructorName redirectedConstructorNode = declaration.redirectedConstructor; if (redirectedConstructorNode == null) { return; } // prepare element if (element == null) { return; } // OK, it is not 'const' if (!element.isConst) { return; } // prepare redirected constructor ConstructorElement redirectedConstructor = element.redirectedConstructor; if (redirectedConstructor == null) { return; } // OK, it is also 'const' if (redirectedConstructor.isConst) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.REDIRECT_TO_NON_CONST_CONSTRUCTOR, redirectedConstructorNode); } void _checkForReferenceBeforeDeclaration(SimpleIdentifier node) { if (!node.inDeclarationContext() && _hiddenElements != null && _hiddenElements.contains(node.staticElement) && node.parent is! CommentReference) { _errorReporter.reportError(new DiagnosticFactory() .referencedBeforeDeclaration(_errorReporter.source, node)); } } void _checkForRepeatedType(List<TypeName> typeNames, ErrorCode errorCode) { if (typeNames == null) { return; } int count = typeNames.length; List<bool> detectedRepeatOnIndex = new List<bool>.filled(count, false); for (int i = 0; i < detectedRepeatOnIndex.length; i++) { detectedRepeatOnIndex[i] = false; } for (int i = 0; i < count; i++) { if (!detectedRepeatOnIndex[i]) { Element element = typeNames[i].name.staticElement; for (int j = i + 1; j < count; j++) { TypeName typeName = typeNames[j]; if (typeName.name.staticElement == element) { detectedRepeatOnIndex[j] = true; _errorReporter .reportErrorForNode(errorCode, typeName, [typeName.name.name]); } } } } } /** * Check that the given rethrow [expression] is inside of a catch clause. * * See [CompileTimeErrorCode.RETHROW_OUTSIDE_CATCH]. */ void _checkForRethrowOutsideCatch(RethrowExpression expression) { if (!_isInCatchClause) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.RETHROW_OUTSIDE_CATCH, expression); } } /** * Check that if the given constructor [declaration] is generative, then * it does not have an expression function body. * * See [CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR]. */ void _checkForReturnInGenerativeConstructor( ConstructorDeclaration declaration) { // ignore factory if (declaration.factoryKeyword != null) { return; } // block body (with possible return statement) is checked elsewhere FunctionBody body = declaration.body; if (body is! ExpressionFunctionBody) { return; } _errorReporter.reportErrorForNode( CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR, body); } /** * Check that a type mis-match between the type of the [returnExpression] and * the [expectedReturnType] by the enclosing method or function. * * This method is called both by [_checkForAllReturnStatementErrorCodes] * and [visitExpressionFunctionBody]. * * See [StaticTypeWarningCode.RETURN_OF_INVALID_TYPE]. */ void _checkForReturnOfInvalidType( Expression returnExpression, DartType expectedType, {bool isArrowFunction = false}) { if (_enclosingFunction == null) { return; } if (_inGenerator) { // "return expression;" is disallowed in generators, but this is checked // elsewhere. Bare "return" is always allowed in generators regardless // of the return type. So no need to do any further checking. return; } if (returnExpression == null) { return; // Empty returns are handled elsewhere } DartType expressionType = getStaticType(returnExpression); void reportTypeError() { String displayName = _enclosingFunction.displayName; if (displayName.isEmpty) { _errorReporter.reportTypeErrorForNode( StaticTypeWarningCode.RETURN_OF_INVALID_TYPE_FROM_CLOSURE, returnExpression, [expressionType, expectedType]); } else { _errorReporter.reportTypeErrorForNode( StaticTypeWarningCode.RETURN_OF_INVALID_TYPE, returnExpression, [expressionType, expectedType, displayName]); } } var toType = expectedType; var fromType = expressionType; if (_inAsync) { toType = _typeSystem.flatten(toType); fromType = _typeSystem.flatten(fromType); } // Anything can be returned to `void` in an arrow bodied function // or to `Future<void>` in an async arrow bodied function. if (isArrowFunction && toType.isVoid) { return; } if (toType.isVoid) { if (fromType.isVoid || fromType.isDynamic || fromType.isDartCoreNull || fromType.isBottom) { return; } } else if (fromType.isVoid) { if (toType.isDynamic || toType.isDartCoreNull || toType.isBottom) { return; } } if (!expectedType.isVoid && !fromType.isVoid) { var checkWithType = !_inAsync ? fromType : _typeProvider.futureType2(fromType); if (_typeSystem.isAssignableTo(checkWithType, expectedType, featureSet: _featureSet)) { return; } } reportTypeError(); } /** * Verify that the elements in the given set [literal] are subtypes of the * set's static type. * * See [CompileTimeErrorCode.SET_ELEMENT_TYPE_NOT_ASSIGNABLE], and * [StaticWarningCode.SET_ELEMENT_TYPE_NOT_ASSIGNABLE]. */ void _checkForSetElementTypeNotAssignable3(SetOrMapLiteral literal) { // Determine the set's element type. We base this on the static type and // not the literal's type arguments because in strong mode, the type // arguments may be inferred. DartType setType = literal.staticType; assert(setType is InterfaceTypeImpl); List<DartType> typeArguments = (setType as InterfaceTypeImpl).typeArguments; // It is possible for the number of type arguments to be inconsistent when // the literal is ambiguous and a non-set type was selected. // TODO(brianwilkerson) Unify this and _checkForMapTypeNotAssignable3 to // better handle recovery situations. if (typeArguments.length == 1) { DartType setElementType = typeArguments[0]; // Check every set element. var verifier = LiteralElementVerifier( _typeProvider, _typeSystem, _errorReporter, _checkForUseOfVoidResult, forSet: true, elementType: setElementType, featureSet: _featureSet, ); for (CollectionElement element in literal.elements) { verifier.verify(element); } } } /** * Check the given [typeReference] and that the [name] is not a reference to * an instance member. * * See [StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER]. */ void _checkForStaticAccessToInstanceMember( ClassElement typeReference, SimpleIdentifier name) { // OK, in comment if (_isInComment) { return; } // OK, target is not a type if (typeReference == null) { return; } // prepare member Element Element element = name.staticElement; if (element is ExecutableElement) { // OK, static if (element.isStatic || element is ConstructorElement) { return; } _errorReporter.reportErrorForNode( StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER, name, [name.name]); } } /** * Check that the type of the expression in the given 'switch' [statement] is * assignable to the type of the 'case' members. * * See [StaticWarningCode.SWITCH_EXPRESSION_NOT_ASSIGNABLE]. */ void _checkForSwitchExpressionNotAssignable(SwitchStatement statement) { Expression expression = statement.expression; if (_checkForUseOfVoidResult(expression)) { return; } // prepare 'switch' expression type DartType expressionType = getStaticType(expression); if (expressionType == null) { return; } // compare with type of the first non-default 'case' SwitchCase switchCase = statement.members .firstWhere((member) => member is SwitchCase, orElse: () => null); if (switchCase == null) { return; } Expression caseExpression = switchCase.expression; DartType caseType = getStaticType(caseExpression); // check types if (!_typeSystem.isAssignableTo(expressionType, caseType, featureSet: _featureSet)) { _errorReporter.reportErrorForNode( StaticWarningCode.SWITCH_EXPRESSION_NOT_ASSIGNABLE, expression, [expressionType, caseType]); } } /** * Verify that the given function type [alias] does not reference itself * directly. * * See [CompileTimeErrorCode.TYPE_ALIAS_CANNOT_REFERENCE_ITSELF]. */ void _checkForTypeAliasCannotReferenceItself_function( FunctionTypeAlias alias) { if (_hasTypedefSelfReference(alias.declaredElement)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.TYPE_ALIAS_CANNOT_REFERENCE_ITSELF, alias); } } /** * Verify that the [type] is not a deferred type. * * See [StaticWarningCode.TYPE_ANNOTATION_DEFERRED_CLASS]. */ void _checkForTypeAnnotationDeferredClass(TypeAnnotation type) { if (type is TypeName && type.isDeferred) { _errorReporter.reportErrorForNode( StaticWarningCode.TYPE_ANNOTATION_DEFERRED_CLASS, type, [type.name]); } } /** * Check that none of the type [parameters] references itself in its bound. * * See [StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND]. */ void _checkForTypeParameterBoundRecursion(List<TypeParameter> parameters) { Map<TypeParameterElement, TypeParameter> elementToNode; for (var parameter in parameters) { if (parameter.bound != null) { if (elementToNode == null) { elementToNode = {}; for (var parameter in parameters) { elementToNode[parameter.declaredElement] = parameter; } } TypeParameter current = parameter; for (var step = 0; current != null; step++) { var bound = current.bound; if (bound is TypeName) { current = elementToNode[bound.name.staticElement]; } else { current = null; } if (step == parameters.length) { var element = parameter.declaredElement; _errorReporter.reportErrorForNode( StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND, parameter, [element.displayName, element.bound.displayName], ); break; } } } } } void _checkForTypeParameterReferencedByStatic(SimpleIdentifier identifier) { if (_isInStaticMethod || _isInStaticVariableDeclaration) { var element = identifier.staticElement; if (element is TypeParameterElement && element.enclosingElement is ClassElement) { // The class's type parameters are not in scope for static methods. // However all other type parameters are legal (e.g. the static method's // type parameters, or a local function's type parameters). _errorReporter.reportErrorForNode( StaticWarningCode.TYPE_PARAMETER_REFERENCED_BY_STATIC, identifier); } } } /** * Check that if the given generative [constructor] has neither an explicit * super constructor invocation nor a redirecting constructor invocation, that * the superclass has a default generative constructor. * * See [CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT], * [CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR], and * [StaticWarningCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT]. */ void _checkForUndefinedConstructorInInitializerImplicit( ConstructorDeclaration constructor) { if (_enclosingClass == null) { return; } // Ignore if the constructor is not generative. if (constructor.factoryKeyword != null) { return; } // Ignore if the constructor has either an implicit super constructor // invocation or a redirecting constructor invocation. for (ConstructorInitializer constructorInitializer in constructor.initializers) { if (constructorInitializer is SuperConstructorInvocation || constructorInitializer is RedirectingConstructorInvocation) { return; } } // Check to see whether the superclass has a non-factory unnamed // constructor. InterfaceType superType = _enclosingClass.supertype; if (superType == null) { return; } ClassElement superElement = superType.element; ConstructorElement superUnnamedConstructor = superElement.unnamedConstructor; if (superUnnamedConstructor != null) { if (superUnnamedConstructor.isFactory) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR, constructor.returnType, [superUnnamedConstructor]); } else if (!superUnnamedConstructor.isDefaultConstructor) { Identifier returnType = constructor.returnType; SimpleIdentifier name = constructor.name; int offset = returnType.offset; int length = (name != null ? name.end : returnType.end) - offset; _errorReporter.reportErrorForOffset( CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT, offset, length, [superType.displayName]); } } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT, constructor.returnType, [superElement.name]); } } void _checkForUnnecessaryNullAware(Expression target, Token operator) { if (!_isNonNullable) { return; } ErrorCode errorCode; if (operator.type == TokenType.QUESTION_PERIOD) { errorCode = StaticWarningCode.UNNECESSARY_NULL_AWARE_CALL; } else if (operator.type == TokenType.PERIOD_PERIOD_PERIOD_QUESTION) { errorCode = StaticWarningCode.UNNECESSARY_NULL_AWARE_SPREAD; } else if (operator.type == TokenType.BANG) { errorCode = StaticWarningCode.UNNECESSARY_NON_NULL_ASSERTION; } else { return; } if (target.staticType != null && _typeSystem.isNonNullable(target.staticType)) { _errorReporter.reportErrorForToken(errorCode, operator, []); } } /** * Check that if the given [name] is a reference to a static member it is * defined in the enclosing class rather than in a superclass. * * See [StaticTypeWarningCode.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER]. */ void _checkForUnqualifiedReferenceToNonLocalStaticMember( SimpleIdentifier name) { Element element = name.staticElement; if (element == null || element is TypeParameterElement) { return; } Element enclosingElement = element.enclosingElement; if (identical(enclosingElement, _enclosingClass)) { return; } if (identical(enclosingElement, _enclosingEnum)) { return; } if (enclosingElement is! ClassElement) { return; } if (element is ExecutableElement && !element.isStatic) { return; } if (element is MethodElement) { // Invalid methods are reported in // [MethodInvocationResolver._resolveReceiverNull]. return; } if (_enclosingExtension != null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode .UNQUALIFIED_REFERENCE_TO_STATIC_MEMBER_OF_EXTENDED_TYPE, name, [enclosingElement.displayName]); } else { _errorReporter.reportErrorForNode( StaticTypeWarningCode .UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER, name, [enclosingElement.displayName]); } } /** * While in general Never is a sort of placehold type that should be usable * anywhere, we explicitly bar it from some dubious syntactic locations such * as calling a method on Never, which in practice would look something like * `(throw x).toString()` which is clearly something between a mistake and * dead code. * * See [StaticWarningCode.INVALID_USE_OF_NEVER_VALUE]. */ bool _checkForUseOfNever(Expression expression) { if (expression == null || !identical(expression.staticType, BottomTypeImpl.instance)) { return false; } _errorReporter.reportErrorForNode( StaticWarningCode.INVALID_USE_OF_NEVER_VALUE, expression); return true; } /** * Check for situations where the result of a method or function is used, when * it returns 'void'. Or, in rare cases, when other types of expressions are * void, such as identifiers. * * See [StaticWarningCode.USE_OF_VOID_RESULT]. */ bool _checkForUseOfVoidResult(Expression expression) { if (expression == null || !identical(expression.staticType, VoidTypeImpl.instance)) { return false; } if (expression is MethodInvocation) { SimpleIdentifier methodName = expression.methodName; _errorReporter.reportErrorForNode( StaticWarningCode.USE_OF_VOID_RESULT, methodName, []); } else { _errorReporter.reportErrorForNode( StaticWarningCode.USE_OF_VOID_RESULT, expression, []); } return true; } void _checkForValidField(FieldFormalParameter parameter) { AstNode parent2 = parameter.parent?.parent; if (parent2 is! ConstructorDeclaration && parent2?.parent is! ConstructorDeclaration) { return; } ParameterElement element = parameter.declaredElement; if (element is FieldFormalParameterElement) { FieldElement fieldElement = element.field; if (fieldElement == null || fieldElement.isSynthetic) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD, parameter, [parameter.identifier.name]); } else { ParameterElement parameterElement = parameter.declaredElement; if (parameterElement is FieldFormalParameterElementImpl) { DartType declaredType = parameterElement.type; DartType fieldType = fieldElement.type; if (fieldElement.isSynthetic) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD, parameter, [parameter.identifier.name]); } else if (fieldElement.isStatic) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_STATIC_FIELD, parameter, [parameter.identifier.name]); } else if (declaredType != null && fieldType != null && !_typeSystem.isAssignableTo(declaredType, fieldType, featureSet: _featureSet)) { _errorReporter.reportTypeErrorForNode( StaticWarningCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE, parameter, [declaredType, fieldType]); } } else { if (fieldElement.isSynthetic) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD, parameter, [parameter.identifier.name]); } else if (fieldElement.isStatic) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_STATIC_FIELD, parameter, [parameter.identifier.name]); } } } } // else { // // TODO(jwren) Report error, constructor initializer variable is a top level element // // (Either here or in ErrorVerifier.checkForAllFinalInitializedErrorCodes) // } } /** * Verify the given operator-method [declaration], has correct number of * parameters. * * This method assumes that the method declaration was tested to be an * operator declaration before being called. * * See [CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR]. */ void _checkForWrongNumberOfParametersForOperator( MethodDeclaration declaration) { // prepare number of parameters FormalParameterList parameterList = declaration.parameters; if (parameterList == null) { return; } int numParameters = parameterList.parameters.length; // prepare operator name SimpleIdentifier nameNode = declaration.name; if (nameNode == null) { return; } String name = nameNode.name; // check for exact number of parameters int expected = -1; if ("[]=" == name) { expected = 2; } else if ("<" == name || ">" == name || "<=" == name || ">=" == name || "==" == name || "+" == name || "/" == name || "~/" == name || "*" == name || "%" == name || "|" == name || "^" == name || "&" == name || "<<" == name || ">>" == name || "[]" == name) { expected = 1; } else if ("~" == name) { expected = 0; } if (expected != -1 && numParameters != expected) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR, nameNode, [name, expected, numParameters]); } else if ("-" == name && numParameters > 1) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS, nameNode, [numParameters]); } } /** * Verify that the given setter [parameterList] has only one required * parameter. The [setterName] is the name of the setter to report problems * on. * * This method assumes that the method declaration was tested to be a setter * before being called. * * See [CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER]. */ void _checkForWrongNumberOfParametersForSetter( SimpleIdentifier setterName, FormalParameterList parameterList) { if (setterName == null || parameterList == null) { return; } NodeList<FormalParameter> parameters = parameterList.parameters; if (parameters.length != 1 || !parameters[0].isRequiredPositional) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER, setterName); } } void _checkForWrongTypeParameterVarianceInSuperinterfaces() { void checkOne(DartType superInterface) { if (superInterface != null) { for (var typeParameter in _enclosingClass.typeParameters) { var variance = computeVariance(typeParameter, superInterface); if (variance == Variance.contravariant || variance == Variance.invariant) { _errorReporter.reportErrorForElement( CompileTimeErrorCode .WRONG_TYPE_PARAMETER_VARIANCE_IN_SUPERINTERFACE, typeParameter, [typeParameter.name, superInterface], ); } } } } checkOne(_enclosingClass.supertype); _enclosingClass.interfaces.forEach(checkOne); _enclosingClass.mixins.forEach(checkOne); _enclosingClass.superclassConstraints.forEach(checkOne); } /** * Check for a type mis-match between the yielded type and the declared * return type of a generator function. * * This method should only be called in generator functions. */ void _checkForYieldOfInvalidType( Expression yieldExpression, bool isYieldEach) { assert(_inGenerator); if (_enclosingFunction == null) { return; } DartType declaredReturnType = _enclosingFunction.returnType; DartType staticYieldedType = getStaticType(yieldExpression); DartType impliedReturnType; if (isYieldEach) { impliedReturnType = staticYieldedType; } else if (_enclosingFunction.isAsynchronous) { impliedReturnType = _typeProvider.streamType2(staticYieldedType); } else { impliedReturnType = _typeProvider.iterableType2(staticYieldedType); } if (!_checkForAssignableExpressionAtType(yieldExpression, impliedReturnType, declaredReturnType, StaticTypeWarningCode.YIELD_OF_INVALID_TYPE)) { return; } if (isYieldEach) { // Since the declared return type might have been "dynamic", we need to // also check that the implied return type is assignable to generic // Stream/Iterable. DartType requiredReturnType; if (_enclosingFunction.isAsynchronous) { requiredReturnType = _typeProvider.streamDynamicType; } else { requiredReturnType = _typeProvider.iterableDynamicType; } if (!_typeSystem.isAssignableTo(impliedReturnType, requiredReturnType, featureSet: _featureSet)) { _errorReporter.reportTypeErrorForNode( StaticTypeWarningCode.YIELD_OF_INVALID_TYPE, yieldExpression, [impliedReturnType, requiredReturnType]); return; } } } /** * Verify that the given class [declaration] does not have the same class in * the 'extends' and 'implements' clauses. * * See [CompileTimeErrorCode.IMPLEMENTS_SUPER_CLASS]. */ void _checkImplementsSuperClass(ImplementsClause implementsClause) { // prepare super type InterfaceType superType = _enclosingClass.supertype; if (superType == null) { return; } // prepare interfaces if (implementsClause == null) { return; } // check interfaces for (TypeName interfaceNode in implementsClause.interfaces) { if (interfaceNode.type == superType) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.IMPLEMENTS_SUPER_CLASS, interfaceNode, [superType.displayName]); } } } void _checkMixinInference( NamedCompilationUnitMember node, WithClause withClause) { if (withClause == null) { return; } ClassElement classElement = node.declaredElement; var type = classElement.thisType; var supertype = classElement.supertype; List<InterfaceType> supertypesForMixinInference = <InterfaceType>[]; ClassElementImpl.collectAllSupertypes( supertypesForMixinInference, supertype, type); for (var typeName in withClause.mixinTypes) { var mixinType = typeName.type; var mixinElement = mixinType.element; if (mixinElement is ClassElement) { if (typeName.typeArguments == null) { var mixinSupertypeConstraints = _typeSystem .gatherMixinSupertypeConstraintsForInference(mixinElement); if (mixinSupertypeConstraints.isNotEmpty) { var matchingInterfaceTypes = _findInterfaceTypesForConstraints( typeName, mixinSupertypeConstraints, supertypesForMixinInference); if (matchingInterfaceTypes != null) { // Try to pattern match matchingInterfaceType against // mixinSupertypeConstraint to find the correct set of type // parameters to apply to the mixin. var inferredTypeArguments = _typeSystem.matchSupertypeConstraints( mixinElement, mixinSupertypeConstraints, matchingInterfaceTypes, ); if (inferredTypeArguments == null) { _errorReporter.reportErrorForToken( CompileTimeErrorCode .MIXIN_INFERENCE_NO_POSSIBLE_SUBSTITUTION, typeName.name.beginToken, [typeName]); } } } } ClassElementImpl.collectAllSupertypes( supertypesForMixinInference, mixinType, type); } } } /** * Checks the class for problems with the superclass, mixins, or implemented * interfaces. */ void _checkMixinInheritance(MixinDeclaration node, OnClause onClause, ImplementsClause implementsClause) { // Only check for all of the inheritance logic around clauses if there // isn't an error code such as "Cannot implement double" already. if (!_checkForOnClauseErrorCodes(onClause) && !_checkForImplementsClauseErrorCodes(implementsClause)) { // _checkForImplicitDynamicType(superclass); _checkForConflictingClassMembers(); _checkForRepeatedType( onClause?.superclassConstraints, CompileTimeErrorCode.ON_REPEATED, ); _checkForRepeatedType( implementsClause?.interfaces, CompileTimeErrorCode.IMPLEMENTS_REPEATED, ); if (!disableConflictingGenericsCheck) { _checkForConflictingGenerics(node); } } } void _checkUseOfCovariantInParameters(FormalParameterList node) { AstNode parent = node.parent; if (_enclosingClass != null && parent is MethodDeclaration && !parent.isStatic) { return; } NodeList<FormalParameter> parameters = node.parameters; int length = parameters.length; for (int i = 0; i < length; i++) { FormalParameter parameter = parameters[i]; if (parameter is DefaultFormalParameter) { parameter = (parameter as DefaultFormalParameter).parameter; } Token keyword = parameter.covariantKeyword; if (keyword != null) { if (_enclosingExtension != null) { _errorReporter.reportErrorForToken( CompileTimeErrorCode.INVALID_USE_OF_COVARIANT_IN_EXTENSION, keyword, ); } else { _errorReporter.reportErrorForToken( CompileTimeErrorCode.INVALID_USE_OF_COVARIANT, keyword, ); } } } } void _checkUseOfDefaultValuesInParameters(FormalParameterList node) { if (!_isNonNullable) return; AstNode parent = node.parent; if (parent is FieldFormalParameter || parent is FunctionTypeAlias || parent is FunctionTypedFormalParameter || parent is GenericFunctionType) { // These locations are not allowed to have default values. return; } NodeList<FormalParameter> parameters = node.parameters; int length = parameters.length; for (int i = 0; i < length; i++) { FormalParameter parameter = parameters[i]; if (parameter.isOptional) { DartType type = parameter.declaredElement.type; if (type.isDartAsyncFutureOr) { type = (type as ParameterizedType).typeArguments[0]; } if ((parameter as DefaultFormalParameter).defaultValue == null) { if (_typeSystem.isPotentiallyNonNullable(type)) { SimpleIdentifier parameterName = _parameterName(parameter); if (type is TypeParameterType) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_OPTIONAL_PARAMETER_TYPE, parameterName ?? parameter, [parameterName?.name ?? '?']); } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MISSING_DEFAULT_VALUE_FOR_PARAMETER, parameterName ?? parameter, [parameterName?.name ?? '?']); } } } else if (!_typeSystem.isNonNullable(type) && _typeSystem.isPotentiallyNonNullable(type)) { // If the type is both potentially non-nullable and not // non-nullable, then it cannot be used for an optional parameter. SimpleIdentifier parameterName = _parameterName(parameter); _errorReporter.reportErrorForNode( CompileTimeErrorCode.INVALID_OPTIONAL_PARAMETER_TYPE, parameterName ?? parameter, [parameterName?.name ?? '?']); } } else if (parameter.isRequiredNamed) { if ((parameter as DefaultFormalParameter).defaultValue != null) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.DEFAULT_VALUE_ON_REQUIRED_PARAMETER, _parameterName(parameter) ?? parameter); } } } } InterfaceType _findInterfaceTypeForMixin(TypeName mixin, InterfaceType supertypeConstraint, List<InterfaceType> interfaceTypes) { var element = supertypeConstraint.element; InterfaceType foundInterfaceType; for (var interfaceType in interfaceTypes) { if (interfaceType.element != element) continue; if (foundInterfaceType == null) { foundInterfaceType = interfaceType; } else { if (interfaceType != foundInterfaceType) { _errorReporter.reportErrorForToken( CompileTimeErrorCode .MIXIN_INFERENCE_INCONSISTENT_MATCHING_CLASSES, mixin.name.beginToken, [mixin, supertypeConstraint]); } } } if (foundInterfaceType == null) { _errorReporter.reportErrorForToken( CompileTimeErrorCode.MIXIN_INFERENCE_NO_MATCHING_CLASS, mixin.name.beginToken, [mixin, supertypeConstraint]); } return foundInterfaceType; } List<InterfaceType> _findInterfaceTypesForConstraints( TypeName mixin, List<InterfaceType> supertypeConstraints, List<InterfaceType> interfaceTypes) { var result = <InterfaceType>[]; for (var constraint in supertypeConstraints) { var interfaceType = _findInterfaceTypeForMixin(mixin, constraint, interfaceTypes); if (interfaceType == null) { // No matching interface type found, so inference fails. The error has // already been reported. return null; } result.add(interfaceType); } return result; } /// Find a method which is overridden by [node] and which is annotated with /// `@mustCallSuper`. /// /// As per the definition of `mustCallSuper` [1], every method which overrides /// a method annotated with `@mustCallSuper` is implicitly annotated with /// `@mustCallSuper`. /// /// [1] https://pub.dartlang.org/documentation/meta/latest/meta/mustCallSuper-constant.html MethodElement _findOverriddenMemberThatMustCallSuper(MethodDeclaration node) { Element member = node.declaredElement; if (member.enclosingElement is! ClassElement) { return null; } ClassElement classElement = member.enclosingElement; String name = member.name; // Walk up the type hierarchy from [classElement], ignoring direct interfaces. Queue<ClassElement> superclasses = Queue.of(classElement.mixins.map((i) => i.element)) ..addAll(classElement.superclassConstraints.map((i) => i.element)) ..add(classElement.supertype?.element); Set<ClassElement> visitedClasses = new Set<ClassElement>(); while (superclasses.isNotEmpty) { ClassElement ancestor = superclasses.removeFirst(); if (ancestor == null || !visitedClasses.add(ancestor)) { continue; } ExecutableElement member = ancestor.getMethod(name) ?? ancestor.getGetter(name) ?? ancestor.getSetter(name); if (member is MethodElement && member.hasMustCallSuper) { return member; } superclasses ..addAll(ancestor.mixins.map((i) => i.element)) ..addAll(ancestor.superclassConstraints.map((i) => i.element)) ..add(ancestor.supertype?.element); } return null; } /** * Given an [expression] in a switch case whose value is expected to be an * enum constant, return the name of the constant. */ String _getConstantName(Expression expression) { // TODO(brianwilkerson) Convert this to return the element representing the // constant. if (expression is SimpleIdentifier) { return expression.name; } else if (expression is PrefixedIdentifier) { return expression.identifier.name; } else if (expression is PropertyAccess) { return expression.propertyName.name; } return null; } /** * Return the return type of the given [getter]. */ DartType _getGetterType(PropertyAccessorElement getter) { FunctionType functionType = getter.type; if (functionType != null) { return functionType.returnType; } else { return null; } } /** * Return a human-readable representation of the kind of the [element]. */ String _getKind(ExecutableElement element) { if (element is MethodElement) { return 'method'; } else if (element is PropertyAccessorElement) { if (element.isSynthetic) { PropertyInducingElement variable = element.variable; if (variable is FieldElement) { return 'field'; } return 'variable'; } else if (element.isGetter) { return 'getter'; } else { return 'setter'; } } else if (element is ConstructorElement) { return 'constructor'; } else if (element is FunctionElement) { return 'function'; } return 'member'; } /** * Return the name of the library that defines given [element]. */ String _getLibraryName(Element element) { if (element == null) { return StringUtilities.EMPTY; } LibraryElement library = element.library; if (library == null) { return StringUtilities.EMPTY; } List<ImportElement> imports = _currentLibrary.imports; int count = imports.length; for (int i = 0; i < count; i++) { if (identical(imports[i].importedLibrary, library)) { return library.definingCompilationUnit.source.uri.toString(); } } List<String> indirectSources = new List<String>(); for (int i = 0; i < count; i++) { LibraryElement importedLibrary = imports[i].importedLibrary; if (importedLibrary != null) { for (LibraryElement exportedLibrary in importedLibrary.exportedLibraries) { if (identical(exportedLibrary, library)) { indirectSources.add( importedLibrary.definingCompilationUnit.source.uri.toString()); } } } } int indirectCount = indirectSources.length; StringBuffer buffer = new StringBuffer(); buffer.write(library.definingCompilationUnit.source.uri.toString()); if (indirectCount > 0) { buffer.write(" (via "); if (indirectCount > 1) { indirectSources.sort(); buffer.write(StringUtilities.printListOfQuotedNames(indirectSources)); } else { buffer.write(indirectSources[0]); } buffer.write(")"); } return buffer.toString(); } /** * Return the type of the first and only parameter of the given [setter]. */ DartType _getSetterType(PropertyAccessorElement setter) { // Get the parameters for MethodDeclaration or FunctionDeclaration List<ParameterElement> setterParameters = setter.parameters; // If there are no setter parameters, return no type. if (setterParameters.isEmpty) { return null; } return setterParameters[0].type; } /// Returns whether [node] overrides a concrete method. bool _hasConcreteSuperMethod(MethodDeclaration node) { ClassElement classElement = node.declaredElement.enclosingElement; String name = node.declaredElement.name; Queue<ClassElement> superclasses = Queue.of(classElement.mixins.map((i) => i.element)) ..addAll(classElement.superclassConstraints.map((i) => i.element)); if (classElement.supertype != null) { superclasses.add(classElement.supertype.element); } return superclasses.any( (parent) => parent.lookUpConcreteMethod(name, parent.library) != null); } /** * Return `true` if the given [constructor] redirects to itself, directly or * indirectly. */ bool _hasRedirectingFactoryConstructorCycle(ConstructorElement constructor) { ConstructorElement nonMember(ConstructorElement constructor) { return constructor is ConstructorMember ? constructor.baseElement : constructor; } Set<ConstructorElement> constructors = new HashSet<ConstructorElement>(); ConstructorElement current = constructor; while (current != null) { if (constructors.contains(current)) { return identical(current, constructor); } constructors.add(current); current = nonMember(current.redirectedConstructor); } return false; } /** * Return `true` if the given [element] has direct or indirect reference to * itself from anywhere except a class element or type parameter bounds. */ bool _hasTypedefSelfReference(GenericTypeAliasElement element) { if (element == null) { return false; } if (element is GenericTypeAliasElementImpl && element.linkedNode != null) { return element.hasSelfReference; } var visitor = new _HasTypedefSelfReferenceVisitor(element.function); element.accept(visitor); return visitor.hasSelfReference; } void _initializeInitialFieldElementsMap(List<FieldElement> fields) { _initialFieldElementsMap = new HashMap<FieldElement, INIT_STATE>(); for (FieldElement fieldElement in fields) { if (!fieldElement.isSynthetic) { _initialFieldElementsMap[fieldElement] = fieldElement.initializer == null ? INIT_STATE.NOT_INIT : INIT_STATE.INIT_IN_DECLARATION; } } } bool _isDartCoreList(InterfaceType type) { ClassElement element = type.element; if (element == null) { return false; } return element.name == "List" && element.library.isDartCore; } bool _isFunctionType(DartType type) { if (type.isDynamic || type.isDartCoreNull) { return true; } else if (type is FunctionType || type.isDartCoreFunction) { return true; } else if (type is InterfaceType) { MethodElement callMethod = type.lookUpMethod(FunctionElement.CALL_METHOD_NAME, _currentLibrary); return callMethod != null; } return false; } /** * Return `true` if the given 'this' [expression] is in a valid context. */ bool _isThisInValidContext(ThisExpression expression) { for (AstNode node = expression.parent; node != null; node = node.parent) { if (node is CompilationUnit) { return false; } else if (node is ConstructorDeclaration) { return node.factoryKeyword == null; } else if (node is ConstructorInitializer) { return false; } else if (node is MethodDeclaration) { return !node.isStatic; } else if (node is FieldDeclaration) { if (node.fields.isLate && (node.parent is ClassDeclaration || node.parent is MixinDeclaration)) { return true; } // Continue; a non-late variable may still occur in a valid context. } } return false; } /** * Return `true` if the given [identifier] is in a location where it is * allowed to resolve to a static member of a supertype. */ bool _isUnqualifiedReferenceToNonLocalStaticMemberAllowed( SimpleIdentifier identifier) { if (identifier.inDeclarationContext()) { return true; } AstNode parent = identifier.parent; if (parent is Annotation) { return identical(parent.constructorName, identifier); } if (parent is CommentReference) { return true; } if (parent is ConstructorName) { return identical(parent.name, identifier); } if (parent is MethodInvocation) { return identical(parent.methodName, identifier); } if (parent is PrefixedIdentifier) { return identical(parent.identifier, identifier); } if (parent is PropertyAccess) { return identical(parent.propertyName, identifier); } if (parent is SuperConstructorInvocation) { return identical(parent.constructorName, identifier); } return false; } /// Return the name of the [parameter], or `null` if the parameter does not /// have a name. SimpleIdentifier _parameterName(FormalParameter parameter) { if (parameter is NormalFormalParameter) { return parameter.identifier; } else if (parameter is DefaultFormalParameter) { return parameter.parameter.identifier; } return null; } /** * Return [FieldElement]s that are declared in the [ClassDeclaration] with * the given [constructor], but are not initialized. */ static List<FieldElement> computeNotInitializedFields( ConstructorDeclaration constructor) { Set<FieldElement> fields = new Set<FieldElement>(); var classDeclaration = constructor.parent as ClassDeclaration; for (ClassMember fieldDeclaration in classDeclaration.members) { if (fieldDeclaration is FieldDeclaration) { for (VariableDeclaration field in fieldDeclaration.fields.variables) { if (field.initializer == null) { fields.add(field.declaredElement); } } } } List<FormalParameter> parameters = constructor.parameters?.parameters ?? []; for (FormalParameter parameter in parameters) { if (parameter is DefaultFormalParameter) { parameter = (parameter as DefaultFormalParameter).parameter; } if (parameter is FieldFormalParameter) { FieldFormalParameterElement element = parameter.identifier.staticElement as FieldFormalParameterElement; fields.remove(element.field); } } for (ConstructorInitializer initializer in constructor.initializers) { if (initializer is ConstructorFieldInitializer) { fields.remove(initializer.fieldName.staticElement); } } return fields.toList(); } /** * Return the static type of the given [expression] that is to be used for * type analysis. */ static DartType getStaticType(Expression expression) { DartType type = expression.staticType; if (type == null) { // TODO(brianwilkerson) This should never happen. return DynamicTypeImpl.instance; } return type; } /** * Return the variable element represented by the given [expression], or * `null` if there is no such element. */ static VariableElement getVariableElement(Expression expression) { if (expression is Identifier) { Element element = expression.staticElement; if (element is VariableElement) { return element; } } return null; } } /** * A record of the elements that will be declared in some scope (block), but are * not yet declared. */ class HiddenElements { /** * The elements hidden in outer scopes, or `null` if this is the outermost * scope. */ final HiddenElements outerElements; /** * A set containing the elements that will be declared in this scope, but are * not yet declared. */ Set<Element> _elements = new HashSet<Element>(); /** * Initialize a newly created set of hidden elements to include all of the * elements defined in the set of [outerElements] and all of the elements * declared in the given [block]. */ HiddenElements(this.outerElements, Block block) { _initializeElements(block); } /** * Return `true` if this set of elements contains the given [element]. */ bool contains(Element element) { if (_elements.contains(element)) { return true; } else if (outerElements != null) { return outerElements.contains(element); } return false; } /** * Record that the given [element] has been declared, so it is no longer * hidden. */ void declare(Element element) { _elements.remove(element); } /** * Initialize the list of elements that are not yet declared to be all of the * elements declared somewhere in the given [block]. */ void _initializeElements(Block block) { _elements.addAll(BlockScope.elementsInBlock(block)); } } class _HasTypedefSelfReferenceVisitor extends GeneralizingElementVisitor<void> { final GenericFunctionTypeElement element; bool hasSelfReference = false; _HasTypedefSelfReferenceVisitor(this.element); @override void visitClassElement(ClassElement element) { // Typedefs are allowed to reference themselves via classes. } @override void visitFunctionElement(FunctionElement element) { _addTypeToCheck(element.returnType); super.visitFunctionElement(element); } @override void visitFunctionTypeAliasElement(FunctionTypeAliasElement element) { _addTypeToCheck(element.returnType); super.visitFunctionTypeAliasElement(element); } @override void visitGenericFunctionTypeElement(GenericFunctionTypeElement element) { _addTypeToCheck(element.returnType); super.visitGenericFunctionTypeElement(element); } @override void visitParameterElement(ParameterElement element) { _addTypeToCheck(element.type); super.visitParameterElement(element); } @override void visitTypeParameterElement(TypeParameterElement element) { _addTypeToCheck(element.bound); super.visitTypeParameterElement(element); } void _addTypeToCheck(DartType type) { if (hasSelfReference) { return; } if (type == null) { return; } if (type.element == element) { hasSelfReference = true; return; } if (type is FunctionType) { _addTypeToCheck(type.returnType); for (ParameterElement parameter in type.parameters) { _addTypeToCheck(parameter.type); } } // type arguments if (type is InterfaceType) { for (DartType typeArgument in type.typeArguments) { _addTypeToCheck(typeArgument); } } } } /** * Recursively visits an AST, looking for method invocations. */ class _InvocationCollector extends RecursiveAstVisitor { final List<String> superCalls = <String>[]; @override visitMethodInvocation(MethodInvocation node) { if (node.target is SuperExpression) { superCalls.add(node.methodName.name); } super.visitMethodInvocation(node); } } /** * Recursively visits a type annotation, looking uninstantiated bounds. */ class _UninstantiatedBoundChecker extends RecursiveAstVisitor { final ErrorReporter _errorReporter; _UninstantiatedBoundChecker(this._errorReporter); @override visitTypeName(node) { var typeArgs = node.typeArguments; if (typeArgs != null) { typeArgs.accept(this); return; } var element = node.name.staticElement; if (element is TypeParameterizedElement && !element.isSimplyBounded) { _errorReporter .reportErrorForNode(StrongModeCode.NOT_INSTANTIATED_BOUND, node, []); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/java_core.dart
// Copyright (c) 2014, 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. /** * Inserts the given arguments into [pattern]. * * format('Hello, {0}!', 'John') = 'Hello, John!' * format('{0} are you {1}ing?', 'How', 'do') = 'How are you doing?' * format('{0} are you {1}ing?', 'What', 'read') = 'What are you reading?' */ String format(String pattern, [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7]) { // TODO(rnystrom): This is not used by analyzer, but is called by // analysis_server. Move this code there and remove it from here. return formatList(pattern, [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7]); } /** * Inserts the given [arguments] into [pattern]. * * format('Hello, {0}!', ['John']) = 'Hello, John!' * format('{0} are you {1}ing?', ['How', 'do']) = 'How are you doing?' * format('{0} are you {1}ing?', ['What', 'read']) = 'What are you reading?' */ String formatList(String pattern, List<Object> arguments) { if (arguments == null || arguments.isEmpty) { assert(!pattern.contains(new RegExp(r'\{(\d+)\}')), 'Message requires arguments, but none were provided.'); return pattern; } return pattern.replaceAllMapped(new RegExp(r'\{(\d+)\}'), (match) { String indexStr = match.group(1); int index = int.parse(indexStr); Object arg = arguments[index]; assert(arg != null); return arg?.toString(); }); } /** * Very limited printf implementation, supports only %s and %d. */ String _printf(String fmt, List args) { StringBuffer sb = new StringBuffer(); bool markFound = false; int argIndex = 0; for (int i = 0; i < fmt.length; i++) { int c = fmt.codeUnitAt(i); if (c == 0x25) { if (markFound) { sb.writeCharCode(c); markFound = false; } else { markFound = true; } continue; } if (markFound) { markFound = false; // %d if (c == 0x64) { sb.write(args[argIndex++]); continue; } // %s if (c == 0x73) { sb.write(args[argIndex++]); continue; } // unknown throw new ArgumentError('[$fmt][$i] = 0x${c.toRadixString(16)}'); } else { sb.writeCharCode(c); } } return sb.toString(); } class Character { static const int MAX_VALUE = 0xffff; static const int MAX_CODE_POINT = 0x10ffff; static const int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000; static const int MIN_LOW_SURROGATE = 0xDC00; static const int MIN_HIGH_SURROGATE = 0xD800; static int digit(int codePoint, int radix) { if (radix != 16) { throw new ArgumentError("only radix == 16 is supported"); } if (0x30 <= codePoint && codePoint <= 0x39) { return codePoint - 0x30; } if (0x41 <= codePoint && codePoint <= 0x46) { return 0xA + (codePoint - 0x41); } if (0x61 <= codePoint && codePoint <= 0x66) { return 0xA + (codePoint - 0x61); } return -1; } static bool isDigit(int c) => c >= 0x30 && c <= 0x39; static bool isLetter(int c) => c >= 0x41 && c <= 0x5A || c >= 0x61 && c <= 0x7A; static bool isLetterOrDigit(int c) => isLetter(c) || isDigit(c); static bool isWhitespace(int c) => c == 0x09 || c == 0x20 || c == 0x0A || c == 0x0D; static String toChars(int codePoint) { if (codePoint < 0 || codePoint > MAX_CODE_POINT) { throw new ArgumentError(); } if (codePoint < MIN_SUPPLEMENTARY_CODE_POINT) { return new String.fromCharCode(codePoint); } int offset = codePoint - MIN_SUPPLEMENTARY_CODE_POINT; int c0 = ((offset & 0x7FFFFFFF) >> 10) + MIN_HIGH_SURROGATE; int c1 = (offset & 0x3ff) + MIN_LOW_SURROGATE; return new String.fromCharCodes([c0, c1]); } } @deprecated abstract class Enum<E extends Enum<E>> implements Comparable<E> { /// The name of this enum constant, as declared in the enum declaration. final String name; /// The position in the enum declaration. final int ordinal; const Enum(this.name, this.ordinal); int get hashCode => ordinal; int compareTo(E other) => ordinal - other.ordinal; String toString() => name; } @deprecated class PrintStringWriter extends PrintWriter { final StringBuffer _sb = new StringBuffer(); void print(x) { _sb.write(x); } String toString() => _sb.toString(); } abstract class PrintWriter { void newLine() { this.print('\n'); } void print(x); void printf(String fmt, List args) { this.print(_printf(fmt, args)); } void println(String s) { this.print(s); this.newLine(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/source.dart
// Copyright (c) 2014, 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 'dart:collection'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/context/source.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/java_io.dart' show JavaFile; import 'package:analyzer/src/generated/sdk.dart' show DartSdk; import 'package:analyzer/src/generated/source_io.dart' show FileBasedSource; import 'package:analyzer/src/task/api/model.dart'; import 'package:package_config/packages.dart'; import 'package:path/path.dart' as pathos; export 'package:analyzer/source/line_info.dart' show LineInfo; export 'package:analyzer/source/source_range.dart'; /** * A function that is used to visit [ContentCache] entries. */ typedef void ContentCacheVisitor(String fullPath, int stamp, String contents); /// Base class providing implementations for the methods in [Source] that don't /// require filesystem access. abstract class BasicSource extends Source { final Uri uri; BasicSource(this.uri); @override String get encoding => uri.toString(); @override String get fullName => '$uri'; @override int get hashCode => uri.hashCode; @override bool get isInSystemLibrary => uri.scheme == 'dart'; @override String get shortName => pathos.basename(fullName); @override bool operator ==(Object object) => object is Source && object.uri == uri; } /** * A cache used to override the default content of a [Source]. * * TODO(scheglov) Remove it. */ class ContentCache { /** * A table mapping the full path of sources to the contents of those sources. * This is used to override the default contents of a source. */ Map<String, String> _contentMap = new HashMap<String, String>(); /** * A table mapping the full path of sources to the modification stamps of * those sources. This is used when the default contents of a source has been * overridden. */ Map<String, int> _stampMap = new HashMap<String, int>(); int _nextStamp = 0; /** * Visit all entries of this cache. */ void accept(ContentCacheVisitor visitor) { _contentMap.forEach((String fullPath, String contents) { int stamp = _stampMap[fullPath]; visitor(fullPath, stamp, contents); }); } /** * Return the contents of the given [source], or `null` if this cache does not * override the contents of the source. * * <b>Note:</b> This method is not intended to be used except by * [AnalysisContext.getContents]. */ String getContents(Source source) => _contentMap[source.fullName]; /** * Return `true` if the given [source] exists, `false` if it does not exist, * or `null` if this cache does not override existence of the source. * * <b>Note:</b> This method is not intended to be used except by * [AnalysisContext.exists]. */ bool getExists(Source source) { return _contentMap.containsKey(source.fullName) ? true : null; } /** * Return the modification stamp of the given [source], or `null` if this * cache does not override the contents of the source. * * <b>Note:</b> This method is not intended to be used except by * [AnalysisContext.getModificationStamp]. */ int getModificationStamp(Source source) => _stampMap[source.fullName]; /** * Set the contents of the given [source] to the given [contents]. This has * the effect of overriding the default contents of the source. If the * contents are `null` the override is removed so that the default contents * will be returned. */ String setContents(Source source, String contents) { String fullName = source.fullName; if (contents == null) { _stampMap.remove(fullName); return _contentMap.remove(fullName); } else { int newStamp = _nextStamp++; int oldStamp = _stampMap[fullName]; _stampMap[fullName] = newStamp; // Occasionally, if this method is called in rapid succession, the // timestamps are equal. Guard against this by artificially incrementing // the new timestamp. if (newStamp == oldStamp) { _stampMap[fullName] = newStamp + 1; } String oldContent = _contentMap[fullName]; _contentMap[fullName] = contents; return oldContent; } } } @deprecated class CustomUriResolver extends UriResolver { final Map<String, String> _urlMappings; CustomUriResolver(this._urlMappings); @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { String mapping = _urlMappings[uri.toString()]; if (mapping == null) return null; Uri fileUri = new Uri.file(mapping); if (!fileUri.isAbsolute) return null; JavaFile javaFile = new JavaFile.fromUri(fileUri); return new FileBasedSource(javaFile, actualUri ?? uri); } } /** * Instances of the class `DartUriResolver` resolve `dart` URI's. */ class DartUriResolver extends UriResolver { /** * The name of the `dart` scheme. */ static String DART_SCHEME = "dart"; /** * The prefix of a URI using the dart-ext scheme to reference a native code library. */ static String _DART_EXT_SCHEME = "dart-ext:"; /** * The Dart SDK against which URI's are to be resolved. */ final DartSdk _sdk; /** * Initialize a newly created resolver to resolve Dart URI's against the given platform within the * given Dart SDK. * * @param sdk the Dart SDK against which URI's are to be resolved */ DartUriResolver(this._sdk); /** * Return the [DartSdk] against which URIs are to be resolved. * * @return the [DartSdk] against which URIs are to be resolved. */ DartSdk get dartSdk => _sdk; @override Source resolveAbsolute(Uri uri, [Uri actualUri]) { if (!isDartUri(uri)) { return null; } return _sdk.mapDartUri(uri.toString()); } @override Uri restoreAbsolute(Source source) { Source dartSource = _sdk.fromFileUri(source.uri); return dartSource?.uri; } /** * Return `true` if the given URI is a `dart-ext:` URI. * * @param uriContent the textual representation of the URI being tested * @return `true` if the given URI is a `dart-ext:` URI */ static bool isDartExtUri(String uriContent) => uriContent != null && uriContent.startsWith(_DART_EXT_SCHEME); /** * Return `true` if the given URI is a `dart:` URI. * * @param uri the URI being tested * @return `true` if the given URI is a `dart:` URI */ static bool isDartUri(Uri uri) => DART_SCHEME == uri.scheme; } /** * Instances of the class `Location` represent the location of a character as a line and * column pair. */ @deprecated class LineInfo_Location { /** * The one-based index of the line containing the character. */ final int lineNumber; /** * The one-based index of the column containing the character. */ final int columnNumber; /** * Initialize a newly created location to represent the location of the * character at the given [lineNumber] and [columnNumber]. */ LineInfo_Location(this.lineNumber, this.columnNumber); @override String toString() => '$lineNumber:$columnNumber'; } /** * Instances of interface `LocalSourcePredicate` are used to determine if the given * [Source] is "local" in some sense, so can be updated. */ abstract class LocalSourcePredicate { /** * Instance of [LocalSourcePredicate] that always returns `false`. */ static final LocalSourcePredicate FALSE = new LocalSourcePredicate_FALSE(); /** * Instance of [LocalSourcePredicate] that always returns `true`. */ static final LocalSourcePredicate TRUE = new LocalSourcePredicate_TRUE(); /** * Instance of [LocalSourcePredicate] that returns `true` for all [Source]s * except of SDK. */ static final LocalSourcePredicate NOT_SDK = new LocalSourcePredicate_NOT_SDK(); /** * Determines if the given [Source] is local. * * @param source the [Source] to analyze * @return `true` if the given [Source] is local */ bool isLocal(Source source); } class LocalSourcePredicate_FALSE implements LocalSourcePredicate { @override bool isLocal(Source source) => false; } class LocalSourcePredicate_NOT_SDK implements LocalSourcePredicate { @override bool isLocal(Source source) => source.uriKind != UriKind.DART_URI; } class LocalSourcePredicate_TRUE implements LocalSourcePredicate { @override bool isLocal(Source source) => true; } /** * An implementation of an non-existing [Source]. */ class NonExistingSource extends Source { static final unknown = new NonExistingSource( '/unknown.dart', pathos.toUri('/unknown.dart'), UriKind.FILE_URI); @override final String fullName; @override final Uri uri; @override final UriKind uriKind; NonExistingSource(this.fullName, this.uri, this.uriKind); @override TimestampedData<String> get contents { throw new UnsupportedError('$fullName does not exist.'); } @override String get encoding => uri.toString(); @override int get hashCode => fullName.hashCode; @override bool get isInSystemLibrary => false; @override int get modificationStamp => -1; @override String get shortName => pathos.basename(fullName); @override bool operator ==(Object other) { if (other is NonExistingSource) { return other.uriKind == uriKind && other.fullName == fullName; } return false; } @override bool exists() => false; @override String toString() => 'NonExistingSource($uri, $fullName)'; } /** * The interface `Source` defines the behavior of objects representing source * code that can be analyzed by the analysis engine. * * Implementations of this interface need to be aware of some assumptions made * by the analysis engine concerning sources: * * * Sources are not required to be unique. That is, there can be multiple * instances representing the same source. * * Sources are long lived. That is, the engine is allowed to hold on to a * source for an extended period of time and that source must continue to * report accurate and up-to-date information. * * Because of these assumptions, most implementations will not maintain any * state but will delegate to an authoritative system of record in order to * implement this API. For example, a source that represents files on disk * would typically query the file system to determine the state of the file. * * If the instances that implement this API are the system of record, then they * will typically be unique. In that case, sources that are created that * represent non-existent files must also be retained so that if those files * are created at a later date the long-lived sources representing those files * will know that they now exist. */ abstract class Source implements AnalysisTarget { /** * Get the contents and timestamp of this source. * * Clients should consider using the method [AnalysisContext.getContents] * because contexts can have local overrides of the content of a source that * the source is not aware of. * * @return the contents and timestamp of the source * @throws Exception if the contents of this source could not be accessed */ TimestampedData<String> get contents; /** * Return an encoded representation of this source that can be used to create * a source that is equal to this source. * * @return an encoded representation of this source * See [SourceFactory.fromEncoding]. */ @deprecated String get encoding; /** * Return the full (long) version of the name that can be displayed to the * user to denote this source. For example, for a source representing a file * this would typically be the absolute path of the file. * * @return a name that can be displayed to the user to denote this source */ String get fullName; /** * Return a hash code for this source. * * @return a hash code for this source * See [Object.hashCode]. */ @override int get hashCode; /** * Return `true` if this source is in one of the system libraries. * * @return `true` if this is in a system library */ bool get isInSystemLibrary; @override Source get librarySource => null; /** * Return the modification stamp for this source, or a negative value if the * source does not exist. A modification stamp is a non-negative integer with * the property that if the contents of the source have not been modified * since the last time the modification stamp was accessed then the same * value will be returned, but if the contents of the source have been * modified one or more times (even if the net change is zero) the stamps * will be different. * * Clients should consider using the method * [AnalysisContext.getModificationStamp] because contexts can have local * overrides of the content of a source that the source is not aware of. */ int get modificationStamp; /** * Return a short version of the name that can be displayed to the user to * denote this source. For example, for a source representing a file this * would typically be the name of the file. * * @return a name that can be displayed to the user to denote this source */ String get shortName; @override Source get source => this; /** * Return the URI from which this source was originally derived. * * @return the URI from which this source was originally derived */ Uri get uri; /** * Return the kind of URI from which this source was originally derived. If * this source was created from an absolute URI, then the returned kind will * reflect the scheme of the absolute URI. If it was created from a relative * URI, then the returned kind will be the same as the kind of the source * against which the relative URI was resolved. * * @return the kind of URI from which this source was originally derived */ UriKind get uriKind; /** * Return `true` if the given object is a source that represents the same * source code as this source. * * @param object the object to be compared with this object * @return `true` if the given object is a source that represents the same * source code as this source * See [Object.==]. */ @override bool operator ==(Object object); /** * Return `true` if this source exists. * * Clients should consider using the method [AnalysisContext.exists] because * contexts can have local overrides of the content of a source that the * source is not aware of and a source with local content is considered to * exist even if there is no file on disk. * * @return `true` if this source exists */ bool exists(); } /** * The interface `ContentReceiver` defines the behavior of objects that can receive the * content of a source. */ abstract class Source_ContentReceiver { /** * Accept the contents of a source. * * @param contents the contents of the source * @param modificationTime the time at which the contents were last set */ void accept(String contents, int modificationTime); } /** * The interface `SourceContainer` is used by clients to define a collection of sources * * Source containers are not used within analysis engine, but can be used by clients to group * sources for the purposes of accessing composite dependency information. For example, the Eclipse * client uses source containers to represent Eclipse projects, which allows it to easily compute * project-level dependencies. */ abstract class SourceContainer { /** * Determine if the specified source is part of the receiver's collection of sources. * * @param source the source in question * @return `true` if the receiver contains the source, else `false` */ bool contains(Source source); } /** * Instances of the class `SourceFactory` resolve possibly relative URI's against an existing * [Source]. */ abstract class SourceFactory { /** * The analysis context that this source factory is associated with. */ AnalysisContext context; /** * Initialize a newly created source factory with the given absolute URI * [resolvers] and optional [packages] resolution helper. */ factory SourceFactory(List<UriResolver> resolvers, [Packages packages, ResourceProvider resourceProvider]) = SourceFactoryImpl; /** * Return the [DartSdk] associated with this [SourceFactory], or `null` if * there is no such SDK. * * @return the [DartSdk] associated with this [SourceFactory], or `null` if * there is no such SDK */ DartSdk get dartSdk; /** * Sets the [LocalSourcePredicate]. * * @param localSourcePredicate the predicate to determine is [Source] is local */ void set localSourcePredicate(LocalSourcePredicate localSourcePredicate); /// A table mapping package names to paths of directories containing /// the package (or [null] if there is no registered package URI resolver). Map<String, List<Folder>> get packageMap; /** * Clear any cached URI resolution information in the [SourceFactory] itself, * and also ask each [UriResolver]s to clear its caches. */ void clearCache(); /** * Return a source factory that will resolve URI's in the same way that this * source factory does. */ SourceFactory clone(); /** * Return a source object representing the given absolute URI, or `null` if * the URI is not a valid URI or if it is not an absolute URI. * * @param absoluteUri the absolute URI to be resolved * @return a source object representing the absolute URI */ Source forUri(String absoluteUri); /** * Return a source object representing the given absolute URI, or `null` if * the URI is not an absolute URI. * * @param absoluteUri the absolute URI to be resolved * @return a source object representing the absolute URI */ Source forUri2(Uri absoluteUri); /** * Return a source object that is equal to the source object used to obtain * the given encoding. * * @param encoding the encoding of a source object * @return a source object that is described by the given encoding * @throws IllegalArgumentException if the argument is not a valid encoding */ Source fromEncoding(String encoding); /** * Determines if the given [Source] is local. * * @param source the [Source] to analyze * @return `true` if the given [Source] is local */ bool isLocalSource(Source source); /** * Return a source representing the URI that results from resolving the given * (possibly relative) [containedUri] against the URI associated with the * [containingSource], whether or not the resulting source exists, or `null` * if either the [containedUri] is invalid or if it cannot be resolved against * the [containingSource]'s URI. */ Source resolveUri(Source containingSource, String containedUri); /** * Return an absolute URI that represents the given source, or `null` if a * valid URI cannot be computed. * * @param source the source to get URI for * @return the absolute URI representing the given source */ Uri restoreUri(Source source); } /** * The enumeration `SourceKind` defines the different kinds of sources that are * known to the analysis engine. */ class SourceKind implements Comparable<SourceKind> { /** * A source containing HTML. The HTML might or might not contain Dart scripts. */ static const SourceKind HTML = const SourceKind('HTML', 0); /** * A Dart compilation unit that is not a part of another library. Libraries * might or might not contain any directives, including a library directive. */ static const SourceKind LIBRARY = const SourceKind('LIBRARY', 1); /** * A Dart compilation unit that is part of another library. Parts contain a * part-of directive. */ static const SourceKind PART = const SourceKind('PART', 2); /** * An unknown kind of source. Used both when it is not possible to identify * the kind of a source and also when the kind of a source is not known * without performing a computation and the client does not want to spend the * time to identify the kind. */ static const SourceKind UNKNOWN = const SourceKind('UNKNOWN', 3); static const List<SourceKind> values = const [HTML, LIBRARY, PART, UNKNOWN]; /** * The name of this source kind. */ final String name; /** * The ordinal value of the source kind. */ final int ordinal; const SourceKind(this.name, this.ordinal); @override int get hashCode => ordinal; @override int compareTo(SourceKind other) => ordinal - other.ordinal; @override String toString() => name; } /** * The enumeration `UriKind` defines the different kinds of URI's that are * known to the analysis engine. These are used to keep track of the kind of * URI associated with a given source. */ class UriKind implements Comparable<UriKind> { /** * A 'dart:' URI. */ static const UriKind DART_URI = const UriKind('DART_URI', 0, 0x64); /** * A 'file:' URI. */ static const UriKind FILE_URI = const UriKind('FILE_URI', 1, 0x66); /** * A 'package:' URI. */ static const UriKind PACKAGE_URI = const UriKind('PACKAGE_URI', 2, 0x70); static const List<UriKind> values = const [DART_URI, FILE_URI, PACKAGE_URI]; /** * The name of this URI kind. */ final String name; /** * The ordinal value of the URI kind. */ final int ordinal; /** * The single character encoding used to identify this kind of URI. */ final int encoding; /** * Initialize a newly created URI kind to have the given encoding. */ const UriKind(this.name, this.ordinal, this.encoding); @override int get hashCode => ordinal; @override int compareTo(UriKind other) => ordinal - other.ordinal; @override String toString() => name; /** * Return the URI kind represented by the given [encoding], or `null` if there * is no kind with the given encoding. */ static UriKind fromEncoding(int encoding) { while (true) { if (encoding == 0x64) { return DART_URI; } else if (encoding == 0x66) { return FILE_URI; } else if (encoding == 0x70) { return PACKAGE_URI; } break; } return null; } /** * Return the URI kind corresponding to the given scheme string. */ static UriKind fromScheme(String scheme) { if (scheme == 'package') { return UriKind.PACKAGE_URI; } else if (scheme == 'dart') { return UriKind.DART_URI; } else if (scheme == 'file') { return UriKind.FILE_URI; } return UriKind.FILE_URI; } } /** * The abstract class `UriResolver` defines the behavior of objects that are used to resolve * URI's for a source factory. Subclasses of this class are expected to resolve a single scheme of * absolute URI. * * NOTICE: in a future breaking change release of the analyzer, a method * `void clearCache()` will be added. Clients that implement, but do not * extend, this class, can prepare for the breaking change by adding an * implementation of this method that clears any cached URI resolution * information. */ abstract class UriResolver { /** * Clear any cached URI resolution information. */ void clearCache() {} /** * Resolve the given absolute URI. Return a [Source] representing the file to which * it was resolved, whether or not the resulting source exists, or `null` if it could not be * resolved because the URI is invalid. * * @param uri the URI to be resolved * @param actualUri the actual uri for this source -- if `null`, the value of [uri] will be used * @return a [Source] representing the file to which given URI was resolved */ Source resolveAbsolute(Uri uri, [Uri actualUri]); /** * Return an absolute URI that represents the given [source], or `null` if a * valid URI cannot be computed. * * The computation should be based solely on [source.fullName]. */ Uri restoreAbsolute(Source source) => null; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/utilities_general.dart
// Copyright (c) 2014, 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 'dart:async'; import 'dart:collection'; import 'dart:developer' show UserTag; import 'package:yaml/yaml.dart'; /** * Test if the given [value] is `false` or the string "false" (case-insensitive). */ bool isFalse(Object value) => value is bool ? !value : toLowerCase(value) == 'false'; /** * Test if the given [value] is `true` or the string "true" (case-insensitive). */ bool isTrue(Object value) => value is bool ? value : toLowerCase(value) == 'true'; /** * Safely convert the given [value] to a bool value, or return `null` if the * value could not be converted. */ bool toBool(Object value) { if (value is YamlScalar) { value = (value as YamlScalar).value; } if (value is bool) { return value; } String string = toLowerCase(value); if (string == 'true') { return true; } if (string == 'false') { return false; } return null; } /** * Safely convert this [value] to lower case, returning `null` if [value] is * null. */ String toLowerCase(Object value) => value?.toString()?.toLowerCase(); /** * Safely convert this [value] to upper case, returning `null` if [value] is * null. */ String toUpperCase(Object value) => value?.toString()?.toUpperCase(); /// Jenkins hash function, optimized for small integers. /// /// Static methods borrowed from sdk/lib/math/jenkins_smi_hash.dart. Non-static /// methods are an enhancement for the "front_end" package. /// /// Where performance is critical, use [hash2], [hash3], or [hash4], or the /// pattern `finish(combine(combine(...combine(0, a), b)..., z))`, where a..z /// are hash codes to be combined. /// /// For ease of use, you may also use this pattern: /// `(new JenkinsSmiHash()..add(a)..add(b)....add(z)).hashCode`, where a..z are /// the sub-objects whose hashes should be combined. This pattern performs the /// same operations as the performance critical variant, but allocates an extra /// object. class JenkinsSmiHash { /// Accumulates the hash code [value] into the running hash [hash]. static int combine(int hash, int value) { hash = 0x1fffffff & (hash + value); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } /// Finalizes a running hash produced by [combine]. static int finish(int hash) { hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } /// Combines together two hash codes. static int hash2(a, b) => finish(combine(combine(0, a), b)); /// Combines together three hash codes. static int hash3(a, b, c) => finish(combine(combine(combine(0, a), b), c)); /// Combines together four hash codes. static int hash4(a, b, c, d) => finish(combine(combine(combine(combine(0, a), b), c), d)); int _hash = 0; /// Accumulates the object [o] into the hash. void add(Object o) { _hash = combine(_hash, o.hashCode); } /// Finalizes the hash and return the resulting hashcode. int get hashCode => finish(_hash); } /** * A simple limited queue. */ class LimitedQueue<E> extends ListQueue<E> { final int limit; /** * Create a queue with [limit] items. */ LimitedQueue(this.limit); @override void add(E o) { super.add(o); while (length > limit) { remove(first); } } } /** * Helper class for gathering performance statistics. This class is modeled on * the UserTag class in dart:developer so that it can interoperate easily with * it. */ abstract class PerformanceTag { /** * Return a list of all [PerformanceTag]s which have been created. */ static List<PerformanceTag> get all => _PerformanceTagImpl.all.toList(); /** * Return the current [PerformanceTag] for the isolate. */ static PerformanceTag get current => _PerformanceTagImpl.current; /** * Return the [PerformanceTag] that is initially current. This is intended * to track time when the system is performing unknown operations. */ static PerformanceTag get unknown => _PerformanceTagImpl.unknown; /** * Create a [PerformanceTag] having the given [label]. A [UserTag] will also * be created, having the same [label], so that performance information can * be queried using the observatory. */ factory PerformanceTag(String label) = _PerformanceTagImpl; /** * Return the total number of milliseconds that this [PerformanceTag] has * been the current [PerformanceTag] for the isolate. * * This call is safe even if this [PerformanceTag] is current. */ int get elapsedMs; /** * Return the label for this [PerformanceTag]. */ String get label; /** * Create a child tag of the current tag. The new tag's name will include the * parent's name. */ PerformanceTag createChild(String childTagName); /** * Make this the current tag for the isolate, and return the previous tag. */ PerformanceTag makeCurrent(); /** * Make this the current tag for the isolate, run [f], and restore the * previous tag. Returns the result of invoking [f]. */ E makeCurrentWhile<E>(E f()); /** * Make this the current tag for the isolate, run [f], and restore the * previous tag. Returns the result of invoking [f]. */ Future<E> makeCurrentWhileAsync<E>(Future<E> f()); /** * Reset the total time tracked by all [PerformanceTag]s to zero. */ static void reset() { for (_PerformanceTagImpl tag in _PerformanceTagImpl.all) { tag.stopwatch.reset(); } } } class _PerformanceTagImpl implements PerformanceTag { /** * The current performance tag for the isolate. */ static _PerformanceTagImpl current = unknown; static final _PerformanceTagImpl unknown = new _PerformanceTagImpl('unknown'); /** * A list of all performance tags that have been created so far. */ static List<_PerformanceTagImpl> all = <_PerformanceTagImpl>[]; /** * The [UserTag] associated with this [PerformanceTag]. */ final UserTag userTag; /** * Stopwatch tracking the amount of time this [PerformanceTag] has been the * current tag for the isolate. */ final Stopwatch stopwatch; _PerformanceTagImpl(String label) : userTag = new UserTag(label), stopwatch = new Stopwatch() { all.add(this); } @override int get elapsedMs => stopwatch.elapsedMilliseconds; @override String get label => userTag.label; @override PerformanceTag createChild(String childTagName) { return new _PerformanceTagImpl('$label.$childTagName'); } @override PerformanceTag makeCurrent() { if (identical(this, current)) { return current; } _PerformanceTagImpl previous = current; previous.stopwatch.stop(); stopwatch.start(); current = this; userTag.makeCurrent(); return previous; } E makeCurrentWhile<E>(E f()) { PerformanceTag prevTag = makeCurrent(); try { return f(); } finally { prevTag.makeCurrent(); } } @override Future<E> makeCurrentWhileAsync<E>(Future<E> f()) async { // TODO(brianwilkerson) Determine whether this await is necessary. await null; PerformanceTag prevTag = makeCurrent(); try { return await f(); } finally { prevTag.makeCurrent(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/variable_type_provider.dart
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/type.dart'; /// Provider of types for local variables and formal parameters. abstract class LocalVariableTypeProvider { /// Given that the [node] is a reference to a local variable, or a parameter, /// return the type of the variable at the node - declared or promoted. DartType getType(SimpleIdentifier node); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/java_engine_io.dart
// Copyright (c) 2014, 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 "dart:io"; import "package:analyzer/src/generated/java_io.dart"; class FileUtilities2 { static JavaFile createFile(String path) { return new JavaFile(path).getAbsoluteFile(); } } class OSUtilities { static String LINE_SEPARATOR = isWindows() ? '\r\n' : '\n'; static bool isMac() => Platform.operatingSystem == 'macos'; static bool isWindows() => Platform.operatingSystem == 'windows'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/incremental_resolver.dart
// Copyright (c) 2014, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/exception/exception.dart'; import 'package:analyzer/src/generated/resolver.dart'; /** * The context to resolve an [AstNode] in. */ class ResolutionContext { CompilationUnitElement enclosingUnit; ClassDeclaration enclosingClassDeclaration; ClassElement enclosingClass; Scope scope; } /** * Instances of the class [ResolutionContextBuilder] build the context for a * given node in an AST structure. At the moment, this class only handles * top-level and class-level declarations. */ class ResolutionContextBuilder { /** * The class containing the enclosing [CompilationUnitElement]. */ CompilationUnitElement _enclosingUnit; /** * The class containing the enclosing [ClassDeclaration], or `null` if we are * not in the scope of a class. */ ClassDeclaration _enclosingClassDeclaration; /** * The class containing the enclosing [ClassElement], or `null` if we are not * in the scope of a class. */ ClassElement _enclosingClass; Scope _scopeFor(AstNode node) { if (node is CompilationUnit) { return _scopeForAstNode(node); } AstNode parent = node.parent; if (parent == null) { throw new AnalysisException( "Cannot create scope: node is not part of a CompilationUnit"); } return _scopeForAstNode(parent); } /** * Return the scope in which the given AST structure should be resolved. * * *Note:* This method needs to be kept in sync with * [IncrementalResolver.canBeResolved]. * * [node] - the root of the AST structure to be resolved. * * Throws [AnalysisException] if the AST structure has not been resolved or * is not part of a [CompilationUnit] */ Scope _scopeForAstNode(AstNode node) { if (node is CompilationUnit) { return _scopeForCompilationUnit(node); } AstNode parent = node.parent; if (parent == null) { throw new AnalysisException( "Cannot create scope: node is not part of a CompilationUnit"); } Scope scope = _scopeForAstNode(parent); if (node is ClassDeclaration) { _enclosingClassDeclaration = node; _enclosingClass = node.declaredElement; if (_enclosingClass == null) { throw new AnalysisException( "Cannot build a scope for an unresolved class"); } scope = new ClassScope( new TypeParameterScope(scope, _enclosingClass), _enclosingClass); } else if (node is ClassTypeAlias) { ClassElement element = node.declaredElement; if (element == null) { throw new AnalysisException( "Cannot build a scope for an unresolved class type alias"); } scope = new ClassScope(new TypeParameterScope(scope, element), element); } else if (node is ConstructorDeclaration) { ConstructorElement element = node.declaredElement; if (element == null) { throw new AnalysisException( "Cannot build a scope for an unresolved constructor"); } FunctionScope functionScope = new FunctionScope(scope, element); functionScope.defineParameters(); scope = functionScope; } else if (node is FunctionDeclaration) { ExecutableElement element = node.declaredElement; if (element == null) { throw new AnalysisException( "Cannot build a scope for an unresolved function"); } FunctionScope functionScope = new FunctionScope(scope, element); functionScope.defineParameters(); scope = functionScope; } else if (node is FunctionTypeAlias) { scope = new FunctionTypeScope(scope, node.declaredElement); } else if (node is MethodDeclaration) { ExecutableElement element = node.declaredElement; if (element == null) { throw new AnalysisException( "Cannot build a scope for an unresolved method"); } FunctionScope functionScope = new FunctionScope(scope, element); functionScope.defineParameters(); scope = functionScope; } return scope; } Scope _scopeForCompilationUnit(CompilationUnit node) { _enclosingUnit = node.declaredElement; if (_enclosingUnit == null) { throw new AnalysisException( "Cannot create scope: compilation unit is not resolved"); } LibraryElement libraryElement = _enclosingUnit.library; if (libraryElement == null) { throw new AnalysisException( "Cannot create scope: compilation unit is not part of a library"); } return new LibraryScope(libraryElement); } /** * Return the context in which the given AST structure should be resolved. * * [node] - the root of the AST structure to be resolved. * * Throws [AnalysisException] if the AST structure has not been resolved or * is not part of a [CompilationUnit] */ static ResolutionContext contextFor(AstNode node) { if (node == null) { throw new AnalysisException("Cannot create context: node is null"); } // build scope ResolutionContextBuilder builder = new ResolutionContextBuilder(); Scope scope = builder._scopeFor(node); // prepare context ResolutionContext context = new ResolutionContext(); context.scope = scope; context.enclosingUnit = builder._enclosingUnit; context.enclosingClassDeclaration = builder._enclosingClassDeclaration; context.enclosingClass = builder._enclosingClass; return context; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/constant.dart
// Copyright (c) 2014, 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:analyzer/dart/analysis/declared_variables.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/constant/evaluation.dart'; import 'package:analyzer/src/dart/constant/value.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/engine.dart' show RecordingErrorListener; import 'package:analyzer/src/generated/resolver.dart' show TypeProvider; import 'package:analyzer/src/generated/source.dart' show Source; import 'package:analyzer/src/generated/type_system.dart' show Dart2TypeSystem, TypeSystem; export 'package:analyzer/dart/analysis/declared_variables.dart'; export 'package:analyzer/dart/constant/value.dart'; export 'package:analyzer/src/dart/constant/evaluation.dart'; export 'package:analyzer/src/dart/constant/utilities.dart'; export 'package:analyzer/src/dart/constant/value.dart'; /// Instances of the class [ConstantEvaluator] evaluate constant expressions to /// produce their compile-time value. /// /// According to the Dart Language Specification: /// /// > A constant expression is one of the following: /// > /// > * A literal number. /// > * A literal boolean. /// > * A literal string where any interpolated expression is a compile-time /// > constant that evaluates to a numeric, string or boolean value or to /// > **null**. /// > * A literal symbol. /// > * **null**. /// > * A qualified reference to a static constant variable. /// > * An identifier expression that denotes a constant variable, class or type /// > alias. /// > * A constant constructor invocation. /// > * A constant list literal. /// > * A constant map literal. /// > * A simple or qualified identifier denoting a top-level function or a /// > static method. /// > * A parenthesized expression _(e)_ where _e_ is a constant expression. /// > * <span> /// > An expression of the form <i>identical(e<sub>1</sub>, e<sub>2</sub>)</i> /// > where <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> are constant /// > expressions and <i>identical()</i> is statically bound to the predefined /// > dart function <i>identical()</i> discussed above. /// > </span> /// > * <span> /// > An expression of one of the forms <i>e<sub>1</sub> == e<sub>2</sub></i> /// > or <i>e<sub>1</sub> != e<sub>2</sub></i> where <i>e<sub>1</sub></i> and /// > <i>e<sub>2</sub></i> are constant expressions that evaluate to a /// > numeric, string or boolean value. /// > </span> /// > * <span> /// > An expression of one of the forms <i>!e</i>, <i>e<sub>1</sub> &amp;&amp; /// > e<sub>2</sub></i> or <i>e<sub>1</sub> || e<sub>2</sub></i>, where /// > <i>e</i>, <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> are constant /// > expressions that evaluate to a boolean value. /// > </span> /// > * <span> /// > An expression of one of the forms <i>~e</i>, <i>e<sub>1</sub> ^ /// > e<sub>2</sub></i>, <i>e<sub>1</sub> &amp; e<sub>2</sub></i>, /// > <i>e<sub>1</sub> | e<sub>2</sub></i>, <i>e<sub>1</sub> &gt;&gt; /// > e<sub>2</sub></i> or <i>e<sub>1</sub> &lt;&lt; e<sub>2</sub></i>, where /// > <i>e</i>, <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> are constant /// > expressions that evaluate to an integer value or to <b>null</b>. /// > </span> /// > * <span> /// > An expression of one of the forms <i>-e</i>, <i>e<sub>1</sub> + /// > e<sub>2</sub></i>, <i>e<sub>1</sub> -e<sub>2</sub></i>, /// > <i>e<sub>1</sub> * e<sub>2</sub></i>, <i>e<sub>1</sub> / /// > e<sub>2</sub></i>, <i>e<sub>1</sub> ~/ e<sub>2</sub></i>, /// > <i>e<sub>1</sub> &gt; e<sub>2</sub></i>, <i>e<sub>1</sub> &lt; /// > e<sub>2</sub></i>, <i>e<sub>1</sub> &gt;= e<sub>2</sub></i>, /// > <i>e<sub>1</sub> &lt;= e<sub>2</sub></i> or <i>e<sub>1</sub> % /// > e<sub>2</sub></i>, where <i>e</i>, <i>e<sub>1</sub></i> and /// > <i>e<sub>2</sub></i> are constant expressions that evaluate to a numeric /// > value or to <b>null</b>. /// > </span> /// > * <span> /// > An expression of the form <i>e<sub>1</sub> ? e<sub>2</sub> : /// > e<sub>3</sub></i> where <i>e<sub>1</sub></i>, <i>e<sub>2</sub></i> and /// > <i>e<sub>3</sub></i> are constant expressions, and <i>e<sub>1</sub></i> /// > evaluates to a boolean value. /// > </span> /// /// The values returned by instances of this class are therefore `null` and /// instances of the classes `Boolean`, `BigInteger`, `Double`, `String`, and /// `DartObject`. /// /// In addition, this class defines several values that can be returned to /// indicate various conditions encountered during evaluation. These are /// documented with the static fields that define those values. class ConstantEvaluator { /** * The source containing the expression(s) that will be evaluated. */ final Source _source; /** * The type provider used to access the known types. */ final TypeProvider _typeProvider; /** * The type system primitives. */ final TypeSystem _typeSystem; /** * Initialize a newly created evaluator to evaluate expressions in the given * [source]. The [typeProvider] is the type provider used to access known * types. */ ConstantEvaluator(this._source, TypeProvider typeProvider, {TypeSystem typeSystem}) : _typeSystem = typeSystem ?? new Dart2TypeSystem(typeProvider), _typeProvider = typeProvider; EvaluationResult evaluate(Expression expression) { RecordingErrorListener errorListener = new RecordingErrorListener(); ErrorReporter errorReporter = new ErrorReporter(errorListener, _source); DartObjectImpl result = expression.accept(new ConstantVisitor( new ConstantEvaluationEngine(_typeProvider, new DeclaredVariables(), typeSystem: _typeSystem), errorReporter)); List<AnalysisError> errors = errorListener.errors; if (errors.isNotEmpty) { return EvaluationResult.forErrors(errors); } if (result != null) { return EvaluationResult.forValue(result); } // We should not get here. Either there should be a valid value or there // should be an error explaining why a value could not be generated. return EvaluationResult.forErrors(errors); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/static_type_analyzer.dart
// Copyright (c) 2014, 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:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.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/dart/element/member.dart' show ConstructorMember; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/element/type_algebra.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:analyzer/src/generated/variable_type_provider.dart'; import 'package:analyzer/src/task/strong/checker.dart' show getExpressionType, getReadType; import 'package:meta/meta.dart'; /** * Instances of the class `StaticTypeAnalyzer` perform two type-related tasks. First, they * compute the static type of every expression. Second, they look for any static type errors or * warnings that might need to be generated. The requirements for the type analyzer are: * <ol> * * Every element that refers to types should be fully populated. * * Every node representing an expression should be resolved to the Type of the expression. * </ol> */ class StaticTypeAnalyzer extends SimpleAstVisitor<void> { /** * The resolver driving the resolution and type analysis. */ final ResolverVisitor _resolver; /** * The feature set that should be used to resolve types. */ final FeatureSet _featureSet; /** * The object providing access to the types defined by the language. */ TypeProvider _typeProvider; /** * The type system in use for static type analysis. */ Dart2TypeSystem _typeSystem; /** * The type representing the type 'dynamic'. */ DartType _dynamicType; /** * True if inference failures should be reported, otherwise false. */ bool _strictInference; /** * The type representing the class containing the nodes being analyzed, * or `null` if the nodes are not within a class. */ DartType thisType; /** * The object providing promoted or declared types of variables. */ LocalVariableTypeProvider _localVariableTypeProvider; /** * Initialize a newly created static type analyzer to analyze types for the * [_resolver] based on the * * @param resolver the resolver driving this participant */ StaticTypeAnalyzer(this._resolver, this._featureSet) { _typeProvider = _resolver.typeProvider; _typeSystem = _resolver.typeSystem; _dynamicType = _typeProvider.dynamicType; _localVariableTypeProvider = _resolver.localVariableTypeProvider; AnalysisOptionsImpl analysisOptions = _resolver.definingLibrary.context.analysisOptions; _strictInference = analysisOptions.strictInference; } NullabilitySuffix get _noneOrStarSuffix { return _nonNullableEnabled ? NullabilitySuffix.none : NullabilitySuffix.star; } /** * Return `true` if NNBD is enabled for this compilation unit. */ bool get _nonNullableEnabled => _featureSet.isEnabled(Feature.non_nullable); /** * Given a constructor name [node] and a type [type], record an inferred type * for the constructor if in strong mode. This is used to fill in any * inferred type parameters found by the resolver. */ void inferConstructorName(ConstructorName node, InterfaceType type) { // TODO(scheglov) Inline. node.type.type = type; // TODO(scheglov) Remove when DDC stops using analyzer. var element = type.element; if (element.typeParameters.isNotEmpty) { var typeParameterBounds = _typeSystem.instantiateTypeFormalsToBounds( element.typeParameters, ); var instantiatedToBounds = element.instantiate( typeArguments: typeParameterBounds, nullabilitySuffix: _noneOrStarSuffix, ); if (type != instantiatedToBounds) { _resolver.inferenceContext.recordInference(node.parent, type); } } } /** * Given a formal parameter list and a function type use the function type * to infer types for any of the parameters which have implicit (missing) * types. Returns true if inference has occurred. */ bool inferFormalParameterList( FormalParameterList node, DartType functionType) { bool inferred = false; if (node != null && functionType is FunctionType) { void inferType(ParameterElementImpl p, DartType inferredType) { // Check that there is no declared type, and that we have not already // inferred a type in some fashion. if (p.hasImplicitType && (p.type == null || p.type.isDynamic)) { inferredType = _typeSystem.upperBoundForType(inferredType); if (inferredType.isDartCoreNull) { inferredType = _typeProvider.objectType; } if (!inferredType.isDynamic) { p.type = inferredType; inferred = true; } } } List<ParameterElement> parameters = node.parameterElements; { Iterator<ParameterElement> positional = parameters.where((p) => p.isPositional).iterator; Iterator<ParameterElement> fnPositional = functionType.parameters.where((p) => p.isPositional).iterator; while (positional.moveNext() && fnPositional.moveNext()) { inferType(positional.current, fnPositional.current.type); } } { Map<String, DartType> namedParameterTypes = functionType.namedParameterTypes; Iterable<ParameterElement> named = parameters.where((p) => p.isNamed); for (ParameterElementImpl p in named) { if (!namedParameterTypes.containsKey(p.name)) { continue; } inferType(p, namedParameterTypes[p.name]); } } } return inferred; } DartType inferListType(ListLiteral node, {bool downwards: false}) { DartType contextType = InferenceContext.getContext(node); var element = _typeProvider.listElement; var typeParameters = element.typeParameters; var genericElementType = typeParameters[0].instantiate( nullabilitySuffix: _noneOrStarSuffix, ); List<DartType> elementTypes; List<ParameterElement> parameters; if (downwards) { if (contextType == null) { return null; } elementTypes = []; parameters = []; } else { // Also use upwards information to infer the type. elementTypes = node.elements .map((element) => _computeElementType(element)) .where((t) => t != null) .toList(); var syntheticParameter = ParameterElementImpl.synthetic( 'element', genericElementType, ParameterKind.POSITIONAL); parameters = List.filled(elementTypes.length, syntheticParameter); } if (_strictInference && parameters.isEmpty && contextType == null) { // We cannot infer the type of a collection literal with no elements, and // no context type. If there are any elements, inference has not failed, // as the types of those elements are considered resolved. _resolver.errorReporter.reportErrorForNode( HintCode.INFERENCE_FAILURE_ON_COLLECTION_LITERAL, node, ['List']); } var typeArguments = _typeSystem.inferGenericFunctionOrType( typeParameters: typeParameters, parameters: parameters, declaredReturnType: element.thisType, argumentTypes: elementTypes, contextReturnType: contextType, downwards: downwards, isConst: node.isConst, errorReporter: _resolver.errorReporter, errorNode: node, ); return element.instantiate( typeArguments: typeArguments, nullabilitySuffix: _noneOrStarSuffix, ); } ParameterizedType inferMapTypeDownwards( SetOrMapLiteral node, DartType contextType) { if (contextType == null) { return null; } var element = _typeProvider.mapElement; var typeArguments = _typeSystem.inferGenericFunctionOrType( typeParameters: element.typeParameters, parameters: const [], declaredReturnType: element.thisType, argumentTypes: const [], contextReturnType: contextType, downwards: true, isConst: node.isConst, errorReporter: _resolver.errorReporter, errorNode: node, ); return element.instantiate( typeArguments: typeArguments, nullabilitySuffix: _noneOrStarSuffix, ); } DartType inferSetTypeDownwards(SetOrMapLiteral node, DartType contextType) { if (contextType == null) { return null; } var element = _typeProvider.setElement; var typeArguments = _typeSystem.inferGenericFunctionOrType( typeParameters: element.typeParameters, parameters: const [], declaredReturnType: element.thisType, argumentTypes: const [], contextReturnType: contextType, downwards: true, isConst: node.isConst, errorReporter: _resolver.errorReporter, errorNode: node, ); return element.instantiate( typeArguments: typeArguments, nullabilitySuffix: _noneOrStarSuffix, ); } /** * The Dart Language Specification, 12.5: <blockquote>The static type of a string literal is * `String`.</blockquote> */ @override void visitAdjacentStrings(AdjacentStrings node) { _recordStaticType(node, _nonNullable(_typeProvider.stringType)); } /** * The Dart Language Specification, 12.32: <blockquote>... the cast expression <i>e as T</i> ... * * It is a static warning if <i>T</i> does not denote a type available in the current lexical * scope. * * The static type of a cast expression <i>e as T</i> is <i>T</i>.</blockquote> */ @override void visitAsExpression(AsExpression node) { _recordStaticType(node, _getType(node.type)); } /** * The Dart Language Specification, 12.18: <blockquote>... an assignment <i>a</i> of the form <i>v * = e</i> ... * * It is a static type warning if the static type of <i>e</i> may not be assigned to the static * type of <i>v</i>. * * The static type of the expression <i>v = e</i> is the static type of <i>e</i>. * * ... an assignment of the form <i>C.v = e</i> ... * * It is a static type warning if the static type of <i>e</i> may not be assigned to the static * type of <i>C.v</i>. * * The static type of the expression <i>C.v = e</i> is the static type of <i>e</i>. * * ... an assignment of the form <i>e<sub>1</sub>.v = e<sub>2</sub></i> ... * * Let <i>T</i> be the static type of <i>e<sub>1</sub></i>. It is a static type warning if * <i>T</i> does not have an accessible instance setter named <i>v=</i>. It is a static type * warning if the static type of <i>e<sub>2</sub></i> may not be assigned to <i>T</i>. * * The static type of the expression <i>e<sub>1</sub>.v = e<sub>2</sub></i> is the static type of * <i>e<sub>2</sub></i>. * * ... an assignment of the form <i>e<sub>1</sub>[e<sub>2</sub>] = e<sub>3</sub></i> ... * * The static type of the expression <i>e<sub>1</sub>[e<sub>2</sub>] = e<sub>3</sub></i> is the * static type of <i>e<sub>3</sub></i>. * * A compound assignment of the form <i>v op= e</i> is equivalent to <i>v = v op e</i>. A compound * assignment of the form <i>C.v op= e</i> is equivalent to <i>C.v = C.v op e</i>. A compound * assignment of the form <i>e<sub>1</sub>.v op= e<sub>2</sub></i> is equivalent to <i>((x) => x.v * = x.v op e<sub>2</sub>)(e<sub>1</sub>)</i> where <i>x</i> is a variable that is not used in * <i>e<sub>2</sub></i>. A compound assignment of the form <i>e<sub>1</sub>[e<sub>2</sub>] op= * e<sub>3</sub></i> is equivalent to <i>((a, i) => a[i] = a[i] op e<sub>3</sub>)(e<sub>1</sub>, * e<sub>2</sub>)</i> where <i>a</i> and <i>i</i> are a variables that are not used in * <i>e<sub>3</sub></i>.</blockquote> */ @override void visitAssignmentExpression(AssignmentExpression node) { TokenType operator = node.operator.type; if (operator == TokenType.EQ) { Expression rightHandSide = node.rightHandSide; DartType staticType = _getStaticType(rightHandSide); _recordStaticType(node, staticType); } else if (operator == TokenType.QUESTION_QUESTION_EQ) { if (_nonNullableEnabled) { // The static type of a compound assignment using ??= with NNBD is the // least upper bound of the static types of the LHS and RHS after // promoting the LHS/ to non-null (as we know its value will not be used // if null) _analyzeLeastUpperBoundTypes( node, _typeSystem.promoteToNonNull( _getExpressionType(node.leftHandSide, read: true)), _getExpressionType(node.rightHandSide, read: true)); } else { // The static type of a compound assignment using ??= before NNBD is the // least upper bound of the static types of the LHS and RHS. _analyzeLeastUpperBound(node, node.leftHandSide, node.rightHandSide, read: true); } return; } else if (operator == TokenType.AMPERSAND_AMPERSAND_EQ || operator == TokenType.BAR_BAR_EQ) { _recordStaticType(node, _nonNullable(_typeProvider.boolType)); } else { var operatorElement = node.staticElement; var type = operatorElement?.returnType ?? _dynamicType; type = _typeSystem.refineBinaryExpressionType( _getStaticType(node.leftHandSide, read: true), operator, node.rightHandSide.staticType, type, _featureSet, ); _recordStaticType(node, type); var leftWriteType = _getStaticType(node.leftHandSide); if (!_typeSystem.isAssignableTo(type, leftWriteType, featureSet: _featureSet)) { _resolver.errorReporter.reportTypeErrorForNode( StaticTypeWarningCode.INVALID_ASSIGNMENT, node.rightHandSide, [type, leftWriteType], ); } } _nullShortingTermination(node); } /** * The Dart Language Specification, 16.29 (Await Expressions): * * The static type of [the expression "await e"] is flatten(T) where T is * the static type of e. */ @override void visitAwaitExpression(AwaitExpression node) { // Await the Future. This results in whatever type is (ultimately) returned. DartType awaitType(DartType awaitedType) { if (awaitedType == null) { return null; } if (awaitedType.isDartAsyncFutureOr) { return awaitType((awaitedType as InterfaceType).typeArguments[0]); } return _typeSystem.flatten(awaitedType); } _recordStaticType(node, awaitType(_getStaticType(node.expression))); } /** * The Dart Language Specification, 12.20: <blockquote>The static type of a logical boolean * expression is `bool`.</blockquote> * * The Dart Language Specification, 12.21:<blockquote>A bitwise expression of the form * <i>e<sub>1</sub> op e<sub>2</sub></i> is equivalent to the method invocation * <i>e<sub>1</sub>.op(e<sub>2</sub>)</i>. A bitwise expression of the form <i>super op * e<sub>2</sub></i> is equivalent to the method invocation * <i>super.op(e<sub>2</sub>)</i>.</blockquote> * * The Dart Language Specification, 12.22: <blockquote>The static type of an equality expression * is `bool`.</blockquote> * * The Dart Language Specification, 12.23: <blockquote>A relational expression of the form * <i>e<sub>1</sub> op e<sub>2</sub></i> is equivalent to the method invocation * <i>e<sub>1</sub>.op(e<sub>2</sub>)</i>. A relational expression of the form <i>super op * e<sub>2</sub></i> is equivalent to the method invocation * <i>super.op(e<sub>2</sub>)</i>.</blockquote> * * The Dart Language Specification, 12.24: <blockquote>A shift expression of the form * <i>e<sub>1</sub> op e<sub>2</sub></i> is equivalent to the method invocation * <i>e<sub>1</sub>.op(e<sub>2</sub>)</i>. A shift expression of the form <i>super op * e<sub>2</sub></i> is equivalent to the method invocation * <i>super.op(e<sub>2</sub>)</i>.</blockquote> * * The Dart Language Specification, 12.25: <blockquote>An additive expression of the form * <i>e<sub>1</sub> op e<sub>2</sub></i> is equivalent to the method invocation * <i>e<sub>1</sub>.op(e<sub>2</sub>)</i>. An additive expression of the form <i>super op * e<sub>2</sub></i> is equivalent to the method invocation * <i>super.op(e<sub>2</sub>)</i>.</blockquote> * * The Dart Language Specification, 12.26: <blockquote>A multiplicative expression of the form * <i>e<sub>1</sub> op e<sub>2</sub></i> is equivalent to the method invocation * <i>e<sub>1</sub>.op(e<sub>2</sub>)</i>. A multiplicative expression of the form <i>super op * e<sub>2</sub></i> is equivalent to the method invocation * <i>super.op(e<sub>2</sub>)</i>.</blockquote> */ @override void visitBinaryExpression(BinaryExpression node) { if (node.operator.type == TokenType.QUESTION_QUESTION) { if (_nonNullableEnabled) { // The static type of a compound assignment using ??= with NNBD is the // least upper bound of the static types of the LHS and RHS after // promoting the LHS/ to non-null (as we know its value will not be used // if null) _analyzeLeastUpperBoundTypes( node, _typeSystem.promoteToNonNull( _getExpressionType(node.leftOperand, read: true)), _getExpressionType(node.rightOperand, read: true)); } else { // Without NNBD, evaluation of an if-null expression e of the form // e1 ?? e2 is equivalent to the evaluation of the expression // ((x) => x == null ? e2 : x)(e1). The static type of e is the least // upper bound of the static type of e1 and the static type of e2. _analyzeLeastUpperBound(node, node.leftOperand, node.rightOperand); } return; } DartType staticType = node.staticInvokeType?.returnType ?? _dynamicType; if (node.leftOperand is! ExtensionOverride) { staticType = _typeSystem.refineBinaryExpressionType( node.leftOperand.staticType, node.operator.type, node.rightOperand.staticType, staticType, _featureSet); } _recordStaticType(node, staticType); } /** * The Dart Language Specification, 12.4: <blockquote>The static type of a boolean literal is * bool.</blockquote> */ @override void visitBooleanLiteral(BooleanLiteral node) { _recordStaticType(node, _nonNullable(_typeProvider.boolType)); } /** * The Dart Language Specification, 12.15.2: <blockquote>A cascaded method invocation expression * of the form <i>e..suffix</i> is equivalent to the expression <i>(t) {t.suffix; return * t;}(e)</i>.</blockquote> */ @override void visitCascadeExpression(CascadeExpression node) { _recordStaticType(node, _getStaticType(node.target)); } /** * The Dart Language Specification, 12.19: <blockquote> ... a conditional expression <i>c</i> of * the form <i>e<sub>1</sub> ? e<sub>2</sub> : e<sub>3</sub></i> ... * * It is a static type warning if the type of e<sub>1</sub> may not be assigned to `bool`. * * The static type of <i>c</i> is the least upper bound of the static type of <i>e<sub>2</sub></i> * and the static type of <i>e<sub>3</sub></i>.</blockquote> */ @override void visitConditionalExpression(ConditionalExpression node) { _analyzeLeastUpperBound(node, node.thenExpression, node.elseExpression); } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { super.visitDeclaredIdentifier(node); _inferForEachLoopVariableType(node); } /** * The Dart Language Specification, 12.3: <blockquote>The static type of a literal double is * double.</blockquote> */ @override void visitDoubleLiteral(DoubleLiteral node) { _recordStaticType(node, _nonNullable(_typeProvider.doubleType)); } @override void visitExtensionOverride(ExtensionOverride node) { _resolver.extensionResolver.resolveOverride(node); } @override void visitFunctionDeclaration(FunctionDeclaration node) { FunctionExpression function = node.functionExpression; ExecutableElementImpl functionElement = node.declaredElement as ExecutableElementImpl; if (node.parent is FunctionDeclarationStatement) { // TypeResolverVisitor sets the return type for top-level functions, so // we only need to handle local functions. if (node.returnType == null) { _inferLocalFunctionReturnType(node.functionExpression); return; } functionElement.returnType = _computeStaticReturnTypeOfFunctionDeclaration(node); } _recordStaticType(function, functionElement.type); } /** * The Dart Language Specification, 12.9: <blockquote>The static type of a function literal of the * form <i>(T<sub>1</sub> a<sub>1</sub>, &hellip;, T<sub>n</sub> a<sub>n</sub>, [T<sub>n+1</sub> * x<sub>n+1</sub> = d1, &hellip;, T<sub>n+k</sub> x<sub>n+k</sub> = dk]) => e</i> is * <i>(T<sub>1</sub>, &hellip;, Tn, [T<sub>n+1</sub> x<sub>n+1</sub>, &hellip;, T<sub>n+k</sub> * x<sub>n+k</sub>]) &rarr; T<sub>0</sub></i>, where <i>T<sub>0</sub></i> is the static type of * <i>e</i>. In any case where <i>T<sub>i</sub>, 1 &lt;= i &lt;= n</i>, is not specified, it is * considered to have been specified as dynamic. * * The static type of a function literal of the form <i>(T<sub>1</sub> a<sub>1</sub>, &hellip;, * T<sub>n</sub> a<sub>n</sub>, {T<sub>n+1</sub> x<sub>n+1</sub> : d1, &hellip;, T<sub>n+k</sub> * x<sub>n+k</sub> : dk}) => e</i> is <i>(T<sub>1</sub>, &hellip;, T<sub>n</sub>, {T<sub>n+1</sub> * x<sub>n+1</sub>, &hellip;, T<sub>n+k</sub> x<sub>n+k</sub>}) &rarr; T<sub>0</sub></i>, where * <i>T<sub>0</sub></i> is the static type of <i>e</i>. In any case where <i>T<sub>i</sub>, 1 * &lt;= i &lt;= n</i>, is not specified, it is considered to have been specified as dynamic. * * The static type of a function literal of the form <i>(T<sub>1</sub> a<sub>1</sub>, &hellip;, * T<sub>n</sub> a<sub>n</sub>, [T<sub>n+1</sub> x<sub>n+1</sub> = d1, &hellip;, T<sub>n+k</sub> * x<sub>n+k</sub> = dk]) {s}</i> is <i>(T<sub>1</sub>, &hellip;, T<sub>n</sub>, [T<sub>n+1</sub> * x<sub>n+1</sub>, &hellip;, T<sub>n+k</sub> x<sub>n+k</sub>]) &rarr; dynamic</i>. In any case * where <i>T<sub>i</sub>, 1 &lt;= i &lt;= n</i>, is not specified, it is considered to have been * specified as dynamic. * * The static type of a function literal of the form <i>(T<sub>1</sub> a<sub>1</sub>, &hellip;, * T<sub>n</sub> a<sub>n</sub>, {T<sub>n+1</sub> x<sub>n+1</sub> : d1, &hellip;, T<sub>n+k</sub> * x<sub>n+k</sub> : dk}) {s}</i> is <i>(T<sub>1</sub>, &hellip;, T<sub>n</sub>, {T<sub>n+1</sub> * x<sub>n+1</sub>, &hellip;, T<sub>n+k</sub> x<sub>n+k</sub>}) &rarr; dynamic</i>. In any case * where <i>T<sub>i</sub>, 1 &lt;= i &lt;= n</i>, is not specified, it is considered to have been * specified as dynamic.</blockquote> */ @override void visitFunctionExpression(FunctionExpression node) { if (node.parent is FunctionDeclaration) { // The function type will be resolved and set when we visit the parent // node. return; } _inferLocalFunctionReturnType(node); } /** * The Dart Language Specification, 12.14.4: <blockquote>A function expression invocation <i>i</i> * has the form <i>e<sub>f</sub>(a<sub>1</sub>, &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: * a<sub>n+1</sub>, &hellip;, x<sub>n+k</sub>: a<sub>n+k</sub>)</i>, where <i>e<sub>f</sub></i> is * an expression. * * It is a static type warning if the static type <i>F</i> of <i>e<sub>f</sub></i> may not be * assigned to a function type. * * If <i>F</i> is not a function type, the static type of <i>i</i> is dynamic. Otherwise the * static type of <i>i</i> is the declared return type of <i>F</i>.</blockquote> */ @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { _inferGenericInvocationExpression(node); DartType staticType = _computeInvokeReturnType(node.staticInvokeType, isNullAware: false); _recordStaticType(node, staticType); } /** * The Dart Language Specification, 12.29: <blockquote>An assignable expression of the form * <i>e<sub>1</sub>[e<sub>2</sub>]</i> is evaluated as a method invocation of the operator method * <i>[]</i> on <i>e<sub>1</sub></i> with argument <i>e<sub>2</sub></i>.</blockquote> */ @override void visitIndexExpression(IndexExpression node) { DartType type; if (node.inSetterContext()) { var parameters = node.staticElement?.parameters; if (parameters?.length == 2) { type = parameters[1].type; } } else { type = node.staticElement?.returnType; } type ??= _dynamicType; _recordStaticType(node, type); _nullShortingTermination(node); } /** * The Dart Language Specification, 12.11.1: <blockquote>The static type of a new expression of * either the form <i>new T.id(a<sub>1</sub>, &hellip;, a<sub>n</sub>)</i> or the form <i>new * T(a<sub>1</sub>, &hellip;, a<sub>n</sub>)</i> is <i>T</i>.</blockquote> * * The Dart Language Specification, 12.11.2: <blockquote>The static type of a constant object * expression of either the form <i>const T.id(a<sub>1</sub>, &hellip;, a<sub>n</sub>)</i> or the * form <i>const T(a<sub>1</sub>, &hellip;, a<sub>n</sub>)</i> is <i>T</i>. </blockquote> */ @override void visitInstanceCreationExpression(InstanceCreationExpression node) { _inferInstanceCreationExpression(node); _recordStaticType(node, node.constructorName.type.type); } /** * <blockquote> * An integer literal has static type \code{int}, unless the surrounding * static context type is a type which \code{int} is not assignable to, and * \code{double} is. In that case the static type of the integer literal is * \code{double}. * <blockquote> * * and * * <blockquote> * If $e$ is an expression of the form \code{-$l$} where $l$ is an integer * literal (\ref{numbers}) with numeric integer value $i$, then the static * type of $e$ is the same as the static type of an integer literal with the * same contexttype * </blockquote> */ @override void visitIntegerLiteral(IntegerLiteral node) { // Check the parent context for negated integer literals. var context = InferenceContext.getContext( (node as IntegerLiteralImpl).immediatelyNegated ? node.parent : node); if (context == null || _typeSystem.isAssignableTo(_typeProvider.intType, context, featureSet: _featureSet) || !_typeSystem.isAssignableTo(_typeProvider.doubleType, context, featureSet: _featureSet)) { _recordStaticType(node, _nonNullable(_typeProvider.intType)); } else { _recordStaticType(node, _nonNullable(_typeProvider.doubleType)); } } /** * The Dart Language Specification, 12.31: <blockquote>It is a static warning if <i>T</i> does not * denote a type available in the current lexical scope. * * The static type of an is-expression is `bool`.</blockquote> */ @override void visitIsExpression(IsExpression node) { _recordStaticType(node, _nonNullable(_typeProvider.boolType)); } /** * The Dart Language Specification, 12.6: <blockquote>The static type of a list literal of the * form <i><b>const</b> &lt;E&gt;[e<sub>1</sub>, &hellip;, e<sub>n</sub>]</i> or the form * <i>&lt;E&gt;[e<sub>1</sub>, &hellip;, e<sub>n</sub>]</i> is `List&lt;E&gt;`. The static * type a list literal of the form <i><b>const</b> [e<sub>1</sub>, &hellip;, e<sub>n</sub>]</i> or * the form <i>[e<sub>1</sub>, &hellip;, e<sub>n</sub>]</i> is `List&lt;dynamic&gt;` * .</blockquote> */ @override void visitListLiteral(ListLiteral node) { TypeArgumentList typeArguments = node.typeArguments; // If we have explicit arguments, use them. if (typeArguments != null) { DartType staticType = _dynamicType; NodeList<TypeAnnotation> arguments = typeArguments.arguments; if (arguments != null && arguments.length == 1) { DartType argumentType = _getType(arguments[0]); if (argumentType != null) { staticType = argumentType; } } _recordStaticType( node, _nonNullable(_typeProvider.listType2(staticType))); return; } DartType listDynamicType = _typeProvider.listType2(_dynamicType); // If there are no type arguments, try to infer some arguments. DartType inferred = inferListType(node); if (inferred != listDynamicType) { // TODO(jmesserly): this results in an "inferred" message even when we // in fact had an error above, because it will still attempt to return // a type. Perhaps we should record inference from TypeSystem if // everything was successful? // TODO(brianwilkerson) Determine whether we need to make the inferred // type non-nullable here or whether it will already be non-nullable. _resolver.inferenceContext.recordInference(node, inferred); _recordStaticType(node, inferred); return; } // If we have no type arguments and couldn't infer any, use dynamic. _recordStaticType(node, listDynamicType); } /** * The Dart Language Specification, 12.15.1: <blockquote>An ordinary method invocation <i>i</i> * has the form <i>o.m(a<sub>1</sub>, &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, * &hellip;, x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. * * Let <i>T</i> be the static type of <i>o</i>. It is a static type warning if <i>T</i> does not * have an accessible instance member named <i>m</i>. If <i>T.m</i> exists, it is a static warning * if the type <i>F</i> of <i>T.m</i> may not be assigned to a function type. * * If <i>T.m</i> does not exist, or if <i>F</i> is not a function type, the static type of * <i>i</i> is dynamic. Otherwise the static type of <i>i</i> is the declared return type of * <i>F</i>.</blockquote> * * The Dart Language Specification, 11.15.3: <blockquote>A static method invocation <i>i</i> has * the form <i>C.m(a<sub>1</sub>, &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, * &hellip;, x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. * * It is a static type warning if the type <i>F</i> of <i>C.m</i> may not be assigned to a * function type. * * If <i>F</i> is not a function type, or if <i>C.m</i> does not exist, the static type of i is * dynamic. Otherwise the static type of <i>i</i> is the declared return type of * <i>F</i>.</blockquote> * * The Dart Language Specification, 11.15.4: <blockquote>A super method invocation <i>i</i> has * the form <i>super.m(a<sub>1</sub>, &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, * &hellip;, x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. * * It is a static type warning if <i>S</i> does not have an accessible instance member named m. If * <i>S.m</i> exists, it is a static warning if the type <i>F</i> of <i>S.m</i> may not be * assigned to a function type. * * If <i>S.m</i> does not exist, or if <i>F</i> is not a function type, the static type of * <i>i</i> is dynamic. Otherwise the static type of <i>i</i> is the declared return type of * <i>F</i>.</blockquote> */ @override void visitMethodInvocation(MethodInvocation node) { _inferGenericInvocationExpression(node); // Record static return type of the static element. bool inferredStaticType = _inferMethodInvocationObject(node) || _inferMethodInvocationInlineJS(node); if (!inferredStaticType) { DartType staticStaticType = _computeInvokeReturnType( node.staticInvokeType, isNullAware: node.isNullAware); _recordStaticType(node, staticStaticType); } } @override void visitNamedExpression(NamedExpression node) { Expression expression = node.expression; _recordStaticType(node, _getStaticType(expression)); } /** * The Dart Language Specification, 12.2: <blockquote>The static type of `null` is bottom. * </blockquote> */ @override void visitNullLiteral(NullLiteral node) { _recordStaticType(node, _typeProvider.nullType); } @override void visitParenthesizedExpression(ParenthesizedExpression node) { Expression expression = node.expression; _recordStaticType(node, _getStaticType(expression)); } /** * The Dart Language Specification, 12.28: <blockquote>A postfix expression of the form * <i>v++</i>, where <i>v</i> is an identifier, is equivalent to <i>(){var r = v; v = r + 1; * return r}()</i>. * * A postfix expression of the form <i>C.v++</i> is equivalent to <i>(){var r = C.v; C.v = r + 1; * return r}()</i>. * * A postfix expression of the form <i>e1.v++</i> is equivalent to <i>(x){var r = x.v; x.v = r + * 1; return r}(e1)</i>. * * A postfix expression of the form <i>e1[e2]++</i> is equivalent to <i>(a, i){var r = a[i]; a[i] * = r + 1; return r}(e1, e2)</i> * * A postfix expression of the form <i>v--</i>, where <i>v</i> is an identifier, is equivalent to * <i>(){var r = v; v = r - 1; return r}()</i>. * * A postfix expression of the form <i>C.v--</i> is equivalent to <i>(){var r = C.v; C.v = r - 1; * return r}()</i>. * * A postfix expression of the form <i>e1.v--</i> is equivalent to <i>(x){var r = x.v; x.v = r - * 1; return r}(e1)</i>. * * A postfix expression of the form <i>e1[e2]--</i> is equivalent to <i>(a, i){var r = a[i]; a[i] * = r - 1; return r}(e1, e2)</i></blockquote> */ @override void visitPostfixExpression(PostfixExpression node) { Expression operand = node.operand; TypeImpl staticType = _getStaticType(operand, read: true); if (node.operator.type == TokenType.BANG) { staticType = _typeSystem.promoteToNonNull(staticType); } else { // No need to check for `intVar++`, the result is `int`. if (!staticType.isDartCoreInt) { var operatorElement = node.staticElement; var operatorReturnType = _computeStaticReturnType(operatorElement); _checkForInvalidAssignmentIncDec(node, operand, operatorReturnType); } } _recordStaticType(node, staticType); } /** * See [visitSimpleIdentifier]. */ @override void visitPrefixedIdentifier(PrefixedIdentifier node) { SimpleIdentifier prefixedIdentifier = node.identifier; Element staticElement = prefixedIdentifier.staticElement; if (staticElement is ExtensionElement) { _setExtensionIdentifierType(node); return; } DartType staticType = _dynamicType; if (staticElement is ClassElement) { if (_isNotTypeLiteral(node)) { staticType = staticElement.type; } else { staticType = _nonNullable(_typeProvider.typeType); } } else if (staticElement is FunctionTypeAliasElement) { if (_isNotTypeLiteral(node)) { staticType = staticElement.type; } else { staticType = _nonNullable(_typeProvider.typeType); } } else if (staticElement is MethodElement) { staticType = staticElement.type; } else if (staticElement is PropertyAccessorElement) { staticType = _getTypeOfProperty(staticElement); } else if (staticElement is ExecutableElement) { staticType = staticElement.type; } else if (staticElement is TypeParameterElement) { staticType = staticElement.type; } else if (staticElement is VariableElement) { staticType = staticElement.type; } staticType = _inferTearOff(node, node.identifier, staticType); if (!_inferObjectAccess(node, staticType, prefixedIdentifier)) { _recordStaticType(prefixedIdentifier, staticType); _recordStaticType(node, staticType); } } /** * The Dart Language Specification, 12.27: <blockquote>A unary expression <i>u</i> of the form * <i>op e</i> is equivalent to a method invocation <i>expression e.op()</i>. An expression of the * form <i>op super</i> is equivalent to the method invocation <i>super.op()<i>.</blockquote> */ @override void visitPrefixExpression(PrefixExpression node) { TokenType operator = node.operator.type; if (operator == TokenType.BANG) { _recordStaticType(node, _nonNullable(_typeProvider.boolType)); } else { // The other cases are equivalent to invoking a method. ExecutableElement staticMethodElement = node.staticElement; DartType staticType = _computeStaticReturnType(staticMethodElement); if (operator == TokenType.MINUS_MINUS || operator == TokenType.PLUS_PLUS) { Expression operand = node.operand; var operandReadType = _getStaticType(operand, read: true); if (operandReadType.isDartCoreInt) { staticType = _nonNullable(_typeProvider.intType); } else { _checkForInvalidAssignmentIncDec(node, operand, staticType); } } _recordStaticType(node, staticType); } } /** * The Dart Language Specification, 12.13: <blockquote> Property extraction allows for a member of * an object to be concisely extracted from the object. If <i>o</i> is an object, and if <i>m</i> * is the name of a method member of <i>o</i>, then * * <i>o.m</i> is defined to be equivalent to: <i>(r<sub>1</sub>, &hellip;, r<sub>n</sub>, * {p<sub>1</sub> : d<sub>1</sub>, &hellip;, p<sub>k</sub> : d<sub>k</sub>}){return * o.m(r<sub>1</sub>, &hellip;, r<sub>n</sub>, p<sub>1</sub>: p<sub>1</sub>, &hellip;, * p<sub>k</sub>: p<sub>k</sub>);}</i> if <i>m</i> has required parameters <i>r<sub>1</sub>, * &hellip;, r<sub>n</sub></i>, and named parameters <i>p<sub>1</sub> &hellip; p<sub>k</sub></i> * with defaults <i>d<sub>1</sub>, &hellip;, d<sub>k</sub></i>. * * <i>(r<sub>1</sub>, &hellip;, r<sub>n</sub>, [p<sub>1</sub> = d<sub>1</sub>, &hellip;, * p<sub>k</sub> = d<sub>k</sub>]){return o.m(r<sub>1</sub>, &hellip;, r<sub>n</sub>, * p<sub>1</sub>, &hellip;, p<sub>k</sub>);}</i> if <i>m</i> has required parameters * <i>r<sub>1</sub>, &hellip;, r<sub>n</sub></i>, and optional positional parameters * <i>p<sub>1</sub> &hellip; p<sub>k</sub></i> with defaults <i>d<sub>1</sub>, &hellip;, * d<sub>k</sub></i>. * Otherwise, if <i>m</i> is the name of a getter member of <i>o</i> (declared implicitly or * explicitly) then <i>o.m</i> evaluates to the result of invoking the getter. </blockquote> * * The Dart Language Specification, 12.17: <blockquote> ... a getter invocation <i>i</i> of the * form <i>e.m</i> ... * * Let <i>T</i> be the static type of <i>e</i>. It is a static type warning if <i>T</i> does not * have a getter named <i>m</i>. * * The static type of <i>i</i> is the declared return type of <i>T.m</i>, if <i>T.m</i> exists; * otherwise the static type of <i>i</i> is dynamic. * * ... a getter invocation <i>i</i> of the form <i>C.m</i> ... * * It is a static warning if there is no class <i>C</i> in the enclosing lexical scope of * <i>i</i>, or if <i>C</i> does not declare, implicitly or explicitly, a getter named <i>m</i>. * * The static type of <i>i</i> is the declared return type of <i>C.m</i> if it exists or dynamic * otherwise. * * ... a top-level getter invocation <i>i</i> of the form <i>m</i>, where <i>m</i> is an * identifier ... * * The static type of <i>i</i> is the declared return type of <i>m</i>.</blockquote> */ @override void visitPropertyAccess(PropertyAccess node) { SimpleIdentifier propertyName = node.propertyName; Element staticElement = propertyName.staticElement; DartType staticType = _dynamicType; if (staticElement is MethodElement) { staticType = staticElement.type; } else if (staticElement is PropertyAccessorElement) { staticType = _getTypeOfProperty(staticElement); } else { // TODO(brianwilkerson) Report this internal error. } staticType = _inferTearOff(node, node.propertyName, staticType); if (!_inferObjectAccess(node, staticType, propertyName)) { _recordStaticType(propertyName, staticType); _recordStaticType(node, staticType); _nullShortingTermination(node); } } /** * The Dart Language Specification, 12.9: <blockquote>The static type of a rethrow expression is * bottom.</blockquote> */ @override void visitRethrowExpression(RethrowExpression node) { _recordStaticType(node, _typeProvider.bottomType); } @override void visitSetOrMapLiteral(SetOrMapLiteral node) { var typeArguments = node.typeArguments?.arguments; // If we have type arguments, use them. // TODO(paulberry): this logic seems redundant with // ResolverVisitor._fromTypeArguments if (typeArguments != null) { if (typeArguments.length == 1) { (node as SetOrMapLiteralImpl).becomeSet(); var elementType = _getType(typeArguments[0]) ?? _dynamicType; _recordStaticType( node, _nonNullable(_typeProvider.setType2(elementType))); return; } else if (typeArguments.length == 2) { (node as SetOrMapLiteralImpl).becomeMap(); var keyType = _getType(typeArguments[0]) ?? _dynamicType; var valueType = _getType(typeArguments[1]) ?? _dynamicType; _recordStaticType( node, _nonNullable(_typeProvider.mapType2(keyType, valueType))); return; } // If we get here, then a nonsense number of type arguments were provided, // so treat it as though no type arguments were provided. } DartType literalType = _inferSetOrMapLiteralType(node); if (literalType.isDynamic) { // The literal is ambiguous, and further analysis won't resolve the // ambiguity. Leave it as neither a set nor a map. } else if (literalType.element == _typeProvider.mapElement) { (node as SetOrMapLiteralImpl).becomeMap(); } else { assert(literalType.element == _typeProvider.setElement); (node as SetOrMapLiteralImpl).becomeSet(); } if (_strictInference && node.elements.isEmpty && InferenceContext.getContext(node) == null) { // We cannot infer the type of a collection literal with no elements, and // no context type. If there are any elements, inference has not failed, // as the types of those elements are considered resolved. _resolver.errorReporter.reportErrorForNode( HintCode.INFERENCE_FAILURE_ON_COLLECTION_LITERAL, node, [node.isMap ? 'Map' : 'Set']); } // TODO(brianwilkerson) Decide whether the literalType needs to be made // non-nullable here or whether that will have happened in // _inferSetOrMapLiteralType. _resolver.inferenceContext.recordInference(node, literalType); _recordStaticType(node, literalType); } /** * The Dart Language Specification, 12.30: <blockquote>Evaluation of an identifier expression * <i>e</i> of the form <i>id</i> proceeds as follows: * * Let <i>d</i> be the innermost declaration in the enclosing lexical scope whose name is * <i>id</i>. If no such declaration exists in the lexical scope, let <i>d</i> be the declaration * of the inherited member named <i>id</i> if it exists. * * If <i>d</i> is a class or type alias <i>T</i>, the value of <i>e</i> is the unique instance * of class `Type` reifying <i>T</i>. * * If <i>d</i> is a type parameter <i>T</i>, then the value of <i>e</i> is the value of the * actual type argument corresponding to <i>T</i> that was passed to the generative constructor * that created the current binding of this. We are assured that this is well defined, because if * we were in a static member the reference to <i>T</i> would be a compile-time error. * * If <i>d</i> is a library variable then: * * If <i>d</i> is of one of the forms <i>var v = e<sub>i</sub>;</i>, <i>T v = * e<sub>i</sub>;</i>, <i>final v = e<sub>i</sub>;</i>, <i>final T v = e<sub>i</sub>;</i>, and no * value has yet been stored into <i>v</i> then the initializer expression <i>e<sub>i</sub></i> is * evaluated. If, during the evaluation of <i>e<sub>i</sub></i>, the getter for <i>v</i> is * referenced, a CyclicInitializationError is thrown. If the evaluation succeeded yielding an * object <i>o</i>, let <i>r = o</i>, otherwise let <i>r = null</i>. In any case, <i>r</i> is * stored into <i>v</i>. The value of <i>e</i> is <i>r</i>. * * If <i>d</i> is of one of the forms <i>const v = e;</i> or <i>const T v = e;</i> the result * of the getter is the value of the compile time constant <i>e</i>. Otherwise * * <i>e</i> evaluates to the current binding of <i>id</i>. * * If <i>d</i> is a local variable or formal parameter then <i>e</i> evaluates to the current * binding of <i>id</i>. * * If <i>d</i> is a static method, top level function or local function then <i>e</i> * evaluates to the function defined by <i>d</i>. * * If <i>d</i> is the declaration of a static variable or static getter declared in class * <i>C</i>, then <i>e</i> is equivalent to the getter invocation <i>C.id</i>. * * If <i>d</i> is the declaration of a top level getter, then <i>e</i> is equivalent to the * getter invocation <i>id</i>. * * Otherwise, if <i>e</i> occurs inside a top level or static function (be it function, * method, getter, or setter) or variable initializer, evaluation of e causes a NoSuchMethodError * to be thrown. * * Otherwise <i>e</i> is equivalent to the property extraction <i>this.id</i>. * </blockquote> */ @override void visitSimpleIdentifier(SimpleIdentifier node) { Element element = node.staticElement; if (element is ExtensionElement) { _setExtensionIdentifierType(node); return; } DartType staticType = _dynamicType; if (element is ClassElement) { if (_isNotTypeLiteral(node)) { staticType = element.type; } else { staticType = _nonNullable(_typeProvider.typeType); } } else if (element is FunctionTypeAliasElement) { if (_isNotTypeLiteral(node)) { staticType = element.type; } else { staticType = _nonNullable(_typeProvider.typeType); } } else if (element is MethodElement) { staticType = element.type; } else if (element is PropertyAccessorElement) { staticType = _getTypeOfProperty(element); } else if (element is ExecutableElement) { staticType = element.type; } else if (element is TypeParameterElement) { staticType = _nonNullable(_typeProvider.typeType); } else if (element is VariableElement) { staticType = _localVariableTypeProvider.getType(node); } else if (element is PrefixElement) { var parent = node.parent; if (parent is PrefixedIdentifier && parent.prefix == node || parent is MethodInvocation && parent.target == node) { return; } staticType = _typeProvider.dynamicType; } else if (element is DynamicElementImpl) { staticType = _nonNullable(_typeProvider.typeType); } else { staticType = _dynamicType; } staticType = _inferTearOff(node, node, staticType); _recordStaticType(node, staticType); } /** * The Dart Language Specification, 12.5: <blockquote>The static type of a string literal is * `String`.</blockquote> */ @override void visitSimpleStringLiteral(SimpleStringLiteral node) { _recordStaticType(node, _nonNullable(_typeProvider.stringType)); } /** * The Dart Language Specification, 12.5: <blockquote>The static type of a string literal is * `String`.</blockquote> */ @override void visitStringInterpolation(StringInterpolation node) { _recordStaticType(node, _nonNullable(_typeProvider.stringType)); } @override void visitSuperExpression(SuperExpression node) { if (thisType == null || node.thisOrAncestorOfType<ExtensionDeclaration>() != null) { // TODO(brianwilkerson) Report this error if it hasn't already been // reported. _recordStaticType(node, _dynamicType); } else { _recordStaticType(node, thisType); } } @override void visitSymbolLiteral(SymbolLiteral node) { _recordStaticType(node, _nonNullable(_typeProvider.symbolType)); } /** * The Dart Language Specification, 12.10: <blockquote>The static type of `this` is the * interface of the immediately enclosing class.</blockquote> */ @override void visitThisExpression(ThisExpression node) { if (thisType == null) { // TODO(brianwilkerson) Report this error if it hasn't already been // reported. _recordStaticType(node, _dynamicType); } else { _recordStaticType(node, thisType); } } /** * The Dart Language Specification, 12.8: <blockquote>The static type of a throw expression is * bottom.</blockquote> */ @override void visitThrowExpression(ThrowExpression node) { _recordStaticType(node, _typeProvider.bottomType); } @override void visitVariableDeclaration(VariableDeclaration node) { _inferLocalVariableType(node, node.initializer); } /** * Set the static type of [node] to be the least upper bound of the static * types of subexpressions [expr1] and [expr2]. */ void _analyzeLeastUpperBound( Expression node, Expression expr1, Expression expr2, {bool read: false}) { DartType staticType1 = _getExpressionType(expr1, read: read); DartType staticType2 = _getExpressionType(expr2, read: read); _analyzeLeastUpperBoundTypes(node, staticType1, staticType2); } /** * Set the static type of [node] to be the least upper bound of the static * types [staticType1] and [staticType2]. */ void _analyzeLeastUpperBoundTypes( Expression node, DartType staticType1, DartType staticType2) { if (staticType1 == null) { // TODO(brianwilkerson) Determine whether this can still happen. staticType1 = _dynamicType; } if (staticType2 == null) { // TODO(brianwilkerson) Determine whether this can still happen. staticType2 = _dynamicType; } DartType staticType = _typeSystem.getLeastUpperBound(staticType1, staticType2) ?? _dynamicType; _recordStaticType(node, staticType); } /// Check that the result [type] of a prefix or postfix `++` or `--` /// expression is assignable to the write type of the [operand]. void _checkForInvalidAssignmentIncDec( AstNode node, Expression operand, DartType type) { var operandWriteType = _getStaticType(operand); if (!_typeSystem.isAssignableTo(type, operandWriteType, featureSet: _featureSet)) { _resolver.errorReporter.reportTypeErrorForNode( StaticTypeWarningCode.INVALID_ASSIGNMENT, node, [type, operandWriteType], ); } } DartType _computeElementType(CollectionElement element) { if (element is ForElement) { return _computeElementType(element.body); } else if (element is IfElement) { DartType thenType = _computeElementType(element.thenElement); if (element.elseElement == null) { return thenType; } DartType elseType = _computeElementType(element.elseElement); return _typeSystem.leastUpperBound(thenType, elseType); } else if (element is Expression) { return element.staticType; } else if (element is MapLiteralEntry) { // This error will be reported elsewhere. return _typeProvider.dynamicType; } else if (element is SpreadElement) { DartType expressionType = element.expression.staticType; bool isNull = expressionType.isDartCoreNull; if (!isNull && expressionType is InterfaceType) { if (_typeSystem.isSubtypeOf( expressionType, _typeProvider.iterableObjectType)) { InterfaceType iterableType = (expressionType as InterfaceTypeImpl) .asInstanceOf(_typeProvider.iterableElement); return iterableType.typeArguments[0]; } } else if (expressionType.isDynamic) { return expressionType; } else if (isNull && element.isNullAware) { return expressionType; } // TODO(brianwilkerson) Report this as an error. return _typeProvider.dynamicType; } throw StateError('Unhandled element type ${element.runtimeType}'); } /** * Compute the return type of the method or function represented by the given * type that is being invoked. */ DartType /*!*/ _computeInvokeReturnType(DartType type, {@required bool isNullAware}) { TypeImpl /*!*/ returnType; if (type is InterfaceType) { MethodElement callMethod = type.lookUpMethod( FunctionElement.CALL_METHOD_NAME, _resolver.definingLibrary); returnType = callMethod?.type?.returnType ?? _dynamicType; } else if (type is FunctionType) { returnType = type.returnType ?? _dynamicType; } else { returnType = _dynamicType; } if (isNullAware && _nonNullableEnabled) { returnType = _typeSystem.makeNullable(returnType); } return returnType; } /** * Given a function body and its return type, compute the return type of * the entire function, taking into account whether the function body * is `sync*`, `async` or `async*`. * * See also [FunctionBody.isAsynchronous], [FunctionBody.isGenerator]. */ DartType _computeReturnTypeOfFunction(FunctionBody body, DartType type) { if (body.isGenerator) { InterfaceType generatedType = body.isAsynchronous ? _typeProvider.streamType2(type) : _typeProvider.iterableType2(type); return _nonNullable(generatedType); } else if (body.isAsynchronous) { if (type.isDartAsyncFutureOr) { type = (type as InterfaceType).typeArguments[0]; } DartType futureType = _typeProvider.futureType2(_typeSystem.flatten(type)); return _nonNullable(futureType); } else { return type; } } /** * Compute the static return type of the method or function represented by the given element. * * @param element the element representing the method or function invoked by the given node * @return the static return type that was computed */ DartType _computeStaticReturnType(Element element) { if (element is PropertyAccessorElement) { // // This is a function invocation expression disguised as something else. // We are invoking a getter and then invoking the returned function. // FunctionType propertyType = element.type; if (propertyType != null) { return _computeInvokeReturnType(propertyType.returnType, isNullAware: false); } } else if (element is ExecutableElement) { return _computeInvokeReturnType(element.type, isNullAware: false); } return _dynamicType; } /** * Given a function declaration, compute the return static type of the function. The return type * of functions with a block body is `dynamicType`, with an expression body it is the type * of the expression. * * @param node the function expression whose static return type is to be computed * @return the static return type that was computed */ DartType _computeStaticReturnTypeOfFunctionDeclaration( FunctionDeclaration node) { TypeAnnotation returnType = node.returnType; if (returnType == null) { return _dynamicType; } return returnType.type; } /** * If the given element name can be mapped to the name of a class defined within the given * library, return the type specified by the argument. * * @param library the library in which the specified type would be defined * @param elementName the name of the element for which a type is being sought * @param nameMap an optional map used to map the element name to a type name * @return the type specified by the first argument in the argument list */ DartType _getElementNameAsType( LibraryElement library, String elementName, Map<String, String> nameMap) { if (elementName != null) { if (nameMap != null) { elementName = nameMap[elementName.toLowerCase()]; } ClassElement returnType = library.getType(elementName); if (returnType != null) { return returnType.instantiate( typeArguments: List.filled( returnType.typeParameters.length, _dynamicType, ), nullabilitySuffix: _noneOrStarSuffix, ); } } return null; } /** * Gets the definite type of expression, which can be used in cases where * the most precise type is desired, for example computing the least upper * bound. * * See [getExpressionType] for more information. Without strong mode, this is * equivalent to [_getStaticType]. */ DartType _getExpressionType(Expression expr, {bool read: false}) => getExpressionType(expr, _typeSystem, _typeProvider, read: read); /** * If the given argument list contains at least one argument, and if the argument is a simple * string literal, return the String value of the argument. * * @param argumentList the list of arguments from which a string value is to be extracted * @return the string specified by the first argument in the argument list */ String _getFirstArgumentAsString(ArgumentList argumentList) { NodeList<Expression> arguments = argumentList.arguments; if (arguments.isNotEmpty) { Expression argument = arguments[0]; if (argument is SimpleStringLiteral) { return argument.value; } } return null; } /** * Return the static type of the given [expression]. */ DartType _getStaticType(Expression expression, {bool read: false}) { DartType type; if (read) { type = getReadType(expression); } else { type = expression.staticType; } if (type == null) { // TODO(brianwilkerson) Determine the conditions for which the static type // is null. return _dynamicType; } return type; } /** * Return the type represented by the given type [annotation]. */ DartType _getType(TypeAnnotation annotation) { DartType type = annotation.type; if (type == null) { //TODO(brianwilkerson) Determine the conditions for which the type is // null. return _dynamicType; } return type; } /** * Return the type that should be recorded for a node that resolved to the given accessor. * * @param accessor the accessor that the node resolved to * @return the type that should be recorded for a node that resolved to the given accessor */ DartType _getTypeOfProperty(PropertyAccessorElement accessor) { FunctionType functionType = accessor.type; if (functionType == null) { // TODO(brianwilkerson) Report this internal error. This happens when we // are analyzing a reference to a property before we have analyzed the // declaration of the property or when the property does not have a // defined type. return _dynamicType; } if (accessor.isSetter) { List<DartType> parameterTypes = functionType.normalParameterTypes; if (parameterTypes != null && parameterTypes.isNotEmpty) { return parameterTypes[0]; } PropertyAccessorElement getter = accessor.variable.getter; if (getter != null) { functionType = getter.type; if (functionType != null) { return functionType.returnType; } } return _dynamicType; } return functionType.returnType; } _InferredCollectionElementTypeInformation _inferCollectionElementType( CollectionElement element) { if (element is ForElement) { return _inferCollectionElementType(element.body); } else if (element is IfElement) { _InferredCollectionElementTypeInformation thenType = _inferCollectionElementType(element.thenElement); if (element.elseElement == null) { return thenType; } _InferredCollectionElementTypeInformation elseType = _inferCollectionElementType(element.elseElement); return _InferredCollectionElementTypeInformation.forIfElement( _typeSystem, thenType, elseType); } else if (element is Expression) { return _InferredCollectionElementTypeInformation( elementType: element.staticType, keyType: null, valueType: null); } else if (element is MapLiteralEntry) { return _InferredCollectionElementTypeInformation( elementType: null, keyType: element.key.staticType, valueType: element.value.staticType); } else if (element is SpreadElement) { DartType expressionType = element.expression.staticType; bool isNull = expressionType.isDartCoreNull; if (!isNull && expressionType is InterfaceType) { if (_typeSystem.isSubtypeOf( expressionType, _typeProvider.iterableObjectType)) { InterfaceType iterableType = (expressionType as InterfaceTypeImpl) .asInstanceOf(_typeProvider.iterableElement); return _InferredCollectionElementTypeInformation( elementType: iterableType.typeArguments[0], keyType: null, valueType: null); } else if (_typeSystem.isSubtypeOf( expressionType, _typeProvider.mapObjectObjectType)) { InterfaceType mapType = (expressionType as InterfaceTypeImpl) .asInstanceOf(_typeProvider.mapElement); List<DartType> typeArguments = mapType.typeArguments; return _InferredCollectionElementTypeInformation( elementType: null, keyType: typeArguments[0], valueType: typeArguments[1]); } } else if (expressionType.isDynamic) { return _InferredCollectionElementTypeInformation( elementType: expressionType, keyType: expressionType, valueType: expressionType); } else if (isNull && element.isNullAware) { return _InferredCollectionElementTypeInformation( elementType: expressionType, keyType: expressionType, valueType: expressionType); } return _InferredCollectionElementTypeInformation( elementType: null, keyType: null, valueType: null); } else { throw StateError('Unknown element type ${element.runtimeType}'); } } /** * Given a declared identifier from a foreach loop, attempt to infer * a type for it if one is not already present. Inference is based * on the type of the iterator or stream over which the foreach loop * is defined. */ void _inferForEachLoopVariableType(DeclaredIdentifier loopVariable) { if (loopVariable != null && loopVariable.type == null) { AstNode parent = loopVariable.parent; Token awaitKeyword; Expression iterable; if (parent is ForEachPartsWithDeclaration) { AstNode parentParent = parent.parent; if (parentParent is ForStatementImpl) { awaitKeyword = parentParent.awaitKeyword; } else if (parentParent is ForElement) { awaitKeyword = parentParent.awaitKeyword; } else { return; } iterable = parent.iterable; } else { return; } if (iterable != null) { LocalVariableElementImpl element = loopVariable.declaredElement; DartType iterableType = iterable.staticType; iterableType = iterableType.resolveToBound(_typeProvider.objectType); ClassElement iteratedElement = (awaitKeyword == null) ? _typeProvider.iterableElement : _typeProvider.streamElement; InterfaceType iteratedType = iterableType is InterfaceTypeImpl ? iterableType.asInstanceOf(iteratedElement) : null; if (element != null && iteratedType != null) { DartType elementType = iteratedType.typeArguments.single; element.type = elementType; loopVariable.identifier.staticType = elementType; } } } } /** * Given a possibly generic invocation like `o.m(args)` or `(f)(args)` try to * infer the instantiated generic function type. * * This takes into account both the context type, as well as information from * the argument types. */ void _inferGenericInvocationExpression(InvocationExpression node) { ArgumentList arguments = node.argumentList; var type = node.function.staticType; var freshType = _getFreshType(type); FunctionType inferred = _inferGenericInvoke( node, freshType, node.typeArguments, arguments, node.function); if (inferred != null && inferred != node.staticInvokeType) { // Fix up the parameter elements based on inferred method. arguments.correspondingStaticParameters = ResolverVisitor.resolveArgumentsToParameters( arguments, inferred.parameters, null); node.staticInvokeType = inferred; } } /** * Given a possibly generic invocation or instance creation, such as * `o.m(args)` or `(f)(args)` or `new T(args)` try to infer the instantiated * generic function type. * * This takes into account both the context type, as well as information from * the argument types. */ FunctionType _inferGenericInvoke( Expression node, DartType fnType, TypeArgumentList typeArguments, ArgumentList argumentList, AstNode errorNode, {bool isConst: false}) { if (typeArguments == null && fnType is FunctionType && fnType.typeFormals.isNotEmpty) { // Get the parameters that correspond to the uninstantiated generic. List<ParameterElement> rawParameters = ResolverVisitor.resolveArgumentsToParameters( argumentList, fnType.parameters, null); List<ParameterElement> params = <ParameterElement>[]; List<DartType> argTypes = <DartType>[]; for (int i = 0, length = rawParameters.length; i < length; i++) { ParameterElement parameter = rawParameters[i]; if (parameter != null) { params.add(parameter); argTypes.add(argumentList.arguments[i].staticType); } } var typeArgs = _typeSystem.inferGenericFunctionOrType( typeParameters: fnType.typeFormals, parameters: params, declaredReturnType: fnType.returnType, argumentTypes: argTypes, contextReturnType: InferenceContext.getContext(node), isConst: isConst, errorReporter: _resolver.errorReporter, errorNode: errorNode, ); if (node is InvocationExpressionImpl) { node.typeArgumentTypes = typeArgs; } if (typeArgs != null) { return fnType.instantiate(typeArgs); } return fnType; } // There is currently no other place where we set type arguments // for FunctionExpressionInvocation(s), so set it here, if not inferred. if (node is FunctionExpressionInvocationImpl) { if (typeArguments != null) { var typeArgs = typeArguments.arguments.map((n) => n.type).toList(); node.typeArgumentTypes = typeArgs; } else { node.typeArgumentTypes = const <DartType>[]; } } return null; } /** * Given an instance creation of a possibly generic type, infer the type * arguments using the current context type as well as the argument types. */ void _inferInstanceCreationExpression(InstanceCreationExpression node) { ConstructorName constructor = node.constructorName; ConstructorElement originalElement = constructor.staticElement; // If the constructor is generic, we'll have a ConstructorMember that // substitutes in type arguments (possibly `dynamic`) from earlier in // resolution. // // Otherwise we'll have a ConstructorElement, and we can skip inference // because there's nothing to infer in a non-generic type. if (originalElement is! ConstructorMember) { return; } // TODO(leafp): Currently, we may re-infer types here, since we // sometimes resolve multiple times. We should really check that we // have not already inferred something. However, the obvious ways to // check this don't work, since we may have been instantiated // to bounds in an earlier phase, and we *do* want to do inference // in that case. // Get back to the uninstantiated generic constructor. // TODO(jmesserly): should we store this earlier in resolution? // Or look it up, instead of jumping backwards through the Member? var rawElement = (originalElement as ConstructorMember).baseElement; FunctionType constructorType = constructorToGenericFunctionType(rawElement); ArgumentList arguments = node.argumentList; FunctionType inferred = _inferGenericInvoke(node, constructorType, constructor.type.typeArguments, arguments, node.constructorName, isConst: node.isConst); if (inferred != null && inferred != originalElement.type) { // Fix up the parameter elements based on inferred method. arguments.correspondingStaticParameters = ResolverVisitor.resolveArgumentsToParameters( arguments, inferred.parameters, null); inferConstructorName(constructor, inferred.returnType); // Update the static element as well. This is used in some cases, such as // computing constant values. It is stored in two places. constructor.staticElement = ConstructorMember.from(rawElement, inferred.returnType); node.staticElement = constructor.staticElement; } } /** * Infers the return type of a local function, either a lambda or * (in strong mode) a local function declaration. */ void _inferLocalFunctionReturnType(FunctionExpression node) { ExecutableElementImpl functionElement = node.declaredElement as ExecutableElementImpl; FunctionBody body = node.body; DartType computedType = InferenceContext.getContext(body) ?? _dynamicType; computedType = _computeReturnTypeOfFunction(body, computedType); functionElement.returnType = computedType; _recordStaticType(node, functionElement.type); _resolver.inferenceContext.recordInference(node, functionElement.type); } /** * Given a local variable declaration and its initializer, attempt to infer * a type for the local variable declaration based on the initializer. * Inference is only done if an explicit type is not present, and if * inferring a type improves the type. */ void _inferLocalVariableType( VariableDeclaration node, Expression initializer) { AstNode parent = node.parent; if (initializer != null) { if (parent is VariableDeclarationList && parent.type == null) { DartType type = initializer.staticType; if (type != null && !type.isBottom && !type.isDartCoreNull) { VariableElement element = node.declaredElement; if (element is LocalVariableElementImpl) { element.type = initializer.staticType; node.name.staticType = initializer.staticType; } } } } else if (_strictInference) { if (parent is VariableDeclarationList && parent.type == null) { _resolver.errorReporter.reportTypeErrorForNode( HintCode.INFERENCE_FAILURE_ON_UNINITIALIZED_VARIABLE, node, [node.name.name], ); } } } /** * Given a method invocation [node], attempt to infer a better * type for the result if it is an inline JS invocation */ // TODO(jmesserly): we should remove this, and infer type from context, rather // than try to understand the dart2js type grammar. // (At the very least, we should lookup type name in the correct scope.) bool _inferMethodInvocationInlineJS(MethodInvocation node) { Element e = node.methodName.staticElement; if (e is FunctionElement && e.library.source.uri.toString() == 'dart:_foreign_helper' && e.name == 'JS') { String typeStr = _getFirstArgumentAsString(node.argumentList); DartType returnType; if (typeStr == '-dynamic') { returnType = _typeProvider.bottomType; } else { var components = typeStr.split('|'); if (components.remove('Null')) { typeStr = components.join('|'); } returnType = _getElementNameAsType( _typeProvider.objectType.element.library, typeStr, null); } if (returnType != null) { _recordStaticType(node, returnType); return true; } } return false; } /** * Given a method invocation [node], attempt to infer a better * type for the result if the target is dynamic and the method * being called is one of the object methods. */ // TODO(jmesserly): we should move this logic to ElementResolver. // If we do it here, we won't have correct parameter elements set on the // node's argumentList. (This likely affects only explicit calls to // `Object.noSuchMethod`.) bool _inferMethodInvocationObject(MethodInvocation node) { // If we have a call like `toString()` or `libraryPrefix.toString()` don't // infer it. Expression target = node.realTarget; if (target == null || target is SimpleIdentifier && target.staticElement is PrefixElement) { return false; } // Object methods called on dynamic targets can have their types improved. String name = node.methodName.name; MethodElement inferredElement = _typeProvider.objectType.element.getMethod(name); if (inferredElement == null || inferredElement.isStatic) { return false; } DartType inferredType = inferredElement.type; DartType nodeType = node.staticInvokeType; if (nodeType != null && nodeType.isDynamic && inferredType is FunctionType && inferredType.parameters.isEmpty && node.argumentList.arguments.isEmpty && _typeProvider.nonSubtypableTypes.contains(inferredType.returnType)) { node.staticInvokeType = inferredType; _recordStaticType(node, inferredType.returnType); return true; } return false; } /** * Given a property access [node] with static type [nodeType], * and [id] is the property name being accessed, infer a type for the * access itself and its constituent components if the access is to one of the * methods or getters of the built in 'Object' type, and if the result type is * a sealed type. Returns true if inference succeeded. */ bool _inferObjectAccess( Expression node, DartType nodeType, SimpleIdentifier id) { // If we have an access like `libraryPrefix.hashCode` don't infer it. if (node is PrefixedIdentifier && node.prefix.staticElement is PrefixElement) { return false; } // Search for Object accesses. String name = id.name; PropertyAccessorElement inferredElement = _typeProvider.objectType.element.getGetter(name); if (inferredElement == null || inferredElement.isStatic) { return false; } DartType inferredType = inferredElement.type.returnType; if (nodeType != null && nodeType.isDynamic && inferredType != null && _typeProvider.nonSubtypableTypes.contains(inferredType)) { _recordStaticType(id, inferredType); _recordStaticType(node, inferredType); return true; } return false; } DartType _inferSetOrMapLiteralType(SetOrMapLiteral literal) { var literalImpl = literal as SetOrMapLiteralImpl; DartType contextType = literalImpl.contextType; literalImpl.contextType = null; // Not needed anymore. NodeList<CollectionElement> elements = literal.elements; List<_InferredCollectionElementTypeInformation> inferredTypes = []; bool canBeAMap = true; bool mustBeAMap = false; bool canBeASet = true; bool mustBeASet = false; for (CollectionElement element in elements) { _InferredCollectionElementTypeInformation inferredType = _inferCollectionElementType(element); inferredTypes.add(inferredType); canBeAMap = canBeAMap && inferredType.canBeAMap; mustBeAMap = mustBeAMap || inferredType.mustBeAMap; canBeASet = canBeASet && inferredType.canBeASet; mustBeASet = mustBeASet || inferredType.mustBeASet; } if (canBeASet && mustBeASet) { return _toSetType(literal, contextType, inferredTypes); } else if (canBeAMap && mustBeAMap) { return _toMapType(literal, contextType, inferredTypes); } // Note: according to the spec, the following computations should be based // on the greatest closure of the context type (unless the context type is // `?`). In practice, we can just use the context type directly, because // the only way the greatest closure of the context type could possibly have // a different subtype relationship to `Iterable<Object>` and // `Map<Object, Object>` is if the context type is `?`. bool contextProvidesAmbiguityResolutionClues = contextType != null && contextType is! UnknownInferredType; bool contextIsIterable = contextProvidesAmbiguityResolutionClues && _typeSystem.isSubtypeOf(contextType, _typeProvider.iterableObjectType); bool contextIsMap = contextProvidesAmbiguityResolutionClues && _typeSystem.isSubtypeOf(contextType, _typeProvider.mapObjectObjectType); if (contextIsIterable && !contextIsMap) { return _toSetType(literal, contextType, inferredTypes); } else if ((contextIsMap && !contextIsIterable) || elements.isEmpty) { return _toMapType(literal, contextType, inferredTypes); } else { // Ambiguous. We're not going to get any more information to resolve the // ambiguity. We don't want to make an arbitrary decision at this point // because it will interfere with future type inference (see // dartbug.com/36210), so we return a type of `dynamic`. if (mustBeAMap && mustBeASet) { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.AMBIGUOUS_SET_OR_MAP_LITERAL_BOTH, literal); } else { _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.AMBIGUOUS_SET_OR_MAP_LITERAL_EITHER, literal); } return _typeProvider.dynamicType; } } /** * Given an uninstantiated generic function type, referenced by the * [identifier] in the tear-off [expression], try to infer the instantiated * generic function type from the surrounding context. */ DartType _inferTearOff( Expression expression, SimpleIdentifier identifier, DartType tearOffType, ) { var context = InferenceContext.getContext(expression); if (context is FunctionType && tearOffType is FunctionType) { var typeArguments = _typeSystem.inferFunctionTypeInstantiation( context, tearOffType, errorReporter: _resolver.errorReporter, errorNode: expression, ); (identifier as SimpleIdentifierImpl).tearOffTypeArgumentTypes = typeArguments; if (typeArguments.isNotEmpty) { return tearOffType.instantiate(typeArguments); } } return tearOffType; } /** * Return `true` if the given [node] is not a type literal. */ bool _isNotTypeLiteral(Identifier node) { AstNode parent = node.parent; return parent is TypeName || (parent is PrefixedIdentifier && (parent.parent is TypeName || identical(parent.prefix, node))) || (parent is PropertyAccess && identical(parent.target, node) && parent.operator.type == TokenType.PERIOD) || (parent is MethodInvocation && identical(node, parent.target) && parent.operator.type == TokenType.PERIOD); } /** * Return the non-nullable variant of the [type] if NNBD is enabled, otherwise * return the type itself. */ DartType _nonNullable(DartType type) { if (_nonNullableEnabled) { return _typeSystem.promoteToNonNull(type); } return type; } /// If we reached a null-shorting termination, and the [node] has null /// shorting, make the type of the [node] nullable. void _nullShortingTermination(Expression node) { if (!_nonNullableEnabled) return; var parent = node.parent; if (parent is AssignmentExpression && parent.leftHandSide == node) { return; } if (parent is PropertyAccess) { return; } if (_hasNullShorting(node)) { var type = node.staticType; node.staticType = _typeSystem.makeNullable(type); } } /** * Record that the static type of the given node is the given type. * * @param expression the node whose type is to be recorded * @param type the static type of the node */ void _recordStaticType(Expression expression, DartType type) { if (type == null) { expression.staticType = _dynamicType; } else { expression.staticType = type; } } void _setExtensionIdentifierType(Identifier node) { if (node is SimpleIdentifier && node.inDeclarationContext()) { return; } var parent = node.parent; if (parent is PrefixedIdentifier && parent.identifier == node) { node = parent; parent = node.parent; } if (parent is CommentReference || parent is ExtensionOverride && parent.extensionName == node || parent is MethodInvocation && parent.target == node || parent is PrefixedIdentifier && parent.prefix == node || parent is PropertyAccess && parent.target == node) { return; } _resolver.errorReporter.reportErrorForNode( CompileTimeErrorCode.EXTENSION_AS_EXPRESSION, node, [node.name], ); if (node is PrefixedIdentifier) { node.identifier.staticType = _dynamicType; node.staticType = _dynamicType; } else if (node is SimpleIdentifier) { node.staticType = _dynamicType; } } DartType _toMapType(SetOrMapLiteral node, DartType contextType, List<_InferredCollectionElementTypeInformation> inferredTypes) { DartType dynamicType = _typeProvider.dynamicType; var element = _typeProvider.mapElement; var typeParameters = element.typeParameters; var genericKeyType = typeParameters[0].instantiate( nullabilitySuffix: _noneOrStarSuffix, ); var genericValueType = typeParameters[1].instantiate( nullabilitySuffix: _noneOrStarSuffix, ); var parameters = List<ParameterElement>(2 * inferredTypes.length); var argumentTypes = List<DartType>(2 * inferredTypes.length); for (var i = 0; i < inferredTypes.length; i++) { parameters[2 * i + 0] = ParameterElementImpl.synthetic( 'key', genericKeyType, ParameterKind.POSITIONAL); parameters[2 * i + 1] = ParameterElementImpl.synthetic( 'value', genericValueType, ParameterKind.POSITIONAL); argumentTypes[2 * i + 0] = inferredTypes[i].keyType ?? dynamicType; argumentTypes[2 * i + 1] = inferredTypes[i].valueType ?? dynamicType; } var typeArguments = _typeSystem.inferGenericFunctionOrType( typeParameters: typeParameters, parameters: parameters, declaredReturnType: element.thisType, argumentTypes: argumentTypes, contextReturnType: contextType, ); return element.instantiate( typeArguments: typeArguments, nullabilitySuffix: _noneOrStarSuffix, ); } DartType _toSetType(SetOrMapLiteral node, DartType contextType, List<_InferredCollectionElementTypeInformation> inferredTypes) { DartType dynamicType = _typeProvider.dynamicType; var element = _typeProvider.setElement; var typeParameters = element.typeParameters; var genericElementType = typeParameters[0].instantiate( nullabilitySuffix: _noneOrStarSuffix, ); var parameters = List<ParameterElement>(inferredTypes.length); var argumentTypes = List<DartType>(inferredTypes.length); for (var i = 0; i < inferredTypes.length; i++) { parameters[i] = ParameterElementImpl.synthetic( 'element', genericElementType, ParameterKind.POSITIONAL); argumentTypes[i] = inferredTypes[i].elementType ?? dynamicType; } var typeArguments = _typeSystem.inferGenericFunctionOrType( typeParameters: typeParameters, parameters: parameters, declaredReturnType: element.thisType, argumentTypes: argumentTypes, contextReturnType: contextType, ); return element.instantiate( typeArguments: typeArguments, nullabilitySuffix: _noneOrStarSuffix, ); } /** * Given a constructor for a generic type, returns the equivalent generic * function type that we could use to forward to the constructor, or for a * non-generic type simply returns the constructor type. * * For example given the type `class C<T> { C(T arg); }`, the generic function * type is `<T>(T) -> C<T>`. */ static FunctionType constructorToGenericFunctionType( ConstructorElement constructor) { var classElement = constructor.enclosingElement; var typeParameters = classElement.typeParameters; if (typeParameters.isEmpty) { return constructor.type; } return FunctionTypeImpl.synthetic( constructor.returnType, typeParameters, constructor.parameters, ); } static DartType _getFreshType(DartType type) { if (type is FunctionType) { var parameters = getFreshTypeParameters(type.typeFormals); return parameters.applyToFunctionType(type); } else { return type; } } /// Return `true` if the [node] has null-aware shorting, e.g. `foo?.bar`. static bool _hasNullShorting(Expression node) { if (node is AssignmentExpression) { return _hasNullShorting(node.leftHandSide); } if (node is IndexExpression) { return node.isNullAware || _hasNullShorting(node.target); } if (node is PropertyAccess) { return node.isNullAware || _hasNullShorting(node.target); } return false; } } class _InferredCollectionElementTypeInformation { final DartType elementType; final DartType keyType; final DartType valueType; _InferredCollectionElementTypeInformation( {this.elementType, this.keyType, this.valueType}); factory _InferredCollectionElementTypeInformation.forIfElement( TypeSystem typeSystem, _InferredCollectionElementTypeInformation thenInfo, _InferredCollectionElementTypeInformation elseInfo) { if (thenInfo.isDynamic) { DartType dynamic = thenInfo.elementType; return _InferredCollectionElementTypeInformation( elementType: _dynamicOrNull(elseInfo.elementType, dynamic), keyType: _dynamicOrNull(elseInfo.keyType, dynamic), valueType: _dynamicOrNull(elseInfo.valueType, dynamic)); } else if (elseInfo.isDynamic) { DartType dynamic = elseInfo.elementType; return _InferredCollectionElementTypeInformation( elementType: _dynamicOrNull(thenInfo.elementType, dynamic), keyType: _dynamicOrNull(thenInfo.keyType, dynamic), valueType: _dynamicOrNull(thenInfo.valueType, dynamic)); } return _InferredCollectionElementTypeInformation( elementType: _leastUpperBoundOfTypes( typeSystem, thenInfo.elementType, elseInfo.elementType), keyType: _leastUpperBoundOfTypes( typeSystem, thenInfo.keyType, elseInfo.keyType), valueType: _leastUpperBoundOfTypes( typeSystem, thenInfo.valueType, elseInfo.valueType)); } bool get canBeAMap => keyType != null || valueType != null; bool get canBeASet => elementType != null; bool get isDynamic => elementType != null && elementType.isDynamic && keyType != null && keyType.isDynamic && valueType != null && valueType.isDynamic; bool get mustBeAMap => canBeAMap && elementType == null; bool get mustBeASet => canBeASet && keyType == null && valueType == null; @override String toString() { return '($elementType, $keyType, $valueType)'; } static DartType _dynamicOrNull(DartType type, DartType dynamic) { if (type == null) { return null; } return dynamic; } static DartType _leastUpperBoundOfTypes( TypeSystem typeSystem, DartType first, DartType second) { if (first == null) { return second; } else if (second == null) { return first; } else { return typeSystem.leastUpperBound(first, second); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/type_promotion_manager.dart
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/variable_type_provider.dart'; /// Instances of the class `TypePromotionManager` manage the ability to promote /// types of local variables and formal parameters from their declared types /// based on control flow. class TypePromotionManager { final TypeSystem _typeSystem; /// The current promotion scope, or `null` if no scope has been entered. _TypePromoteScope _currentScope; final List<FunctionBody> _functionBodyStack = []; /// Body of the function currently being analyzed, if any. FunctionBody _currentFunctionBody; TypePromotionManager(this._typeSystem); LocalVariableTypeProvider get localVariableTypeProvider { return _LegacyLocalVariableTypeProvider(this); } /// Returns the elements with promoted types. Iterable<Element> get _promotedElements { return _currentScope.promotedElements; } void enterFunctionBody(FunctionBody body) { _functionBodyStack.add(_currentFunctionBody); _currentFunctionBody = body; } void exitFunctionBody() { if (_functionBodyStack.isEmpty) { assert(false, 'exitFunctionBody without a matching enterFunctionBody'); } else { _currentFunctionBody = _functionBodyStack.removeLast(); } } void visitBinaryExpression_and_rhs( Expression leftOperand, Expression rightOperand, void f()) { if (rightOperand != null) { _enterScope(); try { // Type promotion. _promoteTypes(leftOperand); _clearTypePromotionsIfPotentiallyMutatedIn(leftOperand); _clearTypePromotionsIfPotentiallyMutatedIn(rightOperand); _clearTypePromotionsIfAccessedInClosureAndPotentiallyMutated( rightOperand); // Visit right operand. f(); } finally { _exitScope(); } } } void visitConditionalExpression_then( Expression condition, Expression thenExpression, void f()) { if (thenExpression != null) { _enterScope(); try { // Type promotion. _promoteTypes(condition); _clearTypePromotionsIfPotentiallyMutatedIn(thenExpression); _clearTypePromotionsIfAccessedInClosureAndPotentiallyMutated( thenExpression, ); // Visit "then" expression. f(); } finally { _exitScope(); } } } void visitIfElement_thenElement( Expression condition, CollectionElement thenElement, void f()) { if (thenElement != null) { _enterScope(); try { // Type promotion. _promoteTypes(condition); _clearTypePromotionsIfPotentiallyMutatedIn(thenElement); _clearTypePromotionsIfAccessedInClosureAndPotentiallyMutated( thenElement); // Visit "then". f(); } finally { _exitScope(); } } } void visitIfStatement_thenStatement( Expression condition, Statement thenStatement, void f()) { if (thenStatement != null) { _enterScope(); try { // Type promotion. _promoteTypes(condition); _clearTypePromotionsIfPotentiallyMutatedIn(thenStatement); _clearTypePromotionsIfAccessedInClosureAndPotentiallyMutated( thenStatement); // Visit "then". f(); } finally { _exitScope(); } } } /// Checks each promoted variable in the current scope for compliance with the /// following specification statement: /// /// If the variable <i>v</i> is accessed by a closure in <i>s<sub>1</sub></i> /// then the variable <i>v</i> is not potentially mutated anywhere in the /// scope of <i>v</i>. void _clearTypePromotionsIfAccessedInClosureAndPotentiallyMutated( AstNode target) { for (Element element in _promotedElements) { if (_currentFunctionBody.isPotentiallyMutatedInScope(element)) { if (_isVariableAccessedInClosure(element, target)) { _setType(element, null); } } } } /// Checks each promoted variable in the current scope for compliance with the /// following specification statement: /// /// <i>v</i> is not potentially mutated in <i>s<sub>1</sub></i> or within a /// closure. void _clearTypePromotionsIfPotentiallyMutatedIn(AstNode target) { for (Element element in _promotedElements) { if (_isVariablePotentiallyMutatedIn(element, target)) { _setType(element, null); } } } /// Enter a new promotions scope. void _enterScope() { _currentScope = new _TypePromoteScope(_currentScope); } /// Exit the current promotion scope. void _exitScope() { if (_currentScope == null) { throw new StateError("No scope to exit"); } _currentScope = _currentScope._outerScope; } /// Return the promoted type of the given [element], or `null` if the type of /// the element has not been promoted. DartType _getPromotedType(Element element) { return _currentScope?.getType(element); } /// Return the static element associated with the given expression whose type /// can be promoted, or `null` if there is no element whose type can be /// promoted. VariableElement _getPromotionStaticElement(Expression expression) { expression = expression?.unParenthesized; if (expression is SimpleIdentifier) { Element element = expression.staticElement; if (element is VariableElement) { ElementKind kind = element.kind; if (kind == ElementKind.LOCAL_VARIABLE || kind == ElementKind.PARAMETER) { return element; } } } return null; } /// Given that the [node] is a reference to a [VariableElement], return the /// static type of the variable at this node - declared or promoted. DartType _getType(SimpleIdentifier node) { var variable = node.staticElement as VariableElement; return _getPromotedType(variable) ?? variable.type; } /// Return `true` if the given variable is accessed within a closure in the /// given [AstNode] and also mutated somewhere in variable scope. This /// information is only available for local variables (including parameters). /// /// @param variable the variable to check /// @param target the [AstNode] to check within /// @return `true` if this variable is potentially mutated somewhere in the /// given ASTNode bool _isVariableAccessedInClosure(Element variable, AstNode target) { _ResolverVisitor_isVariableAccessedInClosure visitor = new _ResolverVisitor_isVariableAccessedInClosure(variable); target.accept(visitor); return visitor.result; } /// Return `true` if the given variable is potentially mutated somewhere in /// the given [AstNode]. This information is only available for local /// variables (including parameters). /// /// @param variable the variable to check /// @param target the [AstNode] to check within /// @return `true` if this variable is potentially mutated somewhere in the /// given ASTNode bool _isVariablePotentiallyMutatedIn(Element variable, AstNode target) { _ResolverVisitor_isVariablePotentiallyMutatedIn visitor = new _ResolverVisitor_isVariablePotentiallyMutatedIn(variable); target.accept(visitor); return visitor.result; } /// If it is appropriate to do so, promotes the current type of the static /// element associated with the given expression with the given type. /// Generally speaking, it is appropriate if the given type is more specific /// than the current type. /// /// @param expression the expression used to access the static element whose /// types might be promoted /// @param potentialType the potential type of the elements void _promote(Expression expression, DartType potentialType) { VariableElement element = _getPromotionStaticElement(expression); if (element != null) { // may be mutated somewhere in closure if (_currentFunctionBody.isPotentiallyMutatedInClosure(element)) { return; } // prepare current variable type DartType type = _getPromotedType(element) ?? expression.staticType ?? DynamicTypeImpl.instance; potentialType ??= DynamicTypeImpl.instance; // Check if we can promote to potentialType from type. DartType promoteType = _typeSystem.tryPromoteToType(potentialType, type); if (promoteType != null) { // Do promote type of variable. _setType(element, promoteType); } } } /// Promotes type information using given condition. void _promoteTypes(Expression condition) { if (condition is BinaryExpression) { if (condition.operator.type == TokenType.AMPERSAND_AMPERSAND) { Expression left = condition.leftOperand; Expression right = condition.rightOperand; _promoteTypes(left); _promoteTypes(right); _clearTypePromotionsIfPotentiallyMutatedIn(right); } } else if (condition is IsExpression) { if (condition.notOperator == null) { _promote(condition.expression, condition.type.type); } } else if (condition is ParenthesizedExpression) { _promoteTypes(condition.expression); } } /// Set the promoted type of the given element to the given type. /// /// @param element the element whose type might have been promoted /// @param type the promoted type of the given element void _setType(Element element, DartType type) { if (_currentScope == null) { throw new StateError("Cannot promote without a scope"); } _currentScope.setType(element, type); } } /// The legacy, pre-NNBD implementation of [LocalVariableTypeProvider]. class _LegacyLocalVariableTypeProvider implements LocalVariableTypeProvider { final TypePromotionManager _manager; _LegacyLocalVariableTypeProvider(this._manager); @override DartType getType(SimpleIdentifier node) { return _manager._getType(node); } } class _ResolverVisitor_isVariableAccessedInClosure extends RecursiveAstVisitor<void> { final Element variable; bool result = false; bool _inClosure = false; _ResolverVisitor_isVariableAccessedInClosure(this.variable); @override void visitFunctionExpression(FunctionExpression node) { bool inClosure = this._inClosure; try { this._inClosure = true; super.visitFunctionExpression(node); } finally { this._inClosure = inClosure; } } @override void visitSimpleIdentifier(SimpleIdentifier node) { if (result) { return; } if (_inClosure && identical(node.staticElement, variable)) { result = true; } } } class _ResolverVisitor_isVariablePotentiallyMutatedIn extends RecursiveAstVisitor<void> { final Element variable; bool result = false; _ResolverVisitor_isVariablePotentiallyMutatedIn(this.variable); @override void visitSimpleIdentifier(SimpleIdentifier node) { if (result) { return; } if (identical(node.staticElement, variable)) { if (node.inSetterContext()) { result = true; } } } } /// Instances of the class `TypePromoteScope` represent a scope in which the /// types of elements can be promoted. class _TypePromoteScope { /// The outer scope in which types might be promoter. final _TypePromoteScope _outerScope; /// A table mapping elements to the promoted type of that element. Map<Element, DartType> _promotedTypes = {}; /// Initialize a newly created scope to be an empty child of the given scope. /// /// @param outerScope the outer scope in which types might be promoted _TypePromoteScope(this._outerScope); /// Returns the elements with promoted types. Iterable<Element> get promotedElements => _promotedTypes.keys.toSet(); /// Return the promoted type of the given element, or `null` if the type of /// the element has not been promoted. /// /// @param element the element whose type might have been promoted /// @return the promoted type of the given element DartType getType(Element element) { DartType type = _promotedTypes[element]; if (type == null && element is PropertyAccessorElement) { type = _promotedTypes[element.variable]; } if (type != null) { return type; } else if (_outerScope != null) { return _outerScope.getType(element); } return null; } /// Set the promoted type of the given element to the given type. /// /// @param element the element whose type might have been promoted /// @param type the promoted type of the given element void setType(Element element, DartType type) { _promotedTypes[element] = type; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/sdk.dart
// Copyright (c) 2014, 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/src/generated/engine.dart' show AnalysisContext, AnalysisOptions; import 'package:analyzer/src/generated/source.dart' show Source; import 'package:analyzer/src/generated/utilities_general.dart'; import 'package:analyzer/src/summary/idl.dart' show PackageBundle; /** * A Dart SDK installed in a specified location. */ abstract class DartSdk { /** * The short name of the dart SDK 'async' library. */ static const String DART_ASYNC = "dart:async"; /** * The short name of the dart SDK 'core' library. */ static const String DART_CORE = "dart:core"; /** * The short name of the dart SDK 'html' library. */ static const String DART_HTML = "dart:html"; /** * The prefix shared by all dart library URIs. */ static const String DART_LIBRARY_PREFIX = "dart:"; /** * The version number that is returned when the real version number could not * be determined. */ static const String DEFAULT_VERSION = "0"; /** * Return the analysis context used for all of the sources in this [DartSdk]. */ AnalysisContext get context; /** * Return a list containing all of the libraries defined in this SDK. */ List<SdkLibrary> get sdkLibraries; /** * Return the revision number of this SDK, or `"0"` if the revision number * cannot be discovered. */ String get sdkVersion; /** * Return a list containing the library URI's for the libraries defined in * this SDK. */ List<String> get uris; /** * Return a source representing the given 'file:' [uri] if the file is in this * SDK, or `null` if the file is not in this SDK. */ Source fromFileUri(Uri uri); /** * Return the linked [PackageBundle] for this SDK, if it can be provided, or * `null` otherwise. * * This is a temporary API, don't use it. */ PackageBundle getLinkedBundle(); /** * Return the library representing the library with the given 'dart:' [uri], * or `null` if the given URI does not denote a library in this SDK. */ SdkLibrary getSdkLibrary(String uri); /** * Return the source representing the library with the given 'dart:' [uri], or * `null` if the given URI does not denote a library in this SDK. */ Source mapDartUri(String uri); } /** * Manages the DartSdk's that have been created. Clients need to create multiple * SDKs when the analysis options associated with those SDK's contexts will * produce different analysis results. */ class DartSdkManager { /** * The absolute path to the directory containing the default SDK. */ final String defaultSdkDirectory; /** * A flag indicating whether it is acceptable to use summaries when they are * available. */ final bool canUseSummaries; /** * A table mapping (an encoding of) analysis options and SDK locations to the * DartSdk from that location that has been configured with those options. */ Map<SdkDescription, DartSdk> sdkMap = new HashMap<SdkDescription, DartSdk>(); /** * Initialize a newly created manager. */ DartSdkManager(this.defaultSdkDirectory, this.canUseSummaries, [dynamic ignored]); /** * Return any SDK that has been created, or `null` if no SDKs have been * created. */ DartSdk get anySdk { if (sdkMap.isEmpty) { return null; } return sdkMap.values.first; } /** * Return a list of the descriptors of the SDKs that are currently being * managed. */ List<SdkDescription> get sdkDescriptors => sdkMap.keys.toList(); /** * Return the Dart SDK that is appropriate for the given SDK [description]. * If such an SDK has not yet been created, then the [ifAbsent] function will * be invoked to create it. */ DartSdk getSdk(SdkDescription description, DartSdk ifAbsent()) { return sdkMap.putIfAbsent(description, ifAbsent); } } /** * A map from Dart library URI's to the [SdkLibraryImpl] representing that * library. */ class LibraryMap { /** * A table mapping Dart library URI's to the library. */ Map<String, SdkLibraryImpl> _libraryMap = <String, SdkLibraryImpl>{}; /** * Return a list containing all of the sdk libraries in this mapping. */ List<SdkLibrary> get sdkLibraries => new List.from(_libraryMap.values); /** * Return a list containing the library URI's for which a mapping is available. */ List<String> get uris => _libraryMap.keys.toList(); /** * Return info for debugging https://github.com/dart-lang/sdk/issues/35226. */ Map<String, Object> debugInfo() { var map = <String, Object>{}; for (var uri in _libraryMap.keys) { var lib = _libraryMap[uri]; map[uri] = <String, Object>{ 'path': lib.path, 'shortName': lib.shortName, }; } return map; } /** * Return the library with the given 'dart:' [uri], or `null` if the URI does * not map to a library. */ SdkLibrary getLibrary(String uri) => _libraryMap[uri]; /** * Set the library with the given 'dart:' [uri] to the given [library]. */ void setLibrary(String dartUri, SdkLibraryImpl library) { _libraryMap[dartUri] = library; } /** * Return the number of library URI's for which a mapping is available. */ int size() => _libraryMap.length; } /** * A description of a [DartSdk]. */ class SdkDescription { /** * The paths to the files or directories that define the SDK. */ final List<String> paths; /** * The analysis options that will be used by the SDK's context. */ final AnalysisOptions options; /** * Initialize a newly created SDK description to describe an SDK based on the * files or directories at the given [paths] that is analyzed using the given * [options]. */ SdkDescription(this.paths, this.options); @override int get hashCode { int hashCode = 0; for (int value in options.signature) { hashCode = JenkinsSmiHash.combine(hashCode, value); } for (String path in paths) { hashCode = JenkinsSmiHash.combine(hashCode, path.hashCode); } return JenkinsSmiHash.finish(hashCode); } @override bool operator ==(Object other) { if (other is SdkDescription) { if (!AnalysisOptions.signaturesEqual( options.signature, other.options.signature)) { return false; } int length = paths.length; if (other.paths.length != length) { return false; } for (int i = 0; i < length; i++) { if (other.paths[i] != paths[i]) { return false; } } return true; } return false; } @override String toString() { StringBuffer buffer = new StringBuffer(); bool needsSeparator = false; void add(String optionName) { if (needsSeparator) { buffer.write(', '); } buffer.write(optionName); needsSeparator = true; } for (String path in paths) { add(path); } if (needsSeparator) { buffer.write(' '); } buffer.write('('); buffer.write(options.signature); buffer.write(')'); return buffer.toString(); } } class SdkLibrariesReader_LibraryBuilder extends RecursiveAstVisitor<void> { /** * The prefix added to the name of a library to form the URI used in code to * reference the library. */ static String _LIBRARY_PREFIX = "dart:"; /** * The name of the optional parameter used to indicate whether the library is * an implementation library. */ static String _IMPLEMENTATION = "implementation"; /** * The name of the optional parameter used to specify the path used when * compiling for dart2js. */ static String _DART2JS_PATH = "dart2jsPath"; /** * The name of the optional parameter used to indicate whether the library is * documented. */ static String _DOCUMENTED = "documented"; /** * The name of the optional parameter used to specify the category of the * library. */ static String _CATEGORIES = "categories"; /** * The name of the optional parameter used to specify the platforms on which * the library can be used. */ static String _PLATFORMS = "platforms"; /** * The value of the [PLATFORMS] parameter used to specify that the library can * be used on the VM. */ static String _VM_PLATFORM = "VM_PLATFORM"; /** * A flag indicating whether the dart2js path should be used when it is * available. */ final bool _useDart2jsPaths; /** * The library map that is populated by visiting the AST structure parsed from * the contents of the libraries file. */ LibraryMap _librariesMap = new LibraryMap(); /** * Initialize a newly created library builder to use the dart2js path if * [_useDart2jsPaths] is `true`. */ SdkLibrariesReader_LibraryBuilder(this._useDart2jsPaths); /** * Return the library map that was populated by visiting the AST structure * parsed from the contents of the libraries file. */ LibraryMap get librariesMap => _librariesMap; // To be backwards-compatible the new categories field is translated to // an old approximation. String convertCategories(String categories) { switch (categories) { case "": return "Internal"; case "Client": return "Client"; case "Server": return "Server"; case "Client,Server": return "Shared"; case "Client,Server,Embedded": return "Shared"; } return "Shared"; } @override void visitMapLiteralEntry(MapLiteralEntry node) { String libraryName; Expression key = node.key; if (key is SimpleStringLiteral) { libraryName = "$_LIBRARY_PREFIX${key.value}"; } Expression value = node.value; if (value is InstanceCreationExpression) { SdkLibraryImpl library = new SdkLibraryImpl(libraryName); List<Expression> arguments = value.argumentList.arguments; for (Expression argument in arguments) { if (argument is SimpleStringLiteral) { library.path = argument.value; } else if (argument is NamedExpression) { String name = argument.name.label.name; Expression expression = argument.expression; if (name == _CATEGORIES) { library.category = convertCategories((expression as StringLiteral).stringValue); } else if (name == _IMPLEMENTATION) { library._implementation = (expression as BooleanLiteral).value; } else if (name == _DOCUMENTED) { library.documented = (expression as BooleanLiteral).value; } else if (name == _PLATFORMS) { if (expression is SimpleIdentifier) { String identifier = expression.name; if (identifier == _VM_PLATFORM) { library.setVmLibrary(); } else { library.setDart2JsLibrary(); } } } else if (_useDart2jsPaths && name == _DART2JS_PATH) { if (expression is SimpleStringLiteral) { library.path = expression.value; } } } } _librariesMap.setLibrary(libraryName, library); } } } /** * Represents a single library in the SDK */ abstract class SdkLibrary { /** * Return the name of the category containing the library. */ String get category; /** * Return `true` if this library can be compiled to JavaScript by dart2js. */ bool get isDart2JsLibrary; /** * Return `true` if the library is documented. */ bool get isDocumented; /** * Return `true` if the library is an implementation library. */ bool get isImplementation; /** * Return `true` if library is internal can be used only by other SDK libraries. */ bool get isInternal; /** * Return `true` if this library can be used for both client and server. */ bool get isShared; /** * Return `true` if this library can be run on the VM. */ bool get isVmLibrary; /** * Return the path to the file defining the library. The path is relative to * the `lib` directory within the SDK. */ String get path; /** * Return the short name of the library. This is the URI of the library, * including `dart:`. */ String get shortName; } /** * The information known about a single library within the SDK. */ class SdkLibraryImpl implements SdkLibrary { /** * The bit mask used to access the bit representing the flag indicating * whether a library is intended to work on the dart2js platform. */ static int DART2JS_PLATFORM = 1; /** * The bit mask used to access the bit representing the flag indicating * whether a library is intended to work on the VM platform. */ static int VM_PLATFORM = 2; @override final String shortName; /** * The path to the file defining the library. The path is relative to the * 'lib' directory within the SDK. */ @override String path; /** * The name of the category containing the library. Unless otherwise specified * in the libraries file all libraries are assumed to be shared between server * and client. */ @override String category = "Shared"; /** * A flag indicating whether the library is documented. */ bool _documented = true; /** * A flag indicating whether the library is an implementation library. */ bool _implementation = false; /** * An encoding of which platforms this library is intended to work on. */ int _platforms = 0; /** * Initialize a newly created library to represent the library with the given * [name]. */ SdkLibraryImpl(this.shortName); /** * Set whether the library is documented. */ void set documented(bool documented) { this._documented = documented; } @override bool get isDart2JsLibrary => (_platforms & DART2JS_PLATFORM) != 0; @override bool get isDocumented => _documented; @override bool get isImplementation => _implementation; @override bool get isInternal => category == "Internal"; @override bool get isShared => category == "Shared"; @override bool get isVmLibrary => (_platforms & VM_PLATFORM) != 0; /** * Record that this library can be compiled to JavaScript by dart2js. */ void setDart2JsLibrary() { _platforms |= DART2JS_PLATFORM; } /** * Record that this library can be run on the VM. */ void setVmLibrary() { _platforms |= VM_PLATFORM; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/super_context.dart
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; /// An indication of the kind of context in which a super expression was found. class SuperContext { /// An indication that the super expression is in a context in which it is /// invalid because it is in an instance member of an extension. static const SuperContext extension = SuperContext._('extension'); /// An indication that the super expression is in a context in which it is /// invalid because it is not in an instance member. static const SuperContext static = SuperContext._('static'); /// An indication that the super expression is in a context in which it is /// valid. static const SuperContext valid = SuperContext._('valid'); /// The name of the context. final String name; /// Return an indication of the context in which the super [expression] is /// being used. factory SuperContext.of(SuperExpression expression) { for (AstNode node = expression; node != null; node = node.parent) { if (node is CompilationUnit) { return SuperContext.static; } else if (node is ConstructorDeclaration) { return node.factoryKeyword == null ? SuperContext.valid : SuperContext.static; } else if (node is ConstructorFieldInitializer) { return SuperContext.static; } else if (node is MethodDeclaration) { if (node.isStatic) { return SuperContext.static; } else if (node.parent is ExtensionDeclaration) { return SuperContext.extension; } return SuperContext.valid; } } return SuperContext.static; } const SuperContext._(this.name); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/testing/test_type_provider.dart
// Copyright (c) 2014, 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:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/src/dart/element/type_provider.dart'; import 'package:analyzer/src/generated/engine.dart' show AnalysisContext; import 'package:analyzer/src/generated/source.dart' show Source; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/test_utilities/mock_sdk_elements.dart'; /** * A type provider that can be used by tests without creating the element model * for the core library. */ class TestTypeProvider extends TypeProviderImpl { factory TestTypeProvider([ AnalysisContext context, Object analysisDriver, NullabilitySuffix nullabilitySuffix = NullabilitySuffix.star, ]) { context ??= _MockAnalysisContext(); var sdkElements = MockSdkElements(context, nullabilitySuffix); return TestTypeProvider._( nullabilitySuffix, sdkElements.coreLibrary, sdkElements.asyncLibrary, ); } TestTypeProvider._( NullabilitySuffix nullabilitySuffix, LibraryElement coreLibrary, LibraryElement asyncLibrary, ) : super(coreLibrary, asyncLibrary, nullabilitySuffix: nullabilitySuffix); } class _MockAnalysisContext implements AnalysisContext { @override final SourceFactory sourceFactory = _MockSourceFactory(); noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class _MockSource implements Source { @override final Uri uri; _MockSource(this.uri); @override String get encoding => '$uri'; noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class _MockSourceFactory implements SourceFactory { @override Source forUri(String uriStr) { var uri = Uri.parse(uriStr); return _MockSource(uri); } noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/testing/ast_test_factory.dart
// Copyright (c) 2014, 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:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/standard_ast_factory.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/testing/token_factory.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:meta/meta.dart'; /** * The class `AstTestFactory` defines utility methods that can be used to create AST nodes. The * nodes that are created are complete in the sense that all of the tokens that would have been * associated with the nodes by a parser are also created, but the token stream is not constructed. * None of the nodes are resolved. * * The general pattern is for the name of the factory method to be the same as the name of the class * of AST node being created. There are two notable exceptions. The first is for methods creating * nodes that are part of a cascade expression. These methods are all prefixed with 'cascaded'. The * second is places where a shorter name seemed unambiguous and easier to read, such as using * 'identifier' rather than 'prefixedIdentifier', or 'integer' rather than 'integerLiteral'. */ class AstTestFactory { static AdjacentStrings adjacentStrings(List<StringLiteral> strings) => astFactory.adjacentStrings(strings); static Annotation annotation(Identifier name) => astFactory.annotation( TokenFactory.tokenFromType(TokenType.AT), name, null, null, null); static Annotation annotation2(Identifier name, SimpleIdentifier constructorName, ArgumentList arguments) => astFactory.annotation( TokenFactory.tokenFromType(TokenType.AT), name, constructorName == null ? null : TokenFactory.tokenFromType(TokenType.PERIOD), constructorName, arguments); static ArgumentList argumentList([List<Expression> arguments]) => astFactory.argumentList(TokenFactory.tokenFromType(TokenType.OPEN_PAREN), arguments, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN)); static AsExpression asExpression( Expression expression, TypeAnnotation type) => astFactory.asExpression( expression, TokenFactory.tokenFromKeyword(Keyword.AS), type); static AssertInitializer assertInitializer( Expression condition, Expression message) => astFactory.assertInitializer( TokenFactory.tokenFromKeyword(Keyword.ASSERT), TokenFactory.tokenFromType(TokenType.OPEN_PAREN), condition, TokenFactory.tokenFromType(TokenType.COMMA), message, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN)); static AssertStatement assertStatement(Expression condition, [Expression message]) => astFactory.assertStatement( TokenFactory.tokenFromKeyword(Keyword.ASSERT), TokenFactory.tokenFromType(TokenType.OPEN_PAREN), condition, message == null ? null : TokenFactory.tokenFromType(TokenType.COMMA), message, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static AssignmentExpression assignmentExpression(Expression leftHandSide, TokenType operator, Expression rightHandSide) => astFactory.assignmentExpression( leftHandSide, TokenFactory.tokenFromType(operator), rightHandSide); static BlockFunctionBody asyncBlockFunctionBody( [List<Statement> statements]) => astFactory.blockFunctionBody( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "async"), null, block(statements)); static ExpressionFunctionBody asyncExpressionFunctionBody( Expression expression) => astFactory.expressionFunctionBody( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "async"), TokenFactory.tokenFromType(TokenType.FUNCTION), expression, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static BlockFunctionBody asyncGeneratorBlockFunctionBody( [List<Statement> statements]) => astFactory.blockFunctionBody( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "async"), TokenFactory.tokenFromType(TokenType.STAR), block(statements)); static AwaitExpression awaitExpression(Expression expression) => astFactory.awaitExpression( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "await"), expression); static BinaryExpression binaryExpression(Expression leftOperand, TokenType operator, Expression rightOperand) => astFactory.binaryExpression( leftOperand, TokenFactory.tokenFromType(operator), rightOperand); static Block block([List<Statement> statements]) => astFactory.block( TokenFactory.tokenFromType(TokenType.OPEN_CURLY_BRACKET), statements, TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET)); static BlockFunctionBody blockFunctionBody(Block block) => astFactory.blockFunctionBody(null, null, block); static BlockFunctionBody blockFunctionBody2([List<Statement> statements]) => astFactory.blockFunctionBody(null, null, block(statements)); static BooleanLiteral booleanLiteral(bool value) => astFactory.booleanLiteral( value ? TokenFactory.tokenFromKeyword(Keyword.TRUE) : TokenFactory.tokenFromKeyword(Keyword.FALSE), value); static BreakStatement breakStatement() => astFactory.breakStatement( TokenFactory.tokenFromKeyword(Keyword.BREAK), null, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static BreakStatement breakStatement2(String label) => astFactory.breakStatement(TokenFactory.tokenFromKeyword(Keyword.BREAK), identifier3(label), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static IndexExpression cascadedIndexExpression(Expression index) => astFactory.indexExpressionForCascade( TokenFactory.tokenFromType(TokenType.PERIOD_PERIOD), TokenFactory.tokenFromType(TokenType.OPEN_SQUARE_BRACKET), index, TokenFactory.tokenFromType(TokenType.CLOSE_SQUARE_BRACKET)); static MethodInvocation cascadedMethodInvocation(String methodName, [List<Expression> arguments]) => astFactory.methodInvocation( null, TokenFactory.tokenFromType(TokenType.PERIOD_PERIOD), identifier3(methodName), null, argumentList(arguments)); static PropertyAccess cascadedPropertyAccess(String propertyName) => astFactory.propertyAccess( null, TokenFactory.tokenFromType(TokenType.PERIOD_PERIOD), identifier3(propertyName)); static CascadeExpression cascadeExpression(Expression target, [List<Expression> cascadeSections]) => astFactory.cascadeExpression(target, cascadeSections); static CatchClause catchClause(String exceptionParameter, [List<Statement> statements]) => catchClause5(null, exceptionParameter, null, statements); static CatchClause catchClause2( String exceptionParameter, String stackTraceParameter, [List<Statement> statements]) => catchClause5(null, exceptionParameter, stackTraceParameter, statements); static CatchClause catchClause3(TypeAnnotation exceptionType, [List<Statement> statements]) => catchClause5(exceptionType, null, null, statements); static CatchClause catchClause4( TypeAnnotation exceptionType, String exceptionParameter, [List<Statement> statements]) => catchClause5(exceptionType, exceptionParameter, null, statements); static CatchClause catchClause5(TypeAnnotation exceptionType, String exceptionParameter, String stackTraceParameter, [List<Statement> statements]) => astFactory.catchClause( exceptionType == null ? null : TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "on"), exceptionType, exceptionParameter == null ? null : TokenFactory.tokenFromKeyword(Keyword.CATCH), exceptionParameter == null ? null : TokenFactory.tokenFromType(TokenType.OPEN_PAREN), exceptionParameter == null ? null : identifier3(exceptionParameter), stackTraceParameter == null ? null : TokenFactory.tokenFromType(TokenType.COMMA), stackTraceParameter == null ? null : identifier3(stackTraceParameter), exceptionParameter == null ? null : TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), block(statements)); static ClassDeclaration classDeclaration( Keyword abstractKeyword, String name, TypeParameterList typeParameters, ExtendsClause extendsClause, WithClause withClause, ImplementsClause implementsClause, [List<ClassMember> members]) => astFactory.classDeclaration( null, null, abstractKeyword == null ? null : TokenFactory.tokenFromKeyword(abstractKeyword), TokenFactory.tokenFromKeyword(Keyword.CLASS), identifier3(name), typeParameters, extendsClause, withClause, implementsClause, TokenFactory.tokenFromType(TokenType.OPEN_CURLY_BRACKET), members, TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET)); static ClassTypeAlias classTypeAlias( String name, TypeParameterList typeParameters, Keyword abstractKeyword, TypeName superclass, WithClause withClause, ImplementsClause implementsClause) => astFactory.classTypeAlias( null, null, TokenFactory.tokenFromKeyword(Keyword.CLASS), identifier3(name), typeParameters, TokenFactory.tokenFromType(TokenType.EQ), abstractKeyword == null ? null : TokenFactory.tokenFromKeyword(abstractKeyword), superclass, withClause, implementsClause, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static CompilationUnit compilationUnit() => compilationUnit8(null, null, null); static CompilationUnit compilationUnit2( List<CompilationUnitMember> declarations) => compilationUnit8(null, null, declarations); static CompilationUnit compilationUnit3(List<Directive> directives) => compilationUnit8(null, directives, null); static CompilationUnit compilationUnit4(List<Directive> directives, List<CompilationUnitMember> declarations) => compilationUnit8(null, directives, declarations); static CompilationUnit compilationUnit5(String scriptTag) => compilationUnit8(scriptTag, null, null); static CompilationUnit compilationUnit6( String scriptTag, List<CompilationUnitMember> declarations) => compilationUnit8(scriptTag, null, declarations); static CompilationUnit compilationUnit7( String scriptTag, List<Directive> directives) => compilationUnit8(scriptTag, directives, null); static CompilationUnit compilationUnit8( String scriptTag, List<Directive> directives, List<CompilationUnitMember> declarations) => astFactory.compilationUnit( beginToken: TokenFactory.tokenFromType(TokenType.EOF), scriptTag: scriptTag == null ? null : AstTestFactory.scriptTag(scriptTag), directives: directives == null ? new List<Directive>() : directives, declarations: declarations == null ? new List<CompilationUnitMember>() : declarations, endToken: TokenFactory.tokenFromType(TokenType.EOF), featureSet: null); static CompilationUnit compilationUnit9( {String scriptTag, List<Directive> directives, List<CompilationUnitMember> declarations, FeatureSet featureSet}) => astFactory.compilationUnit( beginToken: TokenFactory.tokenFromType(TokenType.EOF), scriptTag: scriptTag == null ? null : AstTestFactory.scriptTag(scriptTag), directives: directives == null ? new List<Directive>() : directives, declarations: declarations == null ? new List<CompilationUnitMember>() : declarations, endToken: TokenFactory.tokenFromType(TokenType.EOF), featureSet: featureSet); static ConditionalExpression conditionalExpression(Expression condition, Expression thenExpression, Expression elseExpression) => astFactory.conditionalExpression( condition, TokenFactory.tokenFromType(TokenType.QUESTION), thenExpression, TokenFactory.tokenFromType(TokenType.COLON), elseExpression); static ConstructorDeclaration constructorDeclaration( Identifier returnType, String name, FormalParameterList parameters, List<ConstructorInitializer> initializers) => astFactory.constructorDeclaration( null, null, TokenFactory.tokenFromKeyword(Keyword.EXTERNAL), null, null, returnType, name == null ? null : TokenFactory.tokenFromType(TokenType.PERIOD), name == null ? null : identifier3(name), parameters, initializers == null || initializers.isEmpty ? null : TokenFactory.tokenFromType(TokenType.PERIOD), initializers == null ? new List<ConstructorInitializer>() : initializers, null, emptyFunctionBody()); static ConstructorDeclaration constructorDeclaration2( Keyword constKeyword, Keyword factoryKeyword, Identifier returnType, String name, FormalParameterList parameters, List<ConstructorInitializer> initializers, FunctionBody body) => astFactory.constructorDeclaration( null, null, null, constKeyword == null ? null : TokenFactory.tokenFromKeyword(constKeyword), factoryKeyword == null ? null : TokenFactory.tokenFromKeyword(factoryKeyword), returnType, name == null ? null : TokenFactory.tokenFromType(TokenType.PERIOD), name == null ? null : identifier3(name), parameters, initializers == null || initializers.isEmpty ? null : TokenFactory.tokenFromType(TokenType.PERIOD), initializers == null ? new List<ConstructorInitializer>() : initializers, null, body); static ConstructorFieldInitializer constructorFieldInitializer( bool prefixedWithThis, String fieldName, Expression expression) => astFactory.constructorFieldInitializer( prefixedWithThis ? TokenFactory.tokenFromKeyword(Keyword.THIS) : null, prefixedWithThis ? TokenFactory.tokenFromType(TokenType.PERIOD) : null, identifier3(fieldName), TokenFactory.tokenFromType(TokenType.EQ), expression); static ConstructorName constructorName(TypeName type, String name) => astFactory.constructorName( type, name == null ? null : TokenFactory.tokenFromType(TokenType.PERIOD), name == null ? null : identifier3(name)); static ContinueStatement continueStatement([String label]) => astFactory.continueStatement( TokenFactory.tokenFromKeyword(Keyword.CONTINUE), label == null ? null : identifier3(label), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static DeclaredIdentifier declaredIdentifier( Keyword keyword, String identifier) => declaredIdentifier2(keyword, null, identifier); static DeclaredIdentifier declaredIdentifier2( Keyword keyword, TypeAnnotation type, String identifier) => astFactory.declaredIdentifier( null, null, keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), type, identifier3(identifier)); static DeclaredIdentifier declaredIdentifier3(String identifier) => declaredIdentifier2(Keyword.VAR, null, identifier); static DeclaredIdentifier declaredIdentifier4( TypeAnnotation type, String identifier) => declaredIdentifier2(null, type, identifier); static Comment documentationComment( List<Token> tokens, List<CommentReference> references) { return astFactory.documentationComment(tokens, references); } static DoStatement doStatement(Statement body, Expression condition) => astFactory.doStatement( TokenFactory.tokenFromKeyword(Keyword.DO), body, TokenFactory.tokenFromKeyword(Keyword.WHILE), TokenFactory.tokenFromType(TokenType.OPEN_PAREN), condition, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static DoubleLiteral doubleLiteral(double value) => astFactory.doubleLiteral( TokenFactory.tokenFromString(value.toString()), value); static EmptyFunctionBody emptyFunctionBody() => astFactory .emptyFunctionBody(TokenFactory.tokenFromType(TokenType.SEMICOLON)); static EmptyStatement emptyStatement() => astFactory .emptyStatement(TokenFactory.tokenFromType(TokenType.SEMICOLON)); static EnumDeclaration enumDeclaration( SimpleIdentifier name, List<EnumConstantDeclaration> constants) => astFactory.enumDeclaration( null, null, TokenFactory.tokenFromKeyword(Keyword.ENUM), name, TokenFactory.tokenFromType(TokenType.OPEN_CURLY_BRACKET), constants, TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET)); static EnumDeclaration enumDeclaration2( String name, List<String> constantNames) { int count = constantNames.length; List<EnumConstantDeclaration> constants = new List<EnumConstantDeclaration>(count); for (int i = 0; i < count; i++) { constants[i] = astFactory.enumConstantDeclaration( null, null, identifier3(constantNames[i])); } return enumDeclaration(identifier3(name), constants); } static ExportDirective exportDirective(List<Annotation> metadata, String uri, [List<Combinator> combinators]) => astFactory.exportDirective( null, metadata, TokenFactory.tokenFromKeyword(Keyword.EXPORT), string2(uri), null, combinators, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static ExportDirective exportDirective2(String uri, [List<Combinator> combinators]) => exportDirective(null, uri, combinators); static ExpressionFunctionBody expressionFunctionBody(Expression expression) => astFactory.expressionFunctionBody( null, TokenFactory.tokenFromType(TokenType.FUNCTION), expression, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static ExpressionStatement expressionStatement(Expression expression) => astFactory.expressionStatement( expression, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static ExtendsClause extendsClause(TypeName type) => astFactory.extendsClause( TokenFactory.tokenFromKeyword(Keyword.EXTENDS), type); static ExtensionDeclaration extensionDeclaration( {@required String name, TypeParameterList typeParameters, @required TypeAnnotation extendedType, List<ClassMember> members}) => astFactory.extensionDeclaration( comment: null, metadata: null, extensionKeyword: TokenFactory.tokenFromKeyword(Keyword.EXTENSION), name: identifier3(name), typeParameters: typeParameters, onKeyword: TokenFactory.tokenFromKeyword(Keyword.ON), extendedType: extendedType, leftBracket: TokenFactory.tokenFromType(TokenType.OPEN_CURLY_BRACKET), members: members, rightBracket: TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET)); static ExtensionOverride extensionOverride( {@required Identifier extensionName, TypeArgumentList typeArguments, @required ArgumentList argumentList}) => astFactory.extensionOverride( extensionName: extensionName, typeArguments: typeArguments, argumentList: argumentList); static FieldDeclaration fieldDeclaration(bool isStatic, Keyword keyword, TypeAnnotation type, List<VariableDeclaration> variables) => astFactory.fieldDeclaration2( staticKeyword: isStatic ? TokenFactory.tokenFromKeyword(Keyword.STATIC) : null, fieldList: variableDeclarationList(keyword, type, variables), semicolon: TokenFactory.tokenFromType(TokenType.SEMICOLON)); static FieldDeclaration fieldDeclaration2(bool isStatic, Keyword keyword, List<VariableDeclaration> variables) => fieldDeclaration(isStatic, keyword, null, variables); static FieldFormalParameter fieldFormalParameter( Keyword keyword, TypeAnnotation type, String identifier, [FormalParameterList parameterList]) => astFactory.fieldFormalParameter2( keyword: keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), type: type, thisKeyword: TokenFactory.tokenFromKeyword(Keyword.THIS), period: TokenFactory.tokenFromType(TokenType.PERIOD), identifier: identifier3(identifier), parameters: parameterList); static FieldFormalParameter fieldFormalParameter2(String identifier) => fieldFormalParameter(null, null, identifier); static ForEachPartsWithDeclaration forEachPartsWithDeclaration( DeclaredIdentifier loopVariable, Expression iterable) => astFactory.forEachPartsWithDeclaration( loopVariable: loopVariable, inKeyword: TokenFactory.tokenFromKeyword(Keyword.IN), iterable: iterable); static ForEachPartsWithIdentifier forEachPartsWithIdentifier( SimpleIdentifier identifier, Expression iterable) => astFactory.forEachPartsWithIdentifier( identifier: identifier, inKeyword: TokenFactory.tokenFromKeyword(Keyword.IN), iterable: iterable); static ForElement forElement( ForLoopParts forLoopParts, CollectionElement body, {bool hasAwait: false}) => astFactory.forElement( awaitKeyword: hasAwait ? TokenFactory.tokenFromKeyword(Keyword.AWAIT) : null, forKeyword: TokenFactory.tokenFromKeyword(Keyword.FOR), leftParenthesis: TokenFactory.tokenFromType(TokenType.OPEN_PAREN), forLoopParts: forLoopParts, rightParenthesis: TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), body: body); static FormalParameterList formalParameterList( [List<FormalParameter> parameters]) => astFactory.formalParameterList( TokenFactory.tokenFromType(TokenType.OPEN_PAREN), parameters, null, null, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN)); static ForPartsWithDeclarations forPartsWithDeclarations( VariableDeclarationList variables, Expression condition, List<Expression> updaters) => astFactory.forPartsWithDeclarations( variables: variables, leftSeparator: TokenFactory.tokenFromType(TokenType.SEMICOLON), condition: condition, rightSeparator: TokenFactory.tokenFromType(TokenType.SEMICOLON), updaters: updaters); static ForPartsWithExpression forPartsWithExpression( Expression initialization, Expression condition, List<Expression> updaters) => astFactory.forPartsWithExpression( initialization: initialization, leftSeparator: TokenFactory.tokenFromType(TokenType.SEMICOLON), condition: condition, rightSeparator: TokenFactory.tokenFromType(TokenType.SEMICOLON), updaters: updaters); static ForStatement forStatement(ForLoopParts forLoopParts, Statement body) => astFactory.forStatement( forKeyword: TokenFactory.tokenFromKeyword(Keyword.FOR), leftParenthesis: TokenFactory.tokenFromType(TokenType.OPEN_PAREN), forLoopParts: forLoopParts, rightParenthesis: TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), body: body); static FunctionDeclaration functionDeclaration( TypeAnnotation type, Keyword keyword, String name, FunctionExpression functionExpression) => astFactory.functionDeclaration( null, null, null, type, keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), identifier3(name), functionExpression); static FunctionDeclarationStatement functionDeclarationStatement( TypeAnnotation type, Keyword keyword, String name, FunctionExpression functionExpression) => astFactory.functionDeclarationStatement( functionDeclaration(type, keyword, name, functionExpression)); static FunctionExpression functionExpression() => astFactory .functionExpression(null, formalParameterList(), blockFunctionBody2()); static FunctionExpression functionExpression2( FormalParameterList parameters, FunctionBody body) => astFactory.functionExpression(null, parameters, body); static FunctionExpression functionExpression3( TypeParameterList typeParameters, FormalParameterList parameters, FunctionBody body) => astFactory.functionExpression(typeParameters, parameters, body); static FunctionExpressionInvocation functionExpressionInvocation( Expression function, [List<Expression> arguments]) => functionExpressionInvocation2(function, null, arguments); static FunctionExpressionInvocation functionExpressionInvocation2( Expression function, [TypeArgumentList typeArguments, List<Expression> arguments]) => astFactory.functionExpressionInvocation( function, typeArguments, argumentList(arguments)); static FunctionTypedFormalParameter functionTypedFormalParameter( TypeAnnotation returnType, String identifier, [List<FormalParameter> parameters]) => astFactory.functionTypedFormalParameter2( returnType: returnType, identifier: identifier3(identifier), parameters: formalParameterList(parameters)); static GenericFunctionType genericFunctionType(TypeAnnotation returnType, TypeParameterList typeParameters, FormalParameterList parameters, {bool question: false}) => astFactory.genericFunctionType(returnType, TokenFactory.tokenFromString("Function"), typeParameters, parameters, question: question ? TokenFactory.tokenFromType(TokenType.QUESTION) : null); static GenericTypeAlias genericTypeAlias(String name, TypeParameterList typeParameters, GenericFunctionType functionType) => astFactory.genericTypeAlias( null, null, TokenFactory.tokenFromKeyword(Keyword.TYPEDEF), identifier3(name), typeParameters, TokenFactory.tokenFromType(TokenType.EQ), functionType, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static HideCombinator hideCombinator(List<SimpleIdentifier> identifiers) => astFactory.hideCombinator( TokenFactory.tokenFromString("hide"), identifiers); static HideCombinator hideCombinator2(List<String> identifiers) => astFactory.hideCombinator( TokenFactory.tokenFromString("hide"), identifierList(identifiers)); static PrefixedIdentifier identifier( SimpleIdentifier prefix, SimpleIdentifier identifier) => astFactory.prefixedIdentifier( prefix, TokenFactory.tokenFromType(TokenType.PERIOD), identifier); static SimpleIdentifier identifier3(String lexeme) => astFactory.simpleIdentifier( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, lexeme)); static PrefixedIdentifier identifier4( String prefix, SimpleIdentifier identifier) => astFactory.prefixedIdentifier(identifier3(prefix), TokenFactory.tokenFromType(TokenType.PERIOD), identifier); static PrefixedIdentifier identifier5(String prefix, String identifier) => astFactory.prefixedIdentifier( identifier3(prefix), TokenFactory.tokenFromType(TokenType.PERIOD), identifier3(identifier)); static List<SimpleIdentifier> identifierList(List<String> identifiers) { if (identifiers == null) { return null; } return identifiers .map((String identifier) => identifier3(identifier)) .toList(); } static IfElement ifElement( Expression condition, CollectionElement thenElement, [CollectionElement elseElement]) => astFactory.ifElement( ifKeyword: TokenFactory.tokenFromKeyword(Keyword.IF), leftParenthesis: TokenFactory.tokenFromType(TokenType.OPEN_PAREN), condition: condition, rightParenthesis: TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), thenElement: thenElement, elseKeyword: elseElement == null ? null : TokenFactory.tokenFromKeyword(Keyword.ELSE), elseElement: elseElement); static IfStatement ifStatement( Expression condition, Statement thenStatement) => ifStatement2(condition, thenStatement, null); static IfStatement ifStatement2(Expression condition, Statement thenStatement, Statement elseStatement) => astFactory.ifStatement( TokenFactory.tokenFromKeyword(Keyword.IF), TokenFactory.tokenFromType(TokenType.OPEN_PAREN), condition, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), thenStatement, elseStatement == null ? null : TokenFactory.tokenFromKeyword(Keyword.ELSE), elseStatement); static ImplementsClause implementsClause(List<TypeName> types) => astFactory.implementsClause( TokenFactory.tokenFromKeyword(Keyword.IMPLEMENTS), types); static ImportDirective importDirective( List<Annotation> metadata, String uri, bool isDeferred, String prefix, [List<Combinator> combinators]) => astFactory.importDirective( null, metadata, TokenFactory.tokenFromKeyword(Keyword.IMPORT), string2(uri), null, !isDeferred ? null : TokenFactory.tokenFromKeyword(Keyword.DEFERRED), prefix == null ? null : TokenFactory.tokenFromKeyword(Keyword.AS), prefix == null ? null : identifier3(prefix), combinators, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static ImportDirective importDirective2( String uri, bool isDeferred, String prefix, [List<Combinator> combinators]) => importDirective(null, uri, isDeferred, prefix, combinators); static ImportDirective importDirective3(String uri, String prefix, [List<Combinator> combinators]) => importDirective(null, uri, false, prefix, combinators); static IndexExpression indexExpression(Expression array, Expression index, [TokenType leftBracket = TokenType.OPEN_SQUARE_BRACKET]) => astFactory.indexExpressionForTarget( array, TokenFactory.tokenFromType(leftBracket), index, TokenFactory.tokenFromType(TokenType.CLOSE_SQUARE_BRACKET)); static InstanceCreationExpression instanceCreationExpression( Keyword keyword, ConstructorName name, [List<Expression> arguments]) => astFactory.instanceCreationExpression( keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), name, argumentList(arguments)); static InstanceCreationExpression instanceCreationExpression2( Keyword keyword, TypeName type, [List<Expression> arguments]) => instanceCreationExpression3(keyword, type, null, arguments); static InstanceCreationExpression instanceCreationExpression3( Keyword keyword, TypeName type, String identifier, [List<Expression> arguments]) => instanceCreationExpression( keyword, astFactory.constructorName( type, identifier == null ? null : TokenFactory.tokenFromType(TokenType.PERIOD), identifier == null ? null : identifier3(identifier)), arguments); static IntegerLiteral integer(int value) => astFactory.integerLiteral( TokenFactory.tokenFromTypeAndString(TokenType.INT, value.toString()), value); static InterpolationExpression interpolationExpression( Expression expression) => astFactory.interpolationExpression( TokenFactory.tokenFromType(TokenType.STRING_INTERPOLATION_EXPRESSION), expression, TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET)); static InterpolationExpression interpolationExpression2(String identifier) => astFactory.interpolationExpression( TokenFactory.tokenFromType(TokenType.STRING_INTERPOLATION_IDENTIFIER), identifier3(identifier), null); static InterpolationString interpolationString( String contents, String value) => astFactory.interpolationString( TokenFactory.tokenFromString(contents), value); static IsExpression isExpression( Expression expression, bool negated, TypeAnnotation type) => astFactory.isExpression( expression, TokenFactory.tokenFromKeyword(Keyword.IS), negated ? TokenFactory.tokenFromType(TokenType.BANG) : null, type); static Label label(SimpleIdentifier label) => astFactory.label(label, TokenFactory.tokenFromType(TokenType.COLON)); static Label label2(String label) => AstTestFactory.label(identifier3(label)); static LabeledStatement labeledStatement( List<Label> labels, Statement statement) => astFactory.labeledStatement(labels, statement); static LibraryDirective libraryDirective( List<Annotation> metadata, LibraryIdentifier libraryName) => astFactory.libraryDirective( null, metadata, TokenFactory.tokenFromKeyword(Keyword.LIBRARY), libraryName, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static LibraryDirective libraryDirective2(String libraryName) => libraryDirective( new List<Annotation>(), libraryIdentifier2([libraryName])); static LibraryIdentifier libraryIdentifier( List<SimpleIdentifier> components) => astFactory.libraryIdentifier(components); static LibraryIdentifier libraryIdentifier2(List<String> components) { return astFactory.libraryIdentifier(identifierList(components)); } static List list(List<Object> elements) { return elements; } static ListLiteral listLiteral([List<Expression> elements]) => listLiteral2(null, null, elements); static ListLiteral listLiteral2( Keyword keyword, TypeArgumentList typeArguments, [List<CollectionElement> elements]) => astFactory.listLiteral( keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), typeArguments, TokenFactory.tokenFromType(TokenType.OPEN_SQUARE_BRACKET), elements, TokenFactory.tokenFromType(TokenType.CLOSE_SQUARE_BRACKET)); static MapLiteralEntry mapLiteralEntry(String key, Expression value) => astFactory.mapLiteralEntry( string2(key), TokenFactory.tokenFromType(TokenType.COLON), value); static MapLiteralEntry mapLiteralEntry2(Expression key, Expression value) => astFactory.mapLiteralEntry( key, TokenFactory.tokenFromType(TokenType.COLON), value); static MapLiteralEntry mapLiteralEntry3(String key, String value) => astFactory.mapLiteralEntry(string2(key), TokenFactory.tokenFromType(TokenType.COLON), string2(value)); static MethodDeclaration methodDeclaration( Keyword modifier, TypeAnnotation returnType, Keyword property, Keyword operator, SimpleIdentifier name, FormalParameterList parameters) => astFactory.methodDeclaration( null, null, TokenFactory.tokenFromKeyword(Keyword.EXTERNAL), modifier == null ? null : TokenFactory.tokenFromKeyword(modifier), returnType, property == null ? null : TokenFactory.tokenFromKeyword(property), operator == null ? null : TokenFactory.tokenFromKeyword(operator), name, null, parameters, emptyFunctionBody()); static MethodDeclaration methodDeclaration2( Keyword modifier, TypeAnnotation returnType, Keyword property, Keyword operator, SimpleIdentifier name, FormalParameterList parameters, FunctionBody body) => astFactory.methodDeclaration( null, null, null, modifier == null ? null : TokenFactory.tokenFromKeyword(modifier), returnType, property == null ? null : TokenFactory.tokenFromKeyword(property), operator == null ? null : TokenFactory.tokenFromKeyword(operator), name, null, parameters, body); static MethodDeclaration methodDeclaration3( Keyword modifier, TypeAnnotation returnType, Keyword property, Keyword operator, SimpleIdentifier name, TypeParameterList typeParameters, FormalParameterList parameters, FunctionBody body) => astFactory.methodDeclaration( null, null, null, modifier == null ? null : TokenFactory.tokenFromKeyword(modifier), returnType, property == null ? null : TokenFactory.tokenFromKeyword(property), operator == null ? null : TokenFactory.tokenFromKeyword(operator), name, typeParameters, parameters, body); static MethodDeclaration methodDeclaration4( {bool external: false, Keyword modifier, TypeAnnotation returnType, Keyword property, bool operator: false, String name, FormalParameterList parameters, FunctionBody body}) => astFactory.methodDeclaration( null, null, external ? TokenFactory.tokenFromKeyword(Keyword.EXTERNAL) : null, modifier == null ? null : TokenFactory.tokenFromKeyword(modifier), returnType, property == null ? null : TokenFactory.tokenFromKeyword(property), operator ? TokenFactory.tokenFromKeyword(Keyword.OPERATOR) : null, identifier3(name), null, parameters, body); static MethodInvocation methodInvocation(Expression target, String methodName, [List<Expression> arguments, TokenType operator = TokenType.PERIOD]) => astFactory.methodInvocation( target, target == null ? null : TokenFactory.tokenFromType(operator), identifier3(methodName), null, argumentList(arguments)); static MethodInvocation methodInvocation2(String methodName, [List<Expression> arguments]) => methodInvocation(null, methodName, arguments); static MethodInvocation methodInvocation3( Expression target, String methodName, TypeArgumentList typeArguments, [List<Expression> arguments, TokenType operator = TokenType.PERIOD]) => astFactory.methodInvocation( target, target == null ? null : TokenFactory.tokenFromType(operator), identifier3(methodName), typeArguments, argumentList(arguments)); static NamedExpression namedExpression(Label label, Expression expression) => astFactory.namedExpression(label, expression); static NamedExpression namedExpression2( String label, Expression expression) => namedExpression(label2(label), expression); static DefaultFormalParameter namedFormalParameter( NormalFormalParameter parameter, Expression expression) => astFactory.defaultFormalParameter( parameter, ParameterKind.NAMED, expression == null ? null : TokenFactory.tokenFromType(TokenType.COLON), expression); static NativeClause nativeClause(String nativeCode) => astFactory.nativeClause( TokenFactory.tokenFromString("native"), string2(nativeCode)); static NativeFunctionBody nativeFunctionBody(String nativeMethodName) => astFactory.nativeFunctionBody( TokenFactory.tokenFromString("native"), string2(nativeMethodName), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static NullLiteral nullLiteral() => astFactory.nullLiteral(TokenFactory.tokenFromKeyword(Keyword.NULL)); static ParenthesizedExpression parenthesizedExpression( Expression expression) => astFactory.parenthesizedExpression( TokenFactory.tokenFromType(TokenType.OPEN_PAREN), expression, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN)); static PartDirective partDirective(List<Annotation> metadata, String url) => astFactory.partDirective( null, metadata, TokenFactory.tokenFromKeyword(Keyword.PART), string2(url), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static PartDirective partDirective2(String url) => partDirective(new List<Annotation>(), url); static PartOfDirective partOfDirective(LibraryIdentifier libraryName) => partOfDirective2(new List<Annotation>(), libraryName); static PartOfDirective partOfDirective2( List<Annotation> metadata, LibraryIdentifier libraryName) => astFactory.partOfDirective( null, metadata, TokenFactory.tokenFromKeyword(Keyword.PART), TokenFactory.tokenFromString("of"), null, libraryName, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static DefaultFormalParameter positionalFormalParameter( NormalFormalParameter parameter, Expression expression) => astFactory.defaultFormalParameter( parameter, ParameterKind.POSITIONAL, expression == null ? null : TokenFactory.tokenFromType(TokenType.EQ), expression); static PostfixExpression postfixExpression( Expression expression, TokenType operator) => astFactory.postfixExpression( expression, TokenFactory.tokenFromType(operator)); static PrefixExpression prefixExpression( TokenType operator, Expression expression) => astFactory.prefixExpression( TokenFactory.tokenFromType(operator), expression); static PropertyAccess propertyAccess( Expression target, SimpleIdentifier propertyName) => astFactory.propertyAccess( target, TokenFactory.tokenFromType(TokenType.PERIOD), propertyName); static PropertyAccess propertyAccess2(Expression target, String propertyName, [TokenType operator = TokenType.PERIOD]) => astFactory.propertyAccess(target, TokenFactory.tokenFromType(operator), identifier3(propertyName)); static RedirectingConstructorInvocation redirectingConstructorInvocation( [List<Expression> arguments]) => redirectingConstructorInvocation2(null, arguments); static RedirectingConstructorInvocation redirectingConstructorInvocation2( String constructorName, [List<Expression> arguments]) => astFactory.redirectingConstructorInvocation( TokenFactory.tokenFromKeyword(Keyword.THIS), constructorName == null ? null : TokenFactory.tokenFromType(TokenType.PERIOD), constructorName == null ? null : identifier3(constructorName), argumentList(arguments)); static RethrowExpression rethrowExpression() => astFactory .rethrowExpression(TokenFactory.tokenFromKeyword(Keyword.RETHROW)); static ReturnStatement returnStatement() => returnStatement2(null); static ReturnStatement returnStatement2(Expression expression) => astFactory.returnStatement(TokenFactory.tokenFromKeyword(Keyword.RETURN), expression, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static ScriptTag scriptTag(String scriptTag) => astFactory.scriptTag(TokenFactory.tokenFromString(scriptTag)); static SetOrMapLiteral setOrMapLiteral( Keyword keyword, TypeArgumentList typeArguments, [List<CollectionElement> elements]) => astFactory.setOrMapLiteral( constKeyword: keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), typeArguments: typeArguments, elements: elements); static ShowCombinator showCombinator(List<SimpleIdentifier> identifiers) => astFactory.showCombinator( TokenFactory.tokenFromString("show"), identifiers); static ShowCombinator showCombinator2(List<String> identifiers) => astFactory.showCombinator( TokenFactory.tokenFromString("show"), identifierList(identifiers)); static SimpleFormalParameter simpleFormalParameter( Keyword keyword, String parameterName) => simpleFormalParameter2(keyword, null, parameterName); static SimpleFormalParameter simpleFormalParameter2( Keyword keyword, TypeAnnotation type, String parameterName) => astFactory.simpleFormalParameter2( keyword: keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), type: type, identifier: parameterName == null ? null : identifier3(parameterName)); static SimpleFormalParameter simpleFormalParameter3(String parameterName) => simpleFormalParameter2(null, null, parameterName); static SimpleFormalParameter simpleFormalParameter4( TypeAnnotation type, String parameterName) => simpleFormalParameter2(null, type, parameterName); static SpreadElement spreadElement( TokenType operator, Expression expression) => astFactory.spreadElement( spreadOperator: TokenFactory.tokenFromType(operator), expression: expression); static StringInterpolation string([List<InterpolationElement> elements]) => astFactory.stringInterpolation(elements); static SimpleStringLiteral string2(String content) => astFactory .simpleStringLiteral(TokenFactory.tokenFromString("'$content'"), content); static SuperConstructorInvocation superConstructorInvocation( [List<Expression> arguments]) => superConstructorInvocation2(null, arguments); static SuperConstructorInvocation superConstructorInvocation2(String name, [List<Expression> arguments]) => astFactory.superConstructorInvocation( TokenFactory.tokenFromKeyword(Keyword.SUPER), name == null ? null : TokenFactory.tokenFromType(TokenType.PERIOD), name == null ? null : identifier3(name), argumentList(arguments)); static SuperExpression superExpression() => astFactory.superExpression(TokenFactory.tokenFromKeyword(Keyword.SUPER)); static SwitchCase switchCase( Expression expression, List<Statement> statements) => switchCase2(new List<Label>(), expression, statements); static SwitchCase switchCase2(List<Label> labels, Expression expression, List<Statement> statements) => astFactory.switchCase(labels, TokenFactory.tokenFromKeyword(Keyword.CASE), expression, TokenFactory.tokenFromType(TokenType.COLON), statements); static SwitchDefault switchDefault( List<Label> labels, List<Statement> statements) => astFactory.switchDefault( labels, TokenFactory.tokenFromKeyword(Keyword.DEFAULT), TokenFactory.tokenFromType(TokenType.COLON), statements); static SwitchDefault switchDefault2(List<Statement> statements) => switchDefault(new List<Label>(), statements); static SwitchStatement switchStatement( Expression expression, List<SwitchMember> members) => astFactory.switchStatement( TokenFactory.tokenFromKeyword(Keyword.SWITCH), TokenFactory.tokenFromType(TokenType.OPEN_PAREN), expression, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), TokenFactory.tokenFromType(TokenType.OPEN_CURLY_BRACKET), members, TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET)); static SymbolLiteral symbolLiteral(List<String> components) { List<Token> identifierList = new List<Token>(); for (String component in components) { identifierList.add( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, component)); } return astFactory.symbolLiteral( TokenFactory.tokenFromType(TokenType.HASH), identifierList); } static BlockFunctionBody syncBlockFunctionBody( [List<Statement> statements]) => astFactory.blockFunctionBody( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "sync"), null, block(statements)); static BlockFunctionBody syncGeneratorBlockFunctionBody( [List<Statement> statements]) => astFactory.blockFunctionBody( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "sync"), TokenFactory.tokenFromType(TokenType.STAR), block(statements)); static ThisExpression thisExpression() => astFactory.thisExpression(TokenFactory.tokenFromKeyword(Keyword.THIS)); static ThrowExpression throwExpression() => throwExpression2(null); static ThrowExpression throwExpression2(Expression expression) => astFactory.throwExpression( TokenFactory.tokenFromKeyword(Keyword.THROW), expression); static TopLevelVariableDeclaration topLevelVariableDeclaration( Keyword keyword, TypeAnnotation type, List<VariableDeclaration> variables) => astFactory.topLevelVariableDeclaration( null, null, variableDeclarationList(keyword, type, variables), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static TopLevelVariableDeclaration topLevelVariableDeclaration2( Keyword keyword, List<VariableDeclaration> variables) => astFactory.topLevelVariableDeclaration( null, null, variableDeclarationList(keyword, null, variables), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static TryStatement tryStatement(Block body, Block finallyClause) => tryStatement3(body, new List<CatchClause>(), finallyClause); static TryStatement tryStatement2( Block body, List<CatchClause> catchClauses) => tryStatement3(body, catchClauses, null); static TryStatement tryStatement3( Block body, List<CatchClause> catchClauses, Block finallyClause) => astFactory.tryStatement( TokenFactory.tokenFromKeyword(Keyword.TRY), body, catchClauses, finallyClause == null ? null : TokenFactory.tokenFromKeyword(Keyword.FINALLY), finallyClause); static FunctionTypeAlias typeAlias(TypeAnnotation returnType, String name, TypeParameterList typeParameters, FormalParameterList parameters) => astFactory.functionTypeAlias( null, null, TokenFactory.tokenFromKeyword(Keyword.TYPEDEF), returnType, identifier3(name), typeParameters, parameters, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static TypeArgumentList typeArgumentList(List<TypeAnnotation> types) { if (types == null || types.isEmpty) { return null; } return astFactory.typeArgumentList(TokenFactory.tokenFromType(TokenType.LT), types, TokenFactory.tokenFromType(TokenType.GT)); } /** * Create a type name whose name has been resolved to the given [element] and * whose type has been resolved to the type of the given element. * * <b>Note:</b> This method does not correctly handle class elements that have * type parameters. */ static TypeName typeName(ClassElement element, [List<TypeAnnotation> arguments]) { SimpleIdentifier name = identifier3(element.name); name.staticElement = element; TypeName typeName = typeName3(name, arguments); typeName.type = element.instantiate( typeArguments: List.filled( element.typeParameters.length, DynamicTypeImpl.instance, ), nullabilitySuffix: NullabilitySuffix.star, ); return typeName; } static TypeName typeName3(Identifier name, [List<TypeAnnotation> arguments]) => astFactory.typeName(name, typeArgumentList(arguments)); static TypeName typeName4(String name, [List<TypeAnnotation> arguments, bool question = false]) => astFactory.typeName(identifier3(name), typeArgumentList(arguments), question: question ? TokenFactory.tokenFromType(TokenType.QUESTION) : null); static TypeParameter typeParameter(String name) => astFactory.typeParameter(null, null, identifier3(name), null, null); static TypeParameter typeParameter2(String name, TypeAnnotation bound) => astFactory.typeParameter(null, null, identifier3(name), TokenFactory.tokenFromKeyword(Keyword.EXTENDS), bound); static TypeParameterList typeParameterList([List<String> typeNames]) { List<TypeParameter> typeParameters; if (typeNames != null && typeNames.isNotEmpty) { typeParameters = new List<TypeParameter>(); for (String typeName in typeNames) { typeParameters.add(typeParameter(typeName)); } } return astFactory.typeParameterList( TokenFactory.tokenFromType(TokenType.LT), typeParameters, TokenFactory.tokenFromType(TokenType.GT)); } static VariableDeclaration variableDeclaration(String name) => astFactory.variableDeclaration(identifier3(name), null, null); static VariableDeclaration variableDeclaration2( String name, Expression initializer) => astFactory.variableDeclaration(identifier3(name), TokenFactory.tokenFromType(TokenType.EQ), initializer); static VariableDeclarationList variableDeclarationList(Keyword keyword, TypeAnnotation type, List<VariableDeclaration> variables) => astFactory.variableDeclarationList( null, null, keyword == null ? null : TokenFactory.tokenFromKeyword(keyword), type, variables); static VariableDeclarationList variableDeclarationList2( Keyword keyword, List<VariableDeclaration> variables) => variableDeclarationList(keyword, null, variables); static VariableDeclarationStatement variableDeclarationStatement( Keyword keyword, TypeAnnotation type, List<VariableDeclaration> variables) => astFactory.variableDeclarationStatement( variableDeclarationList(keyword, type, variables), TokenFactory.tokenFromType(TokenType.SEMICOLON)); static VariableDeclarationStatement variableDeclarationStatement2( Keyword keyword, List<VariableDeclaration> variables) => variableDeclarationStatement(keyword, null, variables); static WhileStatement whileStatement(Expression condition, Statement body) => astFactory.whileStatement( TokenFactory.tokenFromKeyword(Keyword.WHILE), TokenFactory.tokenFromType(TokenType.OPEN_PAREN), condition, TokenFactory.tokenFromType(TokenType.CLOSE_PAREN), body); static WithClause withClause(List<TypeName> types) => astFactory.withClause(TokenFactory.tokenFromKeyword(Keyword.WITH), types); static YieldStatement yieldEachStatement(Expression expression) => astFactory.yieldStatement( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "yield"), TokenFactory.tokenFromType(TokenType.STAR), expression, TokenFactory.tokenFromType(TokenType.SEMICOLON)); static YieldStatement yieldStatement(Expression expression) => astFactory.yieldStatement( TokenFactory.tokenFromTypeAndString(TokenType.IDENTIFIER, "yield"), null, expression, TokenFactory.tokenFromType(TokenType.SEMICOLON)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/testing/element_search.dart
// Copyright (c) 2017, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; /** * Search the [unit] for the [Element]s with the given [name]. */ List<Element> findElementsByName(CompilationUnit unit, String name) { var finder = new _ElementsByNameFinder(name); unit.accept(finder); return finder.elements; } class _ElementsByNameFinder extends RecursiveAstVisitor<void> { final String name; final List<Element> elements = []; _ElementsByNameFinder(this.name); @override visitSimpleIdentifier(SimpleIdentifier node) { if (node.name == name && node.inDeclarationContext()) { elements.add(node.staticElement); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/testing/element_factory.dart
// Copyright (c) 2014, 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/constant.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/testing/ast_test_factory.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart'; /** * The class `ElementFactory` defines utility methods used to create elements for testing * purposes. The elements that are created are complete in the sense that as much of the element * model as can be created, given the provided information, has been created. */ class ElementFactory { /** * The element representing the class 'Object'. */ static ClassElementImpl _objectElement; static InterfaceType _objectType; static ClassElementImpl get object { if (_objectElement == null) { _objectElement = classElement("Object", null); } return _objectElement; } static InterfaceType get objectType { return _objectType ??= object.instantiate( typeArguments: const [], nullabilitySuffix: NullabilitySuffix.star, ); } static ClassElementImpl classElement( String typeName, InterfaceType superclassType, [List<String> parameterNames]) { ClassElementImpl element = new ClassElementImpl(typeName, 0); element.constructors = const <ConstructorElement>[]; element.supertype = superclassType; if (parameterNames != null) { element.typeParameters = typeParameters(parameterNames); } return element; } static ClassElementImpl classElement2(String typeName, [List<String> parameterNames]) => classElement(typeName, objectType, parameterNames); static ClassElementImpl classElement3({ @required String name, List<TypeParameterElement> typeParameters, List<String> typeParameterNames = const [], InterfaceType supertype, List<InterfaceType> mixins = const [], List<InterfaceType> interfaces = const [], }) { typeParameters ??= ElementFactory.typeParameters(typeParameterNames); supertype ??= objectType; var element = ClassElementImpl(name, 0); element.typeParameters = typeParameters; element.supertype = supertype; element.mixins = mixins; element.interfaces = interfaces; element.constructors = const <ConstructorElement>[]; return element; } static classTypeAlias(String typeName, InterfaceType superclassType, [List<String> parameterNames]) { ClassElementImpl element = classElement(typeName, superclassType, parameterNames); element.mixinApplication = true; return element; } static ClassElementImpl classTypeAlias2(String typeName, [List<String> parameterNames]) => classTypeAlias(typeName, objectType, parameterNames); static CompilationUnitElementImpl compilationUnit(String fileName, [Source librarySource]) { Source source = new NonExistingSource(fileName, toUri(fileName), UriKind.FILE_URI); CompilationUnitElementImpl unit = new CompilationUnitElementImpl(); unit.source = source; if (librarySource == null) { librarySource = source; } unit.librarySource = librarySource; return unit; } static ConstLocalVariableElementImpl constLocalVariableElement(String name) => new ConstLocalVariableElementImpl(name, 0); static ConstructorElementImpl constructorElement( ClassElement definingClass, String name, bool isConst, [List<DartType> argumentTypes]) { ConstructorElementImpl constructor = name == null ? new ConstructorElementImpl("", -1) : new ConstructorElementImpl(name, 0); if (name != null) { if (name.isEmpty) { constructor.nameEnd = definingClass.name.length; } else { constructor.periodOffset = definingClass.name.length; constructor.nameEnd = definingClass.name.length + name.length + 1; } } constructor.isSynthetic = name == null; constructor.isConst = isConst; if (argumentTypes != null) { int count = argumentTypes.length; List<ParameterElement> parameters = new List<ParameterElement>(count); for (int i = 0; i < count; i++) { ParameterElementImpl parameter = new ParameterElementImpl("a$i", i); parameter.type = argumentTypes[i]; parameter.parameterKind = ParameterKind.REQUIRED; parameters[i] = parameter; } constructor.parameters = parameters; } else { constructor.parameters = <ParameterElement>[]; } constructor.enclosingElement = definingClass; if (!constructor.isSynthetic) { constructor.constantInitializers = <ConstructorInitializer>[]; } return constructor; } static ConstructorElementImpl constructorElement2( ClassElement definingClass, String name, [List<DartType> argumentTypes]) => constructorElement(definingClass, name, false, argumentTypes); static EnumElementImpl enumElement(TypeProvider typeProvider, String enumName, [List<String> constantNames]) { // // Build the enum. // EnumElementImpl enumElement = new EnumElementImpl(enumName, -1); InterfaceTypeImpl enumType = enumElement.instantiate( typeArguments: const [], nullabilitySuffix: NullabilitySuffix.star, ); // // Populate the fields. // List<FieldElement> fields = new List<FieldElement>(); InterfaceType intType = typeProvider.intType; InterfaceType stringType = typeProvider.stringType; String indexFieldName = "index"; FieldElementImpl indexField = new FieldElementImpl(indexFieldName, -1); indexField.isFinal = true; indexField.type = intType; fields.add(indexField); String nameFieldName = "_name"; FieldElementImpl nameField = new FieldElementImpl(nameFieldName, -1); nameField.isFinal = true; nameField.type = stringType; fields.add(nameField); FieldElementImpl valuesField = new FieldElementImpl("values", -1); valuesField.isStatic = true; valuesField.isConst = true; valuesField.type = typeProvider.listType2(enumType); fields.add(valuesField); // // Build the enum constants. // if (constantNames != null) { int constantCount = constantNames.length; for (int i = 0; i < constantCount; i++) { String constantName = constantNames[i]; FieldElementImpl constantElement = new ConstFieldElementImpl(constantName, -1); constantElement.isStatic = true; constantElement.isConst = true; constantElement.type = enumType; Map<String, DartObjectImpl> fieldMap = new HashMap<String, DartObjectImpl>(); fieldMap[indexFieldName] = new DartObjectImpl(intType, new IntState(i)); fieldMap[nameFieldName] = new DartObjectImpl(stringType, new StringState(constantName)); DartObjectImpl value = new DartObjectImpl(enumType, new GenericState(fieldMap)); constantElement.evaluationResult = new EvaluationResultImpl(value); fields.add(constantElement); } } // // Finish building the enum. // enumElement.fields = fields; // Client code isn't allowed to invoke the constructor, so we do not model it. return enumElement; } static ExportElementImpl exportFor(LibraryElement exportedLibrary, [List<NamespaceCombinator> combinators = const <NamespaceCombinator>[]]) { ExportElementImpl spec = new ExportElementImpl(-1); spec.exportedLibrary = exportedLibrary; spec.combinators = combinators; return spec; } static ExtensionElementImpl extensionElement( [String name, DartType extendedType]) => ExtensionElementImpl.forNode(AstTestFactory.identifier3(name)) ..extendedType = extendedType; static FieldElementImpl fieldElement( String name, bool isStatic, bool isFinal, bool isConst, DartType type, {Expression initializer}) { FieldElementImpl field = isConst ? new ConstFieldElementImpl(name, 0) : new FieldElementImpl(name, 0); field.isConst = isConst; field.isFinal = isFinal; field.isStatic = isStatic; field.type = type; if (isConst) { (field as ConstFieldElementImpl).constantInitializer = initializer; } new PropertyAccessorElementImpl_ImplicitGetter(field); if (!isConst && !isFinal) { new PropertyAccessorElementImpl_ImplicitSetter(field); } return field; } static FieldFormalParameterElementImpl fieldFormalParameter( Identifier name) => new FieldFormalParameterElementImpl.forNode(name); /** * Destroy any static state retained by [ElementFactory]. This should be * called from the `setUp` method of any tests that use [ElementFactory], in * order to ensure that state is not shared between multiple tests. */ static void flushStaticState() { _objectElement = null; } static FunctionElementImpl functionElement(String functionName) => functionElement4(functionName, null, null, null, null); static FunctionElementImpl functionElement2( String functionName, DartType returnType) => functionElement3(functionName, returnType, null, null); static FunctionElementImpl functionElement3( String functionName, DartType returnType, List<TypeDefiningElement> normalParameters, List<TypeDefiningElement> optionalParameters) { // We don't create parameter elements because we don't have parameter names FunctionElementImpl functionElement = new FunctionElementImpl(functionName, 0); FunctionTypeImpl functionType = new FunctionTypeImpl(functionElement); functionElement.type = functionType; functionElement.returnType = returnType ?? VoidTypeImpl.instance; // parameters int normalCount = normalParameters == null ? 0 : normalParameters.length; int optionalCount = optionalParameters == null ? 0 : optionalParameters.length; int totalCount = normalCount + optionalCount; List<ParameterElement> parameters = new List<ParameterElement>(totalCount); for (int i = 0; i < totalCount; i++) { ParameterElementImpl parameter = new ParameterElementImpl("a$i", i); if (i < normalCount) { parameter.type = _typeDefiningElementType(normalParameters[i]); parameter.parameterKind = ParameterKind.REQUIRED; } else { parameter.type = _typeDefiningElementType(optionalParameters[i - normalCount]); parameter.parameterKind = ParameterKind.POSITIONAL; } parameters[i] = parameter; } functionElement.parameters = parameters; // done return functionElement; } static FunctionElementImpl functionElement4( String functionName, ClassElement returnElement, List<ClassElement> normalParameters, List<String> names, List<ClassElement> namedParameters) { FunctionElementImpl functionElement = new FunctionElementImpl(functionName, 0); FunctionTypeImpl functionType = new FunctionTypeImpl(functionElement); functionElement.type = functionType; // parameters int normalCount = normalParameters == null ? 0 : normalParameters.length; int nameCount = names == null ? 0 : names.length; int typeCount = namedParameters == null ? 0 : namedParameters.length; if (names != null && nameCount != typeCount) { throw new StateError( "The passed String[] and ClassElement[] arrays had different lengths."); } int totalCount = normalCount + nameCount; List<ParameterElement> parameters = new List<ParameterElement>(totalCount); for (int i = 0; i < totalCount; i++) { if (i < normalCount) { ParameterElementImpl parameter = new ParameterElementImpl("a$i", i); parameter.type = _typeDefiningElementType(normalParameters[i]); parameter.parameterKind = ParameterKind.REQUIRED; parameters[i] = parameter; } else { ParameterElementImpl parameter = new ParameterElementImpl(names[i - normalCount], i); parameter.type = _typeDefiningElementType(namedParameters[i - normalCount]); parameter.parameterKind = ParameterKind.NAMED; parameters[i] = parameter; } } functionElement.parameters = parameters; // return type if (returnElement == null) { functionElement.returnType = VoidTypeImpl.instance; } else { functionElement.returnType = _typeDefiningElementType(returnElement); } return functionElement; } static FunctionElementImpl functionElement5( String functionName, List<ClassElement> normalParameters) => functionElement3(functionName, null, normalParameters, null); static FunctionElementImpl functionElement6( String functionName, List<ClassElement> normalParameters, List<ClassElement> optionalParameters) => functionElement3( functionName, null, normalParameters, optionalParameters); static FunctionElementImpl functionElement7( String functionName, List<ClassElement> normalParameters, List<String> names, List<ClassElement> namedParameters) => functionElement4( functionName, null, normalParameters, names, namedParameters); static FunctionElementImpl functionElement8( List<DartType> parameters, DartType returnType, {List<DartType> optional, Map<String, DartType> named}) { List<ParameterElement> parameterElements = new List<ParameterElement>(); for (int i = 0; i < parameters.length; i++) { ParameterElementImpl parameterElement = new ParameterElementImpl("a$i", i); parameterElement.type = parameters[i]; parameterElement.parameterKind = ParameterKind.REQUIRED; parameterElements.add(parameterElement); } if (optional != null) { int j = parameters.length; for (int i = 0; i < optional.length; i++) { ParameterElementImpl parameterElement = new ParameterElementImpl("o$i", j); parameterElement.type = optional[i]; parameterElement.parameterKind = ParameterKind.POSITIONAL; parameterElements.add(parameterElement); j++; } } else if (named != null) { int j = parameters.length; for (String s in named.keys) { ParameterElementImpl parameterElement = new ParameterElementImpl(s, j); parameterElement.type = named[s]; parameterElement.parameterKind = ParameterKind.NAMED; parameterElements.add(parameterElement); } } return functionElementWithParameters("f", returnType, parameterElements); } static FunctionElementImpl functionElementWithParameters(String functionName, DartType returnType, List<ParameterElement> parameters) { FunctionElementImpl functionElement = new FunctionElementImpl(functionName, 0); functionElement.returnType = returnType == null ? VoidTypeImpl.instance : returnType; functionElement.parameters = parameters; FunctionTypeImpl functionType = new FunctionTypeImpl(functionElement); functionElement.type = functionType; return functionElement; } static GenericTypeAliasElementImpl genericTypeAliasElement(String name, {List<ParameterElement> parameters: const [], DartType returnType}) { var element = new GenericTypeAliasElementImpl(name, -1); element.function = new GenericFunctionTypeElementImpl.forOffset(-1) ..parameters = parameters ..returnType = returnType ?? DynamicTypeImpl.instance; return element; } static PropertyAccessorElementImpl getterElement( String name, bool isStatic, DartType type) { FieldElementImpl field = new FieldElementImpl(name, -1); field.isStatic = isStatic; field.isSynthetic = true; field.type = type; field.isFinal = true; PropertyAccessorElementImpl getter = new PropertyAccessorElementImpl(name, 0); getter.isSynthetic = false; getter.getter = true; getter.variable = field; getter.returnType = type; getter.isStatic = isStatic; field.getter = getter; FunctionTypeImpl getterType = new FunctionTypeImpl(getter); getter.type = getterType; return getter; } static ImportElementImpl importFor( LibraryElement importedLibrary, PrefixElement prefix, [List<NamespaceCombinator> combinators = const <NamespaceCombinator>[]]) { ImportElementImpl spec = new ImportElementImpl(0); spec.importedLibrary = importedLibrary; spec.prefix = prefix; spec.combinators = combinators; return spec; } static LibraryElementImpl library(AnalysisContext context, String libraryName, {bool isNonNullableByDefault: true}) { String fileName = "/$libraryName.dart"; CompilationUnitElementImpl unit = compilationUnit(fileName); LibraryElementImpl library = new LibraryElementImpl(context, null, libraryName, 0, libraryName.length, isNonNullableByDefault); library.definingCompilationUnit = unit; return library; } static LocalVariableElementImpl localVariableElement(Identifier name) => new LocalVariableElementImpl.forNode(name); static LocalVariableElementImpl localVariableElement2(String name) => new LocalVariableElementImpl(name, 0); static MethodElementImpl methodElement(String methodName, DartType returnType, [List<DartType> argumentTypes]) { MethodElementImpl method = new MethodElementImpl(methodName, 0); if (argumentTypes == null) { method.parameters = const <ParameterElement>[]; } else { int count = argumentTypes.length; List<ParameterElement> parameters = new List<ParameterElement>(count); for (int i = 0; i < count; i++) { ParameterElementImpl parameter = new ParameterElementImpl("a$i", i); parameter.type = argumentTypes[i]; parameter.parameterKind = ParameterKind.REQUIRED; parameters[i] = parameter; } method.parameters = parameters; } method.returnType = returnType; FunctionTypeImpl methodType = new FunctionTypeImpl(method); method.type = methodType; return method; } static MethodElementImpl methodElementWithParameters( ClassElement enclosingElement, String methodName, DartType returnType, List<ParameterElement> parameters) { MethodElementImpl method = new MethodElementImpl(methodName, 0); method.enclosingElement = enclosingElement; method.parameters = parameters; method.returnType = returnType; method.type = new FunctionTypeImpl(method); return method; } static MixinElementImpl mixinElement({ @required String name, List<TypeParameterElement> typeParameters, List<String> typeParameterNames = const [], List<InterfaceType> constraints = const [], List<InterfaceType> interfaces = const [], }) { typeParameters ??= ElementFactory.typeParameters(typeParameterNames); if (constraints.isEmpty) { constraints = [objectType]; } var element = MixinElementImpl(name, 0); element.typeParameters = typeParameters; element.superclassConstraints = constraints; element.interfaces = interfaces; element.constructors = const <ConstructorElement>[]; return element; } static ParameterElementImpl namedParameter(String name) { ParameterElementImpl parameter = new ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.NAMED; return parameter; } static ParameterElementImpl namedParameter2(String name, DartType type) { ParameterElementImpl parameter = new ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.NAMED; parameter.type = type; return parameter; } static ParameterElementImpl namedParameter3(String name, {DartType type, Expression initializer, String initializerCode}) { DefaultParameterElementImpl parameter = new DefaultParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.NAMED; parameter.type = type; parameter.constantInitializer = initializer; parameter.defaultValueCode = initializerCode; return parameter; } static ParameterElementImpl positionalParameter(String name) { ParameterElementImpl parameter = new ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.POSITIONAL; return parameter; } static ParameterElementImpl positionalParameter2(String name, DartType type) { ParameterElementImpl parameter = new ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.POSITIONAL; parameter.type = type; return parameter; } static PrefixElementImpl prefix(String name) => new PrefixElementImpl(name, 0); static ParameterElementImpl requiredParameter(String name) { ParameterElementImpl parameter = new ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.REQUIRED; return parameter; } static ParameterElementImpl requiredParameter2(String name, DartType type) { ParameterElementImpl parameter = new ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.REQUIRED; parameter.type = type; return parameter; } static PropertyAccessorElementImpl setterElement( String name, bool isStatic, DartType type) { FieldElementImpl field = new FieldElementImpl(name, -1); field.isStatic = isStatic; field.isSynthetic = true; field.type = type; PropertyAccessorElementImpl getter = new PropertyAccessorElementImpl(name, -1); getter.getter = true; getter.variable = field; getter.returnType = type; field.getter = getter; FunctionTypeImpl getterType = new FunctionTypeImpl(getter); getter.type = getterType; ParameterElementImpl parameter = requiredParameter2("a", type); PropertyAccessorElementImpl setter = new PropertyAccessorElementImpl(name, -1); setter.setter = true; setter.isSynthetic = true; setter.variable = field; setter.parameters = <ParameterElement>[parameter]; setter.returnType = VoidTypeImpl.instance; setter.type = new FunctionTypeImpl(setter); setter.isStatic = isStatic; field.setter = setter; return setter; } static TopLevelVariableElementImpl topLevelVariableElement(Identifier name) => new TopLevelVariableElementImpl.forNode(name); static TopLevelVariableElementImpl topLevelVariableElement2(String name) => topLevelVariableElement3(name, false, false, null); static TopLevelVariableElementImpl topLevelVariableElement3( String name, bool isConst, bool isFinal, DartType type) { TopLevelVariableElementImpl variable; if (isConst) { ConstTopLevelVariableElementImpl constant = new ConstTopLevelVariableElementImpl.forNode( AstTestFactory.identifier3(name)); InstanceCreationExpression initializer = AstTestFactory.instanceCreationExpression2( Keyword.CONST, AstTestFactory.typeName(type.element)); if (type is InterfaceType) { ConstructorElement element = type.element.unnamedConstructor; initializer.staticElement = element; initializer.constructorName.staticElement = element; } constant.constantInitializer = initializer; variable = constant; } else { variable = new TopLevelVariableElementImpl(name, -1); } variable.isConst = isConst; variable.isFinal = isFinal; variable.isSynthetic = false; variable.type = type; new PropertyAccessorElementImpl_ImplicitGetter(variable); if (!isConst && !isFinal) { new PropertyAccessorElementImpl_ImplicitSetter(variable); } return variable; } static TypeParameterElementImpl typeParameterElement(String name) { return new TypeParameterElementImpl(name, 0); } static List<TypeParameterElement> typeParameters(List<String> names) { int count = names.length; if (count == 0) { return const <TypeParameterElement>[]; } List<TypeParameterElementImpl> typeParameters = new List<TypeParameterElementImpl>(count); for (int i = 0; i < count; i++) { typeParameters[i] = typeParameterWithType(names[i]); } return typeParameters; } static TypeParameterElementImpl typeParameterWithType(String name, [DartType bound]) { TypeParameterElementImpl typeParameter = typeParameterElement(name); typeParameter.bound = bound; return typeParameter; } static DartType _typeDefiningElementType(TypeDefiningElement element) { if (element is ClassElement) { return element.instantiate( typeArguments: List.filled( element.typeParameters.length, DynamicTypeImpl.instance, ), nullabilitySuffix: NullabilitySuffix.star, ); } throw ArgumentError('element: (${element.runtimeType}) $element'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/testing/node_search.dart
// Copyright (c) 2017, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; /** * Search the [unit] for declared [SimpleIdentifier]s with the given [name]. */ List<SimpleIdentifier> findDeclaredIdentifiersByName( CompilationUnit unit, String name) { var finder = new _DeclaredIdentifiersByNameFinder(name); unit.accept(finder); return finder.identifiers; } class _DeclaredIdentifiersByNameFinder extends RecursiveAstVisitor<void> { final String name; final List<SimpleIdentifier> identifiers = []; _DeclaredIdentifiersByNameFinder(this.name); @override visitSimpleIdentifier(SimpleIdentifier node) { if (node.name == name && node.inDeclarationContext()) { identifiers.add(node); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/generated/testing/token_factory.dart
// Copyright (c) 2014, 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:analyzer/dart/ast/token.dart'; import 'package:analyzer/src/dart/ast/token.dart'; /** * A set of utility methods that can be used to create tokens. */ class TokenFactory { static Token tokenFromKeyword(Keyword keyword) => new KeywordToken(keyword, 0); static Token tokenFromString(String lexeme) => new StringToken(TokenType.STRING, lexeme, 0); static Token tokenFromType(TokenType type) => new Token(type, 0); static Token tokenFromTypeAndString(TokenType type, String lexeme) => new StringToken(type, lexeme, 0); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/pubspec/pubspec_warning_code.dart
// Copyright (c) 2017, 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:analyzer/error/error.dart'; /** * The error codes used for warnings in analysis options files. The convention * for this class is for the name of the error code to indicate the problem that * caused the error to be generated and for the error message to explain what is * wrong and, when appropriate, how the problem can be corrected. */ class PubspecWarningCode extends ErrorCode { /** * A code indicating that a specified asset does not exist. * * Parameters: * 0: the path to the asset as given in the file. */ static const PubspecWarningCode ASSET_DOES_NOT_EXIST = const PubspecWarningCode( 'ASSET_DOES_NOT_EXIST', "The asset {0} does not exist.", correction: "Try creating the file or fixing the path to the file."); /** * A code indicating that a specified asset directory does not exist. * * Parameters: * 0: the path to the asset directory as given in the file. */ static const PubspecWarningCode ASSET_DIRECTORY_DOES_NOT_EXIST = const PubspecWarningCode('ASSET_DIRECTORY_DOES_NOT_EXIST', "The asset directory {0} does not exist.", correction: "Try creating the directory or fixing the path to the " "directory."); /** * A code indicating that the value of the asset field is not a list. */ static const PubspecWarningCode ASSET_FIELD_NOT_LIST = const PubspecWarningCode( 'ASSET_FIELD_NOT_LIST', "The value of the 'asset' field is expected to be a list of relative file paths.", correction: "Try converting the value to be a list of relative file paths."); /** * A code indicating that an element in the asset list is not a string. */ static const PubspecWarningCode ASSET_NOT_STRING = const PubspecWarningCode( 'ASSET_NOT_STRING', "Assets are expected to be a file paths (strings).", correction: "Try converting the value to be a string."); /** * A code indicating that the value of a dependencies field is not a map. */ static const PubspecWarningCode DEPENDENCIES_FIELD_NOT_MAP = const PubspecWarningCode('DEPENDENCIES_FIELD_NOT_MAP', "The value of the '{0}' field is expected to be a map.", correction: "Try converting the value to be a map."); /** * A code indicating that the value of the flutter field is not a map. */ static const PubspecWarningCode FLUTTER_FIELD_NOT_MAP = const PubspecWarningCode('FLUTTER_FIELD_NOT_MAP', "The value of the 'flutter' field is expected to be a map.", correction: "Try converting the value to be a map."); /** * A code indicating that the name field is missing. */ static const PubspecWarningCode MISSING_NAME = const PubspecWarningCode( 'MISSING_NAME', "The name field is required but missing.", correction: "Try adding a field named 'name'."); /** * A code indicating that the name field is not a string. */ static const PubspecWarningCode NAME_NOT_STRING = const PubspecWarningCode( 'NAME_NOT_STRING', "The value of the name field is expected to be a string.", correction: "Try converting the value to be a string."); /** * A code indicating that a package listed as a dev dependency is also listed * as a normal dependency. * * Parameters: * 0: the name of the package in the dev_dependency list. */ static const PubspecWarningCode UNNECESSARY_DEV_DEPENDENCY = const PubspecWarningCode( 'UNNECESSARY_DEV_DEPENDENCY', "The dev dependency on {0} is unnecessary because there is also a " "normal dependency on that package.", correction: "Try removing the dev dependency."); /** * Initialize a newly created warning code to have the given [name], [message] * and [correction]. */ const PubspecWarningCode(String name, String message, {String correction}) : super.temporary(name, message, correction: correction); @override ErrorSeverity get errorSeverity => ErrorSeverity.WARNING; @override ErrorType get type => ErrorType.STATIC_WARNING; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/pubspec/pubspec_validator.dart
// Copyright (c) 2017, 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:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/pubspec/pubspec_warning_code.dart'; import 'package:path/path.dart' as path; import 'package:source_span/src/span.dart'; import 'package:yaml/yaml.dart'; class PubspecValidator { /** * The name of the sub-field (under `flutter`) whose value is a list of assets * available to Flutter apps at runtime. */ static const String ASSETS_FIELD = 'assets'; /** * The name of the field whose value is a map of dependencies. */ static const String DEPENDENCIES_FIELD = 'dependencies'; /** * The name of the field whose value is a map of development dependencies. */ static const String DEV_DEPENDENCIES_FIELD = 'dev_dependencies'; /** * The name of the field whose value is a specification of Flutter-specific * configuration data. */ static const String FLUTTER_FIELD = 'flutter'; /** * The name of the field whose value is the name of the package. */ static const String NAME_FIELD = 'name'; /** * The resource provider used to access the file system. */ final ResourceProvider provider; /** * The source representing the file being validated. */ final Source source; /** * Initialize a newly create validator to validate the content of the given * [source]. */ PubspecValidator(this.provider, this.source); /** * Validate the given [contents]. */ List<AnalysisError> validate(Map<dynamic, YamlNode> contents) { RecordingErrorListener recorder = new RecordingErrorListener(); ErrorReporter reporter = new ErrorReporter(recorder, source); _validateDependencies(reporter, contents); _validateFlutter(reporter, contents); _validateName(reporter, contents); return recorder.errors; } /** * Return `true` if an asset (file) exists at the given absolute, normalized * [assetPath] or in a subdirectory of the parent of the file. */ bool _assetExistsAtPath(String assetPath) { // Check for asset directories. Folder assetDirectory = provider.getFolder(assetPath); if (assetDirectory.exists) { return true; } // Else, check for an asset file. File assetFile = provider.getFile(assetPath); if (assetFile.exists) { return true; } String fileName = assetFile.shortName; Folder assetFolder = assetFile.parent; if (!assetFolder.exists) { return false; } for (Resource child in assetFolder.getChildren()) { if (child is Folder) { File innerFile = child.getChildAssumingFile(fileName); if (innerFile.exists) { return true; } } } return false; } /** * Return a map whose keys are the names of declared dependencies and whose * values are the specifications of those dependencies. The map is extracted * from the given [contents] using the given [key]. */ Map<dynamic, YamlNode> _getDeclaredDependencies( ErrorReporter reporter, Map<dynamic, YamlNode> contents, String key) { YamlNode field = contents[key]; if (field == null || (field is YamlScalar && field.value == null)) { return <String, YamlNode>{}; } else if (field is YamlMap) { return field.nodes; } _reportErrorForNode( reporter, field, PubspecWarningCode.DEPENDENCIES_FIELD_NOT_MAP, [key]); return <String, YamlNode>{}; } /** * Report an error for the given node. */ void _reportErrorForNode( ErrorReporter reporter, YamlNode node, ErrorCode errorCode, [List<Object> arguments]) { SourceSpan span = node.span; reporter.reportErrorForOffset( errorCode, span.start.offset, span.length, arguments); } /** * Validate the value of the required `name` field. */ void _validateDependencies( ErrorReporter reporter, Map<dynamic, YamlNode> contents) { Map<dynamic, YamlNode> declaredDependencies = _getDeclaredDependencies(reporter, contents, DEPENDENCIES_FIELD); Map<dynamic, YamlNode> declaredDevDependencies = _getDeclaredDependencies(reporter, contents, DEV_DEPENDENCIES_FIELD); for (YamlNode packageName in declaredDevDependencies.keys) { if (declaredDependencies.containsKey(packageName)) { _reportErrorForNode(reporter, packageName, PubspecWarningCode.UNNECESSARY_DEV_DEPENDENCY, [packageName.value]); } } } /** * Validate the value of the optional `flutter` field. */ void _validateFlutter( ErrorReporter reporter, Map<dynamic, YamlNode> contents) { YamlNode flutterField = contents[FLUTTER_FIELD]; if (flutterField is YamlMap) { YamlNode assetsField = flutterField.nodes[ASSETS_FIELD]; if (assetsField is YamlList) { path.Context context = provider.pathContext; String packageRoot = context.dirname(source.fullName); for (YamlNode entryValue in assetsField.nodes) { if (entryValue is YamlScalar) { Object entry = entryValue.value; if (entry is String) { if (entry.startsWith('packages/')) { // TODO(brianwilkerson) Add validation of package references. } else { bool isDirectoryEntry = entry.endsWith("/"); String normalizedEntry = context.joinAll(path.posix.split(entry)); String assetPath = context.join(packageRoot, normalizedEntry); if (!_assetExistsAtPath(assetPath)) { ErrorCode errorCode = isDirectoryEntry ? PubspecWarningCode.ASSET_DIRECTORY_DOES_NOT_EXIST : PubspecWarningCode.ASSET_DOES_NOT_EXIST; _reportErrorForNode( reporter, entryValue, errorCode, [entryValue.value]); } } } else { _reportErrorForNode( reporter, entryValue, PubspecWarningCode.ASSET_NOT_STRING); } } else { _reportErrorForNode( reporter, entryValue, PubspecWarningCode.ASSET_NOT_STRING); } } } else if (assetsField != null) { _reportErrorForNode( reporter, assetsField, PubspecWarningCode.ASSET_FIELD_NOT_LIST); } if (flutterField.length > 1) { // TODO(brianwilkerson) Should we report an error if `flutter` contains // keys other than `assets`? } } else if (flutterField != null) { if (flutterField.value == null) { // allow an empty `flutter:` section; explicitly fail on a non-empty, // non-map one } else { _reportErrorForNode( reporter, flutterField, PubspecWarningCode.FLUTTER_FIELD_NOT_MAP); } } } /** * Validate the value of the required `name` field. */ void _validateName(ErrorReporter reporter, Map<dynamic, YamlNode> contents) { YamlNode nameField = contents[NAME_FIELD]; if (nameField == null) { reporter.reportErrorForOffset(PubspecWarningCode.MISSING_NAME, 0, 0); } else if (nameField is! YamlScalar || nameField.value is! String) { _reportErrorForNode( reporter, nameField, PubspecWarningCode.NAME_NOT_STRING); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/hint/sdk_constraint_verifier.dart
// Copyright (c) 2018, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.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/resolver/scope.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:pub_semver/pub_semver.dart'; /// A visitor that finds code that assumes a later version of the SDK than the /// minimum version required by the SDK constraints in `pubspec.yaml`. class SdkConstraintVerifier extends RecursiveAstVisitor<void> { /// The error reporter to be used to report errors. final ErrorReporter _errorReporter; /// The element representing the library containing the unit to be verified. final LibraryElement _containingLibrary; /// The typ provider used to access SDK types. final TypeProvider _typeProvider; /// The version constraint for the SDK. final VersionConstraint _versionConstraint; /// A cached flag indicating whether references to the constant-update-2018 /// features need to be checked. Use [checkConstantUpdate2018] to access this /// field. bool _checkConstantUpdate2018; /// A cached flag indicating whether uses of extension method features need to /// be checked. Use [checkExtensionMethods] to access this field. bool _checkExtensionMethods; /// A cached flag indicating whether references to Future and Stream need to /// be checked. Use [checkFutureAndStream] to access this field. bool _checkFutureAndStream; /// A cached flag indicating whether references to set literals need to /// be checked. Use [checkSetLiterals] to access this field. bool _checkSetLiterals; /// A flag indicating whether we are visiting code inside a set literal. Used /// to prevent over-reporting uses of set literals. bool _inSetLiteral = false; /// A cached flag indicating whether references to the ui-as-code features /// need to be checked. Use [checkUiAsCode] to access this field. bool _checkUiAsCode; /// A flag indicating whether we are visiting code inside one of the /// ui-as-code features. Used to prevent over-reporting uses of these /// features. bool _inUiAsCode = false; /// Initialize a newly created verifier to use the given [_errorReporter] to /// report errors. SdkConstraintVerifier(this._errorReporter, this._containingLibrary, this._typeProvider, this._versionConstraint); /// Return a range covering every version up to, but not including, 2.1.0. VersionRange get before_2_1_0 => new VersionRange(max: Version.parse('2.1.0'), includeMax: false); /// Return a range covering every version up to, but not including, 2.2.0. VersionRange get before_2_2_0 => new VersionRange(max: Version.parse('2.2.0'), includeMax: false); /// Return a range covering every version up to, but not including, 2.2.2. VersionRange get before_2_2_2 => new VersionRange(max: Version.parse('2.2.2'), includeMax: false); /// Return a range covering every version up to, but not including, 2.5.0. VersionRange get before_2_5_0 => new VersionRange(max: Version.parse('2.5.0'), includeMax: false); /// Return a range covering every version up to, but not including, 2.6.0. VersionRange get before_2_6_0 => new VersionRange(max: Version.parse('2.6.0'), includeMax: false); /// Return `true` if references to the constant-update-2018 features need to /// be checked. bool get checkConstantUpdate2018 => _checkConstantUpdate2018 ??= !before_2_5_0.intersect(_versionConstraint).isEmpty; /// Return `true` if references to the extension method features need to /// be checked. bool get checkExtensionMethods => _checkExtensionMethods ??= !before_2_6_0.intersect(_versionConstraint).isEmpty; /// Return `true` if references to Future and Stream need to be checked. bool get checkFutureAndStream => _checkFutureAndStream ??= !before_2_1_0.intersect(_versionConstraint).isEmpty; /// Return `true` if references to the non-nullable features need to be /// checked. // TODO(brianwilkerson) Implement this as a version check when a version has // been selected. bool get checkNnbd => true; /// Return `true` if references to set literals need to be checked. bool get checkSetLiterals => _checkSetLiterals ??= !before_2_2_0.intersect(_versionConstraint).isEmpty; /// Return `true` if references to the ui-as-code features (control flow and /// spread collections) need to be checked. bool get checkUiAsCode => _checkUiAsCode ??= !before_2_2_2.intersect(_versionConstraint).isEmpty; @override void visitAsExpression(AsExpression node) { if (checkConstantUpdate2018 && (node as AsExpressionImpl).inConstantContext) { _errorReporter.reportErrorForNode( HintCode.SDK_VERSION_AS_EXPRESSION_IN_CONST_CONTEXT, node); } super.visitAsExpression(node); } @override void visitBinaryExpression(BinaryExpression node) { if (checkConstantUpdate2018) { TokenType operatorType = node.operator.type; if (operatorType == TokenType.GT_GT_GT) { _errorReporter.reportErrorForToken( HintCode.SDK_VERSION_GT_GT_GT_OPERATOR, node.operator); } else if ((operatorType == TokenType.AMPERSAND || operatorType == TokenType.BAR || operatorType == TokenType.CARET) && (node as BinaryExpressionImpl).inConstantContext) { if (node.leftOperand.staticType.isDartCoreBool) { _errorReporter.reportErrorForToken( HintCode.SDK_VERSION_BOOL_OPERATOR_IN_CONST_CONTEXT, node.operator, [node.operator.lexeme]); } } else if (operatorType == TokenType.EQ_EQ && (node as BinaryExpressionImpl).inConstantContext) { bool primitive(Expression node) { DartType type = node.staticType; return type.isDartCoreBool || type.isDartCoreDouble || type.isDartCoreInt || type.isDartCoreNull || type.isDartCoreString; } if (!primitive(node.leftOperand) || !primitive(node.rightOperand)) { _errorReporter.reportErrorForToken( HintCode.SDK_VERSION_EQ_EQ_OPERATOR_IN_CONST_CONTEXT, node.operator); } } } super.visitBinaryExpression(node); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { if (checkExtensionMethods) { _errorReporter.reportErrorForToken( HintCode.SDK_VERSION_EXTENSION_METHODS, node.extensionKeyword); } super.visitExtensionDeclaration(node); } @override void visitExtensionOverride(ExtensionOverride node) { if (checkExtensionMethods) { _errorReporter.reportErrorForNode( HintCode.SDK_VERSION_EXTENSION_METHODS, node.extensionName); } super.visitExtensionOverride(node); } @override void visitForElement(ForElement node) { _validateUiAsCode(node); _validateUiAsCodeInConstContext(node); bool wasInUiAsCode = _inUiAsCode; _inUiAsCode = true; super.visitForElement(node); _inUiAsCode = wasInUiAsCode; } @override void visitHideCombinator(HideCombinator node) { // Don't flag references to either `Future` or `Stream` within a combinator. } @override void visitIfElement(IfElement node) { _validateUiAsCode(node); _validateUiAsCodeInConstContext(node); bool wasInUiAsCode = _inUiAsCode; _inUiAsCode = true; super.visitIfElement(node); _inUiAsCode = wasInUiAsCode; } @override void visitIsExpression(IsExpression node) { if (checkConstantUpdate2018 && (node as IsExpressionImpl).inConstantContext) { _errorReporter.reportErrorForNode( HintCode.SDK_VERSION_IS_EXPRESSION_IN_CONST_CONTEXT, node); } super.visitIsExpression(node); } @override void visitMethodDeclaration(MethodDeclaration node) { if (checkConstantUpdate2018 && node.isOperator && node.name.name == '>>>') { _errorReporter.reportErrorForNode( HintCode.SDK_VERSION_GT_GT_GT_OPERATOR, node.name); } super.visitMethodDeclaration(node); } @override void visitSetOrMapLiteral(SetOrMapLiteral node) { if (node.isSet && checkSetLiterals && !_inSetLiteral) { _errorReporter.reportErrorForNode(HintCode.SDK_VERSION_SET_LITERAL, node); } bool wasInSetLiteral = _inSetLiteral; _inSetLiteral = true; super.visitSetOrMapLiteral(node); _inSetLiteral = wasInSetLiteral; } @override void visitShowCombinator(ShowCombinator node) { // Don't flag references to either `Future` or `Stream` within a combinator. } @override void visitSimpleIdentifier(SimpleIdentifier node) { if (node.inDeclarationContext()) { return; } Element element = node.staticElement; if (checkFutureAndStream && (element == _typeProvider.futureElement || element == _typeProvider.streamElement)) { for (LibraryElement importedLibrary in _containingLibrary.importedLibraries) { if (!importedLibrary.isDartCore) { Namespace namespace = importedLibrary.exportNamespace; if (namespace != null && namespace.get(element.name) != null) { return; } } } _errorReporter.reportErrorForNode( HintCode.SDK_VERSION_ASYNC_EXPORTED_FROM_CORE, node, [element.name]); } else if (checkNnbd && element == _typeProvider.neverType.element) { _errorReporter.reportErrorForNode(HintCode.SDK_VERSION_NEVER, node); } } @override void visitSpreadElement(SpreadElement node) { _validateUiAsCode(node); _validateUiAsCodeInConstContext(node); bool wasInUiAsCode = _inUiAsCode; _inUiAsCode = true; super.visitSpreadElement(node); _inUiAsCode = wasInUiAsCode; } /// Given that the [node] is only valid when the ui-as-code feature is /// enabled, check that the code will not be executed with a version of the /// SDK that does not support the feature. void _validateUiAsCode(AstNode node) { if (checkUiAsCode && !_inUiAsCode) { _errorReporter.reportErrorForNode(HintCode.SDK_VERSION_UI_AS_CODE, node); } } /// Given that the [node] is only valid when the ui-as-code feature is /// enabled in a const context, check that the code will not be executed with /// a version of the SDK that does not support the feature. void _validateUiAsCodeInConstContext(AstNode node) { if (checkConstantUpdate2018 && !_inUiAsCode && node.thisOrAncestorOfType<TypedLiteral>().isConst) { _errorReporter.reportErrorForNode( HintCode.SDK_VERSION_UI_AS_CODE_IN_CONST_CONTEXT, node); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/hint/sdk_constraint_extractor.dart
// Copyright (c) 2018, 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:analyzer/file_system/file_system.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:yaml/yaml.dart'; /// A utility class used to extract the SDK version constraint from a /// `pubspec.yaml` file. class SdkConstraintExtractor { /// The file from which the constraint is to be extracted. final File pubspecFile; /// A flag indicating whether the [_constraintText], [_constraintOffset] and /// [_constraint] have been initialized. bool _initialized = false; /// The text of the constraint, or `null` if the range has not yet been /// computed or if there was an error when attempting to compute the range. String _constraintText; /// The offset of the constraint text, or `-1` if the offset is not known. int _constraintOffset = -1; /// The cached range of supported versions, or `null` if the range has not yet /// been computed or if there was an error when attempting to compute the /// range. VersionConstraint _constraint; /// Initialize a newly created extractor to extract the SDK version constraint /// from the given `pubspec.yaml` file. SdkConstraintExtractor(this.pubspecFile); /// Return the range of supported versions, or `null` if the range could not /// be computed. VersionConstraint constraint() { if (_constraint == null) { String text = constraintText(); if (text != null) { try { _constraint = new VersionConstraint.parse(text); } catch (e) { // Ignore this, leaving [_constraint] unset. } } } return _constraint; } /// Return the offset of the constraint text. int constraintOffset() { if (_constraintText == null) { _initializeTextAndOffset(); } return _constraintOffset; } /// Return the constraint text following "sdk:". String constraintText() { if (_constraintText == null) { _initializeTextAndOffset(); } return _constraintText; } /// Initialize both [_constraintText] and [_constraintOffset], or neither if /// there is an error or if the pubspec does not contain an sdk constraint. void _initializeTextAndOffset() { if (!_initialized) { _initialized = true; try { String fileContent = pubspecFile.readAsStringSync(); YamlDocument document = loadYamlDocument(fileContent); YamlNode contents = document.contents; if (contents is YamlMap) { YamlNode environment = contents.nodes['environment']; if (environment is YamlMap) { YamlNode sdk = environment.nodes['sdk']; if (sdk is YamlScalar) { _constraintText = sdk.value; _constraintOffset = sdk.span.start.offset; if (sdk.style == ScalarStyle.SINGLE_QUOTED || sdk.style == ScalarStyle.DOUBLE_QUOTED) { _constraintOffset++; } } } } } catch (e) { // Ignore this, leaving both fields unset. } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/manifest/manifest_validator.dart
// Copyright (c) 2019, 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:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:html/dom.dart'; import 'package:html/parser.dart' show parseFragment; import 'package:source_span/source_span.dart'; import 'manifest_values.dart'; import 'manifest_warning_code.dart'; class ManifestValidator { /** * The source representing the file being validated. */ final Source source; /** * Initialize a newly create validator to validate the content of the given * [source]. */ ManifestValidator(this.source); /* * Validate the [contents] of the Android Manifest file. */ List<AnalysisError> validate(String contents, bool checkManifest) { RecordingErrorListener recorder = new RecordingErrorListener(); ErrorReporter reporter = new ErrorReporter(recorder, source); if (checkManifest) { var document = parseFragment(contents, container: MANIFEST_TAG, generateSpans: true); var manifest = document.children.firstWhere( (element) => element.localName == MANIFEST_TAG, orElse: () => null); var features = manifest?.getElementsByTagName(USES_FEATURE_TAG) ?? []; var permissions = manifest?.getElementsByTagName(USES_PERMISSION_TAG) ?? []; var activities = _findActivityElements(manifest); _validateTouchScreenFeature(features, manifest, reporter); _validateFeatures(features, reporter); _validatePermissions(permissions, features, reporter); _validateActivities(activities, reporter); } return recorder.errors; } /* * Validate the presence/absence of the touchscreen feature tag. */ _validateTouchScreenFeature( List<Element> features, Element manifest, ErrorReporter reporter) { var feature = features.firstWhere( (element) => element.attributes[ANDROID_NAME] == HARDWARE_FEATURE_TOUCHSCREEN, orElse: () => null); if (feature != null) { if (!feature.attributes.containsKey(ANDROID_REQUIRED)) { _reportErrorForNode( reporter, feature, ANDROID_NAME, ManifestWarningCode.UNSUPPORTED_CHROME_OS_HARDWARE, [HARDWARE_FEATURE_TOUCHSCREEN]); } else if (feature.attributes[ANDROID_REQUIRED] == 'true') { _reportErrorForNode( reporter, feature, ANDROID_NAME, ManifestWarningCode.UNSUPPORTED_CHROME_OS_FEATURE, [HARDWARE_FEATURE_TOUCHSCREEN]); } } else { _reportErrorForNode( reporter, manifest, null, ManifestWarningCode.NO_TOUCHSCREEN_FEATURE); } } /* * Validate the `uses-feature` tags. */ _validateFeatures(List<Element> features, ErrorReporter reporter) { var unsupported = features .where((element) => UNSUPPORTED_HARDWARE_FEATURES .contains(element.attributes[ANDROID_NAME])) .toList(); unsupported.forEach((element) { if (!element.attributes.containsKey(ANDROID_REQUIRED)) { _reportErrorForNode( reporter, element, ANDROID_NAME, ManifestWarningCode.UNSUPPORTED_CHROME_OS_HARDWARE, [element.attributes[ANDROID_NAME]]); } else if (element.attributes[ANDROID_REQUIRED] == 'true') { _reportErrorForNode( reporter, element, ANDROID_NAME, ManifestWarningCode.UNSUPPORTED_CHROME_OS_FEATURE, [element.attributes[ANDROID_NAME]]); } }); } /* * Validate the `uses-permission` tags. */ _validatePermissions(List<Element> permissions, List<Element> features, ErrorReporter reporter) { permissions.forEach((permission) { if (permission.attributes[ANDROID_NAME] == ANDROID_PERMISSION_CAMERA) { if (!_hasFeatureCamera(features) || !_hasFeatureCameraAutoFocus(features)) { _reportErrorForNode(reporter, permission, ANDROID_NAME, ManifestWarningCode.CAMERA_PERMISSIONS_INCOMPATIBLE); } } else { var featureName = getImpliedUnsupportedHardware(permission.attributes[ANDROID_NAME]); if (featureName != null) { _reportErrorForNode( reporter, permission, ANDROID_NAME, ManifestWarningCode.PERMISSION_IMPLIES_UNSUPPORTED_HARDWARE, [featureName]); } } }); } /* * Validate the 'activity' tags. */ _validateActivities(List<Element> activites, ErrorReporter reporter) { activites.forEach((activity) { var attributes = activity.attributes; if (attributes.containsKey(ATTRIBUTE_SCREEN_ORIENTATION)) { if (UNSUPPORTED_ORIENTATIONS .contains(attributes[ATTRIBUTE_SCREEN_ORIENTATION])) { _reportErrorForNode(reporter, activity, ATTRIBUTE_SCREEN_ORIENTATION, ManifestWarningCode.SETTING_ORIENTATION_ON_ACTIVITY); } } if (attributes.containsKey(ATTRIBUTE_RESIZEABLE_ACTIVITY)) { if (attributes[ATTRIBUTE_RESIZEABLE_ACTIVITY] == 'false') { _reportErrorForNode(reporter, activity, ATTRIBUTE_RESIZEABLE_ACTIVITY, ManifestWarningCode.NON_RESIZABLE_ACTIVITY); } } }); } List<Element> _findActivityElements(Element manifest) { var applications = manifest?.getElementsByTagName(APPLICATION_TAG); var applicationElement = (applications != null && applications.isNotEmpty) ? applications.first : null; var activities = applicationElement?.getElementsByTagName(ACTIVITY_TAG) ?? []; return activities; } bool _hasFeatureCamera(List<Element> features) => features.any((f) => f.localName == HARDWARE_FEATURE_CAMERA); bool _hasFeatureCameraAutoFocus(List<Element> features) => features.any((f) => f.localName == HARDWARE_FEATURE_CAMERA_AUTOFOCUS); /** * Report an error for the given node. */ void _reportErrorForNode( ErrorReporter reporter, Node node, dynamic key, ErrorCode errorCode, [List<Object> arguments]) { FileSpan span = key == null ? node.sourceSpan : node.attributeValueSpans[key]; reporter.reportErrorForOffset( errorCode, span.start.offset, span.length, arguments); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/manifest/manifest_warning_code.dart
// Copyright (c) 2019, 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:analyzer/error/error.dart'; /** * The error codes used for warnings in analysis options files. The convention * for this class is for the name of the error code to indicate the problem that * caused the error to be generated and for the error message to explain what is * wrong and, when appropriate, how the problem can be corrected. */ class ManifestWarningCode extends ErrorCode { /** * A code indicating that a specified hardware feature is not supported on Chrome OS. */ static const ManifestWarningCode UNSUPPORTED_CHROME_OS_HARDWARE = const ManifestWarningCode('UNSUPPORTED_CHROME_OS_HARDWARE', "The feature {0} is not supported on Chrome OS, consider making it optional.", correction: "Try adding `android:required=\"false\"` for this " + "feature."); /** * A code indicating that a specified feature is not supported on Chrome OS. */ static const ManifestWarningCode UNSUPPORTED_CHROME_OS_FEATURE = const ManifestWarningCode('UNSUPPORTED_CHROME_OS_FEATURE', 'The feature {0} is not supported on Chrome OS, consider making it optional.', correction: "Try changing to `android:required=\"false\"` for this " + "feature."); /** * A code indicating that the touchscreen feature is not specified in the * manifest. */ static const ManifestWarningCode NO_TOUCHSCREEN_FEATURE = const ManifestWarningCode( 'NO_TOUCHSCREEN_FEATURE', "The default \"android.hardware.touchscreen\" needs to be optional for Chrome OS. ", correction: "Consider adding " + "<uses-feature android:name=\"android.hardware.touchscreen\" android:required=\"false\" />" + " to the manifest."); /** * A code indicating that a specified permission is not supported on Chrome OS. */ static const ManifestWarningCode PERMISSION_IMPLIES_UNSUPPORTED_HARDWARE = const ManifestWarningCode('PERMISSION_IMPLIES_UNSUPPORTED_HARDWARE', "Permission makes app incompatible for Chrome OS, consider adding optional {0} feature tag, ", correction: " Try adding `<uses-feature " + "android:name=\"{0}\" android:required=\"false\">`."); /** * A code indicating that the camera permissions is not supported on Chrome OS. */ static const ManifestWarningCode CAMERA_PERMISSIONS_INCOMPATIBLE = const ManifestWarningCode( 'CAMERA_PERMISSIONS_INCOMPATIBLE', "Camera permissions make app incompatible for Chrome OS, consider adding " + "optional features \"android.hardware.camera\" and \"android.hardware.camera.autofocus\".", correction: "Try adding `<uses-feature " + "android:name=\"android.hardware.camera\" android:required=\"false\">` " + "`<uses-feature " + "android:name=\"android.hardware.camera.autofocus\" android:required=\"false\">`."); /** * A code indicating that the activity is set to be non resizable. */ static const ManifestWarningCode NON_RESIZABLE_ACTIVITY = const ManifestWarningCode( 'NON_RESIZABLE_ACTIVITY', "The `<activity>` element should be allowed to be resized to allow " + "users to take advantage of the multi-window environment on Chrome OS", correction: "Consider declaring the corresponding " + "activity element with `resizableActivity=\"true\"` attribute."); /** * A code indicating that the activity is locked to an orientation. */ static const ManifestWarningCode SETTING_ORIENTATION_ON_ACTIVITY = const ManifestWarningCode( 'SETTING_ORIENTATION_ON_ACTIVITY', "The `<activity>` element should not be locked to any orientation so " + "that users can take advantage of the multi-window environments " + "and larger screens on Chrome OS", correction: "Consider declaring the corresponding activity element with" + " `screenOrientation=\"unspecified\"` or `\"fullSensor\"` attribute."); /** * Initialize a newly created warning code to have the given [name], [message] * and [correction]. */ const ManifestWarningCode(String name, String message, {String correction}) : super.temporary(name, message, correction: correction); @override ErrorSeverity get errorSeverity => ErrorSeverity.WARNING; @override ErrorType get type => ErrorType.STATIC_WARNING; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/manifest/manifest_values.dart
// Copyright (c) 2019, 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. /* * The attribute values to check for compatibility with Chrome OS. * */ const String MANIFEST_TAG = 'manifest'; const String USES_PERMISSION_TAG = 'uses-permission'; const String USES_FEATURE_TAG = 'uses-feature'; const String APPLICATION_TAG = 'application'; const String ACTIVITY_TAG = 'activity'; const String ANDROID_NAME = 'android:name'; const String ANDROID_REQUIRED = 'android:required'; // The parser does not maintain camelcase for attributes // Use 'resizeableactivity' instead of 'resizeableActivity' const String ATTRIBUTE_RESIZEABLE_ACTIVITY = 'android:resizeableactivity'; // Use 'screenorientation' instead of 'screenOrientation' const String ATTRIBUTE_SCREEN_ORIENTATION = 'android:screenorientation'; const String HARDWARE_FEATURE_CAMERA = 'android.hardware.camera'; const String HARDWARE_FEATURE_TOUCHSCREEN = 'android.hardware.touchscreen'; const String HARDWARE_FEATURE_CAMERA_AUTOFOCUS = 'android.hardware.camera.autofocus'; const String HARDWARE_FEATURE_TELEPHONY = 'android.hardware.telephony'; const String ANDROID_PERMISSION_CAMERA = 'android.permission.CAMERA'; const UNSUPPORTED_HARDWARE_FEATURES = <String>[ HARDWARE_FEATURE_CAMERA, HARDWARE_FEATURE_CAMERA_AUTOFOCUS, 'android.hardware.camera.capability.manual_post_processing', 'android.hardware.camera.capability.manual_sensor', 'android.hardware.camera.capability.raw', 'android.hardware.camera.flash', 'android.hardware.camera.level.full', 'android.hardware.consumerir', 'android.hardware.location.gps', 'android.hardware.nfc', 'android.hardware.nfc.hce', 'android.hardware.sensor.barometer', HARDWARE_FEATURE_TELEPHONY, 'android.hardware.telephony.cdma', 'android.hardware.telephony.gsm', 'android.hardware.type.automotive', 'android.hardware.type.television', 'android.hardware.usb.accessory', 'android.hardware.usb.host', // Partially-supported, only on some Chrome OS devices. 'android.hardware.sensor.accelerometer', 'android.hardware.sensor.compass', 'android.hardware.sensor.gyroscope', 'android.hardware.sensor.light', 'android.hardware.sensor.proximity', 'android.hardware.sensor.stepcounter', 'android.hardware.sensor.stepdetector', // Software features that are not supported 'android.software.app_widgets', 'android.software.device_admin', 'android.software.home_screen', 'android.software.input_methods', 'android.software.leanback', 'android.software.live_wallpaper', 'android.software.live_tv', 'android.software.managed_users', 'android.software.midi', 'android.software.sip', 'android.software.sip.voip', ]; String getImpliedUnsupportedHardware(String permission) { switch (permission) { case ANDROID_PERMISSION_CAMERA: return HARDWARE_FEATURE_CAMERA; case 'android.permission.CALL_PHONE': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.CALL_PRIVILEGED': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.MODIFY_PHONE_STATE': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.PROCESS_OUTGOING_CALLS': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.READ_SMS': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.RECEIVE_SMS': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.RECEIVE_MMS': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.RECEIVE_WAP_PUSH': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.SEND_SMS': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.WRITE_APN_SETTINGS': return HARDWARE_FEATURE_TELEPHONY; case 'android.permission.WRITE_SMS': return HARDWARE_FEATURE_TELEPHONY; default: return null; } } const UNSUPPORTED_ORIENTATIONS = <String>[ 'landscape', 'portrait', 'reverseLandscape', 'reversePortrait', 'sensorLandscape', 'sensorPortrait', 'userLandscape', 'userPortrait' ];
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/util.dart
// Copyright (c) 2015, 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 'dart:io'; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/ast/token.dart'; import 'package:analyzer/src/dart/scanner/reader.dart'; import 'package:analyzer/src/dart/scanner/scanner.dart'; import 'package:analyzer/src/generated/parser.dart' show Parser; import 'package:analyzer/src/string_source.dart' show StringSource; import 'package:path/path.dart' as path; final _identifier = new RegExp(r'^([(_|$)a-zA-Z]+([_a-zA-Z0-9])*)$'); final _lowerCamelCase = new RegExp(r'^(_)*[?$a-z][a-z0-9?$]*([A-Z][a-z0-9?$]*)*$'); final _lowerCaseUnderScore = new RegExp(r'^([a-z]+([_]?[a-z0-9]+)*)+$'); final _lowerCaseUnderScoreWithDots = new RegExp(r'^[a-z][_a-z0-9]*(\.[a-z][_a-z0-9]*)*$'); final _pubspec = new RegExp(r'^[_]?pubspec\.yaml$'); final _underscores = new RegExp(r'^[_]+$'); /// Create a library name prefix based on [libraryPath], [projectRoot] and /// current [packageName]. String createLibraryNamePrefix( {String libraryPath, String projectRoot, String packageName}) { // Use the posix context to canonicalize separators (`\`). var libraryDirectory = path.posix.dirname(libraryPath); var relativePath = path.posix.relative(libraryDirectory, from: projectRoot); // Drop 'lib/'. var segments = path.split(relativePath); if (segments[0] == 'lib') { relativePath = path.posix.joinAll(segments.sublist(1)); } // Replace separators. relativePath = relativePath.replaceAll('/', '.'); // Add separator if needed. if (relativePath.isNotEmpty) { relativePath = '.$relativePath'; } return '$packageName$relativePath'; } /// Returns `true` if this [fileName] is a Dart file. bool isDartFileName(String fileName) => fileName.endsWith('.dart'); /// Returns `true` if this [name] is a legal Dart identifier. @deprecated // Never intended for public use. bool isIdentifier(String name) => _identifier.hasMatch(name); /// Returns `true` of the given [name] is composed only of `_`s. @deprecated // Never intended for public use. bool isJustUnderscores(String name) => _underscores.hasMatch(name); /// Returns `true` if this [id] is `lowerCamelCase`. @deprecated // Never intended for public use. bool isLowerCamelCase(String id) => id.length == 1 && isUpperCase(id.codeUnitAt(0)) || id == '_' || _lowerCamelCase.hasMatch(id); /// Returns `true` if this [id] is `lower_camel_case_with_underscores`. @deprecated // Never intended for public use. bool isLowerCaseUnderScore(String id) => _lowerCaseUnderScore.hasMatch(id); /// Returns `true` if this [id] is `lower_camel_case_with_underscores_or.dots`. @deprecated // Never intended for public use. bool isLowerCaseUnderScoreWithDots(String id) => _lowerCaseUnderScoreWithDots.hasMatch(id); /// Returns `true` if this [fileName] is a Pubspec file. bool isPubspecFileName(String fileName) => _pubspec.hasMatch(fileName); /// Returns `true` if the given code unit [c] is upper case. @deprecated // Never intended for public use. bool isUpperCase(int c) => c >= 0x40 && c <= 0x5A; class Spelunker { final String path; final IOSink sink; FeatureSet featureSet; Spelunker(this.path, {IOSink sink, FeatureSet featureSet}) : this.sink = sink ?? stdout, featureSet = featureSet ?? FeatureSet.fromEnableFlags([]); void spelunk() { var contents = new File(path).readAsStringSync(); var errorListener = new _ErrorListener(); var reader = new CharSequenceReader(contents); var stringSource = new StringSource(contents, path); var scanner = new Scanner(stringSource, reader, errorListener) ..configureFeatures(featureSet); var startToken = scanner.tokenize(); errorListener.throwIfErrors(); var parser = new Parser(stringSource, errorListener, featureSet: featureSet); var node = parser.parseCompilationUnit(startToken); errorListener.throwIfErrors(); var visitor = new _SourceVisitor(sink); node.accept(visitor); } } class _ErrorListener implements AnalysisErrorListener { final errors = <AnalysisError>[]; @override void onError(AnalysisError error) { errors.add(error); } void throwIfErrors() { if (errors.isNotEmpty) { throw new Exception(errors); } } } class _SourceVisitor extends GeneralizingAstVisitor { int indent = 0; final IOSink sink; _SourceVisitor(this.sink); String asString(AstNode node) => typeInfo(node.runtimeType) + ' [${node.toString()}]'; List<CommentToken> getPrecedingComments(Token token) { var comments = <CommentToken>[]; var comment = token.precedingComments; while (comment is CommentToken) { comments.add(comment); comment = comment.next; } return comments; } String getTrailingComment(AstNode node) { var successor = node.endToken.next; if (successor != null) { var precedingComments = successor.precedingComments; if (precedingComments != null) { return precedingComments.toString(); } } return ''; } String typeInfo(Type type) => type.toString(); @override visitNode(AstNode node) { write(node); ++indent; node.visitChildren(this); --indent; return null; } write(AstNode node) { //EOL comments var comments = getPrecedingComments(node.beginToken); comments.forEach((c) => sink.writeln('${" " * indent}$c')); sink.writeln( '${" " * indent}${asString(node)} ${getTrailingComment(node)}'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/linter_visitor.dart
// Copyright (c) 2018, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/src/lint/linter.dart'; import 'package:analyzer/src/services/lint.dart'; /// The type of the function that handles exceptions in lints. typedef void LintRuleExceptionHandler( AstNode node, LintRule linter, dynamic exception, StackTrace stackTrace); /// The AST visitor that runs handlers for nodes from the [registry]. class LinterVisitor extends RecursiveAstVisitor<void> { final NodeLintRegistry registry; final LintRuleExceptionHandler exceptionHandler; LinterVisitor(this.registry, this.exceptionHandler); @override void visitAnnotation(Annotation node) { _runSubscriptions(node, registry._forAnnotation); super.visitAnnotation(node); } @override void visitAsExpression(AsExpression node) { _runSubscriptions(node, registry._forAsExpression); super.visitAsExpression(node); } @override void visitAssertInitializer(AssertInitializer node) { _runSubscriptions(node, registry._forAssertInitializer); super.visitAssertInitializer(node); } @override void visitAssertStatement(AssertStatement node) { _runSubscriptions(node, registry._forAssertStatement); super.visitAssertStatement(node); } @override void visitAssignmentExpression(AssignmentExpression node) { _runSubscriptions(node, registry._forAssignmentExpression); super.visitAssignmentExpression(node); } @override void visitAwaitExpression(AwaitExpression node) { _runSubscriptions(node, registry._forAwaitExpression); super.visitAwaitExpression(node); } @override void visitBinaryExpression(BinaryExpression node) { _runSubscriptions(node, registry._forBinaryExpression); super.visitBinaryExpression(node); } @override void visitBlock(Block node) { _runSubscriptions(node, registry._forBlock); super.visitBlock(node); } @override void visitBlockFunctionBody(BlockFunctionBody node) { _runSubscriptions(node, registry._forBlockFunctionBody); super.visitBlockFunctionBody(node); } @override void visitBooleanLiteral(BooleanLiteral node) { _runSubscriptions(node, registry._forBooleanLiteral); super.visitBooleanLiteral(node); } @override void visitBreakStatement(BreakStatement node) { _runSubscriptions(node, registry._forBreakStatement); super.visitBreakStatement(node); } @override void visitCascadeExpression(CascadeExpression node) { _runSubscriptions(node, registry._forCascadeExpression); super.visitCascadeExpression(node); } @override void visitCatchClause(CatchClause node) { _runSubscriptions(node, registry._forCatchClause); super.visitCatchClause(node); } @override void visitClassDeclaration(ClassDeclaration node) { _runSubscriptions(node, registry._forClassDeclaration); super.visitClassDeclaration(node); } @override void visitClassTypeAlias(ClassTypeAlias node) { _runSubscriptions(node, registry._forClassTypeAlias); super.visitClassTypeAlias(node); } @override void visitComment(Comment node) { _runSubscriptions(node, registry._forComment); super.visitComment(node); } @override void visitCommentReference(CommentReference node) { _runSubscriptions(node, registry._forCommentReference); super.visitCommentReference(node); } @override void visitCompilationUnit(CompilationUnit node) { _runSubscriptions(node, registry._forCompilationUnit); super.visitCompilationUnit(node); } @override void visitConditionalExpression(ConditionalExpression node) { _runSubscriptions(node, registry._forConditionalExpression); super.visitConditionalExpression(node); } @override void visitConfiguration(Configuration node) { _runSubscriptions(node, registry._forConfiguration); super.visitConfiguration(node); } @override void visitConstructorDeclaration(ConstructorDeclaration node) { _runSubscriptions(node, registry._forConstructorDeclaration); super.visitConstructorDeclaration(node); } @override void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { _runSubscriptions(node, registry._forConstructorFieldInitializer); super.visitConstructorFieldInitializer(node); } @override void visitConstructorName(ConstructorName node) { _runSubscriptions(node, registry._forConstructorName); super.visitConstructorName(node); } @override void visitContinueStatement(ContinueStatement node) { _runSubscriptions(node, registry._forContinueStatement); super.visitContinueStatement(node); } @override void visitDeclaredIdentifier(DeclaredIdentifier node) { _runSubscriptions(node, registry._forDeclaredIdentifier); super.visitDeclaredIdentifier(node); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { _runSubscriptions(node, registry._forDefaultFormalParameter); super.visitDefaultFormalParameter(node); } @override void visitDoStatement(DoStatement node) { _runSubscriptions(node, registry._forDoStatement); super.visitDoStatement(node); } @override void visitDottedName(DottedName node) { _runSubscriptions(node, registry._forDottedName); super.visitDottedName(node); } @override void visitDoubleLiteral(DoubleLiteral node) { _runSubscriptions(node, registry._forDoubleLiteral); super.visitDoubleLiteral(node); } @override void visitEmptyFunctionBody(EmptyFunctionBody node) { _runSubscriptions(node, registry._forEmptyFunctionBody); super.visitEmptyFunctionBody(node); } @override void visitEmptyStatement(EmptyStatement node) { _runSubscriptions(node, registry._forEmptyStatement); super.visitEmptyStatement(node); } @override void visitEnumConstantDeclaration(EnumConstantDeclaration node) { _runSubscriptions(node, registry._forEnumConstantDeclaration); super.visitEnumConstantDeclaration(node); } @override void visitEnumDeclaration(EnumDeclaration node) { _runSubscriptions(node, registry._forEnumDeclaration); super.visitEnumDeclaration(node); } @override void visitExportDirective(ExportDirective node) { _runSubscriptions(node, registry._forExportDirective); super.visitExportDirective(node); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { _runSubscriptions(node, registry._forExpressionFunctionBody); super.visitExpressionFunctionBody(node); } @override void visitExpressionStatement(ExpressionStatement node) { _runSubscriptions(node, registry._forExpressionStatement); super.visitExpressionStatement(node); } @override void visitExtendsClause(ExtendsClause node) { _runSubscriptions(node, registry._forExtendsClause); super.visitExtendsClause(node); } @override void visitExtensionDeclaration(ExtensionDeclaration node) { _runSubscriptions(node, registry._forExtensionDeclaration); super.visitExtensionDeclaration(node); } @override void visitExtensionOverride(ExtensionOverride node) { _runSubscriptions(node, registry._forExtensionOverride); super.visitExtensionOverride(node); } @override void visitFieldDeclaration(FieldDeclaration node) { _runSubscriptions(node, registry._forFieldDeclaration); super.visitFieldDeclaration(node); } @override void visitFieldFormalParameter(FieldFormalParameter node) { _runSubscriptions(node, registry._forFieldFormalParameter); super.visitFieldFormalParameter(node); } @override void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) { _runSubscriptions(node, registry._forForEachPartsWithDeclaration); super.visitForEachPartsWithDeclaration(node); } @override void visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) { _runSubscriptions(node, registry._forForEachPartsWithIdentifier); super.visitForEachPartsWithIdentifier(node); } @override void visitForElement(ForElement node) { _runSubscriptions(node, registry._forForElement); super.visitForElement(node); } @override void visitFormalParameterList(FormalParameterList node) { _runSubscriptions(node, registry._forFormalParameterList); super.visitFormalParameterList(node); } @override void visitForPartsWithDeclarations(ForPartsWithDeclarations node) { _runSubscriptions(node, registry._forForPartsWithDeclarations); super.visitForPartsWithDeclarations(node); } @override void visitForPartsWithExpression(ForPartsWithExpression node) { _runSubscriptions(node, registry._forForPartsWithExpression); super.visitForPartsWithExpression(node); } @override void visitForStatement(ForStatement node) { _runSubscriptions(node, registry._forForStatement); super.visitForStatement(node); } @override void visitFunctionDeclaration(FunctionDeclaration node) { _runSubscriptions(node, registry._forFunctionDeclaration); super.visitFunctionDeclaration(node); } @override void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) { _runSubscriptions(node, registry._forFunctionDeclarationStatement); super.visitFunctionDeclarationStatement(node); } @override void visitFunctionExpression(FunctionExpression node) { _runSubscriptions(node, registry._forFunctionExpression); super.visitFunctionExpression(node); } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { _runSubscriptions(node, registry._forFunctionExpressionInvocation); super.visitFunctionExpressionInvocation(node); } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { _runSubscriptions(node, registry._forFunctionTypeAlias); super.visitFunctionTypeAlias(node); } @override void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) { _runSubscriptions(node, registry._forFunctionTypedFormalParameter); super.visitFunctionTypedFormalParameter(node); } @override void visitGenericFunctionType(GenericFunctionType node) { _runSubscriptions(node, registry._forGenericFunctionType); super.visitGenericFunctionType(node); } @override void visitGenericTypeAlias(GenericTypeAlias node) { _runSubscriptions(node, registry._forGenericTypeAlias); super.visitGenericTypeAlias(node); } @override void visitHideCombinator(HideCombinator node) { _runSubscriptions(node, registry._forHideCombinator); super.visitHideCombinator(node); } @override void visitIfElement(IfElement node) { _runSubscriptions(node, registry._forIfElement); super.visitIfElement(node); } @override void visitIfStatement(IfStatement node) { _runSubscriptions(node, registry._forIfStatement); super.visitIfStatement(node); } @override void visitImplementsClause(ImplementsClause node) { _runSubscriptions(node, registry._forImplementsClause); super.visitImplementsClause(node); } @override void visitImportDirective(ImportDirective node) { _runSubscriptions(node, registry._forImportDirective); super.visitImportDirective(node); } @override void visitIndexExpression(IndexExpression node) { _runSubscriptions(node, registry._forIndexExpression); super.visitIndexExpression(node); } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { _runSubscriptions(node, registry._forInstanceCreationExpression); super.visitInstanceCreationExpression(node); } @override void visitIntegerLiteral(IntegerLiteral node) { _runSubscriptions(node, registry._forIntegerLiteral); super.visitIntegerLiteral(node); } @override void visitInterpolationExpression(InterpolationExpression node) { _runSubscriptions(node, registry._forInterpolationExpression); super.visitInterpolationExpression(node); } @override void visitInterpolationString(InterpolationString node) { _runSubscriptions(node, registry._forInterpolationString); super.visitInterpolationString(node); } @override void visitIsExpression(IsExpression node) { _runSubscriptions(node, registry._forIsExpression); super.visitIsExpression(node); } @override void visitLabel(Label node) { _runSubscriptions(node, registry._forLabel); super.visitLabel(node); } @override void visitLabeledStatement(LabeledStatement node) { _runSubscriptions(node, registry._forLabeledStatement); super.visitLabeledStatement(node); } @override void visitLibraryDirective(LibraryDirective node) { _runSubscriptions(node, registry._forLibraryDirective); super.visitLibraryDirective(node); } @override void visitLibraryIdentifier(LibraryIdentifier node) { _runSubscriptions(node, registry._forLibraryIdentifier); super.visitLibraryIdentifier(node); } @override void visitListLiteral(ListLiteral node) { _runSubscriptions(node, registry._forListLiteral); super.visitListLiteral(node); } @override void visitMapLiteralEntry(MapLiteralEntry node) { _runSubscriptions(node, registry._forMapLiteralEntry); super.visitMapLiteralEntry(node); } @override void visitMethodDeclaration(MethodDeclaration node) { _runSubscriptions(node, registry._forMethodDeclaration); super.visitMethodDeclaration(node); } @override void visitMethodInvocation(MethodInvocation node) { _runSubscriptions(node, registry._forMethodInvocation); super.visitMethodInvocation(node); } @override void visitMixinDeclaration(MixinDeclaration node) { _runSubscriptions(node, registry._forMixinDeclaration); super.visitMixinDeclaration(node); } @override void visitNamedExpression(NamedExpression node) { _runSubscriptions(node, registry._forNamedExpression); super.visitNamedExpression(node); } @override void visitNullLiteral(NullLiteral node) { _runSubscriptions(node, registry._forNullLiteral); super.visitNullLiteral(node); } @override void visitOnClause(OnClause node) { _runSubscriptions(node, registry._forOnClause); super.visitOnClause(node); } @override void visitParenthesizedExpression(ParenthesizedExpression node) { _runSubscriptions(node, registry._forParenthesizedExpression); super.visitParenthesizedExpression(node); } @override void visitPartDirective(PartDirective node) { _runSubscriptions(node, registry._forPartDirective); super.visitPartDirective(node); } @override void visitPartOfDirective(PartOfDirective node) { _runSubscriptions(node, registry._forPartOfDirective); super.visitPartOfDirective(node); } @override void visitPostfixExpression(PostfixExpression node) { _runSubscriptions(node, registry._forPostfixExpression); super.visitPostfixExpression(node); } @override void visitPrefixedIdentifier(PrefixedIdentifier node) { _runSubscriptions(node, registry._forPrefixedIdentifier); super.visitPrefixedIdentifier(node); } @override void visitPrefixExpression(PrefixExpression node) { _runSubscriptions(node, registry._forPrefixExpression); super.visitPrefixExpression(node); } @override void visitPropertyAccess(PropertyAccess node) { _runSubscriptions(node, registry._forPropertyAccess); super.visitPropertyAccess(node); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { _runSubscriptions(node, registry._forRedirectingConstructorInvocation); super.visitRedirectingConstructorInvocation(node); } @override void visitRethrowExpression(RethrowExpression node) { _runSubscriptions(node, registry._forRethrowExpression); super.visitRethrowExpression(node); } @override void visitReturnStatement(ReturnStatement node) { _runSubscriptions(node, registry._forReturnStatement); super.visitReturnStatement(node); } @override void visitSetOrMapLiteral(SetOrMapLiteral node) { _runSubscriptions(node, registry._forSetOrMapLiteral); super.visitSetOrMapLiteral(node); } @override void visitShowCombinator(ShowCombinator node) { _runSubscriptions(node, registry._forShowCombinator); super.visitShowCombinator(node); } @override void visitSimpleFormalParameter(SimpleFormalParameter node) { _runSubscriptions(node, registry._forSimpleFormalParameter); super.visitSimpleFormalParameter(node); } @override void visitSimpleIdentifier(SimpleIdentifier node) { _runSubscriptions(node, registry._forSimpleIdentifier); super.visitSimpleIdentifier(node); } @override void visitSimpleStringLiteral(SimpleStringLiteral node) { _runSubscriptions(node, registry._forSimpleStringLiteral); super.visitSimpleStringLiteral(node); } @override void visitSpreadElement(SpreadElement node) { _runSubscriptions(node, registry._forSpreadElement); super.visitSpreadElement(node); } @override void visitStringInterpolation(StringInterpolation node) { _runSubscriptions(node, registry._forStringInterpolation); super.visitStringInterpolation(node); } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { _runSubscriptions(node, registry._forSuperConstructorInvocation); super.visitSuperConstructorInvocation(node); } @override void visitSuperExpression(SuperExpression node) { _runSubscriptions(node, registry._forSuperExpression); super.visitSuperExpression(node); } @override void visitSwitchCase(SwitchCase node) { _runSubscriptions(node, registry._forSwitchCase); super.visitSwitchCase(node); } @override void visitSwitchDefault(SwitchDefault node) { _runSubscriptions(node, registry._forSwitchDefault); super.visitSwitchDefault(node); } @override void visitSwitchStatement(SwitchStatement node) { _runSubscriptions(node, registry._forSwitchStatement); super.visitSwitchStatement(node); } @override void visitSymbolLiteral(SymbolLiteral node) { _runSubscriptions(node, registry._forSymbolLiteral); super.visitSymbolLiteral(node); } @override void visitThisExpression(ThisExpression node) { _runSubscriptions(node, registry._forThisExpression); super.visitThisExpression(node); } @override void visitThrowExpression(ThrowExpression node) { _runSubscriptions(node, registry._forThrowExpression); super.visitThrowExpression(node); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { _runSubscriptions(node, registry._forTopLevelVariableDeclaration); super.visitTopLevelVariableDeclaration(node); } @override void visitTryStatement(TryStatement node) { _runSubscriptions(node, registry._forTryStatement); super.visitTryStatement(node); } @override void visitTypeArgumentList(TypeArgumentList node) { _runSubscriptions(node, registry._forTypeArgumentList); super.visitTypeArgumentList(node); } @override void visitTypeName(TypeName node) { _runSubscriptions(node, registry._forTypeName); super.visitTypeName(node); } @override void visitTypeParameter(TypeParameter node) { _runSubscriptions(node, registry._forTypeParameter); super.visitTypeParameter(node); } @override void visitTypeParameterList(TypeParameterList node) { _runSubscriptions(node, registry._forTypeParameterList); super.visitTypeParameterList(node); } @override void visitVariableDeclaration(VariableDeclaration node) { _runSubscriptions(node, registry._forVariableDeclaration); super.visitVariableDeclaration(node); } @override void visitVariableDeclarationList(VariableDeclarationList node) { _runSubscriptions(node, registry._forVariableDeclarationList); super.visitVariableDeclarationList(node); } @override void visitVariableDeclarationStatement(VariableDeclarationStatement node) { _runSubscriptions(node, registry._forVariableDeclarationStatement); super.visitVariableDeclarationStatement(node); } @override void visitWhileStatement(WhileStatement node) { _runSubscriptions(node, registry._forWhileStatement); super.visitWhileStatement(node); } @override void visitWithClause(WithClause node) { _runSubscriptions(node, registry._forWithClause); super.visitWithClause(node); } @override void visitYieldStatement(YieldStatement node) { _runSubscriptions(node, registry._forYieldStatement); super.visitYieldStatement(node); } void _runSubscriptions<T extends AstNode>( T node, List<_Subscription<T>> subscriptions) { for (int i = 0; i < subscriptions.length; i++) { var subscription = subscriptions[i]; var timer = subscription.timer; timer?.start(); try { node.accept(subscription.visitor); } catch (exception, stackTrace) { exceptionHandler(node, subscription.linter, exception, stackTrace); } timer?.stop(); } } } /// The container to register visitors for separate AST node types. class NodeLintRegistry { final bool enableTiming; final List<_Subscription<Annotation>> _forAnnotation = []; final List<_Subscription<AsExpression>> _forAsExpression = []; final List<_Subscription<AssertInitializer>> _forAssertInitializer = []; final List<_Subscription<AssertStatement>> _forAssertStatement = []; final List<_Subscription<AssignmentExpression>> _forAssignmentExpression = []; final List<_Subscription<AwaitExpression>> _forAwaitExpression = []; final List<_Subscription<BinaryExpression>> _forBinaryExpression = []; final List<_Subscription<Block>> _forBlock = []; final List<_Subscription<BlockFunctionBody>> _forBlockFunctionBody = []; final List<_Subscription<BooleanLiteral>> _forBooleanLiteral = []; final List<_Subscription<BreakStatement>> _forBreakStatement = []; final List<_Subscription<CascadeExpression>> _forCascadeExpression = []; final List<_Subscription<CatchClause>> _forCatchClause = []; final List<_Subscription<ClassDeclaration>> _forClassDeclaration = []; final List<_Subscription<ClassTypeAlias>> _forClassTypeAlias = []; final List<_Subscription<Comment>> _forComment = []; final List<_Subscription<CommentReference>> _forCommentReference = []; final List<_Subscription<CompilationUnit>> _forCompilationUnit = []; final List<_Subscription<ConditionalExpression>> _forConditionalExpression = []; final List<_Subscription<Configuration>> _forConfiguration = []; final List<_Subscription<ConstructorDeclaration>> _forConstructorDeclaration = []; final List<_Subscription<ConstructorFieldInitializer>> _forConstructorFieldInitializer = []; final List<_Subscription<ConstructorName>> _forConstructorName = []; final List<_Subscription<ContinueStatement>> _forContinueStatement = []; final List<_Subscription<DeclaredIdentifier>> _forDeclaredIdentifier = []; final List<_Subscription<DefaultFormalParameter>> _forDefaultFormalParameter = []; final List<_Subscription<DoStatement>> _forDoStatement = []; final List<_Subscription<DottedName>> _forDottedName = []; final List<_Subscription<DoubleLiteral>> _forDoubleLiteral = []; final List<_Subscription<EmptyFunctionBody>> _forEmptyFunctionBody = []; final List<_Subscription<EmptyStatement>> _forEmptyStatement = []; final List<_Subscription<EnumConstantDeclaration>> _forEnumConstantDeclaration = []; final List<_Subscription<EnumDeclaration>> _forEnumDeclaration = []; final List<_Subscription<ExportDirective>> _forExportDirective = []; final List<_Subscription<ExpressionFunctionBody>> _forExpressionFunctionBody = []; final List<_Subscription<ExpressionStatement>> _forExpressionStatement = []; final List<_Subscription<ExtendsClause>> _forExtendsClause = []; final List<_Subscription<ExtendsClause>> _forExtensionDeclaration = []; final List<_Subscription<ExtendsClause>> _forExtensionOverride = []; final List<_Subscription<FieldDeclaration>> _forFieldDeclaration = []; final List<_Subscription<FieldFormalParameter>> _forFieldFormalParameter = []; final List<_Subscription<ForEachPartsWithDeclaration>> _forForEachPartsWithDeclaration = []; final List<_Subscription<ForEachPartsWithIdentifier>> _forForEachPartsWithIdentifier = []; final List<_Subscription<ForElement>> _forForElement = []; final List<_Subscription<FormalParameterList>> _forFormalParameterList = []; final List<_Subscription<ForPartsWithDeclarations>> _forForPartsWithDeclarations = []; final List<_Subscription<ForPartsWithExpression>> _forForPartsWithExpression = []; final List<_Subscription<ForStatement>> _forForStatement = []; final List<_Subscription<FunctionDeclaration>> _forFunctionDeclaration = []; final List<_Subscription<FunctionDeclarationStatement>> _forFunctionDeclarationStatement = []; final List<_Subscription<FunctionExpression>> _forFunctionExpression = []; final List<_Subscription<FunctionExpressionInvocation>> _forFunctionExpressionInvocation = []; final List<_Subscription<FunctionTypeAlias>> _forFunctionTypeAlias = []; final List<_Subscription<FunctionTypedFormalParameter>> _forFunctionTypedFormalParameter = []; final List<_Subscription<GenericFunctionType>> _forGenericFunctionType = []; final List<_Subscription<GenericTypeAlias>> _forGenericTypeAlias = []; final List<_Subscription<HideCombinator>> _forHideCombinator = []; final List<_Subscription<IfElement>> _forIfElement = []; final List<_Subscription<IfStatement>> _forIfStatement = []; final List<_Subscription<ImplementsClause>> _forImplementsClause = []; final List<_Subscription<ImportDirective>> _forImportDirective = []; final List<_Subscription<IndexExpression>> _forIndexExpression = []; final List<_Subscription<InstanceCreationExpression>> _forInstanceCreationExpression = []; final List<_Subscription<IntegerLiteral>> _forIntegerLiteral = []; final List<_Subscription<InterpolationExpression>> _forInterpolationExpression = []; final List<_Subscription<InterpolationString>> _forInterpolationString = []; final List<_Subscription<IsExpression>> _forIsExpression = []; final List<_Subscription<Label>> _forLabel = []; final List<_Subscription<LabeledStatement>> _forLabeledStatement = []; final List<_Subscription<LibraryDirective>> _forLibraryDirective = []; final List<_Subscription<LibraryIdentifier>> _forLibraryIdentifier = []; final List<_Subscription<ListLiteral>> _forListLiteral = []; final List<_Subscription<MapLiteralEntry>> _forMapLiteralEntry = []; final List<_Subscription<MethodDeclaration>> _forMethodDeclaration = []; final List<_Subscription<MethodInvocation>> _forMethodInvocation = []; final List<_Subscription<MixinDeclaration>> _forMixinDeclaration = []; final List<_Subscription<NamedExpression>> _forNamedExpression = []; final List<_Subscription<NullLiteral>> _forNullLiteral = []; final List<_Subscription<OnClause>> _forOnClause = []; final List<_Subscription<ParenthesizedExpression>> _forParenthesizedExpression = []; final List<_Subscription<PartDirective>> _forPartDirective = []; final List<_Subscription<PartOfDirective>> _forPartOfDirective = []; final List<_Subscription<PostfixExpression>> _forPostfixExpression = []; final List<_Subscription<PrefixedIdentifier>> _forPrefixedIdentifier = []; final List<_Subscription<PrefixExpression>> _forPrefixExpression = []; final List<_Subscription<PropertyAccess>> _forPropertyAccess = []; final List<_Subscription<RedirectingConstructorInvocation>> _forRedirectingConstructorInvocation = []; final List<_Subscription<RethrowExpression>> _forRethrowExpression = []; final List<_Subscription<ReturnStatement>> _forReturnStatement = []; final List<_Subscription<SetOrMapLiteral>> _forSetOrMapLiteral = []; final List<_Subscription<ShowCombinator>> _forShowCombinator = []; final List<_Subscription<SimpleFormalParameter>> _forSimpleFormalParameter = []; final List<_Subscription<SimpleIdentifier>> _forSimpleIdentifier = []; final List<_Subscription<SimpleStringLiteral>> _forSimpleStringLiteral = []; final List<_Subscription<SpreadElement>> _forSpreadElement = []; final List<_Subscription<StringInterpolation>> _forStringInterpolation = []; final List<_Subscription<SuperConstructorInvocation>> _forSuperConstructorInvocation = []; final List<_Subscription<SuperExpression>> _forSuperExpression = []; final List<_Subscription<SwitchCase>> _forSwitchCase = []; final List<_Subscription<SwitchDefault>> _forSwitchDefault = []; final List<_Subscription<SwitchStatement>> _forSwitchStatement = []; final List<_Subscription<SymbolLiteral>> _forSymbolLiteral = []; final List<_Subscription<ThisExpression>> _forThisExpression = []; final List<_Subscription<ThrowExpression>> _forThrowExpression = []; final List<_Subscription<TopLevelVariableDeclaration>> _forTopLevelVariableDeclaration = []; final List<_Subscription<TryStatement>> _forTryStatement = []; final List<_Subscription<TypeArgumentList>> _forTypeArgumentList = []; final List<_Subscription<TypeName>> _forTypeName = []; final List<_Subscription<TypeParameter>> _forTypeParameter = []; final List<_Subscription<TypeParameterList>> _forTypeParameterList = []; final List<_Subscription<VariableDeclaration>> _forVariableDeclaration = []; final List<_Subscription<VariableDeclarationList>> _forVariableDeclarationList = []; final List<_Subscription<VariableDeclarationStatement>> _forVariableDeclarationStatement = []; final List<_Subscription<WhileStatement>> _forWhileStatement = []; final List<_Subscription<WithClause>> _forWithClause = []; final List<_Subscription<YieldStatement>> _forYieldStatement = []; NodeLintRegistry(this.enableTiming); void addAnnotation(LintRule linter, AstVisitor visitor) { _forAnnotation.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addAsExpression(LintRule linter, AstVisitor visitor) { _forAsExpression.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addAssertInitializer(LintRule linter, AstVisitor visitor) { _forAssertInitializer .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addAssertStatement(LintRule linter, AstVisitor visitor) { _forAssertStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addAssignmentExpression(LintRule linter, AstVisitor visitor) { _forAssignmentExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addAwaitExpression(LintRule linter, AstVisitor visitor) { _forAwaitExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addBinaryExpression(LintRule linter, AstVisitor visitor) { _forBinaryExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addBlock(LintRule linter, AstVisitor visitor) { _forBlock.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addBlockFunctionBody(LintRule linter, AstVisitor visitor) { _forBlockFunctionBody .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addBooleanLiteral(LintRule linter, AstVisitor visitor) { _forBooleanLiteral .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addBreakStatement(LintRule linter, AstVisitor visitor) { _forBreakStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addCascadeExpression(LintRule linter, AstVisitor visitor) { _forCascadeExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addCatchClause(LintRule linter, AstVisitor visitor) { _forCatchClause.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addClassDeclaration(LintRule linter, AstVisitor visitor) { _forClassDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addClassTypeAlias(LintRule linter, AstVisitor visitor) { _forClassTypeAlias .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addComment(LintRule linter, AstVisitor visitor) { _forComment.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addCommentReference(LintRule linter, AstVisitor visitor) { _forCommentReference .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addCompilationUnit(LintRule linter, AstVisitor visitor) { _forCompilationUnit .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addConditionalExpression(LintRule linter, AstVisitor visitor) { _forConditionalExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addConfiguration(LintRule linter, AstVisitor visitor) { _forConfiguration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addConstructorDeclaration(LintRule linter, AstVisitor visitor) { _forConstructorDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addConstructorFieldInitializer(LintRule linter, AstVisitor visitor) { _forConstructorFieldInitializer .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addConstructorName(LintRule linter, AstVisitor visitor) { _forConstructorName .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addContinueStatement(LintRule linter, AstVisitor visitor) { _forContinueStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addDeclaredIdentifier(LintRule linter, AstVisitor visitor) { _forDeclaredIdentifier .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addDefaultFormalParameter(LintRule linter, AstVisitor visitor) { _forDefaultFormalParameter .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addDoStatement(LintRule linter, AstVisitor visitor) { _forDoStatement.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addDottedName(LintRule linter, AstVisitor visitor) { _forDottedName.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addDoubleLiteral(LintRule linter, AstVisitor visitor) { _forDoubleLiteral .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addEmptyFunctionBody(LintRule linter, AstVisitor visitor) { _forEmptyFunctionBody .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addEmptyStatement(LintRule linter, AstVisitor visitor) { _forEmptyStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addEnumConstantDeclaration(LintRule linter, AstVisitor visitor) { _forEnumConstantDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addEnumDeclaration(LintRule linter, AstVisitor visitor) { _forEnumDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addExportDirective(LintRule linter, AstVisitor visitor) { _forExportDirective .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addExpressionFunctionBody(LintRule linter, AstVisitor visitor) { _forExpressionFunctionBody .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addExpressionStatement(LintRule linter, AstVisitor visitor) { _forExpressionStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addExtendsClause(LintRule linter, AstVisitor visitor) { _forExtendsClause .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addExtensionDeclaration(LintRule linter, AstVisitor visitor) { _forExtensionDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addExtensionOverride(LintRule linter, AstVisitor visitor) { _forExtensionOverride .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFieldDeclaration(LintRule linter, AstVisitor visitor) { _forFieldDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFieldFormalParameter(LintRule linter, AstVisitor visitor) { _forFieldFormalParameter .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addForEachPartsWithDeclaration(LintRule linter, AstVisitor visitor) { _forForEachPartsWithDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addForEachPartsWithIdentifier(LintRule linter, AstVisitor visitor) { _forForEachPartsWithIdentifier .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addForElement(LintRule linter, AstVisitor visitor) { _forForElement.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFormalParameterList(LintRule linter, AstVisitor visitor) { _forFormalParameterList .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addForPartsWithDeclarations(LintRule linter, AstVisitor visitor) { _forForPartsWithDeclarations .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addForPartsWithExpression(LintRule linter, AstVisitor visitor) { _forForPartsWithExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addForStatement(LintRule linter, AstVisitor visitor) { _forForStatement.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFunctionDeclaration(LintRule linter, AstVisitor visitor) { _forFunctionDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFunctionDeclarationStatement(LintRule linter, AstVisitor visitor) { _forFunctionDeclarationStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFunctionExpression(LintRule linter, AstVisitor visitor) { _forFunctionExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFunctionExpressionInvocation(LintRule linter, AstVisitor visitor) { _forFunctionExpressionInvocation .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFunctionTypeAlias(LintRule linter, AstVisitor visitor) { _forFunctionTypeAlias .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addFunctionTypedFormalParameter(LintRule linter, AstVisitor visitor) { _forFunctionTypedFormalParameter .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addGenericFunctionType(LintRule linter, AstVisitor visitor) { _forGenericFunctionType .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addGenericTypeAlias(LintRule linter, AstVisitor visitor) { _forGenericTypeAlias .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addHideCombinator(LintRule linter, AstVisitor visitor) { _forHideCombinator .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addIfElement(LintRule linter, AstVisitor visitor) { _forIfElement.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addIfStatement(LintRule linter, AstVisitor visitor) { _forIfStatement.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addImplementsClause(LintRule linter, AstVisitor visitor) { _forImplementsClause .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addImportDirective(LintRule linter, AstVisitor visitor) { _forImportDirective .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addIndexExpression(LintRule linter, AstVisitor visitor) { _forIndexExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addInstanceCreationExpression(LintRule linter, AstVisitor visitor) { _forInstanceCreationExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addIntegerLiteral(LintRule linter, AstVisitor visitor) { _forIntegerLiteral .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addInterpolationExpression(LintRule linter, AstVisitor visitor) { _forInterpolationExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addInterpolationString(LintRule linter, AstVisitor visitor) { _forInterpolationString .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addIsExpression(LintRule linter, AstVisitor visitor) { _forIsExpression.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addLabel(LintRule linter, AstVisitor visitor) { _forLabel.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addLabeledStatement(LintRule linter, AstVisitor visitor) { _forLabeledStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addLibraryDirective(LintRule linter, AstVisitor visitor) { _forLibraryDirective .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addLibraryIdentifier(LintRule linter, AstVisitor visitor) { _forLibraryIdentifier .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addListLiteral(LintRule linter, AstVisitor visitor) { _forListLiteral.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addMapLiteralEntry(LintRule linter, AstVisitor visitor) { _forMapLiteralEntry .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addMethodDeclaration(LintRule linter, AstVisitor visitor) { _forMethodDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addMethodInvocation(LintRule linter, AstVisitor visitor) { _forMethodInvocation .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addMixinDeclaration(LintRule linter, AstVisitor visitor) { _forMixinDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addNamedExpression(LintRule linter, AstVisitor visitor) { _forNamedExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addNullLiteral(LintRule linter, AstVisitor visitor) { _forNullLiteral.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addOnClause(LintRule linter, AstVisitor visitor) { _forOnClause.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addParenthesizedExpression(LintRule linter, AstVisitor visitor) { _forParenthesizedExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addPartDirective(LintRule linter, AstVisitor visitor) { _forPartDirective .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addPartOfDirective(LintRule linter, AstVisitor visitor) { _forPartOfDirective .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addPostfixExpression(LintRule linter, AstVisitor visitor) { _forPostfixExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addPrefixedIdentifier(LintRule linter, AstVisitor visitor) { _forPrefixedIdentifier .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addPrefixExpression(LintRule linter, AstVisitor visitor) { _forPrefixExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addPropertyAccess(LintRule linter, AstVisitor visitor) { _forPropertyAccess .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addRedirectingConstructorInvocation( LintRule linter, AstVisitor visitor) { _forRedirectingConstructorInvocation .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addRethrowExpression(LintRule linter, AstVisitor visitor) { _forRethrowExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addReturnStatement(LintRule linter, AstVisitor visitor) { _forReturnStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSetOrMapLiteral(LintRule linter, AstVisitor visitor) { _forSetOrMapLiteral .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addShowCombinator(LintRule linter, AstVisitor visitor) { _forShowCombinator .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSimpleFormalParameter(LintRule linter, AstVisitor visitor) { _forSimpleFormalParameter .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSimpleIdentifier(LintRule linter, AstVisitor visitor) { _forSimpleIdentifier .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSimpleStringLiteral(LintRule linter, AstVisitor visitor) { _forSimpleStringLiteral .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSpreadElement(LintRule linter, AstVisitor visitor) { _forSpreadElement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addStringInterpolation(LintRule linter, AstVisitor visitor) { _forStringInterpolation .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSuperConstructorInvocation(LintRule linter, AstVisitor visitor) { _forSuperConstructorInvocation .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSuperExpression(LintRule linter, AstVisitor visitor) { _forSuperExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSwitchCase(LintRule linter, AstVisitor visitor) { _forSwitchCase.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSwitchDefault(LintRule linter, AstVisitor visitor) { _forSwitchDefault .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSwitchStatement(LintRule linter, AstVisitor visitor) { _forSwitchStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addSymbolLiteral(LintRule linter, AstVisitor visitor) { _forSymbolLiteral .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addThisExpression(LintRule linter, AstVisitor visitor) { _forThisExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addThrowExpression(LintRule linter, AstVisitor visitor) { _forThrowExpression .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addTopLevelVariableDeclaration(LintRule linter, AstVisitor visitor) { _forTopLevelVariableDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addTryStatement(LintRule linter, AstVisitor visitor) { _forTryStatement.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addTypeArgumentList(LintRule linter, AstVisitor visitor) { _forTypeArgumentList .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addTypeName(LintRule linter, AstVisitor visitor) { _forTypeName.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addTypeParameter(LintRule linter, AstVisitor visitor) { _forTypeParameter .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addTypeParameterList(LintRule linter, AstVisitor visitor) { _forTypeParameterList .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addVariableDeclaration(LintRule linter, AstVisitor visitor) { _forVariableDeclaration .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addVariableDeclarationList(LintRule linter, AstVisitor visitor) { _forVariableDeclarationList .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addVariableDeclarationStatement(LintRule linter, AstVisitor visitor) { _forVariableDeclarationStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addWhileStatement(LintRule linter, AstVisitor visitor) { _forWhileStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } void addWithClause(LintRule linter, AstVisitor visitor) { _forWithClause.add(new _Subscription(linter, visitor, _getTimer(linter))); } void addYieldStatement(LintRule linter, AstVisitor visitor) { _forYieldStatement .add(new _Subscription(linter, visitor, _getTimer(linter))); } /// Get the timer associated with the given [linter]. Stopwatch _getTimer(LintRule linter) { if (enableTiming) { return lintRegistry.getTimer(linter); } else { return null; } } } /// A single subscription for a node type, by the specified [linter]. class _Subscription<T> { final LintRule linter; final AstVisitor visitor; final Stopwatch timer; _Subscription(this.linter, this.visitor, this.timer); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/analysis.dart
// Copyright (c) 2015, 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 'dart:async'; import 'dart:collection'; import 'dart:io' as io; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/file_system/file_system.dart' show File, Folder, ResourceProvider, ResourceUriResolver; import 'package:analyzer/file_system/physical_file_system.dart'; import 'package:analyzer/src/analysis_options/analysis_options_provider.dart'; import 'package:analyzer/src/context/builder.dart'; import 'package:analyzer/src/dart/analysis/byte_store.dart'; import 'package:analyzer/src/dart/analysis/driver.dart'; import 'package:analyzer/src/dart/analysis/file_state.dart'; import 'package:analyzer/src/dart/analysis/performance_logger.dart'; import 'package:analyzer/src/dart/sdk/sdk.dart'; import 'package:analyzer/src/file_system/file_system.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/source_io.dart'; import 'package:analyzer/src/lint/io.dart'; import 'package:analyzer/src/lint/linter.dart'; import 'package:analyzer/src/lint/project.dart'; import 'package:analyzer/src/lint/registry.dart'; import 'package:analyzer/src/services/lint.dart'; import 'package:analyzer/src/source/package_map_resolver.dart'; import 'package:analyzer/src/task/options.dart'; import 'package:analyzer/src/util/sdk.dart'; import 'package:package_config/packages.dart' show Packages; import 'package:package_config/packages_file.dart' as pkgfile show parse; import 'package:package_config/src/packages_impl.dart' show MapPackages; import 'package:path/path.dart' as p; import 'package:yaml/yaml.dart'; AnalysisOptionsProvider _optionsProvider = new AnalysisOptionsProvider(); Source createSource(Uri sourceUri) { return PhysicalResourceProvider.INSTANCE .getFile(sourceUri.toFilePath()) .createSource(sourceUri); } /// Print the given message and exit with the given [exitCode] void printAndFail(String message, {int exitCode: 15}) { print(message); io.exit(exitCode); } AnalysisOptions _buildAnalyzerOptions(LinterOptions options) { AnalysisOptionsImpl analysisOptions = new AnalysisOptionsImpl(); if (options.analysisOptions != null) { YamlMap map = _optionsProvider.getOptionsFromString(options.analysisOptions); applyToAnalysisOptions(analysisOptions, map); } analysisOptions.hint = false; analysisOptions.lint = options.enableLints; analysisOptions.generateSdkErrors = options.showSdkWarnings; analysisOptions.enableTiming = options.enableTiming; analysisOptions.lintRules = options.enabledLints?.toList(growable: false); return analysisOptions; } class DriverOptions { /// The maximum number of sources for which AST structures should be kept /// in the cache. The default is 512. int cacheSize = 512; /// The path to the dart SDK. String dartSdkPath; /// Whether to show lint warnings. bool enableLints = true; /// Whether to gather timing data during analysis. bool enableTiming = false; /// The path to a `.packages` configuration file String packageConfigPath; /// The path to the package root. String packageRootPath; /// Whether to show SDK warnings. bool showSdkWarnings = false; /// Whether to use Dart's Strong Mode analyzer. bool strongMode = true; /// The mock SDK (to speed up testing) or `null` to use the actual SDK. DartSdk mockSdk; /// Return `true` is the parser is able to parse asserts in the initializer /// list of a constructor. @deprecated bool get enableAssertInitializer => true; /// Set whether the parser is able to parse asserts in the initializer list of /// a constructor to match [enable]. @deprecated void set enableAssertInitializer(bool enable) { // Ignored because the option is now always enabled. } /// Whether to use Dart 2.0 features. @deprecated bool get previewDart2 => true; @deprecated void set previewDart2(bool value) {} } class LintDriver { /// The sources which have been analyzed so far. This is used to avoid /// analyzing a source more than once, and to compute the total number of /// sources analyzed for statistics. Set<Source> _sourcesAnalyzed = new HashSet<Source>(); final LinterOptions options; LintDriver(this.options); /// Return the number of sources that have been analyzed so far. int get numSourcesAnalyzed => _sourcesAnalyzed.length; List<UriResolver> get resolvers { // TODO(brianwilkerson) Use the context builder to compute all of the resolvers. ResourceProvider resourceProvider = PhysicalResourceProvider.INSTANCE; ContextBuilder builder = new ContextBuilder(resourceProvider, null, null); DartSdk sdk = options.mockSdk ?? new FolderBasedDartSdk(resourceProvider, resourceProvider.getFolder(sdkDir), options.strongMode); List<UriResolver> resolvers = [new DartUriResolver(sdk)]; if (options.packageRootPath != null) { // TODO(brianwilkerson) After 0.30.0 is published, clean up the following. try { // Try to use the post 0.30.0 API. (builder as dynamic).builderOptions.defaultPackagesDirectoryPath = options.packageRootPath; } catch (_) { // If that fails, fall back to the pre 0.30.0 API. (builder as dynamic).defaultPackagesDirectoryPath = options.packageRootPath; } Map<String, List<Folder>> packageMap = builder.convertPackagesToMap(builder.createPackageMap(null)); resolvers.add(new PackageMapUriResolver(resourceProvider, packageMap)); } // File URI resolver must come last so that files inside "/lib" are // are analyzed via "package:" URI's. resolvers.add(new ResourceUriResolver(resourceProvider)); return resolvers; } ResourceProvider get resourceProvider => options.resourceProvider; String get sdkDir { // In case no SDK has been specified, fall back to inferring it. return options.dartSdkPath ?? getSdkPath(); } Future<List<AnalysisErrorInfo>> analyze(Iterable<io.File> files) async { // TODO(brianwilkerson) Determine whether this await is necessary. await null; AnalysisEngine.instance.logger = new StdLogger(); SourceFactory sourceFactory = new SourceFactory(resolvers, _getPackageConfig()); PerformanceLog log = new PerformanceLog(null); AnalysisDriverScheduler scheduler = new AnalysisDriverScheduler(log); AnalysisDriver analysisDriver = new AnalysisDriver( scheduler, log, resourceProvider, new MemoryByteStore(), new FileContentOverlay(), null, sourceFactory, _buildAnalyzerOptions(options)); analysisDriver.results.listen((_) {}); analysisDriver.exceptions.listen((_) {}); scheduler.start(); List<Source> sources = []; for (io.File file in files) { File sourceFile = resourceProvider.getFile(p.normalize(file.absolute.path)); Source source = sourceFile.createSource(); Uri uri = sourceFactory.restoreUri(source); if (uri != null) { // Ensure that we analyze the file using its canonical URI (e.g. if // it's in "/lib", analyze it using a "package:" URI). source = sourceFile.createSource(uri); } sources.add(source); analysisDriver.addFile(source.fullName); } DartProject project = await DartProject.create(analysisDriver, sources); Registry.ruleRegistry.forEach((lint) { if (lint is ProjectVisitor) { (lint as ProjectVisitor).visit(project); } }); List<AnalysisErrorInfo> errors = []; for (Source source in sources) { ErrorsResult errorsResult = await analysisDriver.getErrors(source.fullName); errors.add(new AnalysisErrorInfoImpl( errorsResult.errors, errorsResult.lineInfo)); _sourcesAnalyzed.add(source); } return errors; } void registerLinters(AnalysisContext context) { if (options.enableLints) { setLints(context, options.enabledLints?.toList(growable: false)); } } Packages _getPackageConfig() { if (options.packageConfigPath != null) { String packageConfigPath = options.packageConfigPath; Uri fileUri = new Uri.file(packageConfigPath); try { io.File configFile = new io.File.fromUri(fileUri).absolute; List<int> bytes = configFile.readAsBytesSync(); Map<String, Uri> map = pkgfile.parse(bytes, configFile.uri); return new MapPackages(map); } catch (e) { printAndFail( 'Unable to read package config data from $packageConfigPath: $e'); } } return null; } } /// Prints logging information comments to the [outSink] and error messages to /// [errorSink]. class StdLogger extends Logger { @override void logError(String message, [exception]) { errorSink.writeln(message); if (exception != null) { errorSink.writeln(exception); } } @override void logInformation(String message, [exception]) { outSink.writeln(message); if (exception != null) { outSink.writeln(exception); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/config.dart
// Copyright (c) 2015, 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:analyzer/src/util/yaml.dart'; import 'package:yaml/yaml.dart'; /** * Parse the given map into a lint config. */ LintConfig parseConfig(YamlMap optionsMap) { if (optionsMap != null) { var options = getValue(optionsMap, 'linter'); // Quick check of basic contract. if (options is YamlMap) { return new LintConfig.parseMap(options); } } return null; } /** * Process the given option [fileContents] and produce a corresponding * [LintConfig]. */ LintConfig processAnalysisOptionsFile(String fileContents, {String fileUrl}) { var yaml = loadYamlNode(fileContents, sourceUrl: fileUrl); if (yaml is YamlMap) { return parseConfig(yaml); } return null; } /** * The configuration of lint rules within an analysis options file. */ abstract class LintConfig { factory LintConfig.parse(String source, {String sourceUrl}) => new _LintConfig().._parse(source, sourceUrl: sourceUrl); factory LintConfig.parseMap(YamlMap map) => new _LintConfig().._parseYaml(map); List<String> get fileExcludes; List<String> get fileIncludes; List<RuleConfig> get ruleConfigs; } /** * The configuration of a single lint rule within an analysis options file. */ abstract class RuleConfig { Map<String, dynamic> args = <String, dynamic>{}; String get group; String get name; // Provisional bool disables(String ruleName) => ruleName == name && args['enabled'] == false; bool enables(String ruleName) => ruleName == name && args['enabled'] == true; } class _LintConfig implements LintConfig { @override final fileIncludes = <String>[]; @override final fileExcludes = <String>[]; @override final ruleConfigs = <RuleConfig>[]; void addAsListOrString(value, List<String> list) { if (value is List) { value.forEach((v) => list.add(v)); } else if (value is String) { list.add(value); } } bool asBool(scalar) { Object value = scalar is YamlScalar ? scalar.value : scalar; if (value is bool) { return value; } if (value is String) { if (value == 'true') { return true; } if (value == 'false') { return false; } } return null; } String asString(scalar) { Object value = scalar is YamlScalar ? scalar.value : scalar; if (value is String) { return value; } return null; } Map<String, dynamic> parseArgs(args) { bool enabled = asBool(args); if (enabled != null) { return {'enabled': enabled}; } return null; } void _parse(String src, {String sourceUrl}) { var yaml = loadYamlNode(src, sourceUrl: sourceUrl); if (yaml is YamlMap) { _parseYaml(yaml); } } void _parseYaml(YamlMap yaml) { yaml.nodes.forEach((k, v) { if (k is! YamlScalar) { return; } YamlScalar key = k; switch (key.toString()) { case 'files': if (v is YamlMap) { addAsListOrString(v['include'], fileIncludes); addAsListOrString(v['exclude'], fileExcludes); } break; case 'rules': // - unnecessary_getters // - camel_case_types if (v is YamlList) { v.nodes.forEach((rule) { var config = new _RuleConfig(); config.name = asString(rule); config.args = {'enabled': true}; ruleConfigs.add(config); }); } // style_guide: {unnecessary_getters: false, camel_case_types: true} if (v is YamlMap) { v.nodes.forEach((key, value) { //{unnecessary_getters: false} if (asBool(value) != null) { var config = new _RuleConfig(); config.name = asString(key); config.args = {'enabled': asBool(value)}; ruleConfigs.add(config); } // style_guide: {unnecessary_getters: false, camel_case_types: true} if (value is YamlMap) { value.nodes.forEach((rule, args) { // TODO: verify format // unnecessary_getters: false var config = new _RuleConfig(); config.group = asString(key); config.name = asString(rule); config.args = parseArgs(args); ruleConfigs.add(config); }); } }); } break; } }); } } class _RuleConfig extends RuleConfig { @override String group; @override String name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/linter.dart
// Copyright (c) 2015, 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 'dart:async'; import 'dart:io'; import 'package:analyzer/dart/analysis/declared_variables.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/file_system/file_system.dart' as file_system; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/ast/token.dart'; import 'package:analyzer/src/dart/constant/potentially_constant.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/inheritance_manager3.dart'; import 'package:analyzer/src/dart/element/member.dart'; import 'package:analyzer/src/dart/error/lint_codes.dart'; import 'package:analyzer/src/generated/engine.dart' show AnalysisErrorInfo, AnalysisErrorInfoImpl, AnalysisOptions, Logger; import 'package:analyzer/src/generated/java_engine.dart' show CaughtException; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/source.dart' show LineInfo; import 'package:analyzer/src/generated/source_io.dart'; import 'package:analyzer/src/lint/analysis.dart'; import 'package:analyzer/src/lint/config.dart'; import 'package:analyzer/src/lint/io.dart'; import 'package:analyzer/src/lint/linter_visitor.dart' show NodeLintRegistry; import 'package:analyzer/src/lint/project.dart'; import 'package:analyzer/src/lint/pub.dart'; import 'package:analyzer/src/lint/registry.dart'; import 'package:analyzer/src/services/lint.dart' show Linter; import 'package:glob/glob.dart'; import 'package:path/path.dart' as p; export 'package:analyzer/src/lint/linter_visitor.dart' show NodeLintRegistry; typedef Printer(String msg); /// Describes a String in valid camel case format. @deprecated // Never intended for public use. class CamelCaseString { static final _camelCaseMatcher = new RegExp(r'[A-Z][a-z]*'); static final _camelCaseTester = new RegExp(r'^([_$]*)([A-Z?$]+[a-z0-9]*)+$'); final String value; CamelCaseString(this.value) { if (!isCamelCase(value)) { throw new ArgumentError('$value is not CamelCase'); } } String get humanized => _humanize(value); @override String toString() => value; static bool isCamelCase(String name) => _camelCaseTester.hasMatch(name); static String _humanize(String camelCase) => _camelCaseMatcher.allMatches(camelCase).map((m) => m.group(0)).join(' '); } /// Dart source linter. class DartLinter implements AnalysisErrorListener { final errors = <AnalysisError>[]; final LinterOptions options; final Reporter reporter; /// The total number of sources that were analyzed. Only valid after /// [lintFiles] has been called. int numSourcesAnalyzed; /// Creates a new linter. DartLinter(this.options, {this.reporter: const PrintingReporter()}); Future<Iterable<AnalysisErrorInfo>> lintFiles(List<File> files) async { // TODO(brianwilkerson) Determine whether this await is necessary. await null; List<AnalysisErrorInfo> errors = []; final lintDriver = new LintDriver(options); errors.addAll(await lintDriver.analyze(files.where((f) => isDartFile(f)))); numSourcesAnalyzed = lintDriver.numSourcesAnalyzed; files.where((f) => isPubspecFile(f)).forEach((p) { numSourcesAnalyzed++; return errors.addAll(_lintPubspecFile(p)); }); return errors; } Iterable<AnalysisErrorInfo> lintPubspecSource( {String contents, String sourcePath}) { var results = <AnalysisErrorInfo>[]; Uri sourceUrl = sourcePath == null ? null : p.toUri(sourcePath); var spec = new Pubspec.parse(contents, sourceUrl: sourceUrl); for (Linter lint in options.enabledLints) { if (lint is LintRule) { LintRule rule = lint; var visitor = rule.getPubspecVisitor(); if (visitor != null) { // Analyzer sets reporters; if this file is not being analyzed, // we need to set one ourselves. (Needless to say, when pubspec // processing gets pushed down, this hack can go away.) if (rule.reporter == null && sourceUrl != null) { var source = createSource(sourceUrl); rule.reporter = new ErrorReporter(this, source); } try { spec.accept(visitor); } on Exception catch (e) { reporter.exception(new LinterException(e.toString())); } if (rule._locationInfo != null && rule._locationInfo.isNotEmpty) { results.addAll(rule._locationInfo); rule._locationInfo.clear(); } } } } return results; } @override onError(AnalysisError error) => errors.add(error); Iterable<AnalysisErrorInfo> _lintPubspecFile(File sourceFile) => lintPubspecSource( contents: sourceFile.readAsStringSync(), sourcePath: options.resourceProvider.pathContext .normalize(sourceFile.absolute.path)); } class FileGlobFilter extends LintFilter { Iterable<Glob> includes; Iterable<Glob> excludes; FileGlobFilter([Iterable<String> includeGlobs, Iterable<String> excludeGlobs]) : includes = includeGlobs.map((glob) => new Glob(glob)), excludes = excludeGlobs.map((glob) => new Glob(glob)); @override bool filter(AnalysisError lint) { // TODO specify order return excludes.any((glob) => glob.matches(lint.source.fullName)) && !includes.any((glob) => glob.matches(lint.source.fullName)); } } class Group implements Comparable<Group> { /// Defined rule groups. static const Group errors = const Group._('errors', description: 'Possible coding errors.'); static const Group pub = const Group._('pub', description: 'Pub-related rules.', link: const Hyperlink('See the <strong>Pubspec Format</strong>', 'https://www.dartlang.org/tools/pub/pubspec.html')); static const Group style = const Group._('style', description: 'Matters of style, largely derived from the official Dart Style Guide.', link: const Hyperlink('See the <strong>Style Guide</strong>', 'https://www.dartlang.org/articles/style-guide/')); /// List of builtin groups in presentation order. static const Iterable<Group> builtin = const [errors, style, pub]; final String name; final bool custom; final String description; final Hyperlink link; factory Group(String name, {String description: '', Hyperlink link}) { var n = name.toLowerCase(); return builtin.firstWhere((g) => g.name == n, orElse: () => new Group._(name, custom: true, description: description, link: link)); } const Group._(this.name, {this.custom: false, this.description, this.link}); @override int compareTo(Group other) => name.compareTo(other.name); } class Hyperlink { final String label; final String href; final bool bold; const Hyperlink(this.label, this.href, {this.bold: false}); String get html => '<a href="$href">${_emph(label)}</a>'; String _emph(msg) => bold ? '<strong>$msg</strong>' : msg; } /// Provides access to information needed by lint rules that is not available /// from AST nodes or the element model. abstract class LinterContext { List<LinterContextUnit> get allUnits; AnalysisOptions get analysisOptions; LinterContextUnit get currentUnit; DeclaredVariables get declaredVariables; InheritanceManager3 get inheritanceManager; TypeProvider get typeProvider; TypeSystem get typeSystem; /// Return `true` if it would be valid for the given instance creation /// [expression] to have a keyword of `const`. /// /// The [expression] is expected to be a node within one of the compilation /// units in [allUnits]. /// /// Note that this method can cause constant evaluation to occur, which can be /// computationally expensive. bool canBeConst(InstanceCreationExpression expression); /// Return `true` if it would be valid for the given constructor declaration /// [node] to have a keyword of `const`. /// /// The [node] is expected to be a node within one of the compilation /// units in [allUnits]. /// /// Note that this method can cause constant evaluation to occur, which can be /// computationally expensive. bool canBeConstConstructor(ConstructorDeclaration node); } /// Implementation of [LinterContext] class LinterContextImpl implements LinterContext { @override final List<LinterContextUnit> allUnits; @override final AnalysisOptions analysisOptions; @override final LinterContextUnit currentUnit; @override final DeclaredVariables declaredVariables; @override final TypeProvider typeProvider; @override final TypeSystem typeSystem; @override final InheritanceManager3 inheritanceManager; LinterContextImpl( this.allUnits, this.currentUnit, this.declaredVariables, this.typeProvider, this.typeSystem, this.inheritanceManager, this.analysisOptions, ); @override bool canBeConst(InstanceCreationExpression expression) { // // Verify that the invoked constructor is a const constructor. // ConstructorElement element = expression.staticElement; if (element == null || !element.isConst) { return false; } // Ensure that dependencies (e.g. default parameter values) are computed. var implElement = element; if (element is ConstructorMember) { implElement = element.baseElement; } (implElement as ConstructorElementImpl).computeConstantDependencies(); // // Verify that the evaluation of the constructor would not produce an // exception. // Token oldKeyword = expression.keyword; try { expression.keyword = new KeywordToken(Keyword.CONST, expression.offset); return !_hasConstantVerifierError(expression); } finally { expression.keyword = oldKeyword; } } @override bool canBeConstConstructor(ConstructorDeclaration node) { ConstructorElement element = node.declaredElement; ClassElement classElement = element.enclosingElement; if (classElement.hasNonFinalField) return false; var oldKeyword = node.constKeyword; try { temporaryConstConstructorElements[element] = true; node.constKeyword = KeywordToken(Keyword.CONST, node.offset); return !_hasConstantVerifierError(node); } finally { temporaryConstConstructorElements[element] = null; node.constKeyword = oldKeyword; } } /// Return `true` if [ConstantVerifier] reports an error for the [node]. bool _hasConstantVerifierError(AstNode node) { var unitElement = currentUnit.unit.declaredElement; var libraryElement = unitElement.library; var listener = ConstantAnalysisErrorListener(); var errorReporter = ErrorReporter(listener, unitElement.source); node.accept( ConstantVerifier( errorReporter, libraryElement, typeProvider, declaredVariables, featureSet: currentUnit.unit.featureSet, ), ); return listener.hasConstError; } } class LinterContextUnit { final String content; final CompilationUnit unit; LinterContextUnit(this.content, this.unit); } /// Thrown when an error occurs in linting. class LinterException implements Exception { /// A message describing the error. final String message; /// Creates a new LinterException with an optional error [message]. const LinterException([this.message]); @override String toString() => message == null ? "LinterException" : "LinterException: $message"; } /// Linter options. class LinterOptions extends DriverOptions { Iterable<LintRule> enabledLints; String analysisOptions; LintFilter filter; file_system.ResourceProvider resourceProvider; // todo (pq): consider migrating to named params (but note Linter dep). LinterOptions([this.enabledLints, this.analysisOptions]) { enabledLints ??= Registry.ruleRegistry; } void configure(LintConfig config) { enabledLints = Registry.ruleRegistry.where((LintRule rule) => !config.ruleConfigs.any((rc) => rc.disables(rule.name))); filter = new FileGlobFilter(config.fileIncludes, config.fileExcludes); } } /// Filtered lints are omitted from linter output. abstract class LintFilter { bool filter(AnalysisError lint); } /// Describes a lint rule. abstract class LintRule extends Linter implements Comparable<LintRule> { /// Description (in markdown format) suitable for display in a detailed lint /// description. final String details; /// Short description suitable for display in console output. final String description; /// Lint group (for example, 'style'). final Group group; /// Lint maturity (stable|experimental). final Maturity maturity; /// Lint name. @override final String name; /// Until pubspec analysis is pushed into the analyzer proper, we need to /// do some extra book-keeping to keep track of details that will help us /// constitute AnalysisErrorInfos. final List<AnalysisErrorInfo> _locationInfo = <AnalysisErrorInfo>[]; LintRule( {this.name, this.group, this.description, this.details, this.maturity: Maturity.stable}); LintCode get lintCode => new _LintCode(name, description); @override int compareTo(LintRule other) { var g = group.compareTo(other.group); if (g != 0) { return g; } return name.compareTo(other.name); } /// Return a visitor to be passed to provide access to Dart project context /// and to perform project-level analyses. ProjectVisitor getProjectVisitor() => null; /// Return a visitor to be passed to pubspecs to perform lint /// analysis. /// Lint errors are reported via this [Linter]'s error [reporter]. PubspecVisitor getPubspecVisitor() => null; @override AstVisitor getVisitor() => null; void reportLint(AstNode node, {List<Object> arguments: const [], ErrorCode errorCode, bool ignoreSyntheticNodes: true}) { if (node != null && (!node.isSynthetic || !ignoreSyntheticNodes)) { reporter.reportErrorForNode(errorCode ?? lintCode, node, arguments); } } void reportLintForToken(Token token, {List<Object> arguments: const [], ErrorCode errorCode, bool ignoreSyntheticTokens: true}) { if (token != null && (!token.isSynthetic || !ignoreSyntheticTokens)) { reporter.reportErrorForToken(errorCode ?? lintCode, token, arguments); } } void reportPubLint(PSNode node) { Source source = createSource(node.span.sourceUrl); // Cache error and location info for creating AnalysisErrorInfos AnalysisError error = new AnalysisError( source, node.span.start.offset, node.span.length, lintCode); LineInfo lineInfo = new LineInfo.fromContent(source.contents.data); _locationInfo.add(new AnalysisErrorInfoImpl([error], lineInfo)); // Then do the reporting reporter?.reportError(error); } } class Maturity implements Comparable<Maturity> { static const Maturity stable = const Maturity._('stable', ordinal: 0); static const Maturity experimental = const Maturity._('experimental', ordinal: 1); static const Maturity deprecated = const Maturity._('deprecated', ordinal: 2); final String name; final int ordinal; factory Maturity(String name, {int ordinal}) { switch (name.toLowerCase()) { case 'stable': return stable; case 'experimental': return experimental; case 'deprecated': return deprecated; default: return new Maturity._(name, ordinal: ordinal); } } const Maturity._(this.name, {this.ordinal}); @override int compareTo(Maturity other) => this.ordinal - other.ordinal; } /// [LintRule]s that implement this interface want to process only some types /// of AST nodes, and will register their processors in the registry. abstract class NodeLintRule { /// This method is invoked to let the [LintRule] register node processors /// in the given [registry]. /// /// The node processors may use the provided [context] to access information /// that is not available from the AST nodes or their associated elements. void registerNodeProcessors(NodeLintRegistry registry, LinterContext context); } /// [LintRule]s that implement this interface want to process only some types /// of AST nodes, and will register their processors in the registry. /// /// This class exists solely to allow a smoother transition from analyzer /// version 0.33.*. It will be removed in a future analyzer release, so please /// use [NodeLintRule] instead. @deprecated abstract class NodeLintRuleWithContext extends NodeLintRule {} class PrintingReporter implements Reporter, Logger { final Printer _print; const PrintingReporter([this._print = print]); @override void exception(LinterException exception) { _print('EXCEPTION: $exception'); } @override void logError(String message, [CaughtException exception]) { _print('ERROR: $message'); } @override void logInformation(String message, [CaughtException exception]) { _print('INFO: $message'); } @override void warn(String message) { _print('WARN: $message'); } } abstract class Reporter { void exception(LinterException exception); void warn(String message); } /// Linter implementation. class SourceLinter implements DartLinter, AnalysisErrorListener { @override final errors = <AnalysisError>[]; @override final LinterOptions options; @override final Reporter reporter; @override int numSourcesAnalyzed; SourceLinter(this.options, {this.reporter: const PrintingReporter()}); @override Future<Iterable<AnalysisErrorInfo>> lintFiles(List<File> files) async { // TODO(brianwilkerson) Determine whether this await is necessary. await null; List<AnalysisErrorInfo> errors = []; final lintDriver = new LintDriver(options); errors.addAll(await lintDriver.analyze(files.where((f) => isDartFile(f)))); numSourcesAnalyzed = lintDriver.numSourcesAnalyzed; files.where((f) => isPubspecFile(f)).forEach((p) { numSourcesAnalyzed++; return errors.addAll(_lintPubspecFile(p)); }); return errors; } @override Iterable<AnalysisErrorInfo> lintPubspecSource( {String contents, String sourcePath}) { var results = <AnalysisErrorInfo>[]; Uri sourceUrl = sourcePath == null ? null : p.toUri(sourcePath); var spec = new Pubspec.parse(contents, sourceUrl: sourceUrl); for (Linter lint in options.enabledLints) { if (lint is LintRule) { LintRule rule = lint; var visitor = rule.getPubspecVisitor(); if (visitor != null) { // Analyzer sets reporters; if this file is not being analyzed, // we need to set one ourselves. (Needless to say, when pubspec // processing gets pushed down, this hack can go away.) if (rule.reporter == null && sourceUrl != null) { var source = createSource(sourceUrl); rule.reporter = new ErrorReporter(this, source); } try { spec.accept(visitor); } on Exception catch (e) { reporter.exception(new LinterException(e.toString())); } if (rule._locationInfo != null && rule._locationInfo.isNotEmpty) { results.addAll(rule._locationInfo); rule._locationInfo.clear(); } } } } return results; } @override onError(AnalysisError error) => errors.add(error); @override Iterable<AnalysisErrorInfo> _lintPubspecFile(File sourceFile) => lintPubspecSource( contents: sourceFile.readAsStringSync(), sourcePath: sourceFile.path); } class _LintCode extends LintCode { static final registry = <String, LintCode>{}; factory _LintCode(String name, String message) => registry.putIfAbsent( name + message, () => new _LintCode._(name, message)); _LintCode._(String name, String message) : super(name, message); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/pub.dart
// Copyright (c) 2015, 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 'dart:collection'; import 'package:source_span/source_span.dart'; import 'package:yaml/yaml.dart'; PSEntry _findEntry(YamlMap map, String key) { PSEntry entry; map.nodes.forEach((k, v) { if (k is YamlScalar && key == k.toString()) { entry = _processScalar(k, v); } }); return entry; } PSDependencyList _processDependencies(YamlScalar key, YamlNode v) { if (v is! YamlMap) { return null; } YamlMap depsMap = v; _PSDependencyList deps = new _PSDependencyList(new _PSNode(key)); depsMap.nodes.forEach((k, v) => deps.add(new _PSDependency(k, v))); return deps; } PSGitRepo _processGitRepo(YamlScalar key, YamlNode v) { if (v is! YamlMap) { return null; } YamlMap hostMap = v; // url: git://github.com/munificent/kittens.git // ref: some-branch _PSGitRepo repo = new _PSGitRepo(); repo.token = new _PSNode(key); repo.ref = _findEntry(hostMap, 'ref'); repo.url = _findEntry(hostMap, 'url'); return repo; } PSHost _processHost(YamlScalar key, YamlNode v) { if (v is! YamlMap) { return null; } YamlMap hostMap = v; // name: transmogrify // url: http://your-package-server.com _PSHost host = new _PSHost(); host.token = new _PSNode(key); host.name = _findEntry(hostMap, 'name'); host.url = _findEntry(hostMap, 'url'); return host; } PSNodeList _processList(YamlScalar key, YamlNode v) { if (v is! YamlList) { return null; } YamlList nodeList = v; return new _PSNodeList( new _PSNode(key), nodeList.nodes.map((n) => new _PSNode(n))); } PSEntry _processScalar(YamlScalar key, YamlNode value) { if (value is! YamlScalar) { return null; //WARN? } return new PSEntry(new _PSNode(key), new _PSNode(value)); } abstract class PSDependency { PSGitRepo get git; PSHost get host; PSNode get name; PSEntry get version; } abstract class PSDependencyList with IterableMixin<PSDependency> {} class PSEntry { final PSNode key; final PSNode value; PSEntry(this.key, this.value); @override String toString() => '${key != null ? (key.toString() + ': ') : ''}$value'; } abstract class PSGitRepo { PSEntry get ref; PSNode get token; PSEntry get url; } abstract class PSHost { PSEntry get name; PSNode get token; PSEntry get url; } abstract class PSNode { SourceSpan get span; String get text; } abstract class PSNodeList with IterableMixin<PSNode> { @override Iterator<PSNode> get iterator; PSNode get token; } abstract class Pubspec { factory Pubspec.parse(String source, {Uri sourceUrl}) => new _Pubspec(source, sourceUrl: sourceUrl); PSEntry get author; PSNodeList get authors; PSDependencyList get dependencies; PSDependencyList get dependencyOverrides; PSEntry get description; PSDependencyList get devDependencies; PSEntry get documentation; PSEntry get homepage; PSEntry get name; PSEntry get version; accept(PubspecVisitor visitor); } abstract class PubspecVisitor<T> { T visitPackageAuthor(PSEntry author) => null; T visitPackageAuthors(PSNodeList authors) => null; T visitPackageDependencies(PSDependencyList dependencies) => null; T visitPackageDependency(PSDependency dependency) => null; T visitPackageDependencyOverride(PSDependency dependency) => null; T visitPackageDependencyOverrides(PSDependencyList dependencies) => null; T visitPackageDescription(PSEntry description) => null; T visitPackageDevDependencies(PSDependencyList dependencies) => null; T visitPackageDevDependency(PSDependency dependency) => null; T visitPackageDocumentation(PSEntry documentation) => null; T visitPackageHomepage(PSEntry homepage) => null; T visitPackageName(PSEntry name) => null; T visitPackageVersion(PSEntry version) => null; } class _PSDependency extends PSDependency { @override PSNode name; @override PSEntry version; @override PSHost host; @override PSGitRepo git; factory _PSDependency(dynamic k, YamlNode v) { if (k is! YamlScalar) { return null; } YamlScalar key = k; _PSDependency dep = new _PSDependency._(); dep.name = new _PSNode(key); if (v is YamlScalar) { // Simple version dep.version = new PSEntry(null, new _PSNode(v)); } else if (v is YamlMap) { // hosted: // name: transmogrify // url: http://your-package-server.com // version: '>=0.4.0 <1.0.0' YamlMap details = v; details.nodes.forEach((k, v) { if (k is! YamlScalar) { return; } YamlScalar key = k; switch (key.toString()) { case 'version': dep.version = _processScalar(key, v); break; case 'hosted': dep.host = _processHost(key, v); break; case 'git': dep.git = _processGitRepo(key, v); break; } }); } return dep; } _PSDependency._(); @override String toString() { var sb = new StringBuffer(); if (name != null) { sb.write('$name:'); } var versionInfo = ''; if (version != null) { if (version.key == null) { versionInfo = ' $version'; } else { versionInfo = '\n $version'; } } sb.writeln(versionInfo); if (host != null) { sb.writeln(host); } if (git != null) { sb.writeln(git); } return sb.toString(); } } class _PSDependencyList extends PSDependencyList { final dependencies = <PSDependency>[]; final PSNode token; _PSDependencyList(this.token); @override Iterator<PSDependency> get iterator => dependencies.iterator; add(PSDependency dependency) { if (dependency != null) { dependencies.add(dependency); } } @override String toString() => '$token\n${dependencies.join(' ')}'; } class _PSGitRepo implements PSGitRepo { @override PSNode token; @override PSEntry ref; @override PSEntry url; @override String toString() => ''' $token: $url $ref'''; } class _PSHost implements PSHost { @override PSNode token; @override PSEntry name; @override PSEntry url; @override String toString() => ''' $token: $name $url'''; } class _PSNode implements PSNode { @override final String text; @override final SourceSpan span; _PSNode(YamlNode node) : text = node.value?.toString(), span = node.span; @override String toString() => '$text'; } class _PSNodeList extends PSNodeList { @override final PSNode token; final Iterable<PSNode> nodes; _PSNodeList(this.token, this.nodes); @override Iterator<PSNode> get iterator => nodes.iterator; @override String toString() => ''' $token: - ${nodes.join('\n - ')}'''; } class _Pubspec implements Pubspec { @override PSEntry author; @override PSNodeList authors; @override PSEntry description; @override PSEntry documentation; @override PSEntry homepage; @override PSEntry name; @override PSEntry version; @override PSDependencyList dependencies; @override PSDependencyList devDependencies; @override PSDependencyList dependencyOverrides; _Pubspec(String src, {Uri sourceUrl}) { try { _parse(src, sourceUrl: sourceUrl); } on Exception { // ignore } } @override void accept(PubspecVisitor visitor) { if (author != null) { visitor.visitPackageAuthor(author); } if (authors != null) { visitor.visitPackageAuthors(authors); } if (description != null) { visitor.visitPackageDescription(description); } if (documentation != null) { visitor.visitPackageDocumentation(documentation); } if (homepage != null) { visitor.visitPackageHomepage(homepage); } if (name != null) { visitor.visitPackageName(name); } if (version != null) { visitor.visitPackageVersion(version); } if (dependencies != null) { visitor.visitPackageDependencies(dependencies); dependencies.forEach(visitor.visitPackageDependency); } if (devDependencies != null) { visitor.visitPackageDevDependencies(devDependencies); devDependencies.forEach(visitor.visitPackageDevDependency); } if (dependencyOverrides != null) { visitor.visitPackageDependencyOverrides(dependencyOverrides); dependencyOverrides.forEach(visitor.visitPackageDependencyOverride); } } @override String toString() { var sb = new _StringBuilder(); sb.writelin(name); sb.writelin(version); sb.writelin(author); sb.writelin(authors); sb.writelin(description); sb.writelin(homepage); sb.writelin(dependencies); sb.writelin(devDependencies); sb.writelin(dependencyOverrides); return sb.toString(); } _parse(String src, {Uri sourceUrl}) { var yaml = loadYamlNode(src, sourceUrl: sourceUrl); if (yaml is! YamlMap) { return; } YamlMap yamlMap = yaml; yamlMap.nodes.forEach((k, v) { if (k is! YamlScalar) { return; } YamlScalar key = k; switch (key.toString()) { case 'author': author = _processScalar(key, v); break; case 'authors': authors = _processList(key, v); break; case 'homepage': homepage = _processScalar(key, v); break; case 'name': name = _processScalar(key, v); break; case 'description': description = _processScalar(key, v); break; case 'documentation': documentation = _processScalar(key, v); break; case 'dependencies': dependencies = _processDependencies(key, v); break; case 'dev_dependencies': devDependencies = _processDependencies(key, v); break; case 'dependency_overrides': dependencyOverrides = _processDependencies(key, v); break; case 'version': version = _processScalar(key, v); break; } }); } } class _StringBuilder { StringBuffer buffer = new StringBuffer(); @override String toString() => buffer.toString(); writelin(Object value) { if (value != null) { buffer.writeln(value); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/io.dart
// Copyright (c) 2015, 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 'dart:io'; import 'package:analyzer/src/lint/util.dart'; import 'package:glob/glob.dart'; import 'package:path/path.dart' as p; final dartMatcher = new Glob('**.dart'); /// Shared IO sink for standard error reporting. /// Visible for testing IOSink errorSink = stderr; /// Shared IO sink for standard out reporting. /// Visible for testing IOSink outSink = stdout; /// Collect all lintable files, recursively, under this [path] root, ignoring /// links. Iterable<File> collectFiles(String path) { List<File> files = []; var file = new File(path); if (file.existsSync()) { files.add(file); } else { var directory = new Directory(path); if (directory.existsSync()) { for (var entry in directory.listSync(recursive: true, followLinks: false)) { var relative = p.relative(entry.path, from: directory.path); if (isLintable(entry) && !isInHiddenDir(relative)) { files.add(entry); } } } } return files; } /// Returns `true` if this [entry] is a Dart file. bool isDartFile(FileSystemEntity entry) => isDartFileName(entry.path); /// Returns `true` if this relative path is a hidden directory. bool isInHiddenDir(String relative) => p.split(relative).any((part) => part.startsWith(".")); /// Returns `true` if this relative path is a hidden directory. bool isLintable(FileSystemEntity file) => file is File && (isDartFile(file) || isPubspecFile(file)); /// Returns `true` if this [entry] is a pubspec file. bool isPubspecFile(FileSystemEntity entry) => isPubspecFileName(p.basename(entry.path)); /// Synchronously read the contents of the file at the given [path] as a string. String readFile(String path) => new File(path).readAsStringSync();
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/options_rule_validator.dart
// 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 'dart:collection'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/analysis_options/error/option_codes.dart'; import 'package:analyzer/src/lint/linter.dart'; import 'package:analyzer/src/lint/registry.dart'; import 'package:analyzer/src/plugin/options.dart'; import 'package:analyzer/src/util/yaml.dart'; import 'package:yaml/yaml.dart'; /** * A hint code indicating reference to a deprecated lint. * * Parameters: * 0: the rule name */ const AnalysisOptionsHintCode DEPRECATED_LINT_HINT = const AnalysisOptionsHintCode('DEPRECATED_LINT_HINT', "'{0}' is a deprecated lint rule and should not be used"); /** * Duplicate rules. * * Parameters: * 0: the rule name */ const AnalysisOptionsHintCode DUPLICATE_RULE_HINT = const AnalysisOptionsHintCode( 'DUPLICATE_RULE', "The rule {0} is already specified and doesn't need to be specified again.", correction: "Try removing all but one specification of the rule."); /** * An error code indicating an undefined lint rule. * * Parameters: * 0: the rule name */ const AnalysisOptionsWarningCode UNDEFINED_LINT_WARNING = const AnalysisOptionsWarningCode( 'UNDEFINED_LINT_WARNING', "'{0}' is not a recognized lint rule"); /** * Rule provider. */ typedef LintRuleProvider = Iterable<LintRule> Function(); /** * Validates `linter` rule configurations. */ class LinterRuleOptionsValidator extends OptionsValidator { static const linter = 'linter'; static const rulesKey = 'rules'; final LintRuleProvider ruleProvider; LinterRuleOptionsValidator({LintRuleProvider provider}) : ruleProvider = provider ?? (() => Registry.ruleRegistry.rules); LintRule getRegisteredLint(Object value) => ruleProvider() .firstWhere((rule) => rule.name == value, orElse: () => null); @override List<AnalysisError> validate(ErrorReporter reporter, YamlMap options) { List<AnalysisError> errors = <AnalysisError>[]; var node = getValue(options, linter); if (node is YamlMap) { var rules = getValue(node, rulesKey); validateRules(rules, reporter); } return errors; } validateRules(YamlNode rules, ErrorReporter reporter) { if (rules is YamlList) { Set<String> seenRules = new HashSet<String>(); rules.nodes.forEach((YamlNode ruleNode) { Object value = ruleNode.value; if (value != null) { LintRule rule = getRegisteredLint(value); if (rule == null) { reporter.reportErrorForSpan( UNDEFINED_LINT_WARNING, ruleNode.span, [value]); } else if (!seenRules.add(rule.name)) { reporter.reportErrorForSpan( DUPLICATE_RULE_HINT, ruleNode.span, [value]); } else if (rule.maturity == Maturity.deprecated) { reporter.reportErrorForSpan( DEPRECATED_LINT_HINT, ruleNode.span, [value]); } } }); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/project.dart
// Copyright (c) 2015, 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 'dart:async'; import 'dart:io'; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/src/dart/analysis/driver.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/lint/io.dart'; import 'package:analyzer/src/lint/pub.dart'; import 'package:path/path.dart' as p; Pubspec _findAndParsePubspec(Directory root) { if (root.existsSync()) { File pubspec = root .listSync(followLinks: false) .firstWhere((f) => isPubspecFile(f), orElse: () => null); if (pubspec != null) { return new Pubspec.parse(pubspec.readAsStringSync(), sourceUrl: p.toUri(pubspec.path)); } } return null; } /// A semantic representation of a Dart project. /// /// Projects provide a semantic model of a Dart project based on the /// [pub package layout conventions](https://www.dartlang.org/tools/pub/package-layout.html). /// This model allows clients to traverse project contents in a convenient and /// standardized way, access global information (such as whether elements are /// in the "public API") and resources that have special meanings in the /// context of pub package layout conventions. class DartProject { _ApiModel _apiModel; String _name; Pubspec _pubspec; /// Project root. final Directory root; /// Create a Dart project for the corresponding [driver] and [sources]. /// If a [dir] is unspecified the current working directory will be /// used. /// /// Note: clients should call [create] which performs API model initialization. DartProject._(AnalysisDriver driver, List<Source> sources, {Directory dir}) : root = dir ?? Directory.current { _pubspec = _findAndParsePubspec(root); _apiModel = new _ApiModel(driver, sources, root); } /// The project's name. /// /// Project names correspond to the package name as specified in the project's /// [pubspec]. The pubspec is found relative to the project [root]. If no /// pubspec can be found, the name defaults to the project root basename. String get name => _name ??= _calculateName(); /// The project's pubspec. Pubspec get pubspec => _pubspec; /// Returns `true` if the given element is part of this project's public API. /// /// Public API elements are defined as all elements that are in the packages's /// `lib` directory, *less* those in `lib/src` (which are treated as private /// *implementation files*), plus elements having been explicitly exported /// via an `export` directive. bool isApi(Element element) => _apiModel.contains(element); String _calculateName() { if (pubspec != null) { var nameEntry = pubspec.name; if (nameEntry != null) { return nameEntry.value.text; } } return p.basename(root.path); } /// Create an initialized Dart project for the corresponding [driver] and /// [sources]. /// If a [dir] is unspecified the current working directory will be /// used. static Future<DartProject> create(AnalysisDriver driver, List<Source> sources, {Directory dir}) async { // TODO(brianwilkerson) Determine whether this await is necessary. await null; DartProject project = new DartProject._(driver, sources, dir: dir); await project._apiModel._calculate(); return project; } } /// An object that can be used to visit Dart project structure. abstract class ProjectVisitor<T> { T visit(DartProject project) => null; } /// Captures the project's API as defined by pub package layout standards. class _ApiModel { final AnalysisDriver driver; final List<Source> sources; final Directory root; final Set<LibraryElement> elements = new Set(); _ApiModel(this.driver, this.sources, this.root) { _calculate(); } /// Return `true` if this element is part of the public API for this package. bool contains(Element element) { while (element != null) { if (!element.isPrivate && elements.contains(element)) { return true; } element = element.enclosingElement; } return false; } _calculate() async { // TODO(brianwilkerson) Determine whether this await is necessary. await null; if (sources == null || sources.isEmpty) { return; } String libDir = root.path + '/lib'; String libSrcDir = libDir + '/src'; for (Source source in sources) { String path = source.uri.path; if (path.startsWith(libDir) && !path.startsWith(libSrcDir)) { ResolvedUnitResult result = await driver.getResult(source.fullName); LibraryElement library = result.libraryElement; NamespaceBuilder namespaceBuilder = new NamespaceBuilder(); Namespace exports = namespaceBuilder.createExportNamespaceForLibrary(library); Namespace public = namespaceBuilder.createPublicNamespaceForLibrary(library); elements.addAll(exports.definedNames.values); elements.addAll(public.definedNames.values); } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/lint/registry.dart
// Copyright (c) 2015, 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 'dart:collection'; import 'package:analyzer/src/lint/config.dart'; import 'package:analyzer/src/lint/linter.dart'; /** * Registry of lint rules. */ class Registry with IterableMixin<LintRule> { /** * The default registry to be used by clients. */ static final Registry ruleRegistry = new Registry(); /** * A table mapping rule names to rules. */ Map<String, LintRule> _ruleMap = <String, LintRule>{}; @override Iterator<LintRule> get iterator => _ruleMap.values.iterator; /** * Return a list of the rules that are defined. */ Iterable<LintRule> get rules => _ruleMap.values; /** * Return the lint rule with the given [name]. */ LintRule operator [](String name) => _ruleMap[name]; /** * Return a list of the lint rules explicitly enabled by the given [config]. * * For example: * my_rule: true * * enables `my_rule`. * * Unspecified rules are treated as disabled by default. */ Iterable<LintRule> enabled(LintConfig config) => rules .where((rule) => config.ruleConfigs.any((rc) => rc.enables(rule.name))); /** * Return the lint rule with the given [name]. */ LintRule getRule(String name) => _ruleMap[name]; /** * Add the given lint [rule] to this registry. */ void register(LintRule rule) { _ruleMap[rule.name] = rule; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/test_utilities/find_node.dart
// Copyright (c) 2018, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/src/dart/ast/utilities.dart'; class FindNode { final String content; final CompilationUnit unit; FindNode(this.content, this.unit); LibraryDirective get libraryDirective { return unit.directives.singleWhere((d) => d is LibraryDirective); } Annotation annotation(String search) { return _node(search, (n) => n is Annotation); } AstNode any(String search) { return _node(search, (n) => true); } AssignmentExpression assignment(String search) { return _node(search, (n) => n is AssignmentExpression); } BinaryExpression binary(String search) { return _node(search, (n) => n is BinaryExpression); } Block block(String search) { return _node(search, (n) => n is Block); } BooleanLiteral booleanLiteral(String search) { return _node(search, (n) => n is BooleanLiteral); } BreakStatement breakStatement(String search) { return _node(search, (n) => n is BreakStatement); } CascadeExpression cascade(String search) { return _node(search, (n) => n is CascadeExpression); } ClassDeclaration classDeclaration(String search) { return _node(search, (n) => n is ClassDeclaration); } CommentReference commentReference(String search) { return _node(search, (n) => n is CommentReference); } ConditionalExpression conditionalExpression(String search) { return _node(search, (n) => n is ConditionalExpression); } ConstructorDeclaration constructor(String search) { return _node(search, (n) => n is ConstructorDeclaration); } ConstructorFieldInitializer constructorFieldInitializer(String search) { return _node(search, (n) => n is ConstructorFieldInitializer); } ContinueStatement continueStatement(String search) { return _node(search, (n) => n is ContinueStatement); } DefaultFormalParameter defaultParameter(String search) { return _node(search, (n) => n is DefaultFormalParameter); } DoStatement doStatement(String search) { return _node(search, (n) => n is DoStatement); } DoubleLiteral doubleLiteral(String search) { return _node(search, (n) => n is DoubleLiteral); } ExportDirective export(String search) { return _node(search, (n) => n is ExportDirective); } Expression expression(String search) { return _node(search, (n) => n is Expression); } ExpressionStatement expressionStatement(String search) { return _node(search, (n) => n is ExpressionStatement); } ExtensionDeclaration extensionDeclaration(String search) { return _node(search, (n) => n is ExtensionDeclaration); } ExtensionOverride extensionOverride(String search) { return _node(search, (n) => n is ExtensionOverride); } FieldDeclaration fieldDeclaration(String search) { return _node(search, (n) => n is FieldDeclaration); } FieldFormalParameter fieldFormalParameter(String search) { return _node(search, (n) => n is FieldFormalParameter); } ForStatement forStatement(String search) { return _node(search, (n) => n is ForStatement); } FunctionBody functionBody(String search) { return _node(search, (n) => n is FunctionBody); } FunctionDeclaration functionDeclaration(String search) { return _node(search, (n) => n is FunctionDeclaration); } FunctionExpression functionExpression(String search) { return _node(search, (n) => n is FunctionExpression); } FunctionExpressionInvocation functionExpressionInvocation(String search) { return _node(search, (n) => n is FunctionExpressionInvocation); } FunctionTypeAlias functionTypeAlias(String search) { return _node(search, (n) => n is FunctionTypeAlias); } FunctionTypedFormalParameter functionTypedFormalParameter(String search) { return _node(search, (n) => n is FunctionTypedFormalParameter); } GenericFunctionType genericFunctionType(String search) { return _node(search, (n) => n is GenericFunctionType); } ImportDirective import(String search) { return _node(search, (n) => n is ImportDirective); } IndexExpression index(String search) { return _node(search, (n) => n is IndexExpression); } InstanceCreationExpression instanceCreation(String search) { return _node(search, (n) => n is InstanceCreationExpression); } IntegerLiteral integerLiteral(String search) { return _node(search, (n) => n is IntegerLiteral); } Label label(String search) { return _node(search, (n) => n is Label); } LibraryDirective library(String search) { return _node(search, (n) => n is LibraryDirective); } ListLiteral listLiteral(String search) { return _node(search, (n) => n is ListLiteral); } MethodDeclaration methodDeclaration(String search) { return _node(search, (n) => n is MethodDeclaration); } MethodInvocation methodInvocation(String search) { return _node(search, (n) => n is MethodInvocation); } MixinDeclaration mixin(String search) { return _node(search, (n) => n is MixinDeclaration); } NamedExpression namedExpression(String search) { return _node(search, (n) => n is NamedExpression); } NullLiteral nullLiteral(String search) { return _node(search, (n) => n is NullLiteral); } ParenthesizedExpression parenthesized(String search) { return _node(search, (n) => n is ParenthesizedExpression); } PartDirective part(String search) { return _node(search, (n) => n is PartDirective); } PartOfDirective partOf(String search) { return _node(search, (n) => n is PartOfDirective); } PostfixExpression postfix(String search) { return _node(search, (n) => n is PostfixExpression); } PrefixExpression prefix(String search) { return _node(search, (n) => n is PrefixExpression); } PrefixedIdentifier prefixed(String search) { return _node(search, (n) => n is PrefixedIdentifier); } PropertyAccess propertyAccess(String search) { return _node(search, (n) => n is PropertyAccess); } RethrowExpression rethrow_(String search) { return _node(search, (n) => n is RethrowExpression); } SetOrMapLiteral setOrMapLiteral(String search) { return _node(search, (n) => n is SetOrMapLiteral); } SimpleIdentifier simple(String search) { return _node(search, (_) => true); } SimpleFormalParameter simpleParameter(String search) { return _node(search, (n) => n is SimpleFormalParameter); } Statement statement(String search) { return _node(search, (n) => n is Statement); } StringLiteral stringLiteral(String search) { return _node(search, (n) => n is StringLiteral); } SuperExpression super_(String search) { return _node(search, (n) => n is SuperExpression); } SwitchStatement switchStatement(String search) { return _node(search, (n) => n is SwitchStatement); } SymbolLiteral symbolLiteral(String search) { return _node(search, (n) => n is SymbolLiteral); } ThisExpression this_(String search) { return _node(search, (n) => n is ThisExpression); } ThrowExpression throw_(String search) { return _node(search, (n) => n is ThrowExpression); } TopLevelVariableDeclaration topLevelVariableDeclaration(String search) { return _node(search, (n) => n is TopLevelVariableDeclaration); } VariableDeclaration topVariableDeclarationByName(String name) { for (var declaration in unit.declarations) { if (declaration is TopLevelVariableDeclaration) { for (var variable in declaration.variables.variables) { if (variable.name.name == name) { return variable; } } } } throw StateError('$name'); } TypeAnnotation typeAnnotation(String search) { return _node(search, (n) => n is TypeAnnotation); } TypeName typeName(String search) { return _node(search, (n) => n is TypeName); } TypeParameter typeParameter(String search) { return _node(search, (n) => n is TypeParameter); } VariableDeclaration variableDeclaration(String search) { return _node(search, (n) => n is VariableDeclaration); } VariableDeclarationList variableDeclarationList(String search) { return _node(search, (n) => n is VariableDeclarationList); } WhileStatement whileStatement(String search) { return _node(search, (n) => n is WhileStatement); } AstNode _node(String search, bool Function(AstNode) predicate) { var index = content.indexOf(search); if (content.contains(search, index + 1)) { throw new StateError('The pattern |$search| is not unique in:\n$content'); } if (index < 0) { throw new StateError('The pattern |$search| is not found in:\n$content'); } var node = new NodeLocator2(index).searchWithin(unit); if (node == null) { throw new StateError( 'The pattern |$search| had no corresponding node in:\n$content'); } var result = node.thisOrAncestorMatching(predicate); if (result == null) { throw new StateError( 'The node for |$search| had no matching ancestor in:\n$content'); } return result; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/test_utilities/function_ast_visitor.dart
// Copyright (c) 2018, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; /// [RecursiveAstVisitor] that delegates visit methods to functions. class FunctionAstVisitor extends RecursiveAstVisitor<void> { final void Function(FunctionDeclarationStatement) functionDeclarationStatement; final void Function(SimpleIdentifier) simpleIdentifier; final void Function(VariableDeclaration) variableDeclaration; FunctionAstVisitor( {this.functionDeclarationStatement, this.simpleIdentifier, this.variableDeclaration}); @override void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) { if (functionDeclarationStatement != null) { functionDeclarationStatement(node); } super.visitFunctionDeclarationStatement(node); } @override void visitSimpleIdentifier(SimpleIdentifier node) { if (simpleIdentifier != null) { simpleIdentifier(node); } super.visitSimpleIdentifier(node); } @override void visitVariableDeclaration(VariableDeclaration node) { if (variableDeclaration != null) { variableDeclaration(node); } super.visitVariableDeclaration(node); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/test_utilities/find_element.dart
// Copyright (c) 2018, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/test_utilities/function_ast_visitor.dart'; /// Helper for finding elements declared in the resolved [unit]. class FindElement { final CompilationUnit unit; FindElement(this.unit); CompilationUnitElement get unitElement => unit.declaredElement; ClassElement class_(String name) { for (var class_ in unitElement.types) { if (class_.name == name) { return class_; } } throw StateError('Not found: $name'); } ClassElement classOrMixin(String name) { for (var class_ in unitElement.types) { if (class_.name == name) { return class_; } } for (var mixin in unitElement.mixins) { if (mixin.name == name) { return mixin; } } throw StateError('Not found: $name'); } ConstructorElement constructor(String name, {String of}) { assert(name != ''); ConstructorElement result; for (var class_ in unitElement.types) { if (of == null || class_.name == of) { for (var constructor in class_.constructors) { if (constructor.name == name) { if (result != null) { throw StateError('Not unique: $name'); } result = constructor; } } } } if (result != null) { return result; } throw StateError('Not found: $name'); } ClassElement enum_(String name) { for (var enum_ in unitElement.enums) { if (enum_.name == name) { return enum_; } } throw StateError('Not found: $name'); } ExportElement export(String targetUri) { ExportElement result; for (var export in unitElement.library.exports) { var exportedUri = export.exportedLibrary.source.uri.toString(); if (exportedUri == targetUri) { if (result != null) { throw StateError('Not unique: $targetUri'); } result = export; } } if (result != null) { return result; } throw StateError('Not found: $targetUri'); } ExtensionElement extension_(String name) { for (var extension_ in unitElement.extensions) { if (extension_.name == name) { return extension_; } } throw StateError('Not found: $name'); } FieldElement field(String name, {String of}) { FieldElement result; void findIn(List<FieldElement> fields) { for (var field in fields) { if (field.name == name) { if (result != null) { throw StateError('Not unique: $name'); } result = field; } } } for (var enum_ in unitElement.enums) { if (of != null && enum_.name != of) { continue; } findIn(enum_.fields); } for (var class_ in unitElement.types) { if (of != null && class_.name != of) { continue; } findIn(class_.fields); } for (var mixin in unitElement.mixins) { if (of != null && mixin.name != of) { continue; } findIn(mixin.fields); } for (var extension in unitElement.extensions) { if (of != null && extension.name != of) { continue; } findIn(extension.fields); } if (result != null) { return result; } throw StateError('Not found: $name'); } FieldFormalParameterElement fieldFormalParameter(String name) { return parameter(name) as FieldFormalParameterElement; } FunctionElement function(String name) { for (var function in unitElement.functions) { if (function.name == name) { return function; } } throw StateError('Not found: $name'); } GenericTypeAliasElement genericTypeAlias(String name) { for (var element in unitElement.functionTypeAliases) { if (element is GenericTypeAliasElement && element.name == name) { return element; } } throw StateError('Not found: $name'); } PropertyAccessorElement getter(String name, {String of}) { PropertyAccessorElement result; void findIn(List<PropertyAccessorElement> accessors) { for (var accessor in accessors) { if (accessor.isGetter && accessor.displayName == name) { if (result != null) { throw StateError('Not unique: $name'); } result = accessor; } } } for (var enum_ in unitElement.enums) { if (of != null && enum_.name != of) { continue; } findIn(enum_.accessors); } for (var extension_ in unitElement.extensions) { if (of != null && extension_.name != of) { continue; } findIn(extension_.accessors); } for (var class_ in unitElement.types) { if (of != null && class_.name != of) { continue; } findIn(class_.accessors); } for (var mixin in unitElement.mixins) { if (of != null && mixin.name != of) { continue; } findIn(mixin.accessors); } if (result != null) { return result; } throw StateError('Not found: $name'); } ImportElement import(String targetUri) { ImportElement importElement; for (var import in unitElement.library.imports) { var importedUri = import.importedLibrary.source.uri.toString(); if (importedUri == targetUri) { if (importElement != null) { throw StateError('Not unique: $targetUri'); } importElement = import; } } if (importElement != null) { return importElement; } throw StateError('Not found: $targetUri'); } ImportFindElement importFind(String targetUri) { var import = this.import(targetUri); return ImportFindElement(import); } InterfaceType interfaceType(String name) { return class_(name).type; } FunctionElement localFunction(String name) { FunctionElement result; unit.accept(new FunctionAstVisitor( functionDeclarationStatement: (node) { var element = node.functionDeclaration.declaredElement; if (element is FunctionElement) { if (result != null) { throw StateError('Not unique: $name'); } result = element; } }, )); if (result == null) { throw StateError('Not found: $name'); } return result; } LocalVariableElement localVar(String name) { LocalVariableElement result; unit.accept(new FunctionAstVisitor( variableDeclaration: (node) { var element = node.declaredElement; if (element is LocalVariableElement && element.name == name) { if (result != null) { throw StateError('Not unique: $name'); } result = element; } }, )); if (result == null) { throw StateError('Not found: $name'); } return result; } MethodElement method(String name, {String of}) { MethodElement result; void findIn(List<MethodElement> methods) { for (var method in methods) { if (method.name == name) { if (result != null) { throw StateError('Not unique: $name'); } result = method; } } } for (var extension_ in unitElement.extensions) { if (of != null && extension_.name != of) { continue; } findIn(extension_.methods); } for (var class_ in unitElement.types) { if (of != null && class_.name != of) { continue; } findIn(class_.methods); } for (var mixin in unitElement.mixins) { if (of != null && mixin.name != of) { continue; } findIn(mixin.methods); } if (result != null) { return result; } throw StateError('Not found: $name'); } ClassElement mixin(String name) { for (var mixin in unitElement.mixins) { if (mixin.name == name) { return mixin; } } throw StateError('Not found: $name'); } ParameterElement parameter(String name) { ParameterElement result; void findIn(List<ParameterElement> parameters) { for (var parameter in parameters) { if (parameter.name == name) { if (result != null) { throw StateError('Not unique: $name'); } result = parameter; } } } for (var accessor in unitElement.accessors) { findIn(accessor.parameters); } for (var function in unitElement.functions) { findIn(function.parameters); } for (var function in unitElement.functionTypeAliases) { findIn(function.parameters); } for (var extension_ in unitElement.extensions) { for (var method in extension_.methods) { findIn(method.parameters); } for (var accessor in extension_.accessors) { findIn(accessor.parameters); } } for (var class_ in unitElement.types) { for (var constructor in class_.constructors) { findIn(constructor.parameters); } for (var method in class_.methods) { findIn(method.parameters); } for (var accessor in class_.accessors) { findIn(accessor.parameters); } } if (result != null) { return result; } throw StateError('Not found: $name'); } PrefixElement prefix(String name) { for (var import_ in unitElement.library.imports) { var prefix = import_.prefix; if (prefix?.name == name) { return prefix; } } throw StateError('Not found: $name'); } PropertyAccessorElement setter(String name, {String of}) { PropertyAccessorElement result; void findIn(List<PropertyAccessorElement> accessors) { for (var accessor in accessors) { if (accessor.isSetter && accessor.displayName == name) { if (result != null) { throw StateError('Not unique: $name'); } result = accessor; } } } for (var extension_ in unitElement.extensions) { if (of != null && extension_.name != of) { continue; } findIn(extension_.accessors); } for (var class_ in unitElement.types) { if (of != null && class_.name != of) { continue; } findIn(class_.accessors); } for (var mixin in unitElement.mixins) { if (of != null && mixin.name != of) { continue; } findIn(mixin.accessors); } if (result != null) { return result; } throw StateError('Not found: $name'); } FunctionElement topFunction(String name) { for (var function in unitElement.functions) { if (function.name == name) { return function; } } throw StateError('Not found: $name'); } PropertyAccessorElement topGet(String name) { return topVar(name).getter; } PropertyAccessorElement topSet(String name) { return topVar(name).setter; } TopLevelVariableElement topVar(String name) { for (var variable in unitElement.topLevelVariables) { if (variable.name == name) { return variable; } } throw StateError('Not found: $name'); } TypeParameterElement typeParameter(String name) { TypeParameterElement result; void findIn(List<TypeParameterElement> typeParameters) { for (var typeParameter in typeParameters) { if (typeParameter.name == name) { if (result != null) { throw StateError('Not unique: $name'); } result = typeParameter; } } } for (var type in unitElement.functionTypeAliases) { findIn(type.typeParameters); if (type is GenericTypeAliasElement) { findIn(type.function.typeParameters); } } for (var class_ in unitElement.types) { findIn(class_.typeParameters); } for (var mixin in unitElement.mixins) { findIn(mixin.typeParameters); } if (result != null) { return result; } throw StateError('Not found: $name'); } ConstructorElement unnamedConstructor(String name) { return class_(name).unnamedConstructor; } } /// Helper for searching imported elements. class ImportFindElement { final ImportElement import; ImportFindElement(this.import); CompilationUnitElement get definingUnit { return importedLibrary.definingCompilationUnit; } LibraryElement get importedLibrary => import.importedLibrary; PrefixElement get prefix => import.prefix; ClassElement class_(String name) { for (var class_ in definingUnit.types) { if (class_.name == name) { return class_; } } throw StateError('Not found: $name'); } ExtensionElement extension_(String name) { for (var element in definingUnit.extensions) { if (element.name == name) { return element; } } throw StateError('Not found: $name'); } GenericTypeAliasElement functionTypeAlias(String name) { for (var element in definingUnit.functionTypeAliases) { if (element.name == name) { return element; } } throw StateError('Not found: $name'); } FunctionElement topFunction(String name) { for (var function in definingUnit.functions) { if (function.name == name) { return function; } } throw StateError('Not found: $name'); } PropertyAccessorElement topGetter(String name) { for (var accessor in definingUnit.accessors) { if (accessor.name == name && accessor.isGetter) { return accessor; } } throw StateError('Not found: $name'); } TopLevelVariableElement topVar(String name) { for (var variable in definingUnit.topLevelVariables) { if (variable.name == name) { return variable; } } throw StateError('Not found: $name'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/test_utilities/mock_sdk_elements.dart
// Copyright (c) 2019, 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:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/engine.dart' as engine; import 'package:analyzer/src/generated/testing/element_factory.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:meta/meta.dart'; class MockSdkElements { final LibraryElement coreLibrary; final LibraryElement asyncLibrary; factory MockSdkElements( engine.AnalysisContext analysisContext, NullabilitySuffix nullabilitySuffix, ) { var builder = _MockSdkElementsBuilder(analysisContext, nullabilitySuffix); var coreLibrary = builder._buildCore(); var asyncLibrary = builder._buildAsync(); return MockSdkElements._(coreLibrary, asyncLibrary); } MockSdkElements._(this.coreLibrary, this.asyncLibrary); } class _MockSdkElementsBuilder { final engine.AnalysisContext analysisContext; final NullabilitySuffix nullabilitySuffix; ClassElementImpl _boolElement; ClassElementImpl _completerElement; ClassElementImpl _deprecatedElement; ClassElementImpl _doubleElement; ClassElementImpl _functionElement; ClassElementImpl _futureElement; ClassElementImpl _futureOrElement; ClassElementImpl _intElement; ClassElementImpl _iterableElement; ClassElementImpl _iteratorElement; ClassElementImpl _listElement; ClassElementImpl _mapElement; ClassElementImpl _nullElement; ClassElementImpl _numElement; ClassElementImpl _objectElement; ClassElementImpl _overrideElement; ClassElementImpl _proxyElement; ClassElementImpl _setElement; ClassElementImpl _stackTraceElement; ClassElementImpl _streamElement; ClassElementImpl _streamSubscriptionElement; ClassElementImpl _stringElement; ClassElementImpl _symbolElement; ClassElementImpl _typeElement; InterfaceType _boolType; InterfaceType _doubleType; InterfaceType _intType; InterfaceType _numType; InterfaceType _objectType; InterfaceType _stringType; InterfaceType _typeType; _MockSdkElementsBuilder(this.analysisContext, this.nullabilitySuffix); ClassElementImpl get boolElement { if (_boolElement != null) return _boolElement; _boolElement = _class(name: 'bool'); _boolElement.supertype = objectType; _boolElement.constructors = [ _constructor( name: 'fromEnvironment', isConst: true, isFactory: true, parameters: [ _requiredParameter('name', stringType), _namedParameter('defaultValue', boolType), ], ), ]; return _boolElement; } InterfaceType get boolType { return _boolType ??= _interfaceType(boolElement); } ClassElementImpl get completerElement { if (_completerElement != null) return _completerElement; var tElement = _typeParameter('T'); _completerElement = _class( name: 'Completer', isAbstract: true, typeParameters: [tElement], ); _completerElement.supertype = objectType; return _completerElement; } ClassElementImpl get deprecatedElement { if (_deprecatedElement != null) return _deprecatedElement; _deprecatedElement = _class(name: 'Deprecated'); _deprecatedElement.supertype = objectType; _deprecatedElement.fields = <FieldElement>[ _field('message', stringType, isFinal: true), ]; _deprecatedElement.accessors = _deprecatedElement.fields.map((f) => f.getter).toList(); _deprecatedElement.constructors = [ _constructor( isConst: true, parameters: [ _requiredParameter('message', stringType), ], ), ]; return _deprecatedElement; } ClassElementImpl get doubleElement { if (_doubleElement != null) return _doubleElement; _doubleElement = _class(name: 'double', isAbstract: true); _doubleElement.supertype = numType; FieldElement staticConstDoubleField(String name) { return _field(name, doubleType, isStatic: true, isConst: true); } _doubleElement.fields = <FieldElement>[ staticConstDoubleField('nan'), staticConstDoubleField('infinity'), staticConstDoubleField('negativeInfinity'), staticConstDoubleField('minPositive'), staticConstDoubleField('maxFinite'), ]; _doubleElement.accessors = _doubleElement.fields.map((field) => field.getter).toList(); _doubleElement.methods = [ _method('+', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('*', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('-', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('%', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('/', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('~/', intType, parameters: [ _requiredParameter('other', numType), ]), _method('-', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('abs', doubleType), _method('ceil', doubleType), _method('floor', doubleType), _method('remainder', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('round', doubleType), _method('toString', stringType), _method('truncate', doubleType), ]; return _doubleElement; } InterfaceType get doubleType { return _doubleType ??= _interfaceType(doubleElement); } DynamicTypeImpl get dynamicType => DynamicTypeImpl.instance; ClassElementImpl get functionElement { if (_functionElement != null) return _functionElement; _functionElement = _class(name: 'Function', isAbstract: true); _functionElement.supertype = objectType; return _functionElement; } InterfaceType get functionType { return _interfaceType(functionElement); } ClassElementImpl get futureElement { if (_futureElement != null) return _futureElement; var tElement = _typeParameter('T'); var tType = _typeParameterType(tElement); _futureElement = _class( name: 'Future', isAbstract: true, typeParameters: [tElement], ); _futureElement.supertype = objectType; // factory Future.value([FutureOr<T> value]) _futureElement.constructors = [ _constructor( isFactory: true, parameters: [ _positionalParameter('value', futureOrType(tType)), ], ), ]; // Future<R> then<R>(FutureOr<R> onValue(T value), {Function onError}) var rElement = _typeParameter('R'); var rType = _typeParameterType(rElement); _futureElement.methods = [ _method( 'then', futureType(rType), parameters: [ _requiredParameter( 'onValue', _functionType( returnType: futureOrType(rType), parameters: [ _requiredParameter('value', tType), ], ), ), _positionalParameter('onError', functionType), ], ), ]; return _futureElement; } ClassElementImpl get futureOrElement { if (_futureOrElement != null) return _futureOrElement; var tElement = _typeParameter('T'); _futureOrElement = _class( name: 'FutureOr', typeParameters: [tElement], ); _futureOrElement.supertype = objectType; return _futureOrElement; } ClassElementImpl get intElement { if (_intElement != null) return _intElement; _intElement = _class(name: 'int', isAbstract: true); _intElement.supertype = numType; _intElement.constructors = [ _constructor( name: 'fromEnvironment', isConst: true, isFactory: true, parameters: [ _requiredParameter('name', stringType), _namedParameter('defaultValue', intType), ], ), ]; _intElement.methods = [ _method('&', intType, parameters: [ _requiredParameter('other', intType), ]), _method('|', intType, parameters: [ _requiredParameter('other', intType), ]), _method('^', intType, parameters: [ _requiredParameter('other', intType), ]), _method('~', intType), _method('<<', intType, parameters: [ _requiredParameter('shiftAmount', intType), ]), _method('>>', intType, parameters: [ _requiredParameter('shiftAmount', intType), ]), _method('-', intType), _method('abs', intType), _method('round', intType), _method('floor', intType), _method('ceil', intType), _method('truncate', intType), _method('toString', stringType), ]; return _intElement; } InterfaceType get intType { return _intType ??= _interfaceType(intElement); } ClassElementImpl get iterableElement { if (_iterableElement != null) return _iterableElement; var eElement = _typeParameter('E'); var eType = _typeParameterType(eElement); _iterableElement = _class( name: 'Iterable', isAbstract: true, typeParameters: [eElement], ); _iterableElement.supertype = objectType; _iterableElement.constructors = [ _constructor(isConst: true), ]; _setAccessors(_iterableElement, [ _getter('iterator', iteratorType(eType)), _getter('last', eType), ]); return _iterableElement; } ClassElementImpl get iteratorElement { if (_iteratorElement != null) return _iteratorElement; var eElement = _typeParameter('E'); var eType = _typeParameterType(eElement); _iteratorElement = _class( name: 'Iterator', isAbstract: true, typeParameters: [eElement], ); _iteratorElement.supertype = objectType; _setAccessors(_iterableElement, [ _getter('current', eType), ]); return _iteratorElement; } ClassElementImpl get listElement { if (_listElement != null) return _listElement; var eElement = _typeParameter('E'); var eType = _typeParameterType(eElement); _listElement = _class( name: 'List', isAbstract: true, typeParameters: [eElement], ); _listElement.supertype = objectType; _listElement.interfaces = [ iterableType(eType), ]; _listElement.constructors = [ _constructor(isFactory: true, parameters: [ _positionalParameter('length', intType), ]), ]; _setAccessors(_listElement, [ _getter('length', intType), ]); _listElement.methods = [ _method('[]', eType, parameters: [ _requiredParameter('index', intType), ]), _method('[]=', voidType, parameters: [ _requiredParameter('index', intType), _requiredParameter('value', eType), ]), _method('add', voidType, parameters: [ _requiredParameter('value', eType), ]), ]; return _listElement; } ClassElementImpl get mapElement { if (_mapElement != null) return _mapElement; var kElement = _typeParameter('K'); var vElement = _typeParameter('V'); var kType = _typeParameterType(kElement); var vType = _typeParameterType(vElement); _mapElement = _class( name: 'Map', isAbstract: true, typeParameters: [kElement, vElement], ); _mapElement.supertype = objectType; _setAccessors(_mapElement, [ _getter('length', intType), ]); _mapElement.methods = [ _method('[]', vType, parameters: [ _requiredParameter('key', objectType), ]), _method('[]=', voidType, parameters: [ _requiredParameter('key', kType), _requiredParameter('value', vType), ]), ]; return _mapElement; } ClassElementImpl get nullElement { if (_nullElement != null) return _nullElement; _nullElement = _class(name: 'Null'); _nullElement.supertype = objectType; _nullElement.constructors = [ _constructor( name: '_uninstantiatable', isFactory: true, ), ]; return _nullElement; } ClassElementImpl get numElement { if (_numElement != null) return _numElement; _numElement = _class(name: 'num', isAbstract: true); _numElement.supertype = objectType; _numElement.methods = [ _method('+', numType, parameters: [ _requiredParameter('other', numType), ]), _method('-', numType, parameters: [ _requiredParameter('other', numType), ]), _method('*', numType, parameters: [ _requiredParameter('other', numType), ]), _method('%', numType, parameters: [ _requiredParameter('other', numType), ]), _method('/', doubleType, parameters: [ _requiredParameter('other', numType), ]), _method('~/', intType, parameters: [ _requiredParameter('other', numType), ]), _method('-', numType, parameters: [ _requiredParameter('other', numType), ]), _method('remainder', numType, parameters: [ _requiredParameter('other', numType), ]), _method('<', boolType, parameters: [ _requiredParameter('other', numType), ]), _method('<=', boolType, parameters: [ _requiredParameter('other', numType), ]), _method('>', boolType, parameters: [ _requiredParameter('other', numType), ]), _method('>=', boolType, parameters: [ _requiredParameter('other', numType), ]), _method('==', boolType, parameters: [ _requiredParameter('other', objectType), ]), _method('abs', numType), _method('floor', numType), _method('ceil', numType), _method('round', numType), _method('truncate', numType), _method('toInt', intType), _method('toDouble', doubleType), _method('toStringAsFixed', stringType, parameters: [ _requiredParameter('fractionDigits', intType), ]), _method('toStringAsExponential', stringType, parameters: [ _requiredParameter('fractionDigits', intType), ]), _method('toStringAsPrecision', stringType, parameters: [ _requiredParameter('precision', intType), ]), ]; _setAccessors(_numElement, [ _getter('isInfinite', boolType), _getter('isNaN', boolType), _getter('isNegative', boolType), ]); return _numElement; } InterfaceType get numType { return _numType ??= _interfaceType(numElement); } ClassElementImpl get objectElement { if (_objectElement != null) return _objectElement; _objectElement = ElementFactory.object; _objectElement.interfaces = const <InterfaceType>[]; _objectElement.mixins = const <InterfaceType>[]; _objectElement.typeParameters = const <TypeParameterElement>[]; _objectElement.constructors = [ _constructor(isConst: true), ]; _objectElement.methods = [ _method('toString', stringType), _method('==', boolType, parameters: [ _requiredParameter('other', objectType), ]), _method('noSuchMethod', dynamicType, parameters: [ _requiredParameter('other', dynamicType), ]), ]; _setAccessors(_objectElement, [ _getter('hashCode', intType), _getter('runtimeType', typeType), ]); return _objectElement; } InterfaceType get objectType { return _objectType ??= _interfaceType(objectElement); } ClassElementImpl get overrideElement { if (_overrideElement != null) return _overrideElement; _overrideElement = _class(name: '_Override'); _overrideElement.supertype = objectType; _overrideElement.constructors = [ _constructor(isConst: true), ]; return _overrideElement; } ClassElementImpl get proxyElement { if (_proxyElement != null) return _proxyElement; _proxyElement = _class(name: '_Proxy'); _proxyElement.supertype = objectType; _proxyElement.constructors = [ _constructor(isConst: true), ]; return _proxyElement; } ClassElementImpl get setElement { if (_setElement != null) return _setElement; var eElement = _typeParameter('E'); var eType = _typeParameterType(eElement); _setElement = _class( name: 'Set', isAbstract: true, typeParameters: [eElement], ); _setElement.supertype = objectType; _setElement.interfaces = [ iterableType(eType), ]; return _setElement; } ClassElementImpl get stackTraceElement { if (_stackTraceElement != null) return _stackTraceElement; _stackTraceElement = _class(name: 'StackTrace', isAbstract: true); _stackTraceElement.supertype = objectType; return _stackTraceElement; } ClassElementImpl get streamElement { if (_streamElement != null) return _streamElement; var tElement = _typeParameter('T'); var tType = _typeParameterType(tElement); _streamElement = _class( name: 'Stream', isAbstract: true, typeParameters: [tElement], ); _streamElement.isAbstract = true; _streamElement.supertype = objectType; // StreamSubscription<T> listen(void onData(T event), // {Function onError, void onDone(), bool cancelOnError}); _streamElement.methods = [ _method( 'listen', streamSubscriptionType(tType), parameters: [ _requiredParameter( 'onData', _functionType( returnType: voidType, parameters: [ _requiredParameter('event', tType), ], ), ), _namedParameter('onError', functionType), _namedParameter( 'onDone', _functionType(returnType: voidType), ), _namedParameter('cancelOnError', boolType), ], ), ]; return _streamElement; } ClassElementImpl get streamSubscriptionElement { if (_streamSubscriptionElement != null) return _streamSubscriptionElement; var tElement = _typeParameter('T'); _streamSubscriptionElement = _class( name: 'StreamSubscription', isAbstract: true, typeParameters: [tElement], ); _streamSubscriptionElement.supertype = objectType; return _streamSubscriptionElement; } ClassElementImpl get stringElement { if (_stringElement != null) return _stringElement; _stringElement = _class(name: 'String', isAbstract: true); _stringElement.supertype = objectType; _stringElement.constructors = [ _constructor( name: 'fromEnvironment', isConst: true, isFactory: true, parameters: [ _requiredParameter('name', stringType), _namedParameter('defaultValue', stringType), ], ), ]; _setAccessors(_stringElement, [ _getter('isEmpty', boolType), _getter('length', intType), _getter('codeUnits', listType(intType)), ]); _stringElement.methods = [ _method('+', _stringType, parameters: [ _requiredParameter('other', _stringType), ]), _method('toLowerCase', _stringType), _method('toUpperCase', _stringType), ]; return _stringElement; } InterfaceType get stringType { return _stringType ??= _interfaceType(stringElement); } ClassElementImpl get symbolElement { if (_symbolElement != null) return _symbolElement; _symbolElement = _class(name: 'Symbol', isAbstract: true); _symbolElement.supertype = objectType; _symbolElement.constructors = [ _constructor( isConst: true, isFactory: true, parameters: [ _requiredParameter('name', stringType), ], ), ]; return _symbolElement; } ClassElementImpl get typeElement { if (_typeElement != null) return _typeElement; _typeElement = _class(name: 'Type', isAbstract: true); _typeElement.supertype = objectType; return _typeElement; } InterfaceType get typeType { return _typeType ??= _interfaceType(typeElement); } VoidTypeImpl get voidType => VoidTypeImpl.instance; InterfaceType futureOrType(DartType elementType) { return _interfaceType( futureOrElement, typeArguments: [elementType], ); } InterfaceType futureType(DartType elementType) { return _interfaceType( futureElement, typeArguments: [elementType], ); } InterfaceType iterableType(DartType elementType) { return _interfaceType( iterableElement, typeArguments: [elementType], ); } InterfaceType iteratorType(DartType elementType) { return _interfaceType( iteratorElement, typeArguments: [elementType], ); } InterfaceType listType(DartType elementType) { return _interfaceType( listElement, typeArguments: [elementType], ); } InterfaceType streamSubscriptionType(DartType valueType) { return _interfaceType( streamSubscriptionElement, typeArguments: [valueType], ); } LibraryElementImpl _buildAsync() { var asyncLibrary = LibraryElementImpl( analysisContext, null, 'dart.async', 0, 0, nullabilitySuffix == NullabilitySuffix.none, ); var asyncUnit = new CompilationUnitElementImpl(); var asyncSource = analysisContext.sourceFactory.forUri('dart:async'); asyncUnit.librarySource = asyncUnit.source = asyncSource; asyncLibrary.definingCompilationUnit = asyncUnit; asyncUnit.types = <ClassElement>[ completerElement, futureElement, futureOrElement, streamElement, streamSubscriptionElement ]; return asyncLibrary; } LibraryElementImpl _buildCore() { var coreUnit = CompilationUnitElementImpl(); var coreSource = analysisContext.sourceFactory.forUri('dart:core'); coreUnit.librarySource = coreUnit.source = coreSource; coreUnit.types = <ClassElement>[ boolElement, deprecatedElement, doubleElement, functionElement, intElement, iterableElement, iteratorElement, listElement, mapElement, nullElement, numElement, objectElement, overrideElement, proxyElement, setElement, stackTraceElement, stringElement, symbolElement, typeElement, ]; coreUnit.functions = <FunctionElement>[ _function('identical', boolType, parameters: [ _requiredParameter('a', objectType), _requiredParameter('b', objectType), ]), _function('print', voidType, parameters: [ _requiredParameter('object', objectType), ]), ]; var deprecatedVariable = _topLevelVariable( 'deprecated', _interfaceType(deprecatedElement), isConst: true, ); var overrideVariable = _topLevelVariable( 'override', _interfaceType(overrideElement), isConst: true, ); var proxyVariable = _topLevelVariable( 'proxy', _interfaceType(proxyElement), isConst: true, ); coreUnit.accessors = <PropertyAccessorElement>[ deprecatedVariable.getter, overrideVariable.getter, proxyVariable.getter, ]; coreUnit.topLevelVariables = <TopLevelVariableElement>[ deprecatedVariable, overrideVariable, proxyVariable, ]; var coreLibrary = LibraryElementImpl( analysisContext, null, 'dart.core', 0, 0, nullabilitySuffix == NullabilitySuffix.none, ); coreLibrary.definingCompilationUnit = coreUnit; return coreLibrary; } ClassElementImpl _class({ @required String name, bool isAbstract = false, List<TypeParameterElement> typeParameters = const [], }) { var element = ClassElementImpl(name, 0); element.typeParameters = typeParameters; element.constructors = <ConstructorElement>[ _constructor(), ]; return element; } ConstructorElement _constructor({ String name = '', bool isConst = false, bool isFactory = false, List<ParameterElement> parameters = const [], }) { var element = ConstructorElementImpl(name, 0); element.factory = isFactory; element.isConst = isConst; element.parameters = parameters; return element; } FieldElement _field( String name, DartType type, { bool isConst = false, bool isFinal = false, bool isStatic = false, }) { return ElementFactory.fieldElement(name, isStatic, isFinal, isConst, type); } FunctionElement _function( String name, DartType returnType, { List<TypeParameterElement> typeFormals = const [], List<ParameterElement> parameters = const [], }) { var element = FunctionElementImpl(name, 0) ..parameters = parameters ..returnType = returnType ..typeParameters = typeFormals; element.type = _typeOfExecutableElement(element); return element; } FunctionType _functionType({ @required DartType returnType, List<TypeParameterElement> typeFormals = const [], List<ParameterElement> parameters = const [], }) { return FunctionTypeImpl.synthetic(returnType, typeFormals, parameters); } PropertyAccessorElement _getter( String name, DartType type, { bool isStatic = false, }) { var field = FieldElementImpl(name, -1); field.isFinal = true; field.isStatic = isStatic; field.isSynthetic = true; field.type = type; var getter = PropertyAccessorElementImpl(name, 0); getter.getter = true; getter.isStatic = isStatic; getter.isSynthetic = false; getter.returnType = type; getter.type = _typeOfExecutableElement(getter); getter.variable = field; field.getter = getter; return getter; } InterfaceType _interfaceType( ClassElement element, { List<DartType> typeArguments = const [], }) { return InterfaceTypeImpl.explicit( element, typeArguments, nullabilitySuffix: nullabilitySuffix, ); } MethodElement _method( String name, DartType returnType, { List<TypeParameterElement> typeFormals = const [], List<ParameterElement> parameters = const [], }) { var element = MethodElementImpl(name, 0) ..parameters = parameters ..returnType = returnType ..typeParameters = typeFormals; element.type = _typeOfExecutableElement(element); return element; } ParameterElement _namedParameter(String name, DartType type, {String initializerCode}) { var parameter = DefaultParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.NAMED; parameter.type = type; parameter.defaultValueCode = initializerCode; return parameter; } ParameterElement _positionalParameter(String name, DartType type) { var parameter = ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.POSITIONAL; parameter.type = type; return parameter; } ParameterElement _requiredParameter(String name, DartType type) { var parameter = ParameterElementImpl(name, 0); parameter.parameterKind = ParameterKind.REQUIRED; parameter.type = type; return parameter; } /// Set the [accessors] and the corresponding fields for the [classElement]. void _setAccessors( ClassElementImpl classElement, List<PropertyAccessorElement> accessors, ) { classElement.accessors = accessors; classElement.fields = accessors .map((accessor) => accessor.variable) .cast<FieldElement>() .toList(); } TopLevelVariableElement _topLevelVariable( String name, DartType type, { bool isConst = false, bool isFinal = false, }) { return ElementFactory.topLevelVariableElement3( name, isConst, isFinal, type); } /// TODO(scheglov) We should do the opposite - build type in the element. /// But build a similar synthetic / structured type. FunctionType _typeOfExecutableElement(ExecutableElement element) { return FunctionTypeImpl.synthetic( element.returnType, element.typeParameters, element.parameters, ); } TypeParameterElementImpl _typeParameter(String name) { return TypeParameterElementImpl(name, 0); } TypeParameterType _typeParameterType(TypeParameterElement element) { return TypeParameterTypeImpl( element, nullabilitySuffix: nullabilitySuffix, ); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/test_utilities/mock_sdk.dart
// Copyright (c) 2018, 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:analyzer/file_system/file_system.dart'; import 'package:analyzer/file_system/memory_file_system.dart'; import 'package:analyzer/src/context/cache.dart'; import 'package:analyzer/src/context/context.dart'; import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine; import 'package:analyzer/src/generated/sdk.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/summary/idl.dart' show PackageBundle; import 'package:analyzer/src/summary/summary_file_builder.dart'; import 'package:meta/meta.dart'; const String sdkRoot = '/sdk'; final MockSdkLibrary _LIB_ASYNC = MockSdkLibrary([ MockSdkLibraryUnit( 'dart:async', '$sdkRoot/lib/async/async.dart', ''' library dart.async; import 'dart:math'; part 'stream.dart'; class Future<T> { factory Future(computation()) => null; factory Future.delayed(Duration duration, [T computation()]) => null; factory Future.microtask(FutureOr<T> computation()) => null; factory Future.value([FutureOr<T> result]) => null; Future<R> then<R>(FutureOr<R> onValue(T value)) => null; Future<T> whenComplete(action()); static Future<List<T>> wait<T>(Iterable<Future<T>> futures) => null; } class FutureOr<T> {} abstract class Completer<T> { factory Completer() => null; factory Completer.sync() => null; Future<T> get future; bool get isCompleted; void complete([value]); void completeError(Object error, [StackTrace stackTrace]); } abstract class Timer { static void run(void callback()) {} } ''', ), MockSdkLibraryUnit( 'dart:async/stream.dart', '$sdkRoot/lib/async/stream.dart', r''' part of dart.async; abstract class Stream<T> { Stream(); factory Stream.fromIterable(Iterable<T> data) => null; Future<T> get first; StreamSubscription<T> listen(void onData(T event), { Function onError, void onDone(), bool cancelOnError}); } abstract class StreamIterator<T> {} abstract class StreamSubscription<T> { bool get isPaused; Future<E> asFuture<E>([E futureValue]); Future cancel(); void onData(void handleData(T data)); void onError(Function handleError); void onDone(void handleDone()); void pause([Future resumeSignal]); void resume(); } abstract class StreamTransformer<S, T> {} ''', ) ]); final MockSdkLibrary _LIB_ASYNC2 = MockSdkLibrary([ MockSdkLibraryUnit( 'dart:async2', '$sdkRoot/lib/async2/async2.dart', ''' library dart.async2; class Future {} ''', ) ]); final MockSdkLibrary _LIB_COLLECTION = MockSdkLibrary([ MockSdkLibraryUnit( 'dart:collection', '$sdkRoot/lib/collection/collection.dart', ''' library dart.collection; abstract class HashMap<K, V> implements Map<K, V> { external factory HashMap( {bool equals(K key1, K key2), int hashCode(K key), bool isValidKey(potentialKey)}); external factory HashMap.identity(); factory HashMap.from(Map other) => null; factory HashMap.of(Map<K, V> other) => null; factory HashMap.fromIterable(Iterable iterable, {K key(element), V value(element)}) => null; factory HashMap.fromIterables(Iterable<K> keys, Iterable<V> values) => null; factory HashMap.fromEntries(Iterable<MapEntry<K, V>> entries) => null; } abstract class LinkedHashMap<K, V> implements Map<K, V> { external factory LinkedHashMap( {bool equals(K key1, K key2), int hashCode(K key), bool isValidKey(potentialKey)}); external factory LinkedHashMap.identity(); factory LinkedHashMap.from(Map other) => null; factory LinkedHashMap.of(Map<K, V> other) => null; factory LinkedHashMap.fromIterable(Iterable iterable, {K key(element), V value(element)}) => null; factory LinkedHashMap.fromIterables(Iterable<K> keys, Iterable<V> values) => null; factory LinkedHashMap.fromEntries(Iterable<MapEntry<K, V>> entries) => null; } abstract class LinkedHashSet<E> implements Set<E> { external factory LinkedHashSet( {bool equals(E e1, E e2), int hashCode(E e), bool isValidKey(potentialKey)}); external factory LinkedHashSet.identity(); factory LinkedHashSet.from(Iterable elements) => null; factory LinkedHashSet.of(Iterable<E> elements) => null; } ''', ) ]); final MockSdkLibrary _LIB_CONVERT = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:convert', '$sdkRoot/lib/convert/convert.dart', ''' library dart.convert; import 'dart:async'; abstract class Converter<S, T> implements StreamTransformer {} class JsonDecoder extends Converter<String, Object> {} ''', ) ], ); final MockSdkLibrary _LIB_CORE = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:core', '$sdkRoot/lib/core/core.dart', ''' library dart.core; import 'dart:async'; // ignore: unused_import export 'dart:async' show Future, Stream; const deprecated = const Deprecated("next release"); const override = const _Override(); const proxy = const _Proxy(); external bool identical(Object a, Object b); void print(Object object) {} abstract class bool extends Object { external const factory bool.fromEnvironment(String name, {bool defaultValue: false}); bool operator &(bool other); bool operator |(bool other); bool operator ^(bool other); } abstract class Comparable<T> { int compareTo(T other); } class DateTime extends Object {} class Deprecated extends Object { final String expires; const Deprecated(this.expires); } class pragma { final String name; final Object options; const pragma(this.name, [this.options]); } abstract class double extends num { static const double NAN = 0.0 / 0.0; static const double INFINITY = 1.0 / 0.0; static const double NEGATIVE_INFINITY = -INFINITY; static const double MIN_POSITIVE = 5e-324; static const double MAX_FINITE = 1.7976931348623157e+308; double get sign; double operator %(num other); double operator *(num other); double operator +(num other); double operator -(num other); double operator -(); double operator /(num other); int operator ~/(num other); double abs(); int ceil(); double ceilToDouble(); int floor(); double floorToDouble(); double remainder(num other); int round(); double roundToDouble(); int truncate(); double truncateToDouble(); external static double parse(String source, [double onError(String source)]); } class Duration implements Comparable<Duration> {} class Error { Error(); static String safeToString(Object object) => ''; external StackTrace get stackTrace; } class Exception { factory Exception([var message]) => null; } class Function {} abstract class int extends num { external const factory int.fromEnvironment(String name, {int defaultValue}); bool get isEven => false; bool get isNegative; int operator &(int other); int operator -(); int operator <<(int shiftAmount); int operator >>(int shiftAmount); int operator ^(int other); int operator |(int other); int operator ~(); int abs(); int gcd(int other); String toString(); external static int parse(String source, {int radix, int onError(String source)}); } abstract class Invocation {} abstract class Iterable<E> { E get first; bool get isEmpty; bool get isNotEmpty; Iterator<E> get iterator; int get length; bool contains(Object element); Iterable<T> expand<T>(Iterable<T> f(E element)); E firstWhere(bool test(E element), { E orElse()}); R fold<R>(R initialValue, R combine(R previousValue, E element)) => null; void forEach(void f(E element)); Iterable<R> map<R>(R f(E e)); List<E> toList(); Set<E> toSet(); Iterable<E> where(bool test(E element)); } abstract class Iterator<E> { E get current; bool moveNext(); } class List<E> implements Iterable<E> { List([int length]); factory List.from(Iterable elements, {bool growable: true}) => null; E get last => null; E operator [](int index) => null; void operator []=(int index, E value) {} void add(E value) {} void addAll(Iterable<E> iterable) {} Map<int, E> asMap() {} void clear() {} int indexOf(Object element); E removeLast() {} noSuchMethod(Invocation invocation) => null; } class Map<K, V> { factory Map() => null; factory Map.fromIterable(Iterable iterable, {K key(element), V value(element)}) => null; Iterable<K> get keys => null; bool get isEmpty; bool get isNotEmpty; int get length => 0; Iterable<V> get values => null; V operator [](K key) => null; void operator []=(K key, V value) {} Map<RK, RV> cast<RK, RV>() => null; bool containsKey(Object key) => false; } class Null extends Object { factory Null._uninstantiable() => null; } abstract class num implements Comparable<num> { num operator %(num other); num operator *(num other); num operator +(num other); num operator -(num other); num operator -(); double operator /(num other); bool operator <(num other); int operator <<(int other); bool operator <=(num other); bool operator ==(Object other); bool operator >(num other); bool operator >=(num other); int operator >>(int other); int operator ^(int other); int operator |(int other); int operator ~(); int operator ~/(num other); num abs(); int floor(); int round(); double toDouble(); int toInt(); } class Object { const Object(); int get hashCode => 0; Type get runtimeType => null; bool operator ==(other) => identical(this, other); String toString() => 'a string'; dynamic noSuchMethod(Invocation invocation) => null; } abstract class Pattern {} abstract class RegExp implements Pattern { external factory RegExp(String source); } abstract class Set<E> implements Iterable<E> { factory Set() => null; factory Set.identity() => null; factory Set.from(Iterable elements) => null; factory Set.of(Iterable<E> elements) => null; Set<R> cast<R>(); } class StackTrace {} abstract class String implements Comparable<String>, Pattern { external factory String.fromCharCodes(Iterable<int> charCodes, [int start = 0, int end]); List<int> get codeUnits; int indexOf(Pattern pattern, [int start]); bool get isEmpty => false; bool get isNotEmpty => false; int get length => 0; String operator +(String other) => null; bool operator ==(Object other); int codeUnitAt(int index); bool contains(String other, [int startIndex = 0]); String substring(int len) => null; String toLowerCase(); String toUpperCase(); } class Symbol { const factory Symbol(String name) = _SymbolImpl; } class Type {} class Uri { static List<int> parseIPv6Address(String host, [int start = 0, int end]) { return null; } } class _Override { const _Override(); } class _Proxy { const _Proxy(); } class _SymbolImpl { const _SymbolImpl(String name); } ''', ) ], ); final MockSdkLibrary _LIB_FOREIGN_HELPER = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:_foreign_helper', '$sdkRoot/lib/_foreign_helper/_foreign_helper.dart', ''' library dart._foreign_helper; JS(String typeDescription, String codeTemplate, [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11]) {} ''', ) ], ); final MockSdkLibrary _LIB_HTML_DART2JS = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:html', '$sdkRoot/lib/html/dart2js/html_dart2js.dart', ''' library dart.dom.html; import 'dart:async'; class Event {} class MouseEvent extends Event {} class FocusEvent extends Event {} class KeyEvent extends Event {} abstract class ElementStream<T extends Event> implements Stream<T> {} abstract class Element { /// Stream of `cut` events handled by this [Element]. ElementStream<Event> get onCut => null; String get id => null; set id(String value) => null; } class HtmlElement extends Element { int tabIndex; ElementStream<Event> get onChange => null; ElementStream<MouseEvent> get onClick => null; ElementStream<KeyEvent> get onKeyUp => null; ElementStream<KeyEvent> get onKeyDown => null; bool get hidden => null; set hidden(bool value) => null; void set className(String s){} void set readOnly(bool b){} void set tabIndex(int i){} String _innerHtml; String get innerHtml { throw 'not the real implementation'; } set innerHtml(String value) { // stuff } } class AnchorElement extends HtmlElement { factory AnchorElement({String href}) { AnchorElement e = JS('returns:AnchorElement;creates:AnchorElement;new:true', '#.createElement(#)', document, "a"); if (href != null) e.href = href; return e; } String href; String _privateField; } class BodyElement extends HtmlElement { factory BodyElement() => document.createElement("body"); ElementStream<Event> get onUnload => null; } class ButtonElement extends HtmlElement { factory ButtonElement._() { throw new UnsupportedError("Not supported"); } factory ButtonElement() => document.createElement("button"); bool autofocus; } class EmbedElement extends HtmlEment { String src; } class HeadingElement extends HtmlElement { factory HeadingElement._() { throw new UnsupportedError("Not supported"); } factory HeadingElement.h1() => document.createElement("h1"); factory HeadingElement.h2() => document.createElement("h2"); factory HeadingElement.h3() => document.createElement("h3"); } class InputElement extends HtmlElement { factory InputElement._() { throw new UnsupportedError("Not supported"); } factory InputElement() => document.createElement("input"); String value; String validationMessage; } class IFrameElement extends HtmlElement { factory IFrameElement._() { throw new UnsupportedError("Not supported"); } factory IFrameElement() => JS( 'returns:IFrameElement;creates:IFrameElement;new:true', '#.createElement(#)', document, "iframe"); String src; } class ImageElement extends HtmlEment { String src; } class OptionElement extends HtmlElement { factory OptionElement({String data: '', String value : '', bool selected: false}) { } factory OptionElement._([String data, String value, bool defaultSelected, bool selected]) { } } class ScriptElement extends HtmlElement { String src; String type; } class TableSectionElement extends HtmlElement { List<TableRowElement> get rows => null; TableRowElement addRow() { } TableRowElement insertRow(int index) => null; factory TableSectionElement._() { throw new UnsupportedError("Not supported"); } @Deprecated("Internal Use Only") external static Type get instanceRuntimeType; @Deprecated("Internal Use Only") TableSectionElement.internal_() : super.internal_(); } class TemplateElement extends HtmlElement { factory TemplateElement._() { throw new UnsupportedError("Not supported"); } factory TemplateElement() => document.createElement("template"); } class AudioElement extends MediaElement { factory AudioElement._([String src]) { if (src != null) { return AudioElement._create_1(src); } return AudioElement._create_2(); } static AudioElement _create_1(src) => JS('AudioElement', 'new Audio(#)', src); static AudioElement _create_2() => JS('AudioElement', 'new Audio()'); AudioElement.created() : super.created(); factory AudioElement([String src]) => new AudioElement._(src); } class MediaElement extends Element {} dynamic JS(a, b, c, d) {} ''', ) ], ); final MockSdkLibrary _LIB_HTML_DARTIUM = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:html', '$sdkRoot/lib/html/dartium/html_dartium.dart', ''' library dart.dom.html; import 'dart:async'; class Event {} class MouseEvent extends Event {} class FocusEvent extends Event {} class KeyEvent extends Event {} abstract class ElementStream<T extends Event> implements Stream<T> {} abstract class Element { /// Stream of `cut` events handled by this [Element]. ElementStream<Event> get onCut => null; String get id => null; set id(String value) => null; } class HtmlElement extends Element { int tabIndex; ElementStream<Event> get onChange => null; ElementStream<MouseEvent> get onClick => null; ElementStream<KeyEvent> get onKeyUp => null; ElementStream<KeyEvent> get onKeyDown => null; bool get hidden => null; set hidden(bool value) => null; void set className(String s){} void set readOnly(bool b){} void set tabIndex(int i){} String _innerHtml; String get innerHtml { throw 'not the real implementation'; } set innerHtml(String value) { // stuff } } class AnchorElement extends HtmlElement { factory AnchorElement({String href}) { AnchorElement e = JS('returns:AnchorElement;creates:AnchorElement;new:true', '#.createElement(#)', document, "a"); if (href != null) e.href = href; return e; } String href; String _privateField; } class BodyElement extends HtmlElement { factory BodyElement() => document.createElement("body"); ElementStream<Event> get onUnload => null; } class ButtonElement extends HtmlElement { factory ButtonElement._() { throw new UnsupportedError("Not supported"); } factory ButtonElement() => document.createElement("button"); bool autofocus; } class EmbedElement extends HtmlEment { String src; } class HeadingElement extends HtmlElement { factory HeadingElement._() { throw new UnsupportedError("Not supported"); } factory HeadingElement.h1() => document.createElement("h1"); factory HeadingElement.h2() => document.createElement("h2"); factory HeadingElement.h3() => document.createElement("h3"); } class InputElement extends HtmlElement { factory InputElement._() { throw new UnsupportedError("Not supported"); } factory InputElement() => document.createElement("input"); String value; String validationMessage; } class IFrameElement extends HtmlElement { factory IFrameElement._() { throw new UnsupportedError("Not supported"); } factory IFrameElement() => JS( 'returns:IFrameElement;creates:IFrameElement;new:true', '#.createElement(#)', document, "iframe"); String src; } class ImageElement extends HtmlEment { String src; } class OptionElement extends HtmlElement { factory OptionElement({String data: '', String value : '', bool selected: false}) { } factory OptionElement._([String data, String value, bool defaultSelected, bool selected]) { } } class ScriptElement extends HtmlElement { String src; String type; } class TableSectionElement extends HtmlElement { List<TableRowElement> get rows => null; TableRowElement addRow() { } TableRowElement insertRow(int index) => null; factory TableSectionElement._() { throw new UnsupportedError("Not supported"); } @Deprecated("Internal Use Only") external static Type get instanceRuntimeType; @Deprecated("Internal Use Only") TableSectionElement.internal_() : super.internal_(); } class TemplateElement extends HtmlElement { factory TemplateElement._() { throw new UnsupportedError("Not supported"); } factory TemplateElement() => document.createElement("template"); } class AudioElement extends MediaElement { factory AudioElement._([String src]) { if (src != null) { return AudioElement._create_1(src); } return AudioElement._create_2(); } static AudioElement _create_1(src) => JS('AudioElement', 'new Audio(#)', src); static AudioElement _create_2() => JS('AudioElement', 'new Audio()'); AudioElement.created() : super.created(); factory AudioElement([String src]) => new AudioElement._(src); } class MediaElement extends Element {} dynamic JS(a, b, c, d) {} ''', ) ], ); final MockSdkLibrary _LIB_INTERCEPTORS = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:_interceptors', '$sdkRoot/lib/_internal/js_runtime/lib/interceptors.dart', ''' library dart._interceptors; ''', ) ], ); final MockSdkLibrary _LIB_INTERNAL = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:_internal', '$sdkRoot/lib/_internal/internal.dart', ''' library dart._internal; class Symbol {} class ExternalName { final String name; const ExternalName(this.name); } ''', ) ], ); final MockSdkLibrary _LIB_IO = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:io', '$sdkRoot/lib/io/io.dart', ''' library dart.io; abstract class Directory implements FileSystemEntity { factory Directory(String path) => null; Future<bool> exists() async => true; bool existsSync() => true; Future<FileStat> stat() async => null; FileStat statSync() => null; } abstract class File implements FileSystemEntity { factory File(String path) => null; Future<DateTime> lastModified(); DateTime lastModifiedSync(); Future<bool> exists() async => true; bool existsSync() => true; Future<FileStat> stat() async => null; FileStat statSync() => null; } abstract class FileSystemEntity { static Future<bool> isDirectory(String path) => true; static bool isDirectorySync(String path) => true; static Future<bool> isFile(String path) => true; static bool isFileSync(String path) => true; static Future<bool> isLink(String path) => true; static bool isLinkSync(String path) => true; static Future<FileSystemEntityType> type( String path, {bool followLinks: true}) async => null; static FileSystemEntityType typeSync( String path, {bool followLinks: true}) => null; } ''', ) ], ); final MockSdkLibrary _LIB_MATH = MockSdkLibrary( [ MockSdkLibraryUnit( 'dart:math', '$sdkRoot/lib/math/math.dart', ''' library dart.math; const double E = 2.718281828459045; const double PI = 3.1415926535897932; const double LN10 = 2.302585092994046; T min<T extends num>(T a, T b) => null; T max<T extends num>(T a, T b) => null; external double cos(num radians); external double sin(num radians); external double sqrt(num radians); external double tan(num radians); class Random { bool nextBool() => true; double nextDouble() => 2.0; int nextInt() => 1; } class Point<T extends num> {} ''', ) ], ); final List<SdkLibrary> _LIBRARIES = [ _LIB_CORE, _LIB_ASYNC, _LIB_ASYNC2, _LIB_COLLECTION, _LIB_CONVERT, _LIB_FOREIGN_HELPER, _LIB_IO, _LIB_MATH, _LIB_HTML_DART2JS, _LIB_HTML_DARTIUM, _LIB_INTERCEPTORS, _LIB_INTERNAL, ]; final Map<String, String> _librariesDartEntries = { 'async': 'const LibraryInfo("async/async.dart")', 'collection': 'const LibraryInfo("collection/collection.dart")', 'convert': 'const LibraryInfo("convert/convert.dart")', 'core': 'const LibraryInfo("core/core.dart")', 'html': 'const LibraryInfo("html/dartium/html_dartium.dart", ' 'dart2jsPath: "html/dart2js/html_dart2js.dart")', 'io': 'const LibraryInfo("io/io.dart")', 'math': 'const LibraryInfo("math/math.dart")', '_foreign_helper': 'const LibraryInfo("_internal/js_runtime/lib/foreign_helper.dart")', }; class MockSdk implements DartSdk { final MemoryResourceProvider resourceProvider; final Map<String, String> uriMap = {}; /** * The [AnalysisContextImpl] which is used for all of the sources. */ AnalysisContextImpl _analysisContext; @override final List<SdkLibrary> sdkLibraries = []; /** * The cached linked bundle of the SDK. */ PackageBundle _bundle; /// Optional [additionalLibraries] should have unique URIs, and paths in /// their units are relative (will be put into `sdkRoot/lib`). MockSdk({ bool generateSummaryFiles: false, @required this.resourceProvider, List<MockSdkLibrary> additionalLibraries = const [], }) { for (MockSdkLibrary library in _LIBRARIES) { var convertedLibrary = library._toProvider(resourceProvider); sdkLibraries.add(convertedLibrary); } for (MockSdkLibrary library in additionalLibraries) { sdkLibraries.add( MockSdkLibrary( library.units.map( (unit) { var pathContext = resourceProvider.pathContext; var absoluteUri = pathContext.join(sdkRoot, unit.path); return MockSdkLibraryUnit( unit.uriStr, resourceProvider.convertPath(absoluteUri), unit.content, ); }, ).toList(), ), ); } for (MockSdkLibrary library in sdkLibraries) { for (var unit in library.units) { resourceProvider.newFile(unit.path, unit.content); uriMap[unit.uriStr] = unit.path; } } { var buffer = StringBuffer(); buffer.writeln('const Map<String, LibraryInfo> libraries = const {'); for (var e in _librariesDartEntries.entries) { buffer.writeln('"${e.key}": ${e.value},'); } buffer.writeln('};'); resourceProvider.newFile( resourceProvider.convertPath( '$sdkRoot/lib/_internal/sdk_library_metadata/lib/libraries.dart', ), buffer.toString(), ); } if (generateSummaryFiles) { List<int> bytes = _computeLinkedBundleBytes(); resourceProvider.newFileWithBytes( resourceProvider.convertPath('/lib/_internal/strong.sum'), bytes); } } @override AnalysisContextImpl get context { if (_analysisContext == null) { _analysisContext = new _SdkAnalysisContext(this); SourceFactory factory = new SourceFactory([new DartUriResolver(this)]); _analysisContext.sourceFactory = factory; } return _analysisContext; } @override String get sdkVersion => throw new UnimplementedError(); @override List<String> get uris => sdkLibraries.map((SdkLibrary library) => library.shortName).toList(); @override Source fromFileUri(Uri uri) { String filePath = resourceProvider.pathContext.fromUri(uri); if (!filePath.startsWith(resourceProvider.convertPath('$sdkRoot/lib/'))) { return null; } for (SdkLibrary library in sdkLibraries) { String libraryPath = library.path; if (filePath == libraryPath) { try { File file = resourceProvider.getResource(filePath); Uri dartUri = Uri.parse(library.shortName); return file.createSource(dartUri); } catch (exception) { return null; } } String libraryRootPath = resourceProvider.pathContext.dirname(libraryPath) + resourceProvider.pathContext.separator; if (filePath.startsWith(libraryRootPath)) { String pathInLibrary = filePath.substring(libraryRootPath.length); String uriStr = '${library.shortName}/$pathInLibrary'; try { File file = resourceProvider.getResource(filePath); Uri dartUri = Uri.parse(uriStr); return file.createSource(dartUri); } catch (exception) { return null; } } } return null; } @override PackageBundle getLinkedBundle() { if (_bundle == null) { File summaryFile = resourceProvider .getFile(resourceProvider.convertPath('/lib/_internal/strong.sum')); List<int> bytes; if (summaryFile.exists) { bytes = summaryFile.readAsBytesSync(); } else { bytes = _computeLinkedBundleBytes(); } _bundle = new PackageBundle.fromBuffer(bytes); } return _bundle; } @override SdkLibrary getSdkLibrary(String dartUri) { for (SdkLibrary library in _LIBRARIES) { if (library.shortName == dartUri) { return library; } } return null; } @override Source mapDartUri(String dartUri) { String path = uriMap[dartUri]; if (path != null) { File file = resourceProvider.getResource(path); Uri uri = new Uri(scheme: 'dart', path: dartUri.substring(5)); return file.createSource(uri); } // If we reach here then we tried to use a dartUri that's not in the // table above. return null; } /** * Compute the bytes of the linked bundle associated with this SDK. */ List<int> _computeLinkedBundleBytes() { List<Source> librarySources = sdkLibraries .map((SdkLibrary library) => mapDartUri(library.shortName)) .toList(); return new SummaryBuilder(librarySources, context).build(); } } class MockSdkLibrary implements SdkLibrary { final List<MockSdkLibraryUnit> units; MockSdkLibrary(this.units); @override String get category => throw new UnimplementedError(); @override bool get isDart2JsLibrary => throw new UnimplementedError(); @override bool get isDocumented => throw new UnimplementedError(); @override bool get isImplementation => throw new UnimplementedError(); @override bool get isInternal => shortName.startsWith('dart:_'); @override bool get isShared => throw new UnimplementedError(); @override bool get isVmLibrary => throw new UnimplementedError(); @override String get path => units[0].path; @override String get shortName => units[0].uriStr; MockSdkLibrary _toProvider(MemoryResourceProvider provider) { return MockSdkLibrary( units.map((unit) => unit._toProvider(provider)).toList(), ); } } class MockSdkLibraryUnit { final String uriStr; final String path; final String content; MockSdkLibraryUnit(this.uriStr, this.path, this.content); MockSdkLibraryUnit _toProvider(MemoryResourceProvider provider) { return MockSdkLibraryUnit( uriStr, provider.convertPath(path), content, ); } } /** * An [AnalysisContextImpl] that only contains sources for a Dart SDK. */ class _SdkAnalysisContext extends AnalysisContextImpl { final DartSdk sdk; _SdkAnalysisContext(this.sdk); @override AnalysisCache createCacheFromSourceFactory(SourceFactory factory) { if (factory == null) { return super.createCacheFromSourceFactory(factory); } return new AnalysisCache( <CachePartition>[AnalysisEngine.instance.partitionManager.forSdk(sdk)]); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/test_utilities/package_mixin.dart
// Copyright (c) 2019, 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:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/test_utilities/resource_provider_mixin.dart'; /// A mixin for test classes that provides support for creating packages. mixin PackageMixin implements ResourceProviderMixin { /// Return the map from package names to lists of folders that is used to /// resolve 'package:' URIs. Map<String, List<Folder>> get packageMap; /// Create a fake 'js' package that can be used by tests. void addJsPackage() { Folder lib = addPubPackage('js'); newFile(join(lib.path, 'js.dart'), content: r''' library js; class JS { const JS([String js]); } '''); } /// Create a fake 'meta' package that can be used by tests. void addMetaPackage() { Folder lib = addPubPackage('meta'); newFile(join(lib.path, 'meta.dart'), content: r''' library meta; const _AlwaysThrows alwaysThrows = const _AlwaysThrows(); const _Factory factory = const _Factory(); const Immutable immutable = const Immutable(); const _Literal literal = const _Literal(); const _MustCallSuper mustCallSuper = const _MustCallSuper(); const _OptionalTypeArgs optionalTypeArgs = const _OptionalTypeArgs(); const _Protected protected = const _Protected(); const Required required = const Required(); const _Sealed sealed = const _Sealed(); const _VisibleForTesting visibleForTesting = const _VisibleForTesting(); class Immutable { final String reason; const Immutable([this.reason]); } class _AlwaysThrows { const _AlwaysThrows(); } class _Factory { const _Factory(); } class _Literal { const _Literal(); } class _MustCallSuper { const _MustCallSuper(); } class _OptionalTypeArgs { const _OptionalTypeArgs(); } class _Protected { const _Protected(); } class Required { final String reason; const Required([this.reason]); } class _Sealed { const _Sealed(); } class _VisibleForTesting { const _VisibleForTesting(); } '''); } /// Return a newly created directory in which the contents of a pub package /// with the given [packageName] can be written. The package will be added to /// the package map so that the package can be referenced from the code being /// analyzed. Folder addPubPackage(String packageName) { // TODO(brianwilkerson) Consider renaming this to `addPackage` and passing // in a `PackageStyle` (pub, bazel, gn, build, plain) in order to support // creating other styles of packages. Folder lib = getFolder('/.pub-cache/$packageName/lib'); packageMap[packageName] = [lib]; return lib; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/test_utilities/resource_provider_mixin.dart
// Copyright (c) 2017, 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:analyzer/file_system/file_system.dart'; import 'package:analyzer/file_system/memory_file_system.dart'; import 'package:analyzer/src/dart/analysis/context_locator.dart'; /** * A mixin for test classes that adds a [ResourceProvider] and utility methods * for manipulating the file system. The utility methods all take a posix style * path and convert it as appropriate for the actual platform. */ mixin ResourceProviderMixin { MemoryResourceProvider resourceProvider = new MemoryResourceProvider(); String convertPath(String path) => resourceProvider.convertPath(path); void deleteFile(String path) { String convertedPath = convertPath(path); resourceProvider.deleteFile(convertedPath); } void deleteFolder(String path) { String convertedPath = convertPath(path); resourceProvider.deleteFolder(convertedPath); } File getFile(String path) { String convertedPath = convertPath(path); return resourceProvider.getFile(convertedPath); } Folder getFolder(String path) { String convertedPath = convertPath(path); return resourceProvider.getFolder(convertedPath); } String join(String part1, [String part2, String part3, String part4, String part5, String part6, String part7, String part8]) => resourceProvider.pathContext .join(part1, part2, part3, part4, part5, part6, part7, part8); void modifyFile(String path, String content) { String convertedPath = convertPath(path); resourceProvider.modifyFile(convertedPath, content); } File newFile(String path, {String content = ''}) { String convertedPath = convertPath(path); return resourceProvider.newFile(convertedPath, content); } File newFileWithBytes(String path, List<int> bytes) { String convertedPath = convertPath(path); return resourceProvider.newFileWithBytes(convertedPath, bytes); } Folder newFolder(String path) { String convertedPath = convertPath(path); return resourceProvider.newFolder(convertedPath); } File newOptionsFile(String directoryPath, {String content = ''}) { String path = join(directoryPath, ContextLocatorImpl.ANALYSIS_OPTIONS_NAME); return newFile(path, content: content); } File newPackagesFile(String directoryPath) { String path = join(directoryPath, ContextLocatorImpl.PACKAGES_FILE_NAME); return newFile(path); } Uri toUri(String path) { path = convertPath(path); return resourceProvider.pathContext.toUri(path); } String toUriStr(String path) { return toUri(path).toString(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/diagnostic/diagnostic.dart
// Copyright (c) 2019, 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:analyzer/diagnostic/diagnostic.dart'; import 'package:meta/meta.dart'; /// A concrete implementation of a diagnostic message. class DiagnosticMessageImpl implements DiagnosticMessage { @override final String filePath; @override final int length; @override final String message; @override final int offset; /// Initialize a newly created message to represent a [message] reported in /// the file at the given [filePath] at the given [offset] and with the given /// [length]. DiagnosticMessageImpl( {@required this.filePath, @required this.length, @required this.message, @required this.offset}); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/diagnostic/diagnostic_factory.dart
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/diagnostic/diagnostic.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/source/line_info.dart'; import 'package:analyzer/src/diagnostic/diagnostic.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/source.dart'; /// A factory used to create diagnostics. class DiagnosticFactory { /// Initialize a newly created diagnostic factory. DiagnosticFactory(); /// Return a diagnostic indicating that the [duplicateElement] (in a constant /// set) is a duplicate of the [originalElement]. AnalysisError equalElementsInConstSet( Source source, Expression duplicateElement, Expression originalElement) { return new AnalysisError( source, duplicateElement.offset, duplicateElement.length, CompileTimeErrorCode.EQUAL_ELEMENTS_IN_CONST_SET, [], [ new DiagnosticMessageImpl( filePath: source.fullName, message: "The first element with this value.", offset: originalElement.offset, length: originalElement.length) ]); } /// Return a diagnostic indicating that the [duplicateKey] (in a constant map) /// is a duplicate of the [originalKey]. AnalysisError equalKeysInConstMap( Source source, Expression duplicateKey, Expression originalKey) { return new AnalysisError(source, duplicateKey.offset, duplicateKey.length, CompileTimeErrorCode.EQUAL_KEYS_IN_CONST_MAP, [], [ new DiagnosticMessageImpl( filePath: source.fullName, message: "The first key with this value.", offset: originalKey.offset, length: originalKey.length) ]); } /// Return a diagnostic indicating that the given [identifier] was referenced /// before it was declared. AnalysisError referencedBeforeDeclaration( Source source, Identifier identifier, {Element element}) { String name = identifier.name; Element staticElement = element ?? identifier.staticElement; List<DiagnosticMessage> contextMessages; int declarationOffset = staticElement.nameOffset; if (declarationOffset >= 0 && staticElement != null) { CompilationUnitElement unit = staticElement .getAncestor((element) => element is CompilationUnitElement); CharacterLocation location = unit.lineInfo.getLocation(declarationOffset); contextMessages = [ new DiagnosticMessageImpl( filePath: source.fullName, message: "The declaration of '$name' is on line ${location.lineNumber}.", offset: declarationOffset, length: staticElement.nameLength) ]; } return new AnalysisError( source, identifier.offset, identifier.length, CompileTimeErrorCode.REFERENCED_BEFORE_DECLARATION, [name], contextMessages ?? const []); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task/strong_mode.dart
// Copyright (c) 2015, 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/inheritance_manager3.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/resolver.dart' show TypeProvider; import 'package:analyzer/src/summary/format.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'package:analyzer/src/summary2/lazy_ast.dart'; /** * Sets the type of the field. The types in implicit accessors are updated * implicitly, and the types of explicit accessors should be updated separately. */ void setFieldType(VariableElement field, DartType newType) { (field as VariableElementImpl).type = newType; } /** * A function that returns `true` if the given [element] passes the filter. */ typedef bool VariableFilter(VariableElement element); /** * An object used to infer the type of instance fields and the return types of * instance methods within a single compilation unit. */ class InstanceMemberInferrer { final TypeProvider typeProvider; final InheritanceManager3 inheritance; final Set<ClassElement> elementsBeingInferred = new HashSet<ClassElement>(); InterfaceType interfaceType; /** * Initialize a newly create inferrer. */ InstanceMemberInferrer(this.typeProvider, this.inheritance); /** * Infer type information for all of the instance members in the given * compilation [unit]. */ void inferCompilationUnit(CompilationUnitElement unit) { _inferClasses(unit.mixins); _inferClasses(unit.types); } /** * Return `true` if the elements corresponding to the [elements] have the same * kind as the [element]. */ bool _allSameElementKind( ExecutableElement element, List<ExecutableElement> elements) { var elementKind = element.kind; for (int i = 0; i < elements.length; i++) { if (elements[i].kind != elementKind) { return false; } } return true; } /** * Compute the inferred type for the given property [accessor]. The returned * value is never `null`, but might be an error, and/or have the `null` type. */ _FieldOverrideInferenceResult _computeFieldOverrideType( PropertyAccessorElement accessor) { String name = accessor.displayName; var overriddenGetters = inheritance.getOverridden( interfaceType, new Name(accessor.library.source.uri, name), ); List<ExecutableElement> overriddenSetters; if (overriddenGetters == null || !accessor.variable.isFinal) { overriddenSetters = inheritance.getOverridden( interfaceType, new Name(accessor.library.source.uri, '$name='), ); } // Choose overridden members from getters or/and setters. List<ExecutableElement> overriddenElements = <ExecutableElement>[]; if (overriddenGetters == null && overriddenSetters == null) { overriddenElements = const <ExecutableElement>[]; } else if (overriddenGetters == null && overriddenSetters != null) { overriddenElements = overriddenSetters; } else if (overriddenGetters != null && overriddenSetters == null) { overriddenElements = overriddenGetters; } else { overriddenElements = <ExecutableElement>[] ..addAll(overriddenGetters) ..addAll(overriddenSetters); } bool isCovariant = false; DartType impliedType; for (ExecutableElement overriddenElement in overriddenElements) { var overriddenElementKind = overriddenElement.kind; if (overriddenElement == null) { return new _FieldOverrideInferenceResult(false, null, true); } DartType type; if (overriddenElementKind == ElementKind.GETTER) { type = overriddenElement.returnType; } else if (overriddenElementKind == ElementKind.SETTER) { if (overriddenElement.parameters.length == 1) { ParameterElement parameter = overriddenElement.parameters[0]; type = parameter.type; isCovariant = isCovariant || parameter.isCovariant; } } else { return new _FieldOverrideInferenceResult(false, null, true); } if (impliedType == null) { impliedType = type; } else if (type != impliedType) { return new _FieldOverrideInferenceResult(false, null, true); } } return new _FieldOverrideInferenceResult(isCovariant, impliedType, false); } /** * Compute the best type for the [parameter] at the given [index] that must be * compatible with the types of the corresponding parameters of the given * [overriddenTypes]. * * At the moment, this method will only return a type other than 'dynamic' if * the types of all of the parameters are the same. In the future we might * want to be smarter about it, such as by returning the least upper bound of * the parameter types. */ DartType _computeParameterType(ParameterElement parameter, int index, List<FunctionType> overriddenTypes) { DartType parameterType; int length = overriddenTypes.length; for (int i = 0; i < length; i++) { ParameterElement matchingParameter = _getCorrespondingParameter( parameter, index, overriddenTypes[i].parameters); DartType type = matchingParameter?.type ?? typeProvider.dynamicType; if (parameterType == null) { parameterType = type; } else if (parameterType != type) { if (parameter is ParameterElementImpl && parameter.linkedNode != null) { LazyAst.setTypeInferenceError( parameter.linkedNode, TopLevelInferenceErrorBuilder( kind: TopLevelInferenceErrorKind.overrideConflictParameterType, ), ); } return typeProvider.dynamicType; } } return parameterType ?? typeProvider.dynamicType; } /** * Compute the best return type for a method that must be compatible with the * return types of each of the given [overriddenReturnTypes]. * * At the moment, this method will only return a type other than 'dynamic' if * the return types of all of the methods are the same. In the future we might * want to be smarter about it. */ DartType _computeReturnType(Iterable<DartType> overriddenReturnTypes) { DartType returnType; for (DartType type in overriddenReturnTypes) { if (type == null) { type = typeProvider.dynamicType; } if (returnType == null) { returnType = type; } else if (returnType != type) { return typeProvider.dynamicType; } } return returnType ?? typeProvider.dynamicType; } /** * Given a method, return the parameter in the method that corresponds to the * given [parameter]. If the parameter is positional, then * it appears at the given [index] in its enclosing element's list of * parameters. */ ParameterElement _getCorrespondingParameter(ParameterElement parameter, int index, List<ParameterElement> methodParameters) { // // Find the corresponding parameter. // if (parameter.isNamed) { // // If we're looking for a named parameter, only a named parameter with // the same name will be matched. // return methodParameters.lastWhere( (ParameterElement methodParameter) => methodParameter.isNamed && methodParameter.name == parameter.name, orElse: () => null); } // // If we're looking for a positional parameter we ignore the difference // between required and optional parameters. // if (index < methodParameters.length) { var matchingParameter = methodParameters[index]; if (!matchingParameter.isNamed) { return matchingParameter; } } return null; } /** * If the given [element] represents a non-synthetic instance property * accessor for which no type was provided, infer its types. */ void _inferAccessor(PropertyAccessorElement element) { if (element.isSynthetic || element.isStatic) { return; } if (element.kind == ElementKind.GETTER && !element.hasImplicitReturnType) { return; } _FieldOverrideInferenceResult typeResult = _computeFieldOverrideType(element); if (typeResult.isError == null || typeResult.type == null) { return; } if (element.kind == ElementKind.GETTER) { (element as ExecutableElementImpl).returnType = typeResult.type; } else if (element.kind == ElementKind.SETTER) { List<ParameterElement> parameters = element.parameters; if (parameters.isNotEmpty) { var parameter = parameters[0] as ParameterElementImpl; if (parameter.hasImplicitType) { parameter.type = typeResult.type; } parameter.inheritsCovariant = typeResult.isCovariant; } } setFieldType(element.variable, typeResult.type); } /** * Infer type information for all of the instance members in the given * [classElement]. */ void _inferClass(ClassElement classElement) { if (classElement is ClassElementImpl) { if (classElement.hasBeenInferred) { return; } if (!elementsBeingInferred.add(classElement)) { // We have found a circularity in the class hierarchy. For now we just // stop trying to infer any type information for any classes that // inherit from any class in the cycle. We could potentially limit the // algorithm to only not inferring types in the classes in the cycle, // but it isn't clear that the results would be significantly better. throw new _CycleException(); } try { // // Ensure that all of instance members in the supertypes have had types // inferred for them. // _inferType(classElement.supertype); classElement.mixins.forEach(_inferType); classElement.interfaces.forEach(_inferType); classElement.superclassConstraints.forEach(_inferType); // // Then infer the types for the members. // this.interfaceType = classElement.thisType; for (FieldElement field in classElement.fields) { _inferField(field); } for (PropertyAccessorElement accessor in classElement.accessors) { _inferAccessor(accessor); } for (MethodElement method in classElement.methods) { _inferExecutable(method); } // // Infer initializing formal parameter types. This must happen after // field types are inferred. // classElement.constructors.forEach(_inferConstructorFieldFormals); classElement.hasBeenInferred = true; } finally { elementsBeingInferred.remove(classElement); } } } void _inferClasses(List<ClassElement> elements) { for (ClassElement element in elements) { try { _inferClass(element); } on _CycleException { // This is a short circuit return to prevent types that inherit from // types containing a circular reference from being inferred. } } } void _inferConstructorFieldFormals(ConstructorElement constructor) { for (ParameterElement parameter in constructor.parameters) { if (parameter.hasImplicitType && parameter is FieldFormalParameterElementImpl) { FieldElement field = parameter.field; if (field != null) { parameter.type = field.type; } } } } /** * If the given [element] represents a non-synthetic instance method, * getter or setter, infer the return type and any parameter type(s) where * they were not provided. */ void _inferExecutable(ExecutableElement element) { if (element.isSynthetic || element.isStatic) { return; } // TODO(scheglov) If no implicit types, don't ask inherited. List<ExecutableElement> overriddenElements = inheritance.getOverridden( interfaceType, new Name(element.library.source.uri, element.name), ); if (overriddenElements == null || !_allSameElementKind(element, overriddenElements)) { return; } List<FunctionType> overriddenTypes = _toOverriddenFunctionTypes(element, overriddenElements); if (overriddenTypes.isEmpty) { return; } // // Infer the return type. // if (element.hasImplicitReturnType && element.displayName != '[]=') { (element as ExecutableElementImpl).returnType = _computeReturnType(overriddenTypes.map((t) => t.returnType)); if (element is PropertyAccessorElement) { _updateSyntheticVariableType(element); } } // // Infer the parameter types. // List<ParameterElement> parameters = element.parameters; int length = parameters.length; for (int i = 0; i < length; ++i) { ParameterElement parameter = parameters[i]; if (parameter is ParameterElementImpl) { _inferParameterCovariance(parameter, i, overriddenTypes); if (parameter.hasImplicitType) { parameter.type = _computeParameterType(parameter, i, overriddenTypes); if (element is PropertyAccessorElement) { _updateSyntheticVariableType(element); } } } } } /** * If the given [field] represents a non-synthetic instance field for * which no type was provided, infer the type of the field. */ void _inferField(FieldElement field) { if (field.isSynthetic || field.isStatic) { return; } _FieldOverrideInferenceResult typeResult = _computeFieldOverrideType(field.getter); if (typeResult.isError) { if (field is FieldElementImpl && field.linkedNode != null) { LazyAst.setTypeInferenceError( field.linkedNode, TopLevelInferenceErrorBuilder( kind: TopLevelInferenceErrorKind.overrideConflictFieldType, ), ); } return; } if (field.hasImplicitType) { DartType newType = typeResult.type; if (newType == null) { var initializer = field.initializer; if (initializer != null) { newType = initializer.returnType; } } if (newType == null || newType.isBottom || newType.isDartCoreNull) { newType = typeProvider.dynamicType; } setFieldType(field, newType); } if (field.setter != null) { var parameter = field.setter.parameters[0] as ParameterElementImpl; parameter.inheritsCovariant = typeResult.isCovariant; } } /** * If a parameter is covariant, any parameters that override it are too. */ void _inferParameterCovariance(ParameterElementImpl parameter, int index, Iterable<FunctionType> overriddenTypes) { parameter.inheritsCovariant = overriddenTypes.any((f) { var param = _getCorrespondingParameter(parameter, index, f.parameters); return param != null && param.isCovariant; }); } /** * Infer type information for all of the instance members in the given * interface [type]. */ void _inferType(InterfaceType type) { if (type != null) { ClassElement element = type.element; if (element != null) { _inferClass(element); } } } /** * Return the [FunctionType] of the [overriddenElement] that [element] * overrides. Return `null`, in case of type parameters inconsistency. * * The overridden element must have the same number of generic type * parameters as the target element, or none. * * If we do have generic type parameters on the element we're inferring, * we must express its parameter and return types in terms of its own * parameters. For example, given `m<T>(t)` overriding `m<S>(S s)` we * should infer this as `m<T>(T t)`. */ FunctionType _toOverriddenFunctionType( ExecutableElement element, ExecutableElement overriddenElement) { List<DartType> typeFormals = TypeParameterTypeImpl.getTypes(element.type.typeFormals); FunctionType overriddenType = overriddenElement.type; if (overriddenType.typeFormals.isNotEmpty) { if (overriddenType.typeFormals.length != typeFormals.length) { return null; } overriddenType = overriddenType.instantiate(typeFormals); } return overriddenType; } /** * Return [FunctionType]s of [overriddenElements] that override [element]. * Return the empty list, in case of type parameters inconsistency. */ List<FunctionType> _toOverriddenFunctionTypes( ExecutableElement element, List<ExecutableElement> overriddenElements) { var overriddenTypes = <FunctionType>[]; for (ExecutableElement overriddenElement in overriddenElements) { FunctionType overriddenType = _toOverriddenFunctionType(element, overriddenElement); if (overriddenType == null) { return const <FunctionType>[]; } overriddenTypes.add(overriddenType); } return overriddenTypes; } /** * If the given [element] is a non-synthetic getter or setter, update its * synthetic variable's type to match the getter's return type, or if no * corresponding getter exists, use the setter's parameter type. * * In general, the type of the synthetic variable should not be used, because * getters and setters are independent methods. But this logic matches what * `TypeResolverVisitor.visitMethodDeclaration` would fill in there. */ void _updateSyntheticVariableType(PropertyAccessorElement element) { assert(!element.isSynthetic); PropertyAccessorElement getter = element; if (element.isSetter) { // See if we can find any getter. getter = element.correspondingGetter; } DartType newType; if (getter != null) { newType = getter.returnType; } else if (element.isSetter && element.parameters.isNotEmpty) { newType = element.parameters[0].type; } if (newType != null) { (element.variable as VariableElementImpl).type = newType; } } } /** * A visitor that will gather all of the variables referenced within a given * AST structure. The collection can be restricted to contain only those * variables that pass a specified filter. */ class VariableGatherer extends RecursiveAstVisitor { /** * The filter used to limit which variables are gathered, or `null` if no * filtering is to be performed. */ final VariableFilter filter; /** * The variables that were found. */ final Set<VariableElement> results = new HashSet<VariableElement>(); /** * Initialize a newly created gatherer to gather all of the variables that * pass the given [filter] (or all variables if no filter is provided). */ VariableGatherer([this.filter]); @override void visitSimpleIdentifier(SimpleIdentifier node) { if (!node.inDeclarationContext()) { Element nonAccessor(Element element) { if (element is PropertyAccessorElement && element.isSynthetic) { return element.variable; } return element; } Element element = nonAccessor(node.staticElement); if (element is VariableElement && (filter == null || filter(element))) { results.add(element); } } } } /** * A class of exception that is not used anywhere else. */ class _CycleException implements Exception {} /** * The result of field type inference. */ class _FieldOverrideInferenceResult { final bool isCovariant; final DartType type; final bool isError; _FieldOverrideInferenceResult(this.isCovariant, this.type, this.isError); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task/options.dart
// Copyright (c) 2015, 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 'dart:collection'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/source/error_processor.dart'; import 'package:analyzer/src/analysis_options/analysis_options_provider.dart'; import 'package:analyzer/src/analysis_options/error/option_codes.dart'; import 'package:analyzer/src/dart/analysis/experiments.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/java_engine.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/generated/utilities_general.dart'; import 'package:analyzer/src/lint/config.dart'; import 'package:analyzer/src/lint/linter.dart'; import 'package:analyzer/src/lint/options_rule_validator.dart'; import 'package:analyzer/src/lint/registry.dart'; import 'package:analyzer/src/plugin/options.dart'; import 'package:analyzer/src/util/yaml.dart'; import 'package:source_span/source_span.dart'; import 'package:yaml/yaml.dart'; final _OptionsProcessor _processor = new _OptionsProcessor(); List<AnalysisError> analyzeAnalysisOptions( Source source, String content, SourceFactory sourceFactory) { List<AnalysisError> errors = <AnalysisError>[]; Source initialSource = source; SourceSpan initialIncludeSpan; AnalysisOptionsProvider optionsProvider = new AnalysisOptionsProvider(sourceFactory); // Validate the specified options and any included option files void validate(Source source, YamlMap options) { List<AnalysisError> validationErrors = new OptionsFileValidator(source).validate(options); if (initialIncludeSpan != null && validationErrors.isNotEmpty) { for (AnalysisError error in validationErrors) { var args = [ source.fullName, error.offset.toString(), (error.offset + error.length - 1).toString(), error.message, ]; errors.add(new AnalysisError( initialSource, initialIncludeSpan.start.column + 1, initialIncludeSpan.length, AnalysisOptionsWarningCode.INCLUDED_FILE_WARNING, args)); } } else { errors.addAll(validationErrors); } YamlNode node = getValue(options, AnalyzerOptions.include); if (node == null) { return; } SourceSpan span = node.span; initialIncludeSpan ??= span; String includeUri = span.text; Source includedSource = sourceFactory.resolveUri(source, includeUri); if (includedSource == null || !includedSource.exists()) { errors.add(new AnalysisError( initialSource, initialIncludeSpan.start.column + 1, initialIncludeSpan.length, AnalysisOptionsWarningCode.INCLUDE_FILE_NOT_FOUND, [includeUri, source.fullName])); return; } try { YamlMap options = optionsProvider.getOptionsFromString(includedSource.contents.data); validate(includedSource, options); } on OptionsFormatException catch (e) { var args = [ includedSource.fullName, e.span.start.offset.toString(), e.span.end.offset.toString(), e.message, ]; // Report errors for included option files // on the include directive located in the initial options file. errors.add(new AnalysisError( initialSource, initialIncludeSpan.start.column + 1, initialIncludeSpan.length, AnalysisOptionsErrorCode.INCLUDED_FILE_PARSE_ERROR, args)); } } try { YamlMap options = optionsProvider.getOptionsFromString(content); validate(source, options); } on OptionsFormatException catch (e) { SourceSpan span = e.span; errors.add(new AnalysisError(source, span.start.column + 1, span.length, AnalysisOptionsErrorCode.PARSE_ERROR, [e.message])); } return errors; } void applyToAnalysisOptions(AnalysisOptionsImpl options, YamlMap optionMap) { _processor.applyToAnalysisOptions(options, optionMap); } /// `analyzer` analysis options constants. class AnalyzerOptions { static const String analyzer = 'analyzer'; static const String enableSuperMixins = 'enableSuperMixins'; static const String enablePreviewDart2 = 'enablePreviewDart2'; static const String enableExperiment = 'enable-experiment'; static const String errors = 'errors'; static const String exclude = 'exclude'; static const String include = 'include'; static const String language = 'language'; static const String optionalChecks = 'optional-checks'; static const String plugins = 'plugins'; static const String strong_mode = 'strong-mode'; // Optional checks options. static const String chromeOsManifestChecks = 'chrome-os-manifest-checks'; // Strong mode options (see AnalysisOptionsImpl for documentation). static const String declarationCasts = 'declaration-casts'; static const String implicitCasts = 'implicit-casts'; static const String implicitDynamic = 'implicit-dynamic'; // Language options (see AnalysisOptionsImpl for documentation). static const String strictInference = 'strict-inference'; static const String strictRawTypes = 'strict-raw-types'; /// Ways to say `ignore`. static const List<String> ignoreSynonyms = const ['ignore', 'false']; /// Valid error `severity`s. static final List<String> severities = new List.unmodifiable(severityMap.keys); /// Ways to say `include`. static const List<String> includeSynonyms = const ['include', 'true']; /// Ways to say `true` or `false`. static const List<String> trueOrFalse = const ['true', 'false']; /// Supported top-level `analyzer` options. static const List<String> topLevel = const [ enableExperiment, errors, exclude, language, optionalChecks, plugins, strong_mode, ]; /// Supported `analyzer` strong-mode options. static const List<String> strongModeOptions = const [ declarationCasts, // deprecated implicitCasts, implicitDynamic, ]; /// Supported `analyzer` language options. static const List<String> languageOptions = const [ strictInference, strictRawTypes ]; // Supported 'analyzer' optional checks options. static const List<String> optionalChecksOptions = const [ chromeOsManifestChecks, ]; } /// Validates `analyzer` options. class AnalyzerOptionsValidator extends CompositeValidator { AnalyzerOptionsValidator() : super([ new TopLevelAnalyzerOptionsValidator(), new StrongModeOptionValueValidator(), new ErrorFilterOptionValidator(), new EnabledExperimentsValidator(), new LanguageOptionValidator(), new OptionalChecksValueValidator() ]); } /// Convenience class for composing validators. class CompositeValidator extends OptionsValidator { final List<OptionsValidator> validators; CompositeValidator(this.validators); @override void validate(ErrorReporter reporter, YamlMap options) => validators.forEach((v) => v.validate(reporter, options)); } /// Validates `analyzer` language configuration options. class EnabledExperimentsValidator extends OptionsValidator { ErrorBuilder builder = new ErrorBuilder(AnalyzerOptions.languageOptions); ErrorBuilder trueOrFalseBuilder = new TrueOrFalseValueErrorBuilder(); @override void validate(ErrorReporter reporter, YamlMap options) { var analyzer = getValue(options, AnalyzerOptions.analyzer); if (analyzer is YamlMap) { var experimentNames = getValue(analyzer, AnalyzerOptions.enableExperiment); if (experimentNames is YamlList) { var flags = experimentNames.nodes.map((node) => node.toString()).toList(); for (var validationResult in validateFlags(flags)) { var flagIndex = validationResult.stringIndex; var span = experimentNames.nodes[flagIndex].span; if (validationResult is UnrecognizedFlag) { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITHOUT_VALUES, span, [AnalyzerOptions.enableExperiment, flags[flagIndex]]); } else { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.INVALID_OPTION, span, [AnalyzerOptions.enableExperiment, validationResult.message]); } } } else if (experimentNames != null) { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.INVALID_SECTION_FORMAT, experimentNames.span, [AnalyzerOptions.enableExperiment]); } } } } /// Builds error reports with value proposals. class ErrorBuilder { String proposal; AnalysisOptionsWarningCode code; /// Create a builder for the given [supportedOptions]. ErrorBuilder(List<String> supportedOptions) { assert(supportedOptions != null); if (supportedOptions.isEmpty) { code = noProposalCode; } else if (supportedOptions.length == 1) { proposal = "'${supportedOptions.join()}'"; code = singularProposalCode; } else { proposal = StringUtilities.printListOfQuotedNames(supportedOptions); code = pluralProposalCode; } } AnalysisOptionsWarningCode get noProposalCode => AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITHOUT_VALUES; AnalysisOptionsWarningCode get pluralProposalCode => AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES; AnalysisOptionsWarningCode get singularProposalCode => AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE; /// Report an unsupported [node] value, defined in the given [scopeName]. void reportError(ErrorReporter reporter, String scopeName, YamlNode node) { if (proposal != null) { reporter.reportErrorForSpan( code, node.span, [scopeName, node.value, proposal]); } else { reporter.reportErrorForSpan(code, node.span, [scopeName, node.value]); } } } /// Validates `analyzer` error filter options. class ErrorFilterOptionValidator extends OptionsValidator { /// Legal values. static final List<String> legalValues = new List.from(AnalyzerOptions.ignoreSynonyms) ..addAll(AnalyzerOptions.includeSynonyms) ..addAll(AnalyzerOptions.severities); /// Pretty String listing legal values. static final String legalValueString = StringUtilities.printListOfQuotedNames(legalValues); /// Lazily populated set of error codes (hashed for speedy lookup). static HashSet<String> _errorCodes; /// Legal error code names. static Set<String> get errorCodes { if (_errorCodes == null) { _errorCodes = new HashSet<String>(); // Engine codes. _errorCodes.addAll(errorCodeValues.map((ErrorCode code) => code.name)); } return _errorCodes; } /// Lazily populated set of lint codes. Set<String> _lintCodes; Set<String> get lintCodes { if (_lintCodes == null) { _lintCodes = new Set.from( Registry.ruleRegistry.rules.map((rule) => rule.name.toUpperCase())); } return _lintCodes; } @override void validate(ErrorReporter reporter, YamlMap options) { var analyzer = getValue(options, AnalyzerOptions.analyzer); if (analyzer is YamlMap) { var filters = getValue(analyzer, AnalyzerOptions.errors); if (filters is YamlMap) { String value; filters.nodes.forEach((k, v) { if (k is YamlScalar) { value = toUpperCase(k.value); if (!errorCodes.contains(value) && !lintCodes.contains(value)) { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.UNRECOGNIZED_ERROR_CODE, k.span, [k.value?.toString()]); } } if (v is YamlScalar) { value = toLowerCase(v.value); if (!legalValues.contains(value)) { reporter.reportErrorForSpan( AnalysisOptionsWarningCode .UNSUPPORTED_OPTION_WITH_LEGAL_VALUES, v.span, [ AnalyzerOptions.errors, v.value?.toString(), legalValueString ]); } } }); } } } } /// Validates `analyzer` language configuration options. class LanguageOptionValidator extends OptionsValidator { ErrorBuilder builder = new ErrorBuilder(AnalyzerOptions.languageOptions); ErrorBuilder trueOrFalseBuilder = new TrueOrFalseValueErrorBuilder(); @override void validate(ErrorReporter reporter, YamlMap options) { var analyzer = getValue(options, AnalyzerOptions.analyzer); if (analyzer is YamlMap) { var language = getValue(analyzer, AnalyzerOptions.language); if (language is YamlMap) { language.nodes.forEach((k, v) { String key, value; bool validKey = false; if (k is YamlScalar) { key = k.value?.toString(); if (AnalyzerOptions.enablePreviewDart2 == key) { reporter.reportErrorForSpan( AnalysisOptionsHintCode.PREVIEW_DART_2_SETTING_DEPRECATED, k.span); } else if (AnalyzerOptions.enableSuperMixins == key) { reporter.reportErrorForSpan( AnalysisOptionsHintCode.SUPER_MIXINS_SETTING_DEPRECATED, k.span); } else if (!AnalyzerOptions.languageOptions.contains(key)) { builder.reportError(reporter, AnalyzerOptions.language, k); } else { // If we have a valid key, go on and check the value. validKey = true; } } if (validKey && v is YamlScalar) { value = toLowerCase(v.value); if (!AnalyzerOptions.trueOrFalse.contains(value)) { trueOrFalseBuilder.reportError(reporter, key, v); } } }); } else if (language is YamlScalar && language.value != null) { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.INVALID_SECTION_FORMAT, language.span, [AnalyzerOptions.language]); } else if (language is YamlList) { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.INVALID_SECTION_FORMAT, language.span, [AnalyzerOptions.language]); } } } } /// Validates `linter` top-level options. /// TODO(pq): move into `linter` package and plugin. class LinterOptionsValidator extends TopLevelOptionValidator { LinterOptionsValidator() : super('linter', const ['rules']); } /// Validates options defined in an analysis options file. class OptionsFileValidator { /// The source being validated. final Source source; final List<OptionsValidator> _validators = [ new AnalyzerOptionsValidator(), new LinterOptionsValidator(), new LinterRuleOptionsValidator() ]; OptionsFileValidator(this.source); List<AnalysisError> validate(YamlMap options) { RecordingErrorListener recorder = new RecordingErrorListener(); ErrorReporter reporter = new ErrorReporter(recorder, source); if (AnalysisEngine.ANALYSIS_OPTIONS_FILE == source.shortName) { reporter.reportError(new AnalysisError( source, 0, // offset 1, // length AnalysisOptionsHintCode.DEPRECATED_ANALYSIS_OPTIONS_FILE_NAME, [source.shortName])); } _validators.forEach((OptionsValidator v) => v.validate(reporter, options)); return recorder.errors; } } /// Validates `analyzer` strong-mode value configuration options. class StrongModeOptionValueValidator extends OptionsValidator { ErrorBuilder builder = new ErrorBuilder(AnalyzerOptions.strongModeOptions); ErrorBuilder trueOrFalseBuilder = new TrueOrFalseValueErrorBuilder(); @override void validate(ErrorReporter reporter, YamlMap options) { var analyzer = getValue(options, AnalyzerOptions.analyzer); if (analyzer is YamlMap) { var v = getValue(analyzer, AnalyzerOptions.strong_mode); if (v is YamlScalar) { var value = toLowerCase(v.value); if (!AnalyzerOptions.trueOrFalse.contains(value)) { trueOrFalseBuilder.reportError( reporter, AnalyzerOptions.strong_mode, v); } else if (value == 'false') { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.SPEC_MODE_REMOVED, v.span); } else if (value == 'true') { reporter.reportErrorForSpan( AnalysisOptionsHintCode.STRONG_MODE_SETTING_DEPRECATED, v.span); } } else if (v is YamlMap) { v.nodes.forEach((k, v) { String key, value; bool validKey = false; if (k is YamlScalar) { key = k.value?.toString(); if (!AnalyzerOptions.strongModeOptions.contains(key)) { builder.reportError(reporter, AnalyzerOptions.strong_mode, k); } else if (key == AnalyzerOptions.declarationCasts) { reporter.reportErrorForSpan( AnalysisOptionsWarningCode.ANALYSIS_OPTION_DEPRECATED, k.span, [key]); } else { // If we have a valid key, go on and check the value. validKey = true; } } if (validKey && v is YamlScalar) { value = toLowerCase(v.value); if (!AnalyzerOptions.trueOrFalse.contains(value)) { trueOrFalseBuilder.reportError(reporter, key, v); } } }); } } } } /// Validates `analyzer` optional-checks value configuration options. class OptionalChecksValueValidator extends OptionsValidator { ErrorBuilder builder = new ErrorBuilder(AnalyzerOptions.optionalChecksOptions); ErrorBuilder trueOrFalseBuilder = new TrueOrFalseValueErrorBuilder(); @override void validate(ErrorReporter reporter, YamlMap options) { var analyzer = getValue(options, AnalyzerOptions.analyzer); if (analyzer is YamlMap) { var v = getValue(analyzer, AnalyzerOptions.optionalChecks); if (v is YamlScalar) { var value = toLowerCase(v.value); if (value != AnalyzerOptions.chromeOsManifestChecks) { builder.reportError( reporter, AnalyzerOptions.chromeOsManifestChecks, v); } } else if (v is YamlMap) { v.nodes.forEach((k, v) { String key, value; if (k is YamlScalar) { key = k.value?.toString(); if (key != AnalyzerOptions.chromeOsManifestChecks) { builder.reportError( reporter, AnalyzerOptions.chromeOsManifestChecks, k); } else { value = toLowerCase(v.value); if (!AnalyzerOptions.trueOrFalse.contains(value)) { trueOrFalseBuilder.reportError(reporter, key, v); } } } }); } } } } /// Validates `analyzer` top-level options. class TopLevelAnalyzerOptionsValidator extends TopLevelOptionValidator { TopLevelAnalyzerOptionsValidator() : super(AnalyzerOptions.analyzer, AnalyzerOptions.topLevel); } /// Validates top-level options. For example, /// plugin: /// top-level-option: true class TopLevelOptionValidator extends OptionsValidator { final String pluginName; final List<String> supportedOptions; String _valueProposal; AnalysisOptionsWarningCode _warningCode; TopLevelOptionValidator(this.pluginName, this.supportedOptions) { assert(supportedOptions != null && supportedOptions.isNotEmpty); if (supportedOptions.length > 1) { _valueProposal = StringUtilities.printListOfQuotedNames(supportedOptions); _warningCode = AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES; } else { _valueProposal = "'${supportedOptions.join()}'"; _warningCode = AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE; } } @override void validate(ErrorReporter reporter, YamlMap options) { YamlNode node = getValue(options, pluginName); if (node is YamlMap) { node.nodes.forEach((k, v) { if (k is YamlScalar) { if (!supportedOptions.contains(k.value)) { reporter.reportErrorForSpan( _warningCode, k.span, [pluginName, k.value, _valueProposal]); } } //TODO(pq): consider an error if the node is not a Scalar. }); } } } /// An error-builder that knows about `true` and `false` legal values. class TrueOrFalseValueErrorBuilder extends ErrorBuilder { TrueOrFalseValueErrorBuilder() : super(AnalyzerOptions.trueOrFalse); @override AnalysisOptionsWarningCode get pluralProposalCode => AnalysisOptionsWarningCode.UNSUPPORTED_VALUE; } class _OptionsProcessor { static final Map<String, Object> defaults = {'analyzer': {}}; /** * Apply the options in the given [optionMap] to the given analysis [options]. */ void applyToAnalysisOptions(AnalysisOptionsImpl options, YamlMap optionMap) { if (optionMap == null) { return; } var analyzer = getValue(optionMap, AnalyzerOptions.analyzer); if (analyzer is YamlMap) { // Process strong mode option. var strongMode = getValue(analyzer, AnalyzerOptions.strong_mode); _applyStrongOptions(options, strongMode); // Process filters. var filters = getValue(analyzer, AnalyzerOptions.errors); _applyProcessors(options, filters); // Process enabled experiments. var experimentNames = getValue(analyzer, AnalyzerOptions.enableExperiment); if (experimentNames is YamlList) { List<String> enabledExperiments = <String>[]; for (var element in experimentNames.nodes) { String experimentName = _toString(element); if (experimentName != null) { enabledExperiments.add(experimentName); } } options.enabledExperiments = enabledExperiments; } // Process optional checks options. var optionalChecks = getValue(analyzer, AnalyzerOptions.optionalChecks); _applyOptionalChecks(options, optionalChecks); // Process language options. var language = getValue(analyzer, AnalyzerOptions.language); _applyLanguageOptions(options, language); // Process excludes. var excludes = getValue(analyzer, AnalyzerOptions.exclude); _applyExcludes(options, excludes); // Process plugins. var names = getValue(analyzer, AnalyzerOptions.plugins); List<String> pluginNames = <String>[]; String pluginName = _toString(names); if (pluginName != null) { pluginNames.add(pluginName); } else if (names is YamlList) { for (var element in names.nodes) { String pluginName = _toString(element); if (pluginName != null) { pluginNames.add(pluginName); } } } else if (names is YamlMap) { for (var key in names.nodes.keys) { String pluginName = _toString(key); if (pluginName != null) { pluginNames.add(pluginName); } } } options.enabledPluginNames = pluginNames; } LintConfig config = parseConfig(optionMap); if (config != null) { Iterable<LintRule> lintRules = Registry.ruleRegistry.enabled(config); if (lintRules.isNotEmpty) { options.lint = true; options.lintRules = lintRules.toList(); } } } void _applyExcludes(AnalysisOptionsImpl options, YamlNode excludes) { if (excludes is YamlList) { List<String> excludeList = toStringList(excludes); if (excludeList != null) { options.excludePatterns = excludeList; } } } void _applyLanguageOption( AnalysisOptionsImpl options, Object feature, Object value) { bool boolValue = toBool(value); if (boolValue != null) { if (feature == AnalyzerOptions.strictInference) { options.strictInference = boolValue; } if (feature == AnalyzerOptions.strictRawTypes) { options.strictRawTypes = boolValue; } } } void _applyLanguageOptions(AnalysisOptionsImpl options, YamlNode configs) { if (configs is YamlMap) { configs.nodes.forEach((key, value) { if (key is YamlScalar && value is YamlScalar) { String feature = key.value?.toString(); _applyLanguageOption(options, feature, value.value); } }); } } void _applyProcessors(AnalysisOptionsImpl options, YamlNode codes) { ErrorConfig config = new ErrorConfig(codes); options.errorProcessors = config.processors; } void _applyStrongModeOption( AnalysisOptionsImpl options, String feature, Object value) { bool boolValue = toBool(value); if (boolValue != null) { if (feature == AnalyzerOptions.implicitCasts) { options.implicitCasts = boolValue; } if (feature == AnalyzerOptions.implicitDynamic) { options.implicitDynamic = boolValue; } } } void _applyStrongOptions(AnalysisOptionsImpl options, YamlNode config) { if (config is YamlMap) { config.nodes.forEach((k, v) { if (k is YamlScalar && v is YamlScalar) { _applyStrongModeOption(options, k.value?.toString(), v.value); } }); } } void _applyOptionalChecksOption( AnalysisOptionsImpl options, String feature, Object value) { bool boolValue = toBool(value); if (boolValue != null) { if (feature == AnalyzerOptions.chromeOsManifestChecks) { options.chromeOsManifestChecks = boolValue; } } } void _applyOptionalChecks(AnalysisOptionsImpl options, YamlNode config) { if (config is YamlMap) { config.nodes.forEach((k, v) { if (k is YamlScalar && v is YamlScalar) { _applyOptionalChecksOption(options, k.value?.toString(), v.value); } }); } if (config is YamlScalar) { if (config.value?.toString() == AnalyzerOptions.chromeOsManifestChecks) { options.chromeOsManifestChecks = true; } } } String _toString(YamlNode node) { if (node is YamlScalar) { var value = node.value; if (value is String) { return value; } } return null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task/api/model.dart
// Copyright (c) 2015, 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:analyzer/src/generated/source.dart'; /** * An object with which an analysis result can be associated. * * Clients may implement this class when creating new kinds of targets. * Instances of this type are used in hashed data structures, so subtypes are * required to correctly implement [==] and [hashCode]. */ abstract class AnalysisTarget { /** * If this target is associated with a library, return the source of the * library's defining compilation unit; otherwise return `null`. */ Source get librarySource; /** * Return the source associated with this target, or `null` if this target is * not associated with a source. */ Source get source; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task/strong/ast_properties.dart
// 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. /// Properties that result from Strong Mode analysis on an AST. /// /// These properties are not public, but provided by use of back-ends such as /// Dart Dev Compiler. import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; const String _classCovariantParameters = '_classCovariantParameters'; const String _covariantPrivateMembers = '_covariantPrivateMembers'; const String _hasImplicitCasts = '_hasImplicitCasts'; const String _implicitCast = '_implicitCast'; const String _implicitOperationCast = '_implicitAssignmentCast'; const String _implicitSpreadCast = '_implicitSpreadCast'; const String _implicitSpreadKeyCast = '_implicitSpreadKeyCast'; const String _implicitSpreadValueCast = '_implicitSpreadValueCast'; const String _isDynamicInvoke = '_isDynamicInvoke'; const String _superclassCovariantParameters = '_superclassCovariantParameters'; /// Returns a list of parameters and method type parameters in this class /// declaration that need a check at runtime to ensure soundness. Set<Element> getClassCovariantParameters(Declaration node) { return node.getProperty(_classCovariantParameters); } /// Gets the private setters and methods that are accessed unsafely from /// this compilation unit. /// /// These members will require a check. Set<ExecutableElement> getCovariantPrivateMembers(CompilationUnit node) { return node.getProperty(_covariantPrivateMembers); } /// If this expression has an implicit cast, returns the type it is coerced to, /// otherwise returns null. DartType getImplicitCast(Expression node) { return node.getProperty<DartType>(_implicitCast); } /// If this expression needs an implicit cast on a subexpression that cannot be /// expressed anywhere else, returns the type it is coerced to. /// /// For example, op-assign can have an implicit cast on the final assignment, /// and MethodInvocation calls on functions (`obj.f()` where `obj.f` is an /// accessor and not a real method) can need a cast on the function. DartType getImplicitOperationCast(Expression node) { return node.getProperty<DartType>(_implicitOperationCast); } /// If this expression is passed into a spread and the items in the spread need /// an implicit cast, return the type the items are coerced to. DartType getImplicitSpreadCast(Expression node) { return node.getProperty<DartType>(_implicitSpreadCast); } /// If this expression is a map passed into a spread and the keys in the spread /// need an implicit cast, return the type the keys are coerced to. DartType getImplicitSpreadKeyCast(Expression node) { return node.getProperty<DartType>(_implicitSpreadKeyCast); } /// If this expression is a map passed into a spread and the values in the /// spread need an implicit cast, return the type the values are coerced to. DartType getImplicitSpreadValueCast(Expression node) { return node.getProperty<DartType>(_implicitSpreadValueCast); } /// Returns a list of parameters and method type parameters from mixins and /// superclasses of this class that need a stub method to check their type at /// runtime for soundness. Set<Element> getSuperclassCovariantParameters(Declaration node) { return node.getProperty(_superclassCovariantParameters); } /// True if this compilation unit has any implicit casts, otherwise false. /// /// See also [getImplicitCast]. bool hasImplicitCasts(CompilationUnit node) { return node.getProperty<bool>(_hasImplicitCasts) ?? false; } /// True if this node is a dynamic operation that requires dispatch and/or /// checking at runtime. bool isDynamicInvoke(Expression node) { return node.getProperty<bool>(_isDynamicInvoke) ?? false; } /// Sets [getClassCovariantParameters] property for this class. void setClassCovariantParameters(Declaration node, Set<Element> value) { node.setProperty(_classCovariantParameters, value); } /// Sets [getCovariantPrivateMembers] property for this compilation unit. void setCovariantPrivateMembers( CompilationUnit node, Set<ExecutableElement> value) { node.setProperty(_covariantPrivateMembers, value); } /// Sets [hasImplicitCasts] property for this compilation unit. void setHasImplicitCasts(CompilationUnit node, bool value) { node.setProperty(_hasImplicitCasts, value == true ? true : null); } /// Sets the result of [getImplicitCast] for this node. void setImplicitCast(Expression node, DartType type) { node.setProperty(_implicitCast, type); } /// Sets the result of [getImplicitOperationCast] for this node. void setImplicitOperationCast(Expression node, DartType type) { node.setProperty(_implicitOperationCast, type); } /// Sets the result of [getImplicitSpreadCast] for this node. void setImplicitSpreadCast(Expression node, DartType type) { node.setProperty(_implicitSpreadCast, type); } /// Sets the result of [getImplicitSpreadKeyCast] for this node. void setImplicitSpreadKeyCast(Expression node, DartType type) { node.setProperty(_implicitSpreadKeyCast, type); } /// Sets the result of [getImplicitSpreadValueCast] for this node. void setImplicitSpreadValueCast(Expression node, DartType type) { node.setProperty(_implicitSpreadValueCast, type); } /// Sets [isDynamicInvoke] property for this expression. void setIsDynamicInvoke(Expression node, bool value) { node.setProperty(_isDynamicInvoke, value == true ? true : null); } /// Sets [getSuperclassCovariantParameters] property for this class. void setSuperclassCovariantParameters(Declaration node, Set<Element> value) { node.setProperty(_superclassCovariantParameters, value); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/task/strong/checker.dart
// Copyright (c) 2015, 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. // TODO(jmesserly): this was ported from package:dev_compiler, and needs to be // refactored to fit into analyzer. import 'dart:collection'; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart' show TokenType; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/source/error_processor.dart' show ErrorProcessor; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/inheritance_manager3.dart'; import 'package:analyzer/src/dart/element/member.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/element/type_algebra.dart'; import 'package:analyzer/src/error/codes.dart' show StrongModeCode; import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl; import 'package:analyzer/src/generated/resolver.dart' show TypeProvider; import 'package:analyzer/src/generated/type_system.dart'; import 'package:analyzer/src/summary/idl.dart'; import 'ast_properties.dart'; /// Given an [expression] and a corresponding [typeSystem] and [typeProvider], /// gets the known static type of the expression. DartType getExpressionType( Expression expression, TypeSystem typeSystem, TypeProvider typeProvider, {bool read: false}) { DartType type; if (read) { type = getReadType(expression); } else { type = expression.staticType; } type ??= DynamicTypeImpl.instance; return type; } DartType getReadType(Expression expression) { if (expression is IndexExpression) { return expression.auxiliaryElements?.staticElement?.returnType; } { Element setter; if (expression is PrefixedIdentifier) { setter = expression.staticElement; } else if (expression is PropertyAccess) { setter = expression.propertyName.staticElement; } else if (expression is SimpleIdentifier) { setter = expression.staticElement; } if (setter is PropertyAccessorElement && setter.isSetter) { var getter = setter.variable.getter; if (getter != null) { return getter.returnType; } } } if (expression is SimpleIdentifier) { var aux = expression.auxiliaryElements; if (aux != null) { return aux.staticElement?.returnType; } } return expression.staticType; } DartType _elementType(Element e) { if (e == null) { // Malformed code - just return dynamic. return DynamicTypeImpl.instance; } return (e as dynamic).type; } Element _getKnownElement(Expression expression) { if (expression is ParenthesizedExpression) { return _getKnownElement(expression.expression); } else if (expression is NamedExpression) { return _getKnownElement(expression.expression); } else if (expression is FunctionExpression) { return expression.declaredElement; } else if (expression is PropertyAccess) { return expression.propertyName.staticElement; } else if (expression is Identifier) { return expression.staticElement; } return null; } /// Looks up the declaration that matches [member] in [type]. ExecutableElement _getMember(InterfaceType type, ExecutableElement member) { if (member.isPrivate && type.element.library != member.library) { return null; } // TODO(jmesserly): I'm not sure this method will still return the correct // type. This code may need to use InheritanceManager2.getMember instead, // similar to the fix in _checkImplicitCovarianceCast. var name = member.name; var baseMember = member is PropertyAccessorElement ? (member.isGetter ? type.getGetter(name) : type.getSetter(name)) : type.getMethod(name); if (baseMember == null || baseMember.isStatic) return null; return baseMember; } /// Checks the body of functions and properties. class CodeChecker extends RecursiveAstVisitor { final Dart2TypeSystem rules; final TypeProvider typeProvider; final InheritanceManager3 inheritance; final AnalysisErrorListener reporter; final AnalysisOptionsImpl _options; _OverrideChecker _overrideChecker; FeatureSet _featureSet; bool _failure = false; bool _hasImplicitCasts; HashSet<ExecutableElement> _covariantPrivateMembers; CodeChecker(TypeProvider typeProvider, Dart2TypeSystem rules, this.inheritance, AnalysisErrorListener reporter, this._options) : typeProvider = typeProvider, rules = rules, reporter = reporter { _overrideChecker = new _OverrideChecker(this); } bool get failure => _failure; NullabilitySuffix get _noneOrStarSuffix { return _nonNullableEnabled ? NullabilitySuffix.none : NullabilitySuffix.star; } bool get _nonNullableEnabled => _featureSet.isEnabled(Feature.non_nullable); void checkArgument(Expression arg, DartType expectedType) { // Preserve named argument structure, so their immediate parent is the // method invocation. Expression baseExpression = arg is NamedExpression ? arg.expression : arg; checkAssignment(baseExpression, expectedType); } void checkArgumentList(ArgumentList node, FunctionType type) { NodeList<Expression> list = node.arguments; int len = list.length; for (int i = 0; i < len; ++i) { Expression arg = list[i]; ParameterElement element = arg.staticParameterElement; if (element == null) { // We found an argument mismatch, the analyzer will report this too, // so no need to insert an error for this here. continue; } checkArgument(arg, _elementType(element)); } } void checkAssignment(Expression expr, DartType type) { checkForCast(expr, type); } /// Analyzer checks boolean conversions, but we need to check too, because /// it uses the default assignability rules that allow `dynamic` and `Object` /// to be assigned to bool with no message. void checkBoolean(Expression expr) => checkAssignment(expr, typeProvider.boolType); void checkCollectionElement( CollectionElement element, DartType expectedType) { if (element is ForElement) { checkCollectionElement(element.body, expectedType); } else if (element is IfElement) { checkBoolean(element.condition); checkCollectionElement(element.thenElement, expectedType); checkCollectionElement(element.elseElement, expectedType); } else if (element is Expression) { checkAssignment(element, expectedType); } else if (element is SpreadElement) { // Spread expression may be dynamic in which case it's implicitly downcast // to Iterable<dynamic> DartType expressionCastType = typeProvider.iterableDynamicType; checkAssignment(element.expression, expressionCastType); var exprType = element.expression.staticType; var asIterableType = exprType is InterfaceTypeImpl ? exprType.asInstanceOf(typeProvider.iterableElement) : null; var elementType = asIterableType == null ? null : asIterableType.typeArguments[0]; // Items in the spread will then potentially be downcast to the expected // type. _checkImplicitCast(element.expression, expectedType, from: elementType, forSpread: true); } } void checkForCast(Expression expr, DartType type) { if (expr is ParenthesizedExpression) { checkForCast(expr.expression, type); } else { _checkImplicitCast(expr, type); } } void checkMapElement(CollectionElement element, DartType expectedKeyType, DartType expectedValueType) { if (element is ForElement) { checkMapElement(element.body, expectedKeyType, expectedValueType); } else if (element is IfElement) { checkBoolean(element.condition); checkMapElement(element.thenElement, expectedKeyType, expectedValueType); checkMapElement(element.elseElement, expectedKeyType, expectedValueType); } else if (element is MapLiteralEntry) { checkAssignment(element.key, expectedKeyType); checkAssignment(element.value, expectedValueType); } else if (element is SpreadElement) { // Spread expression may be dynamic in which case it's implicitly downcast // to Map<dynamic, dynamic> DartType expressionCastType = typeProvider.mapType2( DynamicTypeImpl.instance, DynamicTypeImpl.instance); checkAssignment(element.expression, expressionCastType); var exprType = element.expression.staticType; var asMapType = exprType is InterfaceTypeImpl ? exprType.asInstanceOf(typeProvider.mapElement) : null; var elementKeyType = asMapType == null ? null : asMapType.typeArguments[0]; var elementValueType = asMapType == null ? null : asMapType.typeArguments[1]; // Keys and values in the spread will then potentially be downcast to // the expected types. _checkImplicitCast(element.expression, expectedKeyType, from: elementKeyType, forSpreadKey: true); _checkImplicitCast(element.expression, expectedValueType, from: elementValueType, forSpreadValue: true); } } DartType getAnnotatedType(TypeAnnotation type) { return type?.type ?? DynamicTypeImpl.instance; } void reset() { _failure = false; } @override void visitAsExpression(AsExpression node) { // We could do the same check as the IsExpression below, but that is // potentially too conservative. Instead, at runtime, we must fail hard // if the Dart as and the DDC as would return different values. node.visitChildren(this); } @override void visitAssignmentExpression(AssignmentExpression node) { Token operator = node.operator; TokenType operatorType = operator.type; if (operatorType == TokenType.EQ || operatorType == TokenType.QUESTION_QUESTION_EQ) { DartType staticType = _getExpressionType(node.leftHandSide); checkAssignment(node.rightHandSide, staticType); } else if (operatorType == TokenType.AMPERSAND_AMPERSAND_EQ || operatorType == TokenType.BAR_BAR_EQ) { checkAssignment(node.leftHandSide, typeProvider.boolType); checkAssignment(node.rightHandSide, typeProvider.boolType); } else { _checkCompoundAssignment(node); } node.visitChildren(this); } @override void visitBinaryExpression(BinaryExpression node) { var op = node.operator; if (op.isUserDefinableOperator) { var invokeType = node.staticInvokeType; if (invokeType == null) { // Dynamic invocation // TODO(vsm): Move this logic to the resolver? if (op.type != TokenType.EQ_EQ && op.type != TokenType.BANG_EQ) { _recordDynamicInvoke(node, node.leftOperand); } } else { // Analyzer should enforce number of parameter types, but check in // case we have erroneous input. if (invokeType.normalParameterTypes.isNotEmpty) { checkArgument(node.rightOperand, invokeType.normalParameterTypes[0]); } } } else { // Non-method operator. switch (op.type) { case TokenType.AMPERSAND_AMPERSAND: case TokenType.BAR_BAR: checkBoolean(node.leftOperand); checkBoolean(node.rightOperand); break; case TokenType.BANG_EQ: break; case TokenType.QUESTION_QUESTION: break; default: assert(false); } } node.visitChildren(this); } @override void visitClassDeclaration(ClassDeclaration node) { _overrideChecker.check(node); super.visitClassDeclaration(node); } @override void visitClassTypeAlias(ClassTypeAlias node) { _overrideChecker.check(node); super.visitClassTypeAlias(node); } @override void visitComment(Comment node) { // skip, no need to do typechecking inside comments (they may contain // comment references which would require resolution). } @override void visitCompilationUnit(CompilationUnit node) { _featureSet = node.featureSet; _hasImplicitCasts = false; _covariantPrivateMembers = new HashSet(); node.visitChildren(this); setHasImplicitCasts(node, _hasImplicitCasts); setCovariantPrivateMembers(node, _covariantPrivateMembers); } @override void visitConditionalExpression(ConditionalExpression node) { checkBoolean(node.condition); node.visitChildren(this); } // Check invocations /// Check constructor declaration to ensure correct super call placement. @override void visitConstructorDeclaration(ConstructorDeclaration node) { node.visitChildren(this); final init = node.initializers; for (int i = 0, last = init.length - 1; i < last; i++) { final node = init[i]; if (node is SuperConstructorInvocation) { _recordMessage(node, StrongModeCode.INVALID_SUPER_INVOCATION, [node]); } } } @override void visitConstructorFieldInitializer(ConstructorFieldInitializer node) { var field = node.fieldName; var element = field.staticElement; DartType staticType = _elementType(element); checkAssignment(node.expression, staticType); node.visitChildren(this); } @override void visitDefaultFormalParameter(DefaultFormalParameter node) { // Check that defaults have the proper subtype. var parameter = node.parameter; var parameterType = _elementType(parameter.declaredElement); assert(parameterType != null); var defaultValue = node.defaultValue; if (defaultValue != null) { checkAssignment(defaultValue, parameterType); } node.visitChildren(this); } @override void visitDoStatement(DoStatement node) { checkBoolean(node.condition); node.visitChildren(this); } @override void visitExpressionFunctionBody(ExpressionFunctionBody node) { _checkReturnOrYield(node.expression, node); node.visitChildren(this); } @override void visitFieldFormalParameter(FieldFormalParameter node) { var element = node.declaredElement; var typeName = node.type; if (typeName != null) { var type = _elementType(element); var fieldElement = node.identifier.staticElement as FieldFormalParameterElement; var fieldType = _elementType(fieldElement.field); if (!rules.isSubtypeOf(type, fieldType)) { _recordMessage(node, StrongModeCode.INVALID_PARAMETER_DECLARATION, [node, fieldType]); } } node.visitChildren(this); } @override void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) { _visitForEachParts(node, node.loopVariable?.identifier); node.visitChildren(this); } @override void visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) { _visitForEachParts(node, node.identifier); node.visitChildren(this); } @override void visitForPartsWithDeclarations(ForPartsWithDeclarations node) { if (node.condition != null) { checkBoolean(node.condition); } node.visitChildren(this); } @override void visitForPartsWithExpression(ForPartsWithExpression node) { if (node.condition != null) { checkBoolean(node.condition); } node.visitChildren(this); } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { _checkFunctionApplication(node); node.visitChildren(this); } @override void visitIfStatement(IfStatement node) { checkBoolean(node.condition); node.visitChildren(this); } @override void visitIndexExpression(IndexExpression node) { var target = node.realTarget; var element = node.staticElement; if (element == null) { _recordDynamicInvoke(node, target); } else if (element is MethodElement) { var type = element.type; // Analyzer should enforce number of parameter types, but check in // case we have erroneous input. if (type.normalParameterTypes.isNotEmpty) { checkArgument(node.index, type.normalParameterTypes[0]); } } else { // TODO(vsm): Assert that the analyzer found an error here? } node.visitChildren(this); } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { var arguments = node.argumentList; var element = node.staticElement; if (element != null) { var type = _elementType(node.staticElement); checkArgumentList(arguments, type); } node.visitChildren(this); } @override void visitIsExpression(IsExpression node) { _checkRuntimeTypeCheck(node, node.type); node.visitChildren(this); } @override void visitListLiteral(ListLiteral node) { DartType type = DynamicTypeImpl.instance; if (node.typeArguments != null) { NodeList<TypeAnnotation> targs = node.typeArguments.arguments; if (targs.isNotEmpty) { type = targs[0].type; } } else { DartType staticType = node.staticType; if (staticType is InterfaceType) { List<DartType> targs = staticType.typeArguments; if (targs != null && targs.isNotEmpty) { type = targs[0]; } } } NodeList<CollectionElement> elements = node.elements; for (int i = 0; i < elements.length; i++) { checkCollectionElement(elements[i], type); } super.visitListLiteral(node); } @override visitMethodInvocation(MethodInvocation node) { var target = node.realTarget; var element = node.methodName.staticElement; if (element == null && !typeProvider.isObjectMethod(node.methodName.name) && node.methodName.name != FunctionElement.CALL_METHOD_NAME) { _recordDynamicInvoke(node, target); // Mark the tear-off as being dynamic, too. This lets us distinguish // cases like: // // dynamic d; // d.someMethod(...); // the whole method call must be a dynamic send. // // ... from case like: // // SomeType s; // s.someDynamicField(...); // static get, followed by dynamic call. // // The first case is handled here, the second case is handled below when // we call [checkFunctionApplication]. setIsDynamicInvoke(node.methodName, true); } else { var invokeType = (node as MethodInvocationImpl).methodNameType; _checkImplicitCovarianceCast(node, target, element, invokeType is FunctionType ? invokeType : null); _checkFunctionApplication(node); } // Don't visit methodName, we already checked things related to the call. node.target?.accept(this); node.typeArguments?.accept(this); node.argumentList?.accept(this); } @override void visitPostfixExpression(PostfixExpression node) { _checkUnary(node.operand, node.operator, node.staticElement); node.visitChildren(this); } @override void visitPrefixedIdentifier(PrefixedIdentifier node) { _checkFieldAccess(node, node.prefix, node.identifier); } @override void visitPrefixExpression(PrefixExpression node) { if (node.operator.type == TokenType.BANG) { checkBoolean(node.operand); } else { _checkUnary(node.operand, node.operator, node.staticElement); } node.visitChildren(this); } @override void visitPropertyAccess(PropertyAccess node) { _checkFieldAccess(node, node.realTarget, node.propertyName); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { var type = node.staticElement?.type; // TODO(leafp): There's a TODO in visitRedirectingConstructorInvocation // in the element_resolver to handle the case that the element is null // and emit an error. In the meantime, just be defensive here. if (type != null) { checkArgumentList(node.argumentList, type); } node.visitChildren(this); } @override void visitReturnStatement(ReturnStatement node) { _checkReturnOrYield(node.expression, node); node.visitChildren(this); } @override void visitSetOrMapLiteral(SetOrMapLiteral node) { if (node.isMap) { DartType keyType = DynamicTypeImpl.instance; DartType valueType = DynamicTypeImpl.instance; if (node.typeArguments != null) { NodeList<TypeAnnotation> typeArguments = node.typeArguments.arguments; if (typeArguments.isNotEmpty) { keyType = typeArguments[0].type; } if (typeArguments.length > 1) { valueType = typeArguments[1].type; } } else { DartType staticType = node.staticType; if (staticType is InterfaceType) { List<DartType> typeArguments = staticType.typeArguments; if (typeArguments != null) { if (typeArguments.isNotEmpty) { keyType = typeArguments[0]; } if (typeArguments.length > 1) { valueType = typeArguments[1]; } } } } NodeList<CollectionElement> elements = node.elements; for (int i = 0; i < elements.length; i++) { checkMapElement(elements[i], keyType, valueType); } } else if (node.isSet) { DartType type = DynamicTypeImpl.instance; if (node.typeArguments != null) { NodeList<TypeAnnotation> typeArguments = node.typeArguments.arguments; if (typeArguments.isNotEmpty) { type = typeArguments[0].type; } } else { DartType staticType = node.staticType; if (staticType is InterfaceType) { List<DartType> typeArguments = staticType.typeArguments; if (typeArguments != null && typeArguments.isNotEmpty) { type = typeArguments[0]; } } } NodeList<CollectionElement> elements = node.elements; for (int i = 0; i < elements.length; i++) { checkCollectionElement(elements[i], type); } } super.visitSetOrMapLiteral(node); } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { var element = node.staticElement; if (element != null) { var type = node.staticElement.type; checkArgumentList(node.argumentList, type); } node.visitChildren(this); } @override void visitSwitchStatement(SwitchStatement node) { // SwitchStatement defines a boolean conversion to check the result of the // case value == the switch value, but in dev_compiler we require a boolean // return type from an overridden == operator (because Object.==), so // checking in SwitchStatement shouldn't be necessary. node.visitChildren(this); } @override Object visitVariableDeclaration(VariableDeclaration node) { VariableElement variableElement = node == null ? null : node.declaredElement; AstNode parent = node.parent; if (variableElement != null && parent is VariableDeclarationList && parent.type == null && node.initializer != null) { if (variableElement.kind == ElementKind.TOP_LEVEL_VARIABLE || variableElement.kind == ElementKind.FIELD) { _validateTopLevelInitializer(variableElement.name, node.initializer); } } return super.visitVariableDeclaration(node); } @override void visitVariableDeclarationList(VariableDeclarationList node) { TypeAnnotation type = node.type; if (type != null) { for (VariableDeclaration variable in node.variables) { var initializer = variable.initializer; if (initializer != null) { checkForCast(initializer, type.type); } } } node.visitChildren(this); } @override void visitWhileStatement(WhileStatement node) { checkBoolean(node.condition); node.visitChildren(this); } @override void visitYieldStatement(YieldStatement node) { _checkReturnOrYield(node.expression, node, yieldStar: node.star != null); node.visitChildren(this); } void _checkCompoundAssignment(AssignmentExpression expr) { var op = expr.operator.type; assert(op.isAssignmentOperator && op != TokenType.EQ); var methodElement = expr.staticElement; if (methodElement == null) { // Dynamic invocation. _recordDynamicInvoke(expr, expr.leftHandSide); } else { // Sanity check the operator. assert(methodElement.isOperator); var functionType = methodElement.type; var paramTypes = functionType.normalParameterTypes; assert(paramTypes.length == 1); assert(functionType.namedParameterTypes.isEmpty); assert(functionType.optionalParameterTypes.isEmpty); // Refine the return type. var rhsType = _getExpressionType(expr.rightHandSide); var lhsType = _getExpressionType(expr.leftHandSide); var returnType = rules.refineBinaryExpressionType( lhsType, op, rhsType, functionType.returnType, _featureSet); // Check the argument for an implicit cast. _checkImplicitCast(expr.rightHandSide, paramTypes[0], from: rhsType); // Check the return type for an implicit cast. // // If needed, mark the assignment to indicate a down cast when we assign // back to it. So these two implicit casts are equivalent: // // y = /*implicit cast*/(y + 42); // /*implicit assignment cast*/y += 42; // _checkImplicitCast(expr.leftHandSide, lhsType, from: returnType, opAssign: true); } } void _checkFieldAccess( AstNode node, Expression target, SimpleIdentifier field) { var element = field.staticElement; var invokeType = element is ExecutableElement ? element.type : null; _checkImplicitCovarianceCast(node, target, element, invokeType); if (element == null && !typeProvider.isObjectMember(field.name)) { _recordDynamicInvoke(node, target); } node.visitChildren(this); } void _checkFunctionApplication(InvocationExpression node) { var ft = _getTypeAsCaller(node); if (_isDynamicCall(node, ft)) { // If f is Function and this is a method invocation, we should have // gotten an analyzer error, so no need to issue another error. _recordDynamicInvoke(node, node.function); } else { checkArgumentList(node.argumentList, ft); } } /// Given an expression [expr] of type [fromType], returns true if an implicit /// downcast is required, false if it is not, or null if the types are /// unrelated. bool _checkFunctionTypeCasts( Expression expr, FunctionType to, DartType fromType) { bool callTearoff = false; FunctionType from; if (fromType is FunctionType) { from = fromType; } else if (fromType is InterfaceType) { from = rules.getCallMethodType(fromType); callTearoff = true; } if (from == null) { return null; // unrelated } if (rules.isSubtypeOf(from, to)) { // Sound subtype. // However we may still need cast if we have a call tearoff. return callTearoff; } if (rules.isSubtypeOf(to, from)) { // Assignable, but needs cast. return true; } return null; } /// Checks if an implicit cast of [expr] from [from] type to [to] type is /// needed, and if so records it. /// /// If [from] is omitted, uses the static type of [expr]. /// /// If [expr] does not require an implicit cast because it is not related to /// [to] or is already a subtype of it, does nothing. void _checkImplicitCast(Expression expr, DartType to, {DartType from, bool opAssign: false, bool forSpread: false, bool forSpreadKey: false, bool forSpreadValue: false}) { from ??= _getExpressionType(expr); if (_needsImplicitCast(expr, to, from: from) == true) { _recordImplicitCast(expr, to, from: from, opAssign: opAssign, forSpread: forSpread, forSpreadKey: forSpreadKey, forSpreadValue: forSpreadValue); } } /// If we're calling into [element] through the [target], we may need to /// insert a caller side check for soundness on the result of the expression /// [node]. The [invokeType] is the type of the [element] in the [target]. /// /// This happens when [target] is an unsafe covariant interface, and [element] /// could return a type that is not a subtype of the expected static type /// given target's type. For example: /// /// typedef F<T>(T t); /// class C<T> { /// F<T> f; /// C(this.f); /// } /// test1() { /// C<Object> c = new C<int>((int x) => x + 42)); /// F<Object> f = c.f; // need an implicit cast here. /// f('hello'); /// } /// /// Here target is `c`, the target type is `C<Object>`, the member is /// `get f() -> F<T>`, and the expression node is `c.f`. When we call `c.f` /// the expected static result is `F<Object>`. However `c.f` actually returns /// `F<int>`, which is not a subtype of `F<Object>`. So this method will add /// an implicit cast `(c.f as F<Object>)` to guard against this case. /// /// Note that it is possible for the cast to succeed, for example: /// `new C<int>((Object x) => '$x'))`. It is safe to pass any object to that /// function, including an `int`. void _checkImplicitCovarianceCast(Expression node, Expression target, Element element, FunctionType invokeType) { // If we're calling an instance method or getter, then we // want to check the result type. // // We intentionally ignore method tear-offs, because those methods have // covariance checks for their parameters inside the method. var targetType = target?.staticType; if (element is ExecutableElement && _isInstanceMember(element) && targetType is InterfaceType && targetType.typeArguments.isNotEmpty && !_targetHasKnownGenericTypeArguments(target) && // Make sure we don't overwrite an existing implicit cast based on // the context type. It will be more precise and will ensure soundness. getImplicitCast(node) == null) { // Track private setters/method calls. We can sometimes eliminate the // parameter check in code generation, if it was never needed. // This member will need a check, however, because we are calling through // an unsafe target. if (element.isPrivate && element.parameters.isNotEmpty) { _covariantPrivateMembers .add(element is ExecutableMember ? element.baseElement : element); } // Get the lower bound of the declared return type (e.g. `F<bottom>`) and // see if it can be assigned to the expected type (e.g. `F<Object>`). // // That way we can tell if any lower `T` will work or not. // The member may be from a superclass, so we need to ensure the type // parameters are properly substituted. var classElement = targetType.element; var classLowerBound = classElement.instantiate( typeArguments: List.filled( classElement.typeParameters.length, BottomTypeImpl.instance, ), nullabilitySuffix: NullabilitySuffix.none, ); var memberLowerBound = inheritance.getMember( classLowerBound, Name(element.librarySource.uri, element.name), ); if (memberLowerBound == null && element.enclosingElement is ExtensionElement) { return; } var expectedType = invokeType.returnType; if (!rules.isSubtypeOf(memberLowerBound.returnType, expectedType)) { var isMethod = element is MethodElement; var isCall = node is MethodInvocation; if (isMethod && !isCall) { // If `o.m` is a method tearoff, cast to the method type. setImplicitCast(node, invokeType); } else if (!isMethod && isCall) { // If `o.g()` is calling a field/getter `g`, we need to cast `o.g` // before the call: `(o.g as expectedType)(args)`. // This cannot be represented by an `as` node without changing the // Dart AST structure, so we record it as a special cast. setImplicitOperationCast(node, expectedType); } else { // For method calls `o.m()` or getters `o.g`, simply cast the result. setImplicitCast(node, expectedType); } _hasImplicitCasts = true; } } } void _checkReturnOrYield(Expression expression, AstNode node, {bool yieldStar: false}) { FunctionBody body = node.thisOrAncestorOfType<FunctionBody>(); var type = _getExpectedReturnType(body, yieldStar: yieldStar); if (type == null) { // We have a type mismatch: the async/async*/sync* modifier does // not match the return or yield type. We should have already gotten an // analyzer error in this case. return; } // TODO(vsm): Enforce void or dynamic (to void?) when expression is null. if (expression != null) checkAssignment(expression, type); } void _checkRuntimeTypeCheck(AstNode node, TypeAnnotation annotation) { var type = getAnnotatedType(annotation); if (!rules.isGroundType(type)) { _recordMessage(node, StrongModeCode.NON_GROUND_TYPE_CHECK_INFO, [type]); } } void _checkUnary(Expression operand, Token op, MethodElement element) { bool isIncrementAssign = op.type == TokenType.PLUS_PLUS || op.type == TokenType.MINUS_MINUS; if (op.isUserDefinableOperator || isIncrementAssign) { if (element == null) { _recordDynamicInvoke(operand.parent, operand); } else if (isIncrementAssign) { // For ++ and --, even if it is not dynamic, we still need to check // that the user defined method accepts an `int` as the RHS. // // We assume Analyzer has done this already (in ErrorVerifier). // // However, we also need to check the return type. // Refine the return type. var functionType = element.type; var rhsType = typeProvider.intType; var lhsType = _getExpressionType(operand); var returnType = rules.refineBinaryExpressionType(lhsType, TokenType.PLUS, rhsType, functionType.returnType, _featureSet); // Skip the argument check - `int` cannot be downcast. // // Check the return type for an implicit cast. // // If needed, mark the assignment to indicate a down cast when we assign // back to it. So these two implicit casts are equivalent: // // y = /*implicit cast*/(y + 1); // /*implicit assignment cast*/y++; // _checkImplicitCast(operand, lhsType, from: returnType, opAssign: true); } } } /// Gets the expected return type of the given function [body], either from /// a normal return/yield, or from a yield*. DartType _getExpectedReturnType(FunctionBody body, {bool yieldStar: false}) { FunctionType functionType; var parent = body.parent; if (parent is Declaration) { functionType = _elementType(parent.declaredElement); } else { assert(parent is FunctionExpression); functionType = (parent as FunctionExpression).staticType ?? DynamicTypeImpl.instance; } var type = functionType.returnType; ClassElement expectedElement; if (body.isAsynchronous) { if (body.isGenerator) { // Stream<T> -> T expectedElement = typeProvider.streamElement; } else { // Future<T> -> FutureOr<T> var typeArg = (type.element == typeProvider.futureElement) ? (type as InterfaceType).typeArguments[0] : typeProvider.dynamicType; return typeProvider.futureOrType2(typeArg); } } else { if (body.isGenerator) { // Iterable<T> -> T expectedElement = typeProvider.iterableElement; } else { // T -> T return type; } } if (yieldStar) { if (type.isDynamic) { // Ensure it's at least a Stream / Iterable. return expectedElement.instantiate( typeArguments: [typeProvider.dynamicType], nullabilitySuffix: _noneOrStarSuffix, ); } else { // Analyzer will provide a separate error if expected type // is not compatible with type. return type; } } if (type.isDynamic) { return type; } else if (type is InterfaceType && type.element == expectedElement) { return type.typeArguments[0]; } else { // Malformed type - fallback on analyzer error. return null; } } DartType _getExpressionType(Expression expr) => getExpressionType(expr, rules, typeProvider); DartType _getInstanceTypeArgument( DartType expressionType, ClassElement instanceType) { if (expressionType is InterfaceTypeImpl) { var asInstanceType = expressionType.asInstanceOf(instanceType); if (asInstanceType != null) { return asInstanceType.typeArguments[0]; } } return null; } /// Given an expression, return its type assuming it is /// in the caller position of a call (that is, accounting /// for the possibility of a call method). Returns null /// if expression is not statically callable. FunctionType _getTypeAsCaller(InvocationExpression node) { DartType type = node.staticInvokeType; if (type is FunctionType) { return type; } else if (type is InterfaceType) { return rules.getCallMethodType(type); } return null; } /// Returns `true` if the expression is a dynamic function call or method /// invocation. bool _isDynamicCall(InvocationExpression call, FunctionType ft) { return ft == null; } bool _isInstanceMember(ExecutableElement e) => !e.isStatic && (e is MethodElement || e is PropertyAccessorElement && e.variable is FieldElement); void _markImplicitCast(Expression expr, DartType to, {bool opAssign: false, bool forSpread: false, bool forSpreadKey: false, bool forSpreadValue: false}) { if (opAssign) { setImplicitOperationCast(expr, to); } else if (forSpread) { setImplicitSpreadCast(expr, to); } else if (forSpreadKey) { setImplicitSpreadKeyCast(expr, to); } else if (forSpreadValue) { setImplicitSpreadValueCast(expr, to); } else { setImplicitCast(expr, to); } _hasImplicitCasts = true; } /// Returns true if we need an implicit cast of [expr] from [from] type to /// [to] type, returns false if no cast is needed, and returns null if the /// types are statically incompatible, or the types are compatible but don't /// allow implicit cast (ie, void, which is one form of Top which will not /// downcast implicitly). /// /// If [from] is omitted, uses the static type of [expr] bool _needsImplicitCast(Expression expr, DartType to, {DartType from}) { from ??= _getExpressionType(expr); // Void is considered Top, but may only be *explicitly* cast. if (from.isVoid) return null; if (to is FunctionType) { bool needsCast = _checkFunctionTypeCasts(expr, to, from); if (needsCast != null) return needsCast; } // fromT <: toT, no coercion needed. if (rules.isSubtypeOf(from, to)) { return false; } // Down cast or legal sideways cast, coercion needed. if (rules.isAssignableTo(from, to, featureSet: _featureSet)) { return true; } // Special case for FutureOr to handle returned values from async functions. // In this case, we're more permissive than assignability. if (to.isDartAsyncFutureOr) { var to1 = (to as InterfaceType).typeArguments[0]; var to2 = typeProvider.futureType2(to1); return _needsImplicitCast(expr, to1, from: from) == true || _needsImplicitCast(expr, to2, from: from) == true; } // Anything else is an illegal sideways cast. // However, these will have been reported already in error_verifier, so we // don't need to report them again. return null; } void _recordDynamicInvoke(AstNode node, Expression target) { _recordMessage(node, StrongModeCode.DYNAMIC_INVOKE, [node]); // TODO(jmesserly): we may eventually want to record if the whole operation // (node) was dynamic, rather than the target, but this is an easier fit // with what we used to do. if (target != null) setIsDynamicInvoke(target, true); } /// Records an implicit cast for the [expr] from [from] to [to]. /// /// This will emit the appropriate error/warning/hint message as well as mark /// the AST node. void _recordImplicitCast(Expression expr, DartType to, {DartType from, bool opAssign: false, forSpread: false, forSpreadKey: false, forSpreadValue: false}) { // If this is an implicit tearoff, we need to mark the cast, but we don't // want to warn if it's a legal subtype. if (from is InterfaceType && rules.acceptsFunctionType(to)) { var type = rules.getCallMethodType(from); if (type != null && rules.isSubtypeOf(type, to)) { _markImplicitCast(expr, to, opAssign: opAssign, forSpread: forSpread, forSpreadKey: forSpreadKey, forSpreadValue: forSpreadValue); return; } } if (!forSpread && !forSpreadKey && !forSpreadValue) { // Spreads are special in that they may create downcasts at runtime but // those casts are implied so we don't treat them as strictly. // Inference "casts": if (expr is Literal) { // fromT should be an exact type - this will almost certainly fail at // runtime. if (expr is ListLiteral) { _recordMessage( expr, StrongModeCode.INVALID_CAST_LITERAL_LIST, [from, to]); } else if (expr is SetOrMapLiteral) { if (expr.isMap) { _recordMessage( expr, StrongModeCode.INVALID_CAST_LITERAL_MAP, [from, to]); } else if (expr.isSet) { _recordMessage( expr, StrongModeCode.INVALID_CAST_LITERAL_SET, [from, to]); } else { // This should only happen when the code is invalid, in which case // the error should have been reported elsewhere. } } else { _recordMessage( expr, StrongModeCode.INVALID_CAST_LITERAL, [expr, from, to]); } return; } if (expr is FunctionExpression) { _recordMessage( expr, StrongModeCode.INVALID_CAST_FUNCTION_EXPR, [from, to]); return; } if (expr is InstanceCreationExpression) { ConstructorElement e = expr.staticElement; if (e == null || !e.isFactory) { // fromT should be an exact type - this will almost certainly fail at // runtime. _recordMessage( expr, StrongModeCode.INVALID_CAST_NEW_EXPR, [from, to]); return; } } Element e = _getKnownElement(expr); if (e is FunctionElement || e is MethodElement && e.isStatic) { _recordMessage( expr, e is MethodElement ? StrongModeCode.INVALID_CAST_METHOD : StrongModeCode.INVALID_CAST_FUNCTION, [e.name, from, to]); return; } } // Composite cast: these are more likely to fail. bool downCastComposite = false; if (!rules.isGroundType(to)) { // This cast is (probably) due to our different treatment of dynamic. // It may be more likely to fail at runtime. if (from is InterfaceType) { // For class types, we'd like to allow non-generic down casts, e.g., // Iterable<T> to List<T>. The intuition here is that raw (generic) // casts are problematic, and we should complain about those. var typeArgs = from.typeArguments; downCastComposite = typeArgs.isEmpty || typeArgs.any((t) => t.isDynamic); } else { downCastComposite = !from.isDynamic; } } var parent = expr.parent; ErrorCode errorCode; if (downCastComposite) { errorCode = StrongModeCode.DOWN_CAST_COMPOSITE; } else if (from.isDynamic) { errorCode = StrongModeCode.DYNAMIC_CAST; } else if (parent is VariableDeclaration && parent.initializer == expr) { errorCode = StrongModeCode.ASSIGNMENT_CAST; } else { errorCode = opAssign ? StrongModeCode.DOWN_CAST_IMPLICIT_ASSIGN : StrongModeCode.DOWN_CAST_IMPLICIT; } _recordMessage(expr, errorCode, [from, to]); _markImplicitCast(expr, to, opAssign: opAssign, forSpread: forSpread, forSpreadKey: forSpreadKey, forSpreadValue: forSpreadValue); } void _recordMessage(AstNode node, ErrorCode errorCode, List arguments) { // Compute the right severity taking the analysis options into account. // We construct a dummy error to make the common case where we end up // ignoring the strong mode message cheaper. var processor = ErrorProcessor.getProcessor(_options, new AnalysisError.forValues(null, -1, 0, errorCode, null, null)); var severity = (processor != null) ? processor.severity : errorCode.errorSeverity; if (severity == ErrorSeverity.ERROR) { _failure = true; } if (errorCode.type == ErrorType.HINT && errorCode.name.startsWith('TOP_LEVEL_')) { severity = ErrorSeverity.ERROR; } if (severity != ErrorSeverity.INFO || _options.strongModeHints) { int begin = node is AnnotatedNode ? node.firstTokenAfterCommentAndMetadata.offset : node.offset; int length = node.end - begin; var source = (node.root as CompilationUnit).declaredElement.source; var error = new AnalysisError(source, begin, length, errorCode, arguments); reporter.onError(error); } } /// Returns true if we can safely skip the covariance checks because [target] /// has known type arguments, such as `this` `super` or a non-factory `new`. /// /// For example: /// /// class C<T> { /// T _t; /// } /// class D<T> extends C<T> { /// method<S extends T>(T t, C<T> c) { /// // implicit cast: t as T; /// // implicit cast: c as C<T>; /// /// // These do not need further checks. The type parameter `T` for /// // `this` must be the same as our `T` /// this._t = t; /// super._t = t; /// new C<T>()._t = t; // non-factory /// /// // This needs further checks. The type of `c` could be `C<S>` for /// // some `S <: T`. /// c._t = t; /// // factory statically returns `C<T>`, dynamically returns `C<S>`. /// new F<T, S>()._t = t; /// } /// } /// class F<T, S extends T> extends C<T> { /// factory F() => new C<S>(); /// } /// bool _targetHasKnownGenericTypeArguments(Expression target) { return target == null || // implicit this target is ThisExpression || target is SuperExpression || target is InstanceCreationExpression && target.staticElement?.isFactory == false; } void _validateTopLevelInitializer(String name, Expression n) { n.accept(new _TopLevelInitializerValidator(this, name)); } void _visitForEachParts(ForEachParts node, SimpleIdentifier loopVariable) { // Safely handle malformed statements. if (loopVariable == null) { return; } Token awaitKeyword; AstNode parent = node.parent; if (parent is ForStatement) { awaitKeyword = parent.awaitKeyword; } else if (parent is ForElement) { awaitKeyword = parent.awaitKeyword; } else { throw new StateError( 'Unexpected parent of ForEachParts: ${parent.runtimeType}'); } // Find the element type of the sequence. var sequenceElement = awaitKeyword != null ? typeProvider.streamElement : typeProvider.iterableElement; var iterableType = _getExpressionType(node.iterable); var elementType = _getInstanceTypeArgument(iterableType, sequenceElement); // If the sequence is not an Iterable (or Stream for await for) but is a // supertype of it, do an implicit downcast to Iterable<dynamic>. Then // we'll do a separate cast of the dynamic element to the variable's type. if (elementType == null) { var sequenceType = sequenceElement.instantiate( typeArguments: [typeProvider.dynamicType], nullabilitySuffix: _noneOrStarSuffix, ); if (rules.isSubtypeOf(sequenceType, iterableType)) { _recordImplicitCast(node.iterable, sequenceType, from: iterableType); elementType = DynamicTypeImpl.instance; } } // If the sequence doesn't implement the interface at all, [ErrorVerifier] // will report the error, so ignore it here. if (elementType != null) { // Insert a cast from the sequence's element type to the loop variable's // if needed. _checkImplicitCast(loopVariable, _getExpressionType(loopVariable), from: elementType); } } } /// Checks for overriding declarations of fields and methods. This is used to /// check overrides between classes and superclasses, interfaces, and mixin /// applications. class _OverrideChecker { final Dart2TypeSystem rules; _OverrideChecker(CodeChecker checker) : rules = checker.rules; void check(Declaration node) { var element = node.declaredElement as ClassElement; if (element.isDartCoreObject) { return; } _checkForCovariantGenerics(node, element); } /// Visits each member on the class [node] and calls [checkMember] with the /// corresponding instance element and AST node (for error reporting). /// /// See also [_checkTypeMembers], which is used when the class AST node is not /// available. void _checkClassMembers(Declaration node, void checkMember(ExecutableElement member, ClassMember location)) { for (var member in _classMembers(node)) { if (member is FieldDeclaration) { if (member.isStatic) { continue; } for (var variable in member.fields.variables) { var element = variable.declaredElement as PropertyInducingElement; checkMember(element.getter, member); if (!variable.isFinal && !variable.isConst) { checkMember(element.setter, member); } } } else if (member is MethodDeclaration) { if (member.isStatic) { continue; } checkMember(member.declaredElement, member); } else { assert(member is ConstructorDeclaration); } } } /// Finds implicit casts that we need on parameters and type formals to /// ensure soundness of covariant generics, and records them on the [node]. /// /// The parameter checks can be retrieved using [getClassCovariantParameters] /// and [getSuperclassCovariantParameters]. /// /// For each member of this class and non-overridden inherited member, we /// check to see if any generic super interface permits an unsound call to the /// concrete member. For example: /// /// class C<T> { /// add(T t) {} // C<Object>.add is unsafe, need a check on `t` /// } /// class D extends C<int> { /// add(int t) {} // C<Object>.add is unsafe, need a check on `t` /// } /// class E extends C<int> { /// add(Object t) {} // no check needed, C<Object>.add is safe /// } /// void _checkForCovariantGenerics(Declaration node, ClassElement element) { // Find all generic interfaces that could be used to call into members of // this class. This will help us identify which parameters need checks // for soundness. var allCovariant = _findAllGenericInterfaces(element); if (allCovariant.isEmpty) return; var seenConcreteMembers = new HashSet<String>(); var members = _getConcreteMembers(element.thisType, seenConcreteMembers); // For members on this class, check them against all generic interfaces. var checks = _findCovariantChecks(members, allCovariant); // Store those checks on the class declaration. setClassCovariantParameters(node, checks); // For members of the superclass, we may need to add checks because this // class adds a new unsafe interface. Collect those checks. checks = _findSuperclassCovariantChecks( element, allCovariant, seenConcreteMembers); // Store the checks on the class declaration, it will need to ensure the // inherited members are appropriately guarded to ensure soundness. setSuperclassCovariantParameters(node, checks); } /// Visits the [type] and calls [checkMember] for each instance member. /// /// See also [_checkClassMembers], which should be used when the class AST /// node is available to allow for better error locations void _checkTypeMembers( InterfaceType type, void checkMember(ExecutableElement member)) { void checkHelper(ExecutableElement e) { if (!e.isStatic) checkMember(e); } type.methods.forEach(checkHelper); type.accessors.forEach(checkHelper); } /// If node is a [ClassDeclaration] returns its members, otherwise if node is /// a [ClassTypeAlias] this returns an empty list. Iterable<ClassMember> _classMembers(Declaration node) { return node is ClassDeclaration ? node.members : []; } /// Find all covariance checks on parameters/type parameters needed for /// soundness given a set of concrete [members] and a set of unsafe generic /// [covariantInterfaces] that may allow those members to be called in an /// unsound way. /// /// See [_findCovariantChecksForMember] for more information and an example. Set<Element> _findCovariantChecks(Iterable<ExecutableElement> members, Iterable<ClassElement> covariantInterfaces, [Set<Element> covariantChecks]) { covariantChecks ??= _createCovariantCheckSet(); if (members.isEmpty) return covariantChecks; for (var iface in covariantInterfaces) { var typeParameters = iface.typeParameters; var defaultTypeArguments = rules.instantiateTypeFormalsToBounds(typeParameters); var unsafeSupertype = iface.instantiate( typeArguments: defaultTypeArguments, nullabilitySuffix: NullabilitySuffix.star, ); for (var m in members) { _findCovariantChecksForMember(m, unsafeSupertype, covariantChecks); } } return covariantChecks; } /// Given a [member] and a covariant [unsafeSupertype], determine if any /// type formals or parameters of this member need a check because of the /// unsoundness in the unsafe covariant supertype. /// /// For example: /// /// class C<T> { /// m(T t) {} /// g<S extends T>() => <S>[]; /// } /// class D extends C<num> { /// m(num n) {} /// g<R extends num>() => <R>[]; /// } /// main() { /// C<Object> c = new C<int>(); /// c.m('hi'); // must throw for soundness /// c.g<String>(); // must throw for soundness /// /// c = new D(); /// c.m('hi'); // must throw for soundness /// c.g<String>(); // must throw for soundness /// } /// /// We've already found `C<Object>` is a potentially unsafe covariant generic /// supertype, and we call this method to see if any members need a check /// because of `C<Object>`. /// /// In this example, we will call this method with: /// - `C<T>.m` and `C<Object>`, finding that `t` needs a check. /// - `C<T>.g` and `C<Object>`, finding that `S` needs a check. /// - `D.m` and `C<Object>`, finding that `n` needs a check. /// - `D.g` and `C<Object>`, finding that `R` needs a check. /// /// Given `C<T>.m` and `C<Object>`, we search for covariance checks like this /// (`*` short for `dynamic`): /// - get the type of `C<Object>.m`: `(Object) -> *` /// - get the type of `C<T>.m`: `(T) -> *` /// - perform a subtype check `(T) -> * <: (Object) -> *`, /// and record any parameters/type formals that violate soundness. /// - that checks `Object <: T`, which is false, thus we need a check on /// parameter `t` of `C<T>.m` /// /// Another example is `D.g` and `C<Object>`: /// - get the type of `C<Object>.m`: `<S extends Object>() -> *` /// - get the type of `D.g`: `<R extends num>() -> *` /// - perform a subtype check /// `<S extends Object>() -> * <: <R extends num>() -> *`, /// and record any parameters/type formals that violate soundness. /// - that checks the type formal bound of `S` and `R` asserting /// `Object <: num`, which is false, thus we need a check on type formal `R` /// of `D.g`. void _findCovariantChecksForMember(ExecutableElement member, InterfaceType unsafeSupertype, Set<Element> covariantChecks) { var f2 = _getMember(unsafeSupertype, member); if (f2 == null) return; var f1 = member; // Find parameter or type formal checks that we need to ensure `f2 <: f1`. // // The static type system allows this subtyping, but it is not sound without // these runtime checks. var fresh = FunctionTypeImpl.relateTypeFormals2( f1.typeParameters, f2.typeParameters, (b2, b1, p2, p1) { if (!rules.isSubtypeOf(b2, b1)) { covariantChecks.add(p1); } return true; }, ); if (fresh != null) { var subst1 = Substitution.fromPairs(f1.typeParameters, fresh); var subst2 = Substitution.fromPairs(f2.typeParameters, fresh); f1 = ExecutableMember.from2(f1, subst1); f2 = ExecutableMember.from2(f2, subst2); } FunctionTypeImpl.relateParameters(f1.parameters, f2.parameters, (p1, p2) { if (!rules.isOverrideSubtypeOfParameter(p1, p2)) { covariantChecks.add(p1); } return true; }); } /// For each member of this class and non-overridden inherited member, we /// check to see if any generic super interface permits an unsound call to the /// concrete member. For example: /// /// We must check non-overridden inherited members because this class could /// contain a new interface that permits unsound access to that member. In /// those cases, the class is expected to insert stub that checks the type /// before calling `super`. For example: /// /// class C<T> { /// add(T t) {} /// } /// class D { /// add(int t) {} /// } /// class E extends D implements C<int> { /// // C<Object>.add is unsafe, and D.m is marked for a check. /// // /// // one way to implement this is to generate a stub method: /// // add(t) => super.add(t as int); /// } /// Set<Element> _findSuperclassCovariantChecks(ClassElement element, Set<ClassElement> allCovariant, HashSet<String> seenConcreteMembers) { var visited = new HashSet<ClassElement>()..add(element); var superChecks = _createCovariantCheckSet(); var existingChecks = _createCovariantCheckSet(); void visitImmediateSuper(InterfaceType type) { // For members of mixins/supertypes, check them against new interfaces, // and also record any existing checks they already had. var oldCovariant = _findAllGenericInterfaces(type.element); var newCovariant = allCovariant.difference(oldCovariant); if (newCovariant.isEmpty) return; void visitSuper(InterfaceType type) { var element = type.element; if (visited.add(element)) { var members = _getConcreteMembers(type, seenConcreteMembers); _findCovariantChecks(members, newCovariant, superChecks); _findCovariantChecks(members, oldCovariant, existingChecks); element.mixins.reversed.forEach(visitSuper); var s = element.supertype; if (s != null) visitSuper(s); } } visitSuper(type); } element.mixins.reversed.forEach(visitImmediateSuper); var s = element.supertype; if (s != null) visitImmediateSuper(s); superChecks.removeAll(existingChecks); return superChecks; } static Set<Element> _createCovariantCheckSet() { return new LinkedHashSet( equals: _equalMemberElements, hashCode: _hashCodeMemberElements); } /// When finding superclass covariance checks, we need to track the /// substituted member/parameter type, but we don't want this type to break /// equality, because [Member] does not implement equality/hashCode, so /// instead we jump to the declaring element. static bool _equalMemberElements(Element x, Element y) { x = x is Member ? x.baseElement : x; y = y is Member ? y.baseElement : y; return x == y; } /// Find all generic interfaces that are implemented by [element], including /// [element] itself if it is generic. /// /// This represents the complete set of unsafe covariant interfaces that could /// be used to call members of [element]. /// /// Because we're going to instantiate these to their upper bound, we don't /// have to track type parameters. static Set<ClassElement> _findAllGenericInterfaces(ClassElement element) { var visited = <ClassElement>{}; var genericSupertypes = <ClassElement>{}; void visitClassAndSupertypes(ClassElement element) { if (visited.add(element)) { if (element.typeParameters.isNotEmpty) { genericSupertypes.add(element); } var supertype = element.supertype; if (supertype != null) { visitClassAndSupertypes(supertype.element); } for (var interface in element.mixins) { visitClassAndSupertypes(interface.element); } for (var interface in element.interfaces) { visitClassAndSupertypes(interface.element); } } } visitClassAndSupertypes(element); return genericSupertypes; } /// Gets all concrete instance members declared on this type, skipping already /// [seenConcreteMembers] and adding any found ones to it. /// /// By tracking the set of seen members, we can visit superclasses and mixins /// and ultimately collect every most-derived member exposed by a given type. static List<ExecutableElement> _getConcreteMembers( InterfaceType type, HashSet<String> seenConcreteMembers) { var members = <ExecutableElement>[]; for (var declaredMembers in [type.accessors, type.methods]) { for (var member in declaredMembers) { // We only visit each most derived concrete member. // To avoid visiting an overridden superclass member, we skip members // we've seen, and visit starting from the class, then mixins in // reverse order, then superclasses. if (!member.isStatic && !member.isAbstract && seenConcreteMembers.add(member.name)) { members.add(member); } } } return members; } static int _hashCodeMemberElements(Element x) { x = x is Member ? x.baseElement : x; return x.hashCode; } } class _TopLevelInitializerValidator extends RecursiveAstVisitor<void> { final CodeChecker _codeChecker; final String _name; /// A flag indicating whether certain diagnostics related to top-level /// elements should be produced. The diagnostics are the ones introduced by /// the analyzer to signal to users when the version of type inference /// performed by the analyzer was unable to accurately infer type information. /// The implementation of type inference used by the task model still has /// these deficiencies, but the implementation used by the driver does not. // TODO(brianwilkerson) Remove this field when the task model has been // removed. final bool flagTopLevel; _TopLevelInitializerValidator(this._codeChecker, this._name, {this.flagTopLevel = true}); void validateHasType(AstNode n, PropertyAccessorElement e) { if (e.hasImplicitReturnType) { var variable = e.variable as VariableElementImpl; TopLevelInferenceError error = variable.typeInferenceError; if (error != null) { if (error.kind == TopLevelInferenceErrorKind.dependencyCycle) { _codeChecker._recordMessage( n, StrongModeCode.TOP_LEVEL_CYCLE, [_name, error.arguments]); } else { _codeChecker._recordMessage( n, StrongModeCode.TOP_LEVEL_IDENTIFIER_NO_TYPE, [_name, e.name]); } } } } void validateIdentifierElement(AstNode n, Element e, {bool isMethodCall: false}) { if (e == null) { return; } Element enclosing = e.enclosingElement; if (enclosing is CompilationUnitElement) { if (e is PropertyAccessorElement) { validateHasType(n, e); } } else if (enclosing is ClassElement) { if (e is PropertyAccessorElement) { if (e.isStatic) { validateHasType(n, e); } else if (e.hasImplicitReturnType && flagTopLevel) { _codeChecker._recordMessage( n, StrongModeCode.TOP_LEVEL_INSTANCE_GETTER, [_name, e.name]); } } else if (!isMethodCall && e is ExecutableElement && e.kind == ElementKind.METHOD && !e.isStatic) { if (_hasAnyImplicitType(e) && flagTopLevel) { _codeChecker._recordMessage( n, StrongModeCode.TOP_LEVEL_INSTANCE_METHOD, [_name, e.name]); } } } } @override visitAsExpression(AsExpression node) { // Nothing to validate. } @override visitBinaryExpression(BinaryExpression node) { TokenType operator = node.operator.type; if (operator == TokenType.AMPERSAND_AMPERSAND || operator == TokenType.BAR_BAR || operator == TokenType.EQ_EQ || operator == TokenType.BANG_EQ) { // These operators give 'bool', no need to validate operands. } else { node.leftOperand.accept(this); } } @override visitCascadeExpression(CascadeExpression node) { node.target.accept(this); } @override visitConditionalExpression(ConditionalExpression node) { // No need to validate the condition, since it can't affect type inference. node.thenExpression.accept(this); node.elseExpression.accept(this); } @override visitFunctionExpression(FunctionExpression node) { FunctionBody body = node.body; if (body is ExpressionFunctionBody) { body.expression.accept(this); } else { _codeChecker._recordMessage( node, StrongModeCode.TOP_LEVEL_FUNCTION_LITERAL_BLOCK, []); } } @override visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { var functionType = node.function.staticType; if (node.typeArguments == null && functionType is FunctionType && functionType.typeFormals.isNotEmpty) { // Type inference might depend on the parameters super.visitFunctionExpressionInvocation(node); } } @override visitIndexExpression(IndexExpression node) { // Nothing to validate. } @override visitInstanceCreationExpression(InstanceCreationExpression node) { var constructor = node.staticElement; ClassElement class_ = constructor?.enclosingElement; if (node.constructorName.type.typeArguments == null && class_ != null && class_.typeParameters.isNotEmpty) { // Type inference might depend on the parameters super.visitInstanceCreationExpression(node); } } @override visitIsExpression(IsExpression node) { // Nothing to validate. } @override visitListLiteral(ListLiteral node) { if (node.typeArguments == null) { super.visitListLiteral(node); } } @override visitMethodInvocation(MethodInvocation node) { node.target?.accept(this); var method = node.methodName.staticElement; validateIdentifierElement(node, method, isMethodCall: true); if (method is ExecutableElement) { if (method.kind == ElementKind.METHOD && !method.isStatic && method.hasImplicitReturnType && flagTopLevel) { _codeChecker._recordMessage(node, StrongModeCode.TOP_LEVEL_INSTANCE_METHOD, [_name, method.name]); } if (node.typeArguments == null && method.typeParameters.isNotEmpty) { if (method.kind == ElementKind.METHOD && !method.isStatic && _anyParameterHasImplicitType(method) && flagTopLevel) { _codeChecker._recordMessage(node, StrongModeCode.TOP_LEVEL_INSTANCE_METHOD, [_name, method.name]); } // Type inference might depend on the parameters node.argumentList?.accept(this); } } } @override visitPrefixExpression(PrefixExpression node) { if (node.operator.type == TokenType.BANG) { // This operator gives 'bool', no need to validate operands. } else { node.operand.accept(this); } } @override visitSetOrMapLiteral(SetOrMapLiteral node) { if (node.typeArguments == null) { super.visitSetOrMapLiteral(node); } } @override visitSimpleIdentifier(SimpleIdentifier node) { validateIdentifierElement(node, node.staticElement); } @override visitThrowExpression(ThrowExpression node) { // Nothing to validate. } bool _anyParameterHasImplicitType(ExecutableElement e) { for (var parameter in e.parameters) { if (parameter.hasImplicitType) return true; } return false; } bool _hasAnyImplicitType(ExecutableElement e) { if (e.hasImplicitReturnType) return true; return _anyParameterHasImplicitType(e); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/required_parameters_verifier.dart
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/error/codes.dart'; /// Checks for missing arguments for required named parameters. class RequiredParametersVerifier extends SimpleAstVisitor<void> { final ErrorReporter _errorReporter; RequiredParametersVerifier(this._errorReporter); @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { _checkForMissingRequiredParam( node.staticInvokeType, node.argumentList, node, ); } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { _checkForMissingRequiredParam( node.staticElement?.type, node.argumentList, node.constructorName, ); } @override void visitMethodInvocation(MethodInvocation node) { _checkForMissingRequiredParam( node.staticInvokeType, node.argumentList, node.methodName, ); } @override void visitRedirectingConstructorInvocation( RedirectingConstructorInvocation node) { _checkForMissingRequiredParam( node.staticElement?.type, node.argumentList, node, ); } @override void visitSuperConstructorInvocation(SuperConstructorInvocation node) { _checkForMissingRequiredParam( node.staticElement?.type, node.argumentList, node, ); } void _checkForMissingRequiredParam( DartType type, ArgumentList argumentList, AstNode node, ) { if (type is FunctionType) { for (ParameterElement parameter in type.parameters) { if (parameter.isRequiredNamed) { String parameterName = parameter.name; if (!_containsNamedExpression(argumentList, parameterName)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.MISSING_REQUIRED_ARGUMENT, node, [parameterName], ); } } if (parameter.isOptionalNamed) { ElementAnnotationImpl annotation = _requiredAnnotation(parameter); if (annotation != null) { String parameterName = parameter.name; if (!_containsNamedExpression(argumentList, parameterName)) { String reason = _requiredReason(annotation); if (reason != null) { _errorReporter.reportErrorForNode( HintCode.MISSING_REQUIRED_PARAM_WITH_DETAILS, node, [parameterName, reason], ); } else { _errorReporter.reportErrorForNode( HintCode.MISSING_REQUIRED_PARAM, node, [parameterName], ); } } } } } } } static bool _containsNamedExpression(ArgumentList args, String name) { NodeList<Expression> arguments = args.arguments; for (int i = arguments.length - 1; i >= 0; i--) { Expression expression = arguments[i]; if (expression is NamedExpression) { if (expression.name.label.name == name) { return true; } } } return false; } static ElementAnnotationImpl _requiredAnnotation(ParameterElement element) { return element.metadata.firstWhere( (e) => e.isRequired, orElse: () => null, ); } static String _requiredReason(ElementAnnotationImpl annotation) { DartObject constantValue = annotation.computeConstantValue(); return constantValue?.getField('reason')?.toStringValue(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/analyzer_error_code.dart
// Copyright (c) 2019, 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:analyzer/error/error.dart'; /// A superclass for error codes that can have a url associated with them. abstract class AnalyzerErrorCode extends ErrorCode { /// Initialize a newly created error code. const AnalyzerErrorCode.temporary(String name, String message, {String correction, bool hasPublishedDocs, bool isUnresolvedIdentifier}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs ?? false, isUnresolvedIdentifier: isUnresolvedIdentifier ?? false); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/literal_element_verifier.dart
// Copyright (c) 2019, 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:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/resolver.dart'; /// Verifier for [CollectionElement]s in list, set, or map literals. class LiteralElementVerifier { final TypeProvider typeProvider; final TypeSystem typeSystem; final ErrorReporter errorReporter; final FeatureSet featureSet; final bool Function(Expression) checkForUseOfVoidResult; final bool forList; final bool forSet; final DartType elementType; final bool forMap; final DartType mapKeyType; final DartType mapValueType; LiteralElementVerifier( this.typeProvider, this.typeSystem, this.errorReporter, this.checkForUseOfVoidResult, { this.forList = false, this.forSet = false, this.elementType, this.forMap = false, this.mapKeyType, this.mapValueType, this.featureSet, }); void verify(CollectionElement element) { _verifyElement(element); } /// Check that the given [type] is assignable to the [elementType], otherwise /// report the list or set error on the [errorNode]. void _checkAssignableToElementType(DartType type, AstNode errorNode) { if (!typeSystem.isAssignableTo(type, elementType, featureSet: featureSet)) { var errorCode = forList ? StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE : StaticWarningCode.SET_ELEMENT_TYPE_NOT_ASSIGNABLE; errorReporter.reportTypeErrorForNode( errorCode, errorNode, [type, elementType], ); } } /// Verify that the given [element] can be assigned to the [elementType] of /// the enclosing list, set, of map literal. void _verifyElement(CollectionElement element) { if (element is Expression) { if (forList || forSet) { if (!elementType.isVoid && checkForUseOfVoidResult(element)) { return; } _checkAssignableToElementType(element.staticType, element); } else { errorReporter.reportErrorForNode( CompileTimeErrorCode.EXPRESSION_IN_MAP, element); } } else if (element is ForElement) { _verifyElement(element.body); } else if (element is IfElement) { _verifyElement(element.thenElement); _verifyElement(element.elseElement); } else if (element is MapLiteralEntry) { if (forMap) { _verifyMapLiteralEntry(element); } else { errorReporter.reportErrorForNode( CompileTimeErrorCode.MAP_ENTRY_NOT_IN_MAP, element); } } else if (element is SpreadElement) { var isNullAware = element.isNullAware; Expression expression = element.expression; if (forList || forSet) { _verifySpreadForListOrSet(isNullAware, expression); } else if (forMap) { _verifySpreadForMap(isNullAware, expression); } } } /// Verify that the [entry]'s key and value are assignable to [mapKeyType] /// and [mapValueType]. void _verifyMapLiteralEntry(MapLiteralEntry entry) { if (!mapKeyType.isVoid && checkForUseOfVoidResult(entry.key)) { return; } if (!mapValueType.isVoid && checkForUseOfVoidResult(entry.value)) { return; } var keyType = entry.key.staticType; if (!typeSystem.isAssignableTo(keyType, mapKeyType, featureSet: featureSet)) { errorReporter.reportTypeErrorForNode( StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE, entry.key, [keyType, mapKeyType], ); } var valueType = entry.value.staticType; if (!typeSystem.isAssignableTo(valueType, mapValueType, featureSet: featureSet)) { errorReporter.reportTypeErrorForNode( StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE, entry.value, [valueType, mapValueType], ); } } /// Verify that the type of the elements of the given [expression] can be /// assigned to the [elementType] of the enclosing collection. void _verifySpreadForListOrSet(bool isNullAware, Expression expression) { var expressionType = expression.staticType; if (expressionType.isDynamic) return; if (expressionType.isDartCoreNull) { if (!isNullAware) { errorReporter.reportErrorForNode( CompileTimeErrorCode.NOT_NULL_AWARE_NULL_SPREAD, expression, ); } return; } InterfaceType iterableType; var iterableDynamicType = (typeProvider.iterableDynamicType as TypeImpl) .withNullability(NullabilitySuffix.question); if (expressionType is InterfaceTypeImpl && typeSystem.isSubtypeOf(expressionType, iterableDynamicType)) { iterableType = expressionType.asInstanceOf( iterableDynamicType.element, ); } if (iterableType == null) { return errorReporter.reportErrorForNode( CompileTimeErrorCode.NOT_ITERABLE_SPREAD, expression, ); } var iterableElementType = iterableType.typeArguments[0]; if (!typeSystem.isAssignableTo(iterableElementType, elementType, featureSet: featureSet)) { var errorCode = forList ? StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE : StaticWarningCode.SET_ELEMENT_TYPE_NOT_ASSIGNABLE; errorReporter.reportTypeErrorForNode( errorCode, expression, [iterableElementType, elementType], ); } } /// Verify that the [expression] is a subtype of `Map<Object, Object>`, and /// its key and values are assignable to [mapKeyType] and [mapValueType]. void _verifySpreadForMap(bool isNullAware, Expression expression) { var expressionType = expression.staticType; if (expressionType.isDynamic) return; if (expressionType.isDartCoreNull) { if (!isNullAware) { errorReporter.reportErrorForNode( CompileTimeErrorCode.NOT_NULL_AWARE_NULL_SPREAD, expression, ); } return; } InterfaceType mapType; var mapObjectObjectType = typeProvider.mapObjectObjectType; if (expressionType is InterfaceTypeImpl && typeSystem.isSubtypeOf(expressionType, mapObjectObjectType)) { mapType = expressionType.asInstanceOf(mapObjectObjectType.element); } if (mapType == null) { return errorReporter.reportErrorForNode( CompileTimeErrorCode.NOT_MAP_SPREAD, expression, ); } var keyType = mapType.typeArguments[0]; if (!typeSystem.isAssignableTo(keyType, mapKeyType, featureSet: featureSet)) { errorReporter.reportTypeErrorForNode( StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE, expression, [keyType, mapKeyType], ); } var valueType = mapType.typeArguments[1]; if (!typeSystem.isAssignableTo(valueType, mapValueType, featureSet: featureSet)) { errorReporter.reportTypeErrorForNode( StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE, expression, [valueType, mapValueType], ); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/duplicate_definition_verifier.dart
// Copyright (c) 2019, 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/error/codes.dart'; class DuplicateDefinitionVerifier { final LibraryElement _currentLibrary; final ErrorReporter _errorReporter; DuplicateDefinitionVerifier(this._currentLibrary, this._errorReporter); /// Check that the exception and stack trace parameters have different names. void checkCatchClause(CatchClause node) { SimpleIdentifier exceptionParameter = node.exceptionParameter; SimpleIdentifier stackTraceParameter = node.stackTraceParameter; if (exceptionParameter != null && stackTraceParameter != null) { String exceptionName = exceptionParameter.name; if (exceptionName == stackTraceParameter.name) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.DUPLICATE_DEFINITION, stackTraceParameter, [exceptionName]); } } } void checkClass(ClassDeclaration node) { _checkClassMembers(node.declaredElement, node.members); } /// Check that there are no members with the same name. void checkEnum(EnumDeclaration node) { ClassElement element = node.declaredElement; Map<String, Element> instanceGetters = new HashMap<String, Element>(); Map<String, Element> staticGetters = new HashMap<String, Element>(); String indexName = 'index'; String valuesName = 'values'; instanceGetters[indexName] = element.getGetter(indexName); staticGetters[valuesName] = element.getGetter(valuesName); for (EnumConstantDeclaration constant in node.constants) { _checkDuplicateIdentifier(staticGetters, constant.name); } for (EnumConstantDeclaration constant in node.constants) { SimpleIdentifier identifier = constant.name; String name = identifier.name; if (instanceGetters.containsKey(name)) { String enumName = element.displayName; _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONFLICTING_STATIC_AND_INSTANCE, identifier, [enumName, name, enumName]); } } } /// Check that there are no members with the same name. void checkExtension(ExtensionDeclaration node) { var instanceGetters = <String, Element>{}; var instanceSetters = <String, Element>{}; var staticGetters = <String, Element>{}; var staticSetters = <String, Element>{}; for (var member in node.members) { if (member is FieldDeclaration) { for (var field in member.fields.variables) { var identifier = field.name; _checkDuplicateIdentifier( member.isStatic ? staticGetters : instanceGetters, identifier, setterScope: member.isStatic ? staticSetters : instanceSetters, ); } } else if (member is MethodDeclaration) { _checkDuplicateIdentifier( member.isStatic ? staticGetters : instanceGetters, member.name, setterScope: member.isStatic ? staticSetters : instanceSetters, ); } } // Check for local static members conflicting with local instance members. for (var member in node.members) { if (member is FieldDeclaration) { if (member.isStatic) { for (var field in member.fields.variables) { var identifier = field.name; var name = identifier.name; if (instanceGetters.containsKey(name) || instanceSetters.containsKey(name)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.EXTENSION_CONFLICTING_STATIC_AND_INSTANCE, identifier, [node.declaredElement.name, name], ); } } } } else if (member is MethodDeclaration) { if (member.isStatic) { var identifier = member.name; var name = identifier.name; if (instanceGetters.containsKey(name) || instanceSetters.containsKey(name)) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.EXTENSION_CONFLICTING_STATIC_AND_INSTANCE, identifier, [node.declaredElement.name, name], ); } } } } } /// Check that the given list of variable declarations does not define /// multiple variables of the same name. void checkForVariables(VariableDeclarationList node) { Map<String, Element> definedNames = new HashMap<String, Element>(); for (VariableDeclaration variable in node.variables) { _checkDuplicateIdentifier(definedNames, variable.name); } } void checkMixin(MixinDeclaration node) { _checkClassMembers(node.declaredElement, node.members); } /** * Check that all of the parameters have unique names. */ void checkParameters(FormalParameterList node) { Map<String, Element> definedNames = new HashMap<String, Element>(); for (FormalParameter parameter in node.parameters) { SimpleIdentifier identifier = parameter.identifier; if (identifier != null) { // The identifier can be null if this is a parameter list for a generic // function type. _checkDuplicateIdentifier(definedNames, identifier); } } } /// Check that all of the variables have unique names. void checkStatements(List<Statement> statements) { Map<String, Element> definedNames = new HashMap<String, Element>(); for (Statement statement in statements) { if (statement is VariableDeclarationStatement) { for (VariableDeclaration variable in statement.variables.variables) { _checkDuplicateIdentifier(definedNames, variable.name); } } else if (statement is FunctionDeclarationStatement) { _checkDuplicateIdentifier( definedNames, statement.functionDeclaration.name); } } } /// Check that all of the parameters have unique names. void checkTypeParameters(TypeParameterList node) { Map<String, Element> definedNames = new HashMap<String, Element>(); for (TypeParameter parameter in node.typeParameters) { _checkDuplicateIdentifier(definedNames, parameter.name); } } /// Check that there are no members with the same name. void checkUnit(CompilationUnit node) { Map<String, Element> definedGetters = new HashMap<String, Element>(); Map<String, Element> definedSetters = new HashMap<String, Element>(); void addWithoutChecking(CompilationUnitElement element) { for (PropertyAccessorElement accessor in element.accessors) { String name = accessor.name; if (accessor.isSetter) { name += '='; } definedGetters[name] = accessor; } for (ClassElement type in element.enums) { definedGetters[type.name] = type; } for (FunctionElement function in element.functions) { definedGetters[function.name] = function; } for (FunctionTypeAliasElement alias in element.functionTypeAliases) { definedGetters[alias.name] = alias; } for (TopLevelVariableElement variable in element.topLevelVariables) { definedGetters[variable.name] = variable; if (!variable.isFinal && !variable.isConst) { definedGetters[variable.name + '='] = variable; } } for (ClassElement type in element.types) { definedGetters[type.name] = type; } } for (ImportElement importElement in _currentLibrary.imports) { PrefixElement prefix = importElement.prefix; if (prefix != null) { definedGetters[prefix.name] = prefix; } } CompilationUnitElement element = node.declaredElement; if (element != _currentLibrary.definingCompilationUnit) { addWithoutChecking(_currentLibrary.definingCompilationUnit); for (CompilationUnitElement part in _currentLibrary.parts) { if (element == part) { break; } addWithoutChecking(part); } } for (CompilationUnitMember member in node.declarations) { if (member is ExtensionDeclaration) { var identifier = member.name; if (identifier != null) { _checkDuplicateIdentifier(definedGetters, identifier, setterScope: definedSetters); } } else if (member is NamedCompilationUnitMember) { _checkDuplicateIdentifier(definedGetters, member.name, setterScope: definedSetters); } else if (member is TopLevelVariableDeclaration) { for (VariableDeclaration variable in member.variables.variables) { _checkDuplicateIdentifier(definedGetters, variable.name, setterScope: definedSetters); } } } } /// Check that there are no members with the same name. void _checkClassMembers(ClassElement element, List<ClassMember> members) { Set<String> constructorNames = new HashSet<String>(); Map<String, Element> instanceGetters = new HashMap<String, Element>(); Map<String, Element> instanceSetters = new HashMap<String, Element>(); Map<String, Element> staticGetters = new HashMap<String, Element>(); Map<String, Element> staticSetters = new HashMap<String, Element>(); for (ClassMember member in members) { if (member is ConstructorDeclaration) { var name = member.name?.name ?? ''; if (!constructorNames.add(name)) { if (name.isEmpty) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, member); } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_NAME, member, [name]); } } } else if (member is FieldDeclaration) { for (VariableDeclaration field in member.fields.variables) { SimpleIdentifier identifier = field.name; _checkDuplicateIdentifier( member.isStatic ? staticGetters : instanceGetters, identifier, setterScope: member.isStatic ? staticSetters : instanceSetters, ); } } else if (member is MethodDeclaration) { _checkDuplicateIdentifier( member.isStatic ? staticGetters : instanceGetters, member.name, setterScope: member.isStatic ? staticSetters : instanceSetters, ); } } // Check for local static members conflicting with local instance members. for (ClassMember member in members) { if (member is ConstructorDeclaration) { if (member.name != null) { String name = member.name.name; var staticMember = staticGetters[name] ?? staticSetters[name]; if (staticMember != null) { if (staticMember is PropertyAccessorElement) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_AND_STATIC_FIELD, member.name, [name], ); } else { _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_AND_STATIC_METHOD, member.name, [name], ); } } } } else if (member is FieldDeclaration) { if (member.isStatic) { for (VariableDeclaration field in member.fields.variables) { SimpleIdentifier identifier = field.name; String name = identifier.name; if (instanceGetters.containsKey(name) || instanceSetters.containsKey(name)) { String className = element.displayName; _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONFLICTING_STATIC_AND_INSTANCE, identifier, [className, name, className]); } } } } else if (member is MethodDeclaration) { if (member.isStatic) { SimpleIdentifier identifier = member.name; String name = identifier.name; if (instanceGetters.containsKey(name) || instanceSetters.containsKey(name)) { String className = identifier.staticElement.enclosingElement.name; _errorReporter.reportErrorForNode( CompileTimeErrorCode.CONFLICTING_STATIC_AND_INSTANCE, identifier, [className, name, className]); } } } } } /// Check whether the given [element] defined by the [identifier] is already /// in one of the scopes - [getterScope] or [setterScope], and produce an /// error if it is. void _checkDuplicateIdentifier( Map<String, Element> getterScope, SimpleIdentifier identifier, {Element element, Map<String, Element> setterScope}) { if (identifier.isSynthetic) { return; } element ??= identifier.staticElement; // Fields define getters and setters, so check them separately. if (element is PropertyInducingElement) { _checkDuplicateIdentifier(getterScope, identifier, element: element.getter, setterScope: setterScope); if (!element.isConst && !element.isFinal) { _checkDuplicateIdentifier(getterScope, identifier, element: element.setter, setterScope: setterScope); } return; } ErrorCode getError(Element previous, Element current) { if (previous is PrefixElement) { return CompileTimeErrorCode.PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER; } return CompileTimeErrorCode.DUPLICATE_DEFINITION; } bool isGetterSetterPair(Element a, Element b) { if (a is PropertyAccessorElement && b is PropertyAccessorElement) { return a.isGetter && b.isSetter || a.isSetter && b.isGetter; } return false; } String name = identifier.name; if (element is MethodElement && element.isOperator && name == '-') { if (element.parameters.isEmpty) { name = 'unary-'; } } Element previous = getterScope[name]; if (previous != null) { if (isGetterSetterPair(element, previous)) { // OK } else { _errorReporter.reportErrorForNode( getError(previous, element), identifier, [name], ); } } else { getterScope[name] = element; } if (element is PropertyAccessorElement && element.isSetter) { previous = setterScope[name]; if (previous != null) { _errorReporter.reportErrorForNode( getError(previous, element), identifier, [name], ); } else { setterScope[name] = element; } } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/imports_verifier.dart
// Copyright (c) 2019, 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/resolver/scope.dart'; import 'package:analyzer/src/error/codes.dart'; /// A visitor that visits ASTs and fills [UsedImportedElements]. class GatherUsedImportedElementsVisitor extends RecursiveAstVisitor { final LibraryElement library; final UsedImportedElements usedElements = new UsedImportedElements(); GatherUsedImportedElementsVisitor(this.library); @override void visitBinaryExpression(BinaryExpression node) { _recordIfExtensionMember(node.staticElement); return super.visitBinaryExpression(node); } @override void visitExportDirective(ExportDirective node) { _visitDirective(node); } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { _recordIfExtensionMember(node.staticElement); return super.visitFunctionExpressionInvocation(node); } @override void visitImportDirective(ImportDirective node) { _visitDirective(node); } @override void visitIndexExpression(IndexExpression node) { _recordIfExtensionMember(node.staticElement); return super.visitIndexExpression(node); } @override void visitLibraryDirective(LibraryDirective node) { _visitDirective(node); } @override void visitPrefixExpression(PrefixExpression node) { _recordIfExtensionMember(node.staticElement); return super.visitPrefixExpression(node); } @override void visitSimpleIdentifier(SimpleIdentifier node) { _visitIdentifier(node, node.staticElement); } void _recordIfExtensionMember(Element element) { if (element != null && element.enclosingElement is ExtensionElement) { _recordUsedExtension(element.enclosingElement); } } /// If the given [identifier] is prefixed with a [PrefixElement], fill the /// corresponding `UsedImportedElements.prefixMap` entry and return `true`. bool _recordPrefixMap(SimpleIdentifier identifier, Element element) { bool recordIfTargetIsPrefixElement(Expression target) { if (target is SimpleIdentifier && target.staticElement is PrefixElement) { List<Element> prefixedElements = usedElements.prefixMap .putIfAbsent(target.staticElement, () => <Element>[]); prefixedElements.add(element); return true; } return false; } AstNode parent = identifier.parent; if (parent is MethodInvocation && parent.methodName == identifier) { return recordIfTargetIsPrefixElement(parent.target); } if (parent is PrefixedIdentifier && parent.identifier == identifier) { return recordIfTargetIsPrefixElement(parent.prefix); } return false; } void _recordUsedElement(Element element) { // Ignore if an unknown library. LibraryElement containingLibrary = element.library; if (containingLibrary == null) { return; } // Ignore if a local element. if (library == containingLibrary) { return; } // Remember the element. usedElements.elements.add(element); } void _recordUsedExtension(ExtensionElement extension) { // Ignore if a local element. if (library == extension.library) { return; } // Remember the element. usedElements.usedExtensions.add(extension); } /// Visit identifiers used by the given [directive]. void _visitDirective(Directive directive) { directive.documentationComment?.accept(this); directive.metadata.accept(this); } void _visitIdentifier(SimpleIdentifier identifier, Element element) { if (element == null) { return; } // Record `importPrefix.identifier` into 'prefixMap'. if (_recordPrefixMap(identifier, element)) { return; } Element enclosingElement = element.enclosingElement; if (enclosingElement is CompilationUnitElement) { _recordUsedElement(element); } else if (enclosingElement is ExtensionElement) { _recordUsedExtension(enclosingElement); return; } else if (element is PrefixElement) { usedElements.prefixMap.putIfAbsent(element, () => <Element>[]); } else if (element is MultiplyDefinedElement) { // If the element is multiply defined then call this method recursively // for each of the conflicting elements. List<Element> conflictingElements = element.conflictingElements; int length = conflictingElements.length; for (int i = 0; i < length; i++) { Element elt = conflictingElements[i]; _visitIdentifier(identifier, elt); } } } } /// Instances of the class `ImportsVerifier` visit all of the referenced /// libraries in the source code verifying that all of the imports are used, /// otherwise a [HintCode.UNUSED_IMPORT] hint is generated with /// [generateUnusedImportHints]. /// /// Additionally, [generateDuplicateImportHints] generates /// [HintCode.DUPLICATE_IMPORT] hints and [HintCode.UNUSED_SHOWN_NAME] hints. /// /// While this class does not yet have support for an "Organize Imports" action, /// this logic built up in this class could be used for such an action in the /// future. class ImportsVerifier { /// All [ImportDirective]s of the current library. final List<ImportDirective> _allImports = <ImportDirective>[]; /// A list of [ImportDirective]s that the current library imports, but does /// not use. /// /// As identifiers are visited by this visitor and an import has been /// identified as being used by the library, the [ImportDirective] is removed /// from this list. After all the sources in the library have been evaluated, /// this list represents the set of unused imports. /// /// See [ImportsVerifier.generateUnusedImportErrors]. final List<ImportDirective> _unusedImports = <ImportDirective>[]; /// After the list of [unusedImports] has been computed, this list is a proper /// subset of the unused imports that are listed more than once. final List<ImportDirective> _duplicateImports = <ImportDirective>[]; /// The cache of [Namespace]s for [ImportDirective]s. final HashMap<ImportDirective, Namespace> _namespaceMap = new HashMap<ImportDirective, Namespace>(); /// This is a map between prefix elements and the import directives from which /// they are derived. In cases where a type is referenced via a prefix /// element, the import directive can be marked as used (removed from the /// unusedImports) by looking at the resolved `lib` in `lib.X`, instead of /// looking at which library the `lib.X` resolves. /// /// TODO (jwren) Since multiple [ImportDirective]s can share the same /// [PrefixElement], it is possible to have an unreported unused import in /// situations where two imports use the same prefix and at least one import /// directive is used. final HashMap<PrefixElement, List<ImportDirective>> _prefixElementMap = new HashMap<PrefixElement, List<ImportDirective>>(); /// A map of identifiers that the current library's imports show, but that the /// library does not use. /// /// Each import directive maps to a list of the identifiers that are imported /// via the "show" keyword. /// /// As each identifier is visited by this visitor, it is identified as being /// used by the library, and the identifier is removed from this map (under /// the import that imported it). After all the sources in the library have /// been evaluated, each list in this map's values present the set of unused /// shown elements. /// /// See [ImportsVerifier.generateUnusedShownNameHints]. final HashMap<ImportDirective, List<SimpleIdentifier>> _unusedShownNamesMap = new HashMap<ImportDirective, List<SimpleIdentifier>>(); /// A map of names that are hidden more than once. final HashMap<NamespaceDirective, List<SimpleIdentifier>> _duplicateHiddenNamesMap = new HashMap<NamespaceDirective, List<SimpleIdentifier>>(); /// A map of names that are shown more than once. final HashMap<NamespaceDirective, List<SimpleIdentifier>> _duplicateShownNamesMap = new HashMap<NamespaceDirective, List<SimpleIdentifier>>(); void addImports(CompilationUnit node) { for (Directive directive in node.directives) { if (directive is ImportDirective) { LibraryElement libraryElement = directive.uriElement; if (libraryElement == null) { continue; } _allImports.add(directive); _unusedImports.add(directive); // // Initialize prefixElementMap // if (directive.asKeyword != null) { SimpleIdentifier prefixIdentifier = directive.prefix; if (prefixIdentifier != null) { Element element = prefixIdentifier.staticElement; if (element is PrefixElement) { List<ImportDirective> list = _prefixElementMap[element]; if (list == null) { list = new List<ImportDirective>(); _prefixElementMap[element] = list; } list.add(directive); } // TODO (jwren) Can the element ever not be a PrefixElement? } } _addShownNames(directive); } if (directive is NamespaceDirective) { _addDuplicateShownHiddenNames(directive); } } if (_unusedImports.length > 1) { // order the list of unusedImports to find duplicates in faster than // O(n^2) time List<ImportDirective> importDirectiveArray = new List<ImportDirective>.from(_unusedImports); importDirectiveArray.sort(ImportDirective.COMPARATOR); ImportDirective currentDirective = importDirectiveArray[0]; for (int i = 1; i < importDirectiveArray.length; i++) { ImportDirective nextDirective = importDirectiveArray[i]; if (ImportDirective.COMPARATOR(currentDirective, nextDirective) == 0) { // Add either the currentDirective or nextDirective depending on which // comes second, this guarantees that the first of the duplicates // won't be highlighted. if (currentDirective.offset < nextDirective.offset) { _duplicateImports.add(nextDirective); } else { _duplicateImports.add(currentDirective); } } currentDirective = nextDirective; } } } /// Any time after the defining compilation unit has been visited by this /// visitor, this method can be called to report an /// [HintCode.DUPLICATE_IMPORT] hint for each of the import directives in the /// [duplicateImports] list. /// /// @param errorReporter the error reporter to report the set of /// [HintCode.DUPLICATE_IMPORT] hints to void generateDuplicateImportHints(ErrorReporter errorReporter) { int length = _duplicateImports.length; for (int i = 0; i < length; i++) { errorReporter.reportErrorForNode( HintCode.DUPLICATE_IMPORT, _duplicateImports[i].uri); } } /// Report a [HintCode.DUPLICATE_SHOWN_HIDDEN_NAME] hint for each duplicate /// shown or hidden name. /// /// Only call this method after all of the compilation units have been visited /// by this visitor. /// /// @param errorReporter the error reporter used to report the set of /// [HintCode.UNUSED_SHOWN_NAME] hints void generateDuplicateShownHiddenNameHints(ErrorReporter reporter) { _duplicateHiddenNamesMap.forEach( (NamespaceDirective directive, List<SimpleIdentifier> identifiers) { int length = identifiers.length; for (int i = 0; i < length; i++) { Identifier identifier = identifiers[i]; reporter.reportErrorForNode( HintCode.DUPLICATE_HIDDEN_NAME, identifier, [identifier.name]); } }); _duplicateShownNamesMap.forEach( (NamespaceDirective directive, List<SimpleIdentifier> identifiers) { int length = identifiers.length; for (int i = 0; i < length; i++) { Identifier identifier = identifiers[i]; reporter.reportErrorForNode( HintCode.DUPLICATE_SHOWN_NAME, identifier, [identifier.name]); } }); } /// Report an [HintCode.UNUSED_IMPORT] hint for each unused import. /// /// Only call this method after all of the compilation units have been visited /// by this visitor. /// /// @param errorReporter the error reporter used to report the set of /// [HintCode.UNUSED_IMPORT] hints void generateUnusedImportHints(ErrorReporter errorReporter) { int length = _unusedImports.length; for (int i = 0; i < length; i++) { ImportDirective unusedImport = _unusedImports[i]; // Check that the imported URI exists and isn't dart:core ImportElement importElement = unusedImport.element; if (importElement != null) { LibraryElement libraryElement = importElement.importedLibrary; if (libraryElement == null || libraryElement.isDartCore || libraryElement.isSynthetic) { continue; } } StringLiteral uri = unusedImport.uri; errorReporter .reportErrorForNode(HintCode.UNUSED_IMPORT, uri, [uri.stringValue]); } } /// Use the error [reporter] to report an [HintCode.UNUSED_SHOWN_NAME] hint /// for each unused shown name. /// /// This method should only be invoked after all of the compilation units have /// been visited by this visitor. void generateUnusedShownNameHints(ErrorReporter reporter) { _unusedShownNamesMap.forEach( (ImportDirective importDirective, List<SimpleIdentifier> identifiers) { if (_unusedImports.contains(importDirective)) { // The whole import is unused, not just one or more shown names from it, // so an "unused_import" hint will be generated, making it unnecessary // to generate hints for the individual names. return; } int length = identifiers.length; for (int i = 0; i < length; i++) { Identifier identifier = identifiers[i]; List<SimpleIdentifier> duplicateNames = _duplicateShownNamesMap[importDirective]; if (duplicateNames == null || !duplicateNames.contains(identifier)) { // Only generate a hint if we won't also generate a // "duplicate_shown_name" hint for the same identifier. reporter.reportErrorForNode( HintCode.UNUSED_SHOWN_NAME, identifier, [identifier.name]); } } }); } /// Remove elements from [_unusedImports] using the given [usedElements]. void removeUsedElements(UsedImportedElements usedElements) { // Stop if all the imports and shown names are known to be used. if (_unusedImports.isEmpty && _unusedShownNamesMap.isEmpty) { return; } // Process import prefixes. usedElements.prefixMap .forEach((PrefixElement prefix, List<Element> elements) { List<ImportDirective> importDirectives = _prefixElementMap[prefix]; if (importDirectives != null) { int importLength = importDirectives.length; for (int i = 0; i < importLength; i++) { ImportDirective importDirective = importDirectives[i]; _unusedImports.remove(importDirective); int elementLength = elements.length; for (int j = 0; j < elementLength; j++) { Element element = elements[j]; _removeFromUnusedShownNamesMap(element, importDirective); } } } }); // Process top-level elements. for (Element element in usedElements.elements) { // Stop if all the imports and shown names are known to be used. if (_unusedImports.isEmpty && _unusedShownNamesMap.isEmpty) { return; } // Find import directives using namespaces. String name = element.name; for (ImportDirective importDirective in _allImports) { Namespace namespace = _computeNamespace(importDirective); if (namespace?.get(name) != null) { _unusedImports.remove(importDirective); _removeFromUnusedShownNamesMap(element, importDirective); } } } // Process extension elements. for (ExtensionElement extensionElement in usedElements.usedExtensions) { // Stop if all the imports and shown names are known to be used. if (_unusedImports.isEmpty && _unusedShownNamesMap.isEmpty) { return; } // Find import directives using namespaces. String name = extensionElement.name; for (ImportDirective importDirective in _allImports) { Namespace namespace = _computeNamespace(importDirective); if (namespace?.get(name) == extensionElement) { _unusedImports.remove(importDirective); _removeFromUnusedShownNamesMap(extensionElement, importDirective); } } } } /// Add duplicate shown and hidden names from [directive] into /// [_duplicateHiddenNamesMap] and [_duplicateShownNamesMap]. void _addDuplicateShownHiddenNames(NamespaceDirective directive) { if (directive.combinators == null) { return; } for (Combinator combinator in directive.combinators) { // Use a Set to find duplicates in faster than O(n^2) time. Set<Element> identifiers = new Set<Element>(); if (combinator is HideCombinator) { for (SimpleIdentifier name in combinator.hiddenNames) { if (name.staticElement != null) { if (!identifiers.add(name.staticElement)) { // [name] is a duplicate. List<SimpleIdentifier> duplicateNames = _duplicateHiddenNamesMap .putIfAbsent(directive, () => new List<SimpleIdentifier>()); duplicateNames.add(name); } } } } else if (combinator is ShowCombinator) { for (SimpleIdentifier name in combinator.shownNames) { if (name.staticElement != null) { if (!identifiers.add(name.staticElement)) { // [name] is a duplicate. List<SimpleIdentifier> duplicateNames = _duplicateShownNamesMap .putIfAbsent(directive, () => new List<SimpleIdentifier>()); duplicateNames.add(name); } } } } } } /// Add every shown name from [importDirective] into [_unusedShownNamesMap]. void _addShownNames(ImportDirective importDirective) { if (importDirective.combinators == null) { return; } List<SimpleIdentifier> identifiers = new List<SimpleIdentifier>(); _unusedShownNamesMap[importDirective] = identifiers; for (Combinator combinator in importDirective.combinators) { if (combinator is ShowCombinator) { for (SimpleIdentifier name in combinator.shownNames) { if (name.staticElement != null) { identifiers.add(name); } } } } } /// Lookup and return the [Namespace] from the [_namespaceMap]. /// /// If the map does not have the computed namespace, compute it and cache it /// in the map. If [importDirective] is not resolved or is not resolvable, /// `null` is returned. /// /// @param importDirective the import directive used to compute the returned /// namespace /// @return the computed or looked up [Namespace] Namespace _computeNamespace(ImportDirective importDirective) { Namespace namespace = _namespaceMap[importDirective]; if (namespace == null) { // If the namespace isn't in the namespaceMap, then compute and put it in // the map. ImportElement importElement = importDirective.element; if (importElement != null) { namespace = importElement.namespace; _namespaceMap[importDirective] = namespace; } } return namespace; } /// Remove [element] from the list of names shown by [importDirective]. void _removeFromUnusedShownNamesMap( Element element, ImportDirective importDirective) { List<SimpleIdentifier> identifiers = _unusedShownNamesMap[importDirective]; if (identifiers == null) { return; } int length = identifiers.length; for (int i = 0; i < length; i++) { Identifier identifier = identifiers[i]; if (element is PropertyAccessorElement) { // If the getter or setter of a variable is used, then the variable (the // shown name) is used. if (identifier.staticElement == element.variable) { identifiers.remove(identifier); break; } } else { if (identifier.staticElement == element) { identifiers.remove(identifier); break; } } } if (identifiers.isEmpty) { _unusedShownNamesMap.remove(importDirective); } } } /// A container with information about used imports prefixes and used imported /// elements. class UsedImportedElements { /// The map of referenced prefix elements and the elements that they prefix. final Map<PrefixElement, List<Element>> prefixMap = {}; /// The set of referenced top-level elements. final Set<Element> elements = {}; /// The set of extensions defining members that are referenced. final Set<ExtensionElement> usedExtensions = {}; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/type_arguments_verifier.dart
// Copyright (c) 2019, 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 "dart:math" as math; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/dart/element/type_algebra.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl; import 'package:analyzer/src/generated/resolver.dart'; class TypeArgumentsVerifier { final AnalysisOptionsImpl _options; final TypeSystem _typeSystem; final ErrorReporter _errorReporter; TypeArgumentsVerifier(this._options, this._typeSystem, this._errorReporter); TypeProvider get _typeProvider => _typeSystem.typeProvider; void checkFunctionExpressionInvocation(FunctionExpressionInvocation node) { _checkTypeArguments(node); _checkForImplicitDynamicInvoke(node); } void checkListLiteral(ListLiteral node) { TypeArgumentList typeArguments = node.typeArguments; if (typeArguments != null) { if (node.isConst) { _checkTypeArgumentConst( typeArguments.arguments, CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_LIST, ); } _checkTypeArgumentCount(typeArguments, 1, StaticTypeWarningCode.EXPECTED_ONE_LIST_TYPE_ARGUMENTS); } _checkForImplicitDynamicTypedLiteral(node); } void checkMapLiteral(SetOrMapLiteral node) { TypeArgumentList typeArguments = node.typeArguments; if (typeArguments != null) { if (node.isConst) { _checkTypeArgumentConst( typeArguments.arguments, CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_MAP, ); } _checkTypeArgumentCount(typeArguments, 2, StaticTypeWarningCode.EXPECTED_TWO_MAP_TYPE_ARGUMENTS); } _checkForImplicitDynamicTypedLiteral(node); } void checkMethodInvocation(MethodInvocation node) { _checkTypeArguments(node); _checkForImplicitDynamicInvoke(node); } void checkSetLiteral(SetOrMapLiteral node) { TypeArgumentList typeArguments = node.typeArguments; if (typeArguments != null) { if (node.isConst) { _checkTypeArgumentConst( typeArguments.arguments, CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_SET, ); } _checkTypeArgumentCount(typeArguments, 1, StaticTypeWarningCode.EXPECTED_ONE_SET_TYPE_ARGUMENTS); } _checkForImplicitDynamicTypedLiteral(node); } void checkTypeName(TypeName node) { _checkForTypeArgumentNotMatchingBounds(node); if (node.parent is! ConstructorName || node.parent.parent is! InstanceCreationExpression) { _checkForRawTypeName(node); } } void _checkForImplicitDynamicInvoke(InvocationExpression node) { if (_options.implicitDynamic || node == null || node.typeArguments != null) { return; } DartType invokeType = node.staticInvokeType; DartType declaredType = node.function.staticType; if (invokeType is FunctionType && declaredType is FunctionType && declaredType.typeFormals.isNotEmpty) { List<DartType> typeArgs = node.typeArgumentTypes; if (typeArgs.any((t) => t.isDynamic)) { // Issue an error depending on what we're trying to call. Expression function = node.function; if (function is Identifier) { Element element = function.staticElement; if (element is MethodElement) { _errorReporter.reportErrorForNode( StrongModeCode.IMPLICIT_DYNAMIC_METHOD, node.function, [element.displayName, element.typeParameters.join(', ')]); return; } if (element is FunctionElement) { _errorReporter.reportErrorForNode( StrongModeCode.IMPLICIT_DYNAMIC_FUNCTION, node.function, [element.displayName, element.typeParameters.join(', ')]); return; } } // The catch all case if neither of those matched. // For example, invoking a function expression. _errorReporter.reportErrorForNode( StrongModeCode.IMPLICIT_DYNAMIC_INVOKE, node.function, [declaredType]); } } } void _checkForImplicitDynamicTypedLiteral(TypedLiteral node) { if (_options.implicitDynamic || node.typeArguments != null) { return; } DartType type = node.staticType; // It's an error if either the key or value was inferred as dynamic. if (type is InterfaceType && type.typeArguments.any((t) => t.isDynamic)) { // TODO(brianwilkerson) Add StrongModeCode.IMPLICIT_DYNAMIC_SET_LITERAL ErrorCode errorCode = node is ListLiteral ? StrongModeCode.IMPLICIT_DYNAMIC_LIST_LITERAL : StrongModeCode.IMPLICIT_DYNAMIC_MAP_LITERAL; _errorReporter.reportErrorForNode(errorCode, node); } } /// Checks a type annotation for a raw generic type, and reports the /// appropriate error if [AnalysisOptionsImpl.strictRawTypes] is set. /// /// This checks if [node] refers to a generic type and does not have explicit /// or inferred type arguments. When that happens, it reports error code /// [HintCode.STRICT_RAW_TYPE]. void _checkForRawTypeName(TypeName node) { AstNode parentEscapingTypeArguments(TypeName node) { AstNode parent = node.parent; while (parent is TypeArgumentList || parent is TypeName) { if (parent.parent == null) { return parent; } parent = parent.parent; } return parent; } if (!_options.strictRawTypes || node == null) return; if (node.typeArguments != null) { // Type has explicit type arguments. return; } if (_isMissingTypeArguments( node, node.type, node.name.staticElement, null)) { AstNode unwrappedParent = parentEscapingTypeArguments(node); if (unwrappedParent is AsExpression || unwrappedParent is IsExpression) { // Do not report a "Strict raw type" error in this case; too noisy. // See https://github.com/dart-lang/language/blob/master/resources/type-system/strict-raw-types.md#conditions-for-a-raw-type-hint } else { _errorReporter .reportErrorForNode(HintCode.STRICT_RAW_TYPE, node, [node.type]); } } } /** * Verify that the type arguments in the given [typeName] are all within * their bounds. */ void _checkForTypeArgumentNotMatchingBounds(TypeName typeName) { // prepare Type DartType type = typeName.type; if (type == null) { return; } if (type is ParameterizedType) { var element = typeName.name.staticElement; // prepare type parameters List<TypeParameterElement> parameterElements; if (element is ClassElement) { parameterElements = element.typeParameters; } else if (element is GenericTypeAliasElement) { parameterElements = element.typeParameters; } else if (element is GenericFunctionTypeElement) { // TODO(paulberry): it seems like either this case or the one above // should be unnecessary. FunctionTypeAliasElement typedefElement = element.enclosingElement; parameterElements = typedefElement.typeParameters; } else if (type is FunctionType) { parameterElements = type.typeFormals; } else { // There are no other kinds of parameterized types. throw new UnimplementedError( 'Unexpected element associated with parameterized type: ' '${element.runtimeType}'); } List<DartType> arguments = type.typeArguments; // iterate over each bounded type parameter and corresponding argument NodeList<TypeAnnotation> argumentNodes = typeName.typeArguments?.arguments; var typeArguments = type.typeArguments; int loopThroughIndex = math.min(typeArguments.length, parameterElements.length); bool shouldSubstitute = arguments.isNotEmpty && arguments.length == parameterElements.length; for (int i = 0; i < loopThroughIndex; i++) { DartType argType = typeArguments[i]; TypeAnnotation argumentNode = argumentNodes != null && i < argumentNodes.length ? argumentNodes[i] : typeName; if (argType is FunctionType && argType.typeFormals.isNotEmpty) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.GENERIC_FUNCTION_TYPE_CANNOT_BE_TYPE_ARGUMENT, argumentNode, ); continue; } DartType boundType = parameterElements[i].bound; if (argType != null && boundType != null) { if (shouldSubstitute) { boundType = Substitution.fromPairs(parameterElements, arguments) .substituteType(boundType); } if (!_typeSystem.isSubtypeOf(argType, boundType)) { if (_shouldAllowSuperBoundedTypes(typeName)) { var replacedType = (argType as TypeImpl).replaceTopAndBottom(_typeProvider); if (!identical(replacedType, argType) && _typeSystem.isSubtypeOf(replacedType, boundType)) { // Bound is satisfied under super-bounded rules, so we're ok. continue; } } _errorReporter.reportTypeErrorForNode( CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS, argumentNode, [argType, boundType]); } } } } } /** * Checks to ensure that the given list of type [arguments] does not have a * type parameter as a type argument. The [errorCode] is either * [CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_LIST] or * [CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_MAP]. */ void _checkTypeArgumentConst( NodeList<TypeAnnotation> arguments, ErrorCode errorCode) { for (TypeAnnotation type in arguments) { if (type is TypeName && type.type is TypeParameterType) { _errorReporter.reportErrorForNode(errorCode, type, [type.name]); } } } /// Verify that the given list of [typeArguments] contains exactly the /// [expectedCount] of elements, reporting an error with the [errorCode] /// if not. void _checkTypeArgumentCount( TypeArgumentList typeArguments, int expectedCount, ErrorCode errorCode, ) { int actualCount = typeArguments.arguments.length; if (actualCount != expectedCount) { _errorReporter.reportErrorForNode( errorCode, typeArguments, [actualCount], ); } } /** * Verify that the given [typeArguments] are all within their bounds, as * defined by the given [element]. */ void _checkTypeArguments(InvocationExpression node) { NodeList<TypeAnnotation> typeArgumentList = node.typeArguments?.arguments; if (typeArgumentList == null) { return; } var genericType = node.function.staticType; var instantiatedType = node.staticInvokeType; if (genericType is FunctionType && instantiatedType is FunctionType) { var fnTypeParams = TypeParameterTypeImpl.getTypes(genericType.typeFormals); var typeArgs = typeArgumentList.map((t) => t.type).toList(); // If the amount mismatches, clean up the lists to be substitutable. The // mismatch in size is reported elsewhere, but we must successfully // perform substitution to validate bounds on mismatched lists. final providedLength = math.min(typeArgs.length, fnTypeParams.length); fnTypeParams = fnTypeParams.sublist(0, providedLength); typeArgs = typeArgs.sublist(0, providedLength); for (int i = 0; i < providedLength; i++) { // Check the `extends` clause for the type parameter, if any. // // Also substitute to handle cases like this: // // <TFrom, TTo extends TFrom> // <TFrom, TTo extends Iterable<TFrom>> // <T extends Cloneable<T>> // DartType argType = typeArgs[i]; if (argType is FunctionType && argType.typeFormals.isNotEmpty) { _errorReporter.reportErrorForNode( CompileTimeErrorCode.GENERIC_FUNCTION_TYPE_CANNOT_BE_TYPE_ARGUMENT, typeArgumentList[i], ); continue; } DartType bound = fnTypeParams[i].bound.substitute2(typeArgs, fnTypeParams); if (!_typeSystem.isSubtypeOf(argType, bound)) { _errorReporter.reportTypeErrorForNode( CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS, typeArgumentList[i], [argType, bound]); } } } } /// Given a [node] without type arguments that refers to [element], issues /// an error if [type] is a generic type, and the type arguments were not /// supplied from inference or a non-dynamic default instantiation. /// /// This function is used by other node-specific type checking functions, and /// should only be called when [node] has no explicit `typeArguments`. /// /// [inferenceContextNode] is the node that has the downwards context type, /// if any. For example an [InstanceCreationExpression]. /// /// This function will return false if any of the following are true: /// /// - [inferenceContextNode] has an inference context type that does not /// contain `?` /// - [type] does not have any `dynamic` type arguments. /// - the element is marked with `@optionalTypeArgs` from "package:meta". bool _isMissingTypeArguments(AstNode node, DartType type, Element element, Expression inferenceContextNode) { // Check if this type has type arguments and at least one is dynamic. // If so, we may need to issue a strict-raw-types error. if (type is ParameterizedType && type.typeArguments.any((t) => t.isDynamic)) { // If we have an inference context node, check if the type was inferred // from it. Some cases will not have a context type, such as the type // annotation `List` in `List list;` if (inferenceContextNode != null) { var contextType = InferenceContext.getContext(inferenceContextNode); if (contextType != null && UnknownInferredType.isKnown(contextType)) { // Type was inferred from downwards context: not an error. return false; } } if (element.hasOptionalTypeArgs) { return false; } return true; } return false; } /// Determines if the given [typeName] occurs in a context where super-bounded /// types are allowed. bool _shouldAllowSuperBoundedTypes(TypeName typeName) { var parent = typeName.parent; if (parent is ExtendsClause) return false; if (parent is OnClause) return false; if (parent is ClassTypeAlias) return false; if (parent is WithClause) return false; if (parent is ConstructorName) return false; if (parent is ImplementsClause) return false; return true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/inheritance_override.dart
// Copyright (c) 2018, 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:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/constant/value.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/inheritance_manager3.dart'; import 'package:analyzer/src/dart/element/member.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/resolver.dart'; import 'package:analyzer/src/generated/type_system.dart'; class InheritanceOverrideVerifier { static const _missingOverridesKey = 'missingOverrides'; final TypeSystem _typeSystem; final TypeProvider _typeProvider; final InheritanceManager3 _inheritance; final ErrorReporter _reporter; InheritanceOverrideVerifier( this._typeSystem, this._inheritance, this._reporter) : _typeProvider = _typeSystem.typeProvider; void verifyUnit(CompilationUnit unit) { var library = unit.declaredElement.library; for (var declaration in unit.declarations) { if (declaration is ClassDeclaration) { new _ClassVerifier( typeSystem: _typeSystem, typeProvider: _typeProvider, inheritance: _inheritance, reporter: _reporter, featureSet: unit.featureSet, library: library, classNameNode: declaration.name, implementsClause: declaration.implementsClause, members: declaration.members, superclass: declaration.extendsClause?.superclass, withClause: declaration.withClause, ).verify(); } else if (declaration is ClassTypeAlias) { new _ClassVerifier( typeSystem: _typeSystem, typeProvider: _typeProvider, inheritance: _inheritance, reporter: _reporter, featureSet: unit.featureSet, library: library, classNameNode: declaration.name, implementsClause: declaration.implementsClause, superclass: declaration.superclass, withClause: declaration.withClause, ).verify(); } else if (declaration is MixinDeclaration) { new _ClassVerifier( typeSystem: _typeSystem, typeProvider: _typeProvider, inheritance: _inheritance, reporter: _reporter, featureSet: unit.featureSet, library: library, classNameNode: declaration.name, implementsClause: declaration.implementsClause, members: declaration.members, onClause: declaration.onClause, ).verify(); } } } /// Returns [ExecutableElement] members that are in the interface of the /// given class, but don't have concrete implementations. static List<ExecutableElement> missingOverrides(ClassDeclaration node) { return node.name.getProperty(_missingOverridesKey) ?? const []; } } class _ClassVerifier { final TypeSystem typeSystem; final TypeProvider typeProvider; final InheritanceManager3 inheritance; final ErrorReporter reporter; final FeatureSet featureSet; final LibraryElement library; final Uri libraryUri; final ClassElementImpl classElement; final SimpleIdentifier classNameNode; final List<ClassMember> members; final ImplementsClause implementsClause; final OnClause onClause; final TypeName superclass; final WithClause withClause; /// The set of unique supertypes of the current class. /// It is used to decide when to add a new element to [allSuperinterfaces]. final Set<InterfaceType> allSupertypes = new Set<InterfaceType>(); /// The list of all superinterfaces, collected so far. final List<Interface> allSuperinterfaces = []; _ClassVerifier({ this.typeSystem, this.typeProvider, this.inheritance, this.reporter, this.featureSet, this.library, this.classNameNode, this.implementsClause, this.members: const [], this.onClause, this.superclass, this.withClause, }) : libraryUri = library.source.uri, classElement = AbstractClassElementImpl.getImpl(classNameNode.staticElement); void verify() { if (_checkDirectSuperTypes()) { return; } if (_checkForRecursiveInterfaceInheritance(classElement)) { return; } InterfaceTypeImpl type = classElement.thisType; // Add all superinterfaces of the direct supertype. if (type.superclass != null) { _addSuperinterfaces(type.superclass); } // Each mixin in `class C extends S with M0, M1, M2 {}` is equivalent to: // class S&M0 extends S { ...members of M0... } // class S&M1 extends S&M0 { ...members of M1... } // class S&M2 extends S&M1 { ...members of M2... } // class C extends S&M2 { ...members of C... } // So, we need to check members of each mixin against superinterfaces // of `S`, and superinterfaces of all previous mixins. var mixinNodes = withClause?.mixinTypes; var mixinTypes = type.mixins; for (var i = 0; i < mixinTypes.length; i++) { var mixinType = mixinTypes[i]; _checkDeclaredMembers(mixinNodes[i], mixinType); _addSuperinterfaces(mixinType); } // Add all superinterfaces of the direct class interfaces. for (var interface in type.interfaces) { _addSuperinterfaces(interface); } // Check the members if the class itself, against all the previously // collected superinterfaces of the supertype, mixins, and interfaces. for (var member in members) { if (member is FieldDeclaration) { var fieldList = member.fields; for (var field in fieldList.variables) { FieldElement fieldElement = field.declaredElement; _checkDeclaredMember(field.name, libraryUri, fieldElement.getter); _checkDeclaredMember(field.name, libraryUri, fieldElement.setter); } } else if (member is MethodDeclaration) { _checkDeclaredMember(member.name, libraryUri, member.declaredElement, methodParameterNodes: member.parameters?.parameters); } } // Compute the interface of the class. var interface = inheritance.getInterface(type); // Report conflicts between direct superinterfaces of the class. for (var conflict in interface.conflicts) { _reportInconsistentInheritance(classNameNode, conflict); } _checkForMismatchedAccessorTypes(interface); if (!classElement.isAbstract) { List<ExecutableElement> inheritedAbstract; for (var name in interface.map.keys) { if (!name.isAccessibleFor(libraryUri)) { continue; } var interfaceElement = interface.map[name]; var concreteElement = interface.implemented[name]; // No concrete implementation of the name. if (concreteElement == null) { if (!_reportConcreteClassWithAbstractMember(name.name)) { inheritedAbstract ??= []; inheritedAbstract.add(interfaceElement); } continue; } // The case when members have different kinds is reported in verifier. if (concreteElement.kind != interfaceElement.kind) { continue; } // If a class declaration is not abstract, and the interface has a // member declaration named `m`, then: // 1. if the class contains a non-overridden member whose signature is // not a valid override of the interface member signature for `m`, // then it's a compile-time error. // 2. if the class contains no member named `m`, and the class member // for `noSuchMethod` is the one declared in `Object`, then it's a // compile-time error. // TODO(brianwilkerson) This code catches some cases not caught in // _checkDeclaredMember, but also duplicates the diagnostic reported // there in some other cases. // TODO(brianwilkerson) In the case of methods inherited via mixins, the // diagnostic should be reported on the name of the mixin defining the // method. In other cases, it should be reported on the name of the // overriding method. The classNameNode is always wrong. if (!typeSystem.isOverrideSubtypeOf( concreteElement.type, interfaceElement.type)) { reporter.reportErrorForNode( CompileTimeErrorCode.INVALID_OVERRIDE, classNameNode, [ name.name, interfaceElement.enclosingElement.name, interfaceElement.type.displayName, concreteElement.enclosingElement.name, concreteElement.type.displayName, ], ); } } _reportInheritedAbstractMembers(inheritedAbstract); } } void _addSuperinterfaces(InterfaceType startingType) { var supertypes = <InterfaceType>[]; ClassElementImpl.collectAllSupertypes(supertypes, startingType, null); for (int i = 0; i < supertypes.length; i++) { var supertype = supertypes[i]; if (allSupertypes.add(supertype)) { var interface = inheritance.getInterface(supertype); allSuperinterfaces.add(interface); } } } /// Check that the given [member] is a valid override of the corresponding /// instance members in each of [allSuperinterfaces]. The [libraryUri] is /// the URI of the library containing the [member]. void _checkDeclaredMember( AstNode node, Uri libraryUri, ExecutableElement member, { List<AstNode> methodParameterNodes, }) { if (member == null) return; if (member.isStatic) return; var name = new Name(libraryUri, member.name); for (var superInterface in allSuperinterfaces) { var superMember = superInterface.declared[name]; if (superMember != null) { // The case when members have different kinds is reported in verifier. // TODO(scheglov) Do it here? if (member.kind != superMember.kind) { continue; } if (!typeSystem.isOverrideSubtypeOf(member.type, superMember.type)) { reporter.reportErrorForNode( CompileTimeErrorCode.INVALID_OVERRIDE, node, [ name.name, member.enclosingElement.name, member.type.displayName, superMember.enclosingElement.name, superMember.type.displayName ], ); } if (methodParameterNodes != null) { _checkForOptionalParametersDifferentDefaultValues( superMember, member, methodParameterNodes, ); } } } } /// Check that instance members of [type] are valid overrides of the /// corresponding instance members in each of [allSuperinterfaces]. void _checkDeclaredMembers(AstNode node, InterfaceTypeImpl type) { var libraryUri = type.element.library.source.uri; for (var method in type.methods) { _checkDeclaredMember(node, libraryUri, method); } for (var accessor in type.accessors) { _checkDeclaredMember(node, libraryUri, accessor); } } /// Verify that the given [typeName] does not extend, implement, or mixes-in /// types such as `num` or `String`. bool _checkDirectSuperType(TypeName typeName, ErrorCode errorCode) { if (typeName.isSynthetic) { return false; } // The SDK implementation may implement disallowed types. For example, // JSNumber in dart2js and _Smi in Dart VM both implement int. if (library.source.isInSystemLibrary) { return false; } DartType type = typeName.type; if (typeProvider.nonSubtypableTypes.contains(type)) { reporter.reportErrorForNode(errorCode, typeName, [type.displayName]); return true; } return false; } /// Verify that direct supertypes are valid, and return `false`. If there /// are direct supertypes that are not valid, report corresponding errors, /// and return `true`. bool _checkDirectSuperTypes() { var hasError = false; if (implementsClause != null) { for (var typeName in implementsClause.interfaces) { if (_checkDirectSuperType( typeName, CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS, )) { hasError = true; } } } if (onClause != null) { for (var typeName in onClause.superclassConstraints) { if (_checkDirectSuperType( typeName, CompileTimeErrorCode.MIXIN_SUPER_CLASS_CONSTRAINT_DISALLOWED_CLASS, )) { hasError = true; } } } if (superclass != null) { if (_checkDirectSuperType( superclass, CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS, )) { hasError = true; } } if (withClause != null) { for (var typeName in withClause.mixinTypes) { if (_checkDirectSuperType( typeName, CompileTimeErrorCode.MIXIN_OF_DISALLOWED_CLASS, )) { hasError = true; } } } return hasError; } void _checkForMismatchedAccessorTypes(Interface interface) { for (var name in interface.map.keys) { if (!name.isAccessibleFor(libraryUri)) continue; var getter = interface.map[name]; if (getter.kind == ElementKind.GETTER) { // TODO(scheglov) We should separate getters and setters. var setter = interface.map[new Name(libraryUri, '${name.name}=')]; if (setter != null && setter.parameters.length == 1) { var getterType = getter.returnType; var setterType = setter.parameters[0].type; if (!typeSystem.isAssignableTo(getterType, setterType, featureSet: featureSet)) { Element errorElement; if (getter.enclosingElement == classElement) { errorElement = getter; } else if (setter.enclosingElement == classElement) { errorElement = setter; } else { errorElement = classElement; } String getterName = getter.displayName; if (getter.enclosingElement != classElement) { var getterClassName = getter.enclosingElement.displayName; getterName = '$getterClassName.$getterName'; } String setterName = setter.displayName; if (setter.enclosingElement != classElement) { var setterClassName = setter.enclosingElement.displayName; setterName = '$setterClassName.$setterName'; } reporter.reportErrorForElement( StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES, errorElement, [getterName, getterType, setterType, setterName]); } } } } } void _checkForOptionalParametersDifferentDefaultValues( ExecutableElement baseExecutable, ExecutableElement derivedExecutable, List<AstNode> derivedParameterNodes, ) { var derivedOptionalNodes = <AstNode>[]; var derivedOptionalElements = <ParameterElementImpl>[]; var derivedParameterElements = derivedExecutable.parameters; for (var i = 0; i < derivedParameterElements.length; i++) { var parameterElement = derivedParameterElements[i]; if (parameterElement.isOptional) { derivedOptionalNodes.add(derivedParameterNodes[i]); derivedOptionalElements.add(parameterElement); } } var baseOptionalElements = <ParameterElementImpl>[]; var baseParameterElements = baseExecutable.parameters; for (var i = 0; i < baseParameterElements.length; ++i) { var baseParameter = baseParameterElements[i]; if (baseParameter.isOptional) { if (baseParameter is ParameterMember) { baseParameter = (baseParameter as ParameterMember).baseElement; } baseOptionalElements.add(baseParameter); } } // Stop if no optional parameters. if (baseOptionalElements.isEmpty || derivedOptionalElements.isEmpty) { return; } if (derivedOptionalElements[0].isNamed) { for (int i = 0; i < derivedOptionalElements.length; i++) { var derivedElement = derivedOptionalElements[i]; var name = derivedElement.name; for (var j = 0; j < baseOptionalElements.length; j++) { var baseParameter = baseOptionalElements[j]; if (name == baseParameter.name && baseParameter.initializer != null) { var baseValue = baseParameter.computeConstantValue(); var derivedResult = derivedElement.evaluationResult; if (!_constantValuesEqual(derivedResult.value, baseValue)) { reporter.reportErrorForNode( StaticWarningCode .INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED, derivedOptionalNodes[i], [ baseExecutable.enclosingElement.displayName, baseExecutable.displayName, name ], ); } } } } } else { for (var i = 0; i < derivedOptionalElements.length && i < baseOptionalElements.length; i++) { var baseElement = baseOptionalElements[i]; if (baseElement.initializer != null) { var baseValue = baseElement.computeConstantValue(); var derivedResult = derivedOptionalElements[i].evaluationResult; if (!_constantValuesEqual(derivedResult.value, baseValue)) { reporter.reportErrorForNode( StaticWarningCode .INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL, derivedOptionalNodes[i], [ baseExecutable.enclosingElement.displayName, baseExecutable.displayName ], ); } } } } } /// Check that [classElement] is not a superinterface to itself. /// The [path] is a list containing the potentially cyclic implements path. /// /// See [CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE], /// [CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_EXTENDS], /// [CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_IMPLEMENTS], /// [CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_ON], /// [CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_WITH]. bool _checkForRecursiveInterfaceInheritance(ClassElement element, [List<ClassElement> path]) { path ??= <ClassElement>[]; // Detect error condition. int size = path.length; // If this is not the base case (size > 0), and the enclosing class is the // given class element then report an error. if (size > 0 && classElement == element) { String className = classElement.displayName; if (size > 1) { // Construct a string showing the cyclic implements path: // "A, B, C, D, A" String separator = ", "; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < size; i++) { buffer.write(path[i].displayName); buffer.write(separator); } buffer.write(element.displayName); reporter.reportErrorForElement( CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, classElement, [className, buffer.toString()]); return true; } else { // RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS or // RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS or // RECURSIVE_INTERFACE_INHERITANCE_ON or // RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH reporter.reportErrorForElement( _getRecursiveErrorCode(element), classElement, [className]); return true; } } if (path.indexOf(element) > 0) { return false; } path.add(element); // n-case InterfaceType supertype = element.supertype; if (supertype != null && _checkForRecursiveInterfaceInheritance(supertype.element, path)) { return true; } for (InterfaceType type in element.mixins) { if (_checkForRecursiveInterfaceInheritance(type.element, path)) { return true; } } for (InterfaceType type in element.superclassConstraints) { if (_checkForRecursiveInterfaceInheritance(type.element, path)) { return true; } } for (InterfaceType type in element.interfaces) { if (_checkForRecursiveInterfaceInheritance(type.element, path)) { return true; } } path.removeAt(path.length - 1); return false; } /// Return the error code that should be used when the given class [element] /// references itself directly. ErrorCode _getRecursiveErrorCode(ClassElement element) { if (element.supertype?.element == classElement) { return CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_EXTENDS; } for (InterfaceType type in element.superclassConstraints) { if (type.element == classElement) { return CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_ON; } } for (InterfaceType type in element.mixins) { if (type.element == classElement) { return CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_WITH; } } return CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_IMPLEMENTS; } /// We identified that the current non-abstract class does not have the /// concrete implementation of a method with the given [name]. If this is /// because the class itself defines an abstract method with this [name], /// report the more specific error, and return `true`. bool _reportConcreteClassWithAbstractMember(String name) { for (var member in members) { if (member is MethodDeclaration) { var name2 = member.name.name; if (member.isSetter) { name2 += '='; } if (name2 == name) { reporter.reportErrorForNode( StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER, member, [name, classElement.name]); return true; } } } return false; } void _reportInconsistentInheritance(AstNode node, Conflict conflict) { var name = conflict.name; if (conflict.getter != null && conflict.method != null) { reporter.reportErrorForNode( CompileTimeErrorCode.INCONSISTENT_INHERITANCE_GETTER_AND_METHOD, node, [ name.name, conflict.getter.enclosingElement.name, conflict.method.enclosingElement.name ], ); } else { var candidatesStr = conflict.candidates.map((candidate) { var className = candidate.enclosingElement.name; return '$className.${name.name} (${candidate.displayName})'; }).join(', '); reporter.reportErrorForNode( CompileTimeErrorCode.INCONSISTENT_INHERITANCE, node, [name.name, candidatesStr], ); } } void _reportInheritedAbstractMembers(List<ExecutableElement> elements) { if (elements == null) { return; } classNameNode.setProperty( InheritanceOverrideVerifier._missingOverridesKey, elements, ); var descriptions = <String>[]; for (ExecutableElement element in elements) { String prefix = ''; if (element is PropertyAccessorElement) { if (element.isGetter) { prefix = 'getter '; } else { prefix = 'setter '; } } String description; var elementName = element.displayName; var enclosingElement = element.enclosingElement; if (enclosingElement != null) { var enclosingName = enclosingElement.displayName; description = "$prefix$enclosingName.$elementName"; } else { description = "$prefix$elementName"; } descriptions.add(description); } descriptions.sort(); if (descriptions.length == 1) { reporter.reportErrorForNode( StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE, classNameNode, [descriptions[0]], ); } else if (descriptions.length == 2) { reporter.reportErrorForNode( StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO, classNameNode, [descriptions[0], descriptions[1]], ); } else if (descriptions.length == 3) { reporter.reportErrorForNode( StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE, classNameNode, [descriptions[0], descriptions[1], descriptions[2]], ); } else if (descriptions.length == 4) { reporter.reportErrorForNode( StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR, classNameNode, [descriptions[0], descriptions[1], descriptions[2], descriptions[3]], ); } else { reporter.reportErrorForNode( StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS, classNameNode, [ descriptions[0], descriptions[1], descriptions[2], descriptions[3], descriptions.length - 4 ], ); } } static bool _constantValuesEqual(DartObject x, DartObject y) { // If either constant value couldn't be computed due to an error, the // corresponding DartObject will be `null`. Since an error has already been // reported, there's no need to report another. if (x == null || y == null) return true; return (x as DartObjectImpl).isEqualIgnoringTypesRecursively(y); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error/codes.dart
// Copyright (c) 2014, 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:analyzer/error/error.dart'; import 'package:analyzer/src/dart/error/syntactic_errors.dart'; import 'analyzer_error_code.dart'; export 'package:analyzer/src/analysis_options/error/option_codes.dart'; export 'package:analyzer/src/dart/error/hint_codes.dart'; export 'package:analyzer/src/dart/error/lint_codes.dart'; export 'package:analyzer/src/dart/error/todo_codes.dart'; /** * The error codes used for compile time errors caused by constant evaluation * that would throw an exception when run in checked mode. The client of the * analysis engine is responsible for determining how these errors should be * presented to the user (for example, a command-line compiler might elect to * treat these errors differently depending whether it is compiling it "checked" * mode). */ class CheckedModeCompileTimeErrorCode extends AnalyzerErrorCode { // TODO(paulberry): improve the text of these error messages so that it's // clear to the user that the error is coming from constant evaluation (and // hence the constant needs to be a subtype of the annotated type) as opposed // to static type analysis (which only requires that the two types be // assignable). Also consider populating the "correction" field for these // errors. /** * 16.12.2 Const: It is a compile-time error if evaluation of a constant * object results in an uncaught exception being thrown. */ static const CheckedModeCompileTimeErrorCode CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH = const CheckedModeCompileTimeErrorCode( 'CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH', "A value of type '{0}' can't be assigned to the field '{1}', which " "has type '{2}'."); /** * 16.12.2 Const: It is a compile-time error if evaluation of a constant * object results in an uncaught exception being thrown. */ static const CheckedModeCompileTimeErrorCode CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH = const CheckedModeCompileTimeErrorCode( 'CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH', "A value of type '{0}' can't be assigned to a parameter of type " "'{1}'."); /** * 7.6.1 Generative Constructors: In checked mode, it is a dynamic type error * if o is not <b>null</b> and the interface of the class of <i>o</i> is not a * subtype of the static type of the field <i>v</i>. * * 16.12.2 Const: It is a compile-time error if evaluation of a constant * object results in an uncaught exception being thrown. * * Parameters: * 0: the name of the type of the initializer expression * 1: the name of the type of the field */ static const CheckedModeCompileTimeErrorCode CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE = const CheckedModeCompileTimeErrorCode( 'CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE', "The initializer type '{0}' can't be assigned to the field type " "'{1}'."); /** * 16.12.2 Const: It is a compile-time error if evaluation of a constant * object results in an uncaught exception being thrown. */ static const CheckedModeCompileTimeErrorCode VARIABLE_TYPE_MISMATCH = const CheckedModeCompileTimeErrorCode( 'VARIABLE_TYPE_MISMATCH', "A value of type '{0}' can't be assigned to a variable of type " "'{1}'."); /** * Initialize a newly created error code to have the given [name]. The message * associated with the error will be created from the given [message] * template. The correction associated with the error will be created from the * given [correction] template. */ const CheckedModeCompileTimeErrorCode(String name, String message, {String correction, bool hasPublishedDocs}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs); @override ErrorSeverity get errorSeverity => ErrorType.CHECKED_MODE_COMPILE_TIME_ERROR.severity; @override ErrorType get type => ErrorType.CHECKED_MODE_COMPILE_TIME_ERROR; } /** * The error codes used for compile time errors. The convention for this class * is for the name of the error code to indicate the problem that caused the * error to be generated and for the error message to explain what is wrong and, * when appropriate, how the problem can be corrected. */ class CompileTimeErrorCode extends AnalyzerErrorCode { /** * Parameters: * 0: the display name for the kind of the found abstract member * 1: the name of the member */ // #### Description // // The analyzer produces this diagnostic when an inherited member is // referenced using `super`, but there is no concrete implementation of the // member in the superclass chain. Abstract members can't be invoked. // // #### Example // // The following code produces this diagnostic: // // ```dart // abstract class A { // int get a; // } // class B extends A { // int get a => super.[!a!]; // } // ``` // // #### Common fixes // // Remove the invocation of the abstract member, possibly replacing it with an // invocation of a concrete member. // TODO(brianwilkerson) This either needs to be generalized (use 'member' // rather than '{0}') or split into multiple codes. static const CompileTimeErrorCode ABSTRACT_SUPER_MEMBER_REFERENCE = const CompileTimeErrorCode('ABSTRACT_SUPER_MEMBER_REFERENCE', "The {0} '{1}' is always abstract in the supertype.", hasPublishedDocs: true); /** * Enum proposal: It is also a compile-time error to explicitly instantiate an * enum via 'new' or 'const' or to access its private fields. */ static const CompileTimeErrorCode ACCESS_PRIVATE_ENUM_FIELD = const CompileTimeErrorCode( 'ACCESS_PRIVATE_ENUM_FIELD', "The private fields of an enum can't be accessed, even within the " "same library."); /** * 14.2 Exports: It is a compile-time error if a name <i>N</i> is re-exported * by a library <i>L</i> and <i>N</i> is introduced into the export namespace * of <i>L</i> by more than one export, unless each all exports refer to same * declaration for the name N. * * Parameters: * 0: the name of the ambiguous element * 1: the name of the first library in which the type is found * 2: the name of the second library in which the type is found */ static const CompileTimeErrorCode AMBIGUOUS_EXPORT = const CompileTimeErrorCode('AMBIGUOUS_EXPORT', "The name '{0}' is defined in the libraries '{1}' and '{2}'.", correction: "Try removing the export of one of the libraries, or " "explicitly hiding the name in one of the export directives."); /** * Parameters: * 0: the name of the member * 1: the name of the first declaring extension * 2: the name of the second declaring extension */ // #### Description // // When code refers to a member of an object (for example, `o.m()` or `o.m` or // `o[i]`) where the static type of `o` doesn't declare the member (`m` or // `[]`, for example), then the analyzer tries to find the member in an // extension. For example, if the member is `m`, then the analyzer looks for // extensions that declare a member named `m` and have an extended type that // the static type of `o` can be assigned to. When there's more than one such // extension in scope, the extension whose extended type is most specific is // selected. // // The analyzer produces this diagnostic when none of the extensions has an // extended type that's more specific than the extended types of all of the // other extensions, making the reference to the member ambiguous. // // #### Example // // The following code produces this diagnostic because there's no way to // choose between the member in `E1` and the member in `E2`: // // ```dart // extension E1 on String { // int get charCount => 1; // } // // extension E2 on String { // int get charCount => 2; // } // // void f(String s) { // print(s.[!charCount!]); // } // ``` // // #### Common fixes // // If you don't need both extensions, then you can delete or hide one of them. // // If you need both, then explicitly select the one you want to use by using // an extension override: // // ```dart // extension E1 on String { // int get charCount => length; // } // // extension E2 on String { // int get charCount => length; // } // // void f(String s) { // print(E2(s).charCount); // } // ``` /* * TODO(brianwilkerson) This message doesn't handle the possible case where * there are more than 2 extensions, nor does it handle well the case where * one or more of the extensions is unnamed. */ static const CompileTimeErrorCode AMBIGUOUS_EXTENSION_MEMBER_ACCESS = const CompileTimeErrorCode( 'AMBIGUOUS_EXTENSION_MEMBER_ACCESS', "A member named '{0}' is defined in extensions '{1}' and '{2}' and " "neither is more specific.", correction: "Try using an extension override to specify the extension " "you want to to be chosen.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // Because map and set literals use the same delimiters (`{` and `}`), the // analyzer looks at the type arguments and the elements to determine which // kind of literal you meant. When there are no type arguments and all of the // elements are spread elements (which are allowed in both kinds of literals), // then the analyzer uses the types of the expressions that are being spread. // If all of the expressions have the type `Iterable`, then it's a set // literal; if they all have the type `Map`, then it's a map literal. // // The analyzer produces this diagnostic when some of the expressions being // spread have the type `Iterable` and others have the type `Map`, making it // impossible for the analyzer to determine whether you are writing a map // literal or a set literal. // // #### Example // // The following code produces this diagnostic: // // ```dart // union(Map<String, String> a, List<String> b, Map<String, String> c) => // [!{...a, ...b, ...c}!]; // ``` // // The list `b` can only be spread into a set, and the maps `a` and `c` can // only be spread into a map, and the literal can't be both. // // #### Common fixes // // There are two common ways to fix this problem. The first is to remove all // of the spread elements of one kind or another, so that the elements are // consistent. In this case, that likely means removing the list and deciding // what to do about the now unused parameter: // // ```dart // union(Map<String, String> a, List<String> b, Map<String, String> c) => // {...a, ...c}; // ``` // // The second fix is to change the elements of one kind into elements that are // consistent with the other elements. For example, you can add the elements // of the list as keys that map to themselves: // // ```dart // union(Map<String, String> a, List<String> b, Map<String, String> c) => // {...a, for (String s in b) s: s, ...c}; // ``` static const CompileTimeErrorCode AMBIGUOUS_SET_OR_MAP_LITERAL_BOTH = const CompileTimeErrorCode( 'AMBIGUOUS_SET_OR_MAP_LITERAL_BOTH', "This literal contains both 'Map' and 'Iterable' spreads, " "which makes it impossible to determine whether the literal is " "a map or a set.", correction: "Try removing or changing some of the elements so that all of " "the elements are consistent.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // Because map and set literals use the same delimiters (`{` and `}`), the // analyzer looks at the type arguments and the elements to determine which // kind of literal you meant. When there are no type arguments and all of the // elements are spread elements (which are allowed in both kinds of literals) // then the analyzer uses the types of the expressions that are being spread. // If all of the expressions have the type `Iterable`, then it's a set // literal; if they all have the type `Map`, then it's a map literal. // // This diagnostic is produced when none of the expressions being spread have // a type that allows the analyzer to decide whether you were writing a map // literal or a set literal. // // #### Example // // The following code produces this diagnostic: // // ```dart // union(a, b) => [!{...a, ...b}!]; // ``` // // The problem occurs because there are no type arguments, and there is no // information about the type of either `a` or `b`. // // #### Common fixes // // There are three common ways to fix this problem. The first is to add type // arguments to the literal. For example, if the literal is intended to be a // map literal, you might write something like this: // // ```dart // union(a, b) => <String, String>{...a, ...b}; // ``` // // The second fix is to add type information so that the expressions have // either the type `Iterable` or the type `Map`. You can add an explicit cast // or, in this case, add types to the declarations of the two parameters: // // ```dart // union(List<int> a, List<int> b) => {...a, ...b}; // ``` // // The third fix is to add context information. In this case, that means // adding a return type to the function: // // ```dart // Set<String> union(a, b) => {...a, ...b}; // ``` // // In other cases, you might add a type somewhere else. For example, say the // original code looks like this: // // ```dart // union(a, b) { // var x = [!{...a, ...b}!]; // return x; // } // ``` // // You might add a type annotation on `x`, like this: // // ```dart // union(a, b) { // Map<String, String> x = {...a, ...b}; // return x; // } // ``` static const CompileTimeErrorCode AMBIGUOUS_SET_OR_MAP_LITERAL_EITHER = const CompileTimeErrorCode( 'AMBIGUOUS_SET_OR_MAP_LITERAL_EITHER', "This literal must be either a map or a set, but the elements don't " "have enough information for type inference to work.", correction: "Try adding type arguments to the literal (one for sets, two " "for maps).", hasPublishedDocs: true); /** * 15 Metadata: The constant expression given in an annotation is type checked * and evaluated in the scope surrounding the declaration being annotated. * * 16.12.2 Const: It is a compile-time error if <i>T</i> is not a class * accessible in the current scope, optionally followed by type arguments. * * 16.12.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>, * &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, &hellip; * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if * <i>T</i> is not a class accessible in the current scope, optionally * followed by type arguments. * * Parameters: * 0: the name of the non-type element */ static const CompileTimeErrorCode ANNOTATION_WITH_NON_CLASS = const CompileTimeErrorCode( 'ANNOTATION_WITH_NON_CLASS', "The name '{0}' isn't a class.", correction: "Try importing the library that declares the class, " "correcting the name to match a defined class, or " "defining a class with the given name."); static const ParserErrorCode ANNOTATION_WITH_TYPE_ARGUMENTS = ParserErrorCode.ANNOTATION_WITH_TYPE_ARGUMENTS; static const CompileTimeErrorCode ASSERT_IN_REDIRECTING_CONSTRUCTOR = const CompileTimeErrorCode('ASSERT_IN_REDIRECTING_CONSTRUCTOR', "A redirecting constructor can't have an 'assert' initializer."); /** * 17.6.3 Asynchronous For-in: It is a compile-time error if an asynchronous * for-in statement appears inside a synchronous function. */ static const CompileTimeErrorCode ASYNC_FOR_IN_WRONG_CONTEXT = const CompileTimeErrorCode('ASYNC_FOR_IN_WRONG_CONTEXT', "The async for-in can only be used in an async function.", correction: "Try marking the function body with either 'async' or 'async*', " "or removing the 'await' before the for loop."); /** * 16.30 Await Expressions: It is a compile-time error if the function * immediately enclosing _a_ is not declared asynchronous. (Where _a_ is the * await expression.) */ static const CompileTimeErrorCode AWAIT_IN_WRONG_CONTEXT = const CompileTimeErrorCode('AWAIT_IN_WRONG_CONTEXT', "The await expression can only be used in an async function.", correction: "Try marking the function body with either 'async' or 'async*'."); /** * Parameters: * 0: the built-in identifier that is being used */ // #### Description // // The analyzer produces this diagnostic when the name of an extension is a // built-in identifier. Built-in identifiers can’t be used as extension names. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension [!mixin!] on int {} // ``` // // #### Common fixes // // Choose a different name for the extension. static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_EXTENSION_NAME = const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_EXTENSION_NAME', "The built-in identifier '{0}' can't be used as an extension name.", correction: "Try choosing a different name for the extension.", hasPublishedDocs: true); /** * 16.33 Identifier Reference: It is a compile-time error if a built-in * identifier is used as the declared name of a prefix, class, type parameter * or type alias. * * Parameters: * 0: the built-in identifier that is being used */ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_PREFIX_NAME = const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_PREFIX_NAME', "The built-in identifier '{0}' can't be used as a prefix name.", correction: "Try choosing a different name for the prefix."); /** * 12.30 Identifier Reference: It is a compile-time error to use a built-in * identifier other than dynamic as a type annotation. * * Parameters: * 0: the built-in identifier that is being used */ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE = const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE', "The built-in identifier '{0}' can't be used as a type.", correction: "Try correcting the name to match an existing type."); /** * 16.33 Identifier Reference: It is a compile-time error if a built-in * identifier is used as the declared name of a prefix, class, type parameter * or type alias. * * Parameters: * 0: the built-in identifier that is being used */ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_NAME = const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE_NAME', "The built-in identifier '{0}' can't be used as a type name.", correction: "Try choosing a different name for the type."); /** * 16.33 Identifier Reference: It is a compile-time error if a built-in * identifier is used as the declared name of a prefix, class, type parameter * or type alias. * * Parameters: * 0: the built-in identifier that is being used */ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME = const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME', "The built-in identifier '{0}' can't be used as a typedef name.", correction: "Try choosing a different name for the typedef."); /** * 16.33 Identifier Reference: It is a compile-time error if a built-in * identifier is used as the declared name of a prefix, class, type parameter * or type alias. * * Parameters: * 0: the built-in identifier that is being used */ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME = const CompileTimeErrorCode( 'BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME', "The built-in identifier '{0}' can't be used as a type parameter " "name.", correction: "Try choosing a different name for the type parameter."); /** * 13.9 Switch: It is a compile-time error if the class <i>C</i> implements * the operator <i>==</i>. * * Parameters: * 0: the this of the switch case expression */ static const CompileTimeErrorCode CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS = const CompileTimeErrorCode( 'CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS', "The switch case expression type '{0}' can't override the == " "operator."); /** * 10.11 Class Member Conflicts: Let `C` be a class. It is a compile-time * error if `C` declares a constructor named `C.n`, and a static member with * basename `n`. * * Parameters: * 0: the name of the constructor */ static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_AND_STATIC_FIELD = const CompileTimeErrorCode( 'CONFLICTING_CONSTRUCTOR_AND_STATIC_FIELD', "'{0}' can't be used to name both a constructor and a static field " "in this class.", correction: "Try renaming either the constructor or the field."); /** * 10.11 Class Member Conflicts: Let `C` be a class. It is a compile-time * error if `C` declares a constructor named `C.n`, and a static member with * basename `n`. * * Parameters: * 0: the name of the constructor */ static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_AND_STATIC_METHOD = const CompileTimeErrorCode( 'CONFLICTING_CONSTRUCTOR_AND_STATIC_METHOD', "'{0}' can't be used to name both a constructor and a static method " "in this class.", correction: "Try renaming either the constructor or the method."); /** * 10.11 Class Member Conflicts: Let `C` be a class. It is a compile-time * error if `C` declares a getter or a setter with basename `n`, and has a * method named `n`. * * Parameters: * 0: the name of the class defining the conflicting field * 1: the name of the conflicting field * 2: the name of the class defining the method with which the field conflicts */ static const CompileTimeErrorCode CONFLICTING_FIELD_AND_METHOD = const CompileTimeErrorCode( 'CONFLICTING_FIELD_AND_METHOD', "Class '{0}' can't define field '{1}' and have method '{2}.{1}' " "with the same name.", correction: "Try converting the getter to a method, or " "renaming the field to a name that doesn't conflict."); /** * 10.10 Superinterfaces: It is a compile-time error if a class `C` has two * superinterfaces that are different instantiations of the same generic * class. For example, a class may not have both `List<int>` and `List<num>` * as superinterfaces. * * Parameters: * 0: the name of the class implementing the conflicting interface * 1: the first conflicting type * 1: the second conflicting type */ static const CompileTimeErrorCode CONFLICTING_GENERIC_INTERFACES = const CompileTimeErrorCode( 'CONFLICTING_GENERIC_INTERFACES', "The class '{0}' cannot implement both '{1}' and '{2}' because the " "type arguments are different."); /** * 10.11 Class Member Conflicts: Let `C` be a class. It is a compile-time * error if `C` declares a method named `n`, and has a getter or a setter * with basename `n`. * * Parameters: * 0: the name of the class defining the conflicting method * 1: the name of the conflicting method * 2: the name of the class defining the field with which the method conflicts */ static const CompileTimeErrorCode CONFLICTING_METHOD_AND_FIELD = const CompileTimeErrorCode( 'CONFLICTING_METHOD_AND_FIELD', "Class '{0}' can't define method '{1}' and have field '{2}.{1}' " "with the same name.", correction: "Try converting the method to a getter, or " "renaming the method to a name that doesn't conflict."); /** * 10.11 Class Member Conflicts: Let `C` be a class. It is a compile-time * error if `C` declares a static member with basename `n`, and has an * instance member with basename `n`. * * Parameters: * 0: the name of the class defining the conflicting member * 1: the name of the conflicting static member * 2: the name of the class defining the field with which the method conflicts */ static const CompileTimeErrorCode CONFLICTING_STATIC_AND_INSTANCE = const CompileTimeErrorCode( 'CONFLICTING_STATIC_AND_INSTANCE', "Class '{0}' can't define static member '{1}' and have instance " "member '{2}.{1}' with the same name.", correction: "Try renaming the member to a name that doesn't conflict."); /** * 7. Classes: It is a compile time error if a generic class declares a type * variable with the same name as the class or any of its members or * constructors. * * Parameters: * 0: the name of the type variable */ static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_CLASS = const CompileTimeErrorCode( 'CONFLICTING_TYPE_VARIABLE_AND_CLASS', "'{0}' can't be used to name both a type variable and the class in " "which the type variable is defined.", correction: "Try renaming either the type variable or the class."); /** * 7. Classes: It is a compile time error if a generic class declares a type * variable with the same name as the class or any of its members or * constructors. * * Parameters: * 0: the name of the type variable */ static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_MEMBER = const CompileTimeErrorCode( 'CONFLICTING_TYPE_VARIABLE_AND_MEMBER', "'{0}' can't be used to name both a type variable and a member in " "this class.", correction: "Try renaming either the type variable or the member."); /** * 16.12.2 Const: It is a compile-time error if evaluation of a constant * object results in an uncaught exception being thrown. */ static const CompileTimeErrorCode CONST_CONSTRUCTOR_THROWS_EXCEPTION = const CompileTimeErrorCode('CONST_CONSTRUCTOR_THROWS_EXCEPTION', "Const constructors can't throw exceptions.", correction: "Try removing the throw statement, or " "removing the keyword 'const'."); /** * 10.6.3 Constant Constructors: It is a compile-time error if a constant * constructor is declared by a class C if any instance variable declared in C * is initialized with an expression that is not a constant expression. * * Parameters: * 0: the name of the field */ static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST = const CompileTimeErrorCode( 'CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST', "Can't define the const constructor because the field '{0}' " "is initialized with a non-constant value.", correction: "Try initializing the field to a constant value, or " "removing the keyword 'const' from the constructor."); /** * 7.6.3 Constant Constructors: The superinitializer that appears, explicitly * or implicitly, in the initializer list of a constant constructor must * specify a constant constructor of the superclass of the immediately * enclosing class or a compile-time error occurs. * * 12.1 Mixin Application: For each generative constructor named ... an * implicitly declared constructor named ... is declared. If Sq is a * generative const constructor, and M does not declare any fields, Cq is * also a const constructor. */ static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_MIXIN_WITH_FIELD = const CompileTimeErrorCode( 'CONST_CONSTRUCTOR_WITH_MIXIN_WITH_FIELD', "Const constructor can't be declared for a class with a mixin " "that declares an instance field.", correction: "Try removing the 'const' keyword or " "removing the 'with' clause from the class declaration, " "or removing fields from the mixin class."); /** * 7.6.3 Constant Constructors: The superinitializer that appears, explicitly * or implicitly, in the initializer list of a constant constructor must * specify a constant constructor of the superclass of the immediately * enclosing class or a compile-time error occurs. * * Parameters: * 0: the name of the superclass */ static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER = const CompileTimeErrorCode( 'CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER', "Constant constructor can't call non-constant super constructor of " "'{0}'.", correction: "Try calling a const constructor in the superclass, or " "removing the keyword 'const' from the constructor."); /** * 7.6.3 Constant Constructors: It is a compile-time error if a constant * constructor is declared by a class that has a non-final instance variable. * * The above refers to both locally declared and inherited instance variables. */ static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD = const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD', "Can't define a const constructor for a class with non-final fields.", correction: "Try making all of the fields final, or " "removing the keyword 'const' from the constructor."); /** * 12.12.2 Const: It is a compile-time error if <i>T</i> is a deferred type. */ static const CompileTimeErrorCode CONST_DEFERRED_CLASS = const CompileTimeErrorCode('CONST_DEFERRED_CLASS', "Deferred classes can't be created with 'const'.", correction: "Try using 'new' to create the instance, or " "changing the import to not be deferred."); /** * 16.12.2 Const: An expression of one of the forms !e, e1 && e2 or e1 || e2, * where e, e1 and e2 are constant expressions that evaluate to a boolean * value. */ static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL = const CompileTimeErrorCode( 'CONST_EVAL_TYPE_BOOL', "In constant expressions, operands of this operator must be of type " "'bool'."); /** * 16.12.2 Const: An expression of one of the forms !e, e1 && e2 or e1 || e2, * where e, e1 and e2 are constant expressions that evaluate to a boolean * value. */ static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL_INT = const CompileTimeErrorCode( 'CONST_EVAL_TYPE_BOOL_INT', "In constant expressions, operands of this operator must be of type " "'bool' or 'int'."); /** * 16.12.2 Const: An expression of one of the forms e1 == e2 or e1 != e2 where * e1 and e2 are constant expressions that evaluate to a numeric, string or * boolean value or to null. */ static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL_NUM_STRING = const CompileTimeErrorCode( 'CONST_EVAL_TYPE_BOOL_NUM_STRING', "In constant expressions, operands of this operator must be of type " "'bool', 'num', 'String' or 'null'."); /** * 16.12.2 Const: An expression of one of the forms ~e, e1 ^ e2, e1 & e2, * e1 | e2, e1 >> e2 or e1 << e2, where e, e1 and e2 are constant expressions * that evaluate to an integer value or to null. */ static const CompileTimeErrorCode CONST_EVAL_TYPE_INT = const CompileTimeErrorCode( 'CONST_EVAL_TYPE_INT', "In constant expressions, operands of this operator must be of type " "'int'."); /** * 16.12.2 Const: An expression of one of the forms e, e1 + e2, e1 - e2, e1 * * e2, e1 / e2, e1 ~/ e2, e1 > e2, e1 < e2, e1 >= e2, e1 <= e2 or e1 % e2, * where e, e1 and e2 are constant expressions that evaluate to a numeric * value or to null. */ static const CompileTimeErrorCode CONST_EVAL_TYPE_NUM = const CompileTimeErrorCode( 'CONST_EVAL_TYPE_NUM', "In constant expressions, operands of this operator must be of type " "'num'."); static const CompileTimeErrorCode CONST_EVAL_TYPE_TYPE = const CompileTimeErrorCode( 'CONST_EVAL_TYPE_TYPE', "In constant expressions, operands of this operator must be of type " "'Type'."); /** * 16.12.2 Const: It is a compile-time error if evaluation of a constant * object results in an uncaught exception being thrown. */ static const CompileTimeErrorCode CONST_EVAL_THROWS_EXCEPTION = const CompileTimeErrorCode('CONST_EVAL_THROWS_EXCEPTION', "Evaluation of this constant expression throws an exception."); /** * 16.12.2 Const: It is a compile-time error if evaluation of a constant * object results in an uncaught exception being thrown. */ static const CompileTimeErrorCode CONST_EVAL_THROWS_IDBZE = const CompileTimeErrorCode( 'CONST_EVAL_THROWS_IDBZE', "Evaluation of this constant expression throws an " "IntegerDivisionByZeroException."); /** * 6.2 Formal Parameters: It is a compile-time error if a formal parameter is * declared as a constant variable. */ static const CompileTimeErrorCode CONST_FORMAL_PARAMETER = const CompileTimeErrorCode( 'CONST_FORMAL_PARAMETER', "Parameters can't be const.", correction: "Try removing the 'const' keyword."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a value that isn't statically // known to be a constant is assigned to a variable that's declared to be a // 'const' variable. // // #### Example // // The following code produces this diagnostic because `x` isn't declared to // be `const`: // // ```dart // var x = 0; // const y = [!x!]; // ``` // // #### Common fixes // // If the value being assigned can be declared to be `const`, then change the // declaration: // // ```dart // const x = 0; // const y = x; // ``` // // If the value can't be declared to be `const`, then remove the `const` // modifier from the variable, possibly using `final` in its place: // // ```dart // var x = 0; // final y = x; // ``` static const CompileTimeErrorCode CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE = const CompileTimeErrorCode('CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE', "Const variables must be initialized with a constant value.", correction: "Try changing the initializer to be a constant expression.", hasPublishedDocs: true); /** * 5 Variables: A constant variable must be initialized to a compile-time * constant or a compile-time error occurs. * * 12.1 Constants: A qualified reference to a static constant variable that is * not qualified by a deferred prefix. */ static const CompileTimeErrorCode CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used to " "initialized a const variable.", correction: "Try initializing the variable without referencing members of " "the deferred library, or changing the import to not be " "deferred."); /** * 7.5 Instance Variables: It is a compile-time error if an instance variable * is declared to be constant. */ static const CompileTimeErrorCode CONST_INSTANCE_FIELD = const CompileTimeErrorCode('CONST_INSTANCE_FIELD', "Only static fields can be declared as const.", correction: "Try declaring the field as final, or adding the keyword " "'static'."); /** * 12.8 Maps: It is a compile-time error if the key of an entry in a constant * map literal is an instance of a class that implements the operator * <i>==</i> unless the key is a string or integer. * * Parameters: * 0: the type of the entry's key */ static const CompileTimeErrorCode CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS = const CompileTimeErrorCode( 'CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS', "The constant map entry key expression type '{0}' can't override " "the == operator.", correction: "Try using a different value for the key, or " "removing the keyword 'const' from the map."); /** * 5 Variables: A constant variable must be initialized to a compile-time * constant (12.1) or a compile-time error occurs. * * Parameters: * 0: the name of the uninitialized final variable */ static const CompileTimeErrorCode CONST_NOT_INITIALIZED = const CompileTimeErrorCode('CONST_NOT_INITIALIZED', "The const variable '{0}' must be initialized.", correction: "Try adding an initialization to the declaration."); /** * Parameters: * 0: the type of the element */ static const CompileTimeErrorCode CONST_SET_ELEMENT_TYPE_IMPLEMENTS_EQUALS = const CompileTimeErrorCode( 'CONST_SET_ELEMENT_TYPE_IMPLEMENTS_EQUALS', "The constant set element type '{0}' can't override " "the == operator.", correction: "Try using a different value for the element, or " "removing the keyword 'const' from the set."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the expression of a spread // operator in a constant list or set evaluates to something other than a list // or a set. // // #### Example // // The following code produces this diagnostic: // // ```dart // const List<int> list1 = null; // const List<int> list2 = [...[!list1!]]; // ``` // // #### Common fixes // // Change the expression to something that evaluates to either a constant list // or a constant set: // // ```dart // const List<int> list1 = []; // const List<int> list2 = [...list1]; // ``` static const CompileTimeErrorCode CONST_SPREAD_EXPECTED_LIST_OR_SET = const CompileTimeErrorCode('CONST_SPREAD_EXPECTED_LIST_OR_SET', "A list or a set is expected in this spread.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the expression of a spread // operator in a constant map evaluates to something other than a map. // // #### Example // // The following code produces this diagnostic: // // ```dart // const Map<String, int> map1 = null; // const Map<String, int> map2 = {...[!map1!]}; // ``` // // #### Common fixes // // Change the expression to something that evaluates to a constant map: // // ```dart // const Map<String, int> map1 = {}; // const Map<String, int> map2 = {...map1}; // ``` static const CompileTimeErrorCode CONST_SPREAD_EXPECTED_MAP = const CompileTimeErrorCode( 'CONST_SPREAD_EXPECTED_MAP', "A map is expected in this spread.", hasPublishedDocs: true); /** * 16.12.2 Const: If <i>T</i> is a parameterized type <i>S&lt;U<sub>1</sub>, * &hellip;, U<sub>m</sub>&gt;</i>, let <i>R = S</i>; It is a compile time * error if <i>S</i> is not a generic type with <i>m</i> type parameters. * * Parameters: * 0: the name of the type being referenced (<i>S</i>) * 1: the number of type parameters that were declared * 2: the number of type arguments provided * * See [StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS], and * [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS]. */ static const CompileTimeErrorCode CONST_WITH_INVALID_TYPE_PARAMETERS = const CompileTimeErrorCode( 'CONST_WITH_INVALID_TYPE_PARAMETERS', "The type '{0}' is declared with {1} type parameters, but {2} type " "arguments were given.", correction: "Try adjusting the number of type arguments to match the number " "of type parameters."); /** * 16.12.2 Const: If <i>e</i> is of the form <i>const T(a<sub>1</sub>, * &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, &hellip;, * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if the * type <i>T</i> does not declare a constant constructor with the same name as * the declaration of <i>T</i>. */ static const CompileTimeErrorCode CONST_WITH_NON_CONST = const CompileTimeErrorCode('CONST_WITH_NON_CONST', "The constructor being called isn't a const constructor.", correction: "Try using 'new' to call the constructor."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a const constructor is invoked // with an argument that isn't a constant expression. // // #### Example // // The following code produces this diagnostic: // // ```dart // class C { // final int i; // const C(this.i); // } // C f(int i) => const C([!i!]); // ``` // // #### Common fixes // // Either make all of the arguments constant expressions, or remove the // `const` keyword to use the non-constant form of the constructor: // // ```dart // class C { // final int i; // const C(this.i); // } // C f(int i) => C(i); // ``` static const CompileTimeErrorCode CONST_WITH_NON_CONSTANT_ARGUMENT = const CompileTimeErrorCode('CONST_WITH_NON_CONSTANT_ARGUMENT', "Arguments of a constant creation must be constant expressions.", correction: "Try making the argument a valid constant, or " "use 'new' to call the constructor.", hasPublishedDocs: true); /** * 16.12.2 Const: It is a compile-time error if <i>T</i> is not a class * accessible in the current scope, optionally followed by type arguments. * * 16.12.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>, * &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, &hellip; * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if * <i>T</i> is not a class accessible in the current scope, optionally * followed by type arguments. * * Parameters: * 0: the name of the non-type element */ static const CompileTimeErrorCode CONST_WITH_NON_TYPE = const CompileTimeErrorCode( 'CONST_WITH_NON_TYPE', "The name '{0}' isn't a class.", correction: "Try correcting the name to match an existing class."); /** * 16.12.2 Const: If <i>T</i> is a parameterized type, it is a compile-time * error if <i>T</i> includes a type variable among its type arguments. */ static const CompileTimeErrorCode CONST_WITH_TYPE_PARAMETERS = const CompileTimeErrorCode('CONST_WITH_TYPE_PARAMETERS', "A constant creation can't use a type parameter as a type argument.", correction: "Try replacing the type parameter with a different type."); /** * 16.12.2 Const: It is a compile-time error if <i>T.id</i> is not the name of * a constant constructor declared by the type <i>T</i>. * * Parameters: * 0: the name of the type * 1: the name of the requested constant constructor */ static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR = const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR', "The class '{0}' doesn't have a constant constructor '{1}'.", correction: "Try calling a different constructor."); /** * 16.12.2 Const: It is a compile-time error if <i>T.id</i> is not the name of * a constant constructor declared by the type <i>T</i>. * * Parameters: * 0: the name of the type */ static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT = const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT', "The class '{0}' doesn't have a default constant constructor.", correction: "Try calling a different constructor."); /** * It is an error to call the default List constructor with a length argument * and a type argument which is potentially non-nullable. */ static const CompileTimeErrorCode DEFAULT_LIST_CONSTRUCTOR_MISMATCH = const CompileTimeErrorCode( 'DEFAULT_LIST_CONSTRUCTOR_MISMATCH', "A list whose values can't be 'null' can't be given an initial " "length because the initial values would all be 'null'.", correction: "Try removing the argument or using 'List.filled'."); /** * 15.3.1 Typedef: It is a compile-time error if any default values are * specified in the signature of a function type alias. */ static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS = const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS', "Default parameter values aren't allowed in typedefs.", correction: "Try removing the default value."); /** * 6.2.1 Required Formals: By means of a function signature that names the * parameter and describes its type as a function type. It is a compile-time * error if any default values are specified in the signature of such a * function type. */ static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER = const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER', "Default values aren't allowed in function typed parameters.", correction: "Try removing the default value."); /** * 7.6.2 Factories: It is a compile-time error if <i>k</i> explicitly * specifies a default value for an optional parameter. */ static const CompileTimeErrorCode DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR = const CompileTimeErrorCode( 'DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR', "Default values aren't allowed in factory constructors that redirect " "to another constructor.", correction: "Try removing the default value."); /** * No parameters. */ /* #### Description // // The analyzer produces this diagnostic when a named parameter has both the // `required` modifier and a default value. If the parameter is required, then // a value for the parameter is always provided at the call sites, so the // default value can never be used. // // #### Example // // The following code generates this diagnostic: // // ```dart // void log({required String [!message!] = 'no message'}) {} // ``` // // #### Common fixes // // If the parameter is really required, then remove the default value: // // ```dart // void log({required String message}) {} // ``` // // If the parameter isn't always required, then remove the `required` // modifier: // // ```dart // void log({String message = 'no message'}) {} // ``` */ static const CompileTimeErrorCode DEFAULT_VALUE_ON_REQUIRED_PARAMETER = const CompileTimeErrorCode('DEFAULT_VALUE_ON_REQUIRED_PARAMETER', "Required named parameters can't have a default value.", correction: "Try removing either the default value or the 'required' " "modifier."); /** * 3.1 Scoping: It is a compile-time error if there is more than one entity * with the same name declared in the same scope. */ static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_DEFAULT = const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_DEFAULT', "The default constructor is already defined.", correction: "Try giving one of the constructors a name."); /** * 3.1 Scoping: It is a compile-time error if there is more than one entity * with the same name declared in the same scope. * * Parameters: * 0: the name of the duplicate entity */ static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_NAME = const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_NAME', "The constructor with name '{0}' is already defined.", correction: "Try renaming one of the constructors."); /** * Parameters: * 0: the name of the duplicate entity */ // #### Description // // The analyzer produces this diagnostic when a name is declared, and there is // a previous declaration with the same name in the same scope. // // #### Example // // The following code produces this diagnostic: // // ```dart // int x = 0; // int [!x!] = 1; // ``` // // #### Common fixes // // Choose a different name for one of the declarations. // // ```dart // int x = 0; // int y = 1; // ``` static const CompileTimeErrorCode DUPLICATE_DEFINITION = const CompileTimeErrorCode( 'DUPLICATE_DEFINITION', "The name '{0}' is already defined.", correction: "Try renaming one of the declarations.", hasPublishedDocs: true); /** * 18.3 Parts: It's a compile-time error if the same library contains two part * directives with the same URI. * * Parameters: * 0: the URI of the duplicate part */ static const CompileTimeErrorCode DUPLICATE_PART = const CompileTimeErrorCode( 'DUPLICATE_PART', "The library already contains a part with the uri '{0}'.", correction: "Try removing all but one of the duplicated part directives."); /** * 12.14.2 Binding Actuals to Formals: It is a compile-time error if * <i>q<sub>i</sub> = q<sub>j</sub></i> for any <i>i != j</i> [where * <i>q<sub>i</sub></i> is the label for a named argument]. * * Parameters: * 0: the name of the parameter that was duplicated */ static const CompileTimeErrorCode DUPLICATE_NAMED_ARGUMENT = const CompileTimeErrorCode('DUPLICATE_NAMED_ARGUMENT', "The argument for the named parameter '{0}' was already specified.", correction: "Try removing one of the named arguments, or " "correcting one of the names to reference a different named " "parameter."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when two elements in a constant set // literal have the same value. The set can only contain each value once, // which means that one of the values is unnecessary. // // #### Example // // The following code produces this diagnostic: // // ```dart // const Set<String> set = {'a', [!'a'!]}; // ``` // // #### Common fixes // // Remove one of the duplicate values: // // ```dart // const Set<String> set = {'a'}; // ``` // // Note that literal sets preserve the order of their elements, so the choice // of which element to remove might affect the order in which elements are // returned by an iterator. static const CompileTimeErrorCode EQUAL_ELEMENTS_IN_CONST_SET = const CompileTimeErrorCode('EQUAL_ELEMENTS_IN_CONST_SET', "Two values in a constant set can't be equal.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a key in a constant map is the // same as a previous key in the same map. If two keys are the same, then the // second value would overwrite the first value, which makes having both pairs // pointless. // // #### Example // // The following code produces this diagnostic: // // ```dart // const map = <int, String>{1: 'a', 2: 'b', [!1!]: 'c', 4: 'd'}; // ``` // // #### Common fixes // // If both entries should be included in the map, then change one of the keys // to be different: // // ```dart // const map = <int, String>{1: 'a', 2: 'b', 3: 'c', 4: 'd'}; // ``` // // If only one of the entries is needed, then remove the one that isn't // needed: // // ```dart // const map = <int, String>{1: 'a', 2: 'b', 4: 'd'}; // ``` // // Note that literal maps preserve the order of their entries, so the choice // of which entry to remove might affect the order in which keys and values // are returned by an iterator. static const CompileTimeErrorCode EQUAL_KEYS_IN_CONST_MAP = const CompileTimeErrorCode('EQUAL_KEYS_IN_CONST_MAP', "Two keys in a constant map literal can't be equal.", correction: "Change or remove the duplicate key.", hasPublishedDocs: true); /** * SDK implementation libraries can be exported only by other SDK libraries. * * Parameters: * 0: the uri pointing to a library */ static const CompileTimeErrorCode EXPORT_INTERNAL_LIBRARY = const CompileTimeErrorCode('EXPORT_INTERNAL_LIBRARY', "The library '{0}' is internal and can't be exported."); /** * 14.2 Exports: It is a compile-time error if the compilation unit found at * the specified URI is not a library declaration. * * Parameters: * 0: the uri pointing to a non-library declaration */ static const CompileTimeErrorCode EXPORT_OF_NON_LIBRARY = const CompileTimeErrorCode('EXPORT_OF_NON_LIBRARY', "The exported library '{0}' can't have a part-of directive.", correction: "Try exporting the library that the part is a part of."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the analyzer finds an // expression, rather than a map entry, in what appears to be a map literal. // // #### Example // // The following code generates this diagnostic: // // ```dart // var map = <String, int>{'a': 0, 'b': 1, [!'c'!]}; // ``` // // #### Common fixes // // If the expression is intended to compute either a key or a value in an // entry, fix the issue by replacing the expression with the key or the value. // For example: // // ```dart // var map = <String, int>{'a': 0, 'b': 1, 'c': 2}; // ``` static const CompileTimeErrorCode EXPRESSION_IN_MAP = const CompileTimeErrorCode( 'EXPRESSION_IN_MAP', "Expressions can't be used in a map literal.", correction: "Try removing the expression or converting it to be a map " "entry.", hasPublishedDocs: true); /** * 12.2 Null: It is a compile-time error for a class to attempt to extend or * implement Null. * * 12.3 Numbers: It is a compile-time error for a class to attempt to extend * or implement int. * * 12.3 Numbers: It is a compile-time error for a class to attempt to extend * or implement double. * * 12.3 Numbers: It is a compile-time error for any type other than the types * int and double to * attempt to extend or implement num. * * 12.4 Booleans: It is a compile-time error for a class to attempt to extend * or implement bool. * * 12.5 Strings: It is a compile-time error for a class to attempt to extend * or implement String. * * Parameters: * 0: the name of the type that cannot be extended * * See [IMPLEMENTS_DISALLOWED_CLASS] and [MIXIN_OF_DISALLOWED_CLASS]. * * TODO(scheglov) We might want to restore specific code with FrontEnd. * https://github.com/dart-lang/sdk/issues/31821 */ static const CompileTimeErrorCode EXTENDS_DISALLOWED_CLASS = const CompileTimeErrorCode( 'EXTENDS_DISALLOWED_CLASS', "Classes can't extend '{0}'.", correction: "Try specifying a different superclass, or " "removing the extends clause."); /** * 7.9 Superclasses: It is a compile-time error if the extends clause of a * class <i>C</i> includes a deferred type expression. * * Parameters: * 0: the name of the type that cannot be extended * * See [IMPLEMENTS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS]. */ static const CompileTimeErrorCode EXTENDS_DEFERRED_CLASS = const CompileTimeErrorCode( 'EXTENDS_DEFERRED_CLASS', "Classes can't extend deferred classes.", correction: "Try specifying a different superclass, or " "removing the extends clause."); /** * 7.9 Superclasses: It is a compile-time error if the extends clause of a * class <i>C</i> includes a type expression that does not denote a class * available in the lexical scope of <i>C</i>. * * Parameters: * 0: the name of the superclass that was not found */ static const CompileTimeErrorCode EXTENDS_NON_CLASS = const CompileTimeErrorCode( 'EXTENDS_NON_CLASS', "Classes can only extend other classes.", correction: "Try specifying a different superclass, or removing the extends " "clause."); /** * Parameters: * 0: the name of the extension */ // #### Description // // The analyzer produces this diagnostic when the name of an extension is used // in an expression other than in an extension override or to qualify an // access to a static member of the extension. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on int { // static String m() => ''; // } // // var x = [!E!]; // ``` // // #### Common fixes // // Replace the name of the extension with a name that can be referenced, such // as a static member defined on the extension: // // ```dart // extension E on int { // static String m() => ''; // } // // var x = E.m(); // ``` static const CompileTimeErrorCode EXTENSION_AS_EXPRESSION = const CompileTimeErrorCode('EXTENSION_AS_EXPRESSION', "Extension '{0}' can't be used as an expression.", correction: "Try replacing it with a valid expression.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the extension defining the conflicting member * 1: the name of the conflicting static member */ // #### Description // // The analyzer produces this diagnostic when an extension declaration // contains both an instance member and a static member that have the same // name. The instance member and the static member can't have the same name // because it's unclear which member is being referenced by an unqualified use // of the name within the body of the extension. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on Object { // int get a => 0; // static int [!a!]() => 0; // } // ``` // // #### Common fixes // // Rename or remove one of the members: // // ```dart // extension E on Object { // int get a => 0; // static int b() => 0; // } // ``` static const CompileTimeErrorCode EXTENSION_CONFLICTING_STATIC_AND_INSTANCE = const CompileTimeErrorCode( 'EXTENSION_CONFLICTING_STATIC_AND_INSTANCE', "Extension '{0}' can't define static member '{1}' and an instance " "member with the same name.", correction: "Try renaming the member to a name that doesn't conflict.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an extension declaration // declares a member with the same name as a member declared in the class // `Object`. Such a member can never be used because the member in `Object` is // always found first. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on String { // String [!toString!]() => this; // } // ``` // // #### Common fixes // // Remove the member or rename it so that the name doesn't conflict with the // member in `Object`: // // ```dart // extension E on String { // String displayString() => this; // } // ``` static const CompileTimeErrorCode EXTENSION_DECLARES_MEMBER_OF_OBJECT = const CompileTimeErrorCode( 'EXTENSION_DECLARES_MEMBER_OF_OBJECT', "Extensions can't declare members with the same name as a member " "declared by 'Object'.", correction: "Try specifying a different name for the member.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an extension override is the // target of the invocation of a static member. Similar to static members in // classes, the static members of an extension should be accessed using the // name of the extension, not an extension override. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on String { // static void staticMethod() {} // } // // void f() { // E('').[!staticMethod!](); // } // ``` // // #### Common fixes // // Replace the extension override with the name of the extension: // // ```dart // extension E on String { // static void staticMethod() {} // } // // void f() { // E.staticMethod(); // } // ``` static const CompileTimeErrorCode EXTENSION_OVERRIDE_ACCESS_TO_STATIC_MEMBER = const CompileTimeErrorCode( 'EXTENSION_OVERRIDE_ACCESS_TO_STATIC_MEMBER', "An extension override can't be used to access a static member from " "an extension.", correction: "Try using just the name of the extension.", hasPublishedDocs: true); /** * Parameters: * 0: the type of the argument * 1: the extended type */ // #### Description // // The analyzer produces this diagnostic when the argument to an extension // override isn't assignable to the type being extended by the extension. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on String { // void method() {} // } // // void f() { // E([!3!]).method(); // } // ``` // // #### Common fixes // // If you're using the correct extension, then update the argument to have the // correct type: // // ```dart // extension E on String { // void method() {} // } // // void f() { // E(3.toString()).method(); // } // ``` // // If there's a different extension that's valid for the type of the argument, // then either replace the name of the extension or unwrap the target so that // the correct extension is found. static const CompileTimeErrorCode EXTENSION_OVERRIDE_ARGUMENT_NOT_ASSIGNABLE = const CompileTimeErrorCode( 'EXTENSION_OVERRIDE_ARGUMENT_NOT_ASSIGNABLE', "The type of the argument to the extension override '{0}' " "isn't assignable to the extended type '{1}'.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an extension override is used as // the target of a cascade expression. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on int { // void m() {} // } // f() { // E(3)[!..!]m(); // } // ``` // // #### Common fixes // // Use '.' rather than '..': // // ```dart // extension E on int { // void m() {} // } // f() { // E(3).m(); // } // ``` // // If there are multiple cascaded accesses, you'll need to duplicate the // extension override for each one. static const CompileTimeErrorCode EXTENSION_OVERRIDE_WITH_CASCADE = const CompileTimeErrorCode( 'EXTENSION_OVERRIDE_WITH_CASCADE', "Extension overrides have no value so they can't be used as the " "target of a cascade expression.", correction: "Try using '.' instead of '..'.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an extension override is found // that isn't being used to access one of the members of the extension. The // extension override syntax doesn't have any runtime semantics; it only // controls which member is selected at compile time. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on int { // int get a => 0; // } // // void f(int i) { // print([!E(i)!]); // } // ``` // // #### Common fixes // // If you want to invoke one of the members of the extension, then add the // invocation: // // ```dart // extension E on int { // int get a => 0; // } // // void f(int i) { // print(E(i).a); // } // ``` // // If you don't want to invoke a member, then unwrap the target: // // ```dart // extension E on int { // int get a => 0; // } // // void f(int i) { // print(i); // } // ``` static const CompileTimeErrorCode EXTENSION_OVERRIDE_WITHOUT_ACCESS = const CompileTimeErrorCode('EXTENSION_OVERRIDE_WITHOUT_ACCESS', "An extension override can only be used to access instance members.", correction: "Consider adding an access to an instance member.", hasPublishedDocs: true); /** * Parameters: * 0: the maximum number of positional arguments * 1: the actual number of positional arguments given */ // #### Description // // The analyzer produces this diagnostic when a method or function invocation // has more positional arguments than the method or function allows. // // #### Example // // The following code produces this diagnostic: // // ```dart // void f(int a, int b) {} // void g() { // f[!(1, 2, 3)!]; // } // ``` // // #### Common fixes // // Remove the arguments that don't correspond to parameters: // // ```dart // void f(int a, int b) {} // void g() { // f(1, 2); // } // ``` static const CompileTimeErrorCode EXTRA_POSITIONAL_ARGUMENTS = const CompileTimeErrorCode('EXTRA_POSITIONAL_ARGUMENTS', "Too many positional arguments: {0} expected, but {1} found.", correction: "Try removing the extra arguments.", hasPublishedDocs: true); /** * Parameters: * 0: the maximum number of positional arguments * 1: the actual number of positional arguments given */ // #### Description // // The analyzer produces this diagnostic when a method or function invocation // has more positional arguments than the method or function allows, but the // method or function defines named parameters. // // #### Example // // The following code produces this diagnostic: // // ```dart // void f(int a, int b, {int c}) {} // void g() { // f[!(1, 2, 3)!]; // } // ``` // // #### Common fixes // // If some of the arguments should be values for named parameters, then add // the names before the arguments: // // ```dart // void f(int a, int b, {int c}) {} // void g() { // f(1, 2, c: 3); // } // ``` // // Otherwise, remove the arguments that don't correspond to positional // parameters: // // ```dart // void f(int a, int b, {int c}) {} // void g() { // f(1, 2); // } // ``` static const CompileTimeErrorCode EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED = const CompileTimeErrorCode('EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED', "Too many positional arguments: {0} expected, but {1} found.", correction: "Try removing the extra positional arguments, " "or specifying the name for named arguments.", hasPublishedDocs: true); /** * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It * is a compile time error if more than one initializer corresponding to a * given instance variable appears in <i>k</i>'s list. * * Parameters: * 0: the name of the field being initialized multiple times */ static const CompileTimeErrorCode FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS = const CompileTimeErrorCode('FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS', "The field '{0}' can't be initialized twice in the same constructor.", correction: "Try removing one of the initializations."); /** * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It * is a compile time error if <i>k</i>'s initializer list contains an * initializer for a variable that is initialized by means of an initializing * formal of <i>k</i>. */ static const CompileTimeErrorCode FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER = const CompileTimeErrorCode( 'FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER', "Fields can't be initialized in both the parameter list and the " "initializers.", correction: "Try removing one of the initializations."); /** * 7.6.1 Generative Constructors: It is a compile-time error if an * initializing formal is used by a function other than a non-redirecting * generative constructor. */ static const CompileTimeErrorCode FIELD_INITIALIZER_FACTORY_CONSTRUCTOR = const CompileTimeErrorCode( 'FIELD_INITIALIZER_FACTORY_CONSTRUCTOR', "Initializing formal parameters can't be used in factory " "constructors.", correction: "Try using a normal parameter."); /** * 7.6.1 Generative Constructors: It is a compile-time error if an * initializing formal is used by a function other than a non-redirecting * generative constructor. */ static const CompileTimeErrorCode FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR = const CompileTimeErrorCode('FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR', "Initializing formal parameters can only be used in constructors.", correction: "Try using a normal parameter."); /** * 7.6.1 Generative Constructors: A generative constructor may be redirecting, * in which case its only action is to invoke another generative constructor. * * 7.6.1 Generative Constructors: It is a compile-time error if an * initializing formal is used by a function other than a non-redirecting * generative constructor. */ static const CompileTimeErrorCode FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR = const CompileTimeErrorCode('FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR', "The redirecting constructor can't have a field initializer.", correction: "Try using a normal parameter."); /** * 5 Variables: It is a compile-time error if a final instance variable that * has is initialized by means of an initializing formal of a constructor is * also initialized elsewhere in the same constructor. * * Parameters: * 0: the name of the field in question */ static const CompileTimeErrorCode FINAL_INITIALIZED_MULTIPLE_TIMES = const CompileTimeErrorCode('FINAL_INITIALIZED_MULTIPLE_TIMES', "'{0}' is a final field and so can only be set once.", correction: "Try removing all but one of the initializations."); static const CompileTimeErrorCode FOR_IN_WITH_CONST_VARIABLE = const CompileTimeErrorCode('FOR_IN_WITH_CONST_VARIABLE', "A for-in loop-variable can't be 'const'.", correction: "Try removing the 'const' modifier from the variable, or " "use a different variable."); /** * It is a compile-time error if a generic function type is used as a bound * for a formal type parameter of a class or a function. */ static const CompileTimeErrorCode GENERIC_FUNCTION_TYPE_CANNOT_BE_BOUND = const CompileTimeErrorCode('GENERIC_FUNCTION_TYPE_CANNOT_BE_BOUND', "Generic function types can't be used as type parameter bounds", correction: "Try making the free variable in the function type part" " of the larger declaration signature"); /** * It is a compile-time error if a generic function type is used as an actual * type argument. */ static const CompileTimeErrorCode GENERIC_FUNCTION_TYPE_CANNOT_BE_TYPE_ARGUMENT = const CompileTimeErrorCode( 'GENERIC_FUNCTION_TYPE_CANNOT_BE_TYPE_ARGUMENT', "A generic function type can't be a type argument.", correction: "Try removing type parameters from the generic function " "type, or using 'dynamic' as the type argument here."); /** * Temporary error to work around dartbug.com/28515. * * We cannot yet properly summarize function-typed parameters with generic * arguments, so to prevent confusion, we produce an error for any such * constructs (regardless of whether summaries are in use). * * TODO(paulberry): remove this once dartbug.com/28515 is fixed. */ static const CompileTimeErrorCode GENERIC_FUNCTION_TYPED_PARAM_UNSUPPORTED = const CompileTimeErrorCode('GENERIC_FUNCTION_TYPED_PARAM_UNSUPPORTED', "Analysis of generic function typed parameters isn't yet supported.", correction: "Try using an explicit typedef, or changing type parameters to " "`dynamic`."); static const CompileTimeErrorCode IF_ELEMENT_CONDITION_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'IF_ELEMENT_CONDITION_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as values in " "an if condition inside a const collection literal.", correction: "Try making the deferred import non-deferred."); /** * 7.10 Superinterfaces: It is a compile-time error if the implements clause * of a class <i>C</i> specifies a malformed type or deferred type as a * superinterface. * * See [EXTENDS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS]. */ static const CompileTimeErrorCode IMPLEMENTS_DEFERRED_CLASS = const CompileTimeErrorCode('IMPLEMENTS_DEFERRED_CLASS', "Classes and mixins can't implement deferred classes.", correction: "Try specifying a different interface, " "removing the class from the list, or " "changing the import to not be deferred."); /** * 12.2 Null: It is a compile-time error for a class to attempt to extend or * implement Null. * * 12.3 Numbers: It is a compile-time error for a class to attempt to extend * or implement int. * * 12.3 Numbers: It is a compile-time error for a class to attempt to extend * or implement double. * * 12.3 Numbers: It is a compile-time error for any type other than the types * int and double to * attempt to extend or implement num. * * 12.4 Booleans: It is a compile-time error for a class to attempt to extend * or implement bool. * * 12.5 Strings: It is a compile-time error for a class to attempt to extend * or implement String. * * Parameters: * 0: the name of the type that cannot be implemented * * See [EXTENDS_DISALLOWED_CLASS]. */ static const CompileTimeErrorCode IMPLEMENTS_DISALLOWED_CLASS = const CompileTimeErrorCode('IMPLEMENTS_DISALLOWED_CLASS', "Classes and mixins can't implement '{0}'.", correction: "Try specifying a different interface, or " "remove the class from the list."); /** * Parameters: * 0: the name of the interface that was not found */ // #### Description // // The analyzer produces this diagnostic when a name used in the implements // clause of a class or mixin declaration is defined to be something other // than a class or mixin. // // #### Example // // The following code produces this diagnostic: // // ```dart // var x; // class C implements [!x!] {} // ``` // // #### Common fixes // // If the name is the name of an existing class or mixin that's already being // imported, then add a prefix to the import so that the local definition of // the name doesn't shadow the imported name. // // If the name is the name of an existing class or mixin that isn't being // imported, then add an import, with a prefix, for the library in which it’s // declared. // // Otherwise, either replace the name in the implements clause with the name // of an existing class or mixin, or remove the name from the implements // clause. static const CompileTimeErrorCode IMPLEMENTS_NON_CLASS = const CompileTimeErrorCode('IMPLEMENTS_NON_CLASS', "Classes and mixins can only implement other classes and mixins.", correction: "Try specifying a class or mixin, or remove the name from the " "list.", hasPublishedDocs: true); /** * 10.10 Superinterfaces: It is a compile-time error if two elements in the * type list of the implements clause of a class `C` specifies the same * type `T`. * * Parameters: * 0: the name of the interface that is implemented more than once */ static const CompileTimeErrorCode IMPLEMENTS_REPEATED = const CompileTimeErrorCode( 'IMPLEMENTS_REPEATED', "'{0}' can only be implemented once.", correction: "Try removing all but one occurrence of the class name."); /** * 7.10 Superinterfaces: It is a compile-time error if the superclass of a * class <i>C</i> appears in the implements clause of <i>C</i>. * * Parameters: * 0: the name of the class that appears in both "extends" and "implements" * clauses */ static const CompileTimeErrorCode IMPLEMENTS_SUPER_CLASS = const CompileTimeErrorCode('IMPLEMENTS_SUPER_CLASS', "'{0}' can't be used in both 'extends' and 'implements' clauses.", correction: "Try removing one of the occurrences."); /** * 7.6.1 Generative Constructors: Note that <b>this</b> is not in scope on the * right hand side of an initializer. * * 12.10 This: It is a compile-time error if this appears in a top-level * function or variable initializer, in a factory constructor, or in a static * method or variable initializer, or in the initializer of an instance * variable. */ static const CompileTimeErrorCode IMPLICIT_THIS_REFERENCE_IN_INITIALIZER = const CompileTimeErrorCode('IMPLICIT_THIS_REFERENCE_IN_INITIALIZER', "Only static members can be accessed in initializers."); /** * SDK implementation libraries can be imported only by other SDK libraries. * * Parameters: * 0: the uri pointing to a library */ static const CompileTimeErrorCode IMPORT_INTERNAL_LIBRARY = const CompileTimeErrorCode('IMPORT_INTERNAL_LIBRARY', "The library '{0}' is internal and can't be imported."); /** * 14.1 Imports: It is a compile-time error if the specified URI of an * immediate import does not refer to a library declaration. * * Parameters: * 0: the uri pointing to a non-library declaration */ static const CompileTimeErrorCode IMPORT_OF_NON_LIBRARY = const CompileTimeErrorCode('IMPORT_OF_NON_LIBRARY', "The imported library '{0}' can't have a part-of directive.", correction: "Try importing the library that the part is a part of."); /** * 13.9 Switch: It is a compile-time error if values of the expressions * <i>e<sub>k</sub></i> are not instances of the same class <i>C</i>, for all * <i>1 &lt;= k &lt;= n</i>. * * Parameters: * 0: the expression source code that is the unexpected type * 1: the name of the expected type */ static const CompileTimeErrorCode INCONSISTENT_CASE_EXPRESSION_TYPES = const CompileTimeErrorCode('INCONSISTENT_CASE_EXPRESSION_TYPES', "Case expressions must have the same types, '{0}' isn't a '{1}'."); /** * If a class declaration does not have a member declaration with a * particular name, but some super-interfaces do have a member with that * name, it's a compile-time error if there is no signature among the * super-interfaces that is a valid override of all the other super-interface * signatures with the same name. That "most specific" signature becomes the * signature of the class's interface. * * Parameters: * 0: the name of the instance member with inconsistent inheritance. * 1: the list of all inherited signatures for this member. */ static const CompileTimeErrorCode INCONSISTENT_INHERITANCE = const CompileTimeErrorCode('INCONSISTENT_INHERITANCE', "Superinterfaces don't have a valid override for '{0}': {1}.", correction: "Try adding an explicit override that is consistent with all " "of the inherited members."); /** * 11.1.1 Inheritance and Overriding. Let `I` be the implicit interface of a * class `C` declared in library `L`. `I` inherits all members of * `inherited(I, L)` and `I` overrides `m'` if `m' ∈ overrides(I, L)`. It is * a compile-time error if `m` is a method and `m'` is a getter, or if `m` * is a getter and `m'` is a method. * * Parameters: * 0: the name of the the instance member with inconsistent inheritance. * 1: the name of the superinterface that declares the name as a getter. * 2: the name of the superinterface that declares the name as a method. */ static const CompileTimeErrorCode INCONSISTENT_INHERITANCE_GETTER_AND_METHOD = const CompileTimeErrorCode( 'INCONSISTENT_INHERITANCE_GETTER_AND_METHOD', "'{0}' is inherited as a getter (from '{1}') and also a " "method (from '{2}').", correction: "Try adjusting the supertypes of this class to remove the " "inconsistency."); /** * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It * is a compile-time error if <i>k</i>'s initializer list contains an * initializer for a variable that is not an instance variable declared in the * immediately surrounding class. * * Parameters: * 0: the name of the initializing formal that is not an instance variable in * the immediately enclosing class * * See [INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD]. */ static const CompileTimeErrorCode INITIALIZER_FOR_NON_EXISTENT_FIELD = const CompileTimeErrorCode('INITIALIZER_FOR_NON_EXISTENT_FIELD', "'{0}' isn't a field in the enclosing class.", correction: "Try correcting the name to match an existing field, or " "defining a field named '{0}'."); /** * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It * is a compile-time error if <i>k</i>'s initializer list contains an * initializer for a variable that is not an instance variable declared in the * immediately surrounding class. * * Parameters: * 0: the name of the initializing formal that is a static variable in the * immediately enclosing class * * See [INITIALIZING_FORMAL_FOR_STATIC_FIELD]. */ static const CompileTimeErrorCode INITIALIZER_FOR_STATIC_FIELD = const CompileTimeErrorCode( 'INITIALIZER_FOR_STATIC_FIELD', "'{0}' is a static field in the enclosing class. Fields initialized " "in a constructor can't be static.", correction: "Try removing the initialization."); /** * 7.6.1 Generative Constructors: An initializing formal has the form * <i>this.id</i>. It is a compile-time error if <i>id</i> is not the name of * an instance variable of the immediately enclosing class. * * Parameters: * 0: the name of the initializing formal that is not an instance variable in * the immediately enclosing class * * See [INITIALIZING_FORMAL_FOR_STATIC_FIELD], and * [INITIALIZER_FOR_NON_EXISTENT_FIELD]. */ static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD = const CompileTimeErrorCode('INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD', "'{0}' isn't a field in the enclosing class.", correction: "Try correcting the name to match an existing field, or " "defining a field named '{0}'."); /** * 7.6.1 Generative Constructors: An initializing formal has the form * <i>this.id</i>. It is a compile-time error if <i>id</i> is not the name of * an instance variable of the immediately enclosing class. * * Parameters: * 0: the name of the initializing formal that is a static variable in the * immediately enclosing class * * See [INITIALIZER_FOR_STATIC_FIELD]. */ static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_STATIC_FIELD = const CompileTimeErrorCode( 'INITIALIZING_FORMAL_FOR_STATIC_FIELD', "'{0}' is a static field in the enclosing class. Fields initialized " "in a constructor can't be static.", correction: "Try removing the initialization."); /** * 12.30 Identifier Reference: Otherwise, e is equivalent to the property * extraction <b>this</b>.<i>id</i>. */ static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_FACTORY = const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_FACTORY', "Instance members can't be accessed from a factory constructor.", correction: "Try removing the reference to the instance member."); /** * 12.30 Identifier Reference: Otherwise, e is equivalent to the property * extraction <b>this</b>.<i>id</i>. */ static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_STATIC = const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_STATIC', "Instance members can't be accessed from a static method.", correction: "Try removing the reference to the instance member, or ." "removing the keyword 'static' from the method."); /** * Enum proposal: It is also a compile-time error to explicitly instantiate an * enum via 'new' or 'const' or to access its private fields. */ static const CompileTimeErrorCode INSTANTIATE_ENUM = const CompileTimeErrorCode( 'INSTANTIATE_ENUM', "Enums can't be instantiated.", correction: "Try using one of the defined constants."); static const CompileTimeErrorCode INTEGER_LITERAL_OUT_OF_RANGE = const CompileTimeErrorCode('INTEGER_LITERAL_OUT_OF_RANGE', "The integer literal {0} can't be represented in 64 bits.", correction: "Try using the BigInt class if you need an integer larger than " "9,223,372,036,854,775,807 or less than " "-9,223,372,036,854,775,808."); /** * An integer literal with static type `double` and numeric value `i` * evaluates to an instance of the `double` class representing the value `i`. * It is a compile-time error if the value `i` cannot be represented * _precisely_ by the an instace of `double`. */ static const CompileTimeErrorCode INTEGER_LITERAL_IMPRECISE_AS_DOUBLE = const CompileTimeErrorCode( 'INTEGER_LITERAL_IMPRECISE_AS_DOUBLE', "The integer literal is being used as a double, but can't be " "represented as a 64 bit double without overflow and/or loss of " "precision: {0}", correction: "Try using the BigInt class, or switch to the closest valid " "double: {1}"); /** * 15 Metadata: Metadata consists of a series of annotations, each of which * begin with the character @, followed by a constant expression that must be * either a reference to a compile-time constant variable, or a call to a * constant constructor. */ static const CompileTimeErrorCode INVALID_ANNOTATION = const CompileTimeErrorCode( 'INVALID_ANNOTATION', "Annotation must be either a const variable reference or const " "constructor invocation."); /** * 15 Metadata: Metadata consists of a series of annotations, each of which * begin with the character @, followed by a constant expression that must be * either a reference to a compile-time constant variable, or a call to a * constant constructor. * * 12.1 Constants: A qualified reference to a static constant variable that is * not qualified by a deferred prefix. */ static const CompileTimeErrorCode INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as " "annotations.", correction: "Try removing the annotation, or " "changing the import to not be deferred."); /** * 15 Metadata: Metadata consists of a series of annotations, each of which * begin with the character @, followed by a constant expression that must be * either a reference to a compile-time constant variable, or a call to a * constant constructor. */ static const CompileTimeErrorCode INVALID_ANNOTATION_GETTER = const CompileTimeErrorCode( 'INVALID_ANNOTATION_GETTER', "Getters can't be used as annotations.", correction: "Try using a top-level variable or a field."); /** * TODO(brianwilkerson) Remove this when we have decided on how to report * errors in compile-time constants. Until then, this acts as a placeholder * for more informative errors. * * See TODOs in ConstantVisitor */ static const CompileTimeErrorCode INVALID_CONSTANT = const CompileTimeErrorCode('INVALID_CONSTANT', "Invalid constant value."); /** * 7.6 Constructors: It is a compile-time error if the name of a constructor * is not a constructor name. */ static const CompileTimeErrorCode INVALID_CONSTRUCTOR_NAME = const CompileTimeErrorCode( 'INVALID_CONSTRUCTOR_NAME', "Invalid constructor name."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an extension override doesn't // have exactly one argument. The argument is the expression used to compute // the value of `this` within the extension method, so there must be one // argument. // // #### Example // // The following code produces this diagnostic because there are no arguments: // // ```dart // extension E on String { // String join(String other) => '$this $other'; // } // // void f() { // E[!()!].join('b'); // } // ``` // // And, the following code produces this diagnostic because there's more than // one argument: // // ```dart // extension E on String { // String join(String other) => '$this $other'; // } // // void f() { // E[!('a', 'b')!].join('c'); // } // ``` // // #### Common fixes // // Provide one argument for the extension override: // // ```dart // extension E on String { // String join(String other) => '$this $other'; // } // // void f() { // E('a').join('b'); // } // ``` static const CompileTimeErrorCode INVALID_EXTENSION_ARGUMENT_COUNT = const CompileTimeErrorCode( 'INVALID_EXTENSION_ARGUMENT_COUNT', "Extension overrides must have exactly one argument: " "the value of 'this' in the extension method.", correction: "Try specifying exactly one argument.", hasPublishedDocs: true); /** * 7.6.2 Factories: It is a compile-time error if <i>M</i> is not the name of * the immediately enclosing class. */ static const CompileTimeErrorCode INVALID_FACTORY_NAME_NOT_A_CLASS = const CompileTimeErrorCode( 'INVALID_FACTORY_NAME_NOT_A_CLASS', "The name of a factory constructor must be the same as the name of " "the immediately enclosing class."); static const CompileTimeErrorCode INVALID_INLINE_FUNCTION_TYPE = const CompileTimeErrorCode( 'INVALID_INLINE_FUNCTION_TYPE', "Inline function types can't be used for parameters in a generic " "function type.", correction: "Try using a generic function type " "(returnType 'Function(' parameters ')')."); /** * 9. Functions: It is a compile-time error if an async, async* or sync* * modifier is attached to the body of a setter or constructor. */ static const CompileTimeErrorCode INVALID_MODIFIER_ON_CONSTRUCTOR = const CompileTimeErrorCode('INVALID_MODIFIER_ON_CONSTRUCTOR', "The modifier '{0}' can't be applied to the body of a constructor.", correction: "Try removing the modifier."); /** * 9. Functions: It is a compile-time error if an async, async* or sync* * modifier is attached to the body of a setter or constructor. */ static const CompileTimeErrorCode INVALID_MODIFIER_ON_SETTER = const CompileTimeErrorCode('INVALID_MODIFIER_ON_SETTER', "The modifier '{0}' can't be applied to the body of a setter.", correction: "Try removing the modifier."); /** * It is an error if an optional parameter (named or otherwise) with no * default value has a potentially non-nullable type. This is produced in * cases where there is no valid default value. */ static const CompileTimeErrorCode INVALID_OPTIONAL_PARAMETER_TYPE = const CompileTimeErrorCode( 'INVALID_OPTIONAL_PARAMETER_TYPE', "The parameter '{0}' can't have a value of 'null' because of its " "type, but no non-null default value is provided.", correction: "Try making this nullable (by adding a '?'), " "adding a default value, or " "making this a required parameter."); /** * If a class declaration has a member declaration, the signature of that * member declaration becomes the signature in the interface. It's a * compile-time error if that signature is not a valid override of all * super-interface member signatures with the same name. (Not just the * members of the immediate super-interfaces, but all of them. For * non-covariant parameters, it's sufficient to check just the immediate * super-interfaces). * * Parameters: * 0: the name of the declared member that is not a valid override. * 1: the name of the interface that declares the member. * 2: the type of the declared member in the interface. * 3. the name of the interface with the overridden member. * 4. the type of the overridden member. */ static const CompileTimeErrorCode INVALID_OVERRIDE = const CompileTimeErrorCode('INVALID_OVERRIDE', "'{1}.{0}' ('{2}') isn't a valid override of '{3}.{0}' ('{4}')."); /** * 12.10 This: It is a compile-time error if this appears in a top-level * function or variable initializer, in a factory constructor, or in a static * method or variable initializer, or in the initializer of an instance * variable. */ static const CompileTimeErrorCode INVALID_REFERENCE_TO_THIS = const CompileTimeErrorCode('INVALID_REFERENCE_TO_THIS', "Invalid reference to 'this' expression."); /** * 12.6 Lists: It is a compile time error if the type argument of a constant * list literal includes a type parameter. * * Parameters: * 0: the name of the type parameter */ static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_LIST = const CompileTimeErrorCode( 'INVALID_TYPE_ARGUMENT_IN_CONST_LIST', "Constant list literals can't include a type parameter as a type " "argument, such as '{0}'.", correction: "Try replacing the type parameter with a different type."); /** * 12.7 Maps: It is a compile time error if the type arguments of a constant * map literal include a type parameter. * * Parameters: * 0: the name of the type parameter */ static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_MAP = const CompileTimeErrorCode( 'INVALID_TYPE_ARGUMENT_IN_CONST_MAP', "Constant map literals can't include a type parameter as a type " "argument, such as '{0}'.", correction: "Try replacing the type parameter with a different type."); static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_SET = const CompileTimeErrorCode( 'INVALID_TYPE_ARGUMENT_IN_CONST_SET', "Constant set literals can't include a type parameter as a type " "argument, such as '{0}'.", correction: "Try replacing the type parameter with a different type."); /** * The 'covariant' keyword was found in an inappropriate location. */ static const CompileTimeErrorCode INVALID_USE_OF_COVARIANT = const CompileTimeErrorCode( 'INVALID_USE_OF_COVARIANT', "The 'covariant' keyword can only be used for parameters in instance " "methods or before non-final instance fields.", correction: "Try removing the 'covariant' keyword."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a member declared inside an // extension uses the keyword `covariant` in the declaration of a parameter. // Extensions aren't classes and don't have subclasses, so the keyword serves // no purpose. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on String { // void a([!covariant!] int i) {} // } // ``` // // #### Common fixes // // Remove the 'covariant' keyword: // // ```dart // extension E on String { // void a(int i) {} // } // ``` static const CompileTimeErrorCode INVALID_USE_OF_COVARIANT_IN_EXTENSION = const CompileTimeErrorCode('INVALID_USE_OF_COVARIANT_IN_EXTENSION', "The 'covariant' keyword can't be used in an extension.", correction: "Try removing the 'covariant' keyword.", hasPublishedDocs: true); /** * 14.2 Exports: It is a compile-time error if the compilation unit found at * the specified URI is not a library declaration. * * 14.1 Imports: It is a compile-time error if the compilation unit found at * the specified URI is not a library declaration. * * 14.3 Parts: It is a compile time error if the contents of the URI are not a * valid part declaration. * * Parameters: * 0: the URI that is invalid * * See [URI_DOES_NOT_EXIST]. */ static const CompileTimeErrorCode INVALID_URI = const CompileTimeErrorCode('INVALID_URI', "Invalid URI syntax: '{0}'."); /** * Parameters: * 0: the name of the extension */ static const CompileTimeErrorCode INVOCATION_OF_EXTENSION_WITHOUT_CALL = const CompileTimeErrorCode( 'INVOCATION_OF_EXTENSION_WITHOUT_CALL', "The extension '{0}' does not define a 'call' method so the override " "can't be used in an invocation."); /** * 13.13 Break: It is a compile-time error if no such statement * <i>s<sub>E</sub></i> exists within the innermost function in which * <i>s<sub>b</sub></i> occurs. * * 13.14 Continue: It is a compile-time error if no such statement or case * clause <i>s<sub>E</sub></i> exists within the innermost function in which * <i>s<sub>c</sub></i> occurs. * * Parameters: * 0: the name of the unresolvable label */ static const CompileTimeErrorCode LABEL_IN_OUTER_SCOPE = const CompileTimeErrorCode('LABEL_IN_OUTER_SCOPE', "Can't reference label '{0}' declared in an outer method."); /** * 13.13 Break: It is a compile-time error if no such statement * <i>s<sub>E</sub></i> exists within the innermost function in which * <i>s<sub>b</sub></i> occurs. * * 13.14 Continue: It is a compile-time error if no such statement or case * clause <i>s<sub>E</sub></i> exists within the innermost function in which * <i>s<sub>c</sub></i> occurs. * * Parameters: * 0: the name of the unresolvable label */ static const CompileTimeErrorCode LABEL_UNDEFINED = const CompileTimeErrorCode( 'LABEL_UNDEFINED', "Can't reference undefined label '{0}'.", correction: "Try defining the label, or " "correcting the name to match an existing label."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a map entry (a key/value pair) // is found in a set literal. // // #### Example // // The following code produces this diagnostic: // // ```dart // const collection = <String>{[!'a' : 'b'!]}; // ``` // // #### Common fixes // // If you intended for the collection to be a map, then change the code so // that it is a map. In the previous example, you could do this by adding // another type argument: // // ```dart // const collection = <String, String>{'a' : 'b'}; // ``` // // In other cases, you might need to change the explicit type from `Set` to // `Map`. // // If you intended for the collection to be a set, then remove the map entry, // possibly by replacing the colon with a comma if both values should be // included in the set: // // ```dart // const collection = <String>{'a', 'b'}; // ``` static const CompileTimeErrorCode MAP_ENTRY_NOT_IN_MAP = const CompileTimeErrorCode('MAP_ENTRY_NOT_IN_MAP', "Map entries can only be used in a map literal.", correction: "Try converting the collection to a map or removing the map " "entry.", hasPublishedDocs: true); /** * 7 Classes: It is a compile time error if a class <i>C</i> declares a member * with the same name as <i>C</i>. */ static const CompileTimeErrorCode MEMBER_WITH_CLASS_NAME = const CompileTimeErrorCode('MEMBER_WITH_CLASS_NAME', "Class members can't have the same name as the enclosing class."); /** * 12.1 Constants: A constant expression is ... a constant list literal. */ static const CompileTimeErrorCode MISSING_CONST_IN_LIST_LITERAL = const CompileTimeErrorCode( 'MISSING_CONST_IN_LIST_LITERAL', "List literals must be prefixed with 'const' when used as a constant " "expression.", correction: "Try adding the keyword 'const' before the literal."); /** * 12.1 Constants: A constant expression is ... a constant map literal. */ static const CompileTimeErrorCode MISSING_CONST_IN_MAP_LITERAL = const CompileTimeErrorCode( 'MISSING_CONST_IN_MAP_LITERAL', "Map literals must be prefixed with 'const' when used as a constant " "expression.", correction: "Try adding the keyword 'const' before the literal."); /** * 12.1 Constants: A constant expression is ... a constant set literal. */ static const CompileTimeErrorCode MISSING_CONST_IN_SET_LITERAL = const CompileTimeErrorCode( 'MISSING_CONST_IN_SET_LITERAL', "Set literals must be prefixed with 'const' when used as a constant " "expression.", correction: "Try adding the keyword 'const' before the literal."); static const CompileTimeErrorCode MISSING_DART_LIBRARY = const CompileTimeErrorCode( 'MISSING_DART_LIBRARY', "Required library '{0}' is missing.", correction: "Check your Dart SDK installation for completeness."); /** * No parameters. */ /* #### Description // // The analyzer produces this diagnostic when an optional parameter doesn't // have a default value, but has a // <a href=”#potentially-non-nullable”>potentially non-nullable</a> type. // Optional parameters that have no explicit default value have an implicit // default value of `null`. If the type of the parameter doesn't allow the // parameter to have a value of null, then the implicit default value is not // valid. // // #### Example // // The following code generates this diagnostic: // // ```dart // void log({String [!message!]}) {} // ``` // // #### Common fixes // // If the parameter can have the value `null`, then add a question mark after // the type annotation: // // ```dart // void log({String? message}) {} // ``` // // If the parameter can't be null, then either provide a default value: // // ```dart // void log({String message = ''}) {} // ``` // // or add the `required` modifier to the parameter: // // ```dart // void log({required String message}) {} // ``` */ static const CompileTimeErrorCode MISSING_DEFAULT_VALUE_FOR_PARAMETER = const CompileTimeErrorCode( 'MISSING_DEFAULT_VALUE_FOR_PARAMETER', "The parameter '{0}' can't have a value of 'null' because of its " "type, so it must either be a required parameter or have a " "default value.", correction: "Try adding either a default value or the 'required' modifier."); /** * It is an error if a named parameter that is marked as being required is * not bound to an argument at a call site. * * Parameters: * 0: the name of the parameter */ static const CompileTimeErrorCode MISSING_REQUIRED_ARGUMENT = const CompileTimeErrorCode('MISSING_REQUIRED_ARGUMENT', "The named parameter '{0}' is required but was not provided.", correction: "Try adding the required argument."); /** * It's a compile-time error to apply a mixin containing super-invocations to * a class that doesn't have a concrete implementation of the super-invoked * members compatible with the super-constraint interface. * * This ensures that if more than one super-constraint interface declares a * member with the same name, at least one of those members is more specific * than the rest, and this is the unique signature that super-invocations * are allowed to invoke. * * Parameters: * 0: the name of the super-invoked member * 1: the display name of the type of the super-invoked member in the mixin * 2: the display name of the type of the concrete member in the class */ static const CompileTimeErrorCode MIXIN_APPLICATION_CONCRETE_SUPER_INVOKED_MEMBER_TYPE = const CompileTimeErrorCode( 'MIXIN_APPLICATION_CONCRETE_SUPER_INVOKED_MEMBER_TYPE', "The super-invoked member '{0}' has the type '{1}', but the " "concrete member in the class has type '{2}'."); /** * It's a compile-time error to apply a mixin to a class that doesn't * implement all the `on` type requirements of the mixin declaration. * * Parameters: * 0: the display name of the mixin * 1: the display name of the superclass * 2: the display name of the type that is not implemented */ static const CompileTimeErrorCode MIXIN_APPLICATION_NOT_IMPLEMENTED_INTERFACE = const CompileTimeErrorCode( 'MIXIN_APPLICATION_NOT_IMPLEMENTED_INTERFACE', "'{0}' can't be mixed onto '{1}' because '{1}' doesn't implement " "'{2}'.", correction: "Try extending the class '{0}'."); /** * It's a compile-time error to apply a mixin containing super-invocations to * a class that doesn't have a concrete implementation of the super-invoked * members compatible with the super-constraint interface. * * Parameters: * 0: the display name of the member without a concrete implementation */ static const CompileTimeErrorCode MIXIN_APPLICATION_NO_CONCRETE_SUPER_INVOKED_MEMBER = const CompileTimeErrorCode( 'MIXIN_APPLICATION_NO_CONCRETE_SUPER_INVOKED_MEMBER', "The class doesn't have a concrete implementation of the " "super-invoked member '{0}'."); /** * 9 Mixins: It is a compile-time error if a declared or derived mixin * explicitly declares a constructor. * * Parameters: * 0: the name of the mixin that is invalid */ static const CompileTimeErrorCode MIXIN_CLASS_DECLARES_CONSTRUCTOR = const CompileTimeErrorCode( 'MIXIN_CLASS_DECLARES_CONSTRUCTOR', "The class '{0}' can't be used as a mixin because it declares a " "constructor."); /** * The <i>mixinMember</i> production allows the same instance or static * members that a class would allow, but no constructors (for now). */ static const CompileTimeErrorCode MIXIN_DECLARES_CONSTRUCTOR = const CompileTimeErrorCode( 'MIXIN_DECLARES_CONSTRUCTOR', "Mixins can't declare constructors."); /** * 9.1 Mixin Application: It is a compile-time error if the with clause of a * mixin application <i>C</i> includes a deferred type expression. * * Parameters: * 0: the name of the type that cannot be extended * * See [EXTENDS_DEFERRED_CLASS], and [IMPLEMENTS_DEFERRED_CLASS]. */ static const CompileTimeErrorCode MIXIN_DEFERRED_CLASS = const CompileTimeErrorCode( 'MIXIN_DEFERRED_CLASS', "Classes can't mixin deferred classes.", correction: "Try changing the import to not be deferred."); static const CompileTimeErrorCode MIXIN_INFERENCE_INCONSISTENT_MATCHING_CLASSES = const CompileTimeErrorCode( 'MIXIN_INFERENCE_INCONSISTENT_MATCHING_CLASSES', "Type parameters couldn't be inferred for the mixin '{0}' because " "the base class implements the mixin's supertype constraint " "'{1}' in multiple conflicting ways"); static const CompileTimeErrorCode MIXIN_INFERENCE_NO_MATCHING_CLASS = const CompileTimeErrorCode( 'MIXIN_INFERENCE_NO_MATCHING_CLASS', "Type parameters couldn't be inferred for the mixin '{0}' because " "the base class doesn't implement the mixin's supertype " "constraint '{1}'"); static const CompileTimeErrorCode MIXIN_INFERENCE_NO_POSSIBLE_SUBSTITUTION = const CompileTimeErrorCode( 'MIXIN_INFERENCE_NO_POSSIBLE_SUBSTITUTION', "Type parameters couldn't be inferred for the mixin '{0}' because " "no type parameter substitution could be found matching the " "mixin's supertype constraints"); /** * 9 Mixins: It is a compile-time error if a mixin is derived from a class * whose superclass is not Object. * * Parameters: * 0: the name of the mixin that is invalid */ static const CompileTimeErrorCode MIXIN_INHERITS_FROM_NOT_OBJECT = const CompileTimeErrorCode( 'MIXIN_INHERITS_FROM_NOT_OBJECT', "The class '{0}' can't be used as a mixin because it extends a class " "other than Object."); /** * A mixin declaration introduces a mixin and an interface, but not a class. */ static const CompileTimeErrorCode MIXIN_INSTANTIATE = const CompileTimeErrorCode( 'MIXIN_INSTANTIATE', "Mixins can't be instantiated."); /** * 12.2 Null: It is a compile-time error for a class to attempt to extend or * implement Null. * * 12.3 Numbers: It is a compile-time error for a class to attempt to extend * or implement int. * * 12.3 Numbers: It is a compile-time error for a class to attempt to extend * or implement double. * * 12.3 Numbers: It is a compile-time error for any type other than the types * int and double to attempt to extend or implement num. * * 12.4 Booleans: It is a compile-time error for a class to attempt to extend * or implement bool. * * 12.5 Strings: It is a compile-time error for a class to attempt to extend * or implement String. * * Parameters: * 0: the name of the type that cannot be extended * * See [IMPLEMENTS_DISALLOWED_CLASS]. */ static const CompileTimeErrorCode MIXIN_OF_DISALLOWED_CLASS = const CompileTimeErrorCode( 'MIXIN_OF_DISALLOWED_CLASS', "Classes can't mixin '{0}'."); /** * 9.1 Mixin Application: It is a compile-time error if <i>M</i> does not * denote a class or mixin available in the immediately enclosing scope. */ static const CompileTimeErrorCode MIXIN_OF_NON_CLASS = const CompileTimeErrorCode( 'MIXIN_OF_NON_CLASS', "Classes can only mixin other classes."); /** * 9 Mixins: It is a compile-time error if a declared or derived mixin refers * to super. */ static const CompileTimeErrorCode MIXIN_REFERENCES_SUPER = const CompileTimeErrorCode( 'MIXIN_REFERENCES_SUPER', "The class '{0}' can't be used as a mixin because it references " "'super'."); static const CompileTimeErrorCode MIXIN_SUPER_CLASS_CONSTRAINT_DEFERRED_CLASS = const CompileTimeErrorCode( 'MIXIN_SUPER_CLASS_CONSTRAINT_DEFERRED_CLASS', "Deferred classes can't be used as super-class constraints.", correction: "Try changing the import to not be deferred."); static const CompileTimeErrorCode MIXIN_SUPER_CLASS_CONSTRAINT_DISALLOWED_CLASS = const CompileTimeErrorCode( 'MIXIN_SUPER_CLASS_CONSTRAINT_DISALLOWED_CLASS', "'{0}' can't be used as a super-class constraint."); static const CompileTimeErrorCode MIXIN_SUPER_CLASS_CONSTRAINT_NON_INTERFACE = const CompileTimeErrorCode('MIXIN_SUPER_CLASS_CONSTRAINT_NON_INTERFACE', "Only classes and mixins can be used as super-class constraints."); /** * 9.1 Mixin Application: It is a compile-time error if <i>S</i> does not * denote a class available in the immediately enclosing scope. */ static const CompileTimeErrorCode MIXIN_WITH_NON_CLASS_SUPERCLASS = const CompileTimeErrorCode('MIXIN_WITH_NON_CLASS_SUPERCLASS', "Mixin can only be applied to class."); /** * 7.6.1 Generative Constructors: A generative constructor may be redirecting, * in which case its only action is to invoke another generative constructor. */ static const CompileTimeErrorCode MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS = const CompileTimeErrorCode( 'MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS', "Constructors can have at most one 'this' redirection.", correction: "Try removing all but one of the redirections."); /** * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. * Then <i>k</i> may include at most one superinitializer in its initializer * list or a compile time error occurs. */ static const CompileTimeErrorCode MULTIPLE_SUPER_INITIALIZERS = const CompileTimeErrorCode('MULTIPLE_SUPER_INITIALIZERS', "Constructor may have at most one 'super' initializer.", correction: "Try removing all but one of the 'super' initializers."); /** * 15 Metadata: Metadata consists of a series of annotations, each of which * begin with the character @, followed by a constant expression that must be * either a reference to a compile-time constant variable, or a call to a * constant constructor. */ static const CompileTimeErrorCode NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS = const CompileTimeErrorCode('NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS', "Annotation creation must have arguments.", correction: "Try adding an empty argument list."); /** * This error is generated if a constructor declaration has an implicit * invocation of a zero argument super constructor (`super()`), but the * superclass does not define a zero argument constructor. * * 7.6.1 Generative Constructors: If no superinitializer is provided, an * implicit superinitializer of the form <b>super</b>() is added at the end of * <i>k</i>'s initializer list, unless the enclosing class is class * <i>Object</i>. * * 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i> * does not declare a generative constructor named <i>S</i> (respectively * <i>S.id</i>) * * Parameters: * 0: the name of the superclass that does not define the implicitly invoked * constructor */ static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT = const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT', "The superclass '{0}' doesn't have a zero argument constructor.", correction: "Try declaring a zero argument constructor in '{0}', or " "explicitly invoking a different constructor in '{0}'."); /** * This error is generated if a class declaration has an implicit default * constructor, which implicitly invokes a zero argument super constructor * (`super()`), but the superclass does not define a zero argument * constructor. * * 7.6 Constructors: Iff no constructor is specified for a class <i>C</i>, it * implicitly has a default constructor C() : <b>super<b>() {}, unless * <i>C</i> is class <i>Object</i>. * * 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i> * does not declare a generative constructor named <i>S</i> (respectively * <i>S.id</i>) * * Parameters: * 0: the name of the superclass that does not define the implicitly invoked * constructor * 1: the name of the subclass that does not contain any explicit constructors */ static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT = const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT', "The superclass '{0}' doesn't have a zero argument constructor.", correction: "Try declaring a zero argument constructor in '{0}', or " "declaring a constructor in {1} that explicitly invokes a " "constructor in '{0}'."); /** * 13.2 Expression Statements: It is a compile-time error if a non-constant * map literal that has no explicit type arguments appears in a place where a * statement is expected. */ static const CompileTimeErrorCode NON_CONST_MAP_AS_EXPRESSION_STATEMENT = const CompileTimeErrorCode( 'NON_CONST_MAP_AS_EXPRESSION_STATEMENT', "A non-constant map or set literal without type arguments can't be " "used as an expression statement."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the expression in a case clause // isn't a constant expression. // // #### Example // // The following code produces this diagnostic: // // ```dart // void f(int i, int j) { // switch (i) { // case [!j!]: // // ... // break; // } // } // ``` // // #### Common fixes // // Either make the expression a constant expression, or rewrite the switch // statement as a sequence of if statements: // // ```dart // void f(int i, int j) { // if (i == j) { // // ... // } // } // ``` static const CompileTimeErrorCode NON_CONSTANT_CASE_EXPRESSION = const CompileTimeErrorCode( 'NON_CONSTANT_CASE_EXPRESSION', "Case expressions must be constant.", hasPublishedDocs: true); /** * 13.9 Switch: Given a switch statement of the form <i>switch (e) { * label<sub>11</sub> &hellip; label<sub>1j1</sub> case e<sub>1</sub>: * s<sub>1</sub> &hellip; label<sub>n1</sub> &hellip; label<sub>njn</sub> case * e<sub>n</sub>: s<sub>n</sub> default: s<sub>n+1</sub>}</i> or the form * <i>switch (e) { label<sub>11</sub> &hellip; label<sub>1j1</sub> case * e<sub>1</sub>: s<sub>1</sub> &hellip; label<sub>n1</sub> &hellip; * label<sub>njn</sub> case e<sub>n</sub>: s<sub>n</sub>}</i>, it is a * compile-time error if the expressions <i>e<sub>k</sub></i> are not * compile-time constants, for all <i>1 &lt;= k &lt;= n</i>. * * 12.1 Constants: A qualified reference to a static constant variable that is * not qualified by a deferred prefix. */ static const CompileTimeErrorCode NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as a case " "expression.", correction: "Try re-writing the switch as a series of if statements, or " "changing the import to not be deferred."); /** * 6.2.2 Optional Formals: It is a compile-time error if the default value of * an optional parameter is not a compile-time constant. */ static const CompileTimeErrorCode NON_CONSTANT_DEFAULT_VALUE = const CompileTimeErrorCode('NON_CONSTANT_DEFAULT_VALUE', "Default values of an optional parameter must be constant."); /** * 6.2.2 Optional Formals: It is a compile-time error if the default value of * an optional parameter is not a compile-time constant. * * 12.1 Constants: A qualified reference to a static constant variable that is * not qualified by a deferred prefix. */ static const CompileTimeErrorCode NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as a default " "parameter value.", correction: "Try leaving the default as null and initializing the parameter " "inside the function body."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an element in a constant list // literal isn't a constant value. The list literal can be constant either // explicitly (because it's prefixed by the `const` keyword) or implicitly // (because it appears in a [constant context](#constant-context)). // // #### Example // // The following code produces this diagnostic because `x` isn't a constant, // even though it appears in an implicitly constant list literal: // // ```dart // var x = 2; // var y = const <int>[0, 1, [!x!]]; // ``` // // #### Common fixes // // If the list needs to be a constant list, then convert the element to be a // constant. In the example above, you might add the `const` keyword to the // declaration of `x`: // // ```dart // const x = 2; // var y = const <int>[0, 1, x]; // ``` // // If the expression can't be made a constant, then the list can't be a // constant either, so you must change the code so that the list isn't a // constant. In the example above this means removing the `const` keyword // before the list literal: // // ```dart // var x = 2; // var y = <int>[0, 1, x]; // ``` static const CompileTimeErrorCode NON_CONSTANT_LIST_ELEMENT = const CompileTimeErrorCode('NON_CONSTANT_LIST_ELEMENT', "The values in a const list literal must be constants.", correction: "Try removing the keyword 'const' from the list literal.", hasPublishedDocs: true); /** * 12.6 Lists: It is a compile time error if an element of a constant list * literal is not a compile-time constant. * * 12.1 Constants: A qualified reference to a static constant variable that is * not qualified by a deferred prefix. */ static const CompileTimeErrorCode NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as values in " "a 'const' list.", correction: "Try removing the keyword 'const' from the list literal."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a key in a constant map literal // isn't a constant value. // // #### Example // // The following code produces this diagnostic: // // ```dart // var a = 'a'; // var m = const {[!a!]: 0}; // ``` // // #### Common fixes // // If the map needs to be a constant map, then make the key a constant: // // ```dart // const a = 'a'; // var m = const {a: 0}; // ``` // // If the map doesn't need to be a constant map, then remove the `const` // keyword: // // ```dart // var a = 'a'; // var m = {a: 0}; // ``` static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY = const CompileTimeErrorCode('NON_CONSTANT_MAP_KEY', "The keys in a const map literal must be constant.", correction: "Try removing the keyword 'const' from the map literal.", hasPublishedDocs: true); /** * 12.7 Maps: It is a compile time error if either a key or a value of an * entry in a constant map literal is not a compile-time constant. * * 12.1 Constants: A qualified reference to a static constant variable that is * not qualified by a deferred prefix. */ static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as keys in a " "const map literal.", correction: "Try removing the keyword 'const' from the map literal."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a value in a constant map // literal isn't a constant value. // // #### Example // // The following code produces this diagnostic: // // ```dart // var a = 'a'; // var m = const {0: [!a!]}; // ``` // // #### Common fixes // // If the map needs to be a constant map, then make the key a constant: // // ```dart // const a = 'a'; // var m = const {0: a}; // ``` // // If the map doesn't need to be a constant map, then remove the `const` // keyword: // // ```dart // var a = 'a'; // var m = {0: a}; // ``` static const CompileTimeErrorCode NON_CONSTANT_MAP_VALUE = const CompileTimeErrorCode('NON_CONSTANT_MAP_VALUE', "The values in a const map literal must be constant.", correction: "Try removing the keyword 'const' from the map literal.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when an if element or a spread // element in a constant map isn't a constant element. // // #### Example // // The following code produces this diagnostic because it is attempting to // spread a non-constant map: // // ```dart // var notConst = <int, int>{}; // var map = const <int, int>{...[!notConst!]}; // ``` // // Similarly, the following code produces this diagnostic because the // condition in the if element isn't a constant expression: // // ```dart // bool notConst = true; // var map = const <int, int>{if ([!notConst!]) 1 : 2}; // ``` // // #### Common fixes // // If the map needs to be a constant map, then make the elements constants. // In the spread example, you might do that by making the collection being // spread a constant: // // ```dart // const notConst = <int, int>{}; // var map = const <int, int>{...notConst}; // ``` // // If the map doesn't need to be a constant map, then remove the `const` // keyword: // // ```dart // bool notConst = true; // var map = <int, int>{if (notConst) 1 : 2}; // ``` static const CompileTimeErrorCode NON_CONSTANT_MAP_ELEMENT = const CompileTimeErrorCode('NON_CONSTANT_MAP_ELEMENT', "The elements in a const map literal must be constant.", correction: "Try removing the keyword 'const' from the map literal.", hasPublishedDocs: true); /** * 12.7 Maps: It is a compile time error if either a key or a value of an * entry in a constant map literal is not a compile-time constant. * * 12.1 Constants: A qualified reference to a static constant variable that is * not qualified by a deferred prefix. */ static const CompileTimeErrorCode NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as values in " "a const map literal.", correction: "Try removing the keyword 'const' from the map literal."); /** * 15 Metadata: Metadata consists of a series of annotations, each of which * begin with the character @, followed by a constant expression that must be * either a reference to a compile-time constant variable, or a call to a * constant constructor. * * "From deferred library" case is covered by * [CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY]. */ static const CompileTimeErrorCode NON_CONSTANT_ANNOTATION_CONSTRUCTOR = const CompileTimeErrorCode('NON_CONSTANT_ANNOTATION_CONSTRUCTOR', "Annotation creation can only call a const constructor."); static const CompileTimeErrorCode NON_CONSTANT_SET_ELEMENT = const CompileTimeErrorCode('NON_CONSTANT_SET_ELEMENT', "The values in a const set literal must be constants.", correction: "Try removing the keyword 'const' from the set literal."); /** * This error code is no longer being generated. It should be removed when the * reference to it in the linter has been removed and rolled into the SDK. */ @deprecated static const CompileTimeErrorCode NON_CONSTANT_VALUE_IN_INITIALIZER = const CompileTimeErrorCode( 'NON_CONSTANT_VALUE_IN_INITIALIZER', "Initializer expressions in constant constructors must be " "constants."); /** * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>. * Let <i>k</i> be a generative constructor. It is a compile-time error if * class <i>S</i> does not declare a generative constructor named <i>S</i> * (respectively <i>S.id</i>) */ static const CompileTimeErrorCode NON_GENERATIVE_CONSTRUCTOR = const CompileTimeErrorCode('NON_GENERATIVE_CONSTRUCTOR', "The generative constructor '{0}' expected, but factory found.", correction: "Try calling a different constructor in the superclass, or " "making the called constructor not be a factory constructor."); static const CompileTimeErrorCode NON_SYNC_FACTORY = const CompileTimeErrorCode('NON_SYNC_FACTORY', "Factory bodies can't use 'async', 'async*', or 'sync*'."); /** * It is an error if a potentially non-nullable local variable which has no * initializer expression and is not marked `late` is used before it is * definitely assigned. * * Parameters: * 0: the name of the variable that is invalid */ static const CompileTimeErrorCode NOT_ASSIGNED_POTENTIALLY_NON_NULLABLE_LOCAL_VARIABLE = const CompileTimeErrorCode( 'NOT_ASSIGNED_POTENTIALLY_NON_NULLABLE_LOCAL_VARIABLE', "The non-nullable local variable '{0}' must be assigned before it " "can be used.", correction: "Try giving it an initializer expression, " "or ensure that it is assigned on every execution path, " "or mark it 'late'."); /** * Parameters: * 0: the expected number of required arguments * 1: the actual number of positional arguments given */ // #### Description // // The analyzer produces this diagnostic when a method or function invocation // has fewer positional arguments than the number of required positional // parameters. // // #### Example // // The following code produces this diagnostic: // // ```dart // void f(int a, int b) {} // void g() { // f[!(0)!]; // } // ``` // // #### Common fixes // // Add arguments corresponding to the remaining parameters: // // ```dart // void f(int a, int b) {} // void g() { // f(0, 1); // } // ``` static const CompileTimeErrorCode NOT_ENOUGH_POSITIONAL_ARGUMENTS = const CompileTimeErrorCode('NOT_ENOUGH_POSITIONAL_ARGUMENTS', "{0} positional argument(s) expected, but {1} found.", correction: "Try adding the missing arguments.", hasPublishedDocs: true); @Deprecated('Use CompileTimeErrorCode NOT_ENOUGH_POSITIONAL_ARGUMENTS') static const CompileTimeErrorCode NOT_ENOUGH_REQUIRED_ARGUMENTS = NOT_ENOUGH_POSITIONAL_ARGUMENTS; /** * It is an error if an instance field with potentially non-nullable type has * no initializer expression and is not initialized in a constructor via an * initializing formal or an initializer list entry, unless the field is * marked with the `late` modifier. * * Parameters: * 0: the name of the field that is not initialized */ static const CompileTimeErrorCode NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD = const CompileTimeErrorCode( 'NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD', "Non-nullable instance field '{0}' must be initialized.", correction: "Try adding an initializer expression, " "or a generative constructor that initializes it, " "or mark it 'late'."); /** * It is an error if an instance field with potentially non-nullable type has * no initializer expression and is not initialized in a constructor via an * initializing formal or an initializer list entry, unless the field is * marked with the `late` modifier. * * Parameters: * * Parameters: * 0: the name of the field that is not initialized */ static const CompileTimeErrorCode NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD_CONSTRUCTOR = const CompileTimeErrorCode( 'NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD_CONSTRUCTOR', "Non-nullable instance field '{0}' must be initialized.", correction: "Try adding an initializer expression, " "or add a field initializer in this constructor, " "or mark it 'late'."); /** * It is an error if a static field or top-level variable with potentially * non-nullable type has no initializer expression. * * Parameters: * 0: the name of the variable that is invalid */ static const CompileTimeErrorCode NOT_INITIALIZED_NON_NULLABLE_VARIABLE = const CompileTimeErrorCode('NOT_INITIALIZED_NON_NULLABLE_VARIABLE', "The non-nullable variable '{0}' must be initialized.", correction: "Try adding an initializer expression."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the static type of the // expression of a spread element that appears in either a list literal or a // set literal doesn't implement the type `Iterable`. // // #### Example // // The following code generates this diagnostic: // // ```dart // var m = <String, int>{'a': 0, 'b': 1}; // var s = <String>{...[!m!]}; // ``` // // #### Common fixes // // The most common fix is to replace the expression with one that produces an // iterable object: // // ```dart // var m = <String, int>{'a': 0, 'b': 1}; // var s = <String>{...m.keys}; // ``` static const CompileTimeErrorCode NOT_ITERABLE_SPREAD = const CompileTimeErrorCode('NOT_ITERABLE_SPREAD', "Spread elements in list or set literals must implement 'Iterable'.", hasPublishedDocs: true); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the static type of the // expression of a spread element that appears in a map literal doesn't // implement the type `Map`. // // #### Example // // The following code produces this diagnostic: // // ```dart // var l = <String>['a', 'b']; // var m = <int, String>{...[!l!]}; // ``` // // #### Common fixes // // The most common fix is to replace the expression with one that produces a // map: // // ```dart // var l = <String>['a', 'b']; // var m = <int, String>{...l.asMap()}; // ``` static const CompileTimeErrorCode NOT_MAP_SPREAD = const CompileTimeErrorCode( 'NOT_MAP_SPREAD', "Spread elements in map literals must implement 'Map'.", hasPublishedDocs: true); static const CompileTimeErrorCode NOT_NULL_AWARE_NULL_SPREAD = const CompileTimeErrorCode( 'NOT_NULL_AWARE_NULL_SPREAD', "The Null typed expression can't be used with a non-null-aware " "spread."); /** * It is an error if the type `T` in the on-catch clause `on T catch` is * potentially nullable. */ static const CompileTimeErrorCode NULLABLE_TYPE_IN_CATCH_CLAUSE = const CompileTimeErrorCode( 'NULLABLE_TYPE_IN_CATCH_CLAUSE', "A nullable type can't be used in an 'on' clause because it isn't " "valid to throw 'null'.", correction: "Try removing the question mark."); /** * No parameters. */ /* #### Description // // The analyzer produces this diagnostic when a class declaration uses an // extends clause to specify a superclass, and the type that's specified is a // nullable type. // // The reason the supertype is a _type_ rather than a class name is to allow // you to control the signatures of the members to be inherited from the // supertype, such as by specifying type arguments. However, the nullability // of a type doesn't change the signatures of any members, so there isn't any // reason to allow the nullability to be specified when used in the extends // clause. // // #### Example // // The following code generates this diagnostic: // // ```dart // class Invalid extends [!Duration?!] {} // ``` // // #### Common fixes // // The most common fix is to remove the question mark: // // ```dart // class Invalid extends Duration {} // ``` */ static const CompileTimeErrorCode NULLABLE_TYPE_IN_EXTENDS_CLAUSE = const CompileTimeErrorCode('NULLABLE_TYPE_IN_EXTENDS_CLAUSE', "A class can't extend a nullable type.", correction: "Try removing the question mark."); /** * It is a compile-time error for a class to extend, implement, or mixin a * type of the form T? for any T. */ static const CompileTimeErrorCode NULLABLE_TYPE_IN_IMPLEMENTS_CLAUSE = const CompileTimeErrorCode('NULLABLE_TYPE_IN_IMPLEMENTS_CLAUSE', "A class or mixin can't implement a nullable type.", correction: "Try removing the question mark."); /** * It is a compile-time error for a class to extend, implement, or mixin a * type of the form T? for any T. */ static const CompileTimeErrorCode NULLABLE_TYPE_IN_ON_CLAUSE = const CompileTimeErrorCode('NULLABLE_TYPE_IN_ON_CLAUSE', "A mixin can't have a nullable type as a superclass constraint.", correction: "Try removing the question mark."); /** * It is a compile-time error for a class to extend, implement, or mixin a * type of the form T? for any T. */ static const CompileTimeErrorCode NULLABLE_TYPE_IN_WITH_CLAUSE = const CompileTimeErrorCode('NULLABLE_TYPE_IN_WITH_CLAUSE', "A class or mixin can't mix in a nullable type.", correction: "Try removing the question mark."); /** * 7.9 Superclasses: It is a compile-time error to specify an extends clause * for class Object. */ static const CompileTimeErrorCode OBJECT_CANNOT_EXTEND_ANOTHER_CLASS = const CompileTimeErrorCode('OBJECT_CANNOT_EXTEND_ANOTHER_CLASS', "The class 'Object' can't extend any other class."); /** * 10.10 Superinterfaces: It is a compile-time error if two elements in the * type list of the implements clause of a class `C` specifies the same * type `T`. * * Parameters: * 0: the name of the interface that is implemented more than once */ static const CompileTimeErrorCode ON_REPEATED = const CompileTimeErrorCode( 'ON_REPEATED', "'{0}' can only be used in super-class constraints only once.", correction: "Try removing all but one occurrence of the class name."); /** * 7.1.1 Operators: It is a compile-time error to declare an optional * parameter in an operator. */ static const CompileTimeErrorCode OPTIONAL_PARAMETER_IN_OPERATOR = const CompileTimeErrorCode('OPTIONAL_PARAMETER_IN_OPERATOR', "Optional parameters aren't allowed when defining an operator.", correction: "Try removing the optional parameters."); /** * 14.3 Parts: It is a compile time error if the contents of the URI are not a * valid part declaration. * * Parameters: * 0: the uri pointing to a non-library declaration */ static const CompileTimeErrorCode PART_OF_NON_PART = const CompileTimeErrorCode('PART_OF_NON_PART', "The included part '{0}' must have a part-of directive.", correction: "Try adding a part-of directive to '{0}'."); /** * 14.1 Imports: It is a compile-time error if the current library declares a * top-level member named <i>p</i>. */ static const CompileTimeErrorCode PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER = const CompileTimeErrorCode( 'PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER', "The name '{0}' is already used as an import prefix and can't be " "used to name a top-level element.", correction: "Try renaming either the top-level element or the prefix."); /** * 16.32 Identifier Reference: If d is a prefix p, a compile-time error * occurs unless the token immediately following d is '.'. */ static const CompileTimeErrorCode PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT = const CompileTimeErrorCode( 'PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT', "The name '{0}' refers to an import prefix, so it must be followed " "by '.'.", correction: "Try correcting the name to refer to something other than a " "prefix, or renaming the prefix."); /** * It is an error for a mixin to add a private name that conflicts with a * private name added by a superclass or another mixin. */ static const CompileTimeErrorCode PRIVATE_COLLISION_IN_MIXIN_APPLICATION = const CompileTimeErrorCode( 'PRIVATE_COLLISION_IN_MIXIN_APPLICATION', "The private name '{0}', defined by '{1}', " "conflicts with the same name defined by '{2}'.", correction: "Try removing '{1}' from the 'with' clause."); /** * 6.2.2 Optional Formals: It is a compile-time error if the name of a named * optional parameter begins with an '_' character. */ static const CompileTimeErrorCode PRIVATE_OPTIONAL_PARAMETER = const CompileTimeErrorCode('PRIVATE_OPTIONAL_PARAMETER', "Named optional parameters can't start with an underscore."); /** * 12.1 Constants: It is a compile-time error if the value of a compile-time * constant expression depends on itself. */ static const CompileTimeErrorCode RECURSIVE_COMPILE_TIME_CONSTANT = const CompileTimeErrorCode('RECURSIVE_COMPILE_TIME_CONSTANT', "Compile-time constant expression depends on itself."); /** * 7.6.1 Generative Constructors: A generative constructor may be redirecting, * in which case its only action is to invoke another generative constructor. * * TODO(scheglov) review this later, there are no explicit "it is a * compile-time error" in specification. But it was added to the co19 and * there is same error for factories. * * https://code.google.com/p/dart/issues/detail?id=954 */ static const CompileTimeErrorCode RECURSIVE_CONSTRUCTOR_REDIRECT = const CompileTimeErrorCode('RECURSIVE_CONSTRUCTOR_REDIRECT', "Cycle in redirecting generative constructors."); /** * 7.6.2 Factories: It is a compile-time error if a redirecting factory * constructor redirects to itself, either directly or indirectly via a * sequence of redirections. */ static const CompileTimeErrorCode RECURSIVE_FACTORY_REDIRECT = const CompileTimeErrorCode('RECURSIVE_FACTORY_REDIRECT', "Cycle in redirecting factory constructors."); /** * 7.10 Superinterfaces: It is a compile-time error if the interface of a * class <i>C</i> is a superinterface of itself. * * 8.1 Superinterfaces: It is a compile-time error if an interface is a * superinterface of itself. * * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a * superclass of itself. * * Parameters: * 0: the name of the class that implements itself recursively * 1: a string representation of the implements loop */ static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE = const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE', "'{0}' can't be a superinterface of itself: {1}."); /** * 7.10 Superinterfaces: It is a compile-time error if the interface of a * class <i>C</i> is a superinterface of itself. * * 8.1 Superinterfaces: It is a compile-time error if an interface is a * superinterface of itself. * * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a * superclass of itself. * * Parameters: * 0: the name of the class that implements itself recursively */ static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE_EXTENDS = const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE_EXTENDS', "'{0}' can't extend itself."); /** * 7.10 Superinterfaces: It is a compile-time error if the interface of a * class <i>C</i> is a superinterface of itself. * * 8.1 Superinterfaces: It is a compile-time error if an interface is a * superinterface of itself. * * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a * superclass of itself. * * Parameters: * 0: the name of the class that implements itself recursively */ static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE_IMPLEMENTS = const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE_IMPLEMENTS', "'{0}' can't implement itself."); /** * Parameters: * 0: the name of the mixin that constraints itself recursively */ static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE_ON = const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE_ON', "'{0}' can't use itself as a superclass constraint."); /** * 7.10 Superinterfaces: It is a compile-time error if the interface of a * class <i>C</i> is a superinterface of itself. * * 8.1 Superinterfaces: It is a compile-time error if an interface is a * superinterface of itself. * * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a * superclass of itself. * * Parameters: * 0: the name of the class that implements itself recursively */ static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE_WITH = const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE_WITH', "'{0}' can't use itself as a mixin."); /** * 7.6.1 Generative constructors: A generative constructor may be * <i>redirecting</i>, in which case its only action is to invoke another * generative constructor. */ static const CompileTimeErrorCode REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR = const CompileTimeErrorCode('REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR', "The constructor '{0}' couldn't be found in '{1}'.", correction: "Try redirecting to a different constructor, or " "defining the constructor named '{0}'."); /** * 7.6.1 Generative constructors: A generative constructor may be * <i>redirecting</i>, in which case its only action is to invoke another * generative constructor. */ static const CompileTimeErrorCode REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR = const CompileTimeErrorCode( 'REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR', "Generative constructor can't redirect to a factory constructor.", correction: "Try redirecting to a different constructor."); /** * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with * the const modifier but <i>k'</i> is not a constant constructor. */ static const CompileTimeErrorCode REDIRECT_TO_MISSING_CONSTRUCTOR = const CompileTimeErrorCode('REDIRECT_TO_MISSING_CONSTRUCTOR', "The constructor '{0}' couldn't be found in '{1}'.", correction: "Try redirecting to a different constructor, or " "define the constructor named '{0}'."); /** * Parameters: * 0: the name of the non-type referenced in the redirect */ // #### Description // // One way to implement a factory constructor is to redirect to another // constructor by referencing the name of the constructor. The analyzer // produces this diagnostic when the redirect is to something other than a // constructor. // // #### Example // // The following code produces this diagnostic because `f` is a function: // // ```dart // C f() => null; // // class C { // factory C() = [!f!]; // } // ``` // // #### Common fixes // // If the constructor isn't defined, then either define it or replace it with // a constructor that is defined. // // If the constructor is defined but the class that defines it isn't visible, // then you probably need to add an import. // // If you're trying to return the value returned by a function, then rewrite // the constructor to return the value from the constructor's body: // // ```dart // C f() => null; // // class C { // factory C() => f(); // } // ``` static const CompileTimeErrorCode REDIRECT_TO_NON_CLASS = const CompileTimeErrorCode( 'REDIRECT_TO_NON_CLASS', "The name '{0}' isn't a type and can't be used in a redirected " "constructor.", correction: "Try redirecting to a different constructor.", hasPublishedDocs: true); /** * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with * the const modifier but <i>k'</i> is not a constant constructor. */ static const CompileTimeErrorCode REDIRECT_TO_NON_CONST_CONSTRUCTOR = const CompileTimeErrorCode( 'REDIRECT_TO_NON_CONST_CONSTRUCTOR', "Constant factory constructor can't delegate to a non-constant " "constructor.", correction: "Try redirecting to a different constructor."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a variable is referenced before // it’s declared. In Dart, variables are visible everywhere in the block in // which they are declared, but can only be referenced after they are // declared. // // The analyzer also produces a context message that indicates where the // declaration is located. // // #### Example // // The following code produces this diagnostic: // // ```dart // void f() { // print([!i!]); // int i = 5; // } // ``` // // #### Common fixes // // If you intended to reference the local variable, move the declaration // before the first reference: // // ```dart // void f() { // int i = 5; // print(i); // } // ``` // // If you intended to reference a name from an outer scope, such as a // parameter, instance field or top-level variable, then rename the local // declaration so that it doesn't hide the outer variable. // // ```dart // void f(int i) { // print(i); // int x = 5; // print(x); // } // ``` static const CompileTimeErrorCode REFERENCED_BEFORE_DECLARATION = const CompileTimeErrorCode('REFERENCED_BEFORE_DECLARATION', "Local variable '{0}' can't be referenced before it is declared.", correction: "Try moving the declaration to before the first use, or " "renaming the local variable so that it doesn't hide a name from " "an enclosing scope.", hasPublishedDocs: true); /** * 12.8.1 Rethrow: It is a compile-time error if an expression of the form * <i>rethrow;</i> is not enclosed within a on-catch clause. */ static const CompileTimeErrorCode RETHROW_OUTSIDE_CATCH = const CompileTimeErrorCode( 'RETHROW_OUTSIDE_CATCH', "Rethrow must be inside of catch clause.", correction: "Try moving the expression into a catch clause, or using a " "'throw' expression."); /** * 13.12 Return: It is a compile-time error if a return statement of the form * <i>return e;</i> appears in a generative constructor. */ static const CompileTimeErrorCode RETURN_IN_GENERATIVE_CONSTRUCTOR = const CompileTimeErrorCode('RETURN_IN_GENERATIVE_CONSTRUCTOR', "Constructors can't return values.", correction: "Try removing the return statement or using a factory " "constructor."); /** * 13.12 Return: It is a compile-time error if a return statement of the form * <i>return e;</i> appears in a generator function. */ static const CompileTimeErrorCode RETURN_IN_GENERATOR = const CompileTimeErrorCode( 'RETURN_IN_GENERATOR', "Can't return a value from a generator function (using the '{0}' " "modifier).", correction: "Try removing the value, replacing 'return' with 'yield' or " "changing the method body modifier."); static const CompileTimeErrorCode SET_ELEMENT_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'SET_ELEMENT_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be used as values in " "a const set.", correction: "Try making the deferred import non-deferred."); /** * 14.1 Imports: It is a compile-time error if a prefix used in a deferred * import is used in another import clause. */ static const CompileTimeErrorCode SHARED_DEFERRED_PREFIX = const CompileTimeErrorCode( 'SHARED_DEFERRED_PREFIX', "The prefix of a deferred import can't be used in other import " "directives.", correction: "Try renaming one of the prefixes."); static const CompileTimeErrorCode SPREAD_EXPRESSION_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode( 'SPREAD_EXPRESSION_FROM_DEFERRED_LIBRARY', "Constant values from a deferred library can't be spread into a " "const literal.", correction: "Try making the deferred import non-deferred."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a member declared inside an // extension uses the `super` keyword . Extensions aren't classes and don't // have superclasses, so the `super` keyword serves no purpose. // // #### Example // // The following code produces this diagnostic: // // ```dart // extension E on Object { // String get displayString => [!super!].toString(); // } // ``` // // #### Common fixes // // Remove the `super` keyword : // // ```dart // extension E on Object { // String get displayString => toString(); // } // ``` static const CompileTimeErrorCode SUPER_IN_EXTENSION = const CompileTimeErrorCode( 'SUPER_IN_EXTENSION', "The 'super' keyword can't be used in an extension because an " "extension doesn't have a superclass.", hasPublishedDocs: true); /** * 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form * <i>super.m(a<sub>1</sub>, &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: * a<sub>n+1</sub>, &hellip; x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. It is a * compile-time error if a super method invocation occurs in a top-level * function or variable initializer, in an instance variable initializer or * initializer list, in class Object, in a factory constructor, or in a static * method or variable initializer. */ static const CompileTimeErrorCode SUPER_IN_INVALID_CONTEXT = const CompileTimeErrorCode('SUPER_IN_INVALID_CONTEXT', "Invalid context for 'super' invocation."); /** * 7.6.1 Generative Constructors: A generative constructor may be redirecting, * in which case its only action is to invoke another generative constructor. */ static const CompileTimeErrorCode SUPER_IN_REDIRECTING_CONSTRUCTOR = const CompileTimeErrorCode('SUPER_IN_REDIRECTING_CONSTRUCTOR', "The redirecting constructor can't have a 'super' initializer."); /** * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It * is a compile-time error if a generative constructor of class Object * includes a superinitializer. */ static const CompileTimeErrorCode SUPER_INITIALIZER_IN_OBJECT = const CompileTimeErrorCode('SUPER_INITIALIZER_IN_OBJECT', "The class 'Object' can't invoke a constructor from a superclass."); /** * Parameters: * 0: the name of the type used in the instance creation that should be * limited by the bound as specified in the class declaration * 1: the name of the bounding type */ // #### Description // // The analyzer produces this diagnostic when a type argument isn't the same // as or a subclass of the bounds of the corresponding type parameter. // // #### Example // // The following code produces this diagnostic: // // ```dart // class A<E extends num> {} // // var a = A<[!String!]>(); // ``` // // #### Common fixes // // Change the type argument to be a subclass of the bounds: // // ```dart // class A<E extends num> {} // // var a = A<int>(); // ``` static const CompileTimeErrorCode TYPE_ARGUMENT_NOT_MATCHING_BOUNDS = const CompileTimeErrorCode( 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS', "'{0}' doesn't extend '{1}'.", correction: "Try using a type that is or is a subclass of '{1}'.", hasPublishedDocs: true); /** * 15.3.1 Typedef: Any self reference, either directly, or recursively via * another typedef, is a compile time error. */ static const CompileTimeErrorCode TYPE_ALIAS_CANNOT_REFERENCE_ITSELF = const CompileTimeErrorCode( 'TYPE_ALIAS_CANNOT_REFERENCE_ITSELF', "Typedefs can't reference themselves directly or recursively via " "another typedef."); static const CompileTimeErrorCode TYPE_PARAMETER_ON_CONSTRUCTOR = const CompileTimeErrorCode('TYPE_PARAMETER_ON_CONSTRUCTOR', "Constructors can't have type parameters.", correction: "Try removing the type parameters."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a name that isn't defined is // used as an annotation. // // #### Example // // The following code produces this diagnostic: // // ```dart // [!@undefined!] // void f() {} // ``` // // #### Common fixes // // If the name is correct, but it isn’t declared yet, then declare the name as // a constant value: // // ```dart // const undefined = 'undefined'; // // @undefined // void f() {} // ``` // // If the name is wrong, replace the name with the name of a valid constant: // // ```dart // @deprecated // void f() {} // ``` // // Otherwise, remove the annotation. static const CompileTimeErrorCode UNDEFINED_ANNOTATION = const CompileTimeErrorCode( 'UNDEFINED_ANNOTATION', "Undefined name '{0}' used as an annotation.", correction: "Try defining the name or importing it from another library.", hasPublishedDocs: true, isUnresolvedIdentifier: true); /** * Parameters: * 0: the name of the undefined class */ // #### Description // // The analyzer produces this diagnostic when it encounters an identifier that // appears to be the name of a class but either isn't defined or isn't visible // in the scope in which it's being referenced. // // #### Example // // The following code produces this diagnostic: // // ```dart // class Point {} // // void f([!Piont!] p) {} // ``` // // #### Common fixes // // If the identifier isn't defined, then either define it or replace it with // the name of a class that is defined. The example above can be corrected by // fixing the spelling of the class: // // ```dart // class Point {} // // void f(Point p) {} // ``` // // If the class is defined but isn't visible, then you probably need to add an // import. static const CompileTimeErrorCode UNDEFINED_CLASS = const CompileTimeErrorCode('UNDEFINED_CLASS', "Undefined class '{0}'.", correction: "Try changing the name to the name of an existing class, or " "creating a class with the name '{0}'.", hasPublishedDocs: true, isUnresolvedIdentifier: true); /** * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>. * Let <i>k</i> be a generative constructor. It is a compile-time error if * class <i>S</i> does not declare a generative constructor named <i>S</i> * (respectively <i>S.id</i>) * * Parameters: * 0: the name of the superclass that does not define the invoked constructor * 1: the name of the constructor being invoked */ static const CompileTimeErrorCode UNDEFINED_CONSTRUCTOR_IN_INITIALIZER = const CompileTimeErrorCode('UNDEFINED_CONSTRUCTOR_IN_INITIALIZER', "The class '{0}' doesn't have a constructor named '{1}'.", correction: "Try defining a constructor named '{1}' in '{0}', or " "invoking a different constructor."); /** * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>. * Let <i>k</i> be a generative constructor. It is a compile-time error if * class <i>S</i> does not declare a generative constructor named <i>S</i> * (respectively <i>S.id</i>) * * Parameters: * 0: the name of the superclass that does not define the invoked constructor */ static const CompileTimeErrorCode UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT = const CompileTimeErrorCode( 'UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT', "The class '{0}' doesn't have an unnamed constructor.", correction: "Try defining an unnamed constructor in '{0}', or " "invoking a different constructor."); /** * Parameters: * 0: the name of the getter that is undefined * 1: the name of the extension that was explicitly specified */ // #### Description // // The analyzer produces this diagnostic when an extension override is used to // invoke a getter, but the getter isn't defined by the specified extension. // The analyzer also produces this diagnostic when a static getter is // referenced but isn't defined by the specified extension. // // #### Example // // The following code produces this diagnostic because the extension `E` // doesn't declare an instance getter named `b`: // // ```dart // extension E on String { // String get a => 'a'; // } // // extension F on String { // String get b => 'b'; // } // // void f() { // E('c').[!b!]; // } // ``` // // The following code produces this diagnostic because the extension `E` // doesn't declare a static getter named `a`: // // ```dart // extension E on String {} // // var x = E.[!a!]; // ``` // // #### Common fixes // // If the name of the getter is incorrect, then change it to the name of an // existing getter: // // ```dart // extension E on String { // String get a => 'a'; // } // // extension F on String { // String get b => 'b'; // } // // void f() { // E('c').a; // } // ``` // // If the name of the getter is correct but the name of the extension is // wrong, then change the name of the extension to the correct name: // // ```dart // extension E on String { // String get a => 'a'; // } // // extension F on String { // String get b => 'b'; // } // // void f() { // F('c').b; // } // ``` // // If the name of the getter and extension are both correct, but the getter // isn't defined, then define the getter: // // ```dart // extension E on String { // String get a => 'a'; // String get b => 'z'; // } // // extension F on String { // String get b => 'b'; // } // // void f() { // E('c').b; // } // ``` static const CompileTimeErrorCode UNDEFINED_EXTENSION_GETTER = const CompileTimeErrorCode('UNDEFINED_EXTENSION_GETTER', "The getter '{0}' isn't defined for the extension '{1}'.", correction: "Try correcting the name to the name of an existing getter, or " "defining a getter named '{0}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the method that is undefined * 1: the name of the extension that was explicitly specified */ // #### Description // // The analyzer produces this diagnostic when an extension override is used to // invoke a method, but the method isn't defined by the specified extension. // The analyzer also produces this diagnostic when a static method is // referenced but isn't defined by the specified extension. // // #### Example // // The following code produces this diagnostic because the extension `E` // doesn't declare an instance method named `b`: // // ```dart // extension E on String { // String a() => 'a'; // } // // extension F on String { // String b() => 'b'; // } // // void f() { // E('c').[!b!](); // } // ``` // // The following code produces this diagnostic because the extension `E` // doesn't declare a static method named `a`: // // ```dart // extension E on String {} // // var x = E.[!a!](); // ``` // // #### Common fixes // // If the name of the method is incorrect, then change it to the name of an // existing method: // // ```dart // extension E on String { // String a() => 'a'; // } // // extension F on String { // String b() => 'b'; // } // // void f() { // E('c').a(); // } // ``` // // If the name of the method is correct, but the name of the extension is // wrong, then change the name of the extension to the correct name: // // ```dart // extension E on String { // String a() => 'a'; // } // // extension F on String { // String b() => 'b'; // } // // void f() { // F('c').b(); // } // ``` // // If the name of the method and extension are both correct, but the method // isn't defined, then define the method: // // ```dart // extension E on String { // String a() => 'a'; // String b() => 'z'; // } // // extension F on String { // String b() => 'b'; // } // // void f() { // E('c').b(); // } // ``` static const CompileTimeErrorCode UNDEFINED_EXTENSION_METHOD = const CompileTimeErrorCode('UNDEFINED_EXTENSION_METHOD', "The method '{0}' isn't defined for the extension '{1}'.", correction: "Try correcting the name to the name of an existing method, or " "defining a method named '{0}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the operator that is undefined * 1: the name of the extension that was explicitly specified */ static const CompileTimeErrorCode UNDEFINED_EXTENSION_OPERATOR = const CompileTimeErrorCode('UNDEFINED_EXTENSION_OPERATOR', "The operator '{0}' isn't defined for the extension '{1}'.", correction: "Try defining the operator '{0}'."); /** * Parameters: * 0: the name of the setter that is undefined * 1: the name of the extension that was explicitly specified */ // #### Description // // The analyzer produces this diagnostic when an extension override is used to // invoke a setter, but the setter isn't defined by the specified extension. // The analyzer also produces this diagnostic when a static setter is // referenced but isn't defined by the specified extension. // // #### Example // // The following code produces this diagnostic because the extension `E` // doesn't declare an instance setter named `b`: // // ```dart // extension E on String { // set a(String v) {} // } // // extension F on String { // set b(String v) {} // } // // void f() { // E('c').[!b!] = 'd'; // } // ``` // // The following code produces this diagnostic because the extension `E` // doesn't declare a static setter named `a`: // // ```dart // extension E on String {} // // void f() { // E.[!a!] = 3; // } // ``` // // #### Common fixes // // If the name of the setter is incorrect, then change it to the name of an // existing setter: // // ```dart // extension E on String { // set a(String v) {} // } // // extension F on String { // set b(String v) {} // } // // void f() { // E('c').a = 'd'; // } // ``` // // If the name of the setter is correct, but the name of the extension is // wrong, then change the name of the extension to the correct name: // // ```dart // extension E on String { // set a(String v) {} // } // // extension F on String { // set b(String v) {} // } // // void f() { // F('c').b = 'd'; // } // ``` // // If the name of the setter and extension are both correct, but the setter // isn't defined, then define the setter: // // ```dart // extension E on String { // set a(String v) {} // set b(String v) {} // } // // extension F on String { // set b(String v) {} // } // // void f() { // E('c').b = 'd'; // } // ``` static const CompileTimeErrorCode UNDEFINED_EXTENSION_SETTER = const CompileTimeErrorCode('UNDEFINED_EXTENSION_SETTER', "The setter '{0}' isn't defined for the extension '{1}'.", correction: "Try correcting the name to the name of an existing setter, or " "defining a setter named '{0}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the requested named parameter */ // #### Description // // The analyzer produces this diagnostic when a method or function invocation // has a named argument, but the method or function being invoked doesn't // define a parameter with the same name. // // #### Example // // The following code produces this diagnostic: // // ```dart // class C { // m({int b}) {} // } // // void f(C c) { // c.m([!a!]: 1); // } // ``` // // #### Common fixes // // If the argument name is mistyped, then replace it with the correct name. // The example above can be fixed by changing `a` to `b`: // // ```dart // class C { // m({int b}) {} // } // // void f(C c) { // c.m(b: 1); // } // ``` // // If a subclass adds a parameter with the name in question, then cast the // target to the subclass: // // ```dart // class C { // m({int b}) {} // } // // class D extends C { // m({int a, int b}) {} // } // // void f(C c) { // (c as D).m(a: 1); // } // ``` // // If the parameter should be added to the function, then add it: // // ```dart // class C { // m({int a, int b}) {} // } // // void f(C c) { // c.m(a: 1); // } // ``` static const CompileTimeErrorCode UNDEFINED_NAMED_PARAMETER = const CompileTimeErrorCode('UNDEFINED_NAMED_PARAMETER', "The named parameter '{0}' isn't defined.", correction: "Try correcting the name to an existing named parameter's name, " "or defining a named parameter with the name '{0}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the defining type */ // #### Description // // The analyzer produces this diagnostic when an undefined name is found, and // the name is the same as a static member of the extended type or one of its // superclasses. // // #### Example // // The following code produces this diagnostic: // // ```dart // class C { // static void m() {} // } // // extension E on C { // void f() { // [!m!](); // } // } // ``` // // #### Common fixes // // If you're trying to reference a static member that's declared outside the // extension, then add the name of the class or extension before the reference // to the member: // // ```dart // class C { // static void m() {} // } // // extension E on C { // void f() { // C.m(); // } // } // ``` // // If you're referencing a member that isn't declared yet, add a declaration: // // ```dart // class C { // static void m() {} // } // // extension E on C { // void f() { // m(); // } // // void m() {} // } // ``` static const CompileTimeErrorCode UNQUALIFIED_REFERENCE_TO_STATIC_MEMBER_OF_EXTENDED_TYPE = const CompileTimeErrorCode( 'UNQUALIFIED_REFERENCE_TO_STATIC_MEMBER_OF_EXTENDED_TYPE', "Static members from the extended type or one of its superclasses " "must be qualified by the name of the defining type.", correction: "Try adding '{0}.' before the name.", hasPublishedDocs: true); /** * Parameters: * 0: the URI pointing to a non-existent file */ // #### Description // // The analyzer produces this diagnostic when an import, export, or part // directive is found where the URI refers to a file that doesn't exist. // // #### Example // // If the file `lib.dart` doesn't exist, the following code produces this // diagnostic: // // ```dart // import [!'lib.dart'!]; // ``` // // #### Common fixes // // If the URI was mistyped or invalid, then correct the URI. // // If the URI is correct, then create the file. static const CompileTimeErrorCode URI_DOES_NOT_EXIST = const CompileTimeErrorCode( 'URI_DOES_NOT_EXIST', "Target of URI doesn't exist: '{0}'.", correction: "Try creating the file referenced by the URI, or " "Try using a URI for a file that does exist.", hasPublishedDocs: true); /** * Parameters: * 0: the URI pointing to a non-existent file */ // #### Description // // The analyzer produces this diagnostic when an import, export, or part // directive is found where the URI refers to a file that doesn't exist and // the name of the file ends with a pattern that's commonly produced by code // generators, such as one of the following: // - `.g.dart` // - `.pb.dart` // - `.pbenum.dart` // - `.pbserver.dart` // - `.pbjson.dart` // - `.template.dart` // // #### Example // // If the file `lib.g.dart` doesn't exist, the following code produces this // diagnostic: // // ```dart // import [!'lib.g.dart'!]; // ``` // // #### Common fixes // // If the file is a generated file, then run the generator that generates the // file. // // If the file isn't a generated file, then check the spelling of the URI or // create the file. static const CompileTimeErrorCode URI_HAS_NOT_BEEN_GENERATED = const CompileTimeErrorCode('URI_HAS_NOT_BEEN_GENERATED', "Target of URI hasn't been generated: '{0}'.", correction: "Try running the generator that will generate the file " "referenced by the URI.", hasPublishedDocs: true); /** * 14.1 Imports: It is a compile-time error if <i>x</i> is not a compile-time * constant, or if <i>x</i> involves string interpolation. * * 14.3 Parts: It is a compile-time error if <i>s</i> is not a compile-time * constant, or if <i>s</i> involves string interpolation. * * 14.5 URIs: It is a compile-time error if the string literal <i>x</i> that * describes a URI is not a compile-time constant, or if <i>x</i> involves * string interpolation. */ static const CompileTimeErrorCode URI_WITH_INTERPOLATION = const CompileTimeErrorCode( 'URI_WITH_INTERPOLATION', "URIs can't use string interpolation."); /** * 7.1.1 Operators: It is a compile-time error if the arity of the * user-declared operator []= is not 2. It is a compile time error if the * arity of a user-declared operator with one of the names: &lt;, &gt;, &lt;=, * &gt;=, ==, +, /, ~/, *, %, |, ^, &, &lt;&lt;, &gt;&gt;, [] is not 1. It is * a compile time error if the arity of the user-declared operator - is not 0 * or 1. It is a compile time error if the arity of the user-declared operator * ~ is not 0. * * Parameters: * 0: the name of the declared operator * 1: the number of parameters expected * 2: the number of parameters found in the operator declaration */ static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR = const CompileTimeErrorCode( 'WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR', "Operator '{0}' should declare exactly {1} parameter(s), but {2} " "found."); /** * 7.1.1 Operators: It is a compile time error if the arity of the * user-declared operator - is not 0 or 1. * * Parameters: * 0: the number of parameters found in the operator declaration */ static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS = const CompileTimeErrorCode( 'WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS', "Operator '-' should declare 0 or 1 parameter, but {0} found."); /** * 7.3 Setters: It is a compile-time error if a setter's formal parameter list * does not include exactly one required formal parameter <i>p</i>. */ static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER = const CompileTimeErrorCode('WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER', "Setters should declare exactly one required parameter."); /** * Let `C` be a generic class that declares a formal type parameter `X`, and * assume that `T` is a direct superinterface of `C`. It is a compile-time * error if `X` occurs contravariantly or invariantly in `T`. */ static const CompileTimeErrorCode WRONG_TYPE_PARAMETER_VARIANCE_IN_SUPERINTERFACE = const CompileTimeErrorCode( 'WRONG_TYPE_PARAMETER_VARIANCE_IN_SUPERINTERFACE', "'{0}' can't be used contravariantly or invariantly in '{1}'.", correction: "Try not using class type parameters in types of formal " "parameters of function types.", ); /** * ?? Yield: It is a compile-time error if a yield statement appears in a * function that is not a generator function. */ static const CompileTimeErrorCode YIELD_EACH_IN_NON_GENERATOR = const CompileTimeErrorCode( 'YIELD_EACH_IN_NON_GENERATOR', "Yield-each statements must be in a generator function " "(one marked with either 'async*' or 'sync*').", correction: "Try adding 'async*' or 'sync*' to the enclosing function."); /** * ?? Yield: It is a compile-time error if a yield statement appears in a * function that is not a generator function. */ static const CompileTimeErrorCode YIELD_IN_NON_GENERATOR = const CompileTimeErrorCode( 'YIELD_IN_NON_GENERATOR', "Yield statements must be in a generator function " "(one marked with either 'async*' or 'sync*').", correction: "Try adding 'async*' or 'sync*' to the enclosing function."); /** * Initialize a newly created error code to have the given [name]. The message * associated with the error will be created from the given [message] * template. The correction associated with the error will be created from the * given [correction] template. */ const CompileTimeErrorCode(String name, String message, {String correction, bool hasPublishedDocs, bool isUnresolvedIdentifier: false}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs, isUnresolvedIdentifier: isUnresolvedIdentifier); @override ErrorSeverity get errorSeverity => ErrorType.COMPILE_TIME_ERROR.severity; @override ErrorType get type => ErrorType.COMPILE_TIME_ERROR; } /** * The error codes used for static type warnings. The convention for this class * is for the name of the error code to indicate the problem that caused the * error to be generated and for the error message to explain what is wrong and, * when appropriate, how the problem can be corrected. */ class StaticTypeWarningCode extends AnalyzerErrorCode { /** * 12.7 Lists: A fresh instance (7.6.1) <i>a</i>, of size <i>n</i>, whose * class implements the built-in class <i>List&lt;E></i> is allocated. * * Parameters: * 0: the number of provided type arguments */ static const StaticTypeWarningCode EXPECTED_ONE_LIST_TYPE_ARGUMENTS = const StaticTypeWarningCode( 'EXPECTED_ONE_LIST_TYPE_ARGUMENTS', "List literals require exactly one type argument or none, " "but {0} found.", correction: "Try adjusting the number of type arguments."); /** * Parameters: * 0: the number of provided type arguments */ static const StaticTypeWarningCode EXPECTED_ONE_SET_TYPE_ARGUMENTS = const StaticTypeWarningCode( 'EXPECTED_ONE_SET_TYPE_ARGUMENTS', "Set literals require exactly one type argument or none, " "but {0} found.", correction: "Try adjusting the number of type arguments."); /** * 12.8 Maps: A fresh instance (7.6.1) <i>m</i>, of size <i>n</i>, whose class * implements the built-in class <i>Map&lt;K, V></i> is allocated. * * Parameters: * 0: the number of provided type arguments */ static const StaticTypeWarningCode EXPECTED_TWO_MAP_TYPE_ARGUMENTS = const StaticTypeWarningCode( 'EXPECTED_TWO_MAP_TYPE_ARGUMENTS', "Map literals require exactly two type arguments or none, " "but {0} found.", correction: "Try adjusting the number of type arguments."); /** * 9 Functions: It is a static warning if the declared return type of a * function marked async* may not be assigned to Stream. */ static const StaticTypeWarningCode ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE = const StaticTypeWarningCode( 'ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE', "Functions marked 'async*' must have a return type assignable to " "'Stream'.", correction: "Try fixing the return type of the function, or " "removing the modifier 'async*' from the function body."); /** * 9 Functions: It is a static warning if the declared return type of a * function marked async may not be assigned to Future. */ static const StaticTypeWarningCode ILLEGAL_ASYNC_RETURN_TYPE = const StaticTypeWarningCode( 'ILLEGAL_ASYNC_RETURN_TYPE', "Functions marked 'async' must have a return type assignable to " "'Future'.", correction: "Try fixing the return type of the function, or " "removing the modifier 'async' from the function body."); /** * 9 Functions: It is a static warning if the declared return type of a * function marked sync* may not be assigned to Iterable. */ static const StaticTypeWarningCode ILLEGAL_SYNC_GENERATOR_RETURN_TYPE = const StaticTypeWarningCode( 'ILLEGAL_SYNC_GENERATOR_RETURN_TYPE', "Functions marked 'sync*' must have a return type assignable to " "'Iterable'.", correction: "Try fixing the return type of the function, or " "removing the modifier 'sync*' from the function body."); /** * 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does * not have an accessible (3.2) instance member named <i>m</i>. * * Parameters: * 0: the name of the static member * 1: the kind of the static member (field, getter, setter, or method) * 2: the name of the defining class * * See [UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER]. */ static const StaticTypeWarningCode INSTANCE_ACCESS_TO_STATIC_MEMBER = const StaticTypeWarningCode('INSTANCE_ACCESS_TO_STATIC_MEMBER', "Static {1} '{0}' can't be accessed through an instance.", correction: "Try using the class '{2}' to access the {1}."); /** * Parameters: * 0: the name of the right hand side type * 1: the name of the left hand side type */ // #### Description // // The analyzer produces this diagnostic when the static type of an expression // that is assigned to a variable isn't assignable to the type of the // variable. // // #### Example // // The following code produces this diagnostic because the type of the // initializer (`int`) isn't assignable to the type of the variable // (`String`): // // ```dart // int i = 0; // String s = [!i!]; // ``` // // #### Common fixes // // If the value being assigned is always assignable at runtime, even though // the static types don't reflect that, then add an explicit cast. // // Otherwise, change the value being assigned so that it has the expected // type. In the previous example, this might look like: // // ```dart // int i = 0; // String s = i.toString(); // ``` // // If you can’t change the value, then change the type of the variable to be // compatible with the type of the value being assigned: // // ```dart // int i = 0; // int s = i; // ``` static const StaticTypeWarningCode INVALID_ASSIGNMENT = const StaticTypeWarningCode( 'INVALID_ASSIGNMENT', "A value of type '{0}' can't be assigned to a variable of type " "'{1}'.", correction: "Try changing the type of the variable, or " "casting the right-hand type to '{1}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the identifier that is not a function type */ // #### Description // // The analyzer produces this diagnostic when it finds a function invocation, // but the name of the function being invoked is defined to be something other // than a function. // // #### Example // // The following code produces this diagnostic: // // ```dart // typedef Binary = int Function(int, int); // // int f() { // return [!Binary!](1, 2); // } // ``` // // #### Common fixes // // Replace the name with the name of a function. static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION = const StaticTypeWarningCode( 'INVOCATION_OF_NON_FUNCTION', "'{0}' isn't a function.", // TODO(brianwilkerson) Split this error code so that we can provide // better error and correction messages. correction: "Try correcting the name to match an existing function, or " "define a method or function named '{0}'.", hasPublishedDocs: true); /** * 12.14.4 Function Expression Invocation: A function expression invocation * <i>i</i> has the form <i>e<sub>f</sub>(a<sub>1</sub>, &hellip;, * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, &hellip;, x<sub>n+k</sub>: * a<sub>n+k</sub>)</i>, where <i>e<sub>f</sub></i> is an expression. * * It is a static type warning if the static type <i>F</i> of * <i>e<sub>f</sub></i> may not be assigned to a function type. */ static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION_EXPRESSION = const StaticTypeWarningCode( 'INVOCATION_OF_NON_FUNCTION_EXPRESSION', "The expression doesn't evaluate to a function, so it can't be " "invoked."); /** * 12.20 Conditional: It is a static type warning if the type of * <i>e<sub>1</sub></i> may not be assigned to bool. * * 13.5 If: It is a static type warning if the type of the expression <i>b</i> * may not be assigned to bool. * * 13.7 While: It is a static type warning if the type of <i>e</i> may not be * assigned to bool. * * 13.8 Do: It is a static type warning if the type of <i>e</i> cannot be * assigned to bool. */ static const StaticTypeWarningCode NON_BOOL_CONDITION = const StaticTypeWarningCode( 'NON_BOOL_CONDITION', "Conditions must have a static type of 'bool'.", correction: "Try changing the condition."); /** * 17.17 Assert: It is a static type warning if the type of <i>e</i> may not * be assigned to bool. */ static const StaticTypeWarningCode NON_BOOL_EXPRESSION = const StaticTypeWarningCode('NON_BOOL_EXPRESSION', "The expression in an assert must be of type 'bool'.", correction: "Try changing the expression."); /** * 12.28 Unary Expressions: The expression !<i>e</i> is equivalent to the * expression <i>e</i>?<b>false<b> : <b>true</b>. * * 12.20 Conditional: It is a static type warning if the type of * <i>e<sub>1</sub></i> may not be assigned to bool. */ static const StaticTypeWarningCode NON_BOOL_NEGATION_EXPRESSION = const StaticTypeWarningCode('NON_BOOL_NEGATION_EXPRESSION', "Negation argument must have a static type of 'bool'.", correction: "Try changing the argument to the '!' operator."); /** * 12.21 Logical Boolean Expressions: It is a static type warning if the * static types of both of <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> may * not be assigned to bool. * * Parameters: * 0: the lexeme of the logical operator */ static const StaticTypeWarningCode NON_BOOL_OPERAND = const StaticTypeWarningCode('NON_BOOL_OPERAND', "The operands of the '{0}' operator must be assignable to 'bool'."); /** * Parameters: * 0: the name appearing where a type is expected */ // #### Description // // The analyzer produces this diagnostic when an identifier that isn't a type // is used as a type argument. // // #### Example // // The following code produces this diagnostic because `x` is a variable, not // a type: // // ```dart // var x = 0; // List<[!x!]> xList = []; // ``` // // #### Common fixes // // Change the type argument to be a type: // // ```dart // var x = 0; // List<int> xList = []; // ``` static const StaticTypeWarningCode NON_TYPE_AS_TYPE_ARGUMENT = const StaticTypeWarningCode('NON_TYPE_AS_TYPE_ARGUMENT', "The name '{0}' isn't a type so it can't be used as a type argument.", correction: "Try correcting the name to an existing type, or " "defining a type named '{0}'.", hasPublishedDocs: true, isUnresolvedIdentifier: true); /** * 13.11 Return: It is a static type warning if the type of <i>e</i> may not * be assigned to the declared return type of the immediately enclosing * function. * * Parameters: * 0: the return type as declared in the return statement * 1: the expected return type as defined by the method * 2: the name of the method */ static const StaticTypeWarningCode RETURN_OF_INVALID_TYPE = const StaticTypeWarningCode( 'RETURN_OF_INVALID_TYPE', "The return type '{0}' isn't a '{1}', as defined by the method " "'{2}'."); /** * 13.11 Return: It is a static type warning if the type of <i>e</i> may not * be assigned to the declared return type of the immediately enclosing * function. * * Parameters: * 0: the return type as declared in the return statement * 1: the expected return type as defined by the method */ static const StaticTypeWarningCode RETURN_OF_INVALID_TYPE_FROM_CLOSURE = const StaticTypeWarningCode( 'RETURN_OF_INVALID_TYPE_FROM_CLOSURE', "The return type '{0}' isn't a '{1}', as defined by anonymous " "closure."); /** * 10 Generics: It is a static type warning if a type parameter is a supertype * of its upper bound. * * Parameters: * 0: the name of the type parameter * 1: the name of the bounding type * * See [CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS]. */ static const StaticTypeWarningCode TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND = const StaticTypeWarningCode('TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND', "'{0}' can't be a supertype of its upper bound.", correction: "Try using a type that is or is a subclass of '{1}'."); /** * 12.17 Getter Invocation: It is a static warning if there is no class * <i>C</i> in the enclosing lexical scope of <i>i</i>, or if <i>C</i> does * not declare, implicitly or explicitly, a getter named <i>m</i>. * * Parameters: * 0: the name of the enumeration constant that is not defined * 1: the name of the enumeration used to access the constant */ static const StaticTypeWarningCode UNDEFINED_ENUM_CONSTANT = const StaticTypeWarningCode('UNDEFINED_ENUM_CONSTANT', "There is no constant named '{0}' in '{1}'.", correction: "Try correcting the name to the name of an existing constant, or " "defining a constant named '{0}'."); /** * Parameters: * 0: the name of the method that is undefined */ // #### Description // // The analyzer produces this diagnostic when it encounters an identifier that // appears to be the name of a function but either isn't defined or isn't // visible in the scope in which it's being referenced. // // #### Example // // The following code produces this diagnostic: // // ```dart // List<int> empty() => []; // // void main() { // print([!emty!]()); // } // ``` // // #### Common fixes // // If the identifier isn't defined, then either define it or replace it with // the name of a function that is defined. The example above can be corrected // by fixing the spelling of the function: // // ```dart // List<int> empty() => []; // // void main() { // print(empty()); // } // ``` // // If the function is defined but isn't visible, then you probably need to add // an import or re-arrange your code to make the function visible. static const StaticTypeWarningCode UNDEFINED_FUNCTION = const StaticTypeWarningCode( 'UNDEFINED_FUNCTION', "The function '{0}' isn't defined.", correction: "Try importing the library that defines '{0}', " "correcting the name to the name of an existing function, or " "defining a function named '{0}'.", hasPublishedDocs: true, isUnresolvedIdentifier: true); /** * Parameters: * 0: the name of the getter * 1: the name of the enclosing type where the getter is being looked for */ // #### Description // // The analyzer produces this diagnostic when it encounters an identifier that // appears to be the name of a getter but either isn't defined or isn't // visible in the scope in which it's being referenced. // // #### Example // // The following code produces this diagnostic: // // ```dart // int f(String s) => s.[!len!]; // ``` // // #### Common fixes // // If the identifier isn't defined, then either define it or replace it with // the name of a getter that is defined. The example above can be corrected by // fixing the spelling of the getter: // // ```dart // int f(String s) => s.length; // ``` static const StaticTypeWarningCode UNDEFINED_GETTER = // TODO(brianwilkerson) When the "target" is an enum, report // UNDEFINED_ENUM_CONSTANT instead. const StaticTypeWarningCode('UNDEFINED_GETTER', "The getter '{0}' isn't defined for the class '{1}'.", correction: "Try importing the library that defines '{0}', " "correcting the name to the name of an existing getter, or " "defining a getter or field named '{0}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the method that is undefined * 1: the resolved type name that the method lookup is happening on */ // #### Description // // The analyzer produces this diagnostic when it encounters an identifier that // appears to be the name of a method but either isn't defined or isn't // visible in the scope in which it's being referenced. // // #### Example // // The following code produces this diagnostic: // // ```dart // int f(List<int> l) => l.[!removeMiddle!](); // ``` // // #### Common fixes // // If the identifier isn't defined, then either define it or replace it with // the name of a method that is defined. The example above can be corrected by // fixing the spelling of the method: // // ```dart // int f(List<int> l) => l.removeLast(); // ``` static const StaticTypeWarningCode UNDEFINED_METHOD = const StaticTypeWarningCode('UNDEFINED_METHOD', "The method '{0}' isn't defined for the class '{1}'.", correction: "Try correcting the name to the name of an existing method, or " "defining a method named '{0}'.", hasPublishedDocs: true); /** * 12.18 Assignment: Evaluation of an assignment of the form * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] = <i>e<sub>3</sub></i> is * equivalent to the evaluation of the expression (a, i, e){a.[]=(i, e); * return e;} (<i>e<sub>1</sub></i>, <i>e<sub>2</sub></i>, * <i>e<sub>2</sub></i>). * * 12.29 Assignable Expressions: An assignable expression of the form * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] is evaluated as a method * invocation of the operator method [] on <i>e<sub>1</sub></i> with argument * <i>e<sub>2</sub></i>. * * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>. * It is a static type warning if <i>T</i> does not have an accessible * instance member named <i>m</i>. * * Parameters: * 0: the name of the operator * 1: the name of the enclosing type where the operator is being looked for */ static const StaticTypeWarningCode UNDEFINED_OPERATOR = const StaticTypeWarningCode('UNDEFINED_OPERATOR', "The operator '{0}' isn't defined for the class '{1}'.", correction: "Try defining the operator '{0}'."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when a prefixed identifier is found // where the prefix is valid, but the identifier isn't declared in any of the // libraries imported using that prefix. // // #### Example // // The following code produces this diagnostic: // // ```dart // import 'dart:core' as p; // // void f() { // p.[!a!]; // } // ``` // // #### Common fixes // // If the library in which the name is declared isn't imported yet, add an // import for the library. // // If the name is wrong, then change it to one of the names that's declared in // the imported libraries. static const StaticTypeWarningCode UNDEFINED_PREFIXED_NAME = const StaticTypeWarningCode( 'UNDEFINED_PREFIXED_NAME', "The name '{0}' is being referenced through the prefix '{1}', but it " "isn't defined in any of the libraries imported using that " "prefix.", correction: "Try correcting the prefix or " "importing the library that defines '{0}'.", hasPublishedDocs: true); /** * Parameters: * 0: the name of the setter * 1: the name of the enclosing type where the setter is being looked for */ // #### Description // // The analyzer produces this diagnostic when it encounters an identifier that // appears to be the name of a setter but either isn't defined or isn't // visible in the scope in which the identifier is being referenced. // // #### Example // // The following code produces this diagnostic: // // ```dart // class C { // int x = 0; // void m(int y) { // this.[!z!] = y; // } // } // ``` // // #### Common fixes // // If the identifier isn't defined, then either define it or replace it with // the name of a setter that is defined. The example above can be corrected by // fixing the spelling of the setter: // // ```dart // class C { // int x = 0; // void m(int y) { // this.x = y; // } // } // ``` static const StaticTypeWarningCode UNDEFINED_SETTER = const StaticTypeWarningCode('UNDEFINED_SETTER', "The setter '{0}' isn't defined for the class '{1}'.", correction: "Try importing the library that defines '{0}', " "correcting the name to the name of an existing setter, or " "defining a setter or field named '{0}'.", hasPublishedDocs: true); /** * 12.17 Getter Invocation: Let <i>T</i> be the static type of <i>e</i>. It is * a static type warning if <i>T</i> does not have a getter named <i>m</i>. * * Parameters: * 0: the name of the getter * 1: the name of the enclosing type where the getter is being looked for */ static const StaticTypeWarningCode UNDEFINED_SUPER_GETTER = const StaticTypeWarningCode('UNDEFINED_SUPER_GETTER', "The getter '{0}' isn't defined in a superclass of '{1}'.", correction: "Try correcting the name to the name of an existing getter, or " "defining a getter or field named '{0}' in a superclass."); /** * Parameters: * 0: the name of the method that is undefined * 1: the resolved type name that the method lookup is happening on */ // #### Description // // The analyzer produces this diagnostic when an inherited method is // referenced using `super`, but there’s no method with that name in the // superclass chain. // // #### Example // // The following code produces this diagnostic: // // ```dart // class C { // void m() { // super.[!n!](); // } // } // ``` // // #### Common fixes // // If the inherited method you intend to invoke has a different name, then // make the name of the invoked method match the inherited method. // // If the method you intend to invoke is defined in the same class, then // remove the `super.`. // // If not, then either add the method to one of the superclasses or remove the // invocation. static const StaticTypeWarningCode UNDEFINED_SUPER_METHOD = const StaticTypeWarningCode('UNDEFINED_SUPER_METHOD', "The method '{0}' isn't defined in a superclass of '{1}'.", correction: "Try correcting the name to the name of an existing method, or " "defining a method named '{0}' in a superclass.", hasPublishedDocs: true); /** * 12.18 Assignment: Evaluation of an assignment of the form * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] = <i>e<sub>3</sub></i> is * equivalent to the evaluation of the expression (a, i, e){a.[]=(i, e); * return e;} (<i>e<sub>1</sub></i>, <i>e<sub>2</sub></i>, * <i>e<sub>2</sub></i>). * * 12.29 Assignable Expressions: An assignable expression of the form * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] is evaluated as a method * invocation of the operator method [] on <i>e<sub>1</sub></i> with argument * <i>e<sub>2</sub></i>. * * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>. * It is a static type warning if <i>T</i> does not have an accessible * instance member named <i>m</i>. * * Parameters: * 0: the name of the operator * 1: the name of the enclosing type where the operator is being looked for */ static const StaticTypeWarningCode UNDEFINED_SUPER_OPERATOR = const StaticTypeWarningCode('UNDEFINED_SUPER_OPERATOR', "The operator '{0}' isn't defined in a superclass of '{1}'.", correction: "Try defining the operator '{0}' in a superclass."); /** * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>. * It is a static type warning if <i>T</i> does not have an accessible * instance setter named <i>v=</i>. * * Parameters: * 0: the name of the setter * 1: the name of the enclosing type where the setter is being looked for */ static const StaticTypeWarningCode UNDEFINED_SUPER_SETTER = const StaticTypeWarningCode('UNDEFINED_SUPER_SETTER', "The setter '{0}' isn't defined in a superclass of '{1}'.", correction: "Try correcting the name to the name of an existing setter, or " "defining a setter or field named '{0}' in a superclass."); /** * 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does * not have an accessible (3.2) instance member named <i>m</i>. * * This is a specialization of [INSTANCE_ACCESS_TO_STATIC_MEMBER] that is used * when we are able to find the name defined in a supertype. It exists to * provide a more informative error message. * * Parameters: * 0: the name of the defining type */ static const StaticTypeWarningCode UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER = const StaticTypeWarningCode( 'UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER', "Static members from supertypes must be qualified by the name of the " "defining type.", correction: "Try adding '{0}.' before the name."); /** * 15.8 Parameterized Types: It is a static type warning if <i>G</i> is not a * generic type with exactly <i>n</i> type parameters. * * Parameters: * 0: the name of the type being referenced (<i>G</i>) * 1: the number of type parameters that were declared * 2: the number of type arguments provided * * See [CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS], and * [CompileTimeErrorCode.NEW_WITH_INVALID_TYPE_PARAMETERS]. */ static const StaticTypeWarningCode WRONG_NUMBER_OF_TYPE_ARGUMENTS = const StaticTypeWarningCode( 'WRONG_NUMBER_OF_TYPE_ARGUMENTS', "The type '{0}' is declared with {1} type parameters, " "but {2} type arguments were given.", correction: "Try adjusting the number of type arguments."); /** * It will be a static type warning if <i>m</i> is not a generic method with * exactly <i>n</i> type parameters. * * Parameters: * 0: the name of the class being instantiated * 1: the name of the constructor being invoked */ static const StaticTypeWarningCode WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR = const StaticTypeWarningCode( 'WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR', "The constructor '{0}.{1}' doesn't have type parameters.", correction: "Try moving type arguments to after the type name."); /** * It will be a static type warning if <i>m</i> is not a generic method with * exactly <i>n</i> type parameters. * * Parameters: * 0: the name of the method being referenced (<i>G</i>) * 1: the number of type parameters that were declared * 2: the number of type arguments provided */ static const StaticTypeWarningCode WRONG_NUMBER_OF_TYPE_ARGUMENTS_METHOD = const StaticTypeWarningCode( 'WRONG_NUMBER_OF_TYPE_ARGUMENTS_METHOD', "The method '{0}' is declared with {1} type parameters, " "but {2} type arguments were given.", correction: "Try adjusting the number of type arguments."); /** * 17.16.1 Yield: Let T be the static type of e [the expression to the right * of "yield"] and let f be the immediately enclosing function. It is a * static type warning if either: * * - the body of f is marked async* and the type Stream<T> may not be * assigned to the declared return type of f. * * - the body of f is marked sync* and the type Iterable<T> may not be * assigned to the declared return type of f. * * 17.16.2 Yield-Each: Let T be the static type of e [the expression to the * right of "yield*"] and let f be the immediately enclosing function. It is * a static type warning if T may not be assigned to the declared return type * of f. If f is synchronous it is a static type warning if T may not be * assigned to Iterable. If f is asynchronous it is a static type warning if * T may not be assigned to Stream. */ static const StaticTypeWarningCode YIELD_OF_INVALID_TYPE = const StaticTypeWarningCode( 'YIELD_OF_INVALID_TYPE', "The type '{0}' implied by the 'yield' expression must be assignable " "to '{1}'."); /** * 17.6.2 For-in. If the iterable expression does not implement Iterable, * this warning is reported. * * Parameters: * 0: The type of the iterable expression. * 1: The sequence type -- Iterable for `for` or Stream for `await for`. */ static const StaticTypeWarningCode FOR_IN_OF_INVALID_TYPE = const StaticTypeWarningCode('FOR_IN_OF_INVALID_TYPE', "The type '{0}' used in the 'for' loop must implement {1}."); /** * 17.6.2 For-in. It the iterable expression does not implement Iterable with * a type argument that can be assigned to the for-in variable's type, this * warning is reported. * * Parameters: * 0: The type of the iterable expression. * 1: The sequence type -- Iterable for `for` or Stream for `await for`. * 2: The loop variable type. */ static const StaticTypeWarningCode FOR_IN_OF_INVALID_ELEMENT_TYPE = const StaticTypeWarningCode( 'FOR_IN_OF_INVALID_ELEMENT_TYPE', "The type '{0}' used in the 'for' loop must implement {1} with a " "type argument that can be assigned to '{2}'."); /** * Initialize a newly created error code to have the given [name]. The message * associated with the error will be created from the given [message] * template. The correction associated with the error will be created from the * given [correction] template. */ const StaticTypeWarningCode(String name, String message, {String correction, bool hasPublishedDocs, bool isUnresolvedIdentifier: false}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs, isUnresolvedIdentifier: isUnresolvedIdentifier); @override ErrorSeverity get errorSeverity => ErrorSeverity.ERROR; @override ErrorType get type => ErrorType.STATIC_TYPE_WARNING; } /** * The error codes used for static warnings. The convention for this class is * for the name of the error code to indicate the problem that caused the error * to be generated and for the error message to explain what is wrong and, when * appropriate, how the problem can be corrected. */ class StaticWarningCode extends AnalyzerErrorCode { /** * 14.1 Imports: If a name <i>N</i> is referenced by a library <i>L</i> and * <i>N</i> is introduced into the top level scope <i>L</i> by more than one * import then: * 1. A static warning occurs. * 2. If <i>N</i> is referenced as a function, getter or setter, a * <i>NoSuchMethodError</i> is raised. * 3. If <i>N</i> is referenced as a type, it is treated as a malformed type. * * Parameters: * 0: the name of the ambiguous type * 1: the name of the first library that the type is found * 2: the name of the second library that the type is found */ static const StaticWarningCode AMBIGUOUS_IMPORT = const StaticWarningCode( 'AMBIGUOUS_IMPORT', "The name '{0}' is defined in the libraries {1}.", correction: "Try using 'as prefix' for one of the import directives, or " "hiding the name from all but one of the imports."); /** * Parameters: * 0: the name of the actual argument type * 1: the name of the expected type */ // #### Description // // The analyzer produces this diagnostic when the static type of an argument // can't be assigned to the static type of the corresponding parameter. // // #### Example // // The following code produces this diagnostic: // // ```dart // String f(String x) => x; // String g(num y) => f([!y!]); // ``` // // #### Common fixes // // If possible, rewrite the code so that the static type is assignable. In the // example above you might be able to change the type of the parameter `y`: // // ```dart // String f(String x) => x; // String g(String y) => f(y); // ``` // // If that fix isn't possible, then add code to handle the case where the // argument value isn't the required type. One approach is to coerce other // types to the required type: // // ```dart // String f(String x) => x; // String g(num y) => f(y.toString()); // ``` // // Another approach is to add explicit type tests and fallback code: // // ```dart // String f(String x) => x; // String g(num y) => f(y is String ? y : ''); // ``` // // If you believe that the runtime type of the argument will always be the // same as the static type of the parameter, and you're willing to risk having // an exception thrown at runtime if you're wrong, then add an explicit cast: // // ```dart // String f(String x) => x; // String g(num y) => f(y as String); // ``` static const StaticWarningCode ARGUMENT_TYPE_NOT_ASSIGNABLE = const StaticWarningCode( 'ARGUMENT_TYPE_NOT_ASSIGNABLE', "The argument type '{0}' can't be assigned to the parameter type " "'{1}'.", hasPublishedDocs: true); /** * 5 Variables: Attempting to assign to a final variable elsewhere will cause * a NoSuchMethodError to be thrown, because no setter is defined for it. The * assignment will also give rise to a static warning for the same reason. * * A constant variable is always implicitly final. */ static const StaticWarningCode ASSIGNMENT_TO_CONST = const StaticWarningCode( 'ASSIGNMENT_TO_CONST', "Constant variables can't be assigned a value.", correction: "Try removing the assignment, or " "remove the modifier 'const' from the variable."); /** * 5 Variables: Attempting to assign to a final variable elsewhere will cause * a NoSuchMethodError to be thrown, because no setter is defined for it. The * assignment will also give rise to a static warning for the same reason. */ static const StaticWarningCode ASSIGNMENT_TO_FINAL = const StaticWarningCode( 'ASSIGNMENT_TO_FINAL', "'{0}' can't be used as a setter because it is final.", correction: "Try finding a different setter, or making '{0}' non-final."); /** * 5 Variables: Attempting to assign to a final variable elsewhere will cause * a NoSuchMethodError to be thrown, because no setter is defined for it. The * assignment will also give rise to a static warning for the same reason. */ static const StaticWarningCode ASSIGNMENT_TO_FINAL_LOCAL = const StaticWarningCode('ASSIGNMENT_TO_FINAL_LOCAL', "'{0}', a final variable, can only be set once.", correction: "Try making '{0}' non-final."); /** * 5 Variables: Attempting to assign to a final variable elsewhere will cause * a NoSuchMethodError to be thrown, because no setter is defined for it. The * assignment will also give rise to a static warning for the same reason. */ static const StaticWarningCode ASSIGNMENT_TO_FINAL_NO_SETTER = const StaticWarningCode('ASSIGNMENT_TO_FINAL_NO_SETTER', "No setter named '{0}' in class '{1}'.", correction: "Try correcting the name to reference an existing setter, or " "declare the setter."); /** * 12.18 Assignment: It is as static warning if an assignment of the form * <i>v = e</i> occurs inside a top level or static function (be it function, * method, getter, or setter) or variable initializer and there is neither a * local variable declaration with name <i>v</i> nor setter declaration with * name <i>v=</i> in the lexical scope enclosing the assignment. */ static const StaticWarningCode ASSIGNMENT_TO_FUNCTION = const StaticWarningCode( 'ASSIGNMENT_TO_FUNCTION', "Functions can't be assigned a value."); /** * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i> * It is a static type warning if <i>T</i> does not have an accessible * instance setter named <i>v=</i>. */ static const StaticWarningCode ASSIGNMENT_TO_METHOD = const StaticWarningCode( 'ASSIGNMENT_TO_METHOD', "Methods can't be assigned a value."); /** * 12.18 Assignment: It is as static warning if an assignment of the form * <i>v = e</i> occurs inside a top level or static function (be it function, * method, getter, or setter) or variable initializer and there is neither a * local variable declaration with name <i>v</i> nor setter declaration with * name <i>v=</i> in the lexical scope enclosing the assignment. */ static const StaticWarningCode ASSIGNMENT_TO_TYPE = const StaticWarningCode( 'ASSIGNMENT_TO_TYPE', "Types can't be assigned a value."); /** * 13.9 Switch: It is a static warning if the last statement of the statement * sequence <i>s<sub>k</sub></i> is not a break, continue, rethrow, return * or throw statement. */ static const StaticWarningCode CASE_BLOCK_NOT_TERMINATED = const StaticWarningCode( 'CASE_BLOCK_NOT_TERMINATED', "The last statement of the 'case' should be 'break', 'continue', " "'rethrow', 'return' or 'throw'.", correction: "Try adding one of the required statements."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the name following the `as` in a // cast expression is defined to be something other than a type. // // #### Example // // The following code produces this diagnostic: // // ```dart // num x = 0; // int y = x as [!x!]; // ``` // // #### Common fixes // // Replace the name with the name of a type: // // ```dart // num x = 0; // int y = x as int; // ``` static const StaticWarningCode CAST_TO_NON_TYPE = const StaticWarningCode( 'CAST_TO_NON_TYPE', "The name '{0}' isn't a type, so it can't be used in an 'as' expression.", correction: "Try changing the name to the name of an existing type, or " "creating a type with the name '{0}'.", hasPublishedDocs: true); /** * 7.4 Abstract Instance Members: It is a static warning if an abstract member * is declared or inherited in a concrete class. * * Parameters: * 0: the name of the abstract method * 1: the name of the enclosing class */ static const StaticWarningCode CONCRETE_CLASS_WITH_ABSTRACT_MEMBER = const StaticWarningCode('CONCRETE_CLASS_WITH_ABSTRACT_MEMBER', "'{0}' must have a method body because '{1}' isn't abstract.", correction: "Try making '{1}' abstract, or adding a body to '{0}'."); /** * 16.12.2 Const: Given an instance creation expression of the form <i>const * q(a<sub>1</sub>, &hellip; a<sub>n</sub>)</i> it is a static warning if * <i>q</i> is the constructor of an abstract class but <i>q</i> is not a * factory constructor. */ static const StaticWarningCode CONST_WITH_ABSTRACT_CLASS = const StaticWarningCode('CONST_WITH_ABSTRACT_CLASS', "Abstract classes can't be created with a 'const' expression.", correction: "Try creating an instance of a subtype."); /** * 14.2 Exports: It is a static warning to export two different libraries with * the same name. * * Parameters: * 0: the uri pointing to a first library * 1: the uri pointing to a second library * 2:e the shared name of the exported libraries */ static const StaticWarningCode EXPORT_DUPLICATED_LIBRARY_NAMED = const StaticWarningCode( 'EXPORT_DUPLICATED_LIBRARY_NAMED', "The exported libraries '{0}' and '{1}' can't have the same name " "'{2}'.", correction: "Try adding a hide clause to one of the export directives."); @Deprecated('Use CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS') static const CompileTimeErrorCode EXTRA_POSITIONAL_ARGUMENTS = CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS; @Deprecated( 'Use CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED') static const CompileTimeErrorCode EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED = CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED; /** * 5. Variables: It is a static warning if a final instance variable that has * been initialized at its point of declaration is also initialized in a * constructor. */ static const StaticWarningCode FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION = const StaticWarningCode( 'FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION', "Fields can't be initialized in the constructor if they are final " "and have already been initialized at their declaration.", correction: "Try removing one of the initializations."); /** * 5. Variables: It is a static warning if a final instance variable that has * been initialized at its point of declaration is also initialized in a * constructor. * * Parameters: * 0: the name of the field in question */ static const StaticWarningCode FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR = const StaticWarningCode( 'FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR', "'{0}' is final and was given a value when it was declared, " "so it can't be set to a new value.", correction: "Try removing one of the initializations."); /** * 7.6.1 Generative Constructors: Execution of an initializer of the form * <b>this</b>.<i>v</i> = <i>e</i> proceeds as follows: First, the expression * <i>e</i> is evaluated to an object <i>o</i>. Then, the instance variable * <i>v</i> of the object denoted by this is bound to <i>o</i>. * * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of * <i>p<sub>i</sub>, 1 &lt;= i &lt;= n+k</i> and let <i>S<sub>q</sub></i> be * the type of the named parameter <i>q</i> of <i>f</i>. It is a static * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1 * &lt;= j &lt;= m</i>. * * Parameters: * 0: the name of the type of the initializer expression * 1: the name of the type of the field */ static const StaticWarningCode FIELD_INITIALIZER_NOT_ASSIGNABLE = const StaticWarningCode( 'FIELD_INITIALIZER_NOT_ASSIGNABLE', "The initializer type '{0}' can't be assigned to the field type " "'{1}'."); /** * 7.6.1 Generative Constructors: An initializing formal has the form * <i>this.id</i>. It is a static warning if the static type of <i>id</i> is * not assignable to <i>T<sub>id</sub></i>. * * Parameters: * 0: the name of the type of the field formal parameter * 1: the name of the type of the field */ static const StaticWarningCode FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE = const StaticWarningCode('FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE', "The parameter type '{0}' is incompatible with the field type '{1}'.", correction: "Try changing or removing the parameter's type, or " "changing the field's type."); /** * Parameters: * 0: the name of the uninitialized final variable */ // #### Description // // The analyzer produces this diagnostic when a final field or variable isn't // initialized. // // #### Example // // The following code produces this diagnostic: // // ```dart // final [!x!]; // ``` // // #### Common fixes // // For variables and static fields, you can add an initializer: // // ```dart // final x = 0; // ``` // // For instance fields, you can add an initializer as shown in the previous // example, or you can initialize the field in every constructor. You can // initialize the field by using a field formal parameter: // // ```dart // class C { // final int x; // C(this.x); // } // ``` // // You can also initialize the field by using an initializer in the // constructor: // // ```dart // class C { // final int x; // C(int y) : x = y * 2; // } // ``` static const StaticWarningCode FINAL_NOT_INITIALIZED = const StaticWarningCode('FINAL_NOT_INITIALIZED', "The final variable '{0}' must be initialized.", // TODO(brianwilkerson) Split this error code so that we can suggest // initializing fields in constructors (FINAL_FIELD_NOT_INITIALIZED // and FINAL_VARIABLE_NOT_INITIALIZED). correction: "Try initializing the variable.", hasPublishedDocs: true); /** * 7.6.1 Generative Constructors: Each final instance variable <i>f</i> * declared in the immediately enclosing class must have an initializer in * <i>k</i>'s initializer list unless it has already been initialized by one * of the following means: * * Initialization at the declaration of <i>f</i>. * * Initialization by means of an initializing formal of <i>k</i>. * or a static warning occurs. * * Parameters: * 0: the name of the uninitialized final variable */ static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_1 = const StaticWarningCode('FINAL_NOT_INITIALIZED_CONSTRUCTOR_1', "The final variable '{0}' must be initialized.", correction: "Try adding an initializer for the field."); /** * 7.6.1 Generative Constructors: Each final instance variable <i>f</i> * declared in the immediately enclosing class must have an initializer in * <i>k</i>'s initializer list unless it has already been initialized by one * of the following means: * * Initialization at the declaration of <i>f</i>. * * Initialization by means of an initializing formal of <i>k</i>. * or a static warning occurs. * * Parameters: * 0: the name of the uninitialized final variable * 1: the name of the uninitialized final variable */ static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_2 = const StaticWarningCode('FINAL_NOT_INITIALIZED_CONSTRUCTOR_2', "The final variables '{0}' and '{1}' must be initialized.", correction: "Try adding initializers for the fields."); /** * 7.6.1 Generative Constructors: Each final instance variable <i>f</i> * declared in the immediately enclosing class must have an initializer in * <i>k</i>'s initializer list unless it has already been initialized by one * of the following means: * * Initialization at the declaration of <i>f</i>. * * Initialization by means of an initializing formal of <i>k</i>. * or a static warning occurs. * * Parameters: * 0: the name of the uninitialized final variable * 1: the name of the uninitialized final variable * 2: the number of additional not initialized variables that aren't listed */ static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS = const StaticWarningCode('FINAL_NOT_INITIALIZED_CONSTRUCTOR_3', "The final variables '{0}', '{1}' and {2} more must be initialized.", correction: "Try adding initializers for the fields."); /** * 14.1 Imports: It is a static warning to import two different libraries with * the same name. * * Parameters: * 0: the uri pointing to a first library * 1: the uri pointing to a second library * 2: the shared name of the imported libraries */ static const StaticWarningCode IMPORT_DUPLICATED_LIBRARY_NAMED = const StaticWarningCode( 'IMPORT_DUPLICATED_LIBRARY_NAMED', "The imported libraries '{0}' and '{1}' can't have the same name " "'{2}'.", correction: "Try adding a hide clause to one of the imports."); @Deprecated('Use CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY') static const CompileTimeErrorCode IMPORT_OF_NON_LIBRARY = CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY; /** * 7.1 Instance Methods: It is a static warning if an instance method * <i>m1</i> overrides an instance member <i>m2</i>, the signature of * <i>m2</i> explicitly specifies a default value for a formal parameter * <i>p</i> and the signature of <i>m1</i> specifies a different default value * for <i>p</i>. */ static const StaticWarningCode INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED = const StaticWarningCode( 'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED', "Parameters can't override default values, this method overrides " "'{0}.{1}' where '{2}' has a different value.", correction: "Try using the same default value in both methods.", errorSeverity: ErrorSeverity.WARNING); /** * 7.1 Instance Methods: It is a static warning if an instance method * <i>m1</i> overrides an instance member <i>m2</i>, the signature of * <i>m2</i> explicitly specifies a default value for a formal parameter * <i>p</i> and the signature of <i>m1</i> specifies a different default value * for <i>p</i>. */ static const StaticWarningCode INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL = const StaticWarningCode( 'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL', "Parameters can't override default values, this method overrides " "'{0}.{1}' where this positional parameter has a different " "value.", correction: "Try using the same default value in both methods.", errorSeverity: ErrorSeverity.WARNING); /** * 12.6 Lists: A run-time list literal &lt;<i>E</i>&gt; [<i>e<sub>1</sub></i> * &hellip; <i>e<sub>n</sub></i>] is evaluated as follows: * * The operator []= is invoked on <i>a</i> with first argument <i>i</i> and * second argument <i>o<sub>i+1</sub></i><i>, 1 &lt;= i &lt;= n</i> * * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of * <i>p<sub>i</sub>, 1 &lt;= i &lt;= n+k</i> and let <i>S<sub>q</sub></i> be * the type of the named parameter <i>q</i> of <i>f</i>. It is a static * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1 * &lt;= j &lt;= m</i>. * * Parameters: * 0: the actual type of the list element * 1: the expected type of the list element */ static const StaticWarningCode LIST_ELEMENT_TYPE_NOT_ASSIGNABLE = const StaticWarningCode('LIST_ELEMENT_TYPE_NOT_ASSIGNABLE', "The element type '{0}' can't be assigned to the list type '{1}'."); /** * 12.7 Map: A run-time map literal &lt;<i>K</i>, <i>V</i>&gt; * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> &hellip; <i>k<sub>n</sub></i> * : <i>e<sub>n</sub></i>] is evaluated as follows: * * The operator []= is invoked on <i>m</i> with first argument * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 &lt;= * i &lt;= n</i> * * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of * <i>p<sub>i</sub>, 1 &lt;= i &lt;= n+k</i> and let <i>S<sub>q</sub></i> be * the type of the named parameter <i>q</i> of <i>f</i>. It is a static * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1 * &lt;= j &lt;= m</i>. */ static const StaticWarningCode MAP_KEY_TYPE_NOT_ASSIGNABLE = const StaticWarningCode( 'MAP_KEY_TYPE_NOT_ASSIGNABLE', "The element type '{0}' can't be assigned to the map key type " "'{1}'."); /** * 12.7 Map: A run-time map literal &lt;<i>K</i>, <i>V</i>&gt; * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> &hellip; <i>k<sub>n</sub></i> * : <i>e<sub>n</sub></i>] is evaluated as follows: * * The operator []= is invoked on <i>m</i> with first argument * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 &lt;= * i &lt;= n</i> * * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of * <i>p<sub>i</sub>, 1 &lt;= i &lt;= n+k</i> and let <i>S<sub>q</sub></i> be * the type of the named parameter <i>q</i> of <i>f</i>. It is a static * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1 * &lt;= j &lt;= m</i>. */ static const StaticWarningCode MAP_VALUE_TYPE_NOT_ASSIGNABLE = const StaticWarningCode( 'MAP_VALUE_TYPE_NOT_ASSIGNABLE', "The element type '{0}' can't be assigned to the map value type " "'{1}'."); /** * 10.3 Setters: It is a compile-time error if a class has a setter named * `v=` with argument type `T` and a getter named `v` with return type `S`, * and `S` may not be assigned to `T`. * * Parameters: * 0: the name of the getter * 1: the type of the getter * 2: the type of the setter * 3: the name of the setter */ static const StaticWarningCode MISMATCHED_GETTER_AND_SETTER_TYPES = const StaticWarningCode( 'MISMATCHED_GETTER_AND_SETTER_TYPES', "The return type of getter '{0}' is '{1}' which isn't assignable " "to the type '{2}' of its setter '{3}'.", correction: "Try changing the types so that they are compatible."); /** * 17.9 Switch: It is a static warning if all of the following conditions * hold: * * The switch statement does not have a 'default' clause. * * The static type of <i>e</i> is an enumerated typed with elements * <i>id<sub>1</sub></i>, &hellip;, <i>id<sub>n</sub></i>. * * The sets {<i>e<sub>1</sub></i>, &hellip;, <i>e<sub>k</sub></i>} and * {<i>id<sub>1</sub></i>, &hellip;, <i>id<sub>n</sub></i>} are not the * same. * * Parameters: * 0: the name of the constant that is missing */ static const StaticWarningCode MISSING_ENUM_CONSTANT_IN_SWITCH = const StaticWarningCode( 'MISSING_ENUM_CONSTANT_IN_SWITCH', "Missing case clause for '{0}'.", correction: "Try adding a case clause for the missing constant, or " "adding a default clause."); /** * 13.12 Return: It is a static warning if a function contains both one or * more return statements of the form <i>return;</i> and one or more return * statements of the form <i>return e;</i>. */ static const StaticWarningCode MIXED_RETURN_TYPES = const StaticWarningCode( 'MIXED_RETURN_TYPES', "Functions can't include return statements both with and without values.", // TODO(brianwilkerson) Split this error code depending on whether the // function declares a return type. correction: "Try making all the return statements consistent " "(either include a value or not)."); /** * 12.11.1 New: It is a static warning if <i>q</i> is a constructor of an * abstract class and <i>q</i> is not a factory constructor. */ static const StaticWarningCode NEW_WITH_ABSTRACT_CLASS = const StaticWarningCode('NEW_WITH_ABSTRACT_CLASS', "Abstract classes can't be instantiated.", correction: "Try creating an instance of a subtype."); /** * 15.8 Parameterized Types: Any use of a malbounded type gives rise to a * static warning. * * Parameters: * 0: the name of the type being referenced (<i>S</i>) * 1: the number of type parameters that were declared * 2: the number of type arguments provided * * See [CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS], and * [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS]. */ static const StaticWarningCode NEW_WITH_INVALID_TYPE_PARAMETERS = const StaticWarningCode( 'NEW_WITH_INVALID_TYPE_PARAMETERS', "The type '{0}' is declared with {1} type parameters, " "but {2} type arguments were given.", correction: "Try adjusting the number of type arguments."); /** * 12.11.1 New: It is a static warning if <i>T</i> is not a class accessible * in the current scope, optionally followed by type arguments. * * Parameters: * 0: the name of the non-type element */ static const StaticWarningCode NEW_WITH_NON_TYPE = const StaticWarningCode( 'NEW_WITH_NON_TYPE', "The name '{0}' isn't a class.", correction: "Try correcting the name to match an existing class."); /** * 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the * current scope then: * 1. If <i>e</i> is of the form <i>new T.id(a<sub>1</sub>, &hellip;, * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, &hellip;, * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a static warning if * <i>T.id</i> is not the name of a constructor declared by the type * <i>T</i>. * If <i>e</i> of the form <i>new T(a<sub>1</sub>, &hellip;, a<sub>n</sub>, * x<sub>n+1</sub>: a<sub>n+1</sub>, &hellip;, x<sub>n+k</sub>: * a<sub>n+kM/sub>)</i> it is a static warning if the type <i>T</i> does not * declare a constructor with the same name as the declaration of <i>T</i>. */ static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR = const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR', "The class '{0}' doesn't have a constructor named '{1}'.", correction: "Try invoking a different constructor, or " "define a constructor named '{1}'."); /** * 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the * current scope then: * 1. If <i>e</i> is of the form <i>new T.id(a<sub>1</sub>, &hellip;, * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, &hellip;, x<sub>n+k</sub>: * a<sub>n+k</sub>)</i> it is a static warning if <i>T.id</i> is not the name * of a constructor declared by the type <i>T</i>. If <i>e</i> of the form * <i>new T(a<sub>1</sub>, &hellip;, a<sub>n</sub>, x<sub>n+1</sub>: * a<sub>n+1</sub>, &hellip;, x<sub>n+k</sub>: a<sub>n+kM/sub>)</i> it is a * static warning if the type <i>T</i> does not declare a constructor with the * same name as the declaration of <i>T</i>. */ static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT = const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT', "The class '{0}' doesn't have a default constructor.", correction: "Try using one of the named constructors defined in '{0}'."); /** * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract * class inherits an abstract method. * * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not * declare its own <i>noSuchMethod()</i> method. It is a static warning if the * implicit interface of <i>C</i> includes an instance member <i>m</i> of type * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>. * * 7.4 Abstract Instance Members: It is a static warning if an abstract member * is declared or inherited in a concrete class unless that member overrides a * concrete one. * * Parameters: * 0: the name of the first member * 1: the name of the second member * 2: the name of the third member * 3: the name of the fourth member * 4: the number of additional missing members that aren't listed */ static const StaticWarningCode NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS = const StaticWarningCode( 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS', "Missing concrete implementations of {0}, {1}, {2}, {3} and {4} " "more.", correction: "Try implementing the missing methods, or make the class " "abstract."); /** * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract * class inherits an abstract method. * * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not * declare its own <i>noSuchMethod()</i> method. It is a static warning if the * implicit interface of <i>C</i> includes an instance member <i>m</i> of type * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>. * * 7.4 Abstract Instance Members: It is a static warning if an abstract member * is declared or inherited in a concrete class unless that member overrides a * concrete one. * * Parameters: * 0: the name of the first member * 1: the name of the second member * 2: the name of the third member * 3: the name of the fourth member */ static const StaticWarningCode NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR = const StaticWarningCode( 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR', "Missing concrete implementations of {0}, {1}, {2} and {3}.", correction: "Try implementing the missing methods, or make the class " "abstract."); /** * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract * class inherits an abstract method. * * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not * declare its own <i>noSuchMethod()</i> method. It is a static warning if the * implicit interface of <i>C</i> includes an instance member <i>m</i> of type * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>. * * 7.4 Abstract Instance Members: It is a static warning if an abstract member * is declared or inherited in a concrete class unless that member overrides a * concrete one. * * Parameters: * 0: the name of the member */ static const StaticWarningCode NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE = const StaticWarningCode( 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE', "Missing concrete implementation of {0}.", correction: "Try implementing the missing method, or make the class " "abstract."); /** * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract * class inherits an abstract method. * * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not * declare its own <i>noSuchMethod()</i> method. It is a static warning if the * implicit interface of <i>C</i> includes an instance member <i>m</i> of type * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>. * * 7.4 Abstract Instance Members: It is a static warning if an abstract member * is declared or inherited in a concrete class unless that member overrides a * concrete one. * * Parameters: * 0: the name of the first member * 1: the name of the second member * 2: the name of the third member */ static const StaticWarningCode NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE = const StaticWarningCode( 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE', "Missing concrete implementations of {0}, {1} and {2}.", correction: "Try implementing the missing methods, or make the class " "abstract."); /** * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract * class inherits an abstract method. * * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not * declare its own <i>noSuchMethod()</i> method. It is a static warning if the * implicit interface of <i>C</i> includes an instance member <i>m</i> of type * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>. * * 7.4 Abstract Instance Members: It is a static warning if an abstract member * is declared or inherited in a concrete class unless that member overrides a * concrete one. * * Parameters: * 0: the name of the first member * 1: the name of the second member */ static const StaticWarningCode NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO = const StaticWarningCode( 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO', "Missing concrete implementations of {0} and {1}.", correction: "Try implementing the missing methods, or make the class " "abstract."); /** * 13.11 Try: An on-catch clause of the form <i>on T catch (p<sub>1</sub>, * p<sub>2</sub>) s</i> or <i>on T s</i> matches an object <i>o</i> if the * type of <i>o</i> is a subtype of <i>T</i>. It is a static warning if * <i>T</i> does not denote a type available in the lexical scope of the * catch clause. * * Parameters: * 0: the name of the non-type element */ static const StaticWarningCode NON_TYPE_IN_CATCH_CLAUSE = const StaticWarningCode( 'NON_TYPE_IN_CATCH_CLAUSE', "The name '{0}' isn't a type and can't be used in an on-catch " "clause.", correction: "Try correcting the name to match an existing class."); /** * 7.1.1 Operators: It is a static warning if the return type of the * user-declared operator []= is explicitly declared and not void. */ static const StaticWarningCode NON_VOID_RETURN_FOR_OPERATOR = const StaticWarningCode('NON_VOID_RETURN_FOR_OPERATOR', "The return type of the operator []= must be 'void'.", correction: "Try changing the return type to 'void'."); /** * 7.3 Setters: It is a static warning if a setter declares a return type * other than void. */ static const StaticWarningCode NON_VOID_RETURN_FOR_SETTER = const StaticWarningCode('NON_VOID_RETURN_FOR_SETTER', "The return type of the setter must be 'void' or absent.", correction: "Try removing the return type, or " "define a method rather than a setter."); /** * Parameters: * 0: the name that is not a type */ // #### Description // // The analyzer produces this diagnostic when a name is used as a type but // declared to be something other than a type. // // #### Example // // The following code produces this diagnostic because `f` is a function: // // ```dart // f() {} // g([!f!] v) {} // ``` // // #### Common fixes // // Replace the name with the name of a type. static const StaticWarningCode NOT_A_TYPE = const StaticWarningCode( 'NOT_A_TYPE', "{0} isn't a type.", correction: "Try correcting the name to match an existing type.", hasPublishedDocs: true); @Deprecated('Use CompileTimeErrorCode.NOT_ENOUGH_POSITIONAL_ARGUMENTS') static const CompileTimeErrorCode NOT_ENOUGH_REQUIRED_ARGUMENTS = CompileTimeErrorCode.NOT_ENOUGH_POSITIONAL_ARGUMENTS; /** * 14.3 Parts: It is a static warning if the referenced part declaration * <i>p</i> names a library other than the current library as the library to * which <i>p</i> belongs. * * Parameters: * 0: the name of expected library name * 1: the non-matching actual library name from the "part of" declaration */ static const StaticWarningCode PART_OF_DIFFERENT_LIBRARY = const StaticWarningCode('PART_OF_DIFFERENT_LIBRARY', "Expected this library to be part of '{0}', not '{1}'.", correction: "Try including a different part, or changing the name of " "the library in the part's part-of directive."); /** * 7.6.2 Factories: It is a static warning if the function type of <i>k'</i> * is not a subtype of the type of <i>k</i>. * * Parameters: * 0: the name of the redirected constructor * 1: the name of the redirecting constructor */ static const StaticWarningCode REDIRECT_TO_INVALID_FUNCTION_TYPE = const StaticWarningCode( 'REDIRECT_TO_INVALID_FUNCTION_TYPE', "The redirected constructor '{0}' has incompatible parameters with " "'{1}'.", correction: "Try redirecting to a different constructor, or directly " "invoking the desired constructor rather than redirecting to " "it."); /** * 7.6.2 Factories: It is a static warning if the function type of <i>k'</i> * is not a subtype of the type of <i>k</i>. * * Parameters: * 0: the name of the redirected constructor's return type * 1: the name of the redirecting constructor's return type */ static const StaticWarningCode REDIRECT_TO_INVALID_RETURN_TYPE = const StaticWarningCode( 'REDIRECT_TO_INVALID_RETURN_TYPE', "The return type '{0}' of the redirected constructor isn't " "assignable to '{1}'.", correction: "Try redirecting to a different constructor, or directly " "invoking the desired constructor rather than redirecting to " "it."); @Deprecated('Use CompileTimeErrorCode.REDIRECT_TO_MISSING_CONSTRUCTOR') static const CompileTimeErrorCode REDIRECT_TO_MISSING_CONSTRUCTOR = CompileTimeErrorCode.REDIRECT_TO_MISSING_CONSTRUCTOR; @Deprecated('Use CompileTimeErrorCode.REDIRECT_TO_NON_CLASS') static const CompileTimeErrorCode REDIRECT_TO_NON_CLASS = CompileTimeErrorCode.REDIRECT_TO_NON_CLASS; /** * 13.12 Return: Let <i>f</i> be the function immediately enclosing a return * statement of the form <i>return;</i> It is a static warning if both of the * following conditions hold: * * <i>f</i> is not a generative constructor. * * The return type of <i>f</i> may not be assigned to void. */ static const StaticWarningCode RETURN_WITHOUT_VALUE = const StaticWarningCode( 'RETURN_WITHOUT_VALUE', "Missing return value after 'return'."); /** * Parameters: * 0: the actual type of the set element * 1: the expected type of the set element */ static const StaticWarningCode SET_ELEMENT_TYPE_NOT_ASSIGNABLE = const StaticWarningCode('SET_ELEMENT_TYPE_NOT_ASSIGNABLE', "The element type '{0}' can't be assigned to the set type '{1}'."); /** * 12.16.3 Static Invocation: It is a static warning if <i>C</i> does not * declare a static method or getter <i>m</i>. * * Parameters: * 0: the name of the instance member */ static const StaticWarningCode STATIC_ACCESS_TO_INSTANCE_MEMBER = const StaticWarningCode('STATIC_ACCESS_TO_INSTANCE_MEMBER', "Instance member '{0}' can't be accessed using static access."); /** * 13.9 Switch: It is a static warning if the type of <i>e</i> may not be * assigned to the type of <i>e<sub>k</sub></i>. */ static const StaticWarningCode SWITCH_EXPRESSION_NOT_ASSIGNABLE = const StaticWarningCode( 'SWITCH_EXPRESSION_NOT_ASSIGNABLE', "Type '{0}' of the switch expression isn't assignable to " "the type '{1}' of case expressions."); /** * 15.1 Static Types: It is a static warning to use a deferred type in a type * annotation. * * Parameters: * 0: the name of the type that is deferred and being used in a type * annotation */ static const StaticWarningCode TYPE_ANNOTATION_DEFERRED_CLASS = const StaticWarningCode( 'TYPE_ANNOTATION_DEFERRED_CLASS', "The deferred type '{0}' can't be used in a declaration, cast or " "type test.", correction: "Try using a different type, or " "changing the import to not be deferred."); /** * 12.31 Type Test: It is a static warning if <i>T</i> does not denote a type * available in the current lexical scope. */ static const StaticWarningCode TYPE_TEST_WITH_NON_TYPE = const StaticWarningCode( 'TYPE_TEST_WITH_NON_TYPE', "The name '{0}' isn't a type and can't be used in an 'is' " "expression.", correction: "Try correcting the name to match an existing type."); /** * No parameters. */ // #### Description // // The analyzer produces this diagnostic when the name following the `is` in a // type test expression isn't defined. // // #### Example // // The following code produces this diagnostic: // // ```dart // void f(Object o) { // if (o is [!Srting!]) { // // ... // } // } // ``` // // #### Common fixes // // Replace the name with the name of a type: // // ```dart // void f(Object o) { // if (o is String) { // // ... // } // } // ``` static const StaticWarningCode TYPE_TEST_WITH_UNDEFINED_NAME = const StaticWarningCode( 'TYPE_TEST_WITH_UNDEFINED_NAME', "The name '{0}' isn't defined, so it can't be used in an 'is' " "expression.", correction: "Try changing the name to the name of an existing type, or " "creating a type with the name '{0}'.", hasPublishedDocs: true); /** * 10 Generics: However, a type parameter is considered to be a malformed type * when referenced by a static member. * * 15.1 Static Types: Any use of a malformed type gives rise to a static * warning. A malformed type is then interpreted as dynamic by the static type * checker and the runtime. */ static const StaticWarningCode TYPE_PARAMETER_REFERENCED_BY_STATIC = const StaticWarningCode('TYPE_PARAMETER_REFERENCED_BY_STATIC', "Static members can't reference type parameters of the class.", correction: "Try removing the reference to the type parameter, or " "making the member an instance member."); @Deprecated('Use CompileTimeErrorCode.UNDEFINED_CLASS') static const CompileTimeErrorCode UNDEFINED_CLASS = CompileTimeErrorCode.UNDEFINED_CLASS; /** * Same as [CompileTimeErrorCode.UNDEFINED_CLASS], but to catch using * "boolean" instead of "bool". */ static const StaticWarningCode UNDEFINED_CLASS_BOOLEAN = const StaticWarningCode( 'UNDEFINED_CLASS_BOOLEAN', "Undefined class 'boolean'.", correction: "Try using the type 'bool'."); /** * Parameters: * 0: the name of the identifier */ // #### Description // // The analyzer produces this diagnostic when it encounters an identifier that // either isn't defined or isn't visible in the scope in which it's being // referenced. // // #### Example // // The following code produces this diagnostic: // // ```dart // int min(int left, int right) => left <= [!rihgt!] ? left : right; // ``` // // #### Common fixes // // If the identifier isn't defined, then either define it or replace it with // an identifier that is defined. The example above can be corrected by // fixing the spelling of the variable: // // ```dart // int min(int left, int right) => left <= right ? left : right; // ``` // // If the identifier is defined but isn't visible, then you probably need to // add an import or re-arrange your code to make the identifier visible. static const StaticWarningCode UNDEFINED_IDENTIFIER = const StaticWarningCode('UNDEFINED_IDENTIFIER', "Undefined name '{0}'.", correction: "Try correcting the name to one that is defined, or " "defining the name.", hasPublishedDocs: true, isUnresolvedIdentifier: true); /** * If the identifier is 'await', be helpful about it. */ static const StaticWarningCode UNDEFINED_IDENTIFIER_AWAIT = const StaticWarningCode('UNDEFINED_IDENTIFIER_AWAIT', "Undefined name 'await' in function body not marked with 'async'.", correction: "Try correcting the name to one that is defined, " "defining the name, or " "adding 'async' to the enclosing function body."); @Deprecated('Use CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER') static const CompileTimeErrorCode UNDEFINED_NAMED_PARAMETER = CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER; /** * For the purposes of experimenting with potential non-null type semantics. * * Parameters: none */ static const StaticWarningCode UNCHECKED_USE_OF_NULLABLE_VALUE = const StaticWarningCode( 'UNCHECKED_USE_OF_NULLABLE_VALUE', "The expression is nullable and must be null-checked before it can " "be used.", correction: "Try checking that the value isn't null before using it."); /** * When the '!' operator is used on a value that we know to be non-null, * it is unnecessary. */ static const StaticWarningCode UNNECESSARY_NON_NULL_ASSERTION = const StaticWarningCode( 'UNNECESSARY_NON_NULL_ASSERTION', "The '!' will have no effect because the target expression cannot be" " null.", correction: "Try removing the '!' operator here."); /** * When the '...?' operator is used on a value that we know to be non-null, * it is unnecessary. */ static const StaticWarningCode UNNECESSARY_NULL_AWARE_SPREAD = const StaticWarningCode( 'UNNECESSARY_NULL_AWARE_SPREAD', "The target expression can't be null, so it isn't necessary to use " "the null-aware spread operator '...?'.", correction: "Try replacing the '...?' with a '...' in the spread."); /** * For the purposes of experimenting with potential non-null type semantics. * * Whereas [UNCHECKED_USE_OF_NULLABLE] refers to using a value of type T? as * if it were a T, this refers to using a value of type [Null] itself. These * occur at many of the same times ([Null] is a potentially nullable type) but * it indicates a different type of programmer error and has different * corrections. * * Parameters: none */ static const StaticWarningCode INVALID_USE_OF_NULL_VALUE = const StaticWarningCode('INVALID_USE_OF_NULL_VALUE', "This expression is invalid as it will always be null.", correction: "Try changing the type, or casting, to a more useful type like " "dynamic."); /** * It is an error to call a method or getter on an expression of type `Never`, * or to invoke it as if it were a function. * * Go out of our way to provide a *little* more information here because many * dart users probably have never heard of the type Never. Be careful however * of providing too much information or it only becomes more confusing. Hard * balance to strike. * * Parameters: none */ static const StaticWarningCode INVALID_USE_OF_NEVER_VALUE = const StaticWarningCode( 'INVALID_USE_OF_NEVER_VALUE', 'This expression is invalid because its target is of type Never and' ' will never complete with a value', correction: 'Try checking for throw expressions or type errors in the' ' target expression'); /** * When the '?.' operator is used on a target that we know to be non-null, * it is unnecessary. */ static const StaticWarningCode UNNECESSARY_NULL_AWARE_CALL = const StaticWarningCode('UNNECESSARY_NULL_AWARE_CALL', "The target expression can't be null, and so '?.' isn't necessary.", correction: "Try replacing the '?.' with a '.' in the invocation."); /** * It is a static warning to assign void to any non-void type in dart. * compile-time error). Report that error specially for a better user * experience. * * Parameters: none */ static const StaticWarningCode USE_OF_VOID_RESULT = const StaticWarningCode( 'USE_OF_VOID_RESULT', "The expression here has a type of 'void', and therefore can't be used.", correction: "Try checking to see if you're using the correct API; there might " "be a function or call that returns void you didn't expect. Also " "check type parameters and variables which might also be void."); @override final ErrorSeverity errorSeverity; /** * Initialize a newly created error code to have the given [name]. The message * associated with the error will be created from the given [message] * template. The correction associated with the error will be created from the * given [correction] template. */ const StaticWarningCode(String name, String message, {String correction, this.errorSeverity = ErrorSeverity.ERROR, bool hasPublishedDocs, bool isUnresolvedIdentifier: false}) : super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs, isUnresolvedIdentifier: isUnresolvedIdentifier); @override ErrorType get type => ErrorType.STATIC_WARNING; } /** * This class has Strong Mode specific error codes. * * "Strong Mode" was the prototype for Dart 2's sound type system. Many of these * errors became part of Dart 2. Some of them are optional flags, used for * stricter checking. * * These error codes tend to use the same message across different severity * levels, so they are grouped for clarity. */ class StrongModeCode extends ErrorCode { static const String _implicitCastMessage = "Unsafe implicit cast from '{0}' to '{1}'. " "This usually indicates that type information was lost and resulted in " "'dynamic' and/or a place that will have a failure at runtime."; static const String _implicitCastCorrection = "Try adding an explicit cast to '{1}' or improving the type of '{0}'."; /** * This is appended to the end of an error message about implicit dynamic. * * The idea is to make sure the user is aware that this error message is the * result of turning on a particular option, and they are free to turn it * back off. */ static const String _implicitDynamicCorrection = "Try adding an explicit type like 'dynamic', or " "enable implicit-dynamic in your analysis options file."; static const String _inferredTypeMessage = "'{0}' has inferred type '{1}'."; static const StrongModeCode DOWN_CAST_COMPOSITE = const StrongModeCode( ErrorType.HINT, 'DOWN_CAST_COMPOSITE', _implicitCastMessage, correction: _implicitCastCorrection); static const StrongModeCode DOWN_CAST_IMPLICIT = const StrongModeCode( ErrorType.HINT, 'DOWN_CAST_IMPLICIT', _implicitCastMessage, correction: _implicitCastCorrection); static const StrongModeCode DOWN_CAST_IMPLICIT_ASSIGN = const StrongModeCode( ErrorType.HINT, 'DOWN_CAST_IMPLICIT_ASSIGN', _implicitCastMessage, correction: _implicitCastCorrection); static const StrongModeCode DYNAMIC_CAST = const StrongModeCode( ErrorType.HINT, 'DYNAMIC_CAST', _implicitCastMessage, correction: _implicitCastCorrection); static const StrongModeCode ASSIGNMENT_CAST = const StrongModeCode( ErrorType.HINT, 'ASSIGNMENT_CAST', _implicitCastMessage, correction: _implicitCastCorrection); static const StrongModeCode INVALID_PARAMETER_DECLARATION = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_PARAMETER_DECLARATION', "Type check failed: '{0}' isn't of type '{1}'."); static const StrongModeCode COULD_NOT_INFER = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'COULD_NOT_INFER', "Couldn't infer type parameter '{0}'.{1}"); static const StrongModeCode INFERRED_TYPE = const StrongModeCode( ErrorType.HINT, 'INFERRED_TYPE', _inferredTypeMessage); static const StrongModeCode INFERRED_TYPE_LITERAL = const StrongModeCode( ErrorType.HINT, 'INFERRED_TYPE_LITERAL', _inferredTypeMessage); static const StrongModeCode INFERRED_TYPE_ALLOCATION = const StrongModeCode( ErrorType.HINT, 'INFERRED_TYPE_ALLOCATION', _inferredTypeMessage); static const StrongModeCode INFERRED_TYPE_CLOSURE = const StrongModeCode( ErrorType.HINT, 'INFERRED_TYPE_CLOSURE', _inferredTypeMessage); static const StrongModeCode INVALID_CAST_LITERAL = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_LITERAL', "The literal '{0}' with type '{1}' isn't of expected type '{2}'."); static const StrongModeCode INVALID_CAST_LITERAL_LIST = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_LITERAL_LIST', "The list literal type '{0}' isn't of expected type '{1}'. The list's " "type can be changed with an explicit generic type argument or by " "changing the element types."); static const StrongModeCode INVALID_CAST_LITERAL_MAP = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_LITERAL_MAP', "The map literal type '{0}' isn't of expected type '{1}'. The maps's " "type can be changed with an explicit generic type arguments or by " "changing the key and value types."); static const StrongModeCode INVALID_CAST_LITERAL_SET = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_LITERAL_SET', "The set literal type '{0}' isn't of expected type '{1}'. The set's " "type can be changed with an explicit generic type argument or by " "changing the element types."); static const StrongModeCode INVALID_CAST_FUNCTION_EXPR = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_FUNCTION_EXPR', "The function expression type '{0}' isn't of type '{1}'. " "This means its parameter or return type doesn't match what is " "expected. Consider changing parameter type(s) or the returned " "type(s)."); static const StrongModeCode INVALID_CAST_NEW_EXPR = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_NEW_EXPR', "The constructor returns type '{0}' that isn't of expected type '{1}'."); static const StrongModeCode INVALID_CAST_METHOD = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_METHOD', "The method tear-off '{0}' has type '{1}' that isn't of expected type " "'{2}'. This means its parameter or return type doesn't match what " "is expected."); static const StrongModeCode INVALID_CAST_FUNCTION = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_CAST_FUNCTION', "The function '{0}' has type '{1}' that isn't of expected type " "'{2}'. This means its parameter or return type doesn't match what " "is expected."); static const StrongModeCode INVALID_SUPER_INVOCATION = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'INVALID_SUPER_INVOCATION', "The super call must be last in an initializer " "list (see https://goo.gl/EY6hDP): '{0}'."); static const StrongModeCode NON_GROUND_TYPE_CHECK_INFO = const StrongModeCode( ErrorType.HINT, 'NON_GROUND_TYPE_CHECK_INFO', "Runtime check on non-ground type '{0}' may throw StrongModeError."); static const StrongModeCode DYNAMIC_INVOKE = const StrongModeCode( ErrorType.HINT, 'DYNAMIC_INVOKE', "'{0}' requires a dynamic invoke."); static const StrongModeCode IMPLICIT_DYNAMIC_PARAMETER = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_PARAMETER', "Missing parameter type for '{0}'.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_RETURN = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_RETURN', "Missing return type for '{0}'.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_VARIABLE = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_VARIABLE', "Missing variable type for '{0}'.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_FIELD = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_FIELD', "Missing field type for '{0}'.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_TYPE = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_TYPE', "Missing type arguments for generic type '{0}'.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_LIST_LITERAL = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_LIST_LITERAL', "Missing type argument for list literal.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_MAP_LITERAL = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_MAP_LITERAL', "Missing type arguments for map literal.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_FUNCTION = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_FUNCTION', "Missing type arguments for generic function '{0}<{1}>'.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_METHOD = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_METHOD', "Missing type arguments for generic method '{0}<{1}>'.", correction: _implicitDynamicCorrection); static const StrongModeCode IMPLICIT_DYNAMIC_INVOKE = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'IMPLICIT_DYNAMIC_INVOKE', "Missing type arguments for calling generic function type '{0}'.", correction: _implicitDynamicCorrection); static const StrongModeCode NOT_INSTANTIATED_BOUND = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'NOT_INSTANTIATED_BOUND', "Type parameter bound types must be instantiated.", correction: "Try adding type arguments."); /* * TODO(brianwilkerson) Make the TOP_LEVEL_ error codes be errors rather than * hints and then clean up the function _errorSeverity in * test/src/task/strong/strong_test_helper.dart. */ /* TODO(leafp) Delete most of these. */ static const StrongModeCode TOP_LEVEL_CYCLE = const StrongModeCode( ErrorType.COMPILE_TIME_ERROR, 'TOP_LEVEL_CYCLE', "The type of '{0}' can't be inferred because it depends on itself " "through the cycle: {1}.", correction: "Try adding an explicit type to one or more of the variables in the " "cycle in order to break the cycle."); static const StrongModeCode TOP_LEVEL_FUNCTION_LITERAL_BLOCK = const StrongModeCode( ErrorType.HINT, 'TOP_LEVEL_FUNCTION_LITERAL_BLOCK', "The type of the function literal can't be inferred because the " "literal has a block as its body.", correction: "Try adding an explicit type to the variable."); static const StrongModeCode TOP_LEVEL_IDENTIFIER_NO_TYPE = const StrongModeCode( ErrorType.HINT, 'TOP_LEVEL_IDENTIFIER_NO_TYPE', "The type of '{0}' can't be inferred because the type of '{1}' " "couldn't be inferred.", correction: "Try adding an explicit type to either the variable '{0}' or the " "variable '{1}'."); static const StrongModeCode TOP_LEVEL_INSTANCE_GETTER = const StrongModeCode( ErrorType.STATIC_WARNING, 'TOP_LEVEL_INSTANCE_GETTER', "The type of '{0}' can't be inferred because it refers to an instance " "getter, '{1}', which has an implicit type.", correction: "Add an explicit type for either '{0}' or '{1}'."); static const StrongModeCode TOP_LEVEL_INSTANCE_METHOD = const StrongModeCode( ErrorType.STATIC_WARNING, 'TOP_LEVEL_INSTANCE_METHOD', "The type of '{0}' can't be inferred because it refers to an instance " "method, '{1}', which has an implicit type.", correction: "Add an explicit type for either '{0}' or '{1}'."); @override final ErrorType type; /** * Initialize a newly created error code to have the given [type] and [name]. * * The message associated with the error will be created from the given * [message] template. The correction associated with the error will be * created from the optional [correction] template. */ const StrongModeCode(ErrorType type, String name, String message, {String correction, bool hasPublishedDocs}) : type = type, super.temporary(name, message, correction: correction, hasPublishedDocs: hasPublishedDocs ?? false); @override ErrorSeverity get errorSeverity => type.severity; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/services/lint.dart
// Copyright (c) 2015, 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/error/lint_codes.dart'; import 'package:analyzer/src/generated/engine.dart'; /// Shared lint registry. LintRegistry lintRegistry = new LintRegistry(); /// Current linter version. String linterVersion; /// Return lints associated with this [context], or an empty list if there are /// none. List<Linter> getLints(AnalysisContext context) => context.analysisOptions.lintRules; /// Associate these [lints] with the given [context]. void setLints(AnalysisContext context, List<Linter> lints) { AnalysisOptionsImpl options = new AnalysisOptionsImpl.from(context.analysisOptions); options.lintRules = lints; context.analysisOptions = options; } /// Implementers contribute lint warnings via the provided error [reporter]. abstract class Linter { /// Used to report lint warnings. /// NOTE: this is set by the framework before visit begins. ErrorReporter reporter; /** * Return the lint code associated with this linter. */ LintCode get lintCode => null; /// Linter name. String get name; /// Return a visitor to be passed to compilation units to perform lint /// analysis. /// Lint errors are reported via this [Linter]'s error [reporter]. AstVisitor getVisitor(); } /// Manages lint timing. class LintRegistry { /// Dictionary mapping lints (by name) to timers. final Map<String, Stopwatch> timers = new HashMap<String, Stopwatch>(); /// Get a timer associated with the given lint rule (or create one if none /// exists). Stopwatch getTimer(Linter linter) => timers.putIfAbsent(linter.name, () => new Stopwatch()); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/services/available_declarations.dart
// Copyright (c) 2019, 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 'dart:async'; import 'dart:collection'; import 'package:analyzer/dart/analysis/analysis_context.dart'; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/source/line_info.dart'; import 'package:analyzer/src/dart/analysis/byte_store.dart'; import 'package:analyzer/src/dart/analysis/session.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/ast/token.dart'; import 'package:analyzer/src/dart/scanner/reader.dart'; import 'package:analyzer/src/dart/scanner/scanner.dart'; import 'package:analyzer/src/dartdoc/dartdoc_directive_info.dart'; import 'package:analyzer/src/generated/parser.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:analyzer/src/string_source.dart'; import 'package:analyzer/src/summary/api_signature.dart'; import 'package:analyzer/src/summary/format.dart' as idl; import 'package:analyzer/src/summary/idl.dart' as idl; import 'package:analyzer/src/summary/link.dart' as graph show DependencyWalker, Node; import 'package:analyzer/src/util/comment.dart'; import 'package:convert/convert.dart'; import 'package:meta/meta.dart'; import 'package:yaml/yaml.dart'; /// A top-level public declaration. class Declaration { final List<Declaration> children; final int codeLength; final int codeOffset; final String defaultArgumentListString; final List<int> defaultArgumentListTextRanges; final String docComplete; final String docSummary; final bool isAbstract; final bool isConst; final bool isDeprecated; final bool isFinal; final DeclarationKind kind; final LineInfo lineInfo; final int locationOffset; final String locationPath; final int locationStartColumn; final int locationStartLine; final String name; final String parameters; final List<String> parameterNames; final List<String> parameterTypes; final Declaration parent; final int requiredParameterCount; final String returnType; final String typeParameters; List<String> _relevanceTags; Uri _locationLibraryUri; Declaration({ @required this.children, @required this.codeLength, @required this.codeOffset, @required this.defaultArgumentListString, @required this.defaultArgumentListTextRanges, @required this.docComplete, @required this.docSummary, @required this.isAbstract, @required this.isConst, @required this.isDeprecated, @required this.isFinal, @required this.kind, @required this.lineInfo, @required this.locationOffset, @required this.locationPath, @required this.locationStartColumn, @required this.locationStartLine, @required this.name, @required this.parameters, @required this.parameterNames, @required this.parameterTypes, @required this.parent, @required List<String> relevanceTags, @required this.requiredParameterCount, @required this.returnType, @required this.typeParameters, }) : _relevanceTags = relevanceTags; Uri get locationLibraryUri => _locationLibraryUri; List<String> get relevanceTags => _relevanceTags; @override String toString() { return '($kind, $name)'; } } /// A kind of a top-level declaration. enum DeclarationKind { CLASS, CLASS_TYPE_ALIAS, CONSTRUCTOR, ENUM, ENUM_CONSTANT, EXTENSION, FIELD, FUNCTION, FUNCTION_TYPE_ALIAS, GETTER, METHOD, MIXIN, SETTER, VARIABLE } /// The context in which completions happens, so declarations are collected. class DeclarationsContext { final DeclarationsTracker _tracker; /// The analysis context for this context. Declarations from all files in /// the root are included into completion, even in 'lib/src' folders. final AnalysisContext _analysisContext; /// Packages in the analysis context. /// /// Packages are sorted so that inner packages are before outer. final List<_Package> _packages = []; /// The list of paths of all files inside the context. final List<String> _contextPathList = []; /// The list of paths of all SDK libraries. final List<String> _sdkLibraryPathList = []; /// The combined information about all of the dartdoc directives in this /// context. final DartdocDirectiveInfo _dartdocDirectiveInfo = new DartdocDirectiveInfo(); /// Map of path prefixes to lists of paths of files from dependencies /// (both libraries and parts, we don't know at the time when we fill this /// map) that libraries with paths starting with these prefixes can access. /// /// The path prefix keys are sorted so that the longest keys are first. final Map<String, List<String>> _pathPrefixToDependencyPathList = {}; /// The set of paths of already checked known files, some of which were /// added to [_knownPathList]. For example we skip non-API files. final Set<String> _knownPathSet = Set<String>(); /// The list of paths of files known to this context - from the context /// itself, from direct dependencies, from indirect dependencies. /// /// We include libraries from this list only when actual context dependencies /// are not known. Dependencies are always know for Pub packages, but are /// currently never known for Bazel packages. final List<String> _knownPathList = []; DeclarationsContext(this._tracker, this._analysisContext); /// Return the combined information about all of the dartdoc directives in /// this context. DartdocDirectiveInfo get dartdocDirectiveInfo => _dartdocDirectiveInfo; /// The set of features that are globally enabled for this context. FeatureSet get featureSet { return _analysisContext.analysisOptions.contextFeatures; } /// Return libraries that are available to the file with the given [path]. /// /// With `Pub`, files below the `pubspec.yaml` file can access libraries /// of packages listed as `dependencies`, and files in the `test` directory /// can in addition access libraries of packages listed as `dev_dependencies`. /// /// With `Bazel` sets of accessible libraries are specified explicitly by /// the client using [setDependencies]. Libraries getLibraries(String path) { var sdkLibraries = <Library>[]; _addLibrariesWithPaths(sdkLibraries, _sdkLibraryPathList); var dependencyLibraries = <Library>[]; for (var pathPrefix in _pathPrefixToDependencyPathList.keys) { if (path.startsWith(pathPrefix)) { var pathList = _pathPrefixToDependencyPathList[pathPrefix]; _addLibrariesWithPaths(dependencyLibraries, pathList); break; } } if (_pathPrefixToDependencyPathList.isEmpty) { _addLibrariesWithPaths(dependencyLibraries, _knownPathList); } _Package package; for (var candidatePackage in _packages) { if (candidatePackage.contains(path)) { package = candidatePackage; break; } } var contextPathList = <String>[]; if (package != null) { var containingFolder = package.folderInRootContaining(path); if (containingFolder != null) { for (var contextPath in _contextPathList) { // `lib/` can see only libraries in `lib/`. // `test/` can see libraries in `lib/` and in `test/`. if (package.containsInLib(contextPath) || containingFolder.contains(contextPath)) { contextPathList.add(contextPath); } } } } else { // Not in a package, include all libraries of the context. contextPathList = _contextPathList; } var contextLibraries = <Library>[]; _addLibrariesWithPaths( contextLibraries, contextPathList, excludingLibraryOfPath: path, ); return Libraries(sdkLibraries, dependencyLibraries, contextLibraries); } /// Set dependencies for path prefixes in this context. /// /// The map [pathPrefixToPathList] specifies the list of paths of libraries /// and directories with libraries that are accessible to the files with /// paths that start with the path that is the key in the map. The longest /// (so most specific) key will be used, each list of paths is complete, and /// is not combined with any enclosing locations. /// /// For `Pub` packages this method is invoked automatically, because their /// dependencies, described in `pubspec.yaml` files, and can be automatically /// included. This method is useful for `Bazel` contexts, where dependencies /// are specified externally, in form of `BUILD` files. /// /// New dependencies will replace any previously set dependencies for this /// context. /// /// Every path in the list must be absolute and normalized. void setDependencies(Map<String, List<String>> pathPrefixToPathList) { var rootFolder = _analysisContext.contextRoot.root; _pathPrefixToDependencyPathList.removeWhere((pathPrefix, _) { return rootFolder.isOrContains(pathPrefix); }); var sortedPrefixes = pathPrefixToPathList.keys.toList(); sortedPrefixes.sort((a, b) { return b.compareTo(a); }); for (var pathPrefix in sortedPrefixes) { var pathList = pathPrefixToPathList[pathPrefix]; var files = <String>[]; for (var path in pathList) { var resource = _tracker._resourceProvider.getResource(path); _scheduleDependencyResource(files, resource); } _pathPrefixToDependencyPathList[pathPrefix] = files; } } void _addContextFile(String path) { if (!_contextPathList.contains(path)) { _contextPathList.add(path); } } void _addLibrariesWithPaths(List<Library> libraries, List<String> pathList, {String excludingLibraryOfPath}) { var excludedFile = _tracker._pathToFile[excludingLibraryOfPath]; var excludedLibraryPath = (excludedFile?.library ?? excludedFile)?.path; for (var path in pathList) { if (path == excludedLibraryPath) continue; var file = _tracker._pathToFile[path]; if (file != null && file.isLibrary) { var library = _tracker._idToLibrary[file.id]; if (library != null) { libraries.add(library); } } } } /// Traverse the folders of this context and fill [_packages]; use /// `pubspec.yaml` files to set `Pub` dependencies. void _findPackages() { var pathContext = _tracker._resourceProvider.pathContext; var pubPathPrefixToPathList = <String, List<String>>{}; void visitFolder(Folder folder) { var buildFile = folder.getChildAssumingFile('BUILD'); var pubspecFile = folder.getChildAssumingFile('pubspec.yaml'); if (buildFile.exists) { _packages.add(_Package(folder)); } else if (pubspecFile.exists) { var dependencies = _parsePubspecDependencies(pubspecFile); var libPaths = _resolvePackageNamesToLibPaths(dependencies.lib); var devPaths = _resolvePackageNamesToLibPaths(dependencies.dev); var packagePath = folder.path; pubPathPrefixToPathList[packagePath] = <String>[] ..addAll(libPaths) ..addAll(devPaths); var libPath = pathContext.join(packagePath, 'lib'); pubPathPrefixToPathList[libPath] = libPaths; _packages.add(_Package(folder)); } try { for (var resource in folder.getChildren()) { if (resource is Folder) { visitFolder(resource); } } } on FileSystemException {} } visitFolder(_analysisContext.contextRoot.root); setDependencies(pubPathPrefixToPathList); _packages.sort((a, b) { var aRoot = a.root.path; var bRoot = b.root.path; return bRoot.compareTo(aRoot); }); } bool _isLibSrcPath(String path) { var parts = _tracker._resourceProvider.pathContext.split(path); for (var i = 0; i < parts.length - 1; ++i) { if (parts[i] == 'lib' && parts[i + 1] == 'src') return true; } return false; } List<String> _resolvePackageNamesToLibPaths(List<String> packageNames) { return packageNames .map(_resolvePackageNameToLibPath) .where((path) => path != null) .toList(); } String _resolvePackageNameToLibPath(String packageName) { try { var uri = Uri.parse('package:$packageName/ref.dart'); var path = _resolveUri(uri); if (path == null) return null; return _tracker._resourceProvider.pathContext.dirname(path); } on FormatException { return null; } } String _resolveUri(Uri uri) { var uriConverter = _analysisContext.currentSession.uriConverter; return uriConverter.uriToPath(uri); } Uri _restoreUri(String path) { var uriConverter = _analysisContext.currentSession.uriConverter; return uriConverter.pathToUri(path); } void _scheduleContextFiles() { var contextFiles = _analysisContext.contextRoot.analyzedFiles(); for (var path in contextFiles) { _contextPathList.add(path); _tracker._addFile(this, path); } } void _scheduleDependencyFolder(List<String> files, Folder folder) { if (_isLibSrcPath(folder.path)) return; try { for (var resource in folder.getChildren()) { _scheduleDependencyResource(files, resource); } } on FileSystemException catch (_) {} } void _scheduleDependencyResource(List<String> files, Resource resource) { if (resource is File) { files.add(resource.path); _tracker._addFile(this, resource.path); } else if (resource is Folder) { _scheduleDependencyFolder(files, resource); } } void _scheduleKnownFiles() { var session = _analysisContext.currentSession as AnalysisSessionImpl; // ignore: deprecated_member_use_from_same_package var analysisDriver = session.getDriver(); for (var path in analysisDriver.knownFiles) { if (_knownPathSet.add(path)) { if (!path.contains(r'/lib/src/') && !path.contains(r'\lib\src\')) { _knownPathList.add(path); _tracker._addFile(this, path); } } } } void _scheduleSdkLibraries() { // ignore: deprecated_member_use_from_same_package var sdk = _analysisContext.currentSession.sourceFactory.dartSdk; for (var uriStr in sdk.uris) { if (!uriStr.startsWith('dart:_')) { var uri = Uri.parse(uriStr); var path = _resolveUri(uri); if (path != null) { _sdkLibraryPathList.add(path); _tracker._addFile(this, path); } } } } static _PubspecDependencies _parsePubspecDependencies(File pubspecFile) { var dependencies = <String>[]; var devDependencies = <String>[]; try { var fileContent = pubspecFile.readAsStringSync(); var document = loadYamlDocument(fileContent); var contents = document.contents; if (contents is YamlMap) { var dependenciesNode = contents.nodes['dependencies']; if (dependenciesNode is YamlMap) { dependencies = dependenciesNode.keys.whereType<String>().toList(); } var devDependenciesNode = contents.nodes['dev_dependencies']; if (devDependenciesNode is YamlMap) { devDependencies = devDependenciesNode.keys.whereType<String>().toList(); } } } catch (e) {} return _PubspecDependencies(dependencies, devDependencies); } } /// Tracker for top-level declarations across multiple analysis contexts /// and their dependencies. class DeclarationsTracker { final ByteStore _byteStore; final ResourceProvider _resourceProvider; final Map<AnalysisContext, DeclarationsContext> _contexts = {}; final Map<String, _File> _pathToFile = {}; final Map<Uri, _File> _uriToFile = {}; final Map<int, Library> _idToLibrary = {}; final _changesController = _StreamController<LibraryChange>(); /// The list of changed file paths. final List<String> _changedPaths = []; /// The list of files scheduled for processing. It may include parts and /// libraries, but parts are ignored when we detect them. final List<_ScheduledFile> _scheduledFiles = []; /// The time when known files were last pulled. DateTime _whenKnownFilesPulled = DateTime.fromMillisecondsSinceEpoch(0); DeclarationsTracker(this._byteStore, this._resourceProvider); /// Return all known libraries. Iterable<Library> get allLibraries { return _idToLibrary.values; } /// The stream of changes to the set of libraries used by the added contexts. Stream<LibraryChange> get changes => _changesController.stream; /// Return `true` if there is scheduled work to do, as a result of adding /// new contexts, or changes to files. bool get hasWork { var now = DateTime.now(); if (now.difference(_whenKnownFilesPulled).inSeconds > 1) { _whenKnownFilesPulled = now; _pullKnownFiles(); } return _changedPaths.isNotEmpty || _scheduledFiles.isNotEmpty; } /// Add the [analysisContext], so that its libraries are reported via the /// [changes] stream, and return the [DeclarationsContext] that can be used /// to set additional dependencies and request libraries available to this /// context. DeclarationsContext addContext(AnalysisContext analysisContext) { if (_contexts.containsKey(analysisContext)) { throw StateError('The analysis context has already been added.'); } var declarationsContext = DeclarationsContext(this, analysisContext); _contexts[analysisContext] = declarationsContext; declarationsContext._scheduleContextFiles(); declarationsContext._scheduleSdkLibraries(); declarationsContext._findPackages(); return declarationsContext; } /// The file with the given [path] was changed - added, updated, or removed. /// /// The [path] must be absolute and normalized. /// /// Usually causes [hasWork] to return `true`, so that [doWork] should /// be invoked to send updates to [changes] that reflect changes to the /// library of the file, and other libraries that export it. void changeFile(String path) { if (!path.endsWith('.dart')) return; _changedPaths.add(path); } /// Discard the [analysisContext], but don't discard any libraries that it /// might have in its dependencies. void discardContext(AnalysisContext analysisContext) { _contexts.remove(analysisContext); } /// Discard all contexts and libraries, notify the [changes] stream that /// these libraries are removed. void discardContexts() { var libraryIdList = _idToLibrary.keys.toList(); _changesController.add(LibraryChange._([], libraryIdList)); _contexts.clear(); _pathToFile.clear(); _uriToFile.clear(); _idToLibrary.clear(); _changedPaths.clear(); _scheduledFiles.clear(); } /// Do a single piece of work. /// /// The client should call this method until [hasWork] returns `false`. /// This would mean that all previous changes have been processed, and /// updates scheduled to be delivered via the [changes] stream. void doWork() { if (_changedPaths.isNotEmpty) { var path = _changedPaths.removeLast(); _performChangeFile(path); return; } if (_scheduledFiles.isNotEmpty) { var scheduledFile = _scheduledFiles.removeLast(); var file = _getFileByPath(scheduledFile.context, scheduledFile.path); if (!file.isLibrary) return; if (file.isSent) { return; } else { file.isSent = true; } if (file.exportedDeclarations == null) { new _LibraryWalker().walkLibrary(file); assert(file.exportedDeclarations != null); } var library = Library._( file.id, file.path, file.uri, file.isLibraryDeprecated, file.exportedDeclarations ?? const [], ); _idToLibrary[file.id] = library; _changesController.add( LibraryChange._([library], []), ); } } /// Return the context associated with the given [analysisContext], or `null` /// if there is none. DeclarationsContext getContext(AnalysisContext analysisContext) { return _contexts[analysisContext]; } /// Return the library with the given [id], or `null` if there is none. Library getLibrary(int id) { return _idToLibrary[id]; } void _addFile(DeclarationsContext context, String path) { if (path.endsWith('.dart')) { _scheduledFiles.add(_ScheduledFile(context, path)); } } /// Compute exported declarations for the given [libraries]. void _computeExportedDeclarations(Set<_File> libraries) { var walker = new _LibraryWalker(); for (var library in libraries) { if (library.isLibrary && library.exportedDeclarations == null) { walker.walkLibrary(library); assert(library.exportedDeclarations != null); } } } DeclarationsContext _findContextOfPath(String path) { // Prefer the context in which the path is analyzed. for (var context in _contexts.values) { if (context._analysisContext.contextRoot.isAnalyzed(path)) { context._addContextFile(path); return context; } } // The path must have the URI with one of the supported URI schemes. for (var context in _contexts.values) { var uri = context._restoreUri(path); if (uri != null) { if (uri.isScheme('dart') || uri.isScheme('package')) { return context; } } } return null; } _File _getFileByPath(DeclarationsContext context, String path) { var file = _pathToFile[path]; if (file == null) { var uri = context._restoreUri(path); if (uri != null) { file = _File(this, path, uri); _pathToFile[path] = file; _uriToFile[uri] = file; file.refresh(context); } } return file; } _File _getFileByUri(DeclarationsContext context, Uri uri) { var file = _uriToFile[uri]; if (file == null) { var path = context._resolveUri(uri); if (path != null) { file = _File(this, path, uri); _pathToFile[path] = file; _uriToFile[uri] = file; file.refresh(context); } } return file; } /// Recursively invalidate exported declarations of the given [library] /// and libraries that export it. void _invalidateExportedDeclarations(Set<_File> libraries, _File library) { if (libraries.add(library)) { library.exportedDeclarations = null; for (var exporter in library.directExporters) { _invalidateExportedDeclarations(libraries, exporter); } } } void _performChangeFile(String path) { var containingContext = _findContextOfPath(path); if (containingContext == null) return; var file = _getFileByPath(containingContext, path); if (file == null) return; var wasLibrary = file.isLibrary; var oldLibrary = wasLibrary ? file : file.library; file.refresh(containingContext); var isLibrary = file.isLibrary; var newLibrary = isLibrary ? file : file.library; var invalidatedLibraries = Set<_File>(); var notLibraries = <_File>[]; if (wasLibrary) { if (isLibrary) { _invalidateExportedDeclarations(invalidatedLibraries, file); } else { notLibraries.add(file); if (newLibrary != null) { newLibrary.refresh(containingContext); _invalidateExportedDeclarations(invalidatedLibraries, newLibrary); } } } else { if (oldLibrary != null) { oldLibrary.refresh(containingContext); _invalidateExportedDeclarations(invalidatedLibraries, oldLibrary); } if (newLibrary != null && newLibrary != oldLibrary) { newLibrary.refresh(containingContext); _invalidateExportedDeclarations(invalidatedLibraries, newLibrary); } } _computeExportedDeclarations(invalidatedLibraries); var changedLibraries = <Library>[]; var removedLibraries = <int>[]; for (var libraryFile in invalidatedLibraries) { if (libraryFile.exists) { var library = Library._( libraryFile.id, libraryFile.path, libraryFile.uri, libraryFile.isLibraryDeprecated, libraryFile.exportedDeclarations ?? const [], ); _idToLibrary[library.id] = library; changedLibraries.add(library); } else { _idToLibrary.remove(libraryFile.id); removedLibraries.add(libraryFile.id); } } for (var file in notLibraries) { _idToLibrary.remove(file.id); removedLibraries.add(file.id); } _changesController.add( LibraryChange._(changedLibraries, removedLibraries), ); } /// Pull known files into [DeclarationsContext]s. /// /// This is a temporary support for Bazel repositories, because IDEA /// does not yet give us dependencies for them. void _pullKnownFiles() { for (var context in _contexts.values) { context._scheduleKnownFiles(); } } } class Libraries { final List<Library> sdk; final List<Library> dependencies; final List<Library> context; Libraries(this.sdk, this.dependencies, this.context); } /// A library with declarations. class Library { /// The unique identifier of a library with the given [path]. final int id; /// The path to the file that defines this library. final String path; /// The URI of the library. final Uri uri; /// Is `true` if the library has `@deprecated` annotation, so it probably /// deprecated. But we don't actually resolve the annotation, so it might be /// a false positive. final bool isDeprecated; /// All public declaration that the library declares or (re)exports. final List<Declaration> declarations; Library._(this.id, this.path, this.uri, this.isDeprecated, this.declarations); String get uriStr => '$uri'; @override String toString() { return '(id: $id, uri: $uri, path: $path)'; } } /// A change to the set of libraries and their declarations. class LibraryChange { /// The list of new or changed libraries. final List<Library> changed; /// The list of identifier of libraries that are removed, either because /// the corresponding files were removed, or because none of the contexts /// has these libraries as dependencies, so that they cannot be used anymore. final List<int> removed; LibraryChange._(this.changed, this.removed); } class RelevanceTags { static List<String> _forDeclaration(String uriStr, Declaration declaration) { switch (declaration.kind) { case DeclarationKind.CLASS: case DeclarationKind.CLASS_TYPE_ALIAS: case DeclarationKind.ENUM: case DeclarationKind.MIXIN: case DeclarationKind.FUNCTION_TYPE_ALIAS: var name = declaration.name; return <String>['$uriStr::$name']; case DeclarationKind.CONSTRUCTOR: var className = declaration.parent.name; return <String>['$uriStr::$className']; case DeclarationKind.ENUM_CONSTANT: var enumName = declaration.parent.name; return <String>['$uriStr::$enumName']; default: return null; } } static List<String> _forExpression(Expression expression) { if (expression is BooleanLiteral) { return const ['dart:core::bool']; } else if (expression is DoubleLiteral) { return const ['dart:core::double']; } else if (expression is IntegerLiteral) { return const ['dart:core::int']; } else if (expression is StringLiteral) { return const ['dart:core::String']; } else if (expression is ListLiteral) { return const ['dart:core::List']; } else if (expression is SetOrMapLiteral) { if (expression.isMap) { return const ['dart:core::Map']; } else if (expression.isSet) { return const ['dart:core::Set']; } } return null; } } class _DeclarationStorage { static const fieldDocMask = 1 << 0; static const fieldParametersMask = 1 << 1; static const fieldReturnTypeMask = 1 << 2; static const fieldTypeParametersMask = 1 << 3; static Declaration fromIdl(String path, LineInfo lineInfo, Declaration parent, idl.AvailableDeclaration d) { var fieldMask = d.fieldMask; var hasDoc = fieldMask & fieldDocMask != 0; var hasParameters = fieldMask & fieldParametersMask != 0; var hasReturnType = fieldMask & fieldReturnTypeMask != 0; var hasTypeParameters = fieldMask & fieldTypeParametersMask != 0; var kind = kindFromIdl(d.kind); var relevanceTags = d.relevanceTags.toList(); if (relevanceTags.isEmpty) { relevanceTags = null; } var children = <Declaration>[]; var declaration = Declaration( children: children, codeLength: d.codeLength, codeOffset: d.codeOffset, defaultArgumentListString: d.defaultArgumentListString.isNotEmpty ? d.defaultArgumentListString : null, defaultArgumentListTextRanges: d.defaultArgumentListTextRanges.isNotEmpty ? d.defaultArgumentListTextRanges : null, docComplete: hasDoc ? d.docComplete : null, docSummary: hasDoc ? d.docSummary : null, isAbstract: d.isAbstract, isConst: d.isConst, isDeprecated: d.isDeprecated, isFinal: d.isFinal, kind: kind, lineInfo: lineInfo, locationOffset: d.locationOffset, locationPath: path, locationStartColumn: d.locationStartColumn, locationStartLine: d.locationStartLine, name: d.name, parameters: hasParameters ? d.parameters : null, parameterNames: hasParameters ? d.parameterNames : null, parameterTypes: hasParameters ? d.parameterTypes.toList() : null, parent: parent, relevanceTags: relevanceTags, requiredParameterCount: hasParameters ? d.requiredParameterCount : null, returnType: hasReturnType ? d.returnType : null, typeParameters: hasTypeParameters ? d.typeParameters : null, ); for (var childIdl in d.children) { var child = fromIdl(path, lineInfo, declaration, childIdl); children.add(child); } return declaration; } static DeclarationKind kindFromIdl(idl.AvailableDeclarationKind kind) { switch (kind) { case idl.AvailableDeclarationKind.CLASS: return DeclarationKind.CLASS; case idl.AvailableDeclarationKind.CLASS_TYPE_ALIAS: return DeclarationKind.CLASS_TYPE_ALIAS; case idl.AvailableDeclarationKind.CONSTRUCTOR: return DeclarationKind.CONSTRUCTOR; case idl.AvailableDeclarationKind.ENUM: return DeclarationKind.ENUM; case idl.AvailableDeclarationKind.ENUM_CONSTANT: return DeclarationKind.ENUM_CONSTANT; case idl.AvailableDeclarationKind.EXTENSION: return DeclarationKind.EXTENSION; case idl.AvailableDeclarationKind.FIELD: return DeclarationKind.FIELD; case idl.AvailableDeclarationKind.FUNCTION: return DeclarationKind.FUNCTION; case idl.AvailableDeclarationKind.FUNCTION_TYPE_ALIAS: return DeclarationKind.FUNCTION_TYPE_ALIAS; case idl.AvailableDeclarationKind.GETTER: return DeclarationKind.GETTER; case idl.AvailableDeclarationKind.METHOD: return DeclarationKind.METHOD; case idl.AvailableDeclarationKind.MIXIN: return DeclarationKind.MIXIN; case idl.AvailableDeclarationKind.SETTER: return DeclarationKind.SETTER; case idl.AvailableDeclarationKind.VARIABLE: return DeclarationKind.VARIABLE; default: throw StateError('Unknown kind: $kind'); } } static idl.AvailableDeclarationKind kindToIdl(DeclarationKind kind) { switch (kind) { case DeclarationKind.CLASS: return idl.AvailableDeclarationKind.CLASS; case DeclarationKind.CLASS_TYPE_ALIAS: return idl.AvailableDeclarationKind.CLASS_TYPE_ALIAS; case DeclarationKind.CONSTRUCTOR: return idl.AvailableDeclarationKind.CONSTRUCTOR; case DeclarationKind.ENUM: return idl.AvailableDeclarationKind.ENUM; case DeclarationKind.ENUM_CONSTANT: return idl.AvailableDeclarationKind.ENUM_CONSTANT; case DeclarationKind.EXTENSION: return idl.AvailableDeclarationKind.EXTENSION; case DeclarationKind.FIELD: return idl.AvailableDeclarationKind.FIELD; case DeclarationKind.FUNCTION: return idl.AvailableDeclarationKind.FUNCTION; case DeclarationKind.FUNCTION_TYPE_ALIAS: return idl.AvailableDeclarationKind.FUNCTION_TYPE_ALIAS; case DeclarationKind.GETTER: return idl.AvailableDeclarationKind.GETTER; case DeclarationKind.METHOD: return idl.AvailableDeclarationKind.METHOD; case DeclarationKind.MIXIN: return idl.AvailableDeclarationKind.MIXIN; case DeclarationKind.SETTER: return idl.AvailableDeclarationKind.SETTER; case DeclarationKind.VARIABLE: return idl.AvailableDeclarationKind.VARIABLE; default: throw StateError('Unknown kind: $kind'); } } static idl.AvailableDeclarationBuilder toIdl(Declaration d) { var fieldMask = 0; if (d.docComplete != null) { fieldMask |= fieldDocMask; } if (d.parameters != null) { fieldMask |= fieldParametersMask; } if (d.returnType != null) { fieldMask |= fieldReturnTypeMask; } if (d.typeParameters != null) { fieldMask |= fieldTypeParametersMask; } var idlKind = kindToIdl(d.kind); return idl.AvailableDeclarationBuilder( children: d.children.map(toIdl).toList(), defaultArgumentListString: d.defaultArgumentListString, defaultArgumentListTextRanges: d.defaultArgumentListTextRanges, docComplete: d.docComplete, docSummary: d.docSummary, fieldMask: fieldMask, isAbstract: d.isAbstract, isConst: d.isConst, isDeprecated: d.isDeprecated, isFinal: d.isFinal, kind: idlKind, locationOffset: d.locationOffset, locationStartColumn: d.locationStartColumn, locationStartLine: d.locationStartLine, name: d.name, parameters: d.parameters, parameterNames: d.parameterNames, parameterTypes: d.parameterTypes, relevanceTags: d.relevanceTags, requiredParameterCount: d.requiredParameterCount, returnType: d.returnType, typeParameters: d.typeParameters, ); } } class _DefaultArguments { final String text; final List<int> ranges; _DefaultArguments(this.text, this.ranges); } class _Export { final Uri uri; final List<_ExportCombinator> combinators; _File file; _Export(this.uri, this.combinators); Iterable<Declaration> filter(List<Declaration> declarations) { return declarations.where((d) { var name = d.name; for (var combinator in combinators) { if (combinator.shows.isNotEmpty) { if (!combinator.shows.contains(name)) return false; } if (combinator.hides.isNotEmpty) { if (combinator.hides.contains(name)) return false; } } return true; }); } } class _ExportCombinator { final List<String> shows; final List<String> hides; _ExportCombinator(this.shows, this.hides); } class _File { /// The version of data format, should be incremented on every format change. static const int DATA_VERSION = 13; /// The next value for [id]. static int _nextId = 0; final DeclarationsTracker tracker; final int id = _nextId++; final String path; final Uri uri; bool exists = false; List<int> lineStarts; LineInfo lineInfo; bool isLibrary = false; bool isLibraryDeprecated = false; List<_Export> exports = []; List<_Part> parts = []; /// If this file is a part, the containing library. _File library; /// If this file is a library, libraries that export it. List<_File> directExporters = []; List<Declaration> fileDeclarations = []; List<Declaration> libraryDeclarations = []; List<Declaration> exportedDeclarations; List<String> templateNames = []; List<String> templateValues = []; /// If `true`, then this library has already been sent to the client. bool isSent = false; _File(this.tracker, this.path, this.uri); String get uriStr => uri.toString(); void refresh(DeclarationsContext context) { var resource = tracker._resourceProvider.getFile(path); int modificationStamp; try { modificationStamp = resource.modificationStamp; exists = true; } catch (e) { modificationStamp = -1; exists = false; } // When a file changes, its modification stamp changes. String pathKey; { var pathKeyBuilder = ApiSignature(); pathKeyBuilder.addInt(DATA_VERSION); pathKeyBuilder.addString(path); pathKeyBuilder.addInt(modificationStamp); pathKey = pathKeyBuilder.toHex() + '.declarations_content'; } // With Bazel multiple workspaces might be copies of the same workspace, // and have files with the same content, but with different paths. // So, we use the content hash to reuse their declarations without parsing. String content; String contentKey; { var contentHashBytes = tracker._byteStore.get(pathKey); if (contentHashBytes == null) { content = _readContent(resource); var contentHashBuilder = ApiSignature(); contentHashBuilder.addInt(DATA_VERSION); contentHashBuilder.addString(content); contentHashBytes = contentHashBuilder.toByteList(); tracker._byteStore.put(pathKey, contentHashBytes); } contentKey = hex.encode(contentHashBytes) + '.declarations'; } var bytes = tracker._byteStore.get(contentKey); if (bytes == null) { content ??= _readContent(resource); CompilationUnit unit = _parse(context.featureSet, content); _buildFileDeclarations(unit); _extractDartdocInfoFromUnit(unit); _putFileDeclarationsToByteStore(contentKey); context.dartdocDirectiveInfo .addTemplateNamesAndValues(templateNames, templateValues); } else { _readFileDeclarationsFromBytes(bytes); context.dartdocDirectiveInfo .addTemplateNamesAndValues(templateNames, templateValues); } // Resolve exports and parts. for (var export in exports) { export.file = _fileForRelativeUri(context, export.uri); } for (var part in parts) { part.file = _fileForRelativeUri(context, part.uri); } exports.removeWhere((e) => e.file == null); parts.removeWhere((e) => e.file == null); // Set back pointers. for (var export in exports) { var directExporters = export.file.directExporters; if (!directExporters.contains(this)) { directExporters.add(this); } } for (var part in parts) { part.file.library = this; part.file.isLibrary = false; } // Compute library declarations. if (isLibrary) { libraryDeclarations = <Declaration>[]; libraryDeclarations.addAll(fileDeclarations); for (var part in parts) { libraryDeclarations.addAll(part.file.fileDeclarations); } _computeRelevanceTags(libraryDeclarations); _setLocationLibraryUri(); } } void _buildFileDeclarations(CompilationUnit unit) { lineInfo = unit.lineInfo; lineStarts = lineInfo.lineStarts; isLibrary = true; exports = []; fileDeclarations = []; libraryDeclarations = null; exportedDeclarations = null; templateNames = []; templateValues = []; for (var astDirective in unit.directives) { if (astDirective is ExportDirective) { var uri = _uriFromAst(astDirective.uri); if (uri == null) continue; var combinators = <_ExportCombinator>[]; for (var astCombinator in astDirective.combinators) { if (astCombinator is ShowCombinator) { combinators.add(_ExportCombinator( astCombinator.shownNames.map((id) => id.name).toList(), const [], )); } else if (astCombinator is HideCombinator) { combinators.add(_ExportCombinator( const [], astCombinator.hiddenNames.map((id) => id.name).toList(), )); } } exports.add(_Export(uri, combinators)); } else if (astDirective is LibraryDirective) { isLibraryDeprecated = _hasDeprecatedAnnotation(astDirective); } else if (astDirective is PartDirective) { var uri = _uriFromAst(astDirective.uri); if (uri == null) continue; parts.add(_Part(uri)); } else if (astDirective is PartOfDirective) { isLibrary = false; } } int codeOffset = 0; int codeLength = 0; void setCodeRange(AstNode node) { if (node is VariableDeclaration) { var variables = node.parent as VariableDeclarationList; var i = variables.variables.indexOf(node); codeOffset = (i == 0 ? variables.parent : node).offset; codeLength = node.end - codeOffset; } else { codeOffset = node.offset; codeLength = node.length; } } String docComplete; String docSummary; void setDartDoc(AnnotatedNode node) { if (node.documentationComment != null) { var rawText = getCommentNodeRawText(node.documentationComment); docComplete = getDartDocPlainText(rawText); docSummary = getDartDocSummary(docComplete); } else { docComplete = null; docSummary = null; } } Declaration addDeclaration({ String defaultArgumentListString, List<int> defaultArgumentListTextRanges, bool isAbstract = false, bool isConst = false, bool isDeprecated = false, bool isFinal = false, @required DeclarationKind kind, @required Identifier name, String parameters, List<String> parameterNames, List<String> parameterTypes, Declaration parent, List<String> relevanceTags, int requiredParameterCount, String returnType, String typeParameters, }) { if (Identifier.isPrivateName(name.name)) { return null; } var locationOffset = name.offset; var lineLocation = lineInfo.getLocation(locationOffset); var declaration = Declaration( children: <Declaration>[], codeLength: codeLength, codeOffset: codeOffset, defaultArgumentListString: defaultArgumentListString, defaultArgumentListTextRanges: defaultArgumentListTextRanges, docComplete: docComplete, docSummary: docSummary, isAbstract: isAbstract, isConst: isConst, isDeprecated: isDeprecated, isFinal: isFinal, kind: kind, lineInfo: lineInfo, locationOffset: locationOffset, locationPath: path, name: name.name, locationStartColumn: lineLocation.columnNumber, locationStartLine: lineLocation.lineNumber, parameters: parameters, parameterNames: parameterNames, parameterTypes: parameterTypes, parent: parent, relevanceTags: relevanceTags, requiredParameterCount: requiredParameterCount, returnType: returnType, typeParameters: typeParameters, ); if (parent != null) { parent.children.add(declaration); } else { fileDeclarations.add(declaration); } return declaration; } for (var node in unit.declarations) { setCodeRange(node); setDartDoc(node); var isDeprecated = _hasDeprecatedAnnotation(node); var hasConstructor = false; void addClassMembers(Declaration parent, List<ClassMember> members) { for (var classMember in members) { setCodeRange(classMember); setDartDoc(classMember); isDeprecated = _hasDeprecatedAnnotation(classMember); if (classMember is ConstructorDeclaration) { var parameters = classMember.parameters; var defaultArguments = _computeDefaultArguments(parameters); var constructorName = classMember.name; constructorName ??= SimpleIdentifierImpl( StringToken( TokenType.IDENTIFIER, '', classMember.returnType.offset, ), ); addDeclaration( defaultArgumentListString: defaultArguments?.text, defaultArgumentListTextRanges: defaultArguments?.ranges, isDeprecated: isDeprecated, kind: DeclarationKind.CONSTRUCTOR, name: constructorName, parameters: parameters.toSource(), parameterNames: _getFormalParameterNames(parameters), parameterTypes: _getFormalParameterTypes(parameters), parent: parent, requiredParameterCount: _getFormalParameterRequiredCount(parameters), returnType: classMember.returnType.name, ); hasConstructor = true; } else if (classMember is FieldDeclaration) { var isConst = classMember.fields.isConst; var isFinal = classMember.fields.isFinal; for (var field in classMember.fields.variables) { setCodeRange(field); addDeclaration( isConst: isConst, isDeprecated: isDeprecated, isFinal: isFinal, kind: DeclarationKind.FIELD, name: field.name, parent: parent, relevanceTags: RelevanceTags._forExpression(field.initializer), returnType: _getTypeAnnotationString(classMember.fields.type), ); } } else if (classMember is MethodDeclaration) { var parameters = classMember.parameters; if (classMember.isGetter) { addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.GETTER, name: classMember.name, parent: parent, returnType: _getTypeAnnotationString(classMember.returnType), ); } else if (classMember.isSetter) { addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.SETTER, name: classMember.name, parameters: parameters.toSource(), parameterNames: _getFormalParameterNames(parameters), parameterTypes: _getFormalParameterTypes(parameters), parent: parent, requiredParameterCount: _getFormalParameterRequiredCount(parameters), ); } else { var defaultArguments = _computeDefaultArguments(parameters); addDeclaration( defaultArgumentListString: defaultArguments?.text, defaultArgumentListTextRanges: defaultArguments?.ranges, isDeprecated: isDeprecated, kind: DeclarationKind.METHOD, name: classMember.name, parameters: parameters.toSource(), parameterNames: _getFormalParameterNames(parameters), parameterTypes: _getFormalParameterTypes(parameters), parent: parent, requiredParameterCount: _getFormalParameterRequiredCount(parameters), returnType: _getTypeAnnotationString(classMember.returnType), typeParameters: classMember.typeParameters?.toSource(), ); } } } } if (node is ClassDeclaration) { var classDeclaration = addDeclaration( isAbstract: node.isAbstract, isDeprecated: isDeprecated, kind: DeclarationKind.CLASS, name: node.name, ); if (classDeclaration == null) continue; addClassMembers(classDeclaration, node.members); if (!hasConstructor) { classDeclaration.children.add(Declaration( children: [], codeLength: codeLength, codeOffset: codeOffset, defaultArgumentListString: null, defaultArgumentListTextRanges: null, docComplete: null, docSummary: null, isAbstract: false, isConst: false, isDeprecated: false, isFinal: false, kind: DeclarationKind.CONSTRUCTOR, locationOffset: -1, locationPath: path, name: '', lineInfo: lineInfo, locationStartColumn: 0, locationStartLine: 0, parameters: '()', parameterNames: [], parameterTypes: [], parent: classDeclaration, relevanceTags: null, requiredParameterCount: 0, returnType: node.name.name, typeParameters: null, )); } } else if (node is ClassTypeAlias) { addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.CLASS_TYPE_ALIAS, name: node.name, ); } else if (node is EnumDeclaration) { var enumDeclaration = addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.ENUM, name: node.name, ); if (enumDeclaration == null) continue; for (var constant in node.constants) { setDartDoc(constant); var isDeprecated = _hasDeprecatedAnnotation(constant); addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.ENUM_CONSTANT, name: constant.name, parent: enumDeclaration, ); } } else if (node is ExtensionDeclaration) { if (node.name != null) { addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.EXTENSION, name: node.name, ); } } else if (node is FunctionDeclaration) { var functionExpression = node.functionExpression; var parameters = functionExpression.parameters; if (node.isGetter) { addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.GETTER, name: node.name, returnType: _getTypeAnnotationString(node.returnType), ); } else if (node.isSetter) { addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.SETTER, name: node.name, parameters: parameters.toSource(), parameterNames: _getFormalParameterNames(parameters), parameterTypes: _getFormalParameterTypes(parameters), requiredParameterCount: _getFormalParameterRequiredCount(parameters), ); } else { var defaultArguments = _computeDefaultArguments(parameters); addDeclaration( defaultArgumentListString: defaultArguments?.text, defaultArgumentListTextRanges: defaultArguments?.ranges, isDeprecated: isDeprecated, kind: DeclarationKind.FUNCTION, name: node.name, parameters: parameters.toSource(), parameterNames: _getFormalParameterNames(parameters), parameterTypes: _getFormalParameterTypes(parameters), requiredParameterCount: _getFormalParameterRequiredCount(parameters), returnType: _getTypeAnnotationString(node.returnType), typeParameters: functionExpression.typeParameters?.toSource(), ); } } else if (node is GenericTypeAlias) { var functionType = node.functionType; if (functionType == null) continue; var parameters = functionType.parameters; addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.FUNCTION_TYPE_ALIAS, name: node.name, parameters: parameters.toSource(), parameterNames: _getFormalParameterNames(parameters), parameterTypes: _getFormalParameterTypes(parameters), requiredParameterCount: _getFormalParameterRequiredCount(parameters), returnType: _getTypeAnnotationString(functionType.returnType), typeParameters: functionType.typeParameters?.toSource(), ); } else if (node is FunctionTypeAlias) { var parameters = node.parameters; addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.FUNCTION_TYPE_ALIAS, name: node.name, parameters: parameters.toSource(), parameterNames: _getFormalParameterNames(parameters), parameterTypes: _getFormalParameterTypes(parameters), requiredParameterCount: _getFormalParameterRequiredCount(parameters), returnType: _getTypeAnnotationString(node.returnType), typeParameters: node.typeParameters?.toSource(), ); } else if (node is MixinDeclaration) { var mixinDeclaration = addDeclaration( isDeprecated: isDeprecated, kind: DeclarationKind.MIXIN, name: node.name, ); if (mixinDeclaration == null) continue; addClassMembers(mixinDeclaration, node.members); } else if (node is TopLevelVariableDeclaration) { var isConst = node.variables.isConst; var isFinal = node.variables.isFinal; for (var variable in node.variables.variables) { setCodeRange(variable); addDeclaration( isConst: isConst, isDeprecated: isDeprecated, isFinal: isFinal, kind: DeclarationKind.VARIABLE, name: variable.name, relevanceTags: RelevanceTags._forExpression(variable.initializer), returnType: _getTypeAnnotationString(node.variables.type), ); } } } } void _computeRelevanceTags(List<Declaration> declarations) { for (var declaration in declarations) { declaration._relevanceTags ??= RelevanceTags._forDeclaration(uriStr, declaration); _computeRelevanceTags(declaration.children); } } void _extractDartdocInfoFromUnit(CompilationUnit unit) { DartdocDirectiveInfo info = new DartdocDirectiveInfo(); for (Directive directive in unit.directives) { Comment comment = directive.documentationComment; if (comment != null) { info.extractTemplate(getCommentNodeRawText(comment)); } } for (CompilationUnitMember declaration in unit.declarations) { Comment comment = declaration.documentationComment; if (comment != null) { info.extractTemplate(getCommentNodeRawText(comment)); } if (declaration is ClassOrMixinDeclaration) { for (ClassMember member in declaration.members) { Comment comment = member.documentationComment; if (comment != null) { info.extractTemplate(getCommentNodeRawText(comment)); } } } else if (declaration is EnumDeclaration) { for (EnumConstantDeclaration constant in declaration.constants) { Comment comment = constant.documentationComment; if (comment != null) { info.extractTemplate(getCommentNodeRawText(comment)); } } } } Map<String, String> templateMap = info.templateMap; for (String name in templateMap.keys) { templateNames.add(name); templateValues.add(templateMap[name]); } } /// Return the [_File] for the given [relative] URI, maybe `null`. _File _fileForRelativeUri(DeclarationsContext context, Uri relative) { var absoluteUri = resolveRelativeUri(uri, relative); return tracker._getFileByUri(context, absoluteUri); } void _putFileDeclarationsToByteStore(String contentKey) { var builder = idl.AvailableFileBuilder( lineStarts: lineStarts, isLibrary: isLibrary, isLibraryDeprecated: isLibraryDeprecated, exports: exports.map((e) { return idl.AvailableFileExportBuilder( uri: e.uri.toString(), combinators: e.combinators.map((c) { return idl.AvailableFileExportCombinatorBuilder( shows: c.shows, hides: c.hides); }).toList(), ); }).toList(), parts: parts.map((p) => p.uri.toString()).toList(), declarations: fileDeclarations.map((d) { return _DeclarationStorage.toIdl(d); }).toList(), directiveInfo: idl.DirectiveInfoBuilder( templateNames: templateNames, templateValues: templateValues), ); var bytes = builder.toBuffer(); tracker._byteStore.put(contentKey, bytes); } void _readFileDeclarationsFromBytes(List<int> bytes) { var idlFile = idl.AvailableFile.fromBuffer(bytes); lineStarts = idlFile.lineStarts.toList(); lineInfo = LineInfo(lineStarts); isLibrary = idlFile.isLibrary; isLibraryDeprecated = idlFile.isLibraryDeprecated; exports = idlFile.exports.map((e) { return _Export( Uri.parse(e.uri), e.combinators.map((c) { return _ExportCombinator(c.shows.toList(), c.hides.toList()); }).toList(), ); }).toList(); parts = idlFile.parts.map((e) { var uri = Uri.parse(e); return _Part(uri); }).toList(); fileDeclarations = idlFile.declarations.map((e) { return _DeclarationStorage.fromIdl(path, lineInfo, null, e); }).toList(); templateNames = idlFile.directiveInfo.templateNames.toList(); templateValues = idlFile.directiveInfo.templateValues.toList(); } void _setLocationLibraryUri() { for (var declaration in libraryDeclarations) { declaration._locationLibraryUri = uri; } } static _DefaultArguments _computeDefaultArguments( FormalParameterList parameters) { var buffer = StringBuffer(); var ranges = <int>[]; for (var parameter in parameters.parameters) { if (parameter.isRequired) { if (buffer.isNotEmpty) { buffer.write(', '); } if (parameter.isNamed) { buffer.write(parameter.identifier.name); buffer.write(': '); } var valueOffset = buffer.length; buffer.write(parameter.identifier.name); var valueLength = buffer.length - valueOffset; ranges.add(valueOffset); ranges.add(valueLength); } else if (parameter.isNamed && _hasRequiredAnnotation(parameter)) { if (buffer.isNotEmpty) { buffer.write(', '); } buffer.write(parameter.identifier.name); buffer.write(': '); var valueOffset = buffer.length; buffer.write('null'); var valueLength = buffer.length - valueOffset; ranges.add(valueOffset); ranges.add(valueLength); } } if (buffer.isEmpty) return null; return _DefaultArguments(buffer.toString(), ranges); } static List<String> _getFormalParameterNames(FormalParameterList parameters) { if (parameters == null) return const <String>[]; var names = <String>[]; for (var parameter in parameters.parameters) { var name = parameter.identifier?.name ?? ''; names.add(name); } return names; } static int _getFormalParameterRequiredCount(FormalParameterList parameters) { if (parameters == null) return null; return parameters.parameters .takeWhile((parameter) => parameter.isRequiredPositional) .length; } static String _getFormalParameterType(FormalParameter parameter) { if (parameter is DefaultFormalParameter) { DefaultFormalParameter defaultFormalParameter = parameter; parameter = defaultFormalParameter.parameter; } if (parameter is SimpleFormalParameter) { return _getTypeAnnotationString(parameter.type); } return ''; } static List<String> _getFormalParameterTypes(FormalParameterList parameters) { if (parameters == null) return null; var types = <String>[]; for (var parameter in parameters.parameters) { var type = _getFormalParameterType(parameter); types.add(type); } return types; } static String _getTypeAnnotationString(TypeAnnotation typeAnnotation) { return typeAnnotation?.toSource() ?? ''; } /// Return `true` if the [node] is probably deprecated. static bool _hasDeprecatedAnnotation(AnnotatedNode node) { for (var annotation in node.metadata) { var name = annotation.name; if (name is SimpleIdentifier) { if (name.name == 'deprecated' || name.name == 'Deprecated') { return true; } } } return false; } /// Return `true` if the [node] probably has `@required` annotation. static bool _hasRequiredAnnotation(FormalParameter node) { for (var annotation in node.metadata) { var name = annotation.name; if (name is SimpleIdentifier) { if (name.name == 'required') { return true; } } } return false; } static CompilationUnit _parse(FeatureSet featureSet, String content) { var errorListener = AnalysisErrorListener.NULL_LISTENER; var source = StringSource(content, ''); var reader = new CharSequenceReader(content); var scanner = new Scanner(null, reader, errorListener) ..configureFeatures(featureSet); var token = scanner.tokenize(); var parser = new Parser(source, errorListener, featureSet: featureSet, useFasta: true); var unit = parser.parseCompilationUnit(token); unit.lineInfo = LineInfo(scanner.lineStarts); return unit; } static String _readContent(File resource) { try { return resource.readAsStringSync(); } catch (e) { return ''; } } static Uri _uriFromAst(StringLiteral astUri) { if (astUri is SimpleStringLiteral) { var uriStr = astUri.value.trim(); if (uriStr.isEmpty) return null; try { return Uri.parse(uriStr); } catch (_) {} } return null; } } class _LibraryNode extends graph.Node<_LibraryNode> { final _LibraryWalker walker; final _File file; _LibraryNode(this.walker, this.file); @override bool get isEvaluated => file.exportedDeclarations != null; @override List<_LibraryNode> computeDependencies() { return file.exports .map((export) => export.file) .where((file) => file.isLibrary) .map(walker.getNode) .toList(); } } class _LibraryWalker extends graph.DependencyWalker<_LibraryNode> { final Map<_File, _LibraryNode> nodesOfFiles = {}; @override void evaluate(_LibraryNode node) { var file = node.file; var resultSet = _newDeclarationSet(); resultSet.addAll(file.libraryDeclarations); for (var export in file.exports) { var file = export.file; if (file.isLibrary) { var exportedDeclarations = file.exportedDeclarations; resultSet.addAll(export.filter(exportedDeclarations)); } } file.exportedDeclarations = resultSet.toList(); } @override void evaluateScc(List<_LibraryNode> scc) { for (var node in scc) { var visitedFiles = Set<_File>(); List<Declaration> computeExported(_File file) { if (file.exportedDeclarations != null) { return file.exportedDeclarations; } if (!visitedFiles.add(file)) { return const []; } var resultSet = _newDeclarationSet(); resultSet.addAll(file.libraryDeclarations); for (var export in file.exports) { var exportedDeclarations = computeExported(export.file); resultSet.addAll(export.filter(exportedDeclarations)); } return resultSet.toList(); } var file = node.file; file.exportedDeclarations = computeExported(file); } } _LibraryNode getNode(_File file) { return nodesOfFiles.putIfAbsent(file, () => new _LibraryNode(this, file)); } void walkLibrary(_File file) { var node = getNode(file); walk(node); } static Set<Declaration> _newDeclarationSet() { return HashSet<Declaration>( hashCode: (e) => e.name.hashCode, equals: (a, b) => a.name == b.name, ); } } /// Information about a package: `Pub` or `Bazel`. class _Package { final Folder root; final Folder lib; _Package(this.root) : lib = root.getChildAssumingFolder('lib'); /// Return `true` if the [path] is anywhere in the [root] of the package. /// /// Note, that this method does not check if the are nested packages, that /// might actually contain the [path]. bool contains(String path) { return root.contains(path); } /// Return `true` if the [path] is in the `lib` folder of this package. bool containsInLib(String path) { return lib.contains(path); } /// Return the direct child folder of the root, that contains the [path]. /// /// So, we can know if the [path] is in `lib/`, or `test/`, or `bin/`. Folder folderInRootContaining(String path) { try { var children = root.getChildren(); for (var folder in children) { if (folder is Folder && folder.contains(path)) { return folder; } } } on FileSystemException {} return null; } } class _Part { final Uri uri; _File file; _Part(this.uri); } /// Normal and dev dependencies specified in a `pubspec.yaml` file. class _PubspecDependencies { final List<String> lib; final List<String> dev; _PubspecDependencies(this.lib, this.dev); } class _ScheduledFile { final DeclarationsContext context; final String path; _ScheduledFile(this.context, this.path); } /// Wrapper for a [StreamController] and its unique [Stream] instance. class _StreamController<T> { final StreamController<T> controller = StreamController<T>(); Stream<T> stream; _StreamController() { stream = controller.stream; } void add(T event) { controller.add(event); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/analysis_options/analysis_options_provider.dart
// Copyright (c) 2015, 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 'dart:core'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/generated/engine.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/source/source_resource.dart'; import 'package:analyzer/src/task/options.dart'; import 'package:analyzer/src/util/yaml.dart'; import 'package:source_span/source_span.dart'; import 'package:yaml/yaml.dart'; /// Provide the options found in the analysis options file. class AnalysisOptionsProvider { /// The source factory used to resolve include declarations /// in analysis options files or `null` if include is not supported. SourceFactory sourceFactory; AnalysisOptionsProvider([this.sourceFactory]); /// Provide the options found in either /// [root]/[AnalysisEngine.ANALYSIS_OPTIONS_FILE] or /// [root]/[AnalysisEngine.ANALYSIS_OPTIONS_YAML_FILE]. /// Recursively merge options referenced by an include directive /// and remove the include directive from the resulting options map. /// Return an empty options map if the file does not exist. YamlMap getOptions(Folder root, {bool crawlUp: false}) { File optionsFile = getOptionsFile(root, crawlUp: crawlUp); if (optionsFile == null) { return new YamlMap(); } return getOptionsFromFile(optionsFile); } /// Return the analysis options file from which options should be read, or /// `null` if there is no analysis options file for code in the given [root]. /// /// The given [root] directory will be searched first. If no file is found and /// if [crawlUp] is `true`, then enclosing directories will be searched. File getOptionsFile(Folder root, {bool crawlUp: false}) { Resource resource; for (Folder folder = root; folder != null; folder = folder.parent) { resource = folder.getChild(AnalysisEngine.ANALYSIS_OPTIONS_FILE); if (resource.exists) { break; } resource = folder.getChild(AnalysisEngine.ANALYSIS_OPTIONS_YAML_FILE); if (resource.exists || !crawlUp) { break; } } if (resource is File && resource.exists) { return resource; } return null; } /// Provide the options found in [file]. /// Recursively merge options referenced by an include directive /// and remove the include directive from the resulting options map. /// Return an empty options map if the file does not exist. YamlMap getOptionsFromFile(File file) { return getOptionsFromSource(new FileSource(file)); } /// Provide the options found in [source]. /// Recursively merge options referenced by an include directive /// and remove the include directive from the resulting options map. /// Return an empty options map if the file does not exist. YamlMap getOptionsFromSource(Source source) { YamlMap options = getOptionsFromString(_readAnalysisOptions(source)); YamlNode node = getValue(options, AnalyzerOptions.include); if (sourceFactory != null && node is YamlScalar) { var path = node.value; if (path is String) { Source parent = sourceFactory.resolveUri(source, path); options = merge(getOptionsFromSource(parent), options); } } return options; } /// Provide the options found in [optionsSource]. /// An include directive, if present, will be left as-is, /// and the referenced options will NOT be merged into the result. /// Return an empty options map if the source is null. YamlMap getOptionsFromString(String optionsSource) { if (optionsSource == null) { return new YamlMap(); } try { YamlNode doc = loadYamlNode(optionsSource); if (doc is YamlMap) { return doc; } return new YamlMap(); } on YamlException catch (e) { throw new OptionsFormatException(e.message, e.span); } catch (e) { throw new OptionsFormatException('Unable to parse YAML document.'); } } /// Merge the given options contents where the values in [defaults] may be /// overridden by [overrides]. /// /// Some notes about merge semantics: /// /// * lists are merged (without duplicates). /// * lists of scalar values can be promoted to simple maps when merged with /// maps of strings to booleans (e.g., ['opt1', 'opt2'] becomes /// {'opt1': true, 'opt2': true}. /// * maps are merged recursively. /// * if map values cannot be merged, the overriding value is taken. /// YamlMap merge(YamlMap defaults, YamlMap overrides) => new Merger().mergeMap(defaults, overrides); /// Read the contents of [source] as a string. /// Returns null if source is null or does not exist. String _readAnalysisOptions(Source source) { try { return source.contents.data; } catch (e) { // Source can't be read. return null; } } } /// Thrown on options format exceptions. class OptionsFormatException implements Exception { final String message; final SourceSpan span; OptionsFormatException(this.message, [this.span]); @override String toString() => 'OptionsFormatException: ${message?.toString()}, ${span?.toString()}'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/analysis_options
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/analysis_options/error/option_codes.dart
// Copyright (c) 2014, 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:analyzer/error/error.dart'; /** * The error codes used for errors in analysis options files. The convention for * this class is for the name of the error code to indicate the problem that * caused the error to be generated and for the error message to explain what is * wrong and, when appropriate, how the problem can be corrected. */ class AnalysisOptionsErrorCode extends ErrorCode { /** * An error code indicating that there is a syntactic error in the included * file. * * Parameters: * 0: the path of the file containing the error * 1: the starting offset of the text in the file that contains the error * 2: the ending offset of the text in the file that contains the error * 3: the error message */ static const AnalysisOptionsErrorCode INCLUDED_FILE_PARSE_ERROR = const AnalysisOptionsErrorCode( 'INCLUDED_FILE_PARSE_ERROR', '{3} in {0}({1}..{2})'); /** * An error code indicating that there is a syntactic error in the file. * * Parameters: * 0: the error message from the parse error */ static const AnalysisOptionsErrorCode PARSE_ERROR = const AnalysisOptionsErrorCode('PARSE_ERROR', '{0}'); /** * Initialize a newly created error code to have the given [name]. */ const AnalysisOptionsErrorCode(String name, String message, {String correction}) : super.temporary(name, message, correction: correction); @override ErrorSeverity get errorSeverity => ErrorSeverity.ERROR; @override ErrorType get type => ErrorType.COMPILE_TIME_ERROR; } class AnalysisOptionsHintCode extends ErrorCode { /** * An error code indicating the analysis options file name is deprecated and * the file should be renamed. * * Parameters: * 0: the uri of the file which should be renamed */ static const AnalysisOptionsHintCode DEPRECATED_ANALYSIS_OPTIONS_FILE_NAME = const AnalysisOptionsHintCode( 'DEPRECATED_ANALYSIS_OPTIONS_FILE_NAME', "The name of the analysis options file {0} is deprecated;" " consider renaming it to analysis_options.yaml."); /** * An error code indicating that the enablePreviewDart2 setting is deprecated. */ static const AnalysisOptionsHintCode PREVIEW_DART_2_SETTING_DEPRECATED = const AnalysisOptionsHintCode('PREVIEW_DART_2_SETTING_DEPRECATED', "The 'enablePreviewDart2' setting is deprecated.", correction: "It is no longer necessary to explicitly enable Dart 2."); /** * An error code indicating that strong-mode: true is deprecated. */ static const AnalysisOptionsHintCode STRONG_MODE_SETTING_DEPRECATED = const AnalysisOptionsHintCode('STRONG_MODE_SETTING_DEPRECATED', "The 'strong-mode: true' setting is deprecated.", correction: "It is no longer necessary to explicitly enable strong mode."); /** * An error code indicating that the enablePreviewDart2 setting is deprecated. */ static const AnalysisOptionsHintCode SUPER_MIXINS_SETTING_DEPRECATED = const AnalysisOptionsHintCode('SUPER_MIXINS_SETTING_DEPRECATED', "The 'enableSuperMixins' setting is deprecated.", correction: "Support has been added to the language for 'mixin' based mixins."); /** * Initialize a newly created hint code to have the given [name]. */ const AnalysisOptionsHintCode(String name, String message, {String correction}) : super.temporary(name, message, correction: correction); @override ErrorSeverity get errorSeverity => ErrorSeverity.INFO; @override ErrorType get type => ErrorType.HINT; } /** * The error codes used for warnings in analysis options files. The convention * for this class is for the name of the error code to indicate the problem that * caused the error to be generated and for the error message to explain what is * wrong and, when appropriate, how the problem can be corrected. */ class AnalysisOptionsWarningCode extends ErrorCode { /** * An error code indicating that the given option is deprecated. */ static const AnalysisOptionsWarningCode ANALYSIS_OPTION_DEPRECATED = const AnalysisOptionsWarningCode('ANALYSIS_OPTION_DEPRECATED', "The option '{0}' is no longer supported."); /** * An error code indicating a specified include file could not be found. * * Parameters: * 0: the uri of the file to be included * 1: the path of the file containing the include directive */ static const AnalysisOptionsWarningCode INCLUDE_FILE_NOT_FOUND = const AnalysisOptionsWarningCode('INCLUDE_FILE_NOT_FOUND', "The include file {0} in {1} cannot be found."); /** * An error code indicating a specified include file has a warning. * * Parameters: * 0: the path of the file containing the warnings * 1: the starting offset of the text in the file that contains the warning * 2: the ending offset of the text in the file that contains the warning * 3: the warning message */ static const AnalysisOptionsWarningCode INCLUDED_FILE_WARNING = const AnalysisOptionsWarningCode('INCLUDED_FILE_WARNING', "Warning in the included options file {0}({1}..{2}): {3}"); /** * An error code indicating that a plugin is being configured with an invalid * value for an option and a detail message is provided. */ static const AnalysisOptionsWarningCode INVALID_OPTION = const AnalysisOptionsWarningCode( 'INVALID_OPTION', "Invalid option specified for '{0}': {1}"); /** * An error code indicating an invalid format for an options file section. * * Parameters: * 0: the section name */ static const AnalysisOptionsWarningCode INVALID_SECTION_FORMAT = const AnalysisOptionsWarningCode( 'INVALID_SECTION_FORMAT', "Invalid format for the '{0}' section."); /** * An error code indicating that strong-mode: false is has been removed. */ static const AnalysisOptionsWarningCode SPEC_MODE_REMOVED = const AnalysisOptionsWarningCode('SPEC_MODE_REMOVED', "The option 'strong-mode: false' is no longer supported.", correction: "It's recommended to remove the 'strong-mode:' setting (and make " "your code Dart 2 compliant)."); /** * An error code indicating that an unrecognized error code is being used to * specify an error filter. * * Parameters: * 0: the unrecognized error code */ static const AnalysisOptionsWarningCode UNRECOGNIZED_ERROR_CODE = const AnalysisOptionsWarningCode( 'UNRECOGNIZED_ERROR_CODE', "'{0}' isn't a recognized error code."); /** * An error code indicating that a plugin is being configured with an * unsupported option where there is just one legal value. * * Parameters: * 0: the plugin name * 1: the unsupported option key * 2: the legal value */ static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUE = const AnalysisOptionsWarningCode( 'UNSUPPORTED_OPTION_WITH_LEGAL_VALUE', "The option '{1}' isn't supported by '{0}'. " "Try using the only supported option: '{2}'."); /** * An error code indicating that a plugin is being configured with an * unsupported option and legal options are provided. * * Parameters: * 0: the plugin name * 1: the unsupported option key * 2: legal values */ static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUES = const AnalysisOptionsWarningCode('UNSUPPORTED_OPTION_WITH_LEGAL_VALUES', "The option '{1}' isn't supported by '{0}'.", correction: "Try using one of the supported options: {2}."); /** * An error code indicating that a plugin is being configured with an * unsupported option and legal options are provided. * * Parameters: * 0: the plugin name * 1: the unsupported option key */ static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITHOUT_VALUES = const AnalysisOptionsWarningCode( 'UNSUPPORTED_OPTION_WITHOUT_VALUES', "The option '{1}' isn't supported by '{0}'.", ); /** * An error code indicating that an option entry is being configured with an * unsupported value. * * Parameters: * 0: the option name * 1: the unsupported value * 2: legal values */ static const AnalysisOptionsWarningCode UNSUPPORTED_VALUE = const AnalysisOptionsWarningCode( 'UNSUPPORTED_VALUE', "The value '{1}' isn't supported by '{0}'.", correction: "Try using one of the supported options: {2}."); /** * Initialize a newly created warning code to have the given [name]. */ const AnalysisOptionsWarningCode(String name, String message, {String correction}) : super.temporary(name, message, correction: correction); @override ErrorSeverity get errorSeverity => ErrorSeverity.WARNING; @override ErrorType get type => ErrorType.STATIC_WARNING; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/diagnostic/diagnostic.dart
// Copyright (c) 2019, 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. /// A diagnostic, as defined by the [Diagnostic Design Guidelines][guidelines]: /// /// > An indication of a specific problem at a specific location within the /// > source code being processed by a development tool. /// /// Clients may not extend, implement or mix-in this class. /// /// [guidelines]: ../doc/diagnostics.md abstract class Diagnostic { /// A list of messages that provide context for understanding the problem /// being reported. The list will be empty if there are no such messages. List<DiagnosticMessage> get contextMessages; /// A description of how to fix the problem, or `null` if there is no such /// description. String get correctionMessage; /// A message describing what is wrong and why. DiagnosticMessage get problemMessage; /// The severity associated with the diagnostic. Severity get severity; } /// A single message associated with a [Diagnostic], consisting of the text of /// the message and the location associated with it. /// /// Clients may not extend, implement or mix-in this class. abstract class DiagnosticMessage { /// The absolute and normalized path of the file associated with this message. String get filePath; /// The length of the source range associated with this message. int get length; /// The text of the message. String get message; /// The zero-based offset from the start of the file to the beginning of the /// source range associated with this message. int get offset; } /// An indication of the severity of a [Diagnostic]. enum Severity { error, warning, info }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/task/model.dart
// Copyright (c) 2015, 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. @deprecated library task.model; export 'package:analyzer/src/task/api/model.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/error/error.dart
// Copyright (c) 2014, 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 'dart:collection'; import 'package:analyzer/diagnostic/diagnostic.dart'; import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/dart/scanner/scanner.dart' show ScannerErrorCode; import 'package:analyzer/src/diagnostic/diagnostic.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/generated/java_core.dart'; import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode; import 'package:analyzer/src/generated/resolver.dart' show ResolverErrorCode; import 'package:analyzer/src/generated/source.dart'; import 'package:analyzer/src/manifest/manifest_warning_code.dart'; import 'package:front_end/src/base/errors.dart'; import 'package:front_end/src/scanner/errors.dart'; export 'package:front_end/src/base/errors.dart' show ErrorCode, ErrorSeverity, ErrorType; const List<ErrorCode> errorCodeValues = const [ // // Manually generated. You can mostly reproduce this list by running the // following command from the root of the analyzer package: // // > cat // lib/src/analysis_options/error/option_codes.dart'; // lib/src/dart/error/hint_codes.dart'; // lib/src/dart/error/lint_codes.dart'; // lib/src/dart/error/todo_codes.dart'; // lib/src/html/error/html_codes.dart'; // lib/src/dart/error/syntactic_errors.dart // lib/src/error/codes.dart // ../front_end/lib/src/scanner/errors.dart | // grep 'static const .*Code' | // awk '{print $3"."$4","}' | // sort > codes.txt // // There are a few error codes that are wrapped such that the name of the // error code in on the line following the pattern we're grepping for. Those // need to be filled in by hand. // AnalysisOptionsErrorCode.PARSE_ERROR, AnalysisOptionsErrorCode.INCLUDED_FILE_PARSE_ERROR, AnalysisOptionsWarningCode.ANALYSIS_OPTION_DEPRECATED, AnalysisOptionsWarningCode.INCLUDE_FILE_NOT_FOUND, AnalysisOptionsWarningCode.INCLUDED_FILE_WARNING, AnalysisOptionsWarningCode.INVALID_OPTION, AnalysisOptionsWarningCode.INVALID_SECTION_FORMAT, AnalysisOptionsWarningCode.UNRECOGNIZED_ERROR_CODE, AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE, AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES, AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITHOUT_VALUES, AnalysisOptionsWarningCode.UNSUPPORTED_VALUE, AnalysisOptionsWarningCode.SPEC_MODE_REMOVED, AnalysisOptionsHintCode.DEPRECATED_ANALYSIS_OPTIONS_FILE_NAME, AnalysisOptionsHintCode.PREVIEW_DART_2_SETTING_DEPRECATED, AnalysisOptionsHintCode.STRONG_MODE_SETTING_DEPRECATED, AnalysisOptionsHintCode.SUPER_MIXINS_SETTING_DEPRECATED, CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH, CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH, CheckedModeCompileTimeErrorCode.CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE, CheckedModeCompileTimeErrorCode.VARIABLE_TYPE_MISMATCH, CompileTimeErrorCode.ABSTRACT_SUPER_MEMBER_REFERENCE, CompileTimeErrorCode.ACCESS_PRIVATE_ENUM_FIELD, CompileTimeErrorCode.AMBIGUOUS_EXPORT, CompileTimeErrorCode.AMBIGUOUS_EXTENSION_MEMBER_ACCESS, CompileTimeErrorCode.AMBIGUOUS_SET_OR_MAP_LITERAL_BOTH, CompileTimeErrorCode.AMBIGUOUS_SET_OR_MAP_LITERAL_EITHER, CompileTimeErrorCode.ANNOTATION_WITH_NON_CLASS, CompileTimeErrorCode.ANNOTATION_WITH_TYPE_ARGUMENTS, CompileTimeErrorCode.ASSERT_IN_REDIRECTING_CONSTRUCTOR, CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT, CompileTimeErrorCode.AWAIT_IN_WRONG_CONTEXT, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_EXTENSION_NAME, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_PREFIX_NAME, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME, CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME, CompileTimeErrorCode.CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS, CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_AND_STATIC_FIELD, CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_AND_STATIC_METHOD, CompileTimeErrorCode.CONFLICTING_FIELD_AND_METHOD, CompileTimeErrorCode.CONFLICTING_GENERIC_INTERFACES, CompileTimeErrorCode.CONFLICTING_METHOD_AND_FIELD, CompileTimeErrorCode.CONFLICTING_STATIC_AND_INSTANCE, CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_CLASS, CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_MEMBER, CompileTimeErrorCode.CONST_CONSTRUCTOR_THROWS_EXCEPTION, CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST, CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_MIXIN_WITH_FIELD, CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER, CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD, CompileTimeErrorCode.CONST_DEFERRED_CLASS, CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE, CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL, CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_INT, CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING, CompileTimeErrorCode.CONST_EVAL_TYPE_INT, CompileTimeErrorCode.CONST_EVAL_TYPE_NUM, CompileTimeErrorCode.CONST_EVAL_TYPE_TYPE, CompileTimeErrorCode.CONST_FORMAL_PARAMETER, CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE, CompileTimeErrorCode .CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.CONST_INSTANCE_FIELD, CompileTimeErrorCode.CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS, CompileTimeErrorCode.CONST_NOT_INITIALIZED, CompileTimeErrorCode.CONST_SET_ELEMENT_TYPE_IMPLEMENTS_EQUALS, CompileTimeErrorCode.CONST_SPREAD_EXPECTED_LIST_OR_SET, CompileTimeErrorCode.CONST_SPREAD_EXPECTED_MAP, CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS, CompileTimeErrorCode.CONST_WITH_NON_CONST, CompileTimeErrorCode.CONST_WITH_NON_CONSTANT_ARGUMENT, CompileTimeErrorCode.CONST_WITH_NON_TYPE, CompileTimeErrorCode.CONST_WITH_TYPE_PARAMETERS, CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR, CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT, CompileTimeErrorCode.DEFAULT_LIST_CONSTRUCTOR_MISMATCH, CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER, CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS, CompileTimeErrorCode.DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR, CompileTimeErrorCode.DEFAULT_VALUE_ON_REQUIRED_PARAMETER, CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_NAME, CompileTimeErrorCode.DUPLICATE_DEFINITION, CompileTimeErrorCode.DUPLICATE_NAMED_ARGUMENT, CompileTimeErrorCode.DUPLICATE_PART, CompileTimeErrorCode.EQUAL_KEYS_IN_CONST_MAP, CompileTimeErrorCode.EQUAL_ELEMENTS_IN_CONST_SET, CompileTimeErrorCode.EXPORT_INTERNAL_LIBRARY, CompileTimeErrorCode.EXPORT_OF_NON_LIBRARY, CompileTimeErrorCode.EXPRESSION_IN_MAP, CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS, CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS, CompileTimeErrorCode.EXTENDS_NON_CLASS, CompileTimeErrorCode.EXTENSION_AS_EXPRESSION, CompileTimeErrorCode.EXTENSION_CONFLICTING_STATIC_AND_INSTANCE, CompileTimeErrorCode.EXTENSION_DECLARES_MEMBER_OF_OBJECT, CompileTimeErrorCode.EXTENSION_OVERRIDE_ACCESS_TO_STATIC_MEMBER, CompileTimeErrorCode.EXTENSION_OVERRIDE_ARGUMENT_NOT_ASSIGNABLE, CompileTimeErrorCode.EXTENSION_OVERRIDE_WITH_CASCADE, CompileTimeErrorCode.EXTENSION_OVERRIDE_WITHOUT_ACCESS, CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS, CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED, CompileTimeErrorCode.FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS, CompileTimeErrorCode.FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER, CompileTimeErrorCode.FIELD_INITIALIZER_FACTORY_CONSTRUCTOR, CompileTimeErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR, CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR, CompileTimeErrorCode.FINAL_INITIALIZED_MULTIPLE_TIMES, CompileTimeErrorCode.FOR_IN_WITH_CONST_VARIABLE, CompileTimeErrorCode.GENERIC_FUNCTION_TYPED_PARAM_UNSUPPORTED, CompileTimeErrorCode.GENERIC_FUNCTION_TYPE_CANNOT_BE_BOUND, CompileTimeErrorCode.GENERIC_FUNCTION_TYPE_CANNOT_BE_TYPE_ARGUMENT, CompileTimeErrorCode.IF_ELEMENT_CONDITION_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.IMPLEMENTS_DEFERRED_CLASS, CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS, CompileTimeErrorCode.IMPLEMENTS_NON_CLASS, CompileTimeErrorCode.IMPLEMENTS_REPEATED, CompileTimeErrorCode.IMPLEMENTS_SUPER_CLASS, CompileTimeErrorCode.IMPLICIT_THIS_REFERENCE_IN_INITIALIZER, CompileTimeErrorCode.IMPORT_INTERNAL_LIBRARY, CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY, CompileTimeErrorCode.INCONSISTENT_CASE_EXPRESSION_TYPES, CompileTimeErrorCode.INCONSISTENT_INHERITANCE, CompileTimeErrorCode.INCONSISTENT_INHERITANCE_GETTER_AND_METHOD, CompileTimeErrorCode.INITIALIZER_FOR_NON_EXISTENT_FIELD, CompileTimeErrorCode.INITIALIZER_FOR_STATIC_FIELD, CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD, CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_STATIC_FIELD, CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_FACTORY, CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_STATIC, CompileTimeErrorCode.INSTANTIATE_ENUM, CompileTimeErrorCode.INTEGER_LITERAL_OUT_OF_RANGE, CompileTimeErrorCode.INTEGER_LITERAL_IMPRECISE_AS_DOUBLE, CompileTimeErrorCode.INVALID_ANNOTATION, CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.INVALID_ANNOTATION_GETTER, CompileTimeErrorCode.INVALID_CONSTANT, CompileTimeErrorCode.INVALID_CONSTRUCTOR_NAME, CompileTimeErrorCode.INVALID_EXTENSION_ARGUMENT_COUNT, CompileTimeErrorCode.INVALID_FACTORY_NAME_NOT_A_CLASS, CompileTimeErrorCode.INVALID_MODIFIER_ON_CONSTRUCTOR, CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER, CompileTimeErrorCode.INVALID_INLINE_FUNCTION_TYPE, CompileTimeErrorCode.INVALID_OPTIONAL_PARAMETER_TYPE, CompileTimeErrorCode.INVALID_OVERRIDE, CompileTimeErrorCode.INVALID_REFERENCE_TO_THIS, CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_LIST, CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_MAP, CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_SET, CompileTimeErrorCode.INVALID_URI, CompileTimeErrorCode.INVALID_USE_OF_COVARIANT, CompileTimeErrorCode.INVALID_USE_OF_COVARIANT_IN_EXTENSION, CompileTimeErrorCode.INVOCATION_OF_EXTENSION_WITHOUT_CALL, CompileTimeErrorCode.LABEL_IN_OUTER_SCOPE, CompileTimeErrorCode.LABEL_UNDEFINED, CompileTimeErrorCode.MAP_ENTRY_NOT_IN_MAP, CompileTimeErrorCode.MEMBER_WITH_CLASS_NAME, CompileTimeErrorCode.MISSING_CONST_IN_LIST_LITERAL, CompileTimeErrorCode.MISSING_CONST_IN_MAP_LITERAL, CompileTimeErrorCode.MISSING_CONST_IN_SET_LITERAL, CompileTimeErrorCode.MISSING_DART_LIBRARY, CompileTimeErrorCode.MISSING_DEFAULT_VALUE_FOR_PARAMETER, CompileTimeErrorCode.MISSING_REQUIRED_ARGUMENT, CompileTimeErrorCode.MIXIN_APPLICATION_CONCRETE_SUPER_INVOKED_MEMBER_TYPE, CompileTimeErrorCode.MIXIN_APPLICATION_NOT_IMPLEMENTED_INTERFACE, CompileTimeErrorCode.MIXIN_APPLICATION_NO_CONCRETE_SUPER_INVOKED_MEMBER, CompileTimeErrorCode.MIXIN_CLASS_DECLARES_CONSTRUCTOR, CompileTimeErrorCode.MIXIN_DECLARES_CONSTRUCTOR, CompileTimeErrorCode.MIXIN_DEFERRED_CLASS, CompileTimeErrorCode.MIXIN_INFERENCE_INCONSISTENT_MATCHING_CLASSES, CompileTimeErrorCode.MIXIN_INFERENCE_NO_MATCHING_CLASS, CompileTimeErrorCode.MIXIN_INFERENCE_NO_POSSIBLE_SUBSTITUTION, CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, CompileTimeErrorCode.MIXIN_INSTANTIATE, CompileTimeErrorCode.MIXIN_OF_DISALLOWED_CLASS, CompileTimeErrorCode.MIXIN_OF_NON_CLASS, CompileTimeErrorCode.MIXIN_REFERENCES_SUPER, CompileTimeErrorCode.MIXIN_SUPER_CLASS_CONSTRAINT_DEFERRED_CLASS, CompileTimeErrorCode.MIXIN_SUPER_CLASS_CONSTRAINT_DISALLOWED_CLASS, CompileTimeErrorCode.MIXIN_SUPER_CLASS_CONSTRAINT_NON_INTERFACE, CompileTimeErrorCode.MIXIN_WITH_NON_CLASS_SUPERCLASS, CompileTimeErrorCode.MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS, CompileTimeErrorCode.MULTIPLE_SUPER_INITIALIZERS, CompileTimeErrorCode.NON_CONSTANT_ANNOTATION_CONSTRUCTOR, CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION, CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE, CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT, CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.NON_CONSTANT_MAP_KEY, CompileTimeErrorCode.NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE, CompileTimeErrorCode.NON_CONSTANT_MAP_ELEMENT, CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.NON_CONSTANT_SET_ELEMENT, // ignore: deprecated_member_use_from_same_package CompileTimeErrorCode.NON_CONSTANT_VALUE_IN_INITIALIZER, CompileTimeErrorCode.NON_CONST_MAP_AS_EXPRESSION_STATEMENT, CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR, CompileTimeErrorCode.NON_SYNC_FACTORY, CompileTimeErrorCode.NOT_ASSIGNED_POTENTIALLY_NON_NULLABLE_LOCAL_VARIABLE, CompileTimeErrorCode.NOT_ENOUGH_POSITIONAL_ARGUMENTS, // ignore: deprecated_member_use_from_same_package CompileTimeErrorCode.NOT_ENOUGH_REQUIRED_ARGUMENTS, CompileTimeErrorCode.NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD, CompileTimeErrorCode.NOT_INITIALIZED_NON_NULLABLE_INSTANCE_FIELD_CONSTRUCTOR, CompileTimeErrorCode.NOT_INITIALIZED_NON_NULLABLE_VARIABLE, CompileTimeErrorCode.NOT_ITERABLE_SPREAD, CompileTimeErrorCode.NOT_MAP_SPREAD, CompileTimeErrorCode.NOT_NULL_AWARE_NULL_SPREAD, CompileTimeErrorCode.NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS, CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT, CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT, CompileTimeErrorCode.NULLABLE_TYPE_IN_CATCH_CLAUSE, CompileTimeErrorCode.NULLABLE_TYPE_IN_EXTENDS_CLAUSE, CompileTimeErrorCode.NULLABLE_TYPE_IN_IMPLEMENTS_CLAUSE, CompileTimeErrorCode.NULLABLE_TYPE_IN_ON_CLAUSE, CompileTimeErrorCode.NULLABLE_TYPE_IN_WITH_CLAUSE, CompileTimeErrorCode.OBJECT_CANNOT_EXTEND_ANOTHER_CLASS, CompileTimeErrorCode.ON_REPEATED, CompileTimeErrorCode.OPTIONAL_PARAMETER_IN_OPERATOR, CompileTimeErrorCode.PART_OF_NON_PART, CompileTimeErrorCode.PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER, CompileTimeErrorCode.PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT, CompileTimeErrorCode.PRIVATE_COLLISION_IN_MIXIN_APPLICATION, CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER, CompileTimeErrorCode.RECURSIVE_COMPILE_TIME_CONSTANT, CompileTimeErrorCode.RECURSIVE_CONSTRUCTOR_REDIRECT, CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT, CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_EXTENDS, CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_IMPLEMENTS, CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_ON, CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_WITH, CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR, CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR, CompileTimeErrorCode.REDIRECT_TO_MISSING_CONSTRUCTOR, CompileTimeErrorCode.REDIRECT_TO_NON_CLASS, CompileTimeErrorCode.REDIRECT_TO_NON_CONST_CONSTRUCTOR, CompileTimeErrorCode.REFERENCED_BEFORE_DECLARATION, CompileTimeErrorCode.RETHROW_OUTSIDE_CATCH, CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR, CompileTimeErrorCode.RETURN_IN_GENERATOR, CompileTimeErrorCode.SET_ELEMENT_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.SHARED_DEFERRED_PREFIX, CompileTimeErrorCode.SPREAD_EXPRESSION_FROM_DEFERRED_LIBRARY, CompileTimeErrorCode.SUPER_INITIALIZER_IN_OBJECT, CompileTimeErrorCode.SUPER_IN_EXTENSION, CompileTimeErrorCode.SUPER_IN_INVALID_CONTEXT, CompileTimeErrorCode.SUPER_IN_REDIRECTING_CONSTRUCTOR, CompileTimeErrorCode.TYPE_ALIAS_CANNOT_REFERENCE_ITSELF, CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS, CompileTimeErrorCode.TYPE_PARAMETER_ON_CONSTRUCTOR, CompileTimeErrorCode.UNDEFINED_ANNOTATION, CompileTimeErrorCode.UNDEFINED_CLASS, CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER, CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT, CompileTimeErrorCode.UNDEFINED_EXTENSION_GETTER, CompileTimeErrorCode.UNDEFINED_EXTENSION_METHOD, CompileTimeErrorCode.UNDEFINED_EXTENSION_OPERATOR, CompileTimeErrorCode.UNDEFINED_EXTENSION_SETTER, CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER, CompileTimeErrorCode.UNQUALIFIED_REFERENCE_TO_STATIC_MEMBER_OF_EXTENDED_TYPE, CompileTimeErrorCode.URI_DOES_NOT_EXIST, CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENERATED, CompileTimeErrorCode.URI_WITH_INTERPOLATION, CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR, CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS, CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER, CompileTimeErrorCode.WRONG_TYPE_PARAMETER_VARIANCE_IN_SUPERINTERFACE, CompileTimeErrorCode.YIELD_EACH_IN_NON_GENERATOR, CompileTimeErrorCode.YIELD_IN_NON_GENERATOR, HintCode.CAN_BE_NULL_AFTER_NULL_AWARE, HintCode.DEAD_CODE, HintCode.DEAD_CODE_CATCH_FOLLOWING_CATCH, HintCode.DEAD_CODE_ON_CATCH_SUBTYPE, HintCode.DEPRECATED_EXTENDS_FUNCTION, HintCode.DEPRECATED_FUNCTION_CLASS_DECLARATION, HintCode.DEPRECATED_MEMBER_USE, HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE, HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE_WITH_MESSAGE, HintCode.DEPRECATED_MEMBER_USE_WITH_MESSAGE, HintCode.DEPRECATED_MIXIN_FUNCTION, HintCode.DIVISION_OPTIMIZATION, HintCode.DUPLICATE_IMPORT, HintCode.DUPLICATE_HIDDEN_NAME, HintCode.DUPLICATE_SHOWN_NAME, HintCode.FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE, HintCode.FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE, HintCode.IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION, HintCode.INFERENCE_FAILURE_ON_COLLECTION_LITERAL, HintCode.INFERENCE_FAILURE_ON_FUNCTION_RETURN_TYPE, HintCode.INFERENCE_FAILURE_ON_INSTANCE_CREATION, HintCode.INFERENCE_FAILURE_ON_UNINITIALIZED_VARIABLE, HintCode.INFERENCE_FAILURE_ON_UNTYPED_PARAMETER, HintCode.INVALID_FACTORY_ANNOTATION, HintCode.INVALID_FACTORY_METHOD_DECL, HintCode.INVALID_FACTORY_METHOD_IMPL, HintCode.INVALID_IMMUTABLE_ANNOTATION, HintCode.INVALID_LITERAL_ANNOTATION, HintCode.INVALID_REQUIRED_NAMED_PARAM, HintCode.INVALID_REQUIRED_OPTIONAL_POSITIONAL_PARAM, // ignore: deprecated_member_use_from_same_package HintCode.INVALID_REQUIRED_PARAM, HintCode.INVALID_REQUIRED_POSITIONAL_PARAM, HintCode.INVALID_SEALED_ANNOTATION, HintCode.INVALID_USE_OF_PROTECTED_MEMBER, HintCode.INVALID_USE_OF_VISIBLE_FOR_TEMPLATE_MEMBER, HintCode.INVALID_USE_OF_VISIBLE_FOR_TESTING_MEMBER, HintCode.INVALID_VISIBILITY_ANNOTATION, HintCode.IS_DOUBLE, HintCode.IS_INT, HintCode.IS_NOT_DOUBLE, HintCode.IS_NOT_INT, HintCode.MISSING_JS_LIB_ANNOTATION, HintCode.MISSING_REQUIRED_PARAM, HintCode.MISSING_REQUIRED_PARAM_WITH_DETAILS, HintCode.MISSING_RETURN, HintCode.MIXIN_ON_SEALED_CLASS, HintCode.MUST_BE_IMMUTABLE, HintCode.MUST_CALL_SUPER, HintCode.NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR, HintCode.NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR_USING_NEW, HintCode.NULL_AWARE_BEFORE_OPERATOR, HintCode.NULL_AWARE_IN_CONDITION, HintCode.NULL_AWARE_IN_LOGICAL_OPERATOR, HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE, HintCode.OVERRIDE_ON_NON_OVERRIDING_FIELD, HintCode.OVERRIDE_ON_NON_OVERRIDING_GETTER, HintCode.OVERRIDE_ON_NON_OVERRIDING_METHOD, HintCode.OVERRIDE_ON_NON_OVERRIDING_SETTER, HintCode.PACKAGE_IMPORT_CONTAINS_DOT_DOT, HintCode.SDK_VERSION_ASYNC_EXPORTED_FROM_CORE, HintCode.SDK_VERSION_AS_EXPRESSION_IN_CONST_CONTEXT, HintCode.SDK_VERSION_BOOL_OPERATOR_IN_CONST_CONTEXT, HintCode.SDK_VERSION_EQ_EQ_OPERATOR_IN_CONST_CONTEXT, HintCode.SDK_VERSION_EXTENSION_METHODS, HintCode.SDK_VERSION_GT_GT_GT_OPERATOR, HintCode.SDK_VERSION_IS_EXPRESSION_IN_CONST_CONTEXT, HintCode.SDK_VERSION_NEVER, HintCode.SDK_VERSION_SET_LITERAL, HintCode.SDK_VERSION_UI_AS_CODE, HintCode.SDK_VERSION_UI_AS_CODE_IN_CONST_CONTEXT, HintCode.STRICT_RAW_TYPE, HintCode.SUBTYPE_OF_SEALED_CLASS, HintCode.TYPE_CHECK_IS_NOT_NULL, HintCode.TYPE_CHECK_IS_NULL, HintCode.UNDEFINED_HIDDEN_NAME, HintCode.UNDEFINED_SHOWN_NAME, HintCode.UNNECESSARY_CAST, HintCode.UNNECESSARY_NO_SUCH_METHOD, HintCode.UNNECESSARY_TYPE_CHECK_FALSE, HintCode.UNNECESSARY_TYPE_CHECK_TRUE, HintCode.UNUSED_CATCH_CLAUSE, HintCode.UNUSED_CATCH_STACK, HintCode.UNUSED_ELEMENT, HintCode.UNUSED_FIELD, HintCode.UNUSED_IMPORT, HintCode.UNUSED_LABEL, HintCode.UNUSED_LOCAL_VARIABLE, HintCode.UNUSED_SHOWN_NAME, ManifestWarningCode.CAMERA_PERMISSIONS_INCOMPATIBLE, ManifestWarningCode.NON_RESIZABLE_ACTIVITY, ManifestWarningCode.NO_TOUCHSCREEN_FEATURE, ManifestWarningCode.PERMISSION_IMPLIES_UNSUPPORTED_HARDWARE, ManifestWarningCode.SETTING_ORIENTATION_ON_ACTIVITY, ManifestWarningCode.UNSUPPORTED_CHROME_OS_FEATURE, ManifestWarningCode.UNSUPPORTED_CHROME_OS_HARDWARE, ParserErrorCode.ABSTRACT_CLASS_MEMBER, ParserErrorCode.ABSTRACT_ENUM, ParserErrorCode.ABSTRACT_STATIC_METHOD, ParserErrorCode.ABSTRACT_TOP_LEVEL_FUNCTION, ParserErrorCode.ABSTRACT_TOP_LEVEL_VARIABLE, ParserErrorCode.ABSTRACT_TYPEDEF, ParserErrorCode.ANNOTATION_WITH_TYPE_ARGUMENTS, ParserErrorCode.ASYNC_KEYWORD_USED_AS_IDENTIFIER, ParserErrorCode.BREAK_OUTSIDE_OF_LOOP, ParserErrorCode.CATCH_SYNTAX, ParserErrorCode.CATCH_SYNTAX_EXTRA_PARAMETERS, ParserErrorCode.CLASS_IN_CLASS, ParserErrorCode.COLON_IN_PLACE_OF_IN, ParserErrorCode.CONFLICTING_MODIFIERS, ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE, ParserErrorCode.CONST_AFTER_FACTORY, ParserErrorCode.CONST_AND_COVARIANT, ParserErrorCode.CONST_AND_FINAL, ParserErrorCode.CONST_AND_VAR, ParserErrorCode.CONST_CLASS, ParserErrorCode.CONST_CONSTRUCTOR_WITH_BODY, ParserErrorCode.CONST_ENUM, ParserErrorCode.CONST_FACTORY, ParserErrorCode.CONST_METHOD, ParserErrorCode.CONST_TYPEDEF, ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP, ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE, ParserErrorCode.COVARIANT_AFTER_FINAL, ParserErrorCode.COVARIANT_AFTER_VAR, ParserErrorCode.COVARIANT_AND_STATIC, ParserErrorCode.COVARIANT_CONSTRUCTOR, ParserErrorCode.COVARIANT_MEMBER, ParserErrorCode.COVARIANT_TOP_LEVEL_DECLARATION, ParserErrorCode.DEFERRED_AFTER_PREFIX, ParserErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE, ParserErrorCode.DIRECTIVE_AFTER_DECLARATION, ParserErrorCode.DUPLICATE_DEFERRED, ParserErrorCode.DUPLICATED_MODIFIER, ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT, ParserErrorCode.DUPLICATE_PREFIX, ParserErrorCode.EMPTY_ENUM_BODY, ParserErrorCode.ENUM_IN_CLASS, ParserErrorCode.EQUALITY_CANNOT_BE_EQUALITY_OPERAND, ParserErrorCode.EXPECTED_BODY, ParserErrorCode.EXPECTED_CASE_OR_DEFAULT, ParserErrorCode.EXPECTED_CLASS_MEMBER, ParserErrorCode.EXPECTED_ELSE_OR_COMMA, ParserErrorCode.EXPECTED_EXECUTABLE, ParserErrorCode.EXPECTED_INSTEAD, ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL, ParserErrorCode.EXPECTED_STRING_LITERAL, ParserErrorCode.EXPECTED_TOKEN, ParserErrorCode.EXPECTED_TYPE_NAME, ParserErrorCode.EXPERIMENT_NOT_ENABLED, ParserErrorCode.EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE, ParserErrorCode.EXTENSION_DECLARES_ABSTRACT_MEMBER, ParserErrorCode.EXTENSION_DECLARES_CONSTRUCTOR, ParserErrorCode.EXTENSION_DECLARES_INSTANCE_FIELD, ParserErrorCode.EXTERNAL_AFTER_CONST, ParserErrorCode.EXTERNAL_AFTER_FACTORY, ParserErrorCode.EXTERNAL_AFTER_STATIC, ParserErrorCode.EXTERNAL_CLASS, ParserErrorCode.EXTERNAL_CONSTRUCTOR_WITH_BODY, ParserErrorCode.EXTERNAL_ENUM, ParserErrorCode.EXTERNAL_FACTORY_REDIRECTION, ParserErrorCode.EXTERNAL_FACTORY_WITH_BODY, ParserErrorCode.EXTERNAL_FIELD, ParserErrorCode.EXTERNAL_GETTER_WITH_BODY, ParserErrorCode.EXTERNAL_METHOD_WITH_BODY, ParserErrorCode.EXTERNAL_OPERATOR_WITH_BODY, ParserErrorCode.EXTERNAL_SETTER_WITH_BODY, ParserErrorCode.EXTERNAL_TYPEDEF, ParserErrorCode.EXTRANEOUS_MODIFIER, ParserErrorCode.FACTORY_TOP_LEVEL_DECLARATION, ParserErrorCode.FACTORY_WITHOUT_BODY, ParserErrorCode.FACTORY_WITH_INITIALIZERS, ParserErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR, ParserErrorCode.FIELD_INITIALIZED_OUTSIDE_DECLARING_CLASS, ParserErrorCode.FINAL_AND_COVARIANT, ParserErrorCode.FINAL_AND_VAR, ParserErrorCode.FINAL_CLASS, ParserErrorCode.FINAL_CONSTRUCTOR, ParserErrorCode.FINAL_ENUM, ParserErrorCode.FINAL_METHOD, ParserErrorCode.FINAL_TYPEDEF, ParserErrorCode.FUNCTION_TYPED_PARAMETER_VAR, ParserErrorCode.GETTER_IN_FUNCTION, ParserErrorCode.GETTER_WITH_PARAMETERS, ParserErrorCode.ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE, ParserErrorCode.IMPLEMENTS_BEFORE_EXTENDS, ParserErrorCode.IMPLEMENTS_BEFORE_ON, ParserErrorCode.IMPLEMENTS_BEFORE_WITH, ParserErrorCode.IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE, ParserErrorCode.INITIALIZED_VARIABLE_IN_FOR_EACH, ParserErrorCode.INVALID_AWAIT_IN_FOR, ParserErrorCode.INVALID_CODE_POINT, ParserErrorCode.INVALID_COMMENT_REFERENCE, ParserErrorCode.INVALID_CONSTRUCTOR_NAME, ParserErrorCode.INVALID_GENERIC_FUNCTION_TYPE, ParserErrorCode.INVALID_HEX_ESCAPE, ParserErrorCode.INVALID_INITIALIZER, ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION, ParserErrorCode.INVALID_OPERATOR, ParserErrorCode.INVALID_OPERATOR_FOR_SUPER, ParserErrorCode.INVALID_OPERATOR_QUESTIONMARK_PERIOD_FOR_SUPER, ParserErrorCode.INVALID_STAR_AFTER_ASYNC, ParserErrorCode.INVALID_SYNC, ParserErrorCode.INVALID_UNICODE_ESCAPE, ParserErrorCode.LIBRARY_DIRECTIVE_NOT_FIRST, ParserErrorCode.LOCAL_FUNCTION_DECLARATION_MODIFIER, ParserErrorCode.MISSING_ASSIGNABLE_SELECTOR, ParserErrorCode.MISSING_ASSIGNMENT_IN_INITIALIZER, ParserErrorCode.MISSING_CATCH_OR_FINALLY, ParserErrorCode.MISSING_CLASS_BODY, ParserErrorCode.MISSING_CLOSING_PARENTHESIS, ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE, ParserErrorCode.MISSING_ENUM_BODY, ParserErrorCode.MISSING_EXPRESSION_IN_INITIALIZER, ParserErrorCode.MISSING_EXPRESSION_IN_THROW, ParserErrorCode.MISSING_FUNCTION_BODY, ParserErrorCode.MISSING_FUNCTION_KEYWORD, ParserErrorCode.MISSING_FUNCTION_PARAMETERS, ParserErrorCode.MISSING_GET, ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.MISSING_INITIALIZER, ParserErrorCode.MISSING_KEYWORD_OPERATOR, ParserErrorCode.MISSING_METHOD_PARAMETERS, ParserErrorCode.MISSING_NAME_FOR_NAMED_PARAMETER, ParserErrorCode.MISSING_NAME_IN_LIBRARY_DIRECTIVE, ParserErrorCode.MISSING_NAME_IN_PART_OF_DIRECTIVE, ParserErrorCode.MISSING_PREFIX_IN_DEFERRED_IMPORT, ParserErrorCode.MISSING_STAR_AFTER_SYNC, ParserErrorCode.MISSING_STATEMENT, ParserErrorCode.MISSING_TERMINATOR_FOR_PARAMETER_GROUP, ParserErrorCode.MISSING_TYPEDEF_PARAMETERS, ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH, ParserErrorCode.MIXED_PARAMETER_GROUPS, ParserErrorCode.MIXIN_DECLARES_CONSTRUCTOR, ParserErrorCode.MODIFIER_OUT_OF_ORDER, ParserErrorCode.MULTIPLE_EXTENDS_CLAUSES, ParserErrorCode.MULTIPLE_ON_CLAUSES, ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES, ParserErrorCode.MULTIPLE_LIBRARY_DIRECTIVES, ParserErrorCode.MULTIPLE_NAMED_PARAMETER_GROUPS, ParserErrorCode.MULTIPLE_PART_OF_DIRECTIVES, ParserErrorCode.MULTIPLE_POSITIONAL_PARAMETER_GROUPS, ParserErrorCode.MULTIPLE_VARIABLES_IN_FOR_EACH, ParserErrorCode.MULTIPLE_VARIANCE_MODIFIERS, ParserErrorCode.MULTIPLE_WITH_CLAUSES, ParserErrorCode.NAMED_FUNCTION_EXPRESSION, ParserErrorCode.NAMED_FUNCTION_TYPE, ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP, ParserErrorCode.NATIVE_CLAUSE_IN_NON_SDK_CODE, ParserErrorCode.NATIVE_CLAUSE_SHOULD_BE_ANNOTATION, ParserErrorCode.NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE, ParserErrorCode.NON_CONSTRUCTOR_FACTORY, ParserErrorCode.NON_IDENTIFIER_LIBRARY_NAME, ParserErrorCode.NON_PART_OF_DIRECTIVE_IN_PART, ParserErrorCode.NON_STRING_LITERAL_AS_URI, ParserErrorCode.NON_USER_DEFINABLE_OPERATOR, ParserErrorCode.NORMAL_BEFORE_OPTIONAL_PARAMETERS, ParserErrorCode.NULL_AWARE_CASCADE_OUT_OF_ORDER, ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT, ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP, ParserErrorCode.PREFIX_AFTER_COMBINATOR, ParserErrorCode.REDIRECTING_CONSTRUCTOR_WITH_BODY, ParserErrorCode.REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR, ParserErrorCode.SETTER_IN_FUNCTION, ParserErrorCode.STACK_OVERFLOW, ParserErrorCode.STATIC_AFTER_CONST, ParserErrorCode.STATIC_AFTER_FINAL, ParserErrorCode.STATIC_AFTER_VAR, ParserErrorCode.STATIC_CONSTRUCTOR, ParserErrorCode.STATIC_GETTER_WITHOUT_BODY, ParserErrorCode.STATIC_OPERATOR, ParserErrorCode.STATIC_SETTER_WITHOUT_BODY, ParserErrorCode.STATIC_TOP_LEVEL_DECLARATION, ParserErrorCode.INVALID_SUPER_IN_INITIALIZER, ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE, ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES, ParserErrorCode.INVALID_THIS_IN_INITIALIZER, ParserErrorCode.TOP_LEVEL_OPERATOR, ParserErrorCode.TYPEDEF_IN_CLASS, ParserErrorCode.TYPE_ARGUMENTS_ON_TYPE_VARIABLE, ParserErrorCode.TYPE_BEFORE_FACTORY, ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP, ParserErrorCode.UNEXPECTED_TOKEN, ParserErrorCode.VAR_AND_TYPE, ParserErrorCode.VAR_AS_TYPE_NAME, ParserErrorCode.VAR_CLASS, ParserErrorCode.VAR_ENUM, ParserErrorCode.VAR_RETURN_TYPE, ParserErrorCode.VAR_TYPEDEF, ParserErrorCode.WITH_BEFORE_EXTENDS, ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER, ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP, ResolverErrorCode.BREAK_LABEL_ON_SWITCH_MEMBER, ResolverErrorCode.CONTINUE_LABEL_ON_SWITCH, ResolverErrorCode.PART_OF_UNNAMED_LIBRARY, ScannerErrorCode.EXPECTED_TOKEN, ScannerErrorCode.ILLEGAL_CHARACTER, ScannerErrorCode.MISSING_DIGIT, ScannerErrorCode.MISSING_HEX_DIGIT, ScannerErrorCode.MISSING_IDENTIFIER, ScannerErrorCode.MISSING_QUOTE, ScannerErrorCode.UNABLE_GET_CONTENT, ScannerErrorCode.UNEXPECTED_DOLLAR_IN_STRING, ScannerErrorCode.UNSUPPORTED_OPERATOR, ScannerErrorCode.UNTERMINATED_MULTI_LINE_COMMENT, ScannerErrorCode.UNTERMINATED_STRING_LITERAL, StaticTypeWarningCode.EXPECTED_ONE_LIST_TYPE_ARGUMENTS, StaticTypeWarningCode.EXPECTED_ONE_SET_TYPE_ARGUMENTS, StaticTypeWarningCode.EXPECTED_TWO_MAP_TYPE_ARGUMENTS, StaticTypeWarningCode.FOR_IN_OF_INVALID_ELEMENT_TYPE, StaticTypeWarningCode.FOR_IN_OF_INVALID_TYPE, StaticTypeWarningCode.ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE, StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE, StaticTypeWarningCode.ILLEGAL_SYNC_GENERATOR_RETURN_TYPE, StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER, StaticTypeWarningCode.INVALID_ASSIGNMENT, StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION, StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION_EXPRESSION, StaticTypeWarningCode.NON_BOOL_CONDITION, StaticTypeWarningCode.NON_BOOL_EXPRESSION, StaticTypeWarningCode.NON_BOOL_NEGATION_EXPRESSION, StaticTypeWarningCode.NON_BOOL_OPERAND, StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT, StaticTypeWarningCode.RETURN_OF_INVALID_TYPE, StaticTypeWarningCode.RETURN_OF_INVALID_TYPE_FROM_CLOSURE, StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND, StaticTypeWarningCode.UNDEFINED_ENUM_CONSTANT, StaticTypeWarningCode.UNDEFINED_FUNCTION, StaticTypeWarningCode.UNDEFINED_GETTER, StaticTypeWarningCode.UNDEFINED_METHOD, StaticTypeWarningCode.UNDEFINED_OPERATOR, StaticTypeWarningCode.UNDEFINED_PREFIXED_NAME, StaticTypeWarningCode.UNDEFINED_SETTER, StaticTypeWarningCode.UNDEFINED_SUPER_GETTER, StaticTypeWarningCode.UNDEFINED_SUPER_METHOD, StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR, StaticTypeWarningCode.UNDEFINED_SUPER_SETTER, StaticTypeWarningCode.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER, StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS, StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR, StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS_METHOD, StaticTypeWarningCode.YIELD_OF_INVALID_TYPE, StaticWarningCode.AMBIGUOUS_IMPORT, StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE, StaticWarningCode.ASSIGNMENT_TO_CONST, StaticWarningCode.ASSIGNMENT_TO_FINAL, StaticWarningCode.ASSIGNMENT_TO_FINAL_LOCAL, StaticWarningCode.ASSIGNMENT_TO_FINAL_NO_SETTER, StaticWarningCode.ASSIGNMENT_TO_FUNCTION, StaticWarningCode.ASSIGNMENT_TO_METHOD, StaticWarningCode.ASSIGNMENT_TO_TYPE, StaticWarningCode.CASE_BLOCK_NOT_TERMINATED, StaticWarningCode.CAST_TO_NON_TYPE, StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER, StaticWarningCode.CONST_WITH_ABSTRACT_CLASS, StaticWarningCode.EXPORT_DUPLICATED_LIBRARY_NAMED, // ignore: deprecated_member_use_from_same_package StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS, // ignore: deprecated_member_use_from_same_package StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS_COULD_BE_NAMED, StaticWarningCode.FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION, StaticWarningCode.FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR, StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE, StaticWarningCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE, StaticWarningCode.FINAL_NOT_INITIALIZED, StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_1, StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_2, StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS, StaticWarningCode.IMPORT_DUPLICATED_LIBRARY_NAMED, // ignore: deprecated_member_use_from_same_package StaticWarningCode.IMPORT_OF_NON_LIBRARY, StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED, StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL, StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE, StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE, StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE, StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES, StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH, StaticWarningCode.MIXED_RETURN_TYPES, StaticWarningCode.NEW_WITH_ABSTRACT_CLASS, StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS, StaticWarningCode.NEW_WITH_NON_TYPE, StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR, StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT, StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS, StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR, StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE, StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE, StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO, StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE, StaticWarningCode.NON_VOID_RETURN_FOR_OPERATOR, StaticWarningCode.NON_VOID_RETURN_FOR_SETTER, StaticWarningCode.NOT_A_TYPE, // ignore: deprecated_member_use_from_same_package StaticWarningCode.NOT_ENOUGH_REQUIRED_ARGUMENTS, StaticWarningCode.PART_OF_DIFFERENT_LIBRARY, StaticWarningCode.REDIRECT_TO_INVALID_FUNCTION_TYPE, StaticWarningCode.REDIRECT_TO_INVALID_RETURN_TYPE, // ignore: deprecated_member_use_from_same_package StaticWarningCode.REDIRECT_TO_MISSING_CONSTRUCTOR, // ignore: deprecated_member_use_from_same_package StaticWarningCode.REDIRECT_TO_NON_CLASS, StaticWarningCode.RETURN_WITHOUT_VALUE, StaticWarningCode.SET_ELEMENT_TYPE_NOT_ASSIGNABLE, StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER, StaticWarningCode.SWITCH_EXPRESSION_NOT_ASSIGNABLE, StaticWarningCode.TYPE_ANNOTATION_DEFERRED_CLASS, StaticWarningCode.TYPE_PARAMETER_REFERENCED_BY_STATIC, StaticWarningCode.TYPE_TEST_WITH_NON_TYPE, StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME, StaticWarningCode.UNCHECKED_USE_OF_NULLABLE_VALUE, // ignore: deprecated_member_use_from_same_package StaticWarningCode.UNDEFINED_CLASS, StaticWarningCode.UNDEFINED_CLASS_BOOLEAN, StaticWarningCode.UNDEFINED_IDENTIFIER, StaticWarningCode.UNDEFINED_IDENTIFIER_AWAIT, // ignore: deprecated_member_use_from_same_package StaticWarningCode.UNDEFINED_NAMED_PARAMETER, StaticWarningCode.UNNECESSARY_NON_NULL_ASSERTION, StaticWarningCode.UNNECESSARY_NULL_AWARE_CALL, StaticWarningCode.UNNECESSARY_NULL_AWARE_SPREAD, StaticWarningCode.USE_OF_VOID_RESULT, StaticWarningCode.UNCHECKED_USE_OF_NULLABLE_VALUE, StaticWarningCode.INVALID_USE_OF_NULL_VALUE, StaticWarningCode.INVALID_USE_OF_NEVER_VALUE, StrongModeCode.ASSIGNMENT_CAST, StrongModeCode.COULD_NOT_INFER, StrongModeCode.DOWN_CAST_COMPOSITE, StrongModeCode.DOWN_CAST_IMPLICIT, StrongModeCode.DOWN_CAST_IMPLICIT_ASSIGN, StrongModeCode.DYNAMIC_CAST, StrongModeCode.DYNAMIC_INVOKE, StrongModeCode.IMPLICIT_DYNAMIC_FIELD, StrongModeCode.IMPLICIT_DYNAMIC_FUNCTION, StrongModeCode.IMPLICIT_DYNAMIC_INVOKE, StrongModeCode.IMPLICIT_DYNAMIC_LIST_LITERAL, StrongModeCode.IMPLICIT_DYNAMIC_MAP_LITERAL, StrongModeCode.IMPLICIT_DYNAMIC_METHOD, StrongModeCode.IMPLICIT_DYNAMIC_PARAMETER, StrongModeCode.IMPLICIT_DYNAMIC_RETURN, StrongModeCode.IMPLICIT_DYNAMIC_TYPE, StrongModeCode.IMPLICIT_DYNAMIC_VARIABLE, StrongModeCode.INFERRED_TYPE, StrongModeCode.INFERRED_TYPE_ALLOCATION, StrongModeCode.INFERRED_TYPE_CLOSURE, StrongModeCode.INFERRED_TYPE_LITERAL, StrongModeCode.INVALID_CAST_LITERAL, StrongModeCode.INVALID_CAST_LITERAL_LIST, StrongModeCode.INVALID_CAST_LITERAL_MAP, StrongModeCode.INVALID_CAST_LITERAL_SET, StrongModeCode.INVALID_CAST_FUNCTION_EXPR, StrongModeCode.INVALID_CAST_NEW_EXPR, StrongModeCode.INVALID_CAST_METHOD, StrongModeCode.INVALID_CAST_FUNCTION, StrongModeCode.INVALID_PARAMETER_DECLARATION, StrongModeCode.INVALID_SUPER_INVOCATION, StrongModeCode.NON_GROUND_TYPE_CHECK_INFO, StrongModeCode.NOT_INSTANTIATED_BOUND, StrongModeCode.TOP_LEVEL_CYCLE, StrongModeCode.TOP_LEVEL_FUNCTION_LITERAL_BLOCK, StrongModeCode.TOP_LEVEL_IDENTIFIER_NO_TYPE, StrongModeCode.TOP_LEVEL_INSTANCE_GETTER, StrongModeCode.TOP_LEVEL_INSTANCE_METHOD, TodoCode.TODO, ]; /** * The lazy initialized map from [ErrorCode.uniqueName] to the [ErrorCode] * instance. */ HashMap<String, ErrorCode> _uniqueNameToCodeMap; /** * Return the [ErrorCode] with the given [uniqueName], or `null` if not * found. */ ErrorCode errorCodeByUniqueName(String uniqueName) { if (_uniqueNameToCodeMap == null) { _uniqueNameToCodeMap = new HashMap<String, ErrorCode>(); for (ErrorCode errorCode in errorCodeValues) { _uniqueNameToCodeMap[errorCode.uniqueName] = errorCode; } } return _uniqueNameToCodeMap[uniqueName]; } /** * An error discovered during the analysis of some Dart code. * * See [AnalysisErrorListener]. */ class AnalysisError implements Diagnostic { /** * An empty array of errors used when no errors are expected. */ static const List<AnalysisError> NO_ERRORS = const <AnalysisError>[]; /** * A [Comparator] that sorts by the name of the file that the [AnalysisError] * was found. */ static Comparator<AnalysisError> FILE_COMPARATOR = (AnalysisError o1, AnalysisError o2) => o1.source.shortName.compareTo(o2.source.shortName); /** * A [Comparator] that sorts error codes first by their severity (errors * first, warnings second), and then by the error code type. */ static Comparator<AnalysisError> ERROR_CODE_COMPARATOR = (AnalysisError o1, AnalysisError o2) { ErrorCode errorCode1 = o1.errorCode; ErrorCode errorCode2 = o2.errorCode; ErrorSeverity errorSeverity1 = errorCode1.errorSeverity; ErrorSeverity errorSeverity2 = errorCode2.errorSeverity; if (errorSeverity1 == errorSeverity2) { ErrorType errorType1 = errorCode1.type; ErrorType errorType2 = errorCode2.type; return errorType1.compareTo(errorType2); } else { return errorSeverity2.compareTo(errorSeverity1); } }; /** * The error code associated with the error. */ final ErrorCode errorCode; /** * The message describing the problem. */ DiagnosticMessage _problemMessage; /** * The context messages associated with the problem. This list will be empty * if there are no context messages. */ List<DiagnosticMessage> _contextMessages; /** * The correction to be displayed for this error, or `null` if there is no * correction information for this error. */ String _correction; /** * The source in which the error occurred, or `null` if unknown. */ final Source source; /** * Initialize a newly created analysis error. The error is associated with the * given [source] and is located at the given [offset] with the given * [length]. The error will have the given [errorCode] and the list of * [arguments] will be used to complete the message and correction. If any * [contextMessages] are provided, they will be recorded with the error. */ AnalysisError(this.source, int offset, int length, this.errorCode, [List<Object> arguments, List<DiagnosticMessage> contextMessages = const []]) { String message = formatList(errorCode.message, arguments); String correctionTemplate = errorCode.correction; if (correctionTemplate != null) { this._correction = formatList(correctionTemplate, arguments); } _problemMessage = new DiagnosticMessageImpl( filePath: source?.fullName, length: length, message: message, offset: offset); _contextMessages = contextMessages; } /** * Initialize a newly created analysis error with given values. */ AnalysisError.forValues(this.source, int offset, int length, this.errorCode, String message, this._correction, {List<DiagnosticMessage> contextMessages = const []}) { _problemMessage = new DiagnosticMessageImpl( filePath: source?.fullName, length: length, message: message, offset: offset); _contextMessages = contextMessages; } List<DiagnosticMessage> get contextMessages => _contextMessages; /** * Return the template used to create the correction to be displayed for this * error, or `null` if there is no correction information for this error. The * correction should indicate how the user can fix the error. */ String get correction => _correction; @override String get correctionMessage => _correction; @override int get hashCode { int hashCode = offset; hashCode ^= (message != null) ? message.hashCode : 0; hashCode ^= (source != null) ? source.hashCode : 0; return hashCode; } /** * The number of characters from the offset to the end of the source which * encompasses the compilation error. */ int get length => _problemMessage.length; /** * Return the message to be displayed for this error. The message should * indicate what is wrong and why it is wrong. */ String get message => _problemMessage.message; /** * The character offset from the beginning of the source (zero based) where * the error occurred. */ int get offset => _problemMessage.offset; @override DiagnosticMessage get problemMessage => _problemMessage; @override Severity get severity { switch (errorCode.errorSeverity) { case ErrorSeverity.ERROR: return Severity.error; case ErrorSeverity.WARNING: return Severity.warning; case ErrorSeverity.INFO: return Severity.info; default: throw new StateError( 'Invalid error severity: ${errorCode.errorSeverity}'); } } @override bool operator ==(Object other) { if (identical(other, this)) { return true; } // prepare other AnalysisError if (other is AnalysisError) { // Quick checks. if (!identical(errorCode, other.errorCode)) { return false; } if (offset != other.offset || length != other.length) { return false; } // Deep checks. if (message != other.message) { return false; } if (source != other.source) { return false; } // OK return true; } return false; } @override String toString() { StringBuffer buffer = new StringBuffer(); buffer.write((source != null) ? source.fullName : "<unknown source>"); buffer.write("("); buffer.write(offset); buffer.write(".."); buffer.write(offset + length - 1); buffer.write("): "); //buffer.write("(" + lineNumber + ":" + columnNumber + "): "); buffer.write(message); return buffer.toString(); } /** * Merge all of the errors in the lists in the given list of [errorLists] into * a single list of errors. */ static List<AnalysisError> mergeLists(List<List<AnalysisError>> errorLists) { Set<AnalysisError> errors = new HashSet<AnalysisError>(); for (List<AnalysisError> errorList in errorLists) { errors.addAll(errorList); } return errors.toList(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/error/listener.dart
// Copyright (c) 2014, 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart' show AstNode; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/source.dart'; import 'package:front_end/src/fasta/fasta_codes.dart' show Message; import 'package:source_span/source_span.dart'; /** * An object that listen for [AnalysisError]s being produced by the analysis * engine. */ abstract class AnalysisErrorListener { /** * An error listener that ignores errors that are reported to it. */ static final AnalysisErrorListener NULL_LISTENER = new _NullErrorListener(); /** * This method is invoked when an [error] has been found by the analysis * engine. */ void onError(AnalysisError error); } /** * An [AnalysisErrorListener] that keeps track of whether any error has been * reported to it. */ class BooleanErrorListener implements AnalysisErrorListener { /** * A flag indicating whether an error has been reported to this listener. */ bool _errorReported = false; /** * Return `true` if an error has been reported to this listener. */ bool get errorReported => _errorReported; @override void onError(AnalysisError error) { _errorReported = true; } } /** * An object used to create analysis errors and report then to an error * listener. */ class ErrorReporter { /** * The error listener to which errors will be reported. */ final AnalysisErrorListener _errorListener; /** * The default source to be used when reporting errors. */ final Source _defaultSource; /** * The source to be used when reporting errors. */ Source _source; /** * Initialize a newly created error reporter that will report errors to the * given [_errorListener]. Errors will be reported against the * [_defaultSource] unless another source is provided later. */ ErrorReporter(this._errorListener, this._defaultSource) { if (_errorListener == null) { throw new ArgumentError("An error listener must be provided"); } else if (_defaultSource == null) { throw new ArgumentError("A default source must be provided"); } this._source = _defaultSource; } Source get source => _source; /** * Set the source to be used when reporting errors to the given [source]. * Setting the source to `null` will cause the default source to be used. */ void set source(Source source) { this._source = source ?? _defaultSource; } /** * Report the given [error]. */ void reportError(AnalysisError error) { _errorListener.onError(error); } /** * Report an error with the given [errorCode] and [arguments]. The [element] * is used to compute the location of the error. */ void reportErrorForElement(ErrorCode errorCode, Element element, [List<Object> arguments]) { int length = 0; if (element is ImportElement) { length = 6; // 'import'.length } else if (element is ExportElement) { length = 6; // 'export'.length } else { length = element.nameLength; } reportErrorForOffset(errorCode, element.nameOffset, length, arguments); } /** * Report an error with the given [errorCode] and [arguments]. * The [node] is used to compute the location of the error. * * If the arguments contain the names of two or more types, the method * [reportTypeErrorForNode] should be used and the types * themselves (rather than their names) should be passed as arguments. */ void reportErrorForNode(ErrorCode errorCode, AstNode node, [List<Object> arguments]) { reportErrorForOffset(errorCode, node.offset, node.length, arguments); } /** * Report an error with the given [errorCode] and [arguments]. The location of * the error is specified by the given [offset] and [length]. */ void reportErrorForOffset(ErrorCode errorCode, int offset, int length, [List<Object> arguments]) { _errorListener.onError( new AnalysisError(_source, offset, length, errorCode, arguments)); } /** * Report an error with the given [errorCode] and [arguments]. The location of * the error is specified by the given [span]. */ void reportErrorForSpan(ErrorCode errorCode, SourceSpan span, [List<Object> arguments]) { reportErrorForOffset(errorCode, span.start.offset, span.length, arguments); } /** * Report an error with the given [errorCode] and [arguments]. The [token] is * used to compute the location of the error. */ void reportErrorForToken(ErrorCode errorCode, Token token, [List<Object> arguments]) { reportErrorForOffset(errorCode, token.offset, token.length, arguments); } /** * Report an error with the given [errorCode] and [message]. The location of * the error is specified by the given [offset] and [length]. */ void reportErrorMessage( ErrorCode errorCode, int offset, int length, Message message) { _errorListener.onError(new AnalysisError.forValues( _source, offset, length, errorCode, message.message, message.tip)); } /** * Report an error with the given [errorCode] and [arguments]. The [node] is * used to compute the location of the error. The arguments are expected to * contain two or more types. Convert the types into strings by using the * display names of the types, unless there are two or more types with the * same names, in which case the extended display names of the types will be * used in order to clarify the message. * * If there are not two or more types in the argument list, the method * [reportErrorForNode] should be used instead. */ void reportTypeErrorForNode( ErrorCode errorCode, AstNode node, List<Object> arguments) { _convertTypeNames(arguments); reportErrorForOffset(errorCode, node.offset, node.length, arguments); } /** * Given an array of [arguments] that is expected to contain two or more * types, convert the types into strings by using the display names of the * types, unless there are two or more types with the same names, in which * case the extended display names of the types will be used in order to * clarify the message. */ void _convertTypeNames(List<Object> arguments) { String computeDisplayName(DartType type) { if (type is FunctionType) { String name = type.name; if (name != null && name.isNotEmpty) { StringBuffer buffer = new StringBuffer(); buffer.write(name); (type as TypeImpl).appendTo(buffer, new Set.identity()); return buffer.toString(); } } return type.displayName; } Map<String, List<_TypeToConvert>> typeGroups = {}; for (int i = 0; i < arguments.length; i++) { Object argument = arguments[i]; if (argument is DartType) { String displayName = computeDisplayName(argument); List<_TypeToConvert> types = typeGroups.putIfAbsent(displayName, () => <_TypeToConvert>[]); types.add(new _TypeToConvert(i, argument, displayName)); } } for (List<_TypeToConvert> typeGroup in typeGroups.values) { if (typeGroup.length == 1) { _TypeToConvert typeToConvert = typeGroup[0]; if (typeToConvert.type is DartType) { arguments[typeToConvert.index] = typeToConvert.displayName; } } else { Map<String, Set<Element>> nameToElementMap = {}; for (_TypeToConvert typeToConvert in typeGroup) { for (Element element in typeToConvert.allElements()) { Set<Element> elements = nameToElementMap.putIfAbsent( element.name, () => new Set<Element>()); elements.add(element); } } for (_TypeToConvert typeToConvert in typeGroup) { // TODO(brianwilkerson) When analyzer supports info or context // messages, expose the additional information that way (rather // than being poorly inserted into the problem message). StringBuffer buffer; for (Element element in typeToConvert.allElements()) { String name = element.name; if (nameToElementMap[name].length > 1) { if (buffer == null) { buffer = new StringBuffer(); buffer.write('where '); } else { buffer.write(', '); } buffer.write('$name is defined in ${element.source.fullName}'); } } if (buffer != null) { arguments[typeToConvert.index] = '${typeToConvert.displayName} ($buffer)'; } else { arguments[typeToConvert.index] = typeToConvert.displayName; } } } } } } /** * An error listener that will record the errors that are reported to it in a * way that is appropriate for caching those errors within an analysis context. */ class RecordingErrorListener implements AnalysisErrorListener { Set<AnalysisError> _errors; /** * Return the errors collected by the listener. */ List<AnalysisError> get errors { if (_errors == null) { return const <AnalysisError>[]; } return _errors.toList(); } /** * Return the errors collected by the listener for the given [source]. */ List<AnalysisError> getErrorsForSource(Source source) { if (_errors == null) { return const <AnalysisError>[]; } return _errors.where((error) => error.source == source).toList(); } @override void onError(AnalysisError error) { _errors ??= new HashSet<AnalysisError>(); _errors.add(error); } } /** * An [AnalysisErrorListener] that ignores error. */ class _NullErrorListener implements AnalysisErrorListener { @override void onError(AnalysisError event) { // Ignore errors } } /** * Used by `ErrorReporter._convertTypeNames` to keep track of a type that is * being converted. */ class _TypeToConvert { final int index; final DartType type; final String displayName; List<Element> _allElements; _TypeToConvert(this.index, this.type, this.displayName); List<Element> allElements() { if (_allElements == null) { Set<Element> elements = new Set<Element>(); void addElementsFrom(DartType type) { if (type is FunctionType) { addElementsFrom(type.returnType); for (ParameterElement parameter in type.parameters) { addElementsFrom(parameter.type); } } else if (type is InterfaceType) { if (elements.add(type.element)) { for (DartType typeArgument in type.typeArguments) { addElementsFrom(typeArgument); } } } } addElementsFrom(type); _allElements = elements .where((element) => element.name != null && element.name.isNotEmpty) .toList(); } return _allElements; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/browser_client.dart
// Copyright (c) 2012, 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. export 'src/browser_client.dart' show BrowserClient;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/http.dart
// Copyright (c) 2013, 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. /// A composable, [Future]-based library for making HTTP requests. import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'src/client.dart'; import 'src/response.dart'; export 'src/base_client.dart'; export 'src/base_request.dart'; export 'src/base_response.dart'; export 'src/byte_stream.dart'; export 'src/client.dart'; export 'src/exception.dart'; export 'src/multipart_file.dart'; export 'src/multipart_request.dart'; export 'src/request.dart'; export 'src/response.dart'; export 'src/streamed_request.dart'; export 'src/streamed_response.dart'; /// Sends an HTTP HEAD request with the given headers to the given URL, which /// can be a [Uri] or a [String]. /// /// This automatically initializes a new [Client] and closes that client once /// the request is complete. If you're planning on making multiple requests to /// the same server, you should use a single [Client] for all of those requests. /// /// For more fine-grained control over the request, use [Request] instead. Future<Response> head(url, {Map<String, String> headers}) => _withClient((client) => client.head(url, headers: headers)); /// Sends an HTTP GET request with the given headers to the given URL, which can /// be a [Uri] or a [String]. /// /// This automatically initializes a new [Client] and closes that client once /// the request is complete. If you're planning on making multiple requests to /// the same server, you should use a single [Client] for all of those requests. /// /// For more fine-grained control over the request, use [Request] instead. Future<Response> get(url, {Map<String, String> headers}) => _withClient((client) => client.get(url, headers: headers)); /// Sends an HTTP POST request with the given headers and body to the given URL, /// which can be a [Uri] or a [String]. /// /// [body] sets the body of the request. It can be a [String], a [List<int>] or /// a [Map<String, String>]. If it's a String, it's encoded using [encoding] and /// used as the body of the request. The content-type of the request will /// default to "text/plain". /// /// If [body] is a List, it's used as a list of bytes for the body of the /// request. /// /// If [body] is a Map, it's encoded as form fields using [encoding]. The /// content-type of the request will be set to /// `"application/x-www-form-urlencoded"`; this cannot be overridden. /// /// [encoding] defaults to [utf8]. /// /// For more fine-grained control over the request, use [Request] or /// [StreamedRequest] instead. Future<Response> post(url, {Map<String, String> headers, body, Encoding encoding}) => _withClient((client) => client.post(url, headers: headers, body: body, encoding: encoding)); /// Sends an HTTP PUT request with the given headers and body to the given URL, /// which can be a [Uri] or a [String]. /// /// [body] sets the body of the request. It can be a [String], a [List<int>] or /// a [Map<String, String>]. If it's a String, it's encoded using [encoding] and /// used as the body of the request. The content-type of the request will /// default to "text/plain". /// /// If [body] is a List, it's used as a list of bytes for the body of the /// request. /// /// If [body] is a Map, it's encoded as form fields using [encoding]. The /// content-type of the request will be set to /// `"application/x-www-form-urlencoded"`; this cannot be overridden. /// /// [encoding] defaults to [utf8]. /// /// For more fine-grained control over the request, use [Request] or /// [StreamedRequest] instead. Future<Response> put(url, {Map<String, String> headers, body, Encoding encoding}) => _withClient((client) => client.put(url, headers: headers, body: body, encoding: encoding)); /// Sends an HTTP PATCH request with the given headers and body to the given /// URL, which can be a [Uri] or a [String]. /// /// [body] sets the body of the request. It can be a [String], a [List<int>] or /// a [Map<String, String>]. If it's a String, it's encoded using [encoding] and /// used as the body of the request. The content-type of the request will /// default to "text/plain". /// /// If [body] is a List, it's used as a list of bytes for the body of the /// request. /// /// If [body] is a Map, it's encoded as form fields using [encoding]. The /// content-type of the request will be set to /// `"application/x-www-form-urlencoded"`; this cannot be overridden. /// /// [encoding] defaults to [utf8]. /// /// For more fine-grained control over the request, use [Request] or /// [StreamedRequest] instead. Future<Response> patch(url, {Map<String, String> headers, body, Encoding encoding}) => _withClient((client) => client.patch(url, headers: headers, body: body, encoding: encoding)); /// Sends an HTTP DELETE request with the given headers to the given URL, which /// can be a [Uri] or a [String]. /// /// This automatically initializes a new [Client] and closes that client once /// the request is complete. If you're planning on making multiple requests to /// the same server, you should use a single [Client] for all of those requests. /// /// For more fine-grained control over the request, use [Request] instead. Future<Response> delete(url, {Map<String, String> headers}) => _withClient((client) => client.delete(url, headers: headers)); /// Sends an HTTP GET request with the given headers to the given URL, which can /// be a [Uri] or a [String], and returns a Future that completes to the body of /// the response as a [String]. /// /// The Future will emit a [ClientException] if the response doesn't have a /// success status code. /// /// This automatically initializes a new [Client] and closes that client once /// the request is complete. If you're planning on making multiple requests to /// the same server, you should use a single [Client] for all of those requests. /// /// For more fine-grained control over the request and response, use [Request] /// instead. Future<String> read(url, {Map<String, String> headers}) => _withClient((client) => client.read(url, headers: headers)); /// Sends an HTTP GET request with the given headers to the given URL, which can /// be a [Uri] or a [String], and returns a Future that completes to the body of /// the response as a list of bytes. /// /// The Future will emit a [ClientException] if the response doesn't have a /// success status code. /// /// This automatically initializes a new [Client] and closes that client once /// the request is complete. If you're planning on making multiple requests to /// the same server, you should use a single [Client] for all of those requests. /// /// For more fine-grained control over the request and response, use [Request] /// instead. Future<Uint8List> readBytes(url, {Map<String, String> headers}) => _withClient((client) => client.readBytes(url, headers: headers)); Future<T> _withClient<T>(Future<T> Function(Client) fn) async { var client = Client(); try { return await fn(client); } finally { client.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/testing.dart
// Copyright (c) 2012, 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. /// This library contains testing classes for the HTTP library. /// /// The [MockClient] class is a drop-in replacement for `http.Client` that /// allows test code to set up a local request handler in order to fake a server /// that responds to HTTP requests: /// /// import 'dart:convert'; /// import 'package:http/testing.dart'; /// /// var client = MockClient((request) async { /// if (request.url.path != "/data.json") { /// return Response("", 404); /// } /// return Response( /// json.encode({ /// 'numbers': [1, 4, 15, 19, 214] /// }), /// 200, /// headers: {'content-type': 'application/json'}); /// }); export 'src/mock_client.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/io_client.dart
// Copyright (c) 2018, 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. export 'src/io_client.dart' show IOClient; export 'src/io_streamed_response.dart' show IOStreamedResponse;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/multipart_file_io.dart
// Copyright (c) 2018, 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 'dart:async'; import 'dart:io'; import 'package:http_parser/http_parser.dart'; import 'package:path/path.dart' as p; import 'byte_stream.dart'; import 'multipart_file.dart'; Future<MultipartFile> multipartFileFromPath(String field, String filePath, {String filename, MediaType contentType}) async { filename ??= p.basename(filePath); var file = File(filePath); var length = await file.length(); var stream = ByteStream(file.openRead()); return MultipartFile(field, stream, length, filename: filename, contentType: contentType); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/base_response.dart
// Copyright (c) 2012, 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 'base_request.dart'; /// The base class for HTTP responses. /// /// Subclasses of [BaseResponse] are usually not constructed manually; instead, /// they're returned by [BaseClient.send] or other HTTP client methods. abstract class BaseResponse { /// The (frozen) request that triggered this response. final BaseRequest request; /// The HTTP status code for this response. final int statusCode; /// The reason phrase associated with the status code. final String reasonPhrase; /// The size of the response body, in bytes. /// /// If the size of the request is not known in advance, this is `null`. final int contentLength; // TODO(nweiz): automatically parse cookies from headers // TODO(nweiz): make this a HttpHeaders object. final Map<String, String> headers; final bool isRedirect; /// Whether the server requested that a persistent connection be maintained. final bool persistentConnection; BaseResponse(this.statusCode, {this.contentLength, this.request, this.headers = const {}, this.isRedirect = false, this.persistentConnection = true, this.reasonPhrase}) { if (statusCode < 100) { throw ArgumentError('Invalid status code $statusCode.'); } else if (contentLength != null && contentLength < 0) { throw ArgumentError('Invalid content length $contentLength.'); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/base_client.dart
// Copyright (c) 2012, 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 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'base_request.dart'; import 'client.dart'; import 'exception.dart'; import 'request.dart'; import 'response.dart'; import 'streamed_response.dart'; /// The abstract base class for an HTTP client. /// /// This is a mixin-style class; subclasses only need to implement [send] and /// maybe [close], and then they get various convenience methods for free. abstract class BaseClient implements Client { @override Future<Response> head(url, {Map<String, String> headers}) => _sendUnstreamed('HEAD', url, headers); @override Future<Response> get(url, {Map<String, String> headers}) => _sendUnstreamed('GET', url, headers); @override Future<Response> post(url, {Map<String, String> headers, body, Encoding encoding}) => _sendUnstreamed('POST', url, headers, body, encoding); @override Future<Response> put(url, {Map<String, String> headers, body, Encoding encoding}) => _sendUnstreamed('PUT', url, headers, body, encoding); @override Future<Response> patch(url, {Map<String, String> headers, body, Encoding encoding}) => _sendUnstreamed('PATCH', url, headers, body, encoding); @override Future<Response> delete(url, {Map<String, String> headers}) => _sendUnstreamed('DELETE', url, headers); @override Future<String> read(url, {Map<String, String> headers}) async { final response = await get(url, headers: headers); _checkResponseSuccess(url, response); return response.body; } @override Future<Uint8List> readBytes(url, {Map<String, String> headers}) async { final response = await get(url, headers: headers); _checkResponseSuccess(url, response); return response.bodyBytes; } /// Sends an HTTP request and asynchronously returns the response. /// /// Implementers should call [BaseRequest.finalize] to get the body of the /// request as a [ByteStream]. They shouldn't make any assumptions about the /// state of the stream; it could have data written to it asynchronously at a /// later point, or it could already be closed when it's returned. Any /// internal HTTP errors should be wrapped as [ClientException]s. @override Future<StreamedResponse> send(BaseRequest request); /// Sends a non-streaming [Request] and returns a non-streaming [Response]. Future<Response> _sendUnstreamed( String method, url, Map<String, String> headers, [body, Encoding encoding]) async { var request = Request(method, _fromUriOrString(url)); if (headers != null) request.headers.addAll(headers); if (encoding != null) request.encoding = encoding; if (body != null) { if (body is String) { request.body = body; } else if (body is List) { request.bodyBytes = body.cast<int>(); } else if (body is Map) { request.bodyFields = body.cast<String, String>(); } else { throw ArgumentError('Invalid request body "$body".'); } } return Response.fromStream(await send(request)); } /// Throws an error if [response] is not successful. void _checkResponseSuccess(url, Response response) { if (response.statusCode < 400) return; var message = 'Request to $url failed with status ${response.statusCode}'; if (response.reasonPhrase != null) { message = '$message: ${response.reasonPhrase}'; } throw ClientException('$message.', _fromUriOrString(url)); } @override void close() {} } Uri _fromUriOrString(uri) => uri is String ? Uri.parse(uri) : uri as Uri;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/browser_client.dart
// Copyright (c) 2018, 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 'dart:async'; import 'dart:html'; import 'dart:typed_data'; import 'package:pedantic/pedantic.dart' show unawaited; import 'base_client.dart'; import 'base_request.dart'; import 'byte_stream.dart'; import 'exception.dart'; import 'streamed_response.dart'; /// Create a [BrowserClient]. /// /// Used from conditional imports, matches the definition in `client_stub.dart`. BaseClient createClient() => BrowserClient(); /// A `dart:html`-based HTTP client that runs in the browser and is backed by /// XMLHttpRequests. /// /// This client inherits some of the limitations of XMLHttpRequest. It ignores /// the [BaseRequest.contentLength], [BaseRequest.persistentConnection], /// [BaseRequest.followRedirects], and [BaseRequest.maxRedirects] fields. It is /// also unable to stream requests or responses; a request will only be sent and /// a response will only be returned once all the data is available. class BrowserClient extends BaseClient { /// The currently active XHRs. /// /// These are aborted if the client is closed. final _xhrs = <HttpRequest>{}; /// Whether to send credentials such as cookies or authorization headers for /// cross-site requests. /// /// Defaults to `false`. bool withCredentials = false; /// Sends an HTTP request and asynchronously returns the response. @override Future<StreamedResponse> send(BaseRequest request) async { var bytes = await request.finalize().toBytes(); var xhr = HttpRequest(); _xhrs.add(xhr); xhr ..open(request.method, '${request.url}', async: true) ..responseType = 'blob' ..withCredentials = withCredentials; request.headers.forEach(xhr.setRequestHeader); var completer = Completer<StreamedResponse>(); unawaited(xhr.onLoad.first.then((_) { // TODO(nweiz): Set the response type to "arraybuffer" when issue 18542 // is fixed. var blob = xhr.response as Blob ?? Blob([]); var reader = FileReader(); reader.onLoad.first.then((_) { var body = reader.result as Uint8List; completer.complete(StreamedResponse( ByteStream.fromBytes(body), xhr.status, contentLength: body.length, request: request, headers: xhr.responseHeaders, reasonPhrase: xhr.statusText)); }); reader.onError.first.then((error) { completer.completeError( ClientException(error.toString(), request.url), StackTrace.current); }); reader.readAsArrayBuffer(blob); })); unawaited(xhr.onError.first.then((_) { // Unfortunately, the underlying XMLHttpRequest API doesn't expose any // specific information about the error itself. completer.completeError( ClientException('XMLHttpRequest error.', request.url), StackTrace.current); })); xhr.send(bytes); try { return await completer.future; } finally { _xhrs.remove(xhr); } } /// Closes the client. /// /// This terminates all active requests. @override void close() { for (var xhr in _xhrs) { xhr.abort(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/byte_stream.dart
// Copyright (c) 2013, 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 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; /// A stream of chunks of bytes representing a single piece of data. class ByteStream extends StreamView<List<int>> { ByteStream(Stream<List<int>> stream) : super(stream); /// Returns a single-subscription byte stream that will emit the given bytes /// in a single chunk. factory ByteStream.fromBytes(List<int> bytes) => ByteStream(Stream.fromIterable([bytes])); /// Collects the data of this stream in a [Uint8List]. Future<Uint8List> toBytes() { var completer = Completer<Uint8List>(); var sink = ByteConversionSink.withCallback( (bytes) => completer.complete(Uint8List.fromList(bytes))); listen(sink.add, onError: completer.completeError, onDone: sink.close, cancelOnError: true); return completer.future; } /// Collect the data of this stream in a [String], decoded according to /// [encoding], which defaults to `UTF8`. Future<String> bytesToString([Encoding encoding = utf8]) => encoding.decodeStream(this); Stream<String> toStringStream([Encoding encoding = utf8]) => encoding.decoder.bind(this); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/boundary_characters.dart
// Copyright (c) 2013, 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. /// All character codes that are valid in multipart boundaries. /// /// This is the intersection of the characters allowed in the `bcharsnospace` /// production defined in [RFC 2046][] and those allowed in the `token` /// production defined in [RFC 1521][]. /// /// [RFC 2046]: http://tools.ietf.org/html/rfc2046#section-5.1.1. /// [RFC 1521]: https://tools.ietf.org/html/rfc1521#section-4 const List<int> BOUNDARY_CHARACTERS = <int>[ 43, 95, 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122 ];
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/multipart_file.dart
// Copyright (c) 2012, 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 'dart:async'; import 'dart:convert'; import 'package:http_parser/http_parser.dart'; import 'byte_stream.dart'; // ignore: uri_does_not_exist import 'multipart_file_stub.dart' // ignore: uri_does_not_exist if (dart.library.io) 'multipart_file_io.dart'; import 'utils.dart'; /// A file to be uploaded as part of a [MultipartRequest]. /// /// This doesn't need to correspond to a physical file. class MultipartFile { /// The name of the form field for the file. final String field; /// The size of the file in bytes. /// /// This must be known in advance, even if this file is created from a /// [ByteStream]. final int length; /// The basename of the file. /// /// May be null. final String filename; /// The content-type of the file. /// /// Defaults to `application/octet-stream`. final MediaType contentType; /// The stream that will emit the file's contents. final ByteStream _stream; /// Whether [finalize] has been called. bool get isFinalized => _isFinalized; bool _isFinalized = false; /// Creates a new [MultipartFile] from a chunked [Stream] of bytes. /// /// The length of the file in bytes must be known in advance. If it's not, /// read the data from the stream and use [MultipartFile.fromBytes] instead. /// /// [contentType] currently defaults to `application/octet-stream`, but in the /// future may be inferred from [filename]. MultipartFile(this.field, Stream<List<int>> stream, this.length, {this.filename, MediaType contentType}) : _stream = toByteStream(stream), contentType = contentType ?? MediaType('application', 'octet-stream'); /// Creates a new [MultipartFile] from a byte array. /// /// [contentType] currently defaults to `application/octet-stream`, but in the /// future may be inferred from [filename]. factory MultipartFile.fromBytes(String field, List<int> value, {String filename, MediaType contentType}) { var stream = ByteStream.fromBytes(value); return MultipartFile(field, stream, value.length, filename: filename, contentType: contentType); } /// Creates a new [MultipartFile] from a string. /// /// The encoding to use when translating [value] into bytes is taken from /// [contentType] if it has a charset set. Otherwise, it defaults to UTF-8. /// [contentType] currently defaults to `text/plain; charset=utf-8`, but in /// the future may be inferred from [filename]. factory MultipartFile.fromString(String field, String value, {String filename, MediaType contentType}) { contentType ??= MediaType('text', 'plain'); var encoding = encodingForCharset(contentType.parameters['charset'], utf8); contentType = contentType.change(parameters: {'charset': encoding.name}); return MultipartFile.fromBytes(field, encoding.encode(value), filename: filename, contentType: contentType); } // TODO(nweiz): Infer the content-type from the filename. /// Creates a new [MultipartFile] from a path to a file on disk. /// /// [filename] defaults to the basename of [filePath]. [contentType] currently /// defaults to `application/octet-stream`, but in the future may be inferred /// from [filename]. /// /// Throws an [UnsupportedError] if `dart:io` isn't supported in this /// environment. static Future<MultipartFile> fromPath(String field, String filePath, {String filename, MediaType contentType}) => multipartFileFromPath(field, filePath, filename: filename, contentType: contentType); // Finalizes the file in preparation for it being sent as part of a // [MultipartRequest]. This returns a [ByteStream] that should emit the body // of the file. The stream may be closed to indicate an empty file. ByteStream finalize() { if (isFinalized) { throw StateError("Can't finalize a finalized MultipartFile."); } _isFinalized = true; return _stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/mock_client.dart
// Copyright (c) 2012, 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 'dart:async'; import 'base_client.dart'; import 'base_request.dart'; import 'byte_stream.dart'; import 'request.dart'; import 'response.dart'; import 'streamed_response.dart'; // TODO(nweiz): once Dart has some sort of Rack- or WSGI-like standard for // server APIs, MockClient should conform to it. /// A mock HTTP client designed for use when testing code that uses /// [BaseClient]. /// /// This client allows you to define a handler callback for all requests that /// are made through it so that you can mock a server without having to send /// real HTTP requests. class MockClient extends BaseClient { /// The handler for receiving [StreamedRequest]s and sending /// [StreamedResponse]s. final MockClientStreamHandler _handler; MockClient._(this._handler); /// Creates a [MockClient] with a handler that receives [Request]s and sends /// [Response]s. MockClient(MockClientHandler fn) : this._((baseRequest, bodyStream) async { final bodyBytes = await bodyStream.toBytes(); var request = Request(baseRequest.method, baseRequest.url) ..persistentConnection = baseRequest.persistentConnection ..followRedirects = baseRequest.followRedirects ..maxRedirects = baseRequest.maxRedirects ..headers.addAll(baseRequest.headers) ..bodyBytes = bodyBytes ..finalize(); final response = await fn(request); return StreamedResponse( ByteStream.fromBytes(response.bodyBytes), response.statusCode, contentLength: response.contentLength, request: baseRequest, headers: response.headers, isRedirect: response.isRedirect, persistentConnection: response.persistentConnection, reasonPhrase: response.reasonPhrase); }); /// Creates a [MockClient] with a handler that receives [StreamedRequest]s and /// sends [StreamedResponse]s. MockClient.streaming(MockClientStreamHandler fn) : this._((request, bodyStream) async { final response = await fn(request, bodyStream); return StreamedResponse(response.stream, response.statusCode, contentLength: response.contentLength, request: request, headers: response.headers, isRedirect: response.isRedirect, persistentConnection: response.persistentConnection, reasonPhrase: response.reasonPhrase); }); @override Future<StreamedResponse> send(BaseRequest request) async { var bodyStream = request.finalize(); return await _handler(request, bodyStream); } } /// A handler function that receives [StreamedRequest]s and sends /// [StreamedResponse]s. /// /// Note that [request] will be finalized. typedef MockClientStreamHandler = Future<StreamedResponse> Function( BaseRequest request, ByteStream bodyStream); /// A handler function that receives [Request]s and sends [Response]s. /// /// Note that [request] will be finalized. typedef MockClientHandler = Future<Response> Function(Request request);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/client.dart
// Copyright (c) 2012, 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 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'base_client.dart'; import 'base_request.dart'; // ignore: uri_does_not_exist import 'client_stub.dart' // ignore: uri_does_not_exist if (dart.library.html) 'browser_client.dart' // ignore: uri_does_not_exist if (dart.library.io) 'io_client.dart'; import 'response.dart'; import 'streamed_response.dart'; /// The interface for HTTP clients that take care of maintaining persistent /// connections across multiple requests to the same server. /// /// If you only need to send a single request, it's usually easier to use /// [head], [get], [post], [put], [patch], or [delete] instead. /// /// When creating an HTTP client class with additional functionality, you must /// extend [BaseClient] rather than [Client]. In most cases, you can wrap /// another instance of [Client] and add functionality on top of that. This /// allows all classes implementing [Client] to be mutually composable. abstract class Client { /// Creates a new platform appropriate client. /// /// Creates an `IOClient` if `dart:io` is available and a `BrowserClient` if /// `dart:html` is available, otherwise it will throw an unsupported error. factory Client() => createClient(); /// Sends an HTTP HEAD request with the given headers to the given URL, which /// can be a [Uri] or a [String]. /// /// For more fine-grained control over the request, use [send] instead. Future<Response> head(url, {Map<String, String> headers}); /// Sends an HTTP GET request with the given headers to the given URL, which /// can be a [Uri] or a [String]. /// /// For more fine-grained control over the request, use [send] instead. Future<Response> get(url, {Map<String, String> headers}); /// Sends an HTTP POST request with the given headers and body to the given /// URL, which can be a [Uri] or a [String]. /// /// [body] sets the body of the request. It can be a [String], a [List<int>] /// or a [Map<String, String>]. If it's a String, it's encoded using /// [encoding] and used as the body of the request. The content-type of the /// request will default to "text/plain". /// /// If [body] is a List, it's used as a list of bytes for the body of the /// request. /// /// If [body] is a Map, it's encoded as form fields using [encoding]. The /// content-type of the request will be set to /// `"application/x-www-form-urlencoded"`; this cannot be overridden. /// /// [encoding] defaults to [utf8]. /// /// For more fine-grained control over the request, use [send] instead. Future<Response> post(url, {Map<String, String> headers, body, Encoding encoding}); /// Sends an HTTP PUT request with the given headers and body to the given /// URL, which can be a [Uri] or a [String]. /// /// [body] sets the body of the request. It can be a [String], a [List<int>] /// or a [Map<String, String>]. If it's a String, it's encoded using /// [encoding] and used as the body of the request. The content-type of the /// request will default to "text/plain". /// /// If [body] is a List, it's used as a list of bytes for the body of the /// request. /// /// If [body] is a Map, it's encoded as form fields using [encoding]. The /// content-type of the request will be set to /// `"application/x-www-form-urlencoded"`; this cannot be overridden. /// /// [encoding] defaults to [utf8]. /// /// For more fine-grained control over the request, use [send] instead. Future<Response> put(url, {Map<String, String> headers, body, Encoding encoding}); /// Sends an HTTP PATCH request with the given headers and body to the given /// URL, which can be a [Uri] or a [String]. /// /// [body] sets the body of the request. It can be a [String], a [List<int>] /// or a [Map<String, String>]. If it's a String, it's encoded using /// [encoding] and used as the body of the request. The content-type of the /// request will default to "text/plain". /// /// If [body] is a List, it's used as a list of bytes for the body of the /// request. /// /// If [body] is a Map, it's encoded as form fields using [encoding]. The /// content-type of the request will be set to /// `"application/x-www-form-urlencoded"`; this cannot be overridden. /// /// [encoding] defaults to [utf8]. /// /// For more fine-grained control over the request, use [send] instead. Future<Response> patch(url, {Map<String, String> headers, body, Encoding encoding}); /// Sends an HTTP DELETE request with the given headers to the given URL, /// which can be a [Uri] or a [String]. /// /// For more fine-grained control over the request, use [send] instead. Future<Response> delete(url, {Map<String, String> headers}); /// Sends an HTTP GET request with the given headers to the given URL, which /// can be a [Uri] or a [String], and returns a Future that completes to the /// body of the response as a String. /// /// The Future will emit a [ClientException] if the response doesn't have a /// success status code. /// /// For more fine-grained control over the request and response, use [send] or /// [get] instead. Future<String> read(url, {Map<String, String> headers}); /// Sends an HTTP GET request with the given headers to the given URL, which /// can be a [Uri] or a [String], and returns a Future that completes to the /// body of the response as a list of bytes. /// /// The Future will emit a [ClientException] if the response doesn't have a /// success status code. /// /// For more fine-grained control over the request and response, use [send] or /// [get] instead. Future<Uint8List> readBytes(url, {Map<String, String> headers}); /// Sends an HTTP request and asynchronously returns the response. Future<StreamedResponse> send(BaseRequest request); /// Closes the client and cleans up any resources associated with it. /// /// It's important to close each client when it's done being used; failing to /// do so can cause the Dart process to hang. void close(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/io_streamed_response.dart
// Copyright (c) 2020, 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 'dart:io'; import 'base_request.dart'; import 'streamed_response.dart'; /// An HTTP response where the response body is received asynchronously after /// the headers have been received. class IOStreamedResponse extends StreamedResponse { final HttpClientResponse _inner; /// Creates a new streaming response. /// /// [stream] should be a single-subscription stream. IOStreamedResponse(Stream<List<int>> stream, int statusCode, {int contentLength, BaseRequest request, Map<String, String> headers = const {}, bool isRedirect = false, bool persistentConnection = true, String reasonPhrase, HttpClientResponse inner}) : _inner = inner, super(stream, statusCode, contentLength: contentLength, request: request, headers: headers, isRedirect: isRedirect, persistentConnection: persistentConnection, reasonPhrase: reasonPhrase); /// Detaches the underlying socket from the HTTP server. Future<Socket> detachSocket() async => _inner.detachSocket(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/exception.dart
// Copyright (c) 2014, 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. /// An exception caused by an error in a pkg/http client. class ClientException implements Exception { final String message; /// The URL of the HTTP request or response that failed. final Uri uri; ClientException(this.message, [this.uri]); @override String toString() => message; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/streamed_request.dart
// Copyright (c) 2012, 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 'dart:async'; import 'base_request.dart'; import 'byte_stream.dart'; /// An HTTP request where the request body is sent asynchronously after the /// connection has been established and the headers have been sent. /// /// When the request is sent via [BaseClient.send], only the headers and /// whatever data has already been written to [StreamedRequest.stream] will be /// sent immediately. More data will be sent as soon as it's written to /// [StreamedRequest.sink], and when the sink is closed the request will end. class StreamedRequest extends BaseRequest { /// The sink to which to write data that will be sent as the request body. /// /// This may be safely written to before the request is sent; the data will be /// buffered. /// /// Closing this signals the end of the request. EventSink<List<int>> get sink => _controller.sink; /// The controller for [sink], from which [BaseRequest] will read data for /// [finalize]. final StreamController<List<int>> _controller; /// Creates a new streaming request. StreamedRequest(String method, Uri url) : _controller = StreamController<List<int>>(sync: true), super(method, url); /// Freezes all mutable fields other than [stream] and returns a /// single-subscription [ByteStream] that emits the data being written to /// [sink]. @override ByteStream finalize() { super.finalize(); return ByteStream(_controller.stream); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/multipart_file_stub.dart
// Copyright (c) 2018, 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 'dart:async'; import 'package:http_parser/http_parser.dart'; import 'multipart_file.dart'; Future<MultipartFile> multipartFileFromPath(String field, String filePath, {String filename, MediaType contentType}) => throw UnsupportedError( 'MultipartFile is only supported where dart:io is available.');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/request.dart
// Copyright (c) 2013, 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 'dart:convert'; import 'dart:typed_data'; import 'package:http_parser/http_parser.dart'; import 'base_request.dart'; import 'byte_stream.dart'; import 'utils.dart'; /// An HTTP request where the entire request body is known in advance. class Request extends BaseRequest { /// The size of the request body, in bytes. This is calculated from /// [bodyBytes]. /// /// The content length cannot be set for [Request], since it's automatically /// calculated from [bodyBytes]. @override int get contentLength => bodyBytes.length; @override set contentLength(int value) { throw UnsupportedError('Cannot set the contentLength property of ' 'non-streaming Request objects.'); } /// The default encoding to use when converting between [bodyBytes] and /// [body]. /// /// This is only used if [encoding] hasn't been manually set and if the /// content-type header has no encoding information. Encoding _defaultEncoding; /// The encoding used for the request. /// /// This encoding is used when converting between [bodyBytes] and [body]. /// /// If the request has a `Content-Type` header and that header has a `charset` /// parameter, that parameter's value is used as the encoding. Otherwise, if /// [encoding] has been set manually, that encoding is used. If that hasn't /// been set either, this defaults to [utf8]. /// /// If the `charset` parameter's value is not a known [Encoding], reading this /// will throw a [FormatException]. /// /// If the request has a `Content-Type` header, setting this will set the /// charset parameter on that header. Encoding get encoding { if (_contentType == null || !_contentType.parameters.containsKey('charset')) { return _defaultEncoding; } return requiredEncodingForCharset(_contentType.parameters['charset']); } set encoding(Encoding value) { _checkFinalized(); _defaultEncoding = value; var contentType = _contentType; if (contentType == null) return; _contentType = contentType.change(parameters: {'charset': value.name}); } // TODO(nweiz): make this return a read-only view /// The bytes comprising the body of the request. /// /// This is converted to and from [body] using [encoding]. /// /// This list should only be set, not be modified in place. Uint8List get bodyBytes => _bodyBytes; Uint8List _bodyBytes; set bodyBytes(List<int> value) { _checkFinalized(); _bodyBytes = toUint8List(value); } /// The body of the request as a string. /// /// This is converted to and from [bodyBytes] using [encoding]. /// /// When this is set, if the request does not yet have a `Content-Type` /// header, one will be added with the type `text/plain`. Then the `charset` /// parameter of the `Content-Type` header (whether new or pre-existing) will /// be set to [encoding] if it wasn't already set. String get body => encoding.decode(bodyBytes); set body(String value) { bodyBytes = encoding.encode(value); var contentType = _contentType; if (contentType == null) { _contentType = MediaType('text', 'plain', {'charset': encoding.name}); } else if (!contentType.parameters.containsKey('charset')) { _contentType = contentType.change(parameters: {'charset': encoding.name}); } } /// The form-encoded fields in the body of the request as a map from field /// names to values. /// /// The form-encoded body is converted to and from [bodyBytes] using /// [encoding] (in the same way as [body]). /// /// If the request doesn't have a `Content-Type` header of /// `application/x-www-form-urlencoded`, reading this will throw a /// [StateError]. /// /// If the request has a `Content-Type` header with a type other than /// `application/x-www-form-urlencoded`, setting this will throw a /// [StateError]. Otherwise, the content type will be set to /// `application/x-www-form-urlencoded`. /// /// This map should only be set, not modified in place. Map<String, String> get bodyFields { var contentType = _contentType; if (contentType == null || contentType.mimeType != 'application/x-www-form-urlencoded') { throw StateError('Cannot access the body fields of a Request without ' 'content-type "application/x-www-form-urlencoded".'); } return Uri.splitQueryString(body, encoding: encoding); } set bodyFields(Map<String, String> fields) { var contentType = _contentType; if (contentType == null) { _contentType = MediaType('application', 'x-www-form-urlencoded'); } else if (contentType.mimeType != 'application/x-www-form-urlencoded') { throw StateError('Cannot set the body fields of a Request with ' 'content-type "${contentType.mimeType}".'); } body = mapToQuery(fields, encoding: encoding); } Request(String method, Uri url) : _defaultEncoding = utf8, _bodyBytes = Uint8List(0), super(method, url); /// Freezes all mutable fields and returns a single-subscription [ByteStream] /// containing the request body. @override ByteStream finalize() { super.finalize(); return ByteStream.fromBytes(bodyBytes); } /// The `Content-Type` header of the request (if it exists) as a [MediaType]. MediaType get _contentType { var contentType = headers['content-type']; if (contentType == null) return null; return MediaType.parse(contentType); } set _contentType(MediaType value) { headers['content-type'] = value.toString(); } /// Throw an error if this request has been finalized. void _checkFinalized() { if (!finalized) return; throw StateError("Can't modify a finalized Request."); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/response.dart
// Copyright (c) 2012, 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 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'package:http_parser/http_parser.dart'; import 'base_request.dart'; import 'base_response.dart'; import 'streamed_response.dart'; import 'utils.dart'; /// An HTTP response where the entire response body is known in advance. class Response extends BaseResponse { /// The bytes comprising the body of this response. final Uint8List bodyBytes; /// The body of the response as a string. /// /// This is converted from [bodyBytes] using the `charset` parameter of the /// `Content-Type` header field, if available. If it's unavailable or if the /// encoding name is unknown, [latin1] is used by default, as per /// [RFC 2616][]. /// /// [RFC 2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html String get body => _encodingForHeaders(headers).decode(bodyBytes); /// Creates a new HTTP response with a string body. Response(String body, int statusCode, {BaseRequest request, Map<String, String> headers = const {}, bool isRedirect = false, bool persistentConnection = true, String reasonPhrase}) : this.bytes(_encodingForHeaders(headers).encode(body), statusCode, request: request, headers: headers, isRedirect: isRedirect, persistentConnection: persistentConnection, reasonPhrase: reasonPhrase); /// Create a new HTTP response with a byte array body. Response.bytes(List<int> bodyBytes, int statusCode, {BaseRequest request, Map<String, String> headers = const {}, bool isRedirect = false, bool persistentConnection = true, String reasonPhrase}) : bodyBytes = toUint8List(bodyBytes), super(statusCode, contentLength: bodyBytes.length, request: request, headers: headers, isRedirect: isRedirect, persistentConnection: persistentConnection, reasonPhrase: reasonPhrase); /// Creates a new HTTP response by waiting for the full body to become /// available from a [StreamedResponse]. static Future<Response> fromStream(StreamedResponse response) async { final body = await response.stream.toBytes(); return Response.bytes(body, response.statusCode, request: response.request, headers: response.headers, isRedirect: response.isRedirect, persistentConnection: response.persistentConnection, reasonPhrase: response.reasonPhrase); } } /// Returns the encoding to use for a response with the given headers. /// /// Defaults to [latin1] if the headers don't specify a charset or if that /// charset is unknown. Encoding _encodingForHeaders(Map<String, String> headers) => encodingForCharset(_contentTypeForHeaders(headers).parameters['charset']); /// Returns the [MediaType] object for the given headers's content-type. /// /// Defaults to `application/octet-stream`. MediaType _contentTypeForHeaders(Map<String, String> headers) { var contentType = headers['content-type']; if (contentType != null) return MediaType.parse(contentType); return MediaType('application', 'octet-stream'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/base_request.dart
// Copyright (c) 2012, 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 'dart:async'; import 'dart:collection'; import 'byte_stream.dart'; import 'client.dart'; import 'streamed_response.dart'; import 'utils.dart'; /// The base class for HTTP requests. /// /// Subclasses of [BaseRequest] can be constructed manually and passed to /// [BaseClient.send], which allows the user to provide fine-grained control /// over the request properties. However, usually it's easier to use convenience /// methods like [get] or [BaseClient.get]. abstract class BaseRequest { /// The HTTP method of the request. /// /// Most commonly "GET" or "POST", less commonly "HEAD", "PUT", or "DELETE". /// Non-standard method names are also supported. final String method; /// The URL to which the request will be sent. final Uri url; /// The size of the request body, in bytes. /// /// This defaults to `null`, which indicates that the size of the request is /// not known in advance. May not be assigned a negative value. int get contentLength => _contentLength; int _contentLength; set contentLength(int value) { if (value != null && value < 0) { throw ArgumentError('Invalid content length $value.'); } _checkFinalized(); _contentLength = value; } /// Whether a persistent connection should be maintained with the server. /// /// Defaults to true. bool get persistentConnection => _persistentConnection; bool _persistentConnection = true; set persistentConnection(bool value) { _checkFinalized(); _persistentConnection = value; } /// Whether the client should follow redirects while resolving this request. /// /// Defaults to true. bool get followRedirects => _followRedirects; bool _followRedirects = true; set followRedirects(bool value) { _checkFinalized(); _followRedirects = value; } /// The maximum number of redirects to follow when [followRedirects] is true. /// /// If this number is exceeded the [BaseResponse] future will signal a /// [RedirectException]. Defaults to 5. int get maxRedirects => _maxRedirects; int _maxRedirects = 5; set maxRedirects(int value) { _checkFinalized(); _maxRedirects = value; } // TODO(nweiz): automatically parse cookies from headers // TODO(nweiz): make this a HttpHeaders object final Map<String, String> headers; /// Whether [finalize] has been called. bool get finalized => _finalized; bool _finalized = false; BaseRequest(this.method, this.url) : headers = LinkedHashMap( equals: (key1, key2) => key1.toLowerCase() == key2.toLowerCase(), hashCode: (key) => key.toLowerCase().hashCode); /// Finalizes the HTTP request in preparation for it being sent. /// /// Freezes all mutable fields and returns a single-subscription [ByteStream] /// that emits the body of the request. /// /// The base implementation of this returns null rather than a [ByteStream]; /// subclasses are responsible for creating the return value, which should be /// single-subscription to ensure that no data is dropped. They should also /// freeze any additional mutable fields they add that don't make sense to /// change after the request headers are sent. ByteStream finalize() { // TODO(nweiz): freeze headers if (finalized) throw StateError("Can't finalize a finalized Request."); _finalized = true; return null; } /// Sends this request. /// /// This automatically initializes a new [Client] and closes that client once /// the request is complete. If you're planning on making multiple requests to /// the same server, you should use a single [Client] for all of those /// requests. Future<StreamedResponse> send() async { var client = Client(); try { var response = await client.send(this); var stream = onDone(response.stream, client.close); return StreamedResponse(ByteStream(stream), response.statusCode, contentLength: response.contentLength, request: response.request, headers: response.headers, isRedirect: response.isRedirect, persistentConnection: response.persistentConnection, reasonPhrase: response.reasonPhrase); } catch (_) { client.close(); rethrow; } } /// Throws an error if this request has been finalized. void _checkFinalized() { if (!finalized) return; throw StateError("Can't modify a finalized Request."); } @override String toString() => '$method $url'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/client_stub.dart
// Copyright (c) 2018, 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 'base_client.dart'; /// Implemented in `browser_client.dart` and `io_client.dart`. BaseClient createClient() => throw UnsupportedError( 'Cannot create a client without dart:html or dart:io.');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/io_client.dart
// Copyright (c) 2012, 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 'dart:async'; import 'dart:io'; import 'base_client.dart'; import 'base_request.dart'; import 'exception.dart'; import 'io_streamed_response.dart'; /// Create an [IOClient]. /// /// Used from conditional imports, matches the definition in `client_stub.dart`. BaseClient createClient() => IOClient(); /// A `dart:io`-based HTTP client. class IOClient extends BaseClient { /// The underlying `dart:io` HTTP client. HttpClient _inner; IOClient([HttpClient inner]) : _inner = inner ?? HttpClient(); /// Sends an HTTP request and asynchronously returns the response. @override Future<IOStreamedResponse> send(BaseRequest request) async { var stream = request.finalize(); try { var ioRequest = (await _inner.openUrl(request.method, request.url)) ..followRedirects = request.followRedirects ..maxRedirects = request.maxRedirects ..contentLength = (request?.contentLength ?? -1) ..persistentConnection = request.persistentConnection; request.headers.forEach((name, value) { ioRequest.headers.set(name, value); }); var response = await stream.pipe(ioRequest) as HttpClientResponse; var headers = <String, String>{}; response.headers.forEach((key, values) { headers[key] = values.join(','); }); return IOStreamedResponse( response.handleError((error) { final httpException = error as HttpException; throw ClientException(httpException.message, httpException.uri); }, test: (error) => error is HttpException), response.statusCode, contentLength: response.contentLength == -1 ? null : response.contentLength, request: request, headers: headers, isRedirect: response.isRedirect, persistentConnection: response.persistentConnection, reasonPhrase: response.reasonPhrase, inner: response); } on HttpException catch (error) { throw ClientException(error.message, error.uri); } } /// Closes the client. /// /// Terminates all active connections. If a client remains unclosed, the Dart /// process may not terminate. @override void close() { if (_inner != null) { _inner.close(force: true); _inner = null; } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/utils.dart
// Copyright (c) 2012, 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 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'byte_stream.dart'; /// Converts a [Map] from parameter names to values to a URL query string. /// /// mapToQuery({"foo": "bar", "baz": "bang"}); /// //=> "foo=bar&baz=bang" String mapToQuery(Map<String, String> map, {Encoding encoding}) { var pairs = <List<String>>[]; map.forEach((key, value) => pairs.add([ Uri.encodeQueryComponent(key, encoding: encoding), Uri.encodeQueryComponent(value, encoding: encoding) ])); return pairs.map((pair) => '${pair[0]}=${pair[1]}').join('&'); } /// Returns the [Encoding] that corresponds to [charset]. /// /// Returns [fallback] if [charset] is null or if no [Encoding] was found that /// corresponds to [charset]. Encoding encodingForCharset(String charset, [Encoding fallback = latin1]) { if (charset == null) return fallback; return Encoding.getByName(charset) ?? fallback; } /// Returns the [Encoding] that corresponds to [charset]. /// /// Throws a [FormatException] if no [Encoding] was found that corresponds to /// [charset]. /// /// [charset] may not be null. Encoding requiredEncodingForCharset(String charset) => Encoding.getByName(charset) ?? (throw FormatException('Unsupported encoding "$charset".')); /// A regular expression that matches strings that are composed entirely of /// ASCII-compatible characters. final _asciiOnly = RegExp(r'^[\x00-\x7F]+$'); /// Returns whether [string] is composed entirely of ASCII-compatible /// characters. bool isPlainAscii(String string) => _asciiOnly.hasMatch(string); /// Converts [input] into a [Uint8List]. /// /// If [input] is a [TypedData], this just returns a view on [input]. Uint8List toUint8List(List<int> input) { if (input is Uint8List) return input; if (input is TypedData) { // TODO(nweiz): remove "as" when issue 11080 is fixed. return Uint8List.view((input as TypedData).buffer); } return Uint8List.fromList(input); } ByteStream toByteStream(Stream<List<int>> stream) { if (stream is ByteStream) return stream; return ByteStream(stream); } /// Calls [onDone] once [stream] (a single-subscription [Stream]) is finished. /// /// The return value, also a single-subscription [Stream] should be used in /// place of [stream] after calling this method. Stream<T> onDone<T>(Stream<T> stream, void Function() onDone) => stream.transform(StreamTransformer.fromHandlers(handleDone: (sink) { sink.close(); onDone(); }));
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/streamed_response.dart
// Copyright (c) 2012, 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 'dart:async'; import 'base_request.dart'; import 'base_response.dart'; import 'byte_stream.dart'; import 'utils.dart'; /// An HTTP response where the response body is received asynchronously after /// the headers have been received. class StreamedResponse extends BaseResponse { /// The stream from which the response body data can be read. /// /// This should always be a single-subscription stream. final ByteStream stream; /// Creates a new streaming response. /// /// [stream] should be a single-subscription stream. StreamedResponse(Stream<List<int>> stream, int statusCode, {int contentLength, BaseRequest request, Map<String, String> headers = const {}, bool isRedirect = false, bool persistentConnection = true, String reasonPhrase}) : stream = toByteStream(stream), super(statusCode, contentLength: contentLength, request: request, headers: headers, isRedirect: isRedirect, persistentConnection: persistentConnection, reasonPhrase: reasonPhrase); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http/src/multipart_request.dart
// Copyright (c) 2013, 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 'dart:async'; import 'dart:convert'; import 'dart:math'; import 'base_request.dart'; import 'boundary_characters.dart'; import 'byte_stream.dart'; import 'multipart_file.dart'; import 'utils.dart'; final _newlineRegExp = RegExp(r'\r\n|\r|\n'); /// A `multipart/form-data` request. /// /// Such a request has both string [fields], which function as normal form /// fields, and (potentially streamed) binary [files]. /// /// This request automatically sets the Content-Type header to /// `multipart/form-data`. This value will override any value set by the user. /// /// var uri = Uri.parse('https://example.com/create'); /// var request = http.MultipartRequest('POST', uri) /// ..fields['user'] = '[email protected]' /// ..files.add(await http.MultipartFile.fromPath( /// 'package', 'build/package.tar.gz', /// contentType: MediaType('application', 'x-tar'))); /// var response = await request.send(); /// if (response.statusCode == 200) print('Uploaded!'); class MultipartRequest extends BaseRequest { /// The total length of the multipart boundaries used when building the /// request body. /// /// According to http://tools.ietf.org/html/rfc1341.html, this can't be longer /// than 70. static const int _boundaryLength = 70; static final Random _random = Random(); /// The form fields to send for this request. final fields = <String, String>{}; /// The list of files to upload for this request. final files = <MultipartFile>[]; MultipartRequest(String method, Uri url) : super(method, url); /// The total length of the request body, in bytes. /// /// This is calculated from [fields] and [files] and cannot be set manually. @override int get contentLength { var length = 0; fields.forEach((name, value) { length += '--'.length + _boundaryLength + '\r\n'.length + utf8.encode(_headerForField(name, value)).length + utf8.encode(value).length + '\r\n'.length; }); for (var file in files) { length += '--'.length + _boundaryLength + '\r\n'.length + utf8.encode(_headerForFile(file)).length + file.length + '\r\n'.length; } return length + '--'.length + _boundaryLength + '--\r\n'.length; } @override set contentLength(int value) { throw UnsupportedError('Cannot set the contentLength property of ' 'multipart requests.'); } /// Freezes all mutable fields and returns a single-subscription [ByteStream] /// that will emit the request body. @override ByteStream finalize() { // TODO: freeze fields and files final boundary = _boundaryString(); headers['content-type'] = 'multipart/form-data; boundary=$boundary'; super.finalize(); return ByteStream(_finalize(boundary)); } Stream<List<int>> _finalize(String boundary) async* { const line = [13, 10]; // \r\n final separator = utf8.encode('--$boundary\r\n'); final close = utf8.encode('--$boundary--\r\n'); for (var field in fields.entries) { yield separator; yield utf8.encode(_headerForField(field.key, field.value)); yield utf8.encode(field.value); yield line; } for (final file in files) { yield separator; yield utf8.encode(_headerForFile(file)); yield* file.finalize(); yield line; } yield close; } /// Returns the header string for a field. /// /// The return value is guaranteed to contain only ASCII characters. String _headerForField(String name, String value) { var header = 'content-disposition: form-data; name="${_browserEncode(name)}"'; if (!isPlainAscii(value)) { header = '$header\r\n' 'content-type: text/plain; charset=utf-8\r\n' 'content-transfer-encoding: binary'; } return '$header\r\n\r\n'; } /// Returns the header string for a file. /// /// The return value is guaranteed to contain only ASCII characters. String _headerForFile(MultipartFile file) { var header = 'content-type: ${file.contentType}\r\n' 'content-disposition: form-data; name="${_browserEncode(file.field)}"'; if (file.filename != null) { header = '$header; filename="${_browserEncode(file.filename)}"'; } return '$header\r\n\r\n'; } /// Encode [value] in the same way browsers do. String _browserEncode(String value) { // http://tools.ietf.org/html/rfc2388 mandates some complex encodings for // field names and file names, but in practice user agents seem not to // follow this at all. Instead, they URL-encode `\r`, `\n`, and `\r\n` as // `\r\n`; URL-encode `"`; and do nothing else (even for `%` or non-ASCII // characters). We follow their behavior. return value.replaceAll(_newlineRegExp, '%0D%0A').replaceAll('"', '%22'); } /// Returns a randomly-generated multipart boundary string String _boundaryString() { var prefix = 'dart-http-boundary-'; var list = List<int>.generate( _boundaryLength - prefix.length, (index) => BOUNDARY_CHARACTERS[_random.nextInt(BOUNDARY_CHARACTERS.length)], growable: false); return '$prefix${String.fromCharCodes(list)}'; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_functions_interop/firebase_functions_interop.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. /// Interop library for Firebase Functions Node.js SDK. /// /// Use [functions] object as main entry point. /// /// To create your cloud function see corresponding namespaces on /// [FirebaseFunctions] class: /// /// - [FirebaseFunctions.https] for creating HTTPS triggers /// - [FirebaseFunctions.database] for creating Realtime Database triggers /// - [FirebaseFunctions.firestore] for creating Firestore triggers /// /// Here is an example of creating and exporting an HTTPS trigger: /// /// import 'package:firebase_functions_interop/firebase_functions_interop.dart'; /// /// void main() { /// // Registers helloWorld function under path prefix `/helloWorld` /// functions['helloWorld'] = functions.https /// .onRequest(helloWorld); /// } /// /// // Simple function which returns a response with a body containing /// // "Hello world". /// void helloWorld(ExpressHttpRequest request) { /// request.response.writeln("Hello world"); /// request.response.close(); /// } library firebase_functions_interop; import 'dart:async'; import 'dart:js'; import 'package:firebase_admin_interop/firebase_admin_interop.dart'; import 'package:meta/meta.dart'; import 'package:node_interop/http.dart'; import 'package:node_interop/node.dart'; import 'package:node_interop/util.dart'; import 'src/bindings.dart' as js; import 'src/express.dart'; export 'package:firebase_admin_interop/firebase_admin_interop.dart'; export 'package:node_io/node_io.dart' show HttpRequest, HttpResponse; export 'src/bindings.dart' show CloudFunction, HttpsFunction, EventAuthInfo, RuntimeOptions; export 'src/express.dart'; part 'src/https.dart'; final js.FirebaseFunctions _module = require('firebase-functions'); /// Main library object which can be used to create and register Firebase /// Cloud functions. final FirebaseFunctions functions = FirebaseFunctions._(_module); typedef DataEventHandler<T> = FutureOr<void> Function( T data, EventContext context); typedef ChangeEventHandler<T> = FutureOr<void> Function( Change<T> data, EventContext context); /// Global namespace for Firebase Cloud Functions functionality. /// /// Use [functions] as a singleton instance of this class to export function /// triggers. class FirebaseFunctions { final js.FirebaseFunctions _functions; /// Configuration object for Firebase functions. final Config config; /// HTTPS functions. final HttpsFunctions https; /// Realtime Database functions. final DatabaseFunctions database; /// Firestore functions. final FirestoreFunctions firestore; /// Pubsub functions. final PubsubFunctions pubsub; /// Storage functions. final StorageFunctions storage; /// Authentication functions. final AuthFunctions auth; FirebaseFunctions._(js.FirebaseFunctions functions) : _functions = functions, config = Config._(functions), https = HttpsFunctions._(functions), database = DatabaseFunctions._(functions), firestore = FirestoreFunctions._(functions), pubsub = PubsubFunctions._(functions), storage = StorageFunctions._(functions), auth = AuthFunctions._(functions); /// Configures the regions to which to deploy and run a function. /// /// For a list of valid values see https://firebase.google.com/docs/functions/locations FirebaseFunctions region(String region) { return FirebaseFunctions._(_functions.region(region)); } /// Configures memory allocation and timeout for a function. FirebaseFunctions runWith(js.RuntimeOptions options) { return FirebaseFunctions._(_functions.runWith(options)); } /// Export [function] under specified [key]. /// /// For HTTPS functions the [key] defines URL path prefix. operator []=(String key, dynamic function) { assert(function is js.HttpsFunction || function is js.CloudFunction); setExport(key, function); } } /// Provides access to environment configuration of Firebase Functions. /// /// See also: /// - [https://firebase.google.com/docs/functions/config-env](https://firebase.google.com/docs/functions/config-env) class Config { final js.FirebaseFunctions _functions; Config._(this._functions); /// Returns configuration value specified by it's [key]. /// /// This method expects keys to be fully qualified (namespaced), e.g. /// `some_service.client_secret` or `some_service.url`. /// This is different from native JS implementation where namespaced /// keys are broken into nested JS object structure, e.g. /// `functions.config().some_service.client_secret`. dynamic get(String key) { final List<String> parts = key.split('.'); var data = dartify(_functions.config()); var value; for (var subKey in parts) { if (data is! Map) return null; value = data[subKey]; if (value == null) break; data = value; } return value; } } /// Container for events that change state, such as Realtime Database or /// Cloud Firestore `onWrite` and `onUpdate`. class Change<T> { Change(this.after, this.before); /// The state after the event. final T after; /// The state prior to the event. final T before; } /// The context in which an event occurred. /// /// An EventContext describes: /// /// * The time an event occurred. /// * A unique identifier of the event. /// * The resource on which the event occurred, if applicable. /// * Authorization of the request that triggered the event, if applicable /// and available. class EventContext { EventContext._(this.auth, this.authType, this.eventId, this.eventType, this.params, this.resource, this.timestamp); factory EventContext(js.EventContext data) { return new EventContext._( data.auth, data.authType, data.eventId, data.eventType, new Map<String, String>.from(dartify(data.params)), data.resource, DateTime.parse(data.timestamp), ); } /// Authentication information for the user that triggered the function. /// /// For an unauthenticated user, this field is null. For event types that do /// not provide user information (all except Realtime Database) or for /// Firebase admin users, this field will not exist. final js.EventAuthInfo auth; /// The level of permissions for a user. /// /// Valid values are: `ADMIN`, `USER`, `UNAUTHENTICATED` and `null`. final String authType; /// The event’s unique identifier. final String eventId; /// Type of event. final String eventType; /// An object containing the values of the wildcards in the path parameter /// provided to the ref() method for a Realtime Database trigger. final Map<String, String> params; /// The resource that emitted the event. final js.EventContextResource resource; /// Timestamp for the event. final DateTime timestamp; } /// Realtime Database functions namespace. class DatabaseFunctions { final js.FirebaseFunctions _functions; DatabaseFunctions._(this._functions); /// Returns reference builder for specified [path] in Realtime Database. RefBuilder ref(String path) => new RefBuilder._(_functions.database.ref(path)); } /// The Firebase Realtime Database reference builder. class RefBuilder { final js.RefBuilder nativeInstance; RefBuilder._(this.nativeInstance); /// Event handler that fires every time new data is created in Firebase /// Realtime Database. js.CloudFunction onCreate<T>(DataEventHandler<DataSnapshot<T>> handler) { dynamic wrapper(js.DataSnapshot data, js.EventContext context) => _handleDataEvent<T>(data, context, handler); return nativeInstance.onCreate(allowInterop(wrapper)); } /// Event handler that fires every time data is deleted from Firebase /// Realtime Database. js.CloudFunction onDelete<T>(DataEventHandler<DataSnapshot<T>> handler) { dynamic wrapper(js.DataSnapshot data, js.EventContext context) => _handleDataEvent<T>(data, context, handler); return nativeInstance.onDelete(allowInterop(wrapper)); } /// Event handler that fires every time data is updated in Firebase Realtime /// Database. js.CloudFunction onUpdate<T>(ChangeEventHandler<DataSnapshot<T>> handler) { dynamic wrapper(js.Change<js.DataSnapshot> data, js.EventContext context) => _handleChangeEvent<T>(data, context, handler); return nativeInstance.onUpdate(allowInterop(wrapper)); } /// Event handler that fires every time a Firebase Realtime Database write of /// any kind (creation, update, or delete) occurs. js.CloudFunction onWrite<T>(ChangeEventHandler<DataSnapshot<T>> handler) { dynamic wrapper(js.Change<js.DataSnapshot> data, js.EventContext context) => _handleChangeEvent<T>(data, context, handler); return nativeInstance.onWrite(allowInterop(wrapper)); } dynamic _handleDataEvent<T>(js.DataSnapshot data, js.EventContext jsContext, FutureOr<void> handler(DataSnapshot<T> data, EventContext context)) { var snapshot = new DataSnapshot<T>(data); var context = new EventContext(jsContext); var result = handler(snapshot, context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } dynamic _handleChangeEvent<T>(js.Change<js.DataSnapshot> data, js.EventContext jsContext, ChangeEventHandler<DataSnapshot<T>> handler) { var after = new DataSnapshot<T>(data.after); var before = new DataSnapshot<T>(data.before); var context = new EventContext(jsContext); var result = handler(new Change<DataSnapshot<T>>(after, before), context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } } class FirestoreFunctions { final js.FirebaseFunctions _functions; FirestoreFunctions._(this._functions); DocumentBuilder document(String path) => new DocumentBuilder._(_functions.firestore.document(path)); } class DocumentBuilder { @protected final js.DocumentBuilder nativeInstance; DocumentBuilder._(this.nativeInstance); /// Event handler that fires every time new data is created in Cloud Firestore. js.CloudFunction onCreate(DataEventHandler<DocumentSnapshot> handler) { dynamic wrapper(js.DocumentSnapshot data, js.EventContext context) => _handleEvent(data, context, handler); return nativeInstance.onCreate(allowInterop(wrapper)); } /// Event handler that fires every time data is deleted from Cloud Firestore. js.CloudFunction onDelete(DataEventHandler<DocumentSnapshot> handler) { dynamic wrapper(js.DocumentSnapshot data, js.EventContext context) => _handleEvent(data, context, handler); return nativeInstance.onDelete(allowInterop(wrapper)); } /// Event handler that fires every time data is updated in Cloud Firestore. js.CloudFunction onUpdate(ChangeEventHandler<DocumentSnapshot> handler) { dynamic wrapper( js.Change<js.DocumentSnapshot> data, js.EventContext context) => _handleChangeEvent(data, context, handler); return nativeInstance.onUpdate(allowInterop(wrapper)); } /// Event handler that fires every time a Cloud Firestore write of any /// kind (creation, update, or delete) occurs. js.CloudFunction onWrite(ChangeEventHandler<DocumentSnapshot> handler) { dynamic wrapper( js.Change<js.DocumentSnapshot> data, js.EventContext context) => _handleChangeEvent(data, context, handler); return nativeInstance.onWrite(allowInterop(wrapper)); } dynamic _handleEvent(js.DocumentSnapshot data, js.EventContext jsContext, DataEventHandler<DocumentSnapshot> handler) { final firestore = new Firestore(data.ref.firestore); final snapshot = new DocumentSnapshot(data, firestore); final context = new EventContext(jsContext); var result = handler(snapshot, context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } dynamic _handleChangeEvent(js.Change<js.DocumentSnapshot> data, js.EventContext jsContext, ChangeEventHandler<DocumentSnapshot> handler) { final firestore = new Firestore(data.after.ref.firestore); var after = new DocumentSnapshot(data.after, firestore); var before = new DocumentSnapshot(data.before, firestore); var context = new EventContext(jsContext); var result = handler(new Change<DocumentSnapshot>(after, before), context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } } class PubsubFunctions { final js.FirebaseFunctions _functions; PubsubFunctions._(this._functions); TopicBuilder topic(String path) => new TopicBuilder._(_functions.pubsub.topic(path)); ScheduleBuilder schedule(String expression) => new ScheduleBuilder._(_functions.pubsub.schedule(expression)); } class TopicBuilder { @protected final js.TopicBuilder nativeInstance; TopicBuilder._(this.nativeInstance); /// Event handler that fires every time an event is published in Pubsub. js.CloudFunction onPublish(DataEventHandler<Message> handler) { dynamic wrapper(js.Message jsData, js.EventContext jsContext) => _handleEvent(jsData, jsContext, handler); return nativeInstance.onPublish(allowInterop(wrapper)); } dynamic _handleEvent(js.Message jsData, js.EventContext jsContext, DataEventHandler<Message> handler) { final message = new Message(jsData); final context = new EventContext(jsContext); var result = handler(message, context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } } class ScheduleBuilder { @protected final js.ScheduleBuilder nativeInstance; ScheduleBuilder._(this.nativeInstance); /// Event handler that fires every time a schedule occurs. js.CloudFunction onRun(DataEventHandler<Message> handler) { dynamic wrapper(js.EventContext jsContext) => _handleEvent(jsContext, handler); return nativeInstance.onRun(allowInterop(wrapper)); } dynamic _handleEvent(js.EventContext jsContext, DataEventHandler<Null> handler) { final context = new EventContext(jsContext); var result = handler(null, context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } } class Message { Message(js.Message this.nativeInstance); @protected final js.Message nativeInstance; /// User-defined attributes published with the message, if any. Map<String, String> get attributes => new Map<String, String>.from(dartify(nativeInstance.attributes)); /// The data payload of this message object as a base64-encoded string. String get data => nativeInstance.data; /// The JSON data payload of this message object, if any. dynamic get json => dartify(nativeInstance.json); /// Returns a JSON-serializable representation of this object. dynamic toJson() => dartify(nativeInstance.toJSON()); } class StorageFunctions { final js.FirebaseFunctions _functions; StorageFunctions._(this._functions); /// Registers a Cloud Function scoped to a specific storage [bucket]. BucketBuilder bucket(String path) => new BucketBuilder._(_functions.storage.bucket(path)); /// Registers a Cloud Function scoped to the default storage bucket for the project. ObjectBuilder object() => new ObjectBuilder._(_functions.storage.object()); } class BucketBuilder { @protected final js.BucketBuilder nativeInstance; BucketBuilder._(this.nativeInstance); /// Storage object builder interface scoped to the specified storage bucket. ObjectBuilder object() => new ObjectBuilder._(nativeInstance.object()); } class ObjectBuilder { @protected final js.ObjectBuilder nativeInstance; ObjectBuilder._(this.nativeInstance); /// Event handler sent only when a bucket has enabled object versioning. /// /// This event indicates that the live version of an object has become an /// archived version, either because it was archived or because it was /// overwritten by the upload of an object of the same name. js.CloudFunction onArchive(DataEventHandler<ObjectMetadata> handler) { dynamic wrapper(js.ObjectMetadata data, js.EventContext context) => _handleEvent(data, context, handler); return nativeInstance.onArchive(allowInterop(wrapper)); } /// Event handler which fires every time a Google Cloud Storage deletion /// occurs. /// /// Sent when an object has been permanently deleted. This includes objects /// that are overwritten or are deleted as part of the bucket's lifecycle /// configuration. For buckets with object versioning enabled, this is not /// sent when an object is archived, even if archival occurs via the /// storage.objects.delete method. js.CloudFunction onDelete(DataEventHandler<ObjectMetadata> handler) { dynamic wrapper(js.ObjectMetadata data, js.EventContext context) => _handleEvent(data, context, handler); return nativeInstance.onDelete(allowInterop(wrapper)); } /// Event handler which fires every time a Google Cloud Storage object /// creation occurs. /// /// Sent when a new object (or a new generation of an existing object) is /// successfully created in the bucket. This includes copying or rewriting an /// existing object. A failed upload does not trigger this event. js.CloudFunction onFinalize(DataEventHandler<ObjectMetadata> handler) { dynamic wrapper(js.ObjectMetadata data, js.EventContext context) => _handleEvent(data, context, handler); return nativeInstance.onFinalize(allowInterop(wrapper)); } /// Event handler which fires every time the metadata of an existing object /// changes. js.CloudFunction onMetadataUpdate(DataEventHandler<ObjectMetadata> handler) { dynamic wrapper(js.ObjectMetadata data, js.EventContext context) => _handleEvent(data, context, handler); return nativeInstance.onMetadataUpdate(allowInterop(wrapper)); } dynamic _handleEvent(js.ObjectMetadata jsData, js.EventContext jsContext, DataEventHandler<ObjectMetadata> handler) { final data = new ObjectMetadata(jsData); final context = new EventContext(jsContext); var result = handler(data, context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } } /// Interface representing a Google Google Cloud Storage object metadata object. class ObjectMetadata { ObjectMetadata(js.ObjectMetadata this.nativeInstance); @protected final js.ObjectMetadata nativeInstance; /// Storage bucket that contains the object. String get bucket => nativeInstance.bucket; /// The value of the `Cache-Control` header, used to determine whether Internet /// caches are allowed to cache public data for an object. String get cacheControl => nativeInstance.cacheControl; /// Specifies the number of originally uploaded objects from which a composite /// object was created. int get componentCount => nativeInstance.componentCount; /// The value of the `Content-Disposition` header, used to specify presentation /// information about the data being transmitted. String get contentDisposition => nativeInstance.contentDisposition; /// Content encoding to indicate that an object is compressed (for example, /// with gzip compression) while maintaining its Content-Type. String get contentEncoding => nativeInstance.contentEncoding; /// ISO 639-1 language code of the content. String get contentLanguage => nativeInstance.contentLanguage; /// The object's content type, also known as the MIME type. String get contentType => nativeInstance.contentType; /// The object's CRC32C hash. All Google Cloud Storage objects have a CRC32C /// hash or MD5 hash. String get crc32c => nativeInstance.crc32c; /// Customer-supplied encryption key. CustomerEncryption get customerEncryption { final dartified = dartify(nativeInstance.customerEncryption); if (dartified == null) return null; return new CustomerEncryption( encryptionAlgorithm: dartified['encryptionAlgorithm'], keySha256: dartified['keySha256'], ); } /// Generation version number that changes each time the object is overwritten. String get generation => nativeInstance.generation; /// The ID of the object, including the bucket name, object name, and generation /// number. String get id => nativeInstance.id; /// The kind of the object, which is always `storage#object`. String get kind => nativeInstance.kind; /// MD5 hash for the object. All Google Cloud Storage objects have a CRC32C hash /// or MD5 hash. String get md5Hash => nativeInstance.md5Hash; /// Media download link. String get mediaLink => nativeInstance.mediaLink; /// User-provided metadata. Map<String, dynamic> get metadata => dartify(nativeInstance.metadata); /// Meta-generation version number that changes each time the object's metadata /// is updated. String get metageneration => nativeInstance.metageneration; /// The object's name. String get name => nativeInstance.name; /// The current state of this object resource. /// /// The value can be either "exists" (for object creation and updates) or /// "not_exists" (for object deletion and moves). String get resourceState => nativeInstance.resourceState; /// Link to access the object, assuming you have sufficient permissions. String get selfLink => nativeInstance.selfLink; /// The value of the `Content-Length` header, used to determine the length of /// this object data in bytes. String get size => nativeInstance.size; /// Storage class of this object. String get storageClass => nativeInstance.storageClass; /// The creation time of this object. DateTime get timeCreated => nativeInstance.timeCreated == null ? null : DateTime.parse(nativeInstance.timeCreated); /// The deletion time of this object. /// /// Returned only if this version of the object has been deleted. DateTime get timeDeleted => nativeInstance.timeDeleted == null ? null : DateTime.parse(nativeInstance.timeDeleted); /// The modification time of this object. DateTime get updated => nativeInstance.updated == null ? null : DateTime.parse(nativeInstance.updated); } class CustomerEncryption { final String encryptionAlgorithm; final String keySha256; CustomerEncryption({this.encryptionAlgorithm, this.keySha256}); } /// Namespace for Firebase Authentication functions. class AuthFunctions { final js.FirebaseFunctions _functions; AuthFunctions._(this._functions); /// Registers a Cloud Function to handle user authentication events. UserBuilder user() => new UserBuilder._(_functions.auth.user()); } /// The Firebase Authentication user builder interface. class UserBuilder { @protected final js.UserBuilder nativeInstance; UserBuilder._(this.nativeInstance); /// Event handler that fires every time a Firebase Authentication user is created. js.CloudFunction onCreate(DataEventHandler<UserRecord> handler) { dynamic wrapper(js.UserRecord jsData, js.EventContext jsContext) => _handleEvent(jsData, jsContext, handler); return nativeInstance.onCreate(allowInterop(wrapper)); } /// Event handler that fires every time a Firebase Authentication user is deleted. js.CloudFunction onDelete(DataEventHandler<UserRecord> handler) { dynamic wrapper(js.UserRecord jsData, js.EventContext jsContext) => _handleEvent(jsData, jsContext, handler); return nativeInstance.onDelete(allowInterop(wrapper)); } dynamic _handleEvent(js.UserRecord jsData, js.EventContext jsContext, DataEventHandler<UserRecord> handler) { final data = new UserRecord(jsData); final context = new EventContext(jsContext); var result = handler(data, context); if (result is Future) { return futureToPromise(result); } // See: https://stackoverflow.com/questions/47128440/google-firebase-errorfunction-returned-undefined-expected-promise-or-value return 0; } } /// Interface representing a user. class UserRecord { UserRecord(js.UserRecord this.nativeInstance); @protected final js.UserRecord nativeInstance; /// Whether or not the user is disabled. bool get disabled => nativeInstance.disabled; /// The user's display name. String get displayName => nativeInstance.displayName; /// The user's primary email, if set. String get email => nativeInstance.email; /// Whether or not the user's primary email is verified. bool get emailVerified => nativeInstance.emailVerified; /// Additional metadata about the user. UserMetadata get metadata => nativeInstance.metadata; /// The user's photo URL. String get photoURL => nativeInstance.photoURL; /// An array of providers (for example, Google, Facebook) linked to the user. List<UserInfo> get providerData => nativeInstance.providerData; /// The user's uid. String get uid => nativeInstance.uid; /// Returns a JSON-serializable representation of this object. dynamic toJson() => dartify(nativeInstance.toJSON()); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_functions_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_functions_interop/src/express.dart
import 'package:node_interop/http.dart'; import 'package:node_interop/util.dart'; import 'package:node_io/node_io.dart'; class ExpressHttpRequest extends NodeHttpRequest { ExpressHttpRequest( IncomingMessage nativeRequest, ServerResponse nativeResponse) : super(nativeRequest, nativeResponse); /// Decoded request body. dynamic get body { if (!hasProperty(nativeInstance, 'body')) return null; if (_body != null) return _body; _body = dartify(getProperty(nativeInstance, 'body')); return _body; } dynamic _body; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_functions_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_functions_interop/src/https.dart
part of firebase_functions_interop; /// To send an error from an HTTPS Callable function to a client, throw an /// instance of this class from your handler function. /// /// Make sure to throw this exception at the top level of your function and /// not from within a callback, as that will not necessarily terminate the /// function with this exception. class HttpsError { /// The operation was cancelled (typically by the caller). static const String canceled = 'cancelled'; /// Unknown error or an error from a different error domain. static const String unknown = 'unknown'; /// Client specified an invalid argument. /// /// Note that this differs from [failedPrecondition]. [invalidArgument] /// indicates arguments that are problematic regardless of the state of the /// system (e.g. an invalid field name). static const String invalidArgument = 'invalid-argument'; /// Deadline expired before operation could complete. /// /// For operations that change the state of the system, this error may be /// returned even if the operation has completed successfully. For example, /// a successful response from a server could have been delayed long enough /// for the deadline to expire. static const String deadlineExceeded = 'deadline-exceeded'; /// Some requested document was not found. static const String notFound = 'not-found'; /// Some document that we attempted to create already exists. static const String alreadyExists = 'already-exists'; /// The caller does not have permission to execute the specified operation. static const String permissionDenied = 'permission-denied'; /// Some resource has been exhausted, perhaps a per-user quota, or perhaps /// the entire file system is out of space. static const String resourceExhausted = 'resource-exhausted'; /// Operation was rejected because the system is not in a state required for /// the operation`s execution. static const String failedPrecondition = 'failed-precondition'; /// The operation was aborted, typically due to a concurrency issue like /// transaction aborts, etc. static const String aborted = 'aborted'; /// Operation was attempted past the valid range. static const String outOfRange = 'out-of-range'; /// Operation is not implemented or not supported/enabled. static const String unimplemented = 'unimplemented'; /// Internal errors. Means some invariants expected by underlying system has /// been broken. /// /// If you see one of these errors, something is very broken. static const String internal = 'internal'; /// The service is currently unavailable. /// /// This is most likely a transient condition and may be corrected by /// retrying with a backoff. static const String unavailable = 'unavailable'; /// Unrecoverable data loss or corruption. static const String dataLoss = 'data-loss'; /// The request does not have valid authentication credentials for the /// operation. static const String unauthenticated = 'unauthenticated'; HttpsError(this.code, this.message, this.details); /// A status error code to include in the response. final String code; /// A message string to be included in the response body to the client. final String message; /// An object to include in the "details" field of the response body. /// /// As with the data returned from a callable HTTPS handler, this can be /// `null` or any JSON-encodable object (`String`, `int`, `List` or `Map` /// containing primitive types). final dynamic details; dynamic _toJsHttpsError() { return callConstructor( _module.https.HttpsError, [code, message, jsify(details)]); } } class CallableContext { /// The uid from decoding and verifying a Firebase Auth ID token. Value may /// be `null`. final String authUid; /// The result of decoding and verifying a Firebase Auth ID token. Value may /// be `null`. final DecodedIdToken authToken; /// An unverified token for a Firebase Instance ID. final String instanceIdToken; CallableContext(this.authUid, this.authToken, this.instanceIdToken); } /// HTTPS functions namespace. class HttpsFunctions { final js.FirebaseFunctions _functions; HttpsFunctions._(this._functions); /// Event [handler] which is run every time an HTTPS URL is hit. /// /// Returns a [js.HttpsFunction] which can be exported. /// /// The event handler is called with single [request] argument, instance /// of [ExpressHttpRequest]. This object acts as a /// proxy to JavaScript request and response objects. js.HttpsFunction onRequest(void handler(ExpressHttpRequest request)) { void jsHandler(IncomingMessage request, ServerResponse response) { var requestProxy = new ExpressHttpRequest(request, response); handler(requestProxy); } return _functions.https.onRequest(allowInterop(jsHandler)); } /// Event handler which is run every time an HTTPS Callable function is called /// from a Firebase client SDK. /// /// The event handler is called with the data sent from the client, and with /// a [CallableContext] containing metadata about the request. /// /// The value returned from this handler, either as a [Future] or returned /// directly, is sent back to the client. /// /// If this handler throws (or returns a [Future] which completes with) an /// instance of [HttpsError], then the error details are sent back to the /// client. If this handler throws any other kind of error, then the client /// receives an error of type [HttpsError.internal]. js.HttpsFunction onCall( FutureOr<dynamic> handler(dynamic data, CallableContext context)) { dynamic jsHandler(data, js.CallableContext context) { var auth = context.auth; var ctx = new CallableContext( auth?.uid, auth?.token, context.instanceIdToken, ); try { var result = handler(dartify(data), ctx); if (result is Future) { final future = result.then(_tryJsify).catchError((error) { if (error is HttpsError) { throw error._toJsHttpsError(); } else throw error; }); return futureToPromise(future); } else { return _tryJsify(result); } } on HttpsError catch (error) { throw error._toJsHttpsError(); } } return _functions.https.onCall(allowInterop(jsHandler)); } dynamic _tryJsify(data) { try { return jsify(data); } on ArgumentError { console.error('Response cannot be encoded.', data.toString(), data); throw HttpsError( HttpsError.internal, 'Invalid response, check logs for details', data.toString(), ); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_functions_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_functions_interop/src/bindings.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. @JS() library firebase_functions_interop.bindings; import 'package:js/js.dart'; import 'package:node_interop/http.dart'; import 'package:firebase_admin_interop/js.dart' as admin; export 'package:firebase_admin_interop/js.dart'; @JS() @anonymous abstract class RuntimeOptions { /// Timeout for the function in seconds. external int get timeoutSeconds; /// Amount of memory to allocate to the function. /// /// Valid values are: '128MB', '256MB', '512MB', '1GB', and '2GB'. external String get memory; external factory RuntimeOptions({int timeoutSeconds, String memory}); } @JS() @anonymous abstract class FirebaseFunctions { /// Configures the regions to which to deploy and run a function. /// /// For a list of valid values see https://firebase.google.com/docs/functions/locations external FirebaseFunctions region(String region); /// Configures memory allocation and timeout for a function. external FirebaseFunctions runWith(RuntimeOptions options); /// Store and retrieve project configuration data such as third-party API keys /// or other settings. /// /// You can set configuration values using the Firebase CLI as described in /// [Environment Configuration](https://firebase.google.com/docs/functions/config-env). external Config config(); external HttpsFunctions get https; external DatabaseFunctions get database; external FirestoreFunctions get firestore; external PubsubFunctions get pubsub; external StorageFunctions get storage; external AuthFunctions get auth; /// Constructor for Firebase [Event] objects. external dynamic get Event; } /// The Cloud Function type for all non-HTTPS triggers. /// /// This should be exported from your JavaScript file to define a Cloud Function. /// This type is a special JavaScript function which takes a generic [Event] /// object as its only argument. typedef void CloudFunction<T>(data, EventContext context); /// The Cloud Function type for HTTPS triggers. /// /// This should be exported from your JavaScript file to define a Cloud /// Function. This type is a special JavaScript function which takes Express /// Request and Response objects as its only arguments. typedef void HttpsFunction(IncomingMessage request, ServerResponse response); /// The Functions interface for events that change state, such as /// Realtime Database or Cloud Firestore `onWrite` and `onUpdate`. @JS() @anonymous abstract class Change<T> { /// Represents the state after the event. external T get after; /// Represents the state prior to the event. external T get before; } @JS() @anonymous abstract class EventContextResource { external String get service; external String get name; } /// The context in which an event occurred. /// /// An EventContext describes: /// /// * The time an event occurred. /// * A unique identifier of the event. /// * The resource on which the event occurred, if applicable. /// * Authorization of the request that triggered the event, if applicable /// and available. @JS() @anonymous abstract class EventContext { /// Authentication information for the user that triggered the function. /// /// For an unauthenticated user, this field is null. For event types that do /// not provide user information (all except Realtime Database) or for /// Firebase admin users, this field will not exist. external EventAuthInfo get auth; /// The level of permissions for a user. /// /// Valid values are: `ADMIN`, `USER`, `UNAUTHENTICATED` and `null`. external String get authType; /// The event’s unique identifier. external String get eventId; /// Type of event. external String get eventType; /// An object containing the values of the wildcards in the path parameter /// provided to the ref() method for a Realtime Database trigger. external dynamic get params; /// The resource that emitted the event. external EventContextResource get resource; /// Timestamp for the event as an RFC 3339 string. external String get timestamp; } @JS() @anonymous abstract class EventAuthInfo { external String get uid; external String get token; } @JS() @anonymous abstract class Config {} @JS() @anonymous abstract class HttpsFunctions { /// To send an error from an HTTPS Callable function to a client, throw an /// instance of this class from your handler function. /// /// Make sure to throw this exception at the top level of your function and /// not from within a callback, as that will not necessarily terminate the /// function with this exception. external dynamic get HttpsError; /// Event handler which is run every time an HTTPS URL is hit. /// /// The event handler is called with Express Request and Response objects as its /// only arguments. external HttpsFunction onRequest(HttpRequestListener handler); external HttpsFunction onCall( dynamic handler(dynamic data, CallableContext context)); } @JS() @anonymous abstract class CallableContext { external CallableAuth get auth; external String get instanceIdToken; } @JS() @anonymous abstract class CallableAuth { external String get uid; external admin.DecodedIdToken get token; } @JS() @anonymous abstract class DatabaseFunctions { /// Registers a function that triggers on Firebase Realtime Database write /// events. /// /// This method behaves very similarly to the method of the same name in the /// client and Admin Firebase SDKs. Any change to the Database that affects the /// data at or below the provided path will fire an event in Cloud Functions. external RefBuilder ref(String path); } /// The Firebase Realtime Database reference builder interface. @JS() @anonymous abstract class RefBuilder { /// Event handler that fires every time new data is created in Firebase /// Realtime Database. external CloudFunction onCreate( dynamic handler(admin.DataSnapshot data, EventContext context)); /// Event handler that fires every time data is deleted from Firebase Realtime /// Database. external CloudFunction onDelete( dynamic handler(admin.DataSnapshot data, EventContext context)); /// Event handler that fires every time data is updated in Firebase Realtime /// Database. external CloudFunction onUpdate( dynamic handler(Change<admin.DataSnapshot> data, EventContext context)); /// Event handler that fires every time a Firebase Realtime Database write of /// any kind (creation, update, or delete) occurs. external CloudFunction onWrite( dynamic handler(Change<admin.DataSnapshot> data, EventContext context)); } @JS() @anonymous abstract class FirestoreFunctions { /// Registers a function that triggers on Cloud Firestore write events to /// the [document]. external DocumentBuilder document(String document); } /// The Cloud Firestore document builder interface. @JS() @anonymous abstract class DocumentBuilder { /// Event handler that fires every time new data is created in Cloud /// Firestore. external CloudFunction onCreate( dynamic handler(admin.DocumentSnapshot data, EventContext context)); /// Event handler that fires every time data is deleted from Cloud Firestore. external CloudFunction onDelete( dynamic handler(admin.DocumentSnapshot data, EventContext context)); /// Event handler that fires every time data is updated in Cloud Firestore. external CloudFunction onUpdate( dynamic handler( Change<admin.DocumentSnapshot> data, EventContext context)); /// Event handler that fires every time a Cloud Firestore write of any kind /// (creation, update, or delete) occurs. external CloudFunction onWrite( dynamic handler( Change<admin.DocumentSnapshot> data, EventContext context)); } @JS() @anonymous abstract class PubsubFunctions { /// Registers a function that triggers on Pubsub write events to /// the [topic]. external TopicBuilder topic(String topic); /// Registers a function that triggers on Pubsub [schedule]. external ScheduleBuilder schedule(String expression); } /// The Pubsub topic builder interface. @JS() @anonymous abstract class TopicBuilder { /// Event handler that fires every time an event is publish in Pubsub. external CloudFunction onPublish( dynamic handler(Message data, EventContext context)); } /// The Pubsub schedule builder interface. @JS() @anonymous abstract class ScheduleBuilder { /// Event handler that fires every time a schedule occurs. external CloudFunction onRun( dynamic handler(EventContext context)); } /// Interface representing a Google Cloud Pub/Sub message. @JS() @anonymous abstract class Message { /// User-defined attributes published with the message, if any. external dynamic get attributes; /// The data payload of this message object as a base64-encoded string. external String get data; /// The JSON data payload of this message object, if any. external dynamic get json; /// Returns a JSON-serializable representation of this object. external dynamic toJSON(); } @JS() @anonymous abstract class StorageFunctions { /// Registers a Cloud Function scoped to a specific storage [bucket]. external BucketBuilder bucket(String bucket); /// Registers a Cloud Function scoped to the default storage bucket for the project. external ObjectBuilder object(); } /// The Storage bucket builder interface. @JS() @anonymous abstract class BucketBuilder { /// Storage object builder interface scoped to the specified storage bucket. external ObjectBuilder object(); } /// The Storage object builder interface. @JS() @anonymous abstract class ObjectBuilder { /// Event handler sent only when a bucket has enabled object versioning. /// /// This event indicates that the live version of an object has become an /// archived version, either because it was archived or because it was /// overwritten by the upload of an object of the same name. external CloudFunction onArchive( void handler(ObjectMetadata data, EventContext context)); /// Event handler which fires every time a Google Cloud Storage deletion /// occurs. /// /// Sent when an object has been permanently deleted. This includes objects /// that are overwritten or are deleted as part of the bucket's lifecycle /// configuration. For buckets with object versioning enabled, this is not /// sent when an object is archived, even if archival occurs via the /// storage.objects.delete method. external CloudFunction onDelete( void handler(ObjectMetadata data, EventContext context)); /// Event handler which fires every time a Google Cloud Storage object /// creation occurs. /// /// Sent when a new object (or a new generation of an existing object) is /// successfully created in the bucket. This includes copying or rewriting an /// existing object. A failed upload does not trigger this event. external CloudFunction onFinalize( void handler(ObjectMetadata data, EventContext context)); /// Event handler which fires every time the metadata of an existing object /// changes. external CloudFunction onMetadataUpdate( void handler(ObjectMetadata data, EventContext context)); } /// Interface representing a Google Google Cloud Storage object metadata object. @JS() @anonymous abstract class ObjectMetadata { /// Storage bucket that contains the object. external String get bucket; /// The value of the `Cache-Control` header, used to determine whether Internet /// caches are allowed to cache public data for an object. external String get cacheControl; /// Specifies the number of originally uploaded objects from which a composite /// object was created. external int get componentCount; /// The value of the `Content-Disposition` header, used to specify presentation /// information about the data being transmitted. external String get contentDisposition; /// Content encoding to indicate that an object is compressed (for example, /// with gzip compression) while maintaining its Content-Type. external String get contentEncoding; /// ISO 639-1 language code of the content. external String get contentLanguage; /// The object's content type, also known as the MIME type. external String get contentType; /// The object's CRC32C hash. All Google Cloud Storage objects have a CRC32C /// hash or MD5 hash. external String get crc32c; /// Customer-supplied encryption key. external dynamic get customerEncryption; /// Generation version number that changes each time the object is overwritten. external String get generation; /// The ID of the object, including the bucket name, object name, and generation /// number. external String get id; /// The kind of the object, which is always `storage#object`. external String get kind; /// MD5 hash for the object. All Google Cloud Storage objects have a CRC32C hash /// or MD5 hash. external String get md5Hash; /// Media download link. external String get mediaLink; /// User-provided metadata. external Map<String, dynamic> get metadata; /// Meta-generation version number that changes each time the object's metadata /// is updated. external String get metageneration; /// The object's name. external String get name; /// The current state of this object resource. /// /// The value can be either "exists" (for object creation and updates) or /// "not_exists" (for object deletion and moves). external String get resourceState; /// Link to access the object, assuming you have sufficient permissions. external String get selfLink; /// The value of the `Content-Length` header, used to determine the length of /// this object data in bytes. external String get size; /// Storage class of this object. external String get storageClass; /// The creation time of this object in RFC 3339 format. external String get timeCreated; /// The deletion time of the object in RFC 3339 format. Returned only if this /// version of the object has been deleted. external String get timeDeleted; /// The modification time of this object. external String get updated; } /// Namespace for Firebase Authentication functions. @JS() @anonymous abstract class AuthFunctions { /// Registers a Cloud Function to handle user authentication events. external UserBuilder user(); } /// The Firebase Authentication user builder interface. @JS() @anonymous abstract class UserBuilder { /// Event handler that fires every time a Firebase Authentication user is created. external CloudFunction onCreate( void handler(UserRecord data, EventContext context)); /// Event handler that fires every time a Firebase Authentication user is deleted. external CloudFunction onDelete( void handler(UserRecord data, EventContext context)); } /// Interface representing a user. @JS() @anonymous abstract class UserRecord { /// Whether or not the user is disabled. external bool get disabled; /// The user's display name. external String get displayName; /// The user's primary email, if set. external String get email; /// Whether or not the user's primary email is verified. external bool get emailVerified; /// Additional metadata about the user. external admin.UserMetadata get metadata; /// The user's photo URL. external String get photoURL; /// An array of providers (for example, Google, Facebook) linked to the user. external List<admin.UserInfo> get providerData; /// The user's uid. external String get uid; /// Returns the serialized JSON representation of this object. external dynamic toJSON(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/code_builder.dart
// Copyright (c) 2017, 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. export 'src/allocator.dart' show Allocator; export 'src/base.dart' show lazySpec, Spec; export 'src/emitter.dart' show DartEmitter; export 'src/matchers.dart' show equalsDart, EqualsDart; export 'src/specs/class.dart' show Class, ClassBuilder; export 'src/specs/code.dart' show lazyCode, Block, BlockBuilder, Code, StaticCode, ScopedCode; export 'src/specs/constructor.dart' show Constructor, ConstructorBuilder; export 'src/specs/directive.dart' show Directive, DirectiveType, DirectiveBuilder; export 'src/specs/enum.dart' show Enum, EnumBuilder, EnumValue, EnumValueBuilder; export 'src/specs/expression.dart' show ToCodeExpression, BinaryExpression, CodeExpression, Expression, ExpressionEmitter, ExpressionVisitor, InvokeExpression, InvokeExpressionType, LiteralExpression, LiteralListExpression, literal, literalNull, literalNum, literalBool, literalList, literalConstList, literalSet, literalConstSet, literalMap, literalConstMap, literalString, literalTrue, literalFalse; export 'src/specs/extension.dart' show Extension, ExtensionBuilder; export 'src/specs/field.dart' show Field, FieldBuilder, FieldModifier; export 'src/specs/library.dart' show Library, LibraryBuilder; export 'src/specs/method.dart' show Method, MethodBuilder, MethodModifier, MethodType, Parameter, ParameterBuilder; export 'src/specs/reference.dart' show refer, Reference; export 'src/specs/type_function.dart' show FunctionType, FunctionTypeBuilder; export 'src/specs/type_reference.dart' show TypeReference, TypeReferenceBuilder;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/matchers.dart
// Copyright (c) 2017, 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:matcher/matcher.dart'; import 'base.dart'; import 'emitter.dart'; /// Encodes [spec] as Dart source code. String _dart(Spec spec, DartEmitter emitter) => EqualsDart._format(spec.accept<StringSink>(emitter).toString()); /// Returns a matcher for [Spec] objects that emit code matching [source]. /// /// Both [source] and the result emitted from the compared [Spec] are formatted /// with [EqualsDart.format]. A plain [DartEmitter] is used by default and may /// be overridden with [emitter]. Matcher equalsDart( String source, [ DartEmitter emitter, ]) => EqualsDart._(EqualsDart._format(source), emitter ?? DartEmitter()); /// Implementation detail of using the [equalsDart] matcher. /// /// See [EqualsDart.format] to specify the default source code formatter. class EqualsDart extends Matcher { /// May override to provide a function to format Dart on [equalsDart]. /// /// By default, uses [collapseWhitespace], but it is recommended to instead /// use `dart_style` (dartfmt) where possible. See `test/common.dart` for an /// example. static String Function(String) format = collapseWhitespace; static String _format(String source) { try { return format(source).trim(); } catch (_) { // Ignored on purpose, probably not exactly valid Dart code. return collapseWhitespace(source).trim(); } } final DartEmitter _emitter; final String _expectedSource; const EqualsDart._(this._expectedSource, this._emitter); @override Description describe(Description description) => description.add(_expectedSource); @override Description describeMismatch( covariant Spec item, Description mismatchDescription, matchState, verbose, ) { final actualSource = _dart(item, _emitter); return equals(_expectedSource).describeMismatch( actualSource, mismatchDescription, matchState, verbose, ); } @override bool matches(covariant Spec item, matchState) => _dart(item, _emitter) == _expectedSource; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/allocator.dart
// Copyright (c) 2017, 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 'specs/directive.dart'; import 'specs/reference.dart'; /// Collects references and automatically allocates prefixes and imports. /// /// `Allocator` takes out the manual work of deciding whether a symbol will /// clash with other imports in your generated code, or what imports are needed /// to resolve all symbols in your generated code. abstract class Allocator { /// An allocator that does not prefix symbols nor collects imports. static const Allocator none = _NullAllocator(); /// Creates a new default allocator that applies no prefixing. factory Allocator() = _Allocator; /// Creates a new allocator that applies naive prefixing to avoid conflicts. /// /// This implementation is not optimized for any particular code generation /// style and instead takes a conservative approach of prefixing _every_ /// import except references to `dart:core` (which are considered always /// imported). /// /// The prefixes are not guaranteed to be stable and cannot be expected to /// have any particular value. factory Allocator.simplePrefixing() = _PrefixedAllocator; /// Returns a reference string given a [reference] object. /// /// For example, a no-op implementation: /// ```dart /// allocate(const Reference('List', 'dart:core')); // Returns 'List'. /// ``` /// /// Where-as an implementation that prefixes imports might output: /// ```dart /// allocate(const Reference('Foo', 'package:foo')); // Returns '_i1.Foo'. /// ``` String allocate(Reference reference); /// All imports that have so far been added implicitly via [allocate]. Iterable<Directive> get imports; } class _Allocator implements Allocator { final _imports = <String>{}; @override String allocate(Reference reference) { if (reference.url != null) { _imports.add(reference.url); } return reference.symbol; } @override Iterable<Directive> get imports => _imports.map((u) => Directive.import(u)); } class _NullAllocator implements Allocator { const _NullAllocator(); @override String allocate(Reference reference) => reference.symbol; @override Iterable<Directive> get imports => const []; } class _PrefixedAllocator implements Allocator { static const _doNotPrefix = ['dart:core']; final _imports = <String, int>{}; var _keys = 1; @override String allocate(Reference reference) { final symbol = reference.symbol; if (reference.url == null || _doNotPrefix.contains(reference.url)) { return symbol; } return '_i${_imports.putIfAbsent(reference.url, _nextKey)}.$symbol'; } int _nextKey() => _keys++; @override Iterable<Directive> get imports => _imports.keys.map( (u) => Directive.import(u, as: '_i${_imports[u]}'), ); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/emitter.dart
// Copyright (c) 2017, 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 'allocator.dart'; import 'base.dart'; import 'specs/class.dart'; import 'specs/code.dart'; import 'specs/constructor.dart'; import 'specs/directive.dart'; import 'specs/enum.dart'; import 'specs/expression.dart'; import 'specs/extension.dart'; import 'specs/field.dart'; import 'specs/library.dart'; import 'specs/method.dart'; import 'specs/reference.dart'; import 'specs/type_function.dart'; import 'specs/type_reference.dart'; import 'visitors.dart'; /// Helper method improving on [StringSink.writeAll]. /// /// For every `Spec` in [elements], executing [visit]. /// /// If [elements] is at least 2 elements, inserts [separator] delimiting them. StringSink visitAll<T>( Iterable<T> elements, StringSink output, void Function(T) visit, [ String separator = ', ', ]) { // Basically, this whole method is an improvement on // output.writeAll(specs.map((s) => s.accept(visitor)); // // ... which would allocate more StringBuffer(s) for a one-time use. if (elements.isEmpty) { return output; } final iterator = elements.iterator..moveNext(); visit(iterator.current); while (iterator.moveNext()) { output.write(separator); visit(iterator.current); } return output; } class DartEmitter extends Object with CodeEmitter, ExpressionEmitter implements SpecVisitor<StringSink> { @override final Allocator allocator; /// If directives should be ordered while emitting. /// /// Ordering rules follow the guidance in /// [Effective Dart](https://dart.dev/guides/language/effective-dart/style#ordering) /// and the /// [directives_ordering](https://dart-lang.github.io/linter/lints/directives_ordering.html) /// lint. final bool orderDirectives; /// If nullable types should be emitted with the nullable suffix ("?"). /// /// Null safety syntax should only be enabled if the output will be used with /// a Dart language version which supports it. final bool _useNullSafetySyntax; /// Creates a new instance of [DartEmitter]. /// /// May specify an [Allocator] to use for symbols, otherwise uses a no-op. DartEmitter( [this.allocator = Allocator.none, bool orderDirectives = false, bool useNullSafetySyntax = false]) : orderDirectives = orderDirectives ?? false, _useNullSafetySyntax = useNullSafetySyntax ?? false; /// Creates a new instance of [DartEmitter] with simple automatic imports. factory DartEmitter.scoped( {bool orderDirectives = false, bool useNullSafetySyntax = false}) => DartEmitter( Allocator.simplePrefixing(), orderDirectives, useNullSafetySyntax); static bool _isLambdaBody(Code code) => code is ToCodeExpression && !code.isStatement; /// Whether the provided [method] is considered a lambda method. static bool _isLambdaMethod(Method method) => method.lambda ?? _isLambdaBody(method.body); /// Whether the provided [constructor] is considered a lambda method. static bool _isLambdaConstructor(Constructor constructor) => constructor.lambda ?? constructor.factory && _isLambdaBody(constructor.body); @override StringSink visitAnnotation(Expression spec, [StringSink output]) { (output ??= StringBuffer()).write('@'); spec.accept(this, output); output.write(' '); return output; } @override StringSink visitClass(Class spec, [StringSink output]) { output ??= StringBuffer(); spec.docs.forEach(output.writeln); spec.annotations.forEach((a) => visitAnnotation(a, output)); if (spec.abstract) { output.write('abstract '); } output.write('class ${spec.name}'); visitTypeParameters(spec.types.map((r) => r.type), output); if (spec.extend != null) { output.write(' extends '); spec.extend.type.accept(this, output); } if (spec.mixins.isNotEmpty) { output ..write(' with ') ..writeAll( spec.mixins.map<StringSink>((m) => m.type.accept(this)), ','); } if (spec.implements.isNotEmpty) { output ..write(' implements ') ..writeAll( spec.implements.map<StringSink>((m) => m.type.accept(this)), ','); } output.write(' {'); spec.constructors.forEach((c) { visitConstructor(c, spec.name, output); output.writeln(); }); spec.fields.forEach((f) { visitField(f, output); output.writeln(); }); spec.methods.forEach((m) { visitMethod(m, output); if (_isLambdaMethod(m)) { output.write(';'); } output.writeln(); }); output.writeln(' }'); return output; } @override StringSink visitConstructor(Constructor spec, String clazz, [StringSink output]) { output ??= StringBuffer(); spec.docs.forEach(output.writeln); spec.annotations.forEach((a) => visitAnnotation(a, output)); if (spec.external) { output.write('external '); } if (spec.constant) { output.write('const '); } if (spec.factory) { output.write('factory '); } output.write(clazz); if (spec.name != null) { output..write('.')..write(spec.name); } output.write('('); if (spec.requiredParameters.isNotEmpty) { var count = 0; for (final p in spec.requiredParameters) { count++; _visitParameter(p, output); if (spec.requiredParameters.length != count || spec.optionalParameters.isNotEmpty) { output.write(', '); } } } if (spec.optionalParameters.isNotEmpty) { final named = spec.optionalParameters.any((p) => p.named); if (named) { output.write('{'); } else { output.write('['); } var count = 0; for (final p in spec.optionalParameters) { count++; _visitParameter(p, output, optional: true, named: named); if (spec.optionalParameters.length != count) { output.write(', '); } } if (named) { output.write('}'); } else { output.write(']'); } } output.write(')'); if (spec.initializers.isNotEmpty) { output.write(' : '); var count = 0; for (final initializer in spec.initializers) { count++; initializer.accept(this, output); if (count != spec.initializers.length) { output.write(', '); } } } if (spec.redirect != null) { output.write(' = '); spec.redirect.type.accept(this, output); output.write(';'); } else if (spec.body != null) { if (_isLambdaConstructor(spec)) { output.write(' => '); spec.body.accept(this, output); output.write(';'); } else { output.write(' { '); spec.body.accept(this, output); output.write(' }'); } } else { output.write(';'); } output.writeln(); return output; } @override StringSink visitExtension(Extension spec, [StringSink output]) { output ??= StringBuffer(); spec.docs.forEach(output.writeln); spec.annotations.forEach((a) => visitAnnotation(a, output)); output.write('extension'); if (spec.name != null) { output.write(' ${spec.name}'); } visitTypeParameters(spec.types.map((r) => r.type), output); if (spec.on != null) { output.write(' on '); spec.on.type.accept(this, output); } output.write(' {'); spec.fields.forEach((f) { visitField(f, output); output.writeln(); }); spec.methods.forEach((m) { visitMethod(m, output); if (_isLambdaMethod(m)) { output.write(';'); } output.writeln(); }); output.writeln(' }'); return output; } @override StringSink visitDirective(Directive spec, [StringSink output]) { output ??= StringBuffer(); switch (spec.type) { case DirectiveType.import: output.write('import '); break; case DirectiveType.export: output.write('export '); break; case DirectiveType.part: output.write('part '); break; } output.write("'${spec.url}'"); if (spec.as != null) { if (spec.deferred) { output.write(' deferred '); } output.write(' as ${spec.as}'); } if (spec.show.isNotEmpty) { output ..write(' show ') ..writeAll(spec.show, ', '); } else if (spec.hide.isNotEmpty) { output ..write(' hide ') ..writeAll(spec.hide, ', '); } output.write(';'); return output; } @override StringSink visitField(Field spec, [StringSink output]) { output ??= StringBuffer(); spec.docs.forEach(output.writeln); spec.annotations.forEach((a) => visitAnnotation(a, output)); if (spec.static) { output.write('static '); } switch (spec.modifier) { case FieldModifier.var$: if (spec.type == null) { output.write('var '); } break; case FieldModifier.final$: output.write('final '); break; case FieldModifier.constant: output.write('const '); break; } if (spec.type != null) { spec.type.type.accept(this, output); output.write(' '); } output.write(spec.name); if (spec.assignment != null) { output.write(' = '); startConstCode(spec.modifier == FieldModifier.constant, () { spec.assignment.accept(this, output); }); } output.writeln(';'); return output; } @override StringSink visitLibrary(Library spec, [StringSink output]) { output ??= StringBuffer(); // Process the body first in order to prime the allocators. final body = StringBuffer(); for (final spec in spec.body) { spec.accept(this, body); if (spec is Method && _isLambdaMethod(spec)) { body.write(';'); } } final directives = <Directive>[...allocator.imports, ...spec.directives]; if (orderDirectives) { directives.sort(); } Directive previous; for (final directive in directives) { if (_newLineBetween(orderDirectives, previous, directive)) { // Note: dartfmt handles creating new lines between directives. // 2 lines are written here. The first one comes after the previous // directive `;`, the second is the empty line. output..writeln()..writeln(); } directive.accept(this, output); previous = directive; } output.write(body); return output; } @override StringSink visitFunctionType(FunctionType spec, [StringSink output]) { output ??= StringBuffer(); if (spec.returnType != null) { spec.returnType.accept(this, output); output.write(' '); } output.write('Function'); if (spec.types.isNotEmpty) { output.write('<'); visitAll<Reference>(spec.types, output, (spec) { spec.accept(this, output); }); output.write('>'); } output.write('('); visitAll<Reference>(spec.requiredParameters, output, (spec) { spec.accept(this, output); }); if (spec.requiredParameters.isNotEmpty && (spec.optionalParameters.isNotEmpty || spec.namedParameters.isNotEmpty)) { output.write(', '); } if (spec.optionalParameters.isNotEmpty) { output.write('['); visitAll<Reference>(spec.optionalParameters, output, (spec) { spec.accept(this, output); }); output.write(']'); } else if (spec.namedParameters.isNotEmpty) { output.write('{'); visitAll<String>(spec.namedParameters.keys, output, (name) { spec.namedParameters[name].accept(this, output); output..write(' ')..write(name); }); output.write('}'); } output.write(')'); if (_useNullSafetySyntax && (spec.isNullable ?? false)) { output.write('?'); } return output; } @override StringSink visitMethod(Method spec, [StringSink output]) { output ??= StringBuffer(); spec.docs.forEach(output.writeln); spec.annotations.forEach((a) => visitAnnotation(a, output)); if (spec.external) { output.write('external '); } if (spec.static) { output.write('static '); } if (spec.returns != null) { spec.returns.accept(this, output); output.write(' '); } if (spec.type == MethodType.getter) { output..write('get ')..write(spec.name); } else { if (spec.type == MethodType.setter) { output.write('set '); } if (spec.name != null) { output.write(spec.name); } visitTypeParameters(spec.types.map((r) => r.type), output); output.write('('); if (spec.requiredParameters.isNotEmpty) { var count = 0; for (final p in spec.requiredParameters) { count++; _visitParameter(p, output); if (spec.requiredParameters.length != count || spec.optionalParameters.isNotEmpty) { output.write(', '); } } } if (spec.optionalParameters.isNotEmpty) { final named = spec.optionalParameters.any((p) => p.named); if (named) { output.write('{'); } else { output.write('['); } var count = 0; for (final p in spec.optionalParameters) { count++; _visitParameter(p, output, optional: true, named: named); if (spec.optionalParameters.length != count) { output.write(', '); } } if (named) { output.write('}'); } else { output.write(']'); } } output.write(')'); } if (spec.body != null) { if (spec.modifier != null) { switch (spec.modifier) { case MethodModifier.async: output.write(' async '); break; case MethodModifier.asyncStar: output.write(' async* '); break; case MethodModifier.syncStar: output.write(' sync* '); break; } } if (_isLambdaMethod(spec)) { output.write(' => '); } else { output.write(' { '); } spec.body.accept(this, output); if (!_isLambdaMethod(spec)) { output.write(' } '); } } else { output.write(';'); } return output; } // Expose as a first-class visit function only if needed. void _visitParameter( Parameter spec, StringSink output, { bool optional = false, bool named = false, }) { spec.docs.forEach(output.writeln); spec.annotations.forEach((a) => visitAnnotation(a, output)); // The `required` keyword must precede the `covariant` keyword. if (spec.required) { output.write('required '); } if (spec.covariant) { output.write('covariant '); } if (spec.type != null) { spec.type.type.accept(this, output); output.write(' '); } if (spec.toThis) { output.write('this.'); } output.write(spec.name); if (optional && spec.defaultTo != null) { output.write(' = '); spec.defaultTo.accept(this, output); } } @override StringSink visitReference(Reference spec, [StringSink output]) => (output ??= StringBuffer())..write(allocator.allocate(spec)); @override StringSink visitSpec(Spec spec, [StringSink output]) => spec.accept(this, output); @override StringSink visitType(TypeReference spec, [StringSink output]) { output ??= StringBuffer(); // Intentionally not .accept to avoid stack overflow. visitReference(spec, output); if (spec.bound != null) { output.write(' extends '); spec.bound.type.accept(this, output); } visitTypeParameters(spec.types.map((r) => r.type), output); if (_useNullSafetySyntax && (spec.isNullable ?? false)) { output.write('?'); } return output; } @override StringSink visitTypeParameters(Iterable<Reference> specs, [StringSink output]) { output ??= StringBuffer(); if (specs.isNotEmpty) { output ..write('<') ..writeAll(specs.map<StringSink>((s) => s.accept(this)), ',') ..write('>'); } return output; } @override StringSink visitEnum(Enum spec, [StringSink output]) { output ??= StringBuffer(); spec.docs.forEach(output.writeln); spec.annotations.forEach((a) => visitAnnotation(a, output)); output.writeln('enum ${spec.name} {'); spec.values.forEach((v) { v.docs.forEach(output.writeln); v.annotations.forEach((a) => visitAnnotation(a, output)); output.write(v.name); if (v != spec.values.last) { output.writeln(','); } }); output.writeln('}'); return output; } } /// Returns `true` if: /// /// * [ordered] is `true` /// * [a] is non-`null` /// * If there should be an empty line before [b] if it's emitted after [a]. bool _newLineBetween(bool ordered, Directive a, Directive b) { if (!ordered) return false; if (a == null) return false; assert(b != null); // Put a line between imports and exports if (a.type != b.type) return true; // Within exports, don't put in extra blank lines if (a.type == DirectiveType.export) { assert(b.type == DirectiveType.export); return false; } // Return `true` if the schemes for [a] and [b] are different return !Uri.parse(a.url).isScheme(Uri.parse(b.url).scheme); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/code_builder/src/base.dart
// Copyright (c) 2017, 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 'visitors.dart'; abstract class Spec { R accept<R>(SpecVisitor<R> visitor, [R context]); } /// Returns a generic [Spec] that is lazily generated when visited. Spec lazySpec(Spec Function() generate) => _LazySpec(generate); class _LazySpec implements Spec { final Spec Function() generate; const _LazySpec(this.generate); @override R accept<R>(SpecVisitor<R> visitor, [R context]) => generate().accept(visitor, context); }
0